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