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