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