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