2 # UserExtra.pl: User Commands, Public.
4 # Version: v0.2b (20000707)
8 if (&IsParam("useStrict")) { use strict; }
10 use vars qw($message $arg $qWord $verb $lobotomized);
11 use vars qw(%channels %chanstats %cmdstats);
14 ### Start of command hooks for UserExtra.
17 &addCmdHook("main", 'chan(stats|info)', ('CODEREF' => 'chaninfo', ) );
18 &addCmdHook("main", 'cmd(stats|info)', ('CODEREF' => 'cmdstats', ) );
19 &addCmdHook("main", 'factinfo', ('CODEREF' => 'factinfo',
20 'Cmdstats' => 'Factoid Info', Module => 'factoids', ) );
21 &addCmdHook("main", 'factstats?', ('CODEREF' => 'factstats',
22 'Cmdstats' => 'Factoid Statistics', Help => "factstats",
23 Forker => 1, 'Identifier' => 'factoids', ) );
24 &addCmdHook("main", 'help', ('CODEREF' => 'help',
25 'Cmdstats' => 'Help', ) );
26 &addCmdHook("main", 'karma', ('CODEREF' => 'karma', ) );
27 &addCmdHook("main", 'i?spell', ('CODEREF' => 'ispell',
28 Help => 'spell', Identifier => 'spell', ) );
29 &addCmdHook("main", 'd?nslookup', ('CODEREF' => 'DNS',
30 Help => 'nslookup', Identifier => 'allowDNS',
31 Forker => "NULL", ) );
32 &addCmdHook("main", 'tell|explain', ('CODEREF' => 'tell',
33 Help => 'tell', Identifier => 'allowTelling',
34 Cmdstats => 'Tell') );
35 &addCmdHook("main", 'news', ('CODEREF' => 'News::Parse',
36 Module => 'news', 'Cmdstats' => 'News' ) );
37 &addCmdHook("main", 'countrystats', ('CODEREF' => 'countryStats',
41 &status("CMD: loaded ".scalar(keys %hooks_main)." MAIN command hooks.");
44 ### Start of commands for hooks.
48 my $chan = lc shift(@_);
51 if ($chan eq "") { # all channels.
52 my $i = keys %channels;
53 my $reply = "i am on \002$i\002 ".&fixPlural("channel",$i);
54 my $tucount = 0; # total user count.
55 my $uucount = 0; # unique user count.
59 foreach (sort keys %channels) {
61 &status("chanstats: fe channels: chan == NULL.");
65 push(@array, "$_ (".scalar(keys %{ $channels{$_}{''} }).")");
67 &pSReply($reply.": ".join(' ', @array));
70 foreach $chan (keys %channels) {
71 $tucount += scalar(keys %{ $channels{$chan}{''} });
74 ### unique user count.
76 foreach $chan (keys %channels) {
77 foreach (keys %{ $channels{$chan}{''} }) {
78 next if (grep /^\Q$_\E$/, @nicks);
83 &DEBUG("nicks => '".scalar(@nicks)."'...");
84 if (scalar @nicks != $uucount) {
85 &DEBUG("nicks != uucount...");
88 my $chans = scalar(keys %channels);
90 "i've cached \002$tucount\002 ". &fixPlural("user",$tucount).
91 ", \002$uucount\002 unique ". &fixPlural("user",$uucount).
92 ", distributed over \002$chans\002 ".
93 &fixPlural("channel", $chans)."."
101 if (&validChan($chan) == 0) {
102 &msg($who,"error: invalid channel \002$chan\002");
108 foreach (sort keys %{ $chanstats{$chan} }) {
109 my $int = $chanstats{$chan}{$_};
112 push(@array, "\002$int\002 ". &fixPlural($_,$int));
114 my $reply = "On \002$chan\002, there ".
115 &fixPlural("has",scalar(@array)). " been ".
118 # Step 1b: check channel inconstencies.
119 $chanstats{$chan}{'Join'} ||= 0;
120 $chanstats{$chan}{'SignOff'} ||= 0;
121 $chanstats{$chan}{'Part'} ||= 0;
123 my $delta_stats = $chanstats{$chan}{'Join'}
124 - $chanstats{$chan}{'SignOff'}
125 - $chanstats{$chan}{'Part'};
128 my $total = scalar(keys %{ $channels{$chan}{''} });
129 &status("chaninfo: join ~= signoff + part (drift of $delta_stats < $total).");
131 if ($delta_stats > $total) {
132 &ERROR("chaninfo: delta_stats exceeds total users.");
139 foreach ("v","o","") {
140 my $int = scalar(keys %{ $channels{$chan}{$_} });
143 $type = "Voice" if ($_ eq "v");
144 $type = "Opped" if ($_ eq "o");
145 $type = "Total" if ($_ eq "");
147 push(@array,"\002$int\002 $type");
149 $reply .= ". At the moment, ". &IJoin(@array);
153 foreach (keys %userstats) {
154 next unless (exists $userstats{$_}{'Count'});
155 if ($userstats{$_}{'Count'} =~ /^\D+$/) {
156 &WARN("userstats{$_}{Count} is non-digit.");
160 $new{$_} = $userstats{$_}{'Count'};
163 # todo: show top 3 with percentages?
164 my($count) = (sort { $a <=> $b } keys %new)[0];
166 $reply .= ". \002$count\002 has said the most with a total of \002$new{$count}\002 messages";
171 # Command statistics.
175 if (!scalar(keys %cmdstats)) {
176 &performReply("no-one has run any commands yet");
181 foreach (keys %cmdstats) {
182 $countstats{ $cmdstats{$_} }{$_} = 1;
185 foreach (sort {$b <=> $a} keys %countstats) {
189 foreach (keys %{ $countstats{$int} }) {
190 push(@array, "\002$int\002 of $_");
193 &pSReply("command usage include ". &IJoin(@array).".");
196 # Factoid extension info. xk++
198 my $faqtoid = lc shift(@_);
201 if ($faqtoid =~ /^\-(\S+)(\s+(.*))$/) {
202 &msg($who,"error: individual factoid info queries not supported as yet.");
203 &msg($who,"it's possible that the factoid mistakenly begins with '-'.");
210 &CmdFactInfo($faqtoid, $query);
214 my $type = shift(@_);
216 &Forker("factoids", sub {
217 &pSReply( &CmdFactStats($type) );
222 my $target = lc( shift || $who );
223 my $karma = &dbGet("stats", "counter", "nick=".
224 &dbQuote($target)." AND type='karma'") || 0;
227 &pSReply("$target has karma of $karma");
229 &pSReply("$target has neutral karma");
236 if (! -x "/usr/bin/spell") {
237 &msg($who, "no binary found.");
241 if (!&validExec($query)) {
242 &msg($who,"argument appears to be fuzzy.");
246 my $reply = "I can't find alternate spellings for '$query'";
248 foreach (`/bin/echo '$query' | /usr/bin/ispell -a -S`) {
250 last if !length; # end of query.
252 if (/^\@/) { # intro line.
254 } elsif (/^\*/) { # possibly correct.
255 $reply = "'$query' may be spelled correctly";
257 } elsif (/^\&/) { # possible correction(s).
258 s/^\& (\S+) \d+ \d+: //;
259 my @array = split(/,? /);
261 $reply = "possible spellings for $query: @array";
264 &DEBUG("spell: '+' found => '$_'.");
267 &DEBUG("spell: unknown: '$_'.");
276 &status("DNS Lookup: $query");
282 my ($target, $tell_obj) = ('','');
283 my $dont_tell_me = 0;
286 ### is this fixed elsewhere?
287 $args =~ s/\s+/ /g; # fix up spaces.
288 $args =~ s/^\s+|\s+$//g; # again.
290 # this one catches most of them
291 if ($args =~ /^(\S+) (-?)about (.*)$/i) {
294 $dont_tell_me = ($2) ? 1 : 0;
296 $tell_obj = $who if ($tell_obj =~ /^(me|myself)$/i);
298 } elsif ($args =~ /^(\S+) where (\S+) can (\S+) (.*)$/i) {
299 # i'm sure this could all be nicely collapsed
304 } elsif ($args =~ /^(\S+) (what|where) (.*?) (is|are)[.?!]*$/i) {
309 $query = "$qWord $verb $tell_obj";
311 } elsif ($args =~ /^(.*?) to (\S+)$/i) {
317 # check target type. Deny channel targets.
318 if ($target !~ /^$mask{nick}$/ or $target =~ /^$mask{chan}$/) {
319 &msg($who,"No, $who, I won't. (target invalid?)");
323 $target = $talkchannel if ($target =~ /^us$/i);
324 $target = $who if ($target =~ /^(me|myself)$/i);
326 &status("tell: target = $target, query = $query");
329 # if ($target !~ /^$mask{chan}$/ and !&IsNickInAnyChan($target)) {
330 # &msg($who, "No, $target is not in any of my chans.");
335 if ($target =~ /^\Q$ident\E$/i) {
336 &msg($who, "Isn't that a bit silly?");
341 my $oldmtype = $msgType;
343 my $result = &doQuestion($tell_obj);
344 # ^ returns '0' if nothing was found.
348 if ($result =~ /^0?$/) {
350 $msgType = "private";
352 # support command redirection.
353 # recursive cmdHooks aswell :)
355 $done++ if &parseCmdHook("main", $tell_obj);
356 $done++ if &parseCmdHook("extra", $tell_obj);
357 $message = $tell_obj;
358 $done++ unless (&Modules());
360 &VERB("tell: setting old values of who and msgType.",2);
362 $msgType = $oldmtype;
365 &msg($who, "told $target about CMD '$tell_obj'");
367 &msg($who, "i dunno what is '$tell_obj'.");
374 &status("tell: <$who> telling $target about $tell_obj.");
375 if ($who ne $target) {
377 &msg($who, "told $target about $tell_obj.");
379 &msg($who, "told $target about $tell_obj ($result)");
382 $reply = "$who wants you to know: $result";
384 $reply = "telling yourself: $result";
387 &msg($target, $reply);
392 my($match, $x, $y, $result);
394 $dns =~ s/^\s+|\s+$//g;
396 if ($dns =~ /(\d+\.\d+\.\d+\.\d+)/) {
398 &status("DNS query by IP address: $match");
400 $y = pack('C4', split(/\./, $match));
401 $x = (gethostbyaddr($y, &AF_INET));
404 $result = $match." is ".$x unless ($x =~ /^\s*$/);
406 $result = "I can't seem to find that address in DNS";
411 &status("DNS query by name: $dns");
412 $x = join('.',unpack('C4',(gethostbyname($dns))[4]));
415 $result = $dns." is ".$x;
417 $result = "I can\'t find that machine name";
421 &performReply($result);
425 if (exists $cache{countryStats}) {
426 &msg($who,"countrystats is already running!");
435 &help("countrystats");
439 &rawout("WHO $chan");
440 $cache{countryStats}{chan} = $chan;
441 $cache{countryStats}{mtype} = $msgType;
442 $cache{countryStats}{who} = $who;
443 $cache{on_who_Hack} = 1;
446 sub do_countrystats {
447 $chan = $cache{countryStats}{chan};
448 $msgType = $cache{countryStats}{mtype};
449 $who = $cache{countryStats}{who};
453 foreach (keys %{ $cache{nuhInfo} }) {
454 my $h = $cache{nuhInfo}{$_}{Host};
456 if ($h =~ /^.*\.(\D+)$/) { # host
459 $cstats{unresolve}++;
464 foreach (keys %cstats) {
465 $count{ $cstats{$_} }{$_} = 1;
469 foreach (sort {$b <=> $a} keys %count) {
470 my $str = join(", ", sort keys %{ $count{$_} });
471 # push(@list, "$str ($_)");
472 my $perc = sprintf("%.01f", 100 * $_ / $total);
474 push(@list, "$str ($_, $perc %)");
477 # todo: move this into a scheduler like nickometer
478 $msgType = "private";
479 &pSReply( &formListReply(0, "Country Stats ", @list) );
481 delete $cache{countryStats};
482 delete $cache{on_who_Hack};
486 ### amalgamated commands.
491 if ($message =~ /^(asci*|chr) (\d+)$/) {
492 &DEBUG("ascii/chr called ...");
493 return unless (&hasParam("allowConv"));
495 &DEBUG("ascii/chr called");
499 $result = "NULL" if ($arg == 0);
501 &performReply( sprintf("ascii %s is '%s'", $arg, $result) );
507 if ($message =~ /^ord(\s+(.*))$/) {
508 return unless (&hasParam("allowConv"));
512 if (!defined $arg or length $arg != 1) {
517 if (ord($arg) < 32) {
518 $arg = chr(ord($arg) + 64);
519 if ($arg eq chr(64)) {
526 &performReply( sprintf("'%s' is ascii %s", $arg, ord $1) );
531 if ($message =~ /^hex(\s+(.*))?$/i) {
532 return unless (&hasParam("allowConv"));
540 if (length $arg > 80) {
541 &msg($who, "Too long.");
546 foreach (split //, $arg) {
547 $retval .= sprintf(" %X", ord($_));
550 &pSReply("$arg is$retval");
556 if ($message =~ /^crypt(\s+(.*))?$/i) {
557 my @args = split /\s+/, $2;
559 if (!scalar @args or scalar @args > 2) {
564 if (scalar @args == 2) {
565 if (length $args[0] != 2) {
566 &msg($who, "invalid format...");
570 &pSReply( crypt($args[1], $args[0]) );
572 &pSReply( &mkcrypt($args[0]) );
579 if ($message =~ /^(cycle)(\s+(\S+))?$/i) {
580 return unless (&hasFlag("o"));
584 if ($msgType =~ /public/) {
585 $chan = $talkchannel;
586 &DEBUG("cycle: setting chan to '$chan'.");
593 if (&validChan($chan) == 0) {
594 &msg($who,"error: invalid channel \002$chan\002");
598 &msg($chan, "I'm coming back. (courtesy of $who)");
600 ### &ScheduleThis(5, "getNickInUse") if (@_);
601 &status("Schedule rejoin in 5secs to $chan by $who.");
602 $conn->schedule(5, sub { &joinchan($chan); });
608 if ($message =~ /^redir(\s+(.*))?/i) {
609 return unless (&hasFlag("o"));
612 if (!defined $factoid) {
617 my $val = &getFactInfo($factoid, "factoid_value");
618 if (!defined $val or $val eq "") {
619 &msg($who, "error: '$factoid' does not exist.");
622 &DEBUG("val => '$val'.");
623 my @list = &searchTable("factoids", "factoid_key",
624 "factoid_value", "^$val\$");
626 if (scalar @list == 1) {
627 &msg($who, "hrm... '$factoid' is unique.");
630 if (scalar @list > 5) {
631 &msg($who, "A bit too many factoids to be redirected, hey?");
636 &status("Redirect '$factoid' (". ($#list) .")...");
639 next if (/^\Q$factoid\E$/i);
641 &status(" Redirecting '$_'.");
642 my $was = &getFactoid($_);
643 if ($was =~ /<REPLY> see/i) {
644 &status("warn: not redirecting a redirection.");
648 &DEBUG(" was '$was'.");
650 &setFactInfo($x, "factoid_value", "<REPLY> see $factoid");
654 &msg($who, &formListReply(0, "'$factoid' is redirected to by '", @redir));
660 if ($message =~ /^rot13(\s+(.*))?/i) {
663 if (!defined $reply) {
668 $reply =~ y/A-Za-z/N-ZA-Mn-za-m/;
675 if ($message =~ /^cpustats$/i) {
676 if ($^O !~ /linux/) {
677 &ERROR("cpustats: your OS is not supported yet.");
681 ### poor method to get info out of file, please fix.
682 open(STAT,"/proc/$$/stat");
685 my @data = split(/ /, $line);
688 # utime(13) + stime(14).
689 my $cpu_usage = sprintf("%.01f", ($data[13]+$data[14]) / 100 );
690 # cutime(15) + cstime (16).
691 my $cpu_usage2 = sprintf("%.01f", ($data[15]+$data[16]) / 100 );
692 my $time = time() - $^T;
693 my $raw_perc = $cpu_usage*100/$time;
694 my $raw_perc2 = $cpu_usage2*100/$time;
701 $perc = sprintf("%.01f", $raw_perc);
702 $perc2 = sprintf("%.01f", $raw_perc2);
703 $total = sprintf("%.01f", $raw_perc+$raw_perc2);
704 } elsif ($raw_perc > 0.1) {
705 $perc = sprintf("%.02f", $raw_perc);
706 $perc2 = sprintf("%.02f", $raw_perc2);
707 $total = sprintf("%.02f", $raw_perc+$raw_perc2);
709 $perc = sprintf("%.03f", $raw_perc);
710 $perc2 = sprintf("%.03f", $raw_perc2);
711 $total = sprintf("%.03f", $raw_perc+$raw_perc2);
713 $ratio = sprintf("%.01f", 100*$perc/($perc+$perc2) );
715 &pSReply("Total CPU usage: \002$cpu_usage\002 s ... ".
716 "Total used: \002$total\002 % ".
717 "(parent/child ratio: $ratio %)"
724 if ($message =~ /^ircstats?$/i) {
725 $ircstats{'TotalTime'} ||= 0;
726 $ircstats{'OffTime'} ||= 0;
728 my $count = $ircstats{'ConnectCount'};
729 my $format_time = &Time2String(time() - $ircstats{'ConnectTime'});
730 my $total_time = time() - $ircstats{'ConnectTime'} +
731 $ircstats{'TotalTime'};
734 my $connectivity = 100 * ($total_time - $ircstats{'OffTime'}) /
736 my $p = sprintf("%.03f", $connectivity);
737 $p =~ s/(\.\d*)0+$/$1/;
738 if ($p =~ s/\.0$//) {
739 # this should not happen... but why...
744 if ($total_time != (time() - $ircstats{'ConnectTime'}) ) {
745 my $tt_format = &Time2String($total_time);
746 &DEBUG("tt_format => $tt_format");
750 if ($count == 1) { # good.
751 $reply = "I'm connected to $ircstats{'Server'} and have been so".
754 $reply = "Currently I'm hooked up to $ircstats{'Server'} but only".
755 " for $format_time. ".
756 "I had to reconnect \002$count\002 times.".
757 " Connectivity: $p %";
761 my $reason = $ircstats{'DisconnectReason'};
762 if (defined $reason) {
763 $reply .= ". I was last disconnected for '$reason'.";
772 if ($message =~ /^statu?s$/i) {
773 my $startString = scalar(localtime $^T);
774 my $upString = &Time2String(time() - $^T);
775 my $count = &countKeys("factoids");
777 $count{'Commands'} = 0;
778 foreach (keys %cmdstats) {
779 $count{'Commands'} += $cmdstats{$_};
783 "Since $startString, there have been".
784 " \002$count{'Update'}\002 ".
785 &fixPlural("modification", $count{'Update'}).
786 " and \002$count{'Question'}\002 ".
787 &fixPlural("question",$count{'Question'}).
788 " and \002$count{'Dunno'}\002 ".
789 &fixPlural("dunno",$count{'Dunno'}).
790 " and \002$count{'Moron'}\002 ".
791 &fixPlural("moron",$count{'Moron'}).
792 " and \002$count{'Commands'}\002 ".
793 &fixPlural("command",$count{'Commands'}).
794 ". I have been awake for $upString this session, and ".
795 "currently reference \002$count\002 factoids. ".
796 "I'm using about \002$memusage\002 ".
800 # todo: make dbGetColNiceHash().
801 my %hash = &dbGetCol("stats", "nick,counter", "type='cmdstats'".
802 # " ORDER BY counter DESC LIMIT 3", 1);
803 " ORDER BY counter DESC", 1);
805 foreach (keys %hash) {
806 &DEBUG("cmdstats: hash{$_} => $hash{$_}");
808 &DEBUG("end of cmdstats.");
814 if ($message =~ /^wantNick$/i) {
815 if ($param{'ircNick'} eq $ident) {
816 &msg($who, "I hope you're right. I'll try anyway.");
819 if (! &IsNickInAnyChan( $param{ircNick} ) ) {
820 my $str = "attempting to change nick to $param{'ircNick'}";
823 &nick($param{'ircNick'});
825 &msg($who, "hrm... can't do it");
826 &DEBUG("wN: nick is somewhere... should try later.");