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