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