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