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