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