2 # UserExtra.pl: User Commands, Public.
4 # Version: v0.2b (20000707)
9 use vars qw($message $arg $qWord $verb $lobotomized);
10 use vars qw(%channels %chanstats %cmdstats);
13 ### Start of command hooks for UserExtra.
16 &addCmdHook("main", 'chan(stats|info)', ('CODEREF' => 'chaninfo', ) );
17 &addCmdHook("main", 'cmd(stats|info)', ('CODEREF' => 'cmdstats', ) );
18 &addCmdHook("main", 'factinfo', ('CODEREF' => 'factinfo',
19 'Cmdstats' => 'Factoid Info', Module => 'factoids', ) );
20 &addCmdHook("main", 'factstats?', ('CODEREF' => 'factstats',
21 'Cmdstats' => 'Factoid Statistics', Help => "factstats",
22 Forker => 1, 'Identifier' => 'factoids', ) );
23 &addCmdHook("main", 'help', ('CODEREF' => 'help',
24 'Cmdstats' => 'Help', ) );
25 &addCmdHook("main", 'karma', ('CODEREF' => 'karma', ) );
26 &addCmdHook("main", 'i?spell', ('CODEREF' => 'ispell',
27 Help => 'spell', Identifier => 'spell', ) );
28 &addCmdHook("main", 'd?nslookup', ('CODEREF' => 'DNS',
29 Help => 'nslookup', Identifier => 'allowDNS',
30 Forker => "NULL", ) );
31 &addCmdHook("main", 'tell|explain', ('CODEREF' => 'tell',
32 Help => 'tell', Identifier => 'allowTelling',
33 Cmdstats => 'Tell') );
34 &addCmdHook("main", 'news', ('CODEREF' => 'News::Parse',
35 Module => 'news', 'Cmdstats' => 'News' ) );
36 &addCmdHook("main", 'countrystats', ('CODEREF' => 'countryStats',
40 &status("CMD: loaded ".scalar(keys %hooks_main)." MAIN command hooks.");
43 ### Start of commands for hooks.
47 my $chan = lc shift(@_);
50 if ($chan eq "") { # all channels.
51 my $i = keys %channels;
52 my $reply = "i am on \002$i\002 ".&fixPlural("channel",$i);
53 my $tucount = 0; # total user count.
54 my $uucount = 0; # unique user count.
58 foreach (sort keys %channels) {
60 &status("chanstats: fe channels: chan == NULL.");
64 push(@array, "$_ (".scalar(keys %{ $channels{$_}{''} }).")");
66 &pSReply($reply.": ".join(' ', @array));
69 foreach $chan (keys %channels) {
70 $tucount += scalar(keys %{ $channels{$chan}{''} });
73 ### unique user count.
75 foreach $chan (keys %channels) {
76 foreach (keys %{ $channels{$chan}{''} }) {
77 next if (grep /^\Q$_\E$/, @nicks);
82 &DEBUG("nicks => '".scalar(@nicks)."'...");
83 if (scalar @nicks != $uucount) {
84 &DEBUG("nicks != uucount...");
87 my $chans = scalar(keys %channels);
89 "i've cached \002$tucount\002 ". &fixPlural("user",$tucount).
90 ", \002$uucount\002 unique ". &fixPlural("user",$uucount).
91 ", distributed over \002$chans\002 ".
92 &fixPlural("channel", $chans)."."
100 if (&validChan($chan) == 0) {
101 &msg($who,"error: invalid channel \002$chan\002");
107 foreach (sort keys %{ $chanstats{$chan} }) {
108 my $int = $chanstats{$chan}{$_};
111 push(@array, "\002$int\002 ". &fixPlural($_,$int));
113 my $reply = "On \002$chan\002, there ".
114 &fixPlural("has",scalar(@array)). " been ".
117 # Step 1b: check channel inconstencies.
118 $chanstats{$chan}{'Join'} ||= 0;
119 $chanstats{$chan}{'SignOff'} ||= 0;
120 $chanstats{$chan}{'Part'} ||= 0;
122 my $delta_stats = $chanstats{$chan}{'Join'}
123 - $chanstats{$chan}{'SignOff'}
124 - $chanstats{$chan}{'Part'};
127 my $total = scalar(keys %{ $channels{$chan}{''} });
128 &status("chaninfo: join ~= signoff + part (drift of $delta_stats < $total).");
130 if ($delta_stats > $total) {
131 &ERROR("chaninfo: delta_stats exceeds total users.");
138 foreach ("v","o","") {
139 my $int = scalar(keys %{ $channels{$chan}{$_} });
142 $type = "Voice" if ($_ eq "v");
143 $type = "Opped" if ($_ eq "o");
144 $type = "Total" if ($_ eq "");
146 push(@array,"\002$int\002 $type");
148 $reply .= ". At the moment, ". &IJoin(@array);
152 foreach (keys %userstats) {
153 next unless (exists $userstats{$_}{'Count'});
154 if ($userstats{$_}{'Count'} =~ /^\D+$/) {
155 &WARN("userstats{$_}{Count} is non-digit.");
159 $new{$_} = $userstats{$_}{'Count'};
162 # todo: show top 3 with percentages?
163 my($count) = (sort { $new{$a} <=> $new{$b} } keys %new)[0];
165 $reply .= ". \002$count\002 has said the most with a total of \002$new{$count}\002 messages";
170 # Command statistics.
174 if (!scalar(keys %cmdstats)) {
175 &performReply("no-one has run any commands yet");
180 foreach (keys %cmdstats) {
181 $countstats{ $cmdstats{$_} }{$_} = 1;
184 foreach (sort {$b <=> $a} keys %countstats) {
188 foreach (keys %{ $countstats{$int} }) {
189 push(@array, "\002$int\002 of $_");
192 &pSReply("command usage include ". &IJoin(@array).".");
195 # Factoid extension info. xk++
197 my $faqtoid = lc shift(@_);
200 if ($faqtoid =~ /^\-(\S+)(\s+(.*))$/) {
201 &msg($who,"error: individual factoid info queries not supported as yet.");
202 &msg($who,"it's possible that the factoid mistakenly begins with '-'.");
209 &CmdFactInfo($faqtoid, $query);
213 my $type = shift(@_);
215 &Forker("factoids", sub {
216 &pSReply( &CmdFactStats($type) );
221 my $target = lc( shift || $who );
222 my $karma = &dbGet("stats", "counter", "nick=".
223 &dbQuote($target)." AND type='karma'") || 0;
226 &pSReply("$target has karma of $karma");
228 &pSReply("$target has neutral karma");
235 if (! -x "/usr/bin/ispell") {
236 &msg($who, "no binary found.");
240 if (!&validExec($query)) {
241 &msg($who,"argument appears to be fuzzy.");
245 my $reply = "I can't find alternate spellings for '$query'";
247 foreach (`/bin/echo '$query' | /usr/bin/ispell -a -S`) {
249 last if !length; # end of query.
251 if (/^\@/) { # intro line.
253 } elsif (/^\*/) { # possibly correct.
254 $reply = "'$query' may be spelled correctly";
256 } elsif (/^\&/) { # possible correction(s).
257 s/^\& (\S+) \d+ \d+: //;
258 my @array = split(/,? /);
260 $reply = "possible spellings for $query: @array";
263 &DEBUG("spell: '+' found => '$_'.");
265 } elsif (/^# (.*?) 0$/) {
269 &DEBUG("spell: unknown: '$_'.");
278 &status("DNS Lookup: $query");
284 my ($target, $tell_obj) = ('','');
285 my $dont_tell_me = 0;
288 ### is this fixed elsewhere?
289 $args =~ s/\s+/ /g; # fix up spaces.
290 $args =~ s/^\s+|\s+$//g; # again.
292 # this one catches most of them
293 if ($args =~ /^(\S+) (-?)about (.*)$/i) {
296 $dont_tell_me = ($2) ? 1 : 0;
298 $tell_obj = $who if ($tell_obj =~ /^(me|myself)$/i);
300 } elsif ($args =~ /^(\S+) where (\S+) can (\S+) (.*)$/i) {
301 # i'm sure this could all be nicely collapsed
306 } elsif ($args =~ /^(\S+) (what|where) (.*?) (is|are)[.?!]*$/i) {
311 $query = "$qWord $verb $tell_obj";
313 } elsif ($args =~ /^(.*?) to (\S+)$/i) {
319 # check target type. Deny channel targets.
320 if ($target !~ /^$mask{nick}$/ or $target =~ /^$mask{chan}$/) {
321 &msg($who,"No, $who, I won't. (target invalid?)");
325 $target = $talkchannel if ($target =~ /^us$/i);
326 $target = $who if ($target =~ /^(me|myself)$/i);
328 &status("tell: target = $target, query = $query");
331 # if ($target !~ /^$mask{chan}$/ and !&IsNickInAnyChan($target)) {
332 # &msg($who, "No, $target is not in any of my chans.");
337 if ($target =~ /^\Q$ident\E$/i) {
338 &msg($who, "Isn't that a bit silly?");
343 my $oldmtype = $msgType;
345 my $result = &doQuestion($tell_obj);
346 # ^ returns '0' if nothing was found.
350 if ($result =~ /^0?$/) {
352 $msgType = "private";
354 # support command redirection.
355 # recursive cmdHooks aswell :)
357 $done++ if &parseCmdHook("main", $tell_obj);
358 $done++ if &parseCmdHook("extra", $tell_obj);
359 $message = $tell_obj;
360 $done++ unless (&Modules());
362 &VERB("tell: setting old values of who and msgType.",2);
364 $msgType = $oldmtype;
367 &msg($who, "told $target about CMD '$tell_obj'");
369 &msg($who, "i dunno what is '$tell_obj'.");
376 &status("tell: <$who> telling $target about $tell_obj.");
377 if ($who ne $target) {
379 &msg($who, "told $target about $tell_obj.");
381 &msg($who, "told $target about $tell_obj ($result)");
384 $reply = "$who wants you to know: $result";
386 $reply = "telling yourself: $result";
389 &msg($target, $reply);
394 my($match, $x, $y, $result);
396 $dns =~ s/^\s+|\s+$//g;
398 if (!defined $dns or $dns =~ /^\s*$/ or $dns =~ / /) {
403 if ($dns =~ /(\d+\.\d+\.\d+\.\d+)/) {
405 &status("DNS query by IP address: $match");
407 $y = pack('C4', split(/\./, $match));
408 $x = (gethostbyaddr($y, &AF_INET));
411 $result = $match." is ".$x unless ($x =~ /^\s*$/);
413 $result = "I can't seem to find that address in DNS";
418 &status("DNS query by name: $dns");
419 $x = join('.',unpack('C4',(gethostbyname($dns))[4]));
422 $result = $dns." is ".$x;
424 $result = "I can\'t find that machine name";
428 &performReply($result);
432 if (exists $cache{countryStats}) {
433 &msg($who,"countrystats is already running!");
442 &help("countrystats");
446 &rawout("WHO $chan");
447 $cache{countryStats}{chan} = $chan;
448 $cache{countryStats}{mtype} = $msgType;
449 $cache{countryStats}{who} = $who;
450 $cache{on_who_Hack} = 1;
453 sub do_countrystats {
454 $chan = $cache{countryStats}{chan};
455 $msgType = $cache{countryStats}{mtype};
456 $who = $cache{countryStats}{who};
460 foreach (keys %{ $cache{nuhInfo} }) {
461 my $h = $cache{nuhInfo}{$_}{Host};
463 if ($h =~ /^.*\.(\D+)$/) { # host
466 $cstats{unresolve}++;
471 foreach (keys %cstats) {
472 $count{ $cstats{$_} }{$_} = 1;
476 foreach (sort {$b <=> $a} keys %count) {
477 my $str = join(", ", sort keys %{ $count{$_} });
478 # push(@list, "$str ($_)");
479 my $perc = sprintf("%.01f", 100 * $_ / $total);
481 push(@list, "$str ($_, $perc %)");
484 # todo: move this into a scheduler like nickometer
485 $msgType = "private";
486 &pSReply( &formListReply(0, "Country Stats ", @list) );
488 delete $cache{countryStats};
489 delete $cache{on_who_Hack};
493 ### amalgamated commands.
498 if ($message =~ /^(asci*|chr) (\d+)$/) {
499 &DEBUG("ascii/chr called ...");
500 return unless (&hasParam("allowConv"));
502 &DEBUG("ascii/chr called");
506 $result = "NULL" if ($arg == 0);
508 &performReply( sprintf("ascii %s is '%s'", $arg, $result) );
514 if ($message =~ /^ord(\s+(.*))$/) {
515 return unless (&hasParam("allowConv"));
519 if (!defined $arg or length $arg != 1) {
524 if (ord($arg) < 32) {
525 $arg = chr(ord($arg) + 64);
526 if ($arg eq chr(64)) {
533 &performReply( sprintf("'%s' is ascii %s", $arg, ord $1) );
538 if ($message =~ /^hex(\s+(.*))?$/i) {
539 return unless (&hasParam("allowConv"));
547 if (length $arg > 80) {
548 &msg($who, "Too long.");
553 foreach (split //, $arg) {
554 $retval .= sprintf(" %X", ord($_));
557 &pSReply("$arg is$retval");
563 if ($message =~ /^crypt(\s+(.*))?$/i) {
564 my @args = split /\s+/, $2;
566 if (!scalar @args or scalar @args > 2) {
571 if (scalar @args == 2) {
572 if (length $args[0] != 2) {
573 &msg($who, "invalid format...");
577 &pSReply( crypt($args[1], $args[0]) );
579 &pSReply( &mkcrypt($args[0]) );
586 if ($message =~ /^(cycle)(\s+(\S+))?$/i) {
587 return unless (&hasFlag("o"));
591 if ($msgType =~ /public/) {
592 $chan = $talkchannel;
593 &DEBUG("cycle: setting chan to '$chan'.");
600 if (&validChan($chan) == 0) {
601 &msg($who,"error: invalid channel \002$chan\002");
605 &msg($chan, "I'm coming back. (courtesy of $who)");
607 ### &ScheduleThis(5, "getNickInUse") if (@_);
608 &status("Schedule rejoin in 5secs to $chan by $who.");
609 $conn->schedule(5, sub { &joinchan($chan); });
615 if ($message =~ /^reload$/i) {
616 return unless (&hasFlag("n"));
618 &status("USER reload $who");
619 &pSReply("reloading...");
621 &pSReply("reloaded.");
627 if ($message =~ /^redir(\s+(.*))?/i) {
628 return unless (&hasFlag("o"));
631 if (!defined $factoid) {
636 my $val = &getFactInfo($factoid, "factoid_value");
637 if (!defined $val or $val eq "") {
638 &msg($who, "error: '$factoid' does not exist.");
641 &DEBUG("val => '$val'.");
642 my @list = &searchTable("factoids", "factoid_key",
643 "factoid_value", "^$val\$");
645 if (scalar @list == 1) {
646 &msg($who, "hrm... '$factoid' is unique.");
649 if (scalar @list > 5) {
650 &msg($who, "A bit too many factoids to be redirected, hey?");
655 &status("Redirect '$factoid' (". ($#list) .")...");
658 next if (/^\Q$factoid\E$/i);
660 &status(" Redirecting '$_'.");
661 my $was = &getFactoid($_);
662 if ($was =~ /<REPLY> see/i) {
663 &status("warn: not redirecting a redirection.");
667 &DEBUG(" was '$was'.");
669 &setFactInfo($x, "factoid_value", "<REPLY> see $factoid");
673 &msg($who, &formListReply(0, "'$factoid' is redirected to by '", @redir));
679 if ($message =~ /^rot13(\s+(.*))?/i) {
682 if (!defined $reply) {
687 $reply =~ y/A-Za-z/N-ZA-Mn-za-m/;
694 if ($message =~ /^cpustats$/i) {
695 if ($^O !~ /linux/) {
696 &ERROR("cpustats: your OS is not supported yet.");
700 ### poor method to get info out of file, please fix.
701 open(STAT,"/proc/$$/stat");
704 my @data = split(/ /, $line);
707 # utime(13) + stime(14).
708 my $cpu_usage = sprintf("%.01f", ($data[13]+$data[14]) / 100 );
709 # cutime(15) + cstime (16).
710 my $cpu_usage2 = sprintf("%.01f", ($data[15]+$data[16]) / 100 );
711 my $time = time() - $^T;
712 my $raw_perc = $cpu_usage*100/$time;
713 my $raw_perc2 = $cpu_usage2*100/$time;
720 $perc = sprintf("%.01f", $raw_perc);
721 $perc2 = sprintf("%.01f", $raw_perc2);
722 $total = sprintf("%.01f", $raw_perc+$raw_perc2);
723 } elsif ($raw_perc > 0.1) {
724 $perc = sprintf("%.02f", $raw_perc);
725 $perc2 = sprintf("%.02f", $raw_perc2);
726 $total = sprintf("%.02f", $raw_perc+$raw_perc2);
728 $perc = sprintf("%.03f", $raw_perc);
729 $perc2 = sprintf("%.03f", $raw_perc2);
730 $total = sprintf("%.03f", $raw_perc+$raw_perc2);
732 $ratio = sprintf("%.01f", 100*$perc/($perc+$perc2) );
734 &pSReply("Total CPU usage: \002$cpu_usage\002 s ... ".
735 "Total used: \002$total\002 % ".
736 "(parent/child ratio: $ratio %)"
743 if ($message =~ /^ircstats?$/i) {
744 $ircstats{'TotalTime'} ||= 0;
745 $ircstats{'OffTime'} ||= 0;
747 my $count = $ircstats{'ConnectCount'};
748 my $format_time = &Time2String(time() - $ircstats{'ConnectTime'});
749 my $total_time = time() - $ircstats{'ConnectTime'} +
750 $ircstats{'TotalTime'};
753 my $connectivity = 100 * ($total_time - $ircstats{'OffTime'}) /
755 my $p = sprintf("%.03f", $connectivity);
756 $p =~ s/(\.\d*)0+$/$1/;
757 if ($p =~ s/\.0$//) {
758 # this should not happen... but why...
763 if ($total_time != (time() - $ircstats{'ConnectTime'}) ) {
764 my $tt_format = &Time2String($total_time);
765 &DEBUG("tt_format => $tt_format");
769 if ($count == 1) { # good.
770 $reply = "I'm connected to $ircstats{'Server'} and have been so".
773 $reply = "Currently I'm hooked up to $ircstats{'Server'} but only".
774 " for $format_time. ".
775 "I had to reconnect \002$count\002 times.".
776 " Connectivity: $p %";
780 my $reason = $ircstats{'DisconnectReason'};
781 if (defined $reason) {
782 $reply .= ". I was last disconnected for '$reason'.";
791 if ($message =~ /^statu?s$/i) {
792 my $startString = scalar(localtime $^T);
793 my $upString = &Time2String(time() - $^T);
794 my $count = &countKeys("factoids");
796 $count{'Commands'} = 0;
797 foreach (keys %cmdstats) {
798 $count{'Commands'} += $cmdstats{$_};
802 "Since $startString, there have been".
803 " \002$count{'Update'}\002 ".
804 &fixPlural("modification", $count{'Update'}).
805 " and \002$count{'Question'}\002 ".
806 &fixPlural("question",$count{'Question'}).
807 " and \002$count{'Dunno'}\002 ".
808 &fixPlural("dunno",$count{'Dunno'}).
809 " and \002$count{'Moron'}\002 ".
810 &fixPlural("moron",$count{'Moron'}).
811 " and \002$count{'Commands'}\002 ".
812 &fixPlural("command",$count{'Commands'}).
813 ". I have been awake for $upString this session, and ".
814 "currently reference \002$count\002 factoids. ".
815 "I'm using about \002$memusage\002 ".
819 # todo: make dbGetColNiceHash().
820 my %hash = &dbGetCol("stats", "nick,counter", "type='cmdstats'".
821 # " ORDER BY counter DESC LIMIT 3", 1);
822 " ORDER BY counter DESC", 1);
824 foreach (keys %hash) {
826 foreach (keys %{ $hash{$i} }) {
827 &DEBUG("cmdstats: $hash{$i}{$_} = $_");
830 &DEBUG("end of cmdstats.");
836 if ($message =~ /^wantNick$/i) {
837 if ($param{'ircNick'} eq $ident) {
838 &msg($who, "I hope you're right. I'll try anyway.");
840 &DEBUG("ircNick => $param{'ircNick'}");
841 &DEBUG("ident => $ident");
843 if (! &IsNickInAnyChan( $param{ircNick} ) ) {
844 my $str = "attempting to change nick to $param{'ircNick'}";
847 &nick($param{'ircNick'});
849 &msg($who, "hrm.. I shouldn't do it (BUG?) but doing it anyway!");
850 &DEBUG("wN: nick is somewhere... should try later.");
851 &nick($param{'ircNick'});