]> git.donarmstrong.com Git - infobot.git/blob - src/CommandStubs.pl
- patch from Morten Brix Pedersen <morten@wtf.dk>. Thanks!
[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 ($msgType eq "privmsg" and $message =~ / ($mask{chan})$/) {
284             &DEBUG("ircTC: privmsg detected; chan = $1");
285             $chan = $1;
286         }
287
288         if ($message =~ /^_stats(\s+(\S+))$/i) {
289             &textstats_main($2);
290             return;
291         }
292
293         if ($message =~ /^($z)stats(\s+(\S+))?$/i) {
294             my $type    = $1;
295             my $arg     = $3;
296
297             # even more uglier with channel/time arguments.
298             my $c       = $chan;
299 #           my $c       = $chan || "PRIVATE";
300             my $where   = "type=".&dbQuote($type);
301             $where      .= " AND channel=".&dbQuote($c) if (defined $c);
302             &DEBUG("not using chan arg") if (!defined $c);
303             my $sum = (&dbRawReturn("SELECT SUM(counter) FROM stats"
304                         ." WHERE ".$where ))[0];
305
306             if (!defined $arg or $arg =~ /^\s*$/) {
307                 # this is way fucking ugly.
308
309                 my %hash = &dbGetCol("stats", "nick,counter",
310                         $where." ORDER BY counter DESC LIMIT 3", 1);
311                 my $i;
312                 my @top;
313
314                 # unfortunately we have to sort it again!
315                 # todo: make dbGetCol return hash and array? too much effort.
316                 my $tp = 0;
317                 foreach $i (sort { $b <=> $a } keys %hash) {
318                     foreach (keys %{ $hash{$i} }) {
319                         my $p   = sprintf("%.01f", 100*$i/$sum);
320                         $tp     += $p;
321                         push(@top, "\002$_\002 -- $i ($p%)");
322                     }
323                 }
324                 my $topstr = "";
325                 &DEBUG("*stats: tp => $tp");
326                 if (scalar @top) {
327                     $topstr = ".  Top ".scalar(@top).": ".join(', ', @top);
328                 }
329
330                 if (defined $sum) {
331                     &pSReply("total count of \037$type\037 on \002$c\002: $sum$topstr");
332                 } else {
333                     &pSReply("zero counter for \037$type\037.");
334                 }
335             } else {
336                 my $x = (&dbRawReturn("SELECT SUM(counter) FROM stats".
337                         " WHERE $where AND nick=".&dbQuote($arg) ))[0];
338
339                 if (!defined $x) {      # !defined.
340                     &pSReply("$arg has not said $type yet.");
341                     return;
342                 }
343
344                 # defined.
345                 my @array = &dbGet("stats", "nick",
346                         $where." ORDER BY counter", 1);
347                 my $good = 0;
348                 my $i = 0;
349                 for($i=0; $i<scalar @array; $i++) {
350                     next unless ($array[0] =~ /^\Q$who\E$/);
351                     $good++;
352                     last;
353                 }
354                 $i++;
355
356                 my $total = scalar(@array);
357                 my $xtra = "";
358                 if ($total and $good) {
359                     my $pct = sprintf("%.01f", 100*(1+$total-$i)/$total);
360                     $xtra = ", ranked $i\002/\002$total (percentile: \002$pct\002 %)";
361                 }
362
363                 my $pct1 = sprintf("%.01f", 100*$x/$sum);
364                 &pSReply("\002$arg\002 has said \037$type\037 \002$x\002 times (\002$pct1\002 %)$xtra");
365             }
366
367             return;
368         }
369
370         if ($@) {
371             &DEBUG("regex failed: $@");
372             return;
373         }
374     }
375
376     # list{keys|values}. xk++. Idea taken from #linuxwarez@EFNET
377     if ($message =~ /^list(\S+)(\s+(.*))?$/i) {
378         return unless (&hasParam("search"));
379
380         my $thiscmd     = lc $1;
381         my $args        = $3 || "";
382
383         $thiscmd        =~ s/^vals$/values/;
384 #       $args           =~ s/\s+$//g;
385         return if ($thiscmd ne "keys" && $thiscmd ne "values");
386
387         # Usage:
388         if (!defined $args or $args =~ /^\s*$/) {
389             &help("list". $thiscmd);
390             return;
391         }
392
393         # suggested by asuffield and \broken.
394         if ($args =~ /^["']/ and $args =~ /["']$/) {
395             &DEBUG("list*: removed quotes.");
396             $args       =~ s/^["']|["']$//g;
397         }
398
399         if (length $args == 1) {
400             &msg($who,"search string is too short.");
401             return;
402         }
403
404         &Forker("search", sub { &Search::Search($thiscmd, $args); } );
405
406         $cmdstats{'Factoid Search'}++;
407         return;
408     }
409
410     # Nickometer. Adam Spiers++
411     if ($message =~ /^(?:lame|nick)ometer(?: for)? (\S+)/i) {
412         return unless (&hasParam("nickometer"));
413
414         my $term = (lc $1 eq 'me') ? $who : $1;
415
416         &loadMyModule($myModules{'nickometer'});
417
418         if ($term =~ /^$mask{chan}$/) {
419             &status("Doing nickometer for chan $term.");
420
421             if (!&validChan($term)) {
422                 &msg($who, "error: channel is invalid.");
423                 return;
424             }
425
426             # step 1.
427             my %nickometer;
428             foreach (keys %{ $channels{lc $term}{''} }) {
429                 my $str   = $_;
430                 if (!defined $str) {
431                     &WARN("nickometer: nick in chan $term undefined?");
432                     next;
433                 }
434
435                 my $value = &nickometer($str);
436                 $nickometer{$value}{$str} = 1;
437             }
438
439             # step 2.
440             ### TODO: compact with map?
441             my @list;
442             foreach (sort {$b <=> $a} keys %nickometer) {
443                 my $str = join(", ", sort keys %{ $nickometer{$_} });
444                 push(@list, "$str ($_%)");
445             }
446
447             &pSReply( &formListReply(0, "Nickometer list for $term ", @list) );
448             &DEBUG("test.");
449
450             return;
451         }
452
453         my $percentage = &nickometer($term);
454
455         if ($percentage =~ /NaN/) {
456             $percentage = "off the scale";
457         } else {
458             $percentage = sprintf("%0.4f", $percentage);
459             $percentage =~ s/\.?0+$//;
460             $percentage .= '%';
461         }
462
463         if ($msgType eq 'public') {
464             &say("'$term' is $percentage lame, $who");
465         } else {
466             &msg($who, "the 'lame nick-o-meter' reading for $term is $percentage, $who");
467         }
468
469         return;
470     }
471
472     # Topic management. xk++
473     # may want to add a userflags for topic. -xk
474     if ($message =~ /^topic(\s+(.*))?$/i) {
475         return unless (&hasParam("topic"));
476
477         my $chan        = $talkchannel;
478         my @args        = split / /, $2 || "";
479
480         if (!scalar @args) {
481             &msg($who,"Try 'help topic'");
482             return;
483         }
484
485         $chan           = lc(shift @args) if ($msgType eq 'private');
486         my $thiscmd     = shift @args;
487
488         # topic over public:
489         if ($msgType eq 'public' && $thiscmd =~ /^#/) {
490             &msg($who, "error: channel argument is not required.");
491             &msg($who, "\002Usage\002: topic <CMD>");
492             return;
493         }
494
495         # topic over private:
496         if ($msgType eq 'private' && $chan !~ /^#/) {
497             &msg($who, "error: channel argument is required.");
498             &msg($who, "\002Usage\002: topic #channel <CMD>");
499             return;
500         }
501
502         if (&validChan($chan) == 0) {
503             &msg($who,"error: invalid channel \002$chan\002");
504             return;
505         }
506
507         # for semi-outsiders.
508         if (!&IsNickInChan($who,$chan)) {
509             &msg($who, "Failed. You ($who) are not in $chan, hey?");
510             return;
511         }
512
513         # now lets do it.
514         &loadMyModule($myModules{'topic'});
515         &Topic($chan, $thiscmd, join(' ', @args));
516         $cmdstats{'Topic'}++;
517         return;
518     }
519
520     # wingate.
521     if ($message =~ /^wingate$/i) {
522         return unless (&hasParam("wingate"));
523
524         my $reply = "Wingate statistics: scanned \002"
525                         .scalar(keys %wingate)."\002 hosts";
526         my $queue = scalar(keys %wingateToDo);
527         if ($queue) {
528             $reply .= ".  I have \002$queue\002 hosts in the queue";
529             $reply .= ".  Started the scan ".&Time2String(time() - $wingaterun)." ago";
530         }
531
532         &performStrictReply("$reply.");
533
534         return;
535     }
536
537     # do nothing and let the other routines have a go
538     return "CONTINUE";
539 }
540
541 # Freshmeat. xk++
542 sub freshmeat {
543     my ($query) = @_;
544
545     if (!defined $query) {
546         &help("freshmeat");
547         &msg($who, "I have \002".&countKeys("freshmeat")."\002 entries.");
548         return;
549     }
550
551     &Freshmeat::Freshmeat($query);
552 }
553
554 # Uptime. xk++
555 sub uptime {
556     my $count = 1;
557     &msg($who, "- Uptime for $ident -");
558     &msg($who, "Now: ". &Time2String(&uptimeNow()) ." running $bot_version");
559
560     foreach (&uptimeGetInfo()) {
561         /^(\d+)\.\d+ (.*)/;
562         my $time = &Time2String($1);
563         my $info = $2;
564
565         &msg($who, "$count: $time $2");
566         $count++;
567     }
568 }
569
570 # seen.
571 sub seen {
572     my($person) = lc shift;
573     $person =~ s/\?*$//;
574
575     if (!defined $person or $person =~ /^$/) {
576         &help("seen");
577
578         my $i = &countKeys("seen");
579         &msg($who,"there ". &fixPlural("is",$i) ." \002$i\002 ".
580                 "seen ". &fixPlural("entry",$i) ." that I know of.");
581
582         return;
583     }
584
585     my @seen;
586
587     &seenFlush();       # very evil hack. oh well, better safe than sorry.
588
589     ### TODO: Support &dbGetColInfo(); like in &FactInfo();
590     my $select = "nick,time,channel,host,message";
591     if ($person eq "random") {
592         @seen = &randKey("seen", $select);
593     } else {
594         @seen = &dbGet("seen", $select, "nick=".&dbQuote($person) );
595     }
596
597     if (scalar @seen < 2) {
598         foreach (@seen) {
599             &DEBUG("seen: _ => '$_'.");
600         }
601         &performReply("i haven't seen '$person'");
602         return;
603     }
604
605     # valid seen.
606     my $reply;
607     ### TODO: multi channel support. may require &IsNick() to return
608     ### all channels or something.
609     my @chans = &getNickInChans($seen[0]);
610     if (scalar @chans) {
611         $reply = "$seen[0] is currently on";
612
613         foreach (@chans) {
614             $reply .= " ".$_;
615             next unless (exists $userstats{lc $seen[0]}{'Join'});
616             $reply .= " (".&Time2String(time() - $userstats{lc $seen[0]}{'Join'}).")";
617         }
618
619         if (&IsParam("seenStats")) {
620             my $i;
621             $i = $userstats{lc $seen[0]}{'Count'};
622             $reply .= ".  Has said a total of \002$i\002 messages" if (defined $i);
623             $i = $userstats{lc $seen[0]}{'Time'};
624             $reply .= ".  Is idling for ".&Time2String(time() - $i) if (defined $i);
625         }
626     } else {
627         my $howlong = &Time2String(time() - $seen[1]);
628         $reply = "$seen[0] <$seen[3]> was last seen on IRC ".
629                  "in channel $seen[2], $howlong ago, ".
630                  "saying\002:\002 '$seen[4]'.";
631     }
632
633     &pSReply($reply);
634     return;
635 }
636
637 # User Information Services. requested by Flugh.
638 sub userinfo {
639     my ($arg) = join(' ',@_);
640
641     if ($arg =~ /^set(\s+(.*))?$/i) {
642         $arg = $2;
643         if (!defined $arg) {
644             &help("userinfo set");
645             return;
646         }
647
648         &UserInfoSet(split /\s+/, $arg, 2);
649     } elsif ($arg =~ /^unset(\s+(.*))?$/i) {
650         $arg = $2;
651         if (!defined $arg) {
652             &help("userinfo unset");
653             return;
654         }
655
656         &UserInfoSet($arg, "");
657     } else {
658         &UserInfoGet($arg);
659     }
660 }
661
662 # cookie (random). xk++
663 sub cookie {
664     my ($arg) = @_;
665
666     # lets find that secret cookie.
667     my $target          = ($msgType ne 'public') ? $who : $talkchannel;
668     my $cookiemsg       = &getRandom(keys %{ $lang{'cookie'} });
669     my ($key,$value);
670
671     ### WILL CHEW TONS OF MEM.
672     ### TODO: convert this to a Forker function!
673     if ($arg) {
674         my @list = &searchTable("factoids", "factoid_key", "factoid_value", $arg);
675         $key  = &getRandom(@list);
676         $val  = &getFactInfo("factoids", $key, "factoid_value");
677     } else {
678         ($key,$value) = &randKey("factoids","factoid_key,factoid_value");
679     }
680
681     for ($cookiemsg) {
682         s/##KEY/\002$key\002/;
683         s/##VALUE/$value/;
684         s/##WHO/$who/;
685         s/\$who/$who/;  # cheap fix.
686         s/(\S+)?\s*<\S+>/$1 /;
687         s/\s+/ /g;
688     }
689
690     if ($cookiemsg =~ s/^ACTION //i) {
691         &action($target, $cookiemsg);
692     } else {
693         &msg($target, $cookiemsg);
694     }
695 }
696
697 sub convert {
698     my $arg = join(' ',@_);
699     my ($from,$to) = ('','');
700
701     ($from,$to) = ($1,$2) if ($arg =~ /^(.*?) to (.*)$/i);
702     ($from,$to) = ($2,$1) if ($arg =~ /^(.*?) from (.*)$/i);
703
704     if (!$to or !$from) {
705         &msg($who, "Invalid format!");
706         &help("convert");
707         return;
708     }
709
710     &Units::convertUnits($from, $to);
711
712     return;
713 }
714
715 sub lart {
716     my ($target) = &fixString($_[0]);
717     my $extra   = 0;
718     my $chan    = $talkchannel;
719
720     if ($msgType eq 'private') {
721         if ($target =~ /^($mask{chan})\s+(.*)$/) {
722             $chan       = $1;
723             $target     = $2;
724             $extra      = 1;
725         } else {
726             &msg($who, "error: invalid format or missing arguments.");
727             &help("lart");
728             return;
729         }
730     }
731
732     my $line = &getRandomLineFromFile($bot_data_dir. "/blootbot.lart");
733     if (defined $line) {
734         if ($target =~ /^(me|you|itself|\Q$ident\E)$/i) {
735             $line =~ s/WHO/$who/g;
736         } else {
737             $line =~ s/WHO/$target/g;
738         }
739         $line .= ", courtesy of $who" if ($extra);
740
741         &action($chan, $line);
742     } else {
743         &status("lart: error reading file?");
744     }
745 }
746
747 sub DebianNew {
748     my $idx   = "debian/Packages-woody.idx";
749     my $error = 0;
750     my %pkg;
751     my @new;
752
753     $error++ unless ( -e $idx);
754     $error++ unless ( -e "$idx-old");
755
756     if ($error) {
757         $error = "no woody/woody-old index file found.";
758         &ERROR("Debian: $error");
759         &msg($who, $error);
760         return;
761     }
762
763     open(IDX1, $idx);
764     open(IDX2, "$idx-old");
765
766     while (<IDX2>) {
767         chop;
768         next if (/^\*/);
769
770         $pkg{$_} = 1;
771     }
772     close IDX2;
773
774     open(IDX1,$idx);
775     while (<IDX1>) {
776         chop;
777         next if (/^\*/);
778         next if (exists $pkg{$_});
779
780         push(@new);
781     }
782     close IDX1;
783
784     &::performStrictReply( &::formListReply(0, "New debian packages:", @new) );
785 }
786
787 sub do_verstats {
788     my ($chan)  = @_;
789
790     if (!defined $chan) {
791         &help("verstats");
792         return;
793     }
794
795     if (!&validChan($chan)) {
796         &msg($who, "chan $chan is invalid.");
797         return;
798     }
799
800     if (scalar @vernick > scalar(keys %{ $channels{lc $chan}{''} })/4) {
801         &msg($who, "verstats already in progress for someone else.");
802         return;
803     }
804
805     &msg($who, "Sending CTCP VERSION to #$chan...");
806     $conn->ctcp("VERSION", $chan);
807     $cache{verstats}{chan}      = $chan;
808     $cache{verstats}{who}       = $who;
809     $cache{verstats}{msgType}   = $msgType;
810
811     $conn->schedule(30, sub {
812         my $c           = lc $cache{verstats}{chan};
813         @vernicktodo    = ();
814
815         foreach (keys %{ $channels{$c}{''} } ) {
816             next if (grep /^\Q$_\E$/i, @vernick);
817             push(@vernicktodo, $_);
818         }
819
820         &verstats_flush();
821     } );
822
823     $conn->schedule(60, sub {
824         my $vtotal      = 0;
825         my $c           = lc $cache{verstats}{chan};
826         my $total       = keys %{ $channels{$c}{''} };
827         $chan           = $c;
828         $who            = $cache{verstats}{who};
829         $msgType        = $cache{verstats}{msgType};
830         delete $cache{verstats};        # sufficient?
831
832         foreach (keys %ver) {
833             $vtotal     += scalar keys %{ $ver{$_} };
834         }
835
836         my %sorted;
837         my $unknown     = $total - $vtotal;
838         my $perc        = sprintf("%.1f", $unknown * 100 / $total);
839         $perc           =~ s/.0$//;
840         $sorted{$perc}{"unknown/cloak"} = "$unknown ($perc%)" if ($unknown);
841
842         foreach (keys %ver) {
843             my $count   = scalar keys %{ $ver{$_} };
844             $perc       = sprintf("%.01f", $count * 100 / $total);
845             $perc       =~ s/.0$//;     # lame compression.
846
847             $sorted{$perc}{$_} = "$count ($perc%)";
848         }
849
850         ### can be compressed to a map?
851         my @list;
852         foreach ( sort { $b <=> $a } keys %sorted ) {
853             my $perc = $_;
854             foreach (sort keys %{ $sorted{$perc} }) {
855                 push(@list, "$_ - $sorted{$perc}{$_}");
856             }
857         }
858
859         &pSReply( &formListReply(0, "IRC Client versions for $c ", @list) );
860
861         # clean up not-needed data structures.
862         undef %ver;
863         undef @vernick;
864     } );
865
866     return;
867 }
868
869 sub verstats_flush {
870     for (1..5) {
871         last unless (scalar @vernicktodo);
872
873         my $n = shift(@vernicktodo);
874         $conn->ctcp("VERSION", $n);
875     }
876
877     return unless (scalar @vernicktodo);
878
879     $conn->schedule(3, \&verstats_flush() );
880 }
881
882 sub textstats_main {
883     my($arg) = @_;
884
885     # even more uglier with channel/time arguments.
886     my $c       = $chan;
887 #    my $c      = $chan || "PRIVATE";
888     my $where   = "channel=".&dbQuote($c) if (defined $c);
889     &DEBUG("not using chan arg") if (!defined $c);
890     my $sum = (&dbRawReturn("SELECT SUM(counter) FROM stats"
891                 ." WHERE ".$where ))[0];
892
893     if (!defined $arg or $arg =~ /^\s*$/) {
894         # this is way fucking ugly.
895         &DEBUG("_stats: !arg");
896
897         my %hash = &dbGetCol("stats", "nick,counter",
898                 $where." ORDER BY counter DESC LIMIT 3", 1);
899         my $i;
900         my @top;
901
902         # unfortunately we have to sort it again!
903         # todo: make dbGetCol return hash and array? too much effort.
904         my $tp = 0;
905         foreach $i (sort { $b <=> $a } keys %hash) {
906             foreach (keys %{ $hash{$i} }) {
907                 my $p   = sprintf("%.01f", 100*$i/$sum);
908                 $tp     += $p;
909                 push(@top, "\002$_\002 -- $i ($p%)");
910             }
911         }
912
913         my $topstr = "";
914         &DEBUG("*stats: tp => $tp");
915         if (scalar @top) {
916             $topstr = ".  Top ".scalar(@top).": ".join(', ', @top);
917         }
918
919         if (defined $sum) {
920             &pSReply("total count of \037$type\037 on \002$c\002: $sum$topstr");
921         } else {
922             &pSReply("zero counter for \037$type\037.");
923         }
924     } else {
925         my %hash = &dbGetCol("stats", "type,counter",
926                 "$where AND nick=".&dbQuote($arg) );
927
928         foreach (keys %hash) {
929             &DEBUG("_stats: hash{$_} => $hash{$_}");
930             # ranking.
931             my @array = &dbGet("stats", "nick",
932                 $where." ORDER BY counter", 1);
933             my $good = 0;
934             my $i = 0;
935             for($i=0; $i<scalar @array; $i++) {
936                 next unless ($array[0] =~ /^\Q$who\E$/);
937                 $good++;
938                 last;
939             }
940             $i++;
941
942             my $total = scalar(@array);
943             &DEBUG("   i => $i, good => $good, total => $total");
944         }
945
946         return;
947
948         if (!defined $x) {      # !defined.
949             &pSReply("$arg has not said $type yet.");
950             return;
951         }
952
953         my $xtra = "";
954         if ($total and $good) {
955             my $pct = sprintf("%.01f", 100*(1+$total-$i)/$total);
956             $xtra = ", ranked $i\002/\002$total (percentile: \002$pct\002 %)";
957         }
958
959         my $pct1 = sprintf("%.01f", 100*$x/$sum);
960         &pSReply("\002$arg\002 has said \037$type\037 \002$x\002 times (\002$pct1\002 %)$xtra");
961     }
962 }
963
964 sub nullski { my ($arg) = @_; return unless (defined $arg);
965         foreach (`$arg`) { &msg($who,$_); } }
966
967 1;