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