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