+ # text counters. (eg: hehstats)
+ my $itc;
+ $itc = &getChanConf("ircTextCounters");
+ $itc = &findChanConf("ircTextCounters") unless ($itc);
+ if ($itc) {
+ $itc =~ s/([^\w\s])/\\$1/g;
+ my $z = join '|', split ' ', $itc;
+
+ if ($msgType eq "privmsg" and $message =~ / ($mask{chan})$/) {
+ &DEBUG("ircTC: privmsg detected; chan = $1");
+ $chan = $1;
+ }
+
+ if ($message =~ /^_stats(\s+(\S+))$/i) {
+ &textstats_main($2);
+ return;
+ }
+
+ if ($message =~ /^($z)stats(\s+(\S+))?$/i) {
+ my $type = $1;
+ my $arg = $3;
+
+ # even more uglier with channel/time arguments.
+ my $c = $chan;
+# my $c = $chan || "PRIVATE";
+ my $where = "type=".&dbQuote($type);
+ $where .= " AND channel=".&dbQuote($c) if (defined $c);
+ &DEBUG("not using chan arg") if (!defined $c);
+ my $sum = (&dbRawReturn("SELECT SUM(counter) FROM stats"
+ ." WHERE ".$where ))[0];
+
+ if (!defined $arg or $arg =~ /^\s*$/) {
+ # this is way fucking ugly.
+
+ my %hash = &dbGetCol("stats", "nick,counter",
+ $where." ORDER BY counter DESC LIMIT 3", 1);
+ my $i;
+ my @top;
+
+ # unfortunately we have to sort it again!
+ # todo: make dbGetCol return hash and array? too much effort.
+ my $tp = 0;
+ foreach $i (sort { $b <=> $a } keys %hash) {
+ foreach (keys %{ $hash{$i} }) {
+ my $p = sprintf("%.01f", 100*$i/$sum);
+ $tp += $p;
+ push(@top, "\002$_\002 -- $i ($p%)");
+ }
+ }
+ my $topstr = "";
+ &DEBUG("*stats: tp => $tp");
+ if (scalar @top) {
+ $topstr = ". Top ".scalar(@top).": ".join(', ', @top);
+ }
+
+ if (defined $sum) {
+ &pSReply("total count of \037$type\037 on \002$c\002: $sum$topstr");
+ } else {
+ &pSReply("zero counter for \037$type\037.");
+ }
+ } else {
+ my $x = (&dbRawReturn("SELECT SUM(counter) FROM stats".
+ " WHERE $where AND nick=".&dbQuote($arg) ))[0];
+
+ if (!defined $x) { # !defined.
+ &pSReply("$arg has not said $type yet.");
+ return;
+ }
+
+ # defined.
+ my @array = &dbGet("stats", "nick",
+ $where." ORDER BY counter", 1);
+ my $good = 0;
+ my $i = 0;
+ for($i=0; $i<scalar @array; $i++) {
+ next unless ($array[0] =~ /^\Q$who\E$/);
+ $good++;
+ last;
+ }
+ $i++;
+
+ my $total = scalar(@array);
+ my $xtra = "";
+ if ($total and $good) {
+ my $pct = sprintf("%.01f", 100*(1+$total-$i)/$total);
+ $xtra = ", ranked $i\002/\002$total (percentile: \002$pct\002 %)";
+ }
+
+ my $pct1 = sprintf("%.01f", 100*$x/$sum);
+ &pSReply("\002$arg\002 has said \037$type\037 \002$x\002 times (\002$pct1\002 %)$xtra");
+ }
+
+ return;
+ }
+
+ if ($@) {
+ &DEBUG("regex failed: $@");
+ return;
+ }
+ }
+