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