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