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