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