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