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