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