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", 'sched(stats|info)', ('CODEREF' => 'scheduleList', ) );
21 &addCmdHook("main", 'factinfo', ('CODEREF' => 'factinfo',
22 'Cmdstats' => 'Factoid Info', Module => 'Factoids', ) );
23 &addCmdHook("main", 'factstats?', ('CODEREF' => 'factstats',
24 'Cmdstats' => 'Factoid Stats', Help => "factstats",
25 Forker => 1, 'Identifier' => 'Factoids', ) );
26 &addCmdHook("main", 'help', ('CODEREF' => 'help',
27 'Cmdstats' => 'Help', ) );
28 &addCmdHook("main", 'karma', ('CODEREF' => 'karma', ) );
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) {
60 if ( /^\s*$/ or / / ) {
61 &status("chanstats: fe channels: chan == NULL.");
65 next if (/^_default$/);
67 my $str = sprintf("%s (%d)", $_, scalar(keys %{ $channels{$_}{''} }));
70 &pSReply($reply.": ".join(', ', @array));
74 foreach $chan (keys %channels) {
75 $tucount += scalar(keys %{ $channels{$chan}{''} });
78 ### unique user count.
80 foreach $chan (keys %channels) {
81 foreach (keys %{ $channels{$chan}{''} }) {
82 next if (grep /^\Q$_\E$/, @nicks);
88 if (scalar @nicks != $uucount) {
89 &DEBUG("nicks != uucount...");
92 my $chans = scalar(keys %channels);
94 "i've cached \002$tucount\002 ". &fixPlural("user",$tucount).
95 ", \002$uucount\002 unique ". &fixPlural("user",$uucount).
96 ", distributed over \002$chans\002 ".
97 &fixPlural("channel", $chans)."."
105 if (&validChan($chan) == 0) {
106 &msg($who,"error: invalid channel \002$chan\002");
112 foreach (sort keys %{ $chanstats{$chan} }) {
113 my $int = $chanstats{$chan}{$_};
116 push(@array, "\002$int\002 ". &fixPlural($_,$int));
118 my $reply = "On \002$chan\002, there ".
119 &fixPlural("has",scalar(@array)). " been ".
122 # Step 1b: check channel inconstencies.
123 $chanstats{$chan}{'Join'} ||= 0;
124 $chanstats{$chan}{'SignOff'} ||= 0;
125 $chanstats{$chan}{'Part'} ||= 0;
127 my $delta_stats = $chanstats{$chan}{'Join'}
128 - $chanstats{$chan}{'SignOff'}
129 - $chanstats{$chan}{'Part'};
132 my $total = scalar(keys %{ $channels{$chan}{''} });
133 &status("chaninfo: join ~= signoff + part (drift of $delta_stats < $total).");
135 if ($delta_stats > $total) {
136 &ERROR("chaninfo: delta_stats exceeds total users.");
143 foreach ("v","o","") {
144 my $int = scalar(keys %{ $channels{$chan}{$_} });
147 $type = "Voice" if ($_ eq "v");
148 $type = "Opped" if ($_ eq "o");
149 $type = "Total" if ($_ eq "");
151 push(@array,"\002$int\002 $type");
153 $reply .= ". At the moment, ". &IJoin(@array);
157 foreach (keys %userstats) {
158 next unless (exists $userstats{$_}{'Count'});
159 if ($userstats{$_}{'Count'} =~ /^\D+$/) {
160 &WARN("userstats{$_}{Count} is non-digit.");
164 $new{$_} = $userstats{$_}{'Count'};
167 # TODO: show top 3 with percentages?
168 my($count) = (sort { $new{$b} <=> $new{$a} } keys %new)[0];
170 $reply .= ". \002$count\002 has said the most with a total of \002$new{$count}\002 messages";
175 # Command statistics.
179 if (!scalar(keys %cmdstats)) {
180 &performReply("no-one has run any commands yet");
185 foreach (keys %cmdstats) {
186 $countstats{ $cmdstats{$_} }{$_} = 1;
189 foreach (sort {$b <=> $a} keys %countstats) {
193 foreach (keys %{ $countstats{$int} }) {
194 push(@array, "\002$int\002 of $_");
197 &pSReply("command usage include ". &IJoin(@array).".");
200 # Factoid extension info. xk++
202 my $faqtoid = lc shift(@_);
205 if ($faqtoid =~ /^\-(\S+)(\s+(.*))$/) {
206 &msg($who,"error: individual factoid info queries not supported as yet.");
207 &msg($who,"it's possible that the factoid mistakenly begins with '-'.");
214 &CmdFactInfo($faqtoid, $query);
218 my $type = shift(@_);
220 &Forker("factoids", sub {
221 &pSReply( &CmdFactStats($type) );
226 my $target = lc( shift || $who );
227 my $karma = &sqlSelect("stats", "counter",
228 { nick => $target, type => "karma" }) || 0;
231 &pSReply("$target has karma of $karma");
233 &pSReply("$target has neutral karma");
239 &status("DNS Lookup: $query");
245 my ($target, $tell_obj) = ('','');
246 my $dont_tell_me = 0;
249 ### is this fixed elsewhere?
250 $args =~ s/\s+/ /g; # fix up spaces.
251 $args =~ s/^\s+|\s+$//g; # again.
253 # this one catches most of them
254 if ($args =~ /^(\S+) (-?)about (.*)$/i) {
257 $dont_tell_me = ($2) ? 1 : 0;
259 $tell_obj = $who if ($tell_obj =~ /^(me|myself)$/i);
261 } elsif ($args =~ /^(\S+) where (\S+) can (\S+) (.*)$/i) {
262 # i'm sure this could all be nicely collapsed
267 } elsif ($args =~ /^(\S+) (what|where) (.*?) (is|are)[.?!]*$/i) {
272 $query = "$qWord $verb $tell_obj";
274 } elsif ($args =~ /^(.*?) to (\S+)$/i) {
280 # check target type. Deny channel targets.
281 if ($target !~ /^$mask{nick}$/ or $target =~ /^$mask{chan}$/) {
282 &msg($who,"No, $who, I won't. (target invalid?)");
286 $target = $talkchannel if ($target =~ /^us$/i);
287 $target = $who if ($target =~ /^(me|myself)$/i);
289 &status("tell: target = $target, query = $query");
292 # if ($target !~ /^$mask{chan}$/ and !&IsNickInAnyChan($target)) {
293 # &msg($who, "No, $target is not in any of my chans.");
298 if ($target =~ /^\Q$ident\E$/i) {
299 &msg($who, "Isn't that a bit silly?");
304 my $oldmtype = $msgType;
306 my $result = &doQuestion($tell_obj);
307 # ^ returns '0' if nothing was found.
311 if (!defined $result || $result =~ /^0?$/) {
313 $msgType = "private";
315 # support command redirection.
316 # recursive cmdHooks aswell :)
318 $done++ if &parseCmdHook("main", $tell_obj);
319 $done++ if &parseCmdHook("extra", $tell_obj);
320 $message = $tell_obj;
321 $done++ unless (&Modules());
323 &VERB("tell: setting old values of who and msgType.",2);
325 $msgType = $oldmtype;
328 &msg($who, "told $target about CMD '$tell_obj'");
330 &msg($who, "i dunno what is '$tell_obj'.");
337 &status("tell: <$who> telling $target about $tell_obj.");
338 if ($who ne $target) {
340 &msg($who, "told $target about $tell_obj.");
342 &msg($who, "told $target about $tell_obj ($result)");
345 $reply = "$who wants you to know: $result";
347 $reply = "telling yourself: $result";
350 &msg($target, $reply);
355 my($match, $x, $y, $result);
357 $dns =~ s/^\s+|\s+$//g;
359 if (!defined $dns or $dns =~ /^\s*$/ or $dns =~ / /) {
364 if ($dns =~ /(\d+\.\d+\.\d+\.\d+)/) {
366 &status("DNS query by IP address: $match");
368 $y = pack('C4', split(/\./, $match));
369 $x = (gethostbyaddr($y, &AF_INET));
372 $result = $match." is ".$x unless ($x =~ /^\s*$/);
374 $result = "I can't seem to find that address in DNS";
379 &status("DNS query by name: $dns");
380 $x = join('.',unpack('C4',(gethostbyname($dns))[4]));
383 $result = $dns." is ".$x;
385 $result = "I can\'t find that machine name";
389 &performReply($result);
393 if (exists $cache{countryStats}) {
394 &msg($who,"countrystats is already running!");
403 &help("countrystats");
408 $cache{countryStats}{chan} = $chan;
409 $cache{countryStats}{mtype} = $msgType;
410 $cache{countryStats}{who} = $who;
411 $cache{on_who_Hack} = 1;
414 sub do_countrystats {
415 $chan = $cache{countryStats}{chan};
416 $msgType = $cache{countryStats}{mtype};
417 $who = $cache{countryStats}{who};
421 foreach (keys %{ $cache{nuhInfo} }) {
422 my $h = $cache{nuhInfo}{$_}{Host};
424 if ($h =~ /^.*\.(\D+)$/) { # host
427 $cstats{unresolve}++;
432 foreach (keys %cstats) {
433 $count{ $cstats{$_} }{$_} = 1;
437 foreach (sort {$b <=> $a} keys %count) {
438 my $str = join(", ", sort keys %{ $count{$_} });
439 # push(@list, "$str ($_)");
440 my $perc = sprintf("%.01f", 100 * $_ / $total);
442 push(@list, "$str ($_, $perc %)");
445 # TODO: move this into a scheduler like nickometer
446 $msgType = "private";
447 &pSReply( &formListReply(0, "Country Stats ", @list) );
449 delete $cache{countryStats};
450 delete $cache{on_who_Hack};
454 ### amalgamated commands.
459 if ($message =~ /^(asci*|chr) (\d+)$/) {
460 &DEBUG("ascii/chr called ...");
461 return unless (&hasParam("allowConv"));
463 &DEBUG("ascii/chr called");
467 $result = "NULL" if ($arg == 0);
469 &performReply( sprintf("ascii %s is '%s'", $arg, $result) );
475 if ($message =~ /^ord(\s+(.*))$/) {
476 return unless (&hasParam("allowConv"));
480 if (!defined $arg or length $arg != 1) {
485 if (ord($arg) < 32) {
486 $arg = chr(ord($arg) + 64);
487 if ($arg eq chr(64)) {
494 &performReply( sprintf("'%s' is ascii %s", $arg, ord $arg) );
499 if ($message =~ /^hex(\s+(.*))?$/i) {
500 return unless (&hasParam("allowConv"));
508 if (length $arg > 80) {
509 &msg($who, "Too long.");
514 foreach (split //, $arg) {
515 $retval .= sprintf(" %X", ord($_));
518 &pSReply("$arg is$retval");
524 if ($message =~ /^crypt(\s+(.*))?$/i) {
525 my @args = split /\s+/, $2;
527 if (!scalar @args or scalar @args > 2) {
532 if (scalar @args == 2) {
533 # disable cause $1$ will use md5
534 # if (length $args[0] != 2) {
535 # &msg($who, "invalid format...");
539 &pSReply( crypt($args[1], $args[0]) );
541 &pSReply( &mkcrypt($args[0]) );
548 if ($message =~ /^(cycle)(\s+(\S+))?$/i) {
549 return unless (&hasFlag("o"));
553 if ($msgType =~ /public/) {
554 $chan = $talkchannel;
555 &DEBUG("cycle: setting chan to '$chan'.");
562 if (&validChan($chan) == 0) {
563 &msg($who,"error: invalid channel \002$chan\002");
567 &msg($chan, "I'm coming back. (courtesy of $who)");
569 ### &ScheduleThis(5, "getNickInUse") if (@_);
570 &status("Schedule rejoin in 5secs to $chan by $who.");
571 $conn->schedule(5, sub { &joinchan($chan); });
577 if ($message =~ /^reload$/i) {
578 return unless (&hasFlag("n"));
580 &status("USER reload $who");
581 &pSReply("reloading...");
582 my $modules = &reloadAllModules();
583 &pSReply("reloaded:$modules");
588 if ($message =~ /^redir(\s+(.*))?/i) {
589 return unless (&hasFlag("o"));
592 if (!defined $factoid) {
597 my $val = &getFactInfo($factoid, "factoid_value");
598 if (!defined $val or $val eq "") {
599 &msg($who, "error: '$factoid' does not exist.");
602 &DEBUG("val => '$val'.");
603 my @list = &searchTable("factoids", "factoid_key",
604 "factoid_value", "^$val\$");
606 if (scalar @list == 1) {
607 &msg($who, "hrm... '$factoid' is unique.");
610 if (scalar @list > 5) {
611 &msg($who, "A bit too many factoids to be redirected, hey?");
616 &status("Redirect '$factoid' (". ($#list) .")...");
619 next if (/^\Q$factoid\E$/i);
621 &status(" Redirecting '$_'.");
622 my $was = &getFactoid($_);
623 if ($was =~ /<REPLY> see/i) {
624 &status("warn: not redirecting a redirection.");
628 &DEBUG(" was '$was'.");
630 &setFactInfo($x, "factoid_value", "<REPLY> see $factoid");
634 &msg($who, &formListReply(0, "'$factoid' is redirected to by '", @redir));
640 if ($message =~ /^rot13(\s+(.*))?/i) {
643 if (!defined $reply) {
648 $reply =~ y/A-Za-z/N-ZA-Mn-za-m/;
655 if ($message =~ /^cpustats$/i) {
656 if ($^O !~ /linux/) {
657 &ERROR("cpustats: your OS is not supported yet.");
661 ### poor method to get info out of file, please fix.
662 open(STAT,"/proc/$$/stat");
665 my @data = split(/ /, $line);
668 # utime(13) + stime(14).
669 my $cpu_usage = sprintf("%.01f", ($data[13]+$data[14]) / 100 );
670 # cutime(15) + cstime (16).
671 my $cpu_usage2 = sprintf("%.01f", ($data[15]+$data[16]) / 100 );
672 my $time = time() - $^T;
673 my $raw_perc = $cpu_usage*100/$time;
674 my $raw_perc2 = $cpu_usage2*100/$time;
681 $perc = sprintf("%.01f", $raw_perc);
682 $perc2 = sprintf("%.01f", $raw_perc2);
683 $total = sprintf("%.01f", $raw_perc+$raw_perc2);
684 } elsif ($raw_perc > 0.1) {
685 $perc = sprintf("%.02f", $raw_perc);
686 $perc2 = sprintf("%.02f", $raw_perc2);
687 $total = sprintf("%.02f", $raw_perc+$raw_perc2);
689 $perc = sprintf("%.03f", $raw_perc);
690 $perc2 = sprintf("%.03f", $raw_perc2);
691 $total = sprintf("%.03f", $raw_perc+$raw_perc2);
693 $ratio = sprintf("%.01f", 100*$perc/($perc+$perc2) );
695 &pSReply("Total CPU usage: \002$cpu_usage\002 s ... ".
696 "Total used: \002$total\002 % ".
697 "(parent/child ratio: $ratio %)"
704 if ($message =~ /^ircstats?$/i) {
705 $ircstats{'TotalTime'} ||= 0;
706 $ircstats{'OffTime'} ||= 0;
708 my $count = $ircstats{'ConnectCount'};
709 my $format_time = &Time2String(time() - $ircstats{'ConnectTime'});
710 my $total_time = time() - $ircstats{'ConnectTime'} +
711 $ircstats{'TotalTime'};
714 my $connectivity = 100 * ($total_time - $ircstats{'OffTime'}) /
716 my $p = sprintf("%.03f", $connectivity);
717 $p =~ s/(\.\d*)0+$/$1/;
718 if ($p =~ s/\.0$//) {
719 # this should not happen... but why...
724 if ($total_time != (time() - $ircstats{'ConnectTime'}) ) {
725 my $tt_format = &Time2String($total_time);
726 &DEBUG("tt_format => $tt_format");
730 if ($count == 1) { # good.
731 $reply = "I'm connected to $ircstats{'Server'} and have been so".
734 $reply = "Currently I'm hooked up to $ircstats{'Server'} but only".
735 " for $format_time. ".
736 "I had to reconnect \002$count\002 times.".
737 " Connectivity: $p %";
741 my $reason = $ircstats{'DisconnectReason'};
742 if (defined $reason) {
743 $reply .= ". I was last disconnected for '$reason'.";
752 if ($message =~ /^statu?s$/i) {
753 my $startString = scalar(gmtime $^T);
754 my $upString = &Time2String(time() - $^T);
755 my ($puser,$psystem,$cuser,$csystem) = times;
756 my $factoids = &countKeys("factoids");
758 foreach (keys %forked) {
759 $forks += scalar keys %{ $forked{$_} };
762 $count{'Commands'} = 0;
763 foreach (keys %cmdstats) {
764 $count{'Commands'} += $cmdstats{$_};
768 "Since $startString, there have been".
769 " \002$count{'Update'}\002 ".
770 &fixPlural("modification", $count{'Update'}).
771 ", \002$count{'Question'}\002 ".
772 &fixPlural("question",$count{'Question'}).
773 ", \002$count{'Dunno'}\002 ".
774 &fixPlural("dunno",$count{'Dunno'}).
775 ", \002$count{'Moron'}\002 ".
776 &fixPlural("moron",$count{'Moron'}).
777 " and \002$count{'Commands'}\002 ".
778 &fixPlural("command",$count{'Commands'}).
779 ". I have been awake for $upString this session, and ".
780 "currently reference \002$factoids\002 factoids. ".
781 "I'm using about \002$memusage\002 ".
782 "kB of memory. With \002$forks\002 active ".
783 &fixPlural("fork",$forks).
784 ". Process time user/system $puser/$psystem child $cuser/$csystem"
789 my %hash = &sqlSelectColHash("stats", "nick,counter",
790 { type => "cmdstats" }, 1);
791 # ORDER won't be retained in a hash
792 # " ORDER BY counter DESC", 1);
795 foreach (keys %hash) {
797 foreach (keys %{ $hash{$i} }) {
798 &DEBUG("cmdstats: $hash{$i}{$_} = $_");
801 &DEBUG("end of cmdstats.");
808 # FIXME does not try to get nick "back", just switches nicks
809 if ($message =~ /^wantNick\s(.*)?$/i) {
810 return unless (&hasFlag("o"));
811 my $wantnick = lc $1;
812 my $mynick = $conn->nick();
814 if ($mynick eq $wantnick) {
815 &msg($who, "I hope you're right. I'll try anyway (mynick=$mynick, wantnick=$wantnick).");
818 # fallback check, I guess. needed?
819 if (! &IsNickInAnyChan( $wantnick ) ) {
820 my $str = "attempting to change nick from $mynick to $wantnick";
827 # idea from dondelecarlo :)
828 # TODO: use cache{nickserv}
829 if ($param{'nickServ_pass'}) {
830 my $str = "someone is using nick $wantnick; GHOSTing";
833 &msg("NickServ", "GHOST $wantnick $param{'nickServ_pass'}");
835 $conn->schedule(5, sub {
836 &status("going to change nick from $mynick to $wantnick after GHOST.");