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