]> git.donarmstrong.com Git - infobot.git/blob - src/CommandStubs.pl
move
[infobot.git] / src / CommandStubs.pl
1 #
2 # User Command Extension Stubs
3 # WARN: this file does not reload on HUP.
4 #
5
6 #use strict; # TODO: sub { \&{ $hash{'CODEREF'} }($flatarg) };
7
8 use vars qw($who $msgType $conn $chan $message $ident $talkchannel
9         $bot_version $bot_data_dir);
10 use vars qw(@vernick @vernicktodo);
11 use vars qw(%channels %cache %mask %userstats %myModules %cmdstats
12         %cmdhooks %lang %ver);
13 # TODO: FIX THE FOLLOWING:
14 use vars qw($total $x $type $i $good %wingateToDo);
15
16 ### COMMAND HOOK IMPLEMENTATION.
17 # addCmdHook('TEXT_HOOK',
18 #       (CODEREF        => 'Blah',
19 #       Forker          => 1,
20 #       Module          => 'blah.pl'            # preload module.
21 #       Identifier      => 'config_label',      # change to Config?
22 #       Help            => 'help_label',
23 #       Cmdstats        => 'text_label',)
24 #}
25 ###
26
27 sub addCmdHook {
28     my ($ident, %hash) = @_;
29
30     if (exists $cmdhooks{$ident}) {
31         &WARN("aCH: \$cmdhooks{$ident} already exists.");
32         return;
33     }
34
35     &VERB("aCH: added $ident",2);       # use $hash{'Identifier'}?
36     ### hrm... prevent warnings?
37     $cmdhooks{$ident} = \%hash;
38 }
39
40 # RUN IF ADDRESSED.
41 sub parseCmdHook {
42     my ($line) = @_;
43     $line =~ s/^\s+|\s+$//g;    # again.
44     $line =~ /^(\S+)(\s+(.*))?$/;
45     my $cmd     = $1;   # command name is whitespaceless.
46     my $flatarg = $3;
47     my @args    = split(/\s+/, $flatarg || '');
48     my $done    = 0;
49
50     &shmFlush();
51
52     if (!defined %cmdhooks) {
53         &WARN('%cmdhooks does not exist.');
54         return 0;
55     }
56
57     if (!defined $cmd) {
58         &WARN("cstubs: cmd == NULL.");
59         return 0;
60     }
61
62     foreach (keys %cmdhooks) {
63         # rename to something else! like $id or $label?
64         my $ident = $_;
65
66         next unless ($cmd =~ /^$ident$/i);
67
68         if ($done) {
69             &WARN("pCH: Multiple hook match: $ident");
70             next;
71         }
72
73         &status("cmdhooks: $cmd matched '$ident' '$flatarg'");
74         my %hash = %{ $cmdhooks{$ident} };
75
76         if (!scalar keys %hash) {
77             &WARN("CmdHook: hash is NULL?");
78             return 1;
79         }
80
81         if ($hash{NoArgs} and $flatarg) {
82             &DEBUG("cmd $ident does not take args ('$flatarg'); skipping.");
83             next;
84         }
85
86         if (!exists $hash{CODEREF}) {
87             &ERROR("CODEREF undefined for $cmd or $ident.");
88             return 1;
89         }
90
91         ### DEBUG.
92         foreach (keys %hash) {
93             &VERB(" $cmd->$_ => '$hash{$_}'.",2);
94         }
95
96         ### HELP.
97         if (exists $hash{'Help'} and !scalar(@args)) {
98             &help( $hash{'Help'} );
99             return 1;
100         }
101
102         ### IDENTIFIER.
103         if (exists $hash{'Identifier'}) {
104             return 1 unless (&IsChanConfOrWarn($hash{'Identifier'}));
105         }
106
107         ### USER FLAGS.
108         if (exists $hash{'UserFlag'}) {
109             return 1 unless (&hasFlag($hash{'UserFlag'}));
110         }
111
112         ### FORKER,IDENTIFIER,CODEREF.
113         if (($$ == $bot_pid) && exists $hash{'Forker'}) {
114             $hash{'Identifier'} .= "-" if ($hash{'Forker'} eq "NULL");
115
116             if (exists $hash{'ArrayArgs'}) {
117                 &Forker($hash{'Identifier'}, sub { \&{ $hash{'CODEREF'} }(@args) } );
118             } else {
119                 &Forker($hash{'Identifier'}, sub { \&{ $hash{'CODEREF'} }($flatarg) } );
120             }
121
122         } else {
123             if (exists $hash{'Module'}) {
124                 &loadMyModule($hash{'Module'});
125             }
126
127             # check if CODEREF exists.
128             if (!defined &{ $hash{'CODEREF'} }) {
129                 &WARN("coderef $hash{'CODEREF'} does not exist.");
130                 if (defined $who) {
131                     &msg($who, "coderef does not exist for $ident.");
132                 }
133
134                 return 1;
135             }
136
137             if (exists $hash{'ArrayArgs'}) {
138                 &{ $hash{'CODEREF'} }(@args);
139             } else {
140                 &{ $hash{'CODEREF'} }($flatarg);
141             }
142         }
143
144         ### CMDSTATS.
145         if (exists $hash{'Cmdstats'}) {
146             $cmdstats{ $hash{'Cmdstats'} }++;
147         }
148
149         &VERB("hooks: End of command.",2);
150
151         $done = 1;
152     }
153
154     return 1 if ($done);
155     return 0;
156 }
157
158 sub Modules {
159     if (!defined $message) {
160         &WARN("Modules: message is undefined. should never happen.");
161         return;
162     }
163
164     my $debiancmd        = 'conflicts?|depends?|desc|file|(?:d)?info|provides?';
165     $debiancmd          .= '|recommends?|suggests?|maint|maintainer';
166
167     if ($message =~ /^($debiancmd)(\s+(.*))?$/i) {
168         return unless (&IsChanConfOrWarn('Debian'));
169         my $package = lc $3;
170
171         if (defined $package) {
172             &Forker('Debian', sub { &Debian::infoPackages($1, $package); } );
173         } else {
174             &help($1);
175         }
176
177         return;
178     }
179
180     # google searching. Simon++
181     my $w3search_regex   = "google";
182     if ($message =~ /^(?:search\s+)?($w3search_regex)\s+(?:for\s+)?['"]?(.*?)["']?\s*\?*$/i) {
183         return unless (&IsChanConfOrWarn('W3Search'));
184
185         &Forker('W3Search', sub { &W3Search::W3Search($1,$2); } );
186
187         $cmdstats{'W3Search'}++;
188         return;
189     }
190
191     # text counters. (eg: hehstats)
192     my $itc;
193     $itc = &getChanConf('ircTextCounters');
194     $itc = &findChanConf('ircTextCounters') unless ($itc);
195     return if ($itc && &do_text_counters($itc) == 1);
196     # end of text counters.
197
198     # list{keys|values}. xk++. Idea taken from #linuxwarez@EFNET
199     if ($message =~ /^list(\S+)(\s+(.*))?$/i) {
200         return unless (&IsChanConfOrWarn('Search'));
201
202         my $thiscmd     = lc $1;
203         my $args        = $3 || "";
204
205         $thiscmd        =~ s/^vals$/values/;
206         return if ($thiscmd ne 'keys' && $thiscmd ne 'values');
207
208         # Usage:
209         if (!defined $args or $args =~ /^\s*$/) {
210             &help('list'. $thiscmd);
211             return;
212         }
213
214         # suggested by asuffield and \broken.
215         if ($args =~ /^["']/ and $args =~ /["']$/) {
216             &DEBUG('list*: removed quotes.');
217             $args       =~ s/^["']|["']$//g;
218         }
219
220         if (length $args < 2 && &IsFlag('o') ne 'o') {
221             &msg($who, 'search string is too short.');
222             return;
223         }
224
225         &Forker('Search', sub { &Search::Search($thiscmd, $args); } );
226
227         $cmdstats{'Factoid Search'}++;
228         return;
229     }
230
231     # Nickometer. Adam Spiers++
232     if ($message =~ /^(?:lame|nick)ometer(?: for)? (\S+)/i) {
233         return unless (&IsChanConfOrWarn("nickometer"));
234
235         my $term = (lc $1 eq 'me') ? $who : $1;
236
237         &loadMyModule('nickometer');
238
239         if ($term =~ /^$mask{chan}$/) {
240             &status("Doing nickometer for chan $term.");
241
242             if (!&validChan($term)) {
243                 &msg($who, "error: channel is invalid.");
244                 return;
245             }
246
247             # step 1.
248             my %nickometer;
249             foreach (keys %{ $channels{lc $term}{''} }) {
250                 my $str   = $_;
251                 if (!defined $str) {
252                     &WARN("nickometer: nick in chan $term undefined?");
253                     next;
254                 }
255
256                 my $value = &nickometer($str);
257                 $nickometer{$value}{$str} = 1;
258             }
259
260             # step 2.
261             ### TODO: compact with map?
262             my @list;
263             foreach (sort {$b <=> $a} keys %nickometer) {
264                 my $str = join(", ", sort keys %{ $nickometer{$_} });
265                 push(@list, "$str ($_%)");
266             }
267
268             &performStrictReply( &formListReply(0, "Nickometer list for $term ", @list) );
269             &DEBUG("test.");
270
271             return;
272         }
273
274         my $percentage = &nickometer($term);
275
276         if ($percentage =~ /NaN/) {
277             $percentage = "off the scale";
278         } else {
279             $percentage = sprintf("%0.4f", $percentage);
280             $percentage =~ s/(\.\d+)0+$/$1/;
281             $percentage .= '%';
282         }
283
284         if ($msgType eq 'public') {
285             &say("'$term' is $percentage lame, $who");
286         } else {
287             &msg($who, "the 'lame nick-o-meter' reading for $term is $percentage, $who");
288         }
289
290         return;
291     }
292
293     # Topic management. xk++
294     # may want to add a userflags for topic. -xk
295     if ($message =~ /^topic(\s+(.*))?$/i) {
296         return unless (&IsChanConfOrWarn('Topic'));
297
298         my $chan        = $talkchannel;
299         my @args        = split / /, $2 || "";
300
301         if (!scalar @args) {
302             &msg($who,"Try 'help topic'");
303             return;
304         }
305
306         $chan           = lc(shift @args) if ($msgType eq 'private');
307         my $thiscmd     = shift @args;
308
309         # topic over public:
310         if ($msgType eq 'public' && $thiscmd =~ /^#/) {
311             &msg($who, "error: channel argument is not required.");
312             &msg($who, "\002Usage\002: topic <CMD>");
313             return;
314         }
315
316         # topic over private:
317         if ($msgType eq 'private' && $chan !~ /^#/) {
318             &msg($who, "error: channel argument is required.");
319             &msg($who, "\002Usage\002: topic #channel <CMD>");
320             return;
321         }
322
323         if (&validChan($chan) == 0) {
324             &msg($who,"error: invalid channel \002$chan\002");
325             return;
326         }
327
328         # for semi-outsiders.
329         if (!&IsNickInChan($who,$chan)) {
330             &msg($who, "Failed. You ($who) are not in $chan, hey?");
331             return;
332         }
333
334         # now lets do it.
335         &loadMyModule('Topic');
336         &Topic($chan, $thiscmd, join(' ', @args));
337         $cmdstats{'Topic'}++;
338         return;
339     }
340
341     # wingate.
342     if ($message =~ /^wingate$/i) {
343         return unless (&IsChanConfOrWarn('Wingate'));
344
345         my $reply = "Wingate statistics: scanned \002"
346                         .scalar(keys %wingateToDo)."\002 hosts";
347         my $queue = scalar(keys %wingateToDo);
348         if ($queue) {
349             $reply .= ".  I have \002$queue\002 hosts in the queue";
350             $reply .= ".  Started the scan ".&Time2String(time() - $wingaterun)." ago";
351         }
352
353         &performStrictReply("$reply.");
354
355         return;
356     }
357
358     # do nothing and let the other routines have a go
359     return "CONTINUE";
360 }
361
362 # Uptime. xk++
363 sub uptime {
364     my $count = 1;
365     &msg($who, "- Uptime for $ident -");
366     &msg($who, "Now: ". &Time2String(&uptimeNow()) ." running $bot_version");
367
368     foreach (&uptimeGetInfo()) {
369         /^(\d+)\.\d+ (.*)/;
370         my $time = &Time2String($1);
371         my $info = $2;
372
373         &msg($who, "$count: $time $2");
374         $count++;
375     }
376 }
377
378 # seen.
379 sub seen {
380     my($person) = lc shift;
381     $person =~ s/\?*$//;
382
383     if (!defined $person or $person =~ /^$/) {
384         &help("seen");
385
386         my $i = &countKeys("seen");
387         &msg($who,"there ". &fixPlural("is",$i) ." \002$i\002 ".
388                 "seen ". &fixPlural("entry",$i) ." that I know of.");
389
390         return;
391     }
392
393     my @seen;
394
395     &seenFlush();       # very evil hack. oh well, better safe than sorry.
396
397     # TODO: convert to &sqlSelectRowHash();
398     my $select = "nick,time,channel,host,message";
399     if ($person eq "random") {
400         @seen = &randKey("seen", $select);
401     } else {
402         @seen = &sqlSelect("seen", $select, { nick => $person } );
403     }
404
405     if (scalar @seen < 2) {
406         foreach (@seen) {
407             &DEBUG("seen: _ => '$_'.");
408         }
409         &performReply("i haven't seen '$person'");
410         return;
411     }
412
413     # valid seen.
414     my $reply;
415     ### TODO: multi channel support. may require &IsNick() to return
416     ### all channels or something.
417
418     my @chans = &getNickInChans($seen[0]);
419     if (scalar @chans) {
420         $reply = "$seen[0] is currently on";
421
422         foreach (@chans) {
423             $reply .= " ".$_;
424             next unless (exists $userstats{lc $seen[0]}{'Join'});
425             $reply .= " (".&Time2String(time() - $userstats{lc $seen[0]}{'Join'}).")";
426         }
427
428         if (&IsChanConf("seenStats") > 0) {
429             my $i;
430             $i = $userstats{lc $seen[0]}{'Count'};
431             $reply .= ".  Has said a total of \002$i\002 messages" if (defined $i);
432             $i = $userstats{lc $seen[0]}{'Time'};
433             $reply .= ".  Is idling for ".&Time2String(time() - $i) if (defined $i);
434         }
435     } else {
436         my $howlong = &Time2String(time() - $seen[1]);
437         $reply = "$seen[0] <$seen[3]> was last seen on IRC ".
438                  "in channel $seen[2], $howlong ago, ".
439                  "saying\002:\002 '$seen[4]'.";
440     }
441
442     &performStrictReply($reply);
443     return;
444 }
445
446 # User Information Services. requested by Flugh.
447 sub userinfo {
448     my ($arg) = join(' ',@_);
449
450     if ($arg =~ /^set(\s+(.*))?$/i) {
451         $arg = $2;
452         if (!defined $arg) {
453             &help('userinfo set');
454             return;
455         }
456
457         &UserInfoSet(split /\s+/, $arg, 2);
458     } elsif ($arg =~ /^unset(\s+(.*))?$/i) {
459         $arg = $2;
460         if (!defined $arg) {
461             &help('userinfo unset');
462             return;
463         }
464
465         &UserInfoSet($arg, '');
466     } else {
467         &UserInfoGet($arg);
468     }
469 }
470
471 # cookie (random). xk++
472 sub cookie {
473     my ($arg) = @_;
474
475     # lets find that secret cookie.
476     my $target          = ($msgType ne 'public') ? $who : $talkchannel;
477     my $cookiemsg       = &getRandom(keys %{ $lang{'cookie'} });
478     my ($key,$value);
479
480     ### WILL CHEW TONS OF MEM.
481     ### TODO: convert this to a Forker function!
482     if ($arg) {
483         my @list = &searchTable("factoids", "factoid_key", "factoid_value", $arg);
484         $key    = &getRandom(@list);
485         $value  = &getFactInfo($key, "factoid_value");
486     } else {
487         ($key,$value) = &randKey("factoids","factoid_key,factoid_value");
488     }
489
490     for ($cookiemsg) {
491         s/##KEY/\002$key\002/;
492         s/##VALUE/$value/;
493         s/##WHO/$who/;
494         s/\$who/$who/;  # cheap fix.
495         s/(\S+)?\s*<\S+>/$1 /;
496         s/\s+/ /g;
497     }
498
499     if ($cookiemsg =~ s/^ACTION //i) {
500         &action($target, $cookiemsg);
501     } else {
502         &msg($target, $cookiemsg);
503     }
504 }
505
506 sub convert {
507     my $arg = join(' ',@_);
508     my ($from,$to) = ('','');
509
510     ($from,$to) = ($1,$2) if ($arg =~ /^(.*?) to (.*)$/i);
511     ($from,$to) = ($2,$1) if ($arg =~ /^(.*?) from (.*)$/i);
512
513     if (!$to or !$from) {
514         &msg($who, "Invalid format!");
515         &help("convert");
516         return;
517     }
518
519     &Units::convertUnits($from, $to);
520
521     return;
522 }
523
524 sub lart {
525     my ($target) = &fixString($_[0]);
526     my $extra   = 0;
527     my $chan    = $talkchannel;
528     my ($for);
529
530     if ($msgType eq 'private') {
531         if ($target =~ /^($mask{chan})\s+(.*)$/) {
532             $chan       = $1;
533             $target     = $2;
534             $extra      = 1;
535         } else {
536             &msg($who, "error: invalid format or missing arguments.");
537             &help("lart");
538             return;
539         }
540     }
541     if ($target =~ /^(.*)(\s+for\s+.*)$/) {
542         $target = $1;
543         $for    = $2;
544     }
545
546     my $line = &getRandomLineFromFile($bot_data_dir. "/blootbot.lart");
547     if (defined $line) {
548         if ($target =~ /^(me|you|itself|\Q$ident\E)$/i) {
549             $line =~ s/WHO/$who/g;
550         } else {
551             $line =~ s/WHO/$target/g;
552         }
553         $line .= $for if ($for);
554         $line .= ", courtesy of $who" if ($extra);
555
556         &action($chan, $line);
557     } else {
558         &status("lart: error reading file?");
559     }
560 }
561
562 sub DebianNew {
563     my $idx   = "debian/Packages-sid.idx";
564     my $error = 0;
565     my %pkg;
566     my @new;
567
568     $error++ unless ( -e $idx);
569     $error++ unless ( -e "$idx-old");
570
571     if ($error) {
572         $error = "no sid/sid-old index file found.";
573         &ERROR("Debian: $error");
574         &msg($who, $error);
575         return;
576     }
577
578     open(IDX1, $idx);
579     open(IDX2, "$idx-old");
580
581     while (<IDX2>) {
582         chop;
583         next if (/^\*/);
584
585         $pkg{$_} = 1;
586     }
587     close IDX2;
588
589     open(IDX1,$idx);
590     while (<IDX1>) {
591         chop;
592         next if (/^\*/);
593         next if (exists $pkg{$_});
594
595         push(@new, $_);
596     }
597     close IDX1;
598
599     &::performStrictReply( &::formListReply(0, "New debian packages:", @new) );
600 }
601
602 sub do_verstats {
603     my ($chan)  = @_;
604
605     if (!defined $chan) {
606         &help("verstats");
607         return;
608     }
609
610     if (!&validChan($chan)) {
611         &msg($who, "chan $chan is invalid.");
612         return;
613     }
614
615     if (scalar @vernick > scalar(keys %{ $channels{lc $chan}{''} })/4) {
616         &msg($who, "verstats already in progress for someone else.");
617         return;
618     }
619
620     &msg($who, "Sending CTCP VERSION to $chan; results in 60s.");
621     $conn->ctcp("VERSION", $chan);
622     $cache{verstats}{chan}      = $chan;
623     $cache{verstats}{who}       = $who;
624     $cache{verstats}{msgType}   = $msgType;
625
626     $conn->schedule(30, sub {
627         my $c           = lc $cache{verstats}{chan};
628         @vernicktodo    = ();
629
630         foreach (keys %{ $channels{$c}{''} } ) {
631             next if (grep /^\Q$_\E$/i, @vernick);
632             push(@vernicktodo, $_);
633         }
634
635         &verstats_flush();
636     } );
637
638     $conn->schedule(60, sub {
639         my $vtotal      = 0;
640         my $c           = lc $cache{verstats}{chan};
641         my $total       = keys %{ $channels{$c}{''} };
642         $chan           = $c;
643         $who            = $cache{verstats}{who};
644         $msgType        = $cache{verstats}{msgType};
645         delete $cache{verstats};        # sufficient?
646
647         foreach (keys %ver) {
648             $vtotal     += scalar keys %{ $ver{$_} };
649         }
650
651         my %sorted;
652         my $unknown     = $total - $vtotal;
653         my $perc        = sprintf("%.1f", $unknown * 100 / $total);
654         $perc           =~ s/.0$//;
655         $sorted{$perc}{"unknown/cloak"} = "$unknown ($perc%)" if ($unknown);
656
657         foreach (keys %ver) {
658             my $count   = scalar keys %{ $ver{$_} };
659             $perc       = sprintf("%.01f", $count * 100 / $total);
660             $perc       =~ s/.0$//;     # lame compression.
661
662             $sorted{$perc}{$_} = "$count ($perc%)";
663         }
664
665         ### can be compressed to a map?
666         my @list;
667         foreach ( sort { $b <=> $a } keys %sorted ) {
668             my $perc = $_;
669             foreach (sort keys %{ $sorted{$perc} }) {
670                 push(@list, "$_ - $sorted{$perc}{$_}");
671             }
672         }
673
674         # hack. this is one major downside to scheduling.
675         $chan = $c;
676         &performStrictReply( &formListReply(0, "IRC Client versions for $c ", @list) );
677
678         # clean up not-needed data structures.
679         undef %ver;
680         undef @vernick;
681     } );
682
683     return;
684 }
685
686 sub verstats_flush {
687     for (1..5) {
688         last unless (scalar @vernicktodo);
689
690         my $n = shift(@vernicktodo);
691         $conn->ctcp("VERSION", $n);
692     }
693
694     return unless (scalar @vernicktodo);
695
696     $conn->schedule(3, \&verstats_flush() );
697 }
698
699 sub do_text_counters {
700     my ($itc) = @_;
701     $itc =~ s/([^\w\s])/\\$1/g;
702     my $z = join '|', split ' ', $itc;
703
704     if ($msgType eq "privmsg" and $message =~ / ($mask{chan})$/) {
705         &DEBUG("ircTC: privmsg detected; chan = $1");
706         $chan = $1;
707     }
708
709     if ($message =~ /^_stats(\s+(\S+))$/i) {
710         &textstats_main($2);
711         return 1;
712     }
713
714     my ($type,$arg);
715     if ($message =~ /^($z)stats(\s+(\S+))?$/i) {
716         $type = $1;
717         $arg  = $3;
718     } else {
719         return 0;
720     }
721
722     # even more uglier with channel/time arguments.
723     my $c       = $chan;
724 #   my $c       = $chan || "PRIVATE";
725     my $where   = "type=".&sqlQuote($type);
726     if (defined $c) {
727         &DEBUG("c => $c");
728         $where  .= " AND channel=".&sqlQuote($c) if (defined $c);
729     } else {
730         &DEBUG("not using chan arg");
731     }
732
733     my $sum = (&sqlRawReturn("SELECT SUM(counter) FROM stats"
734                         ." WHERE ".$where ))[0];
735
736     if (!defined $arg or $arg =~ /^\s*$/) {
737         # this is way ugly.
738
739         # TODO: convert $where to hash
740         my %hash = &sqlSelectColHash("stats", "nick,counter",
741                         { },
742                         $where." ORDER BY counter DESC LIMIT 3", 1
743         );
744         my $i;
745         my @top;
746
747         # unfortunately we have to sort it again!
748         my $tp = 0;
749         foreach $i (sort { $b <=> $a } keys %hash) {
750             foreach (keys %{ $hash{$i} }) {
751                 my $p   = sprintf("%.01f", 100*$i/$sum);
752                 $tp     += $p;
753                 push(@top, "\002$_\002 -- $i ($p%)");
754             }
755         }
756         my $topstr = "";
757         if (scalar @top) {
758             $topstr = ".  Top ".scalar(@top).": ".join(', ', @top);
759         }
760
761         if (defined $sum) {
762             &performStrictReply("total count of \037$type\037 on \002$c\002: $sum$topstr");
763         } else {
764             &performStrictReply("zero counter for \037$type\037.");
765         }
766     } else {
767         # TODO: convert $where to hash and use a sqlSelect
768         my $x = (&sqlRawReturn("SELECT SUM(counter) FROM stats".
769                         " WHERE $where AND nick=".&sqlQuote($arg) ))[0];
770
771         if (!defined $x) {      # !defined.
772             &performStrictReply("$arg has not said $type yet.");
773             return 1;
774         }
775
776         # defined.
777         # TODO: convert $where to hash
778         my @array = &sqlSelect("stats", "nick", undef,
779                         $where." ORDER BY counter", 1
780         );
781         my $good = 0;
782         my $i = 0;
783         for ($i=0; $i<scalar @array; $i++) {
784             next unless ($array[0] =~ /^\Q$who\E$/);
785             $good++;
786             last;
787         }
788         $i++;
789
790         my $total = scalar(@array);
791         my $xtra = "";
792         if ($total and $good) {
793             my $pct = sprintf("%.01f", 100*(1+$total-$i)/$total);
794             $xtra = ", ranked $i\002/\002$total (percentile: \002$pct\002 %)";
795         }
796
797         my $pct1 = sprintf("%.01f", 100*$x/$sum);
798         &performStrictReply("\002$arg\002 has said \037$type\037 \002$x\002 times (\002$pct1\002 %)$xtra");
799     }
800
801     return 1;
802 }
803
804 sub textstats_main {
805     my($arg) = @_;
806
807     # even more uglier with channel/time arguments.
808     my $c       = $chan;
809 #    my $c      = $chan || "PRIVATE";
810     &DEBUG("not using chan arg") if (!defined $c);
811
812     # example of converting from RawReturn to sqlSelect.
813     my $where_href = (defined $c) ? { channel => $c } : "";
814     my $sum = &sqlSelect("stats", "SUM(counter)", $where_href);
815
816     if (!defined $arg or $arg =~ /^\s*$/) {
817         # this is way ugly.
818         &DEBUG("_stats: !arg");
819
820         my %hash = &sqlSelectColHash("stats", "nick,counter",
821                 $where_href,
822                 " ORDER BY counter DESC LIMIT 3", 1
823         );
824         my $i;
825         my @top;
826
827         # unfortunately we have to sort it again!
828         my $tp = 0;
829         foreach $i (sort { $b <=> $a } keys %hash) {
830             foreach (keys %{ $hash{$i} }) {
831                 my $p   = sprintf("%.01f", 100*$i/$sum);
832                 $tp     += $p;
833                 push(@top, "\002$_\002 -- $i ($p%)");
834             }
835         }
836
837         my $topstr = "";
838         if (scalar @top) {
839             $topstr = ".  Top ".scalar(@top).": ".join(', ', @top);
840         }
841
842         if (defined $sum) {
843             &performStrictReply("total count of \037$type\037 on \002$c\002: $sum$topstr");
844         } else {
845             &performStrictReply("zero counter for \037$type\037.");
846         }
847
848         return;
849     }
850
851     # TODO: add nick to where_href
852     my %hash = &sqlSelectColHash("stats", "type,counter",
853                 $where_href, " AND nick=".&sqlQuote($arg)
854     );
855
856     # this is totally messed up... needs to be fixed... and cleaned up.
857     my $total;
858     my $good;
859     my $ii;
860     my $x;
861
862     foreach (keys %hash) {
863         &DEBUG("_stats: hash{$_} => $hash{$_}");
864         # ranking.
865         # TODO: convert $where to hash
866         my $where = '';
867         my @array = &sqlSelect("stats", "nick", undef, $where." ORDER BY counter", 1);
868         $good = 0;
869         $ii = 0;
870         for(my $i=0; $i<scalar @array; $i++) {
871             next unless ($array[0] =~ /^\Q$who\E$/);
872             $good++;
873             last;
874         }
875         $ii++;
876
877         $total = scalar(@array);
878         &DEBUG("   i => $i, good => $good, total => $total");
879         $x .= " ".$total."blah blah";
880     }
881
882 #    return;
883
884     if (!defined $x) {  # !defined.
885         &performStrictReply("$arg has not said $type yet.");
886         return;
887     }
888
889     my $xtra = "";
890     if ($total and $good) {
891         my $pct = sprintf("%.01f", 100*(1+$total-$ii)/$total);
892         $xtra = ", ranked $ii\002/\002$total (percentile: \002$pct\002 %)";
893     }
894
895     my $pct1 = sprintf("%.01f", 100*$x/$sum);
896     &performStrictReply("\002$arg\002 has said \037$type\037 \002$x\002 times (\002$pct1\002 %)$xtra");
897 }
898
899 sub nullski {
900     my ($arg) = @_;
901     return unless (defined $arg);
902     # big security hole
903     #foreach (`$arg`) { &msg($who,$_); }
904 }
905
906 %cmdhooks=();
907 ###
908 ### START ADDING HOOKS.
909 ###
910 &addCmdHook('chan(stats|info)', ('CODEREF' => 'chaninfo', ) );
911 &addCmdHook('cmd(stats|info)', ('CODEREF' => 'cmdstats', ) );
912 &addCmdHook('sched(stats|info)', ('CODEREF' => 'scheduleList', ) );
913 &addCmdHook('factinfo', ('CODEREF' => 'factinfo',
914         'Cmdstats' => 'Factoid Info', Module => 'Factoids', ) );
915 &addCmdHook('factstats?', ('CODEREF' => 'factstats',
916         'Cmdstats' => 'Factoid Stats', Help => "factstats",
917         Forker => 1, 'Identifier' => 'Factoids', ) );
918 &addCmdHook('help', ('CODEREF' => 'help',
919         'Cmdstats' => 'Help', ) );
920 &addCmdHook('karma', ('CODEREF' => 'karma', ) );
921 &addCmdHook('tell|explain', ('CODEREF' => 'tell',
922         Help => 'tell', Identifier => 'allowTelling',
923         Cmdstats => 'Tell') );
924 &addCmdHook('News', ('CODEREF' => 'News::Parse',
925         Module => 'News', 'Cmdstats' => 'News' ) );
926 &addCmdHook('countrystats', ('CODEREF' => 'countryStats',
927 #       Forker => "NULL",
928  ) );
929
930 &addCmdHook('d?bugs', ('CODEREF' => 'DebianExtra::Parse',
931         'Forker' => 1, 'Identifier' => 'DebianExtra',
932         'Cmdstats' => 'Debian Bugs') );
933 &addCmdHook('dauthor', ('CODEREF' => 'Debian::searchAuthor',
934         'Forker' => 1, 'Identifier' => 'Debian',
935         'Cmdstats' => 'Debian Author Search', 'Help' => "dauthor" ) );
936 &addCmdHook('(d|search)desc', ('CODEREF' => 'Debian::searchDescFE',
937         'Forker' => 1, 'Identifier' => 'Debian',
938         'Cmdstats' => 'Debian Desc Search', 'Help' => "ddesc" ) );
939 &addCmdHook('dnew', ('CODEREF' => 'DebianNew',
940         'Identifier' => 'Debian' ) );
941 &addCmdHook('dincoming', ('CODEREF' => 'Debian::generateIncoming',
942         'Forker' => 1, 'Identifier' => 'Debian' ) );
943 &addCmdHook('dstats', ('CODEREF' => 'Debian::infoStats',
944         'Forker' => 1, 'Identifier' => 'Debian',
945         'Cmdstats' => 'Debian Statistics' ) );
946 &addCmdHook('d?contents', ('CODEREF' => 'Debian::searchContents',
947         'Forker' => 1, 'Identifier' => 'Debian',
948         'Cmdstats' => 'Debian Contents Search', 'Help' => "contents" ) );
949 &addCmdHook('d?find', ('CODEREF' => 'Debian::DebianFind',
950         'Forker' => 1, 'Identifier' => 'Debian',
951         'Cmdstats' => 'Debian Search', 'Help' => "find" ) );
952 &addCmdHook('insult', ('CODEREF' => 'Insult::Insult',
953         'Forker' => 1, 'Identifier' => 'insult', 'Help' => "insult" ) );
954 &addCmdHook('kernel', ('CODEREF' => 'Kernel::Kernel',
955         'Forker' => 1, 'Identifier' => 'Kernel',
956         'Cmdstats' => 'Kernel', 'NoArgs' => 1) );
957 &addCmdHook('listauth', ('CODEREF' => 'CmdListAuth',
958         'Identifier' => 'Search', Module => 'Factoids',
959         'Help' => 'listauth') );
960 &addCmdHook('quote', ('CODEREF' => 'Quote::Quote',
961         'Forker' => 1, 'Identifier' => 'Quote',
962         'Help' => 'quote', 'Cmdstats' => 'Quote') );
963 &addCmdHook('countdown', ('CODEREF' => 'countdown',
964         'Module' => 'countdown', 'Identifier' => 'countdown',
965         'Cmdstats' => 'countdown') );
966 &addCmdHook('lart', ('CODEREF' => 'lart',
967         'Identifier' => 'lart', 'Help' => 'lart') );
968 &addCmdHook('convert', ('CODEREF' => 'convert',
969         'Forker' => 1, 'Identifier' => 'Units',
970         'Help' => 'convert') );
971 &addCmdHook('(cookie|random)', ('CODEREF' => 'cookie',
972         'Forker' => 1, 'Identifier' => 'Factoids') );
973 &addCmdHook('u(ser)?info', ('CODEREF' => 'userinfo',
974         'Identifier' => 'UserInfo', 'Help' => 'userinfo',
975         'Module' => 'UserInfo') );
976 &addCmdHook('RootWarn', ('CODEREF' => 'CmdrootWarn',
977         'Identifier' => 'RootWarn', 'Module' => 'RootWarn') );
978 &addCmdHook('seen', ('CODEREF' => 'seen', 'Identifier' =>
979         'seen') );
980 &addCmdHook('Dict', ('CODEREF' => 'Dict::Dict',
981         'Identifier' => 'Dict', 'Help' => 'dict',
982         'Forker' => 1, 'Cmdstats' => 'Dict') );
983 &addCmdHook('slashdot', ('CODEREF' => 'Slashdot::Slashdot',
984         'Identifier' => 'slashdot', 'Forker' => 1,
985         'Cmdstats' => 'slashdot') );
986 &addCmdHook('Plug', ('CODEREF' => 'Plug::Plug',
987         'Identifier' => 'Plug', 'Forker' => 1,
988         'Cmdstats' => 'Plug') );
989 &addCmdHook('Uptime', ('CODEREF' => 'uptime', 'Identifier' => 'Uptime',
990         'Cmdstats' => 'Uptime') );
991 &addCmdHook('nullski', ('CODEREF' => 'nullski', ) );
992 &addCmdHook('verstats', ('CODEREF' => 'do_verstats' ) );
993 &addCmdHook('Weather', ('CODEREF' => 'Weather::Weather',
994         'Identifier' => 'Weather', 'Help' => 'weather',
995         'Cmdstats' => 'Weather', 'Forker' => 1) );
996 &addCmdHook('metar', ('CODEREF' => 'Weather::Metar',
997         'Identifier' => 'Weather', 'Help' => 'weather',
998         'Cmdstats' => 'Weather', 'Forker' => 1) );
999 &addCmdHook('bzflist', ('CODEREF' => 'BZFlag::list',
1000         'Identifier' => 'BZFlag', 'Cmdstats' => 'BZFlag',
1001         'Forker' => 1) );
1002 &addCmdHook('bzflist17', ('CODEREF' => 'BZFlag::list17',
1003         'Identifier' => 'BZFlag', 'Cmdstats' => 'BZFlag',
1004         'Forker' => 1) );
1005 &addCmdHook('bzfquery', ('CODEREF' => 'BZFlag::query',
1006         'Identifier' => 'BZFlag', 'Cmdstats' => 'BZFlag',
1007         'Forker' => 1) );
1008 &addCmdHook('zfi', ('CODEREF' => 'zfi::query',
1009         'Identifier' => 'zfi', 'Cmdstats' => 'zfi',
1010         'Forker' => 1) );
1011 &addCmdHook('(zippy|yow)', ('CODEREF' => 'zippy::get',
1012         'Identifier' => 'Zippy', 'Cmdstats' => 'Zippy',
1013         'Forker' => 1) );
1014 &addCmdHook('zsi', ('CODEREF' => 'zsi::query',
1015         'Identifier' => 'zsi', 'Cmdstats' => 'zsi',
1016         'Forker' => 1) );
1017 &addCmdHook('(ex)?change', ('CODEREF' => 'Exchange::query',
1018         'Identifier' => 'Exchange', 'Cmdstats' => 'Exchange',
1019         'Forker' => 1) );
1020 &addCmdHook('(botmail|message)', ('CODEREF' => 'botmail::parse',
1021         'Identifier' => 'botmail', 'Cmdstats' => 'botmail') );
1022 &addCmdHook('HTTPDtype', ('CODEREF' => 'HTTPDtype::HTTPDtype',
1023         'Identifier' => 'HTTPDtype', 'Cmdstats' => 'HTTPDtype',
1024         'Forker' => 1) );
1025 &addCmdHook('scramble', ('CODEREF' => 'scramble::scramble',
1026         'Identifier' => 'scramble', 'Cmdstats' => 'scramble',
1027         'Forker' => 1, 'Module' => 'scramble') );
1028 &addCmdHook('md5(sum)?', ('CODEREF' => 'md5::md5',
1029         'Identifier' => 'md5', 'Cmdstats' => 'md5',
1030         'Forker' => 1) );
1031 &addCmdHook('Rss', ('CODEREF' => 'Rss::Rss',
1032         'Identifier' => 'Rss', 'Cmdstats' => 'Rss',
1033         'Forker' => 1, 'Help' => 'rss') );
1034 &addCmdHook('wiki(pedia)?', ('CODEREF' => 'wikipedia::wikipedia',
1035         'Identifier' => 'wikipedia', 'Cmdstats' => 'wikipedia',
1036         'Forker' => 1, 'Help' => 'wikipedia') );
1037 &addCmdHook('page', ('CODEREF' => 'pager::page',
1038         'Identifier' => 'pager', 'Cmdstats' => 'pager',
1039         'Forker' => 1, 'Help' => 'page') );
1040 &addCmdHook('(babel(fish)?|x|xlate|translate)', ('CODEREF' => 'babelfish::babelfish',
1041         'Identifier' => 'babelfish', 'Cmdstats' => 'babelfish',
1042         'Forker' => 1, 'Help' => 'babelfish', 'Module' => 'babelfish') );
1043 &addCmdHook('wtf', ('CODEREF' => 'wtf::query',
1044         'Identifier' => 'wtf', 'Cmdstats' => 'wtf',
1045         'Forker' => 1, 'Help' => 'wtf') );
1046 &addCmdHook('[ia]?spell', ('CODEREF' => 'spell::query',
1047         'Identifier' => 'spell', 'Cmdstats' => 'spell',
1048         'Forker' => 1, 'Help' => 'spell') );
1049 &addCmdHook('dns|d?nslookup', ('CODEREF' => 'dns::query',
1050         'Identifier' => 'dns', 'Cmdstats' => 'dns',
1051         'Forker' => 1, 'Help' => 'dns') );
1052 &addCmdHook('piglatin', ('CODEREF' => 'piglatin::piglatin',
1053         'Identifier' => 'piglatin', 'Cmdstats' => 'piglatin',
1054         'Forker' => 1) );
1055 ###
1056 ### END OF ADDING HOOKS.
1057 ###
1058 &status("CMD: loaded ".scalar(keys %cmdhooks)." command hooks.");
1059 1;