2 # User Command Extension Stubs
3 # WARN: this file does not reload on HUP.
9 use vars qw($who $msgType $conn $chan $message $ident $talkchannel
10 $bot_version $babel_lang_regex $bot_data_dir);
11 use vars qw(@vernick @vernicktodo);
12 use vars qw(%channels %cache %mask %userstats %myModules %cmdstats
13 %hooks_extra %lang %ver);
15 use vars qw($total $x $type $i $good);
17 $babel_lang_regex = "fr|sp|es|po|pt|it|ge|de|gr|en|zh|ja|jp|ko|kr|nl|ru";
18 $w3search_regex = "google";
20 ### COMMAND HOOK IMPLEMENTATION.
21 # addCmdHook("SECTION", 'TEXT_HOOK',
24 # CheckModule => 1, # ???
25 # Module => 'blah.pl' # preload module.
26 # Identifier => 'config_label', # change to Config?
27 # Help => 'help_label',
28 # Cmdstats => 'text_label',)
33 my ($hashname, $ident, %hash) = @_;
35 if (exists ${"hooks_$hashname"}{$ident}) {
36 ### &WARN("aCH: cmd hooks \%$hashname{$ident} already exists.");
40 &VERB("aCH: added $ident",2); # use $hash{'Identifier'}?
41 ### hrm... prevent warnings?
42 ${"hooks_$hashname"}{$ident} = \%hash;
47 my ($hashname, $line) = @_;
48 $line =~ s/^\s+|\s+$//g; # again.
49 $line =~ /^(\S+)(\s+(.*))?$/;
50 my $cmd = $1; # command name is whitespaceless.
52 my @args = split(/\s+/, $flatarg || '');
57 if (!defined %{"hooks_$hashname"}) {
58 &WARN("cmd hooks \%$hashname does not exist.");
63 &WARN("cstubs: cmd == NULL.");
67 foreach (keys %{"hooks_$hashname"}) {
68 # rename to something else! like $id or $label?
71 next unless ($cmd =~ /^$ident$/i);
74 &WARN("pCH: Multiple hook match: $ident");
78 &status("hooks($hashname): $cmd matched '$ident' '$flatarg'");
79 my %hash = %{ ${"hooks_$hashname"}{$ident} };
81 if (!scalar keys %hash) {
82 &WARN("CmdHook: hash is NULL?");
86 if ($hash{NoArgs} and $flatarg) {
87 &DEBUG("cmd $ident does not take args ('$flatarg'); skipping.");
91 if (!exists $hash{CODEREF}) {
92 &ERROR("CODEREF undefined for $cmd or $ident.");
97 foreach (keys %hash) {
98 &VERB(" $cmd->$_ => '$hash{$_}'.",2);
102 if (exists $hash{'Help'} and !scalar(@args)) {
103 &help( $hash{'Help'} );
108 if (exists $hash{'Identifier'}) {
109 return 1 unless (&hasParam($hash{'Identifier'}));
113 if (exists $hash{'UserFlag'}) {
114 return 1 unless (&hasFlag($hash{'UserFlag'}));
117 ### FORKER,IDENTIFIER,CODEREF.
118 if (exists $hash{'Forker'}) {
119 $hash{'Identifier'} .= "-" if ($hash{'Forker'} eq "NULL");
121 if (exists $hash{'ArrayArgs'}) {
122 &Forker($hash{'Identifier'}, sub { \&{ $hash{'CODEREF'} }(@args) } );
124 &Forker($hash{'Identifier'}, sub { \&{ $hash{'CODEREF'} }($flatarg) } );
128 if (exists $hash{'Module'}) {
129 &loadMyModule($myModules{ $hash{'Module'} });
132 # check if CODEREF exists.
133 if (!defined &{ $hash{'CODEREF'} }) {
134 &WARN("coderef $hash{'CODEREF'} does not exist.");
136 &msg($who, "coderef does not exist for $ident.");
142 if (exists $hash{'ArrayArgs'}) {
143 &{ $hash{'CODEREF'} }(@args);
145 &{ $hash{'CODEREF'} }($flatarg);
150 if (exists $hash{'Cmdstats'}) {
151 $cmdstats{ $hash{'Cmdstats'} }++;
154 &VERB("hooks: End of command.",2);
164 ### START ADDING HOOKS.
166 &addCmdHook("extra", 'd?bugs', ('CODEREF' => 'DBugs::Parse',
167 'Forker' => 1, 'Identifier' => 'debianExtra',
168 'Cmdstats' => 'Debian Bugs') );
169 &addCmdHook("extra", 'dauthor', ('CODEREF' => 'Debian::searchAuthor',
170 'Forker' => 1, 'Identifier' => 'debian',
171 'Cmdstats' => 'Debian Author Search', 'Help' => "dauthor" ) );
172 &addCmdHook("extra", '(d|search)desc', ('CODEREF' => 'Debian::searchDescFE',
173 'Forker' => 1, 'Identifier' => 'debian',
174 'Cmdstats' => 'Debian Desc Search', 'Help' => "ddesc" ) );
175 &addCmdHook("extra", 'dnew', ('CODEREF' => 'DebianNew',
176 'Identifier' => 'debian' ) );
177 &addCmdHook("extra", 'dincoming', ('CODEREF' => 'Debian::generateIncoming',
178 'Forker' => 1, 'Identifier' => 'debian' ) );
179 &addCmdHook("extra", 'dstats', ('CODEREF' => 'Debian::infoStats',
180 'Forker' => 1, 'Identifier' => 'debian',
181 'Cmdstats' => 'Debian Statistics' ) );
182 &addCmdHook("extra", 'd?contents', ('CODEREF' => 'Debian::searchContents',
183 'Forker' => 1, 'Identifier' => 'debian',
184 'Cmdstats' => 'Debian Contents Search', 'Help' => "contents" ) );
185 &addCmdHook("extra", 'd?find', ('CODEREF' => 'Debian::DebianFind',
186 'Forker' => 1, 'Identifier' => 'debian',
187 'Cmdstats' => 'Debian Search', 'Help' => "find" ) );
188 #&addCmdHook("extra", 'insult', ('CODEREF' => 'Insult::Insult',
189 # 'Forker' => 1, 'Identifier' => 'insult', 'Help' => "insult" ) );
190 &addCmdHook("extra", 'kernel', ('CODEREF' => 'Kernel::Kernel',
191 'Forker' => 1, 'Identifier' => 'kernel',
192 'Cmdstats' => 'Kernel', 'NoArgs' => 1) );
193 &addCmdHook("extra", 'listauth', ('CODEREF' => 'CmdListAuth',
194 'Identifier' => 'search', Module => 'factoids',
195 'Help' => 'listauth') );
196 &addCmdHook("extra", 'quote', ('CODEREF' => 'Quote::Quote',
197 'Forker' => 1, 'Identifier' => 'quote',
198 'Help' => 'quote', 'Cmdstats' => 'Quote') );
199 &addCmdHook("extra", 'countdown', ('CODEREF' => 'Countdown',
200 'Module' => 'countdown', 'Identifier' => 'countdown',
201 'Cmdstats' => 'Countdown') );
202 &addCmdHook("extra", 'lart', ('CODEREF' => 'lart',
203 'Identifier' => 'lart', 'Help' => 'lart') );
204 &addCmdHook("extra", 'convert', ('CODEREF' => 'convert',
205 'Forker' => 1, 'Identifier' => 'units',
206 'Help' => 'convert') );
207 &addCmdHook("extra", '(cookie|random)', ('CODEREF' => 'cookie',
208 'Forker' => 1, 'Identifier' => 'factoids') );
209 &addCmdHook("extra", 'u(ser)?info', ('CODEREF' => 'userinfo',
210 'Identifier' => 'userinfo', 'Help' => 'userinfo',
211 'Module' => 'userinfo') );
212 &addCmdHook("extra", 'rootWarn', ('CODEREF' => 'CmdrootWarn',
213 'Identifier' => 'rootWarn', 'Module' => 'rootwarn') );
214 &addCmdHook("extra", 'seen', ('CODEREF' => 'seen', 'Identifier' =>
216 &addCmdHook("extra", 'dict', ('CODEREF' => 'Dict::Dict',
217 'Identifier' => 'dict', 'Help' => 'dict',
218 'Forker' => 1, 'Cmdstats' => 'Dict') );
219 &addCmdHook("extra", 'slashdot', ('CODEREF' => 'Slashdot::Slashdot',
220 'Identifier' => 'slashdot', 'Forker' => 1,
221 'Cmdstats' => 'Slashdot') );
222 &addCmdHook("extra", 'plug', ('CODEREF' => 'Plug::Plug',
223 'Identifier' => 'plug', 'Forker' => 1,
224 'Cmdstats' => 'Plug') );
225 &addCmdHook("extra", 'uptime', ('CODEREF' => 'uptime', 'Identifier' => 'uptime',
226 'Cmdstats' => 'Uptime') );
227 &addCmdHook("extra", 'nullski', ('CODEREF' => 'nullski', ) );
228 &addCmdHook("extra", 'verstats', ('CODEREF' => 'do_verstats' ) );
229 &addCmdHook("extra", 'weather', ('CODEREF' => 'Weather::Weather',
230 'Identifier' => 'weather', 'Help' => 'weather',
231 'Cmdstats' => 'weather', 'Forker' => 1) );
232 &addCmdHook("extra", 'bzflist', ('CODEREF' => 'BZFlag::list',
233 'Identifier' => 'bzflag', 'Cmdstats' => 'BZFlag',
235 &addCmdHook("extra", 'bzflist17', ('CODEREF' => 'BZFlag::list17',
236 'Identifier' => 'bzflag', 'Cmdstats' => 'BZFlag',
238 &addCmdHook("extra", 'bzfquery', ('CODEREF' => 'BZFlag::query',
239 'Identifier' => 'bzflag', 'Cmdstats' => 'BZFlag',
240 'Forker' => 1, 'Help' => 'bzflag') );
241 &addCmdHook("extra", 'zfi', ('CODEREF' => 'zfi::query',
242 'Identifier' => 'zfi', 'Cmdstats' => 'zfi',
244 &addCmdHook("extra", '(zippy|yow)', ('CODEREF' => 'zippy::get',
245 'Identifier' => 'zippy', 'Cmdstats' => 'zippy',
247 &addCmdHook("extra", 'zsi', ('CODEREF' => 'zsi::query',
248 'Identifier' => 'zsi', 'Cmdstats' => 'zsi',
250 &addCmdHook("extra", '(ex)?change', ('CODEREF' => 'Exchange::query',
251 'Identifier' => 'exchange', 'Cmdstats' => 'exchange',
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',
258 &addCmdHook("extra", 'rss', ('CODEREF' => 'Rss::Rss',
259 'Identifier' => 'rss', 'Cmdstats' => 'rss',
260 'Forker' => 1, 'Help' => 'rss') );
262 ### END OF ADDING HOOKS.
264 &status("CMD: loaded ".scalar(keys %hooks_extra)." EXTRA command hooks.");
267 if (!defined $message) {
268 &WARN("Modules: message is undefined. should never happen.");
272 # babel bot: Jonathan Feinberg++
275 (?:babel(?:fish)?|x|xlate|translate)
277 ($babel_lang_regex)\w* # from language?
279 ($babel_lang_regex)\w* # to language?
281 (.+) # The phrase to be translated
283 return unless (&hasParam("babelfish"));
285 &Forker("babelfish", sub { &babel::babelfish(lc $1, lc $2, $3); } );
287 $cmdstats{'BabelFish'}++;
291 my $debiancmd = 'conflicts?|depends?|desc|file|(?:d)?info|provides?';
292 $debiancmd .= '|recommends?|suggests?|maint|maintainer';
294 if ($message =~ /^($debiancmd)(\s+(.*))?$/i) {
295 return unless (&hasParam("debian"));
298 if (defined $package) {
299 &Forker("debian", sub { &Debian::infoPackages($1, $package); } );
307 # google searching. Simon++
308 if ($message =~ /^(?:search\s+)?($w3search_regex)\s+(?:for\s+)?['"]?(.*?)["']?\s*\?*$/i) {
309 return unless (&hasParam("wwwsearch"));
311 &Forker("wwwsearch", sub { &W3Search::W3Search($1,$2); } );
313 $cmdstats{'WWWSearch'}++;
317 # text counters. (eg: hehstats)
319 $itc = &getChanConf("ircTextCounters");
320 $itc = &findChanConf("ircTextCounters") unless ($itc);
321 return if ($itc && &do_text_counters($itc) == 1);
322 # end of text counters.
324 # list{keys|values}. xk++. Idea taken from #linuxwarez@EFNET
325 if ($message =~ /^list(\S+)(\s+(.*))?$/i) {
326 return unless (&hasParam("search"));
331 $thiscmd =~ s/^vals$/values/;
332 return if ($thiscmd ne "keys" && $thiscmd ne "values");
335 if (!defined $args or $args =~ /^\s*$/) {
336 &help("list". $thiscmd);
340 # suggested by asuffield and \broken.
341 if ($args =~ /^["']/ and $args =~ /["']$/) {
342 &DEBUG("list*: removed quotes.");
343 $args =~ s/^["']|["']$//g;
346 if (length $args < 2 && &IsFlag("o") ne "o") {
347 &msg($who, "search string is too short.");
351 &Forker("search", sub { &Search::Search($thiscmd, $args); } );
353 $cmdstats{'Factoid Search'}++;
357 # Nickometer. Adam Spiers++
358 if ($message =~ /^(?:lame|nick)ometer(?: for)? (\S+)/i) {
359 return unless (&hasParam("nickometer"));
361 my $term = (lc $1 eq 'me') ? $who : $1;
363 &loadMyModule($myModules{'nickometer'});
365 if ($term =~ /^$mask{chan}$/) {
366 &status("Doing nickometer for chan $term.");
368 if (!&validChan($term)) {
369 &msg($who, "error: channel is invalid.");
375 foreach (keys %{ $channels{lc $term}{''} }) {
378 &WARN("nickometer: nick in chan $term undefined?");
382 my $value = &nickometer($str);
383 $nickometer{$value}{$str} = 1;
387 ### TODO: compact with map?
389 foreach (sort {$b <=> $a} keys %nickometer) {
390 my $str = join(", ", sort keys %{ $nickometer{$_} });
391 push(@list, "$str ($_%)");
394 &pSReply( &formListReply(0, "Nickometer list for $term ", @list) );
400 my $percentage = &nickometer($term);
402 if ($percentage =~ /NaN/) {
403 $percentage = "off the scale";
405 $percentage = sprintf("%0.4f", $percentage);
406 $percentage =~ s/(\.\d+)0+$/$1/;
410 if ($msgType eq 'public') {
411 &say("'$term' is $percentage lame, $who");
413 &msg($who, "the 'lame nick-o-meter' reading for $term is $percentage, $who");
419 # Topic management. xk++
420 # may want to add a userflags for topic. -xk
421 if ($message =~ /^topic(\s+(.*))?$/i) {
422 return unless (&hasParam("topic"));
424 my $chan = $talkchannel;
425 my @args = split / /, $2 || "";
428 &msg($who,"Try 'help topic'");
432 $chan = lc(shift @args) if ($msgType eq 'private');
433 my $thiscmd = shift @args;
436 if ($msgType eq 'public' && $thiscmd =~ /^#/) {
437 &msg($who, "error: channel argument is not required.");
438 &msg($who, "\002Usage\002: topic <CMD>");
442 # topic over private:
443 if ($msgType eq 'private' && $chan !~ /^#/) {
444 &msg($who, "error: channel argument is required.");
445 &msg($who, "\002Usage\002: topic #channel <CMD>");
449 if (&validChan($chan) == 0) {
450 &msg($who,"error: invalid channel \002$chan\002");
454 # for semi-outsiders.
455 if (!&IsNickInChan($who,$chan)) {
456 &msg($who, "Failed. You ($who) are not in $chan, hey?");
461 &loadMyModule($myModules{'topic'});
462 &Topic($chan, $thiscmd, join(' ', @args));
463 $cmdstats{'Topic'}++;
468 if ($message =~ /^wingate$/i) {
469 return unless (&hasParam("wingate"));
471 my $reply = "Wingate statistics: scanned \002"
472 .scalar(keys %wingate)."\002 hosts";
473 my $queue = scalar(keys %wingateToDo);
475 $reply .= ". I have \002$queue\002 hosts in the queue";
476 $reply .= ". Started the scan ".&Time2String(time() - $wingaterun)." ago";
484 # do nothing and let the other routines have a go
491 &msg($who, "- Uptime for $ident -");
492 &msg($who, "Now: ". &Time2String(&uptimeNow()) ." running $bot_version");
494 foreach (&uptimeGetInfo()) {
496 my $time = &Time2String($1);
499 &msg($who, "$count: $time $2");
506 my($person) = lc shift;
509 if (!defined $person or $person =~ /^$/) {
512 my $i = &countKeys("seen");
513 &msg($who,"there ". &fixPlural("is",$i) ." \002$i\002 ".
514 "seen ". &fixPlural("entry",$i) ." that I know of.");
521 &seenFlush(); # very evil hack. oh well, better safe than sorry.
523 # TODO: convert to &sqlSelectRowHash();
524 my $select = "nick,time,channel,host,message";
525 if ($person eq "random") {
526 @seen = &randKey("seen", $select);
528 @seen = &sqlSelect("seen", $select, { nick => $person } );
531 if (scalar @seen < 2) {
533 &DEBUG("seen: _ => '$_'.");
535 &performReply("i haven't seen '$person'");
541 ### TODO: multi channel support. may require &IsNick() to return
542 ### all channels or something.
544 my @chans = &getNickInChans($seen[0]);
546 $reply = "$seen[0] is currently on";
550 next unless (exists $userstats{lc $seen[0]}{'Join'});
551 $reply .= " (".&Time2String(time() - $userstats{lc $seen[0]}{'Join'}).")";
554 if (&IsChanConf("seenStats") > 0) {
556 $i = $userstats{lc $seen[0]}{'Count'};
557 $reply .= ". Has said a total of \002$i\002 messages" if (defined $i);
558 $i = $userstats{lc $seen[0]}{'Time'};
559 $reply .= ". Is idling for ".&Time2String(time() - $i) if (defined $i);
562 my $howlong = &Time2String(time() - $seen[1]);
563 $reply = "$seen[0] <$seen[3]> was last seen on IRC ".
564 "in channel $seen[2], $howlong ago, ".
565 "saying\002:\002 '$seen[4]'.";
572 # User Information Services. requested by Flugh.
574 my ($arg) = join(' ',@_);
576 if ($arg =~ /^set(\s+(.*))?$/i) {
579 &help("userinfo set");
583 &UserInfoSet(split /\s+/, $arg, 2);
584 } elsif ($arg =~ /^unset(\s+(.*))?$/i) {
587 &help("userinfo unset");
591 &UserInfoSet($arg, "");
597 # cookie (random). xk++
601 # lets find that secret cookie.
602 my $target = ($msgType ne 'public') ? $who : $talkchannel;
603 my $cookiemsg = &getRandom(keys %{ $lang{'cookie'} });
606 ### WILL CHEW TONS OF MEM.
607 ### TODO: convert this to a Forker function!
609 my @list = &searchTable("factoids", "factoid_key", "factoid_value", $arg);
610 $key = &getRandom(@list);
611 $value = &getFactInfo($key, "factoid_value");
613 ($key,$value) = &randKey("factoids","factoid_key,factoid_value");
617 s/##KEY/\002$key\002/;
620 s/\$who/$who/; # cheap fix.
621 s/(\S+)?\s*<\S+>/$1 /;
625 if ($cookiemsg =~ s/^ACTION //i) {
626 &action($target, $cookiemsg);
628 &msg($target, $cookiemsg);
633 my $arg = join(' ',@_);
634 my ($from,$to) = ('','');
636 ($from,$to) = ($1,$2) if ($arg =~ /^(.*?) to (.*)$/i);
637 ($from,$to) = ($2,$1) if ($arg =~ /^(.*?) from (.*)$/i);
639 if (!$to or !$from) {
640 &msg($who, "Invalid format!");
645 &Units::convertUnits($from, $to);
651 my ($target) = &fixString($_[0]);
653 my $chan = $talkchannel;
655 if ($msgType eq 'private') {
656 if ($target =~ /^($mask{chan})\s+(.*)$/) {
661 &msg($who, "error: invalid format or missing arguments.");
667 my $line = &getRandomLineFromFile($bot_data_dir. "/blootbot.lart");
669 if ($target =~ /^(me|you|itself|\Q$ident\E)$/i) {
670 $line =~ s/WHO/$who/g;
672 $line =~ s/WHO/$target/g;
674 $line .= ", courtesy of $who" if ($extra);
676 &action($chan, $line);
678 &status("lart: error reading file?");
683 my $idx = "debian/Packages-sid.idx";
688 $error++ unless ( -e $idx);
689 $error++ unless ( -e "$idx-old");
692 $error = "no sid/sid-old index file found.";
693 &ERROR("Debian: $error");
699 open(IDX2, "$idx-old");
713 next if (exists $pkg{$_});
719 &::pSReply( &::formListReply(0, "New debian packages:", @new) );
725 if (!defined $chan) {
730 if (!&validChan($chan)) {
731 &msg($who, "chan $chan is invalid.");
735 if (scalar @vernick > scalar(keys %{ $channels{lc $chan}{''} })/4) {
736 &msg($who, "verstats already in progress for someone else.");
740 &msg($who, "Sending CTCP VERSION to $chan; results in 60s.");
741 $conn->ctcp("VERSION", $chan);
742 $cache{verstats}{chan} = $chan;
743 $cache{verstats}{who} = $who;
744 $cache{verstats}{msgType} = $msgType;
746 $conn->schedule(30, sub {
747 my $c = lc $cache{verstats}{chan};
750 foreach (keys %{ $channels{$c}{''} } ) {
751 next if (grep /^\Q$_\E$/i, @vernick);
752 push(@vernicktodo, $_);
758 $conn->schedule(60, sub {
760 my $c = lc $cache{verstats}{chan};
761 my $total = keys %{ $channels{$c}{''} };
763 $who = $cache{verstats}{who};
764 $msgType = $cache{verstats}{msgType};
765 delete $cache{verstats}; # sufficient?
767 foreach (keys %ver) {
768 $vtotal += scalar keys %{ $ver{$_} };
772 my $unknown = $total - $vtotal;
773 my $perc = sprintf("%.1f", $unknown * 100 / $total);
775 $sorted{$perc}{"unknown/cloak"} = "$unknown ($perc%)" if ($unknown);
777 foreach (keys %ver) {
778 my $count = scalar keys %{ $ver{$_} };
779 $perc = sprintf("%.01f", $count * 100 / $total);
780 $perc =~ s/.0$//; # lame compression.
782 $sorted{$perc}{$_} = "$count ($perc%)";
785 ### can be compressed to a map?
787 foreach ( sort { $b <=> $a } keys %sorted ) {
789 foreach (sort keys %{ $sorted{$perc} }) {
790 push(@list, "$_ - $sorted{$perc}{$_}");
794 # hack. this is one major downside to scheduling.
796 &pSReply( &formListReply(0, "IRC Client versions for $c ", @list) );
798 # clean up not-needed data structures.
808 last unless (scalar @vernicktodo);
810 my $n = shift(@vernicktodo);
811 $conn->ctcp("VERSION", $n);
814 return unless (scalar @vernicktodo);
816 $conn->schedule(3, \&verstats_flush() );
819 sub do_text_counters {
821 $itc =~ s/([^\w\s])/\\$1/g;
822 my $z = join '|', split ' ', $itc;
824 if ($msgType eq "privmsg" and $message =~ / ($mask{chan})$/) {
825 &DEBUG("ircTC: privmsg detected; chan = $1");
829 if ($message =~ /^_stats(\s+(\S+))$/i) {
835 if ($message =~ /^($z)stats(\s+(\S+))?$/i) {
842 # even more uglier with channel/time arguments.
844 # my $c = $chan || "PRIVATE";
845 my $where = "type=".&sqlQuote($type);
848 $where .= " AND channel=".&sqlQuote($c) if (defined $c);
850 &DEBUG("not using chan arg");
853 my $sum = (&sqlRawReturn("SELECT SUM(counter) FROM stats"
854 ." WHERE ".$where ))[0];
856 if (!defined $arg or $arg =~ /^\s*$/) {
857 # this is way fucking ugly.
859 # TODO: convert $where to hash
860 my %hash = &sqlSelectColHash("stats", "nick,counter",
862 $where." ORDER BY counter DESC LIMIT 3", 1
867 # unfortunately we have to sort it again!
869 foreach $i (sort { $b <=> $a } keys %hash) {
870 foreach (keys %{ $hash{$i} }) {
871 my $p = sprintf("%.01f", 100*$i/$sum);
873 push(@top, "\002$_\002 -- $i ($p%)");
878 $topstr = ". Top ".scalar(@top).": ".join(', ', @top);
882 &pSReply("total count of \037$type\037 on \002$c\002: $sum$topstr");
884 &pSReply("zero counter for \037$type\037.");
887 # TODO: convert $where to hash and use a sqlSelect
888 my $x = (&sqlRawReturn("SELECT SUM(counter) FROM stats".
889 " WHERE $where AND nick=".&sqlQuote($arg) ))[0];
891 if (!defined $x) { # !defined.
892 &pSReply("$arg has not said $type yet.");
897 # TODO: convert $where to hash
898 my @array = &sqlSelect("stats", "nick", undef,
899 $where." ORDER BY counter", 1
903 for ($i=0; $i<scalar @array; $i++) {
904 next unless ($array[0] =~ /^\Q$who\E$/);
910 my $total = scalar(@array);
912 if ($total and $good) {
913 my $pct = sprintf("%.01f", 100*(1+$total-$i)/$total);
914 $xtra = ", ranked $i\002/\002$total (percentile: \002$pct\002 %)";
917 my $pct1 = sprintf("%.01f", 100*$x/$sum);
918 &pSReply("\002$arg\002 has said \037$type\037 \002$x\002 times (\002$pct1\002 %)$xtra");
927 # even more uglier with channel/time arguments.
929 # my $c = $chan || "PRIVATE";
930 &DEBUG("not using chan arg") if (!defined $c);
932 # example of converting from RawReturn to sqlSelect.
933 my $where_href = (defined $c) ? { channel => $c } : "";
934 my $sum = &sqlSelect("stats", "SUM(counter)", $where_href);
936 if (!defined $arg or $arg =~ /^\s*$/) {
937 # this is way fucking ugly.
938 &DEBUG("_stats: !arg");
940 my %hash = &sqlSelectColHash("stats", "nick,counter",
942 " ORDER BY counter DESC LIMIT 3", 1
947 # unfortunately we have to sort it again!
949 foreach $i (sort { $b <=> $a } keys %hash) {
950 foreach (keys %{ $hash{$i} }) {
951 my $p = sprintf("%.01f", 100*$i/$sum);
953 push(@top, "\002$_\002 -- $i ($p%)");
959 $topstr = ". Top ".scalar(@top).": ".join(', ', @top);
963 &pSReply("total count of \037$type\037 on \002$c\002: $sum$topstr");
965 &pSReply("zero counter for \037$type\037.");
971 # TODO: add nick to where_href
972 my %hash = &sqlSelectColHash("stats", "type,counter",
973 $where_href, " AND nick=".&sqlQuote($arg)
975 # this is totally fucked... needs to be fixed... and cleaned up.
981 foreach (keys %hash) {
982 &DEBUG("_stats: hash{$_} => $hash{$_}");
984 # TODO: convert $where to hash
985 my @array = &sqlSelect("stats", "nick", undef,
986 $where." ORDER BY counter", 1);
989 for(my $i=0; $i<scalar @array; $i++) {
990 next unless ($array[0] =~ /^\Q$who\E$/);
996 $total = scalar(@array);
997 &DEBUG(" i => $i, good => $good, total => $total");
998 $x .= " ".$total."blah blah";
1003 if (!defined $x) { # !defined.
1004 &pSReply("$arg has not said $type yet.");
1009 if ($total and $good) {
1010 my $pct = sprintf("%.01f", 100*(1+$total-$ii)/$total);
1011 $xtra = ", ranked $ii\002/\002$total (percentile: \002$pct\002 %)";
1014 my $pct1 = sprintf("%.01f", 100*$x/$sum);
1015 &pSReply("\002$arg\002 has said \037$type\037 \002$x\002 times (\002$pct1\002 %)$xtra");
1020 return unless (defined $arg);
1022 #foreach (`$arg`) { &msg($who,$_); }