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