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