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