2 # UserExtra.pl: User Commands, Public.
4 # Version: v0.2b (20000707)
9 use vars qw($message $arg $qWord $verb $lobotomized $who $result $chan
10 $conn $msgType $query $talkchannel $ident $memusage);
11 use vars qw(%channels %chanstats %cmdstats %count %ircstats %param
12 %cache %mask %userstats %hooks_main);
15 ### Start of command hooks for UserExtra.
18 &addCmdHook("main", 'chan(stats|info)', ('CODEREF' => 'chaninfo', ) );
19 &addCmdHook("main", 'cmd(stats|info)', ('CODEREF' => 'cmdstats', ) );
20 &addCmdHook("main", 'factinfo', ('CODEREF' => 'factinfo',
21 'Cmdstats' => 'Factoid Info', Module => 'factoids', ) );
22 &addCmdHook("main", 'factstats?', ('CODEREF' => 'factstats',
23 'Cmdstats' => 'Factoid Stats', Help => "factstats",
24 Forker => 1, 'Identifier' => 'factoids', ) );
25 &addCmdHook("main", 'help', ('CODEREF' => 'help',
26 'Cmdstats' => 'Help', ) );
27 &addCmdHook("main", 'karma', ('CODEREF' => 'karma', ) );
28 &addCmdHook("main", 'i?spell', ('CODEREF' => 'ispell',
29 Help => 'spell', Identifier => 'spell', ) );
30 &addCmdHook("main", 'd?nslookup', ('CODEREF' => 'DNS',
31 Help => 'nslookup', Identifier => 'allowDNS',
32 Forker => "NULL", ) );
33 &addCmdHook("main", 'tell|explain', ('CODEREF' => 'tell',
34 Help => 'tell', Identifier => 'allowTelling',
35 Cmdstats => 'Tell') );
36 &addCmdHook("main", 'news', ('CODEREF' => 'News::Parse',
37 Module => 'news', 'Cmdstats' => 'News' ) );
38 &addCmdHook("main", 'countrystats', ('CODEREF' => 'countryStats',
42 &status("CMD: loaded ".scalar(keys %hooks_main)." MAIN command hooks.");
45 ### Start of commands for hooks.
49 my $chan = lc shift(@_);
52 if ($chan eq "") { # all channels.
53 my $i = keys %channels;
54 my $reply = "i am on \002$i\002 ".&fixPlural("channel",$i);
55 my $tucount = 0; # total user count.
56 my $uucount = 0; # unique user count.
60 foreach (sort keys %channels) {
62 &status("chanstats: fe channels: chan == NULL.");
66 push(@array, "$_ (".scalar(keys %{ $channels{$_}{''} }).")");
68 &pSReply($reply.": ".join(' ', @array));
71 foreach $chan (keys %channels) {
72 $tucount += scalar(keys %{ $channels{$chan}{''} });
75 ### unique user count.
77 foreach $chan (keys %channels) {
78 foreach (keys %{ $channels{$chan}{''} }) {
79 next if (grep /^\Q$_\E$/, @nicks);
84 &DEBUG("nicks => '".scalar(@nicks)."'...");
85 if (scalar @nicks != $uucount) {
86 &DEBUG("nicks != uucount...");
89 my $chans = scalar(keys %channels);
91 "i've cached \002$tucount\002 ". &fixPlural("user",$tucount).
92 ", \002$uucount\002 unique ". &fixPlural("user",$uucount).
93 ", distributed over \002$chans\002 ".
94 &fixPlural("channel", $chans)."."
102 if (&validChan($chan) == 0) {
103 &msg($who,"error: invalid channel \002$chan\002");
109 foreach (sort keys %{ $chanstats{$chan} }) {
110 my $int = $chanstats{$chan}{$_};
113 push(@array, "\002$int\002 ". &fixPlural($_,$int));
115 my $reply = "On \002$chan\002, there ".
116 &fixPlural("has",scalar(@array)). " been ".
119 # Step 1b: check channel inconstencies.
120 $chanstats{$chan}{'Join'} ||= 0;
121 $chanstats{$chan}{'SignOff'} ||= 0;
122 $chanstats{$chan}{'Part'} ||= 0;
124 my $delta_stats = $chanstats{$chan}{'Join'}
125 - $chanstats{$chan}{'SignOff'}
126 - $chanstats{$chan}{'Part'};
129 my $total = scalar(keys %{ $channels{$chan}{''} });
130 &status("chaninfo: join ~= signoff + part (drift of $delta_stats < $total).");
132 if ($delta_stats > $total) {
133 &ERROR("chaninfo: delta_stats exceeds total users.");
140 foreach ("v","o","") {
141 my $int = scalar(keys %{ $channels{$chan}{$_} });
144 $type = "Voice" if ($_ eq "v");
145 $type = "Opped" if ($_ eq "o");
146 $type = "Total" if ($_ eq "");
148 push(@array,"\002$int\002 $type");
150 $reply .= ". At the moment, ". &IJoin(@array);
154 foreach (keys %userstats) {
155 next unless (exists $userstats{$_}{'Count'});
156 if ($userstats{$_}{'Count'} =~ /^\D+$/) {
157 &WARN("userstats{$_}{Count} is non-digit.");
161 $new{$_} = $userstats{$_}{'Count'};
164 # todo: show top 3 with percentages?
165 my($count) = (sort { $new{$a} <=> $new{$b} } keys %new)[0];
167 $reply .= ". \002$count\002 has said the most with a total of \002$new{$count}\002 messages";
172 # Command statistics.
176 if (!scalar(keys %cmdstats)) {
177 &performReply("no-one has run any commands yet");
182 foreach (keys %cmdstats) {
183 $countstats{ $cmdstats{$_} }{$_} = 1;
186 foreach (sort {$b <=> $a} keys %countstats) {
190 foreach (keys %{ $countstats{$int} }) {
191 push(@array, "\002$int\002 of $_");
194 &pSReply("command usage include ". &IJoin(@array).".");
197 # Factoid extension info. xk++
199 my $faqtoid = lc shift(@_);
202 if ($faqtoid =~ /^\-(\S+)(\s+(.*))$/) {
203 &msg($who,"error: individual factoid info queries not supported as yet.");
204 &msg($who,"it's possible that the factoid mistakenly begins with '-'.");
211 &CmdFactInfo($faqtoid, $query);
215 my $type = shift(@_);
217 &Forker("factoids", sub {
218 &pSReply( &CmdFactStats($type) );
223 my $target = lc( shift || $who );
224 my $karma = &sqlSelect("stats", "counter",
225 { nick => $target, type => "karma" }) || 0;
228 &pSReply("$target has karma of $karma");
230 &pSReply("$target has neutral karma");
237 if (! -x "/usr/bin/ispell") {
238 &msg($who, "no binary found.");
242 if (!&validExec($query)) {
243 &msg($who,"argument appears to be fuzzy.");
247 my $reply = "I can't find alternate spellings for '$query'";
249 foreach (`/bin/echo '$query' | /usr/bin/ispell -a -S`) {
251 last if !length; # end of query.
253 if (/^\@/) { # intro line.
255 } elsif (/^\*/) { # possibly correct.
256 $reply = "'$query' may be spelled correctly";
258 } elsif (/^\&/) { # possible correction(s).
259 s/^\& (\S+) \d+ \d+: //;
260 my @array = split(/,? /);
262 $reply = "possible spellings for $query: @array";
265 &DEBUG("spell: '+' found => '$_'.");
267 } elsif (/^# (.*?) 0$/) {
271 &DEBUG("spell: unknown: '$_'.");
280 &status("DNS Lookup: $query");
286 my ($target, $tell_obj) = ('','');
287 my $dont_tell_me = 0;
290 ### is this fixed elsewhere?
291 $args =~ s/\s+/ /g; # fix up spaces.
292 $args =~ s/^\s+|\s+$//g; # again.
294 # this one catches most of them
295 if ($args =~ /^(\S+) (-?)about (.*)$/i) {
298 $dont_tell_me = ($2) ? 1 : 0;
300 $tell_obj = $who if ($tell_obj =~ /^(me|myself)$/i);
302 } elsif ($args =~ /^(\S+) where (\S+) can (\S+) (.*)$/i) {
303 # i'm sure this could all be nicely collapsed
308 } elsif ($args =~ /^(\S+) (what|where) (.*?) (is|are)[.?!]*$/i) {
313 $query = "$qWord $verb $tell_obj";
315 } elsif ($args =~ /^(.*?) to (\S+)$/i) {
321 # check target type. Deny channel targets.
322 if ($target !~ /^$mask{nick}$/ or $target =~ /^$mask{chan}$/) {
323 &msg($who,"No, $who, I won't. (target invalid?)");
327 $target = $talkchannel if ($target =~ /^us$/i);
328 $target = $who if ($target =~ /^(me|myself)$/i);
330 &status("tell: target = $target, query = $query");
333 # if ($target !~ /^$mask{chan}$/ and !&IsNickInAnyChan($target)) {
334 # &msg($who, "No, $target is not in any of my chans.");
339 if ($target =~ /^\Q$ident\E$/i) {
340 &msg($who, "Isn't that a bit silly?");
345 my $oldmtype = $msgType;
347 my $result = &doQuestion($tell_obj);
348 # ^ returns '0' if nothing was found.
352 if (!defined $result || $result =~ /^0?$/) {
354 $msgType = "private";
356 # support command redirection.
357 # recursive cmdHooks aswell :)
359 $done++ if &parseCmdHook("main", $tell_obj);
360 $done++ if &parseCmdHook("extra", $tell_obj);
361 $message = $tell_obj;
362 $done++ unless (&Modules());
364 &VERB("tell: setting old values of who and msgType.",2);
366 $msgType = $oldmtype;
369 &msg($who, "told $target about CMD '$tell_obj'");
371 &msg($who, "i dunno what is '$tell_obj'.");
378 &status("tell: <$who> telling $target about $tell_obj.");
379 if ($who ne $target) {
381 &msg($who, "told $target about $tell_obj.");
383 &msg($who, "told $target about $tell_obj ($result)");
386 $reply = "$who wants you to know: $result";
388 $reply = "telling yourself: $result";
391 &msg($target, $reply);
396 my($match, $x, $y, $result);
398 $dns =~ s/^\s+|\s+$//g;
400 if (!defined $dns or $dns =~ /^\s*$/ or $dns =~ / /) {
405 if ($dns =~ /(\d+\.\d+\.\d+\.\d+)/) {
407 &status("DNS query by IP address: $match");
409 $y = pack('C4', split(/\./, $match));
410 $x = (gethostbyaddr($y, &AF_INET));
413 $result = $match." is ".$x unless ($x =~ /^\s*$/);
415 $result = "I can't seem to find that address in DNS";
420 &status("DNS query by name: $dns");
421 $x = join('.',unpack('C4',(gethostbyname($dns))[4]));
424 $result = $dns." is ".$x;
426 $result = "I can\'t find that machine name";
430 &performReply($result);
434 if (exists $cache{countryStats}) {
435 &msg($who,"countrystats is already running!");
444 &help("countrystats");
449 $cache{countryStats}{chan} = $chan;
450 $cache{countryStats}{mtype} = $msgType;
451 $cache{countryStats}{who} = $who;
452 $cache{on_who_Hack} = 1;
455 sub do_countrystats {
456 $chan = $cache{countryStats}{chan};
457 $msgType = $cache{countryStats}{mtype};
458 $who = $cache{countryStats}{who};
462 foreach (keys %{ $cache{nuhInfo} }) {
463 my $h = $cache{nuhInfo}{$_}{Host};
465 if ($h =~ /^.*\.(\D+)$/) { # host
468 $cstats{unresolve}++;
473 foreach (keys %cstats) {
474 $count{ $cstats{$_} }{$_} = 1;
478 foreach (sort {$b <=> $a} keys %count) {
479 my $str = join(", ", sort keys %{ $count{$_} });
480 # push(@list, "$str ($_)");
481 my $perc = sprintf("%.01f", 100 * $_ / $total);
483 push(@list, "$str ($_, $perc %)");
486 # todo: move this into a scheduler like nickometer
487 $msgType = "private";
488 &pSReply( &formListReply(0, "Country Stats ", @list) );
490 delete $cache{countryStats};
491 delete $cache{on_who_Hack};
495 ### amalgamated commands.
500 if ($message =~ /^(asci*|chr) (\d+)$/) {
501 &DEBUG("ascii/chr called ...");
502 return unless (&hasParam("allowConv"));
504 &DEBUG("ascii/chr called");
508 $result = "NULL" if ($arg == 0);
510 &performReply( sprintf("ascii %s is '%s'", $arg, $result) );
516 if ($message =~ /^ord(\s+(.*))$/) {
517 return unless (&hasParam("allowConv"));
521 if (!defined $arg or length $arg != 1) {
526 if (ord($arg) < 32) {
527 $arg = chr(ord($arg) + 64);
528 if ($arg eq chr(64)) {
535 &performReply( sprintf("'%s' is ascii %s", $arg, ord $1) );
540 if ($message =~ /^hex(\s+(.*))?$/i) {
541 return unless (&hasParam("allowConv"));
549 if (length $arg > 80) {
550 &msg($who, "Too long.");
555 foreach (split //, $arg) {
556 $retval .= sprintf(" %X", ord($_));
559 &pSReply("$arg is$retval");
565 if ($message =~ /^crypt(\s+(.*))?$/i) {
566 my @args = split /\s+/, $2;
568 if (!scalar @args or scalar @args > 2) {
573 if (scalar @args == 2) {
574 if (length $args[0] != 2) {
575 &msg($who, "invalid format...");
579 &pSReply( crypt($args[1], $args[0]) );
581 &pSReply( &mkcrypt($args[0]) );
588 if ($message =~ /^(cycle)(\s+(\S+))?$/i) {
589 return unless (&hasFlag("o"));
593 if ($msgType =~ /public/) {
594 $chan = $talkchannel;
595 &DEBUG("cycle: setting chan to '$chan'.");
602 if (&validChan($chan) == 0) {
603 &msg($who,"error: invalid channel \002$chan\002");
607 &msg($chan, "I'm coming back. (courtesy of $who)");
609 ### &ScheduleThis(5, "getNickInUse") if (@_);
610 &status("Schedule rejoin in 5secs to $chan by $who.");
611 $conn->schedule(5, sub { &joinchan($chan); });
617 if ($message =~ /^reload$/i) {
618 return unless (&hasFlag("n"));
620 &status("USER reload $who");
621 &pSReply("reloading...");
623 &pSReply("reloaded.");
628 if ($message =~ /^redir(\s+(.*))?/i) {
629 return unless (&hasFlag("o"));
632 if (!defined $factoid) {
637 my $val = &getFactInfo($factoid, "factoid_value");
638 if (!defined $val or $val eq "") {
639 &msg($who, "error: '$factoid' does not exist.");
642 &DEBUG("val => '$val'.");
643 my @list = &searchTable("factoids", "factoid_key",
644 "factoid_value", "^$val\$");
646 if (scalar @list == 1) {
647 &msg($who, "hrm... '$factoid' is unique.");
650 if (scalar @list > 5) {
651 &msg($who, "A bit too many factoids to be redirected, hey?");
656 &status("Redirect '$factoid' (". ($#list) .")...");
659 next if (/^\Q$factoid\E$/i);
661 &status(" Redirecting '$_'.");
662 my $was = &getFactoid($_);
663 if ($was =~ /<REPLY> see/i) {
664 &status("warn: not redirecting a redirection.");
668 &DEBUG(" was '$was'.");
670 &setFactInfo($x, "factoid_value", "<REPLY> see $factoid");
674 &msg($who, &formListReply(0, "'$factoid' is redirected to by '", @redir));
680 if ($message =~ /^rot13(\s+(.*))?/i) {
683 if (!defined $reply) {
688 $reply =~ y/A-Za-z/N-ZA-Mn-za-m/;
695 if ($message =~ /^cpustats$/i) {
696 if ($^O !~ /linux/) {
697 &ERROR("cpustats: your OS is not supported yet.");
701 ### poor method to get info out of file, please fix.
702 open(STAT,"/proc/$$/stat");
705 my @data = split(/ /, $line);
708 # utime(13) + stime(14).
709 my $cpu_usage = sprintf("%.01f", ($data[13]+$data[14]) / 100 );
710 # cutime(15) + cstime (16).
711 my $cpu_usage2 = sprintf("%.01f", ($data[15]+$data[16]) / 100 );
712 my $time = time() - $^T;
713 my $raw_perc = $cpu_usage*100/$time;
714 my $raw_perc2 = $cpu_usage2*100/$time;
721 $perc = sprintf("%.01f", $raw_perc);
722 $perc2 = sprintf("%.01f", $raw_perc2);
723 $total = sprintf("%.01f", $raw_perc+$raw_perc2);
724 } elsif ($raw_perc > 0.1) {
725 $perc = sprintf("%.02f", $raw_perc);
726 $perc2 = sprintf("%.02f", $raw_perc2);
727 $total = sprintf("%.02f", $raw_perc+$raw_perc2);
729 $perc = sprintf("%.03f", $raw_perc);
730 $perc2 = sprintf("%.03f", $raw_perc2);
731 $total = sprintf("%.03f", $raw_perc+$raw_perc2);
733 $ratio = sprintf("%.01f", 100*$perc/($perc+$perc2) );
735 &pSReply("Total CPU usage: \002$cpu_usage\002 s ... ".
736 "Total used: \002$total\002 % ".
737 "(parent/child ratio: $ratio %)"
744 if ($message =~ /^ircstats?$/i) {
745 $ircstats{'TotalTime'} ||= 0;
746 $ircstats{'OffTime'} ||= 0;
748 my $count = $ircstats{'ConnectCount'};
749 my $format_time = &Time2String(time() - $ircstats{'ConnectTime'});
750 my $total_time = time() - $ircstats{'ConnectTime'} +
751 $ircstats{'TotalTime'};
754 my $connectivity = 100 * ($total_time - $ircstats{'OffTime'}) /
756 my $p = sprintf("%.03f", $connectivity);
757 $p =~ s/(\.\d*)0+$/$1/;
758 if ($p =~ s/\.0$//) {
759 # this should not happen... but why...
764 if ($total_time != (time() - $ircstats{'ConnectTime'}) ) {
765 my $tt_format = &Time2String($total_time);
766 &DEBUG("tt_format => $tt_format");
770 if ($count == 1) { # good.
771 $reply = "I'm connected to $ircstats{'Server'} and have been so".
774 $reply = "Currently I'm hooked up to $ircstats{'Server'} but only".
775 " for $format_time. ".
776 "I had to reconnect \002$count\002 times.".
777 " Connectivity: $p %";
781 my $reason = $ircstats{'DisconnectReason'};
782 if (defined $reason) {
783 $reply .= ". I was last disconnected for '$reason'.";
792 if ($message =~ /^statu?s$/i) {
793 my $startString = scalar(gmtime $^T);
794 my $upString = &Time2String(time() - $^T);
795 my $factoids = &countKeys("factoids");
797 $count{'Commands'} = 0;
798 foreach (keys %cmdstats) {
799 $count{'Commands'} += $cmdstats{$_};
803 "Since $startString, there have been".
804 " \002$count{'Update'}\002 ".
805 &fixPlural("modification", $count{'Update'}).
806 " and \002$count{'Question'}\002 ".
807 &fixPlural("question",$count{'Question'}).
808 " and \002$count{'Dunno'}\002 ".
809 &fixPlural("dunno",$count{'Dunno'}).
810 " and \002$count{'Moron'}\002 ".
811 &fixPlural("moron",$count{'Moron'}).
812 " and \002$count{'Commands'}\002 ".
813 &fixPlural("command",$count{'Commands'}).
814 ". I have been awake for $upString this session, and ".
815 "currently reference \002$factoids\002 factoids. ".
816 "I'm using about \002$memusage\002 ".
822 # todo: use dbGetColNiceHash().
823 my %hash = &sqlSelectColHash("stats", "nick,counter",
824 { type => "cmdstats" }, 1);
825 # does ORDER matter when used with a hash?
826 # " ORDER BY counter DESC", 1);
829 foreach (keys %hash) {
831 foreach (keys %{ $hash{$i} }) {
832 &DEBUG("cmdstats: $hash{$i}{$_} = $_");
835 &DEBUG("end of cmdstats.");
842 if ($message =~ /^wantNick$/i) {
843 if ($param{'ircNick'} eq $ident) {
844 &msg($who, "I hope you're right. I'll try anyway.");
846 &DEBUG("ircNick => $param{'ircNick'}");
847 &DEBUG("ident => $ident");
849 if (! &IsNickInAnyChan( $param{ircNick} ) ) {
850 my $str = "attempting to change nick to $param{'ircNick'}";
853 &nick($param{'ircNick'});
855 &msg($who, "hrm.. I shouldn't do it (BUG?) but doing it anyway!");
856 &DEBUG("wN: nick is somewhere... should try later.");
857 &nick($param{'ircNick'});