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