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