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