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