]> git.donarmstrong.com Git - infobot.git/blob - src/CommandStubs.pl
el too
[infobot.git] / src / CommandStubs.pl
1 #
2 # User Command Extension Stubs
3 # WARN: this file does not reload on HUP.
4 #
5
6 # TODO:
7 # use strict;
8
9 use vars qw($who $msgType $conn $chan $message $ident $talkchannel
10         $bot_version $babel_lang_regex $bot_data_dir);
11 use vars qw(@vernick @vernicktodo);
12 use vars qw(%channels %cache %mask %userstats %myModules %cmdstats
13         %hooks_extra %lang %ver);
14 # FIX THE FOLLOWING:
15 use vars qw($total $x $type $i $good);
16
17 $babel_lang_regex = "de|ge|gr|el|sp|es|en|fr|it|ja|jp|ko|kr|nl|po|pt|ru|zh|zt";
18 $w3search_regex   = "google";
19
20 ### COMMAND HOOK IMPLEMENTATION.
21 # addCmdHook("SECTION", 'TEXT_HOOK',
22 #       (CODEREF        => 'Blah',
23 #       Forker          => 1,
24 #       CheckModule     => 1,                   # ???
25 #       Module          => 'blah.pl'            # preload module.
26 #       Identifier      => 'config_label',      # change to Config?
27 #       Help            => 'help_label',
28 #       Cmdstats        => 'text_label',)
29 #}
30 ###
31
32 sub addCmdHook {
33     my ($hashname, $ident, %hash) = @_;
34
35     if (exists ${"hooks_$hashname"}{$ident}) {
36 ###     &WARN("aCH: cmd hooks \%$hashname{$ident} already exists.");
37         return;
38     }
39
40     &VERB("aCH: added $ident",2);       # use $hash{'Identifier'}?
41     ### hrm... prevent warnings?
42     ${"hooks_$hashname"}{$ident} = \%hash;
43 }
44
45 # RUN IF ADDRESSED.
46 sub parseCmdHook {
47     my ($hashname, $line) = @_;
48     $line =~ s/^\s+|\s+$//g;    # again.
49     $line =~ /^(\S+)(\s+(.*))?$/;
50     my $cmd     = $1;   # command name is whitespaceless.
51     my $flatarg = $3;
52     my @args    = split(/\s+/, $flatarg || '');
53     my $done    = 0;
54
55     &shmFlush();
56
57     if (!defined %{"hooks_$hashname"}) {
58         &WARN("cmd hooks \%$hashname does not exist.");
59         return 0;
60     }
61
62     if (!defined $cmd) {
63         &WARN("cstubs: cmd == NULL.");
64         return 0;
65     }
66
67     foreach (keys %{"hooks_$hashname"}) {
68         # rename to something else! like $id or $label?
69         my $ident = $_;
70
71         next unless ($cmd =~ /^$ident$/i);
72
73         if ($done) {
74             &WARN("pCH: Multiple hook match: $ident");
75             next;
76         }
77
78         &status("hooks($hashname): $cmd matched '$ident' '$flatarg'");
79         my %hash = %{ ${"hooks_$hashname"}{$ident} };
80
81         if (!scalar keys %hash) {
82             &WARN("CmdHook: hash is NULL?");
83             return 1;
84         }
85
86         if ($hash{NoArgs} and $flatarg) {
87             &DEBUG("cmd $ident does not take args ('$flatarg'); skipping.");
88             next;
89         }
90
91         if (!exists $hash{CODEREF}) {
92             &ERROR("CODEREF undefined for $cmd or $ident.");
93             return 1;
94         }
95
96         ### DEBUG.
97         foreach (keys %hash) {
98             &VERB(" $cmd->$_ => '$hash{$_}'.",2);
99         }
100
101         ### HELP.
102         if (exists $hash{'Help'} and !scalar(@args)) {
103             &help( $hash{'Help'} );
104             return 1;
105         }
106
107         ### IDENTIFIER.
108         if (exists $hash{'Identifier'}) {
109             return 1 unless (&hasParam($hash{'Identifier'}));
110         }
111
112         ### USER FLAGS.
113         if (exists $hash{'UserFlag'}) {
114             return 1 unless (&hasFlag($hash{'UserFlag'}));
115         }
116
117         ### FORKER,IDENTIFIER,CODEREF.
118         if (exists $hash{'Forker'}) {
119             $hash{'Identifier'} .= "-" if ($hash{'Forker'} eq "NULL");
120
121             if (exists $hash{'ArrayArgs'}) {
122                 &Forker($hash{'Identifier'}, sub { \&{ $hash{'CODEREF'} }(@args) } );
123             } else {
124                 &Forker($hash{'Identifier'}, sub { \&{ $hash{'CODEREF'} }($flatarg) } );
125             }
126
127         } else {
128             if (exists $hash{'Module'}) {
129                 &loadMyModule($myModules{ $hash{'Module'} });
130             }
131
132             # check if CODEREF exists.
133             if (!defined &{ $hash{'CODEREF'} }) {
134                 &WARN("coderef $hash{'CODEREF'} does not exist.");
135                 if (defined $who) {
136                     &msg($who, "coderef does not exist for $ident.");
137                 }
138
139                 return 1;
140             }
141
142             if (exists $hash{'ArrayArgs'}) {
143                 &{ $hash{'CODEREF'} }(@args);
144             } else {
145                 &{ $hash{'CODEREF'} }($flatarg);
146             }
147         }
148
149         ### CMDSTATS.
150         if (exists $hash{'Cmdstats'}) {
151             $cmdstats{ $hash{'Cmdstats'} }++;
152         }
153
154         &VERB("hooks: End of command.",2);
155
156         $done = 1;
157     }
158
159     return 1 if ($done);
160     return 0;
161 }
162
163 ###
164 ### START ADDING HOOKS.
165 ###
166 &addCmdHook("extra", 'd?bugs', ('CODEREF' => 'DBugs::Parse',
167         'Forker' => 1, 'Identifier' => 'debianExtra',
168         'Cmdstats' => 'Debian Bugs') );
169 &addCmdHook("extra", 'dauthor', ('CODEREF' => 'Debian::searchAuthor',
170         'Forker' => 1, 'Identifier' => 'debian',
171         'Cmdstats' => 'Debian Author Search', 'Help' => "dauthor" ) );
172 &addCmdHook("extra", '(d|search)desc', ('CODEREF' => 'Debian::searchDescFE',
173         'Forker' => 1, 'Identifier' => 'debian',
174         'Cmdstats' => 'Debian Desc Search', 'Help' => "ddesc" ) );
175 &addCmdHook("extra", 'dnew', ('CODEREF' => 'DebianNew',
176         'Identifier' => 'debian' ) );
177 &addCmdHook("extra", 'dincoming', ('CODEREF' => 'Debian::generateIncoming',
178         'Forker' => 1, 'Identifier' => 'debian' ) );
179 &addCmdHook("extra", 'dstats', ('CODEREF' => 'Debian::infoStats',
180         'Forker' => 1, 'Identifier' => 'debian',
181         'Cmdstats' => 'Debian Statistics' ) );
182 &addCmdHook("extra", 'd?contents', ('CODEREF' => 'Debian::searchContents',
183         'Forker' => 1, 'Identifier' => 'debian',
184         'Cmdstats' => 'Debian Contents Search', 'Help' => "contents" ) );
185 &addCmdHook("extra", 'd?find', ('CODEREF' => 'Debian::DebianFind',
186         'Forker' => 1, 'Identifier' => 'debian',
187         'Cmdstats' => 'Debian Search', 'Help' => "find" ) );
188 #&addCmdHook("extra", 'insult', ('CODEREF' => 'Insult::Insult',
189 #       'Forker' => 1, 'Identifier' => 'insult', 'Help' => "insult" ) );
190 &addCmdHook("extra", 'kernel', ('CODEREF' => 'Kernel::Kernel',
191         'Forker' => 1, 'Identifier' => 'kernel',
192         'Cmdstats' => 'Kernel', 'NoArgs' => 1) );
193 &addCmdHook("extra", 'listauth', ('CODEREF' => 'CmdListAuth',
194         'Identifier' => 'search', Module => 'factoids',
195         'Help' => 'listauth') );
196 &addCmdHook("extra", 'quote', ('CODEREF' => 'Quote::Quote',
197         'Forker' => 1, 'Identifier' => 'quote',
198         'Help' => 'quote', 'Cmdstats' => 'Quote') );
199 &addCmdHook("extra", 'countdown', ('CODEREF' => 'Countdown',
200         'Module' => 'countdown', 'Identifier' => 'countdown',
201         'Cmdstats' => 'Countdown') );
202 &addCmdHook("extra", 'lart', ('CODEREF' => 'lart',
203         'Identifier' => 'lart', 'Help' => 'lart') );
204 &addCmdHook("extra", 'convert', ('CODEREF' => 'convert',
205         'Forker' => 1, 'Identifier' => 'units',
206         'Help' => 'convert') );
207 &addCmdHook("extra", '(cookie|random)', ('CODEREF' => 'cookie',
208         'Forker' => 1, 'Identifier' => 'factoids') );
209 &addCmdHook("extra", 'u(ser)?info', ('CODEREF' => 'userinfo',
210         'Identifier' => 'userinfo', 'Help' => 'userinfo',
211         'Module' => 'userinfo') );
212 &addCmdHook("extra", 'rootWarn', ('CODEREF' => 'CmdrootWarn',
213         'Identifier' => 'rootWarn', 'Module' => 'rootwarn') );
214 &addCmdHook("extra", 'seen', ('CODEREF' => 'seen', 'Identifier' =>
215         'seen') );
216 &addCmdHook("extra", 'dict', ('CODEREF' => 'Dict::Dict',
217         'Identifier' => 'dict', 'Help' => 'dict',
218         'Forker' => 1, 'Cmdstats' => 'Dict') );
219 &addCmdHook("extra", 'slashdot', ('CODEREF' => 'Slashdot::Slashdot',
220         'Identifier' => 'slashdot', 'Forker' => 1,
221         'Cmdstats' => 'Slashdot') );
222 &addCmdHook("extra", 'plug', ('CODEREF' => 'Plug::Plug',
223         'Identifier' => 'plug', 'Forker' => 1,
224         'Cmdstats' => 'Plug') );
225 &addCmdHook("extra", 'uptime', ('CODEREF' => 'uptime', 'Identifier' => 'uptime',
226         'Cmdstats' => 'Uptime') );
227 &addCmdHook("extra", 'nullski', ('CODEREF' => 'nullski', ) );
228 &addCmdHook("extra", 'verstats', ('CODEREF' => 'do_verstats' ) );
229 &addCmdHook("extra", 'weather', ('CODEREF' => 'Weather::Weather',
230         'Identifier' => 'weather', 'Help' => 'weather',
231         'Cmdstats' => 'weather', 'Forker' => 1) );
232 &addCmdHook("extra", 'bzflist', ('CODEREF' => 'BZFlag::list',
233         'Identifier' => 'bzflag', 'Cmdstats' => 'BZFlag',
234         'Forker' => 1) );
235 &addCmdHook("extra", 'bzflist17', ('CODEREF' => 'BZFlag::list17',
236         'Identifier' => 'bzflag', 'Cmdstats' => 'BZFlag',
237         'Forker' => 1) );
238 &addCmdHook("extra", 'bzfquery', ('CODEREF' => 'BZFlag::query',
239         'Identifier' => 'bzflag', 'Cmdstats' => 'BZFlag',
240         'Forker' => 1, 'Help' => 'bzflag') );
241 &addCmdHook("extra", 'zfi', ('CODEREF' => 'zfi::query',
242         'Identifier' => 'zfi', 'Cmdstats' => 'zfi',
243         'Forker' => 1) );
244 &addCmdHook("extra", '(zippy|yow)', ('CODEREF' => 'zippy::get',
245         'Identifier' => 'zippy', 'Cmdstats' => 'zippy',
246         'Forker' => 1) );
247 &addCmdHook("extra", 'zsi', ('CODEREF' => 'zsi::query',
248         'Identifier' => 'zsi', 'Cmdstats' => 'zsi',
249         'Forker' => 1) );
250 &addCmdHook("extra", '(ex)?change', ('CODEREF' => 'Exchange::query',
251         'Identifier' => 'exchange', 'Cmdstats' => 'exchange',
252         'Forker' => 1) );
253 &addCmdHook("extra", '(botmail|message)', ('CODEREF' => 'botmail::parse',
254         'Identifier' => 'botmail', 'Cmdstats' => 'botmail') );
255 &addCmdHook("extra", 'httpdtype', ('CODEREF' => 'HTTPDtype::HTTPDtype',
256         'Identifier' => 'httpdtype', 'Cmdstats' => 'httpdtype',
257         'Forker' => 1) );
258 &addCmdHook("extra", 'rss', ('CODEREF' => 'Rss::Rss',
259         'Identifier' => 'rss', 'Cmdstats' => 'rss',
260         'Forker' => 1, 'Help' => 'rss') );
261 ###
262 ### END OF ADDING HOOKS.
263 ###
264 &status("CMD: loaded ".scalar(keys %hooks_extra)." EXTRA command hooks.");
265
266 sub Modules {
267     if (!defined $message) {
268         &WARN("Modules: message is undefined. should never happen.");
269         return;
270     }
271
272     # babel bot: Jonathan Feinberg++
273     if ($message =~ m{
274                 ^\s*
275                 (?:babel(?:fish)?|x|xlate|translate)
276                 \s+
277                 ($babel_lang_regex)\w*  # from language?
278                 \s+
279                 ($babel_lang_regex)\w*  # to language?
280                 \s*
281                 (.+)                    # The phrase to be translated
282     }xoi) {
283         return unless (&hasParam("babelfish"));
284
285         &Forker("babelfish", sub { &babel::babelfish(lc $1, lc $2, $3); } );
286
287         $cmdstats{'BabelFish'}++;
288         return;
289     }
290
291     my $debiancmd        = 'conflicts?|depends?|desc|file|(?:d)?info|provides?';
292     $debiancmd          .= '|recommends?|suggests?|maint|maintainer';
293
294     if ($message =~ /^($debiancmd)(\s+(.*))?$/i) {
295         return unless (&hasParam("debian"));
296         my $package = lc $3;
297
298         if (defined $package) {
299             &Forker("debian", sub { &Debian::infoPackages($1, $package); } );
300         } else {
301             &help($1);
302         }
303
304         return;
305     }
306
307     # google searching. Simon++
308     if ($message =~ /^(?:search\s+)?($w3search_regex)\s+(?:for\s+)?['"]?(.*?)["']?\s*\?*$/i) {
309         return unless (&hasParam("wwwsearch"));
310
311         &Forker("wwwsearch", sub { &W3Search::W3Search($1,$2); } );
312
313         $cmdstats{'WWWSearch'}++;
314         return;
315     }
316
317     # text counters. (eg: hehstats)
318     my $itc;
319     $itc = &getChanConf("ircTextCounters");
320     $itc = &findChanConf("ircTextCounters") unless ($itc);
321     return if ($itc && &do_text_counters($itc) == 1);
322     # end of text counters.
323
324     # list{keys|values}. xk++. Idea taken from #linuxwarez@EFNET
325     if ($message =~ /^list(\S+)(\s+(.*))?$/i) {
326         return unless (&hasParam("search"));
327
328         my $thiscmd     = lc $1;
329         my $args        = $3 || "";
330
331         $thiscmd        =~ s/^vals$/values/;
332         return if ($thiscmd ne "keys" && $thiscmd ne "values");
333
334         # Usage:
335         if (!defined $args or $args =~ /^\s*$/) {
336             &help("list". $thiscmd);
337             return;
338         }
339
340         # suggested by asuffield and \broken.
341         if ($args =~ /^["']/ and $args =~ /["']$/) {
342             &DEBUG("list*: removed quotes.");
343             $args       =~ s/^["']|["']$//g;
344         }
345
346         if (length $args < 2 && &IsFlag("o") ne "o") {
347             &msg($who, "search string is too short.");
348             return;
349         }
350
351         &Forker("search", sub { &Search::Search($thiscmd, $args); } );
352
353         $cmdstats{'Factoid Search'}++;
354         return;
355     }
356
357     # Nickometer. Adam Spiers++
358     if ($message =~ /^(?:lame|nick)ometer(?: for)? (\S+)/i) {
359         return unless (&hasParam("nickometer"));
360
361         my $term = (lc $1 eq 'me') ? $who : $1;
362
363         &loadMyModule($myModules{'nickometer'});
364
365         if ($term =~ /^$mask{chan}$/) {
366             &status("Doing nickometer for chan $term.");
367
368             if (!&validChan($term)) {
369                 &msg($who, "error: channel is invalid.");
370                 return;
371             }
372
373             # step 1.
374             my %nickometer;
375             foreach (keys %{ $channels{lc $term}{''} }) {
376                 my $str   = $_;
377                 if (!defined $str) {
378                     &WARN("nickometer: nick in chan $term undefined?");
379                     next;
380                 }
381
382                 my $value = &nickometer($str);
383                 $nickometer{$value}{$str} = 1;
384             }
385
386             # step 2.
387             ### TODO: compact with map?
388             my @list;
389             foreach (sort {$b <=> $a} keys %nickometer) {
390                 my $str = join(", ", sort keys %{ $nickometer{$_} });
391                 push(@list, "$str ($_%)");
392             }
393
394             &pSReply( &formListReply(0, "Nickometer list for $term ", @list) );
395             &DEBUG("test.");
396
397             return;
398         }
399
400         my $percentage = &nickometer($term);
401
402         if ($percentage =~ /NaN/) {
403             $percentage = "off the scale";
404         } else {
405             $percentage = sprintf("%0.4f", $percentage);
406             $percentage =~ s/(\.\d+)0+$/$1/;
407             $percentage .= '%';
408         }
409
410         if ($msgType eq 'public') {
411             &say("'$term' is $percentage lame, $who");
412         } else {
413             &msg($who, "the 'lame nick-o-meter' reading for $term is $percentage, $who");
414         }
415
416         return;
417     }
418
419     # Topic management. xk++
420     # may want to add a userflags for topic. -xk
421     if ($message =~ /^topic(\s+(.*))?$/i) {
422         return unless (&hasParam("topic"));
423
424         my $chan        = $talkchannel;
425         my @args        = split / /, $2 || "";
426
427         if (!scalar @args) {
428             &msg($who,"Try 'help topic'");
429             return;
430         }
431
432         $chan           = lc(shift @args) if ($msgType eq 'private');
433         my $thiscmd     = shift @args;
434
435         # topic over public:
436         if ($msgType eq 'public' && $thiscmd =~ /^#/) {
437             &msg($who, "error: channel argument is not required.");
438             &msg($who, "\002Usage\002: topic <CMD>");
439             return;
440         }
441
442         # topic over private:
443         if ($msgType eq 'private' && $chan !~ /^#/) {
444             &msg($who, "error: channel argument is required.");
445             &msg($who, "\002Usage\002: topic #channel <CMD>");
446             return;
447         }
448
449         if (&validChan($chan) == 0) {
450             &msg($who,"error: invalid channel \002$chan\002");
451             return;
452         }
453
454         # for semi-outsiders.
455         if (!&IsNickInChan($who,$chan)) {
456             &msg($who, "Failed. You ($who) are not in $chan, hey?");
457             return;
458         }
459
460         # now lets do it.
461         &loadMyModule($myModules{'topic'});
462         &Topic($chan, $thiscmd, join(' ', @args));
463         $cmdstats{'Topic'}++;
464         return;
465     }
466
467     # wingate.
468     if ($message =~ /^wingate$/i) {
469         return unless (&hasParam("wingate"));
470
471         my $reply = "Wingate statistics: scanned \002"
472                         .scalar(keys %wingate)."\002 hosts";
473         my $queue = scalar(keys %wingateToDo);
474         if ($queue) {
475             $reply .= ".  I have \002$queue\002 hosts in the queue";
476             $reply .= ".  Started the scan ".&Time2String(time() - $wingaterun)." ago";
477         }
478
479         &pSReply("$reply.");
480
481         return;
482     }
483
484     # do nothing and let the other routines have a go
485     return "CONTINUE";
486 }
487
488 # Uptime. xk++
489 sub uptime {
490     my $count = 1;
491     &msg($who, "- Uptime for $ident -");
492     &msg($who, "Now: ". &Time2String(&uptimeNow()) ." running $bot_version");
493
494     foreach (&uptimeGetInfo()) {
495         /^(\d+)\.\d+ (.*)/;
496         my $time = &Time2String($1);
497         my $info = $2;
498
499         &msg($who, "$count: $time $2");
500         $count++;
501     }
502 }
503
504 # seen.
505 sub seen {
506     my($person) = lc shift;
507     $person =~ s/\?*$//;
508
509     if (!defined $person or $person =~ /^$/) {
510         &help("seen");
511
512         my $i = &countKeys("seen");
513         &msg($who,"there ". &fixPlural("is",$i) ." \002$i\002 ".
514                 "seen ". &fixPlural("entry",$i) ." that I know of.");
515
516         return;
517     }
518
519     my @seen;
520
521     &seenFlush();       # very evil hack. oh well, better safe than sorry.
522
523     # TODO: convert to &sqlSelectRowHash();
524     my $select = "nick,time,channel,host,message";
525     if ($person eq "random") {
526         @seen = &randKey("seen", $select);
527     } else {
528         @seen = &sqlSelect("seen", $select, { nick => $person } );
529     }
530
531     if (scalar @seen < 2) {
532         foreach (@seen) {
533             &DEBUG("seen: _ => '$_'.");
534         }
535         &performReply("i haven't seen '$person'");
536         return;
537     }
538
539     # valid seen.
540     my $reply;
541     ### TODO: multi channel support. may require &IsNick() to return
542     ### all channels or something.
543
544     my @chans = &getNickInChans($seen[0]);
545     if (scalar @chans) {
546         $reply = "$seen[0] is currently on";
547
548         foreach (@chans) {
549             $reply .= " ".$_;
550             next unless (exists $userstats{lc $seen[0]}{'Join'});
551             $reply .= " (".&Time2String(time() - $userstats{lc $seen[0]}{'Join'}).")";
552         }
553
554         if (&IsChanConf("seenStats") > 0) {
555             my $i;
556             $i = $userstats{lc $seen[0]}{'Count'};
557             $reply .= ".  Has said a total of \002$i\002 messages" if (defined $i);
558             $i = $userstats{lc $seen[0]}{'Time'};
559             $reply .= ".  Is idling for ".&Time2String(time() - $i) if (defined $i);
560         }
561     } else {
562         my $howlong = &Time2String(time() - $seen[1]);
563         $reply = "$seen[0] <$seen[3]> was last seen on IRC ".
564                  "in channel $seen[2], $howlong ago, ".
565                  "saying\002:\002 '$seen[4]'.";
566     }
567
568     &pSReply($reply);
569     return;
570 }
571
572 # User Information Services. requested by Flugh.
573 sub userinfo {
574     my ($arg) = join(' ',@_);
575
576     if ($arg =~ /^set(\s+(.*))?$/i) {
577         $arg = $2;
578         if (!defined $arg) {
579             &help("userinfo set");
580             return;
581         }
582
583         &UserInfoSet(split /\s+/, $arg, 2);
584     } elsif ($arg =~ /^unset(\s+(.*))?$/i) {
585         $arg = $2;
586         if (!defined $arg) {
587             &help("userinfo unset");
588             return;
589         }
590
591         &UserInfoSet($arg, "");
592     } else {
593         &UserInfoGet($arg);
594     }
595 }
596
597 # cookie (random). xk++
598 sub cookie {
599     my ($arg) = @_;
600
601     # lets find that secret cookie.
602     my $target          = ($msgType ne 'public') ? $who : $talkchannel;
603     my $cookiemsg       = &getRandom(keys %{ $lang{'cookie'} });
604     my ($key,$value);
605
606     ### WILL CHEW TONS OF MEM.
607     ### TODO: convert this to a Forker function!
608     if ($arg) {
609         my @list = &searchTable("factoids", "factoid_key", "factoid_value", $arg);
610         $key    = &getRandom(@list);
611         $value  = &getFactInfo($key, "factoid_value");
612     } else {
613         ($key,$value) = &randKey("factoids","factoid_key,factoid_value");
614     }
615
616     for ($cookiemsg) {
617         s/##KEY/\002$key\002/;
618         s/##VALUE/$value/;
619         s/##WHO/$who/;
620         s/\$who/$who/;  # cheap fix.
621         s/(\S+)?\s*<\S+>/$1 /;
622         s/\s+/ /g;
623     }
624
625     if ($cookiemsg =~ s/^ACTION //i) {
626         &action($target, $cookiemsg);
627     } else {
628         &msg($target, $cookiemsg);
629     }
630 }
631
632 sub convert {
633     my $arg = join(' ',@_);
634     my ($from,$to) = ('','');
635
636     ($from,$to) = ($1,$2) if ($arg =~ /^(.*?) to (.*)$/i);
637     ($from,$to) = ($2,$1) if ($arg =~ /^(.*?) from (.*)$/i);
638
639     if (!$to or !$from) {
640         &msg($who, "Invalid format!");
641         &help("convert");
642         return;
643     }
644
645     &Units::convertUnits($from, $to);
646
647     return;
648 }
649
650 sub lart {
651     my ($target) = &fixString($_[0]);
652     my $extra   = 0;
653     my $chan    = $talkchannel;
654
655     if ($msgType eq 'private') {
656         if ($target =~ /^($mask{chan})\s+(.*)$/) {
657             $chan       = $1;
658             $target     = $2;
659             $extra      = 1;
660         } else {
661             &msg($who, "error: invalid format or missing arguments.");
662             &help("lart");
663             return;
664         }
665     }
666
667     my $line = &getRandomLineFromFile($bot_data_dir. "/blootbot.lart");
668     if (defined $line) {
669         if ($target =~ /^(me|you|itself|\Q$ident\E)$/i) {
670             $line =~ s/WHO/$who/g;
671         } else {
672             $line =~ s/WHO/$target/g;
673         }
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;