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