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