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