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", 'i?spell', ('CODEREF' => 'ispell',
30 Help => 'spell', Identifier => 'spell', ) );
31 &addCmdHook("main", 'd?nslookup', ('CODEREF' => 'DNS',
32 Help => 'nslookup', Identifier => 'allowDNS',
33 Forker => "NULL", ) );
34 &addCmdHook("main", 'tell|explain', ('CODEREF' => 'tell',
35 Help => 'tell', Identifier => 'allowTelling',
36 Cmdstats => 'Tell') );
37 &addCmdHook("main", 'News', ('CODEREF' => 'News::Parse',
38 Module => 'News', 'Cmdstats' => 'News' ) );
39 &addCmdHook("main", 'countrystats', ('CODEREF' => 'countryStats',
43 &status("CMD: loaded ".scalar(keys %hooks_main)." MAIN command hooks.");
46 ### Start of commands for hooks.
50 my $chan = lc shift(@_);
53 if ($chan eq "") { # all channels.
54 my $i = keys %channels;
55 my $reply = "i am on \002$i\002 ".&fixPlural("channel",$i);
56 my $tucount = 0; # total user count.
57 my $uucount = 0; # unique user count.
61 foreach (sort keys %channels) {
62 if ( /^\s*$/ or / / ) {
63 &status("chanstats: fe channels: chan == NULL.");
67 next if (/^_default$/);
69 my $str = sprintf("%s (%d)", $_, scalar(keys %{ $channels{$_}{''} }));
72 &pSReply($reply.": ".join(', ', @array));
76 foreach $chan (keys %channels) {
77 $tucount += scalar(keys %{ $channels{$chan}{''} });
80 ### unique user count.
82 foreach $chan (keys %channels) {
83 foreach (keys %{ $channels{$chan}{''} }) {
84 next if (grep /^\Q$_\E$/, @nicks);
90 if (scalar @nicks != $uucount) {
91 &DEBUG("nicks != uucount...");
94 my $chans = scalar(keys %channels);
96 "i've cached \002$tucount\002 ". &fixPlural("user",$tucount).
97 ", \002$uucount\002 unique ". &fixPlural("user",$uucount).
98 ", distributed over \002$chans\002 ".
99 &fixPlural("channel", $chans)."."
107 if (&validChan($chan) == 0) {
108 &msg($who,"error: invalid channel \002$chan\002");
114 foreach (sort keys %{ $chanstats{$chan} }) {
115 my $int = $chanstats{$chan}{$_};
118 push(@array, "\002$int\002 ". &fixPlural($_,$int));
120 my $reply = "On \002$chan\002, there ".
121 &fixPlural("has",scalar(@array)). " been ".
124 # Step 1b: check channel inconstencies.
125 $chanstats{$chan}{'Join'} ||= 0;
126 $chanstats{$chan}{'SignOff'} ||= 0;
127 $chanstats{$chan}{'Part'} ||= 0;
129 my $delta_stats = $chanstats{$chan}{'Join'}
130 - $chanstats{$chan}{'SignOff'}
131 - $chanstats{$chan}{'Part'};
134 my $total = scalar(keys %{ $channels{$chan}{''} });
135 &status("chaninfo: join ~= signoff + part (drift of $delta_stats < $total).");
137 if ($delta_stats > $total) {
138 &ERROR("chaninfo: delta_stats exceeds total users.");
145 foreach ("v","o","") {
146 my $int = scalar(keys %{ $channels{$chan}{$_} });
149 $type = "Voice" if ($_ eq "v");
150 $type = "Opped" if ($_ eq "o");
151 $type = "Total" if ($_ eq "");
153 push(@array,"\002$int\002 $type");
155 $reply .= ". At the moment, ". &IJoin(@array);
159 foreach (keys %userstats) {
160 next unless (exists $userstats{$_}{'Count'});
161 if ($userstats{$_}{'Count'} =~ /^\D+$/) {
162 &WARN("userstats{$_}{Count} is non-digit.");
166 $new{$_} = $userstats{$_}{'Count'};
169 # TODO: show top 3 with percentages?
170 my($count) = (sort { $new{$b} <=> $new{$a} } keys %new)[0];
172 $reply .= ". \002$count\002 has said the most with a total of \002$new{$count}\002 messages";
177 # Command statistics.
181 if (!scalar(keys %cmdstats)) {
182 &performReply("no-one has run any commands yet");
187 foreach (keys %cmdstats) {
188 $countstats{ $cmdstats{$_} }{$_} = 1;
191 foreach (sort {$b <=> $a} keys %countstats) {
195 foreach (keys %{ $countstats{$int} }) {
196 push(@array, "\002$int\002 of $_");
199 &pSReply("command usage include ". &IJoin(@array).".");
202 # Factoid extension info. xk++
204 my $faqtoid = lc shift(@_);
207 if ($faqtoid =~ /^\-(\S+)(\s+(.*))$/) {
208 &msg($who,"error: individual factoid info queries not supported as yet.");
209 &msg($who,"it's possible that the factoid mistakenly begins with '-'.");
216 &CmdFactInfo($faqtoid, $query);
220 my $type = shift(@_);
222 &Forker("factoids", sub {
223 &pSReply( &CmdFactStats($type) );
228 my $target = lc( shift || $who );
229 my $karma = &sqlSelect("stats", "counter",
230 { nick => $target, type => "karma" }) || 0;
233 &pSReply("$target has karma of $karma");
235 &pSReply("$target has neutral karma");
248 foreach (@binaries) {
256 &msg($who, "no binary found.");
260 if (!&validExec($query)) {
261 &msg($who,"argument appears to be fuzzy.");
265 my $reply = "I can't find alternate spellings for '$query'";
267 foreach (`/bin/echo '$query' | $binary -a -S`) {
269 last if !length; # end of query.
271 if (/^\@/) { # intro line.
273 } elsif (/^\*/) { # possibly correct.
274 $reply = "'$query' may be spelled correctly";
276 } elsif (/^\&/) { # possible correction(s).
277 s/^\& (\S+) \d+ \d+: //;
278 my @array = split(/,? /);
280 $reply = "possible spellings for $query: @array";
283 &DEBUG("spell: '+' found => '$_'.");
285 } elsif (/^# (.*?) 0$/) {
289 &DEBUG("spell: unknown: '$_'.");
298 &status("DNS Lookup: $query");
304 my ($target, $tell_obj) = ('','');
305 my $dont_tell_me = 0;
308 ### is this fixed elsewhere?
309 $args =~ s/\s+/ /g; # fix up spaces.
310 $args =~ s/^\s+|\s+$//g; # again.
312 # this one catches most of them
313 if ($args =~ /^(\S+) (-?)about (.*)$/i) {
316 $dont_tell_me = ($2) ? 1 : 0;
318 $tell_obj = $who if ($tell_obj =~ /^(me|myself)$/i);
320 } elsif ($args =~ /^(\S+) where (\S+) can (\S+) (.*)$/i) {
321 # i'm sure this could all be nicely collapsed
326 } elsif ($args =~ /^(\S+) (what|where) (.*?) (is|are)[.?!]*$/i) {
331 $query = "$qWord $verb $tell_obj";
333 } elsif ($args =~ /^(.*?) to (\S+)$/i) {
339 # check target type. Deny channel targets.
340 if ($target !~ /^$mask{nick}$/ or $target =~ /^$mask{chan}$/) {
341 &msg($who,"No, $who, I won't. (target invalid?)");
345 $target = $talkchannel if ($target =~ /^us$/i);
346 $target = $who if ($target =~ /^(me|myself)$/i);
348 &status("tell: target = $target, query = $query");
351 # if ($target !~ /^$mask{chan}$/ and !&IsNickInAnyChan($target)) {
352 # &msg($who, "No, $target is not in any of my chans.");
357 if ($target =~ /^\Q$ident\E$/i) {
358 &msg($who, "Isn't that a bit silly?");
363 my $oldmtype = $msgType;
365 my $result = &doQuestion($tell_obj);
366 # ^ returns '0' if nothing was found.
370 if (!defined $result || $result =~ /^0?$/) {
372 $msgType = "private";
374 # support command redirection.
375 # recursive cmdHooks aswell :)
377 $done++ if &parseCmdHook("main", $tell_obj);
378 $done++ if &parseCmdHook("extra", $tell_obj);
379 $message = $tell_obj;
380 $done++ unless (&Modules());
382 &VERB("tell: setting old values of who and msgType.",2);
384 $msgType = $oldmtype;
387 &msg($who, "told $target about CMD '$tell_obj'");
389 &msg($who, "i dunno what is '$tell_obj'.");
396 &status("tell: <$who> telling $target about $tell_obj.");
397 if ($who ne $target) {
399 &msg($who, "told $target about $tell_obj.");
401 &msg($who, "told $target about $tell_obj ($result)");
404 $reply = "$who wants you to know: $result";
406 $reply = "telling yourself: $result";
409 &msg($target, $reply);
414 my($match, $x, $y, $result);
416 $dns =~ s/^\s+|\s+$//g;
418 if (!defined $dns or $dns =~ /^\s*$/ or $dns =~ / /) {
423 if ($dns =~ /(\d+\.\d+\.\d+\.\d+)/) {
425 &status("DNS query by IP address: $match");
427 $y = pack('C4', split(/\./, $match));
428 $x = (gethostbyaddr($y, &AF_INET));
431 $result = $match." is ".$x unless ($x =~ /^\s*$/);
433 $result = "I can't seem to find that address in DNS";
438 &status("DNS query by name: $dns");
439 $x = join('.',unpack('C4',(gethostbyname($dns))[4]));
442 $result = $dns." is ".$x;
444 $result = "I can\'t find that machine name";
448 &performReply($result);
452 if (exists $cache{countryStats}) {
453 &msg($who,"countrystats is already running!");
462 &help("countrystats");
467 $cache{countryStats}{chan} = $chan;
468 $cache{countryStats}{mtype} = $msgType;
469 $cache{countryStats}{who} = $who;
470 $cache{on_who_Hack} = 1;
473 sub do_countrystats {
474 $chan = $cache{countryStats}{chan};
475 $msgType = $cache{countryStats}{mtype};
476 $who = $cache{countryStats}{who};
480 foreach (keys %{ $cache{nuhInfo} }) {
481 my $h = $cache{nuhInfo}{$_}{Host};
483 if ($h =~ /^.*\.(\D+)$/) { # host
486 $cstats{unresolve}++;
491 foreach (keys %cstats) {
492 $count{ $cstats{$_} }{$_} = 1;
496 foreach (sort {$b <=> $a} keys %count) {
497 my $str = join(", ", sort keys %{ $count{$_} });
498 # push(@list, "$str ($_)");
499 my $perc = sprintf("%.01f", 100 * $_ / $total);
501 push(@list, "$str ($_, $perc %)");
504 # TODO: move this into a scheduler like nickometer
505 $msgType = "private";
506 &pSReply( &formListReply(0, "Country Stats ", @list) );
508 delete $cache{countryStats};
509 delete $cache{on_who_Hack};
513 ### amalgamated commands.
518 if ($message =~ /^(asci*|chr) (\d+)$/) {
519 &DEBUG("ascii/chr called ...");
520 return unless (&hasParam("allowConv"));
522 &DEBUG("ascii/chr called");
526 $result = "NULL" if ($arg == 0);
528 &performReply( sprintf("ascii %s is '%s'", $arg, $result) );
534 if ($message =~ /^ord(\s+(.*))$/) {
535 return unless (&hasParam("allowConv"));
539 if (!defined $arg or length $arg != 1) {
544 if (ord($arg) < 32) {
545 $arg = chr(ord($arg) + 64);
546 if ($arg eq chr(64)) {
553 &performReply( sprintf("'%s' is ascii %s", $arg, ord $arg) );
558 if ($message =~ /^hex(\s+(.*))?$/i) {
559 return unless (&hasParam("allowConv"));
567 if (length $arg > 80) {
568 &msg($who, "Too long.");
573 foreach (split //, $arg) {
574 $retval .= sprintf(" %X", ord($_));
577 &pSReply("$arg is$retval");
583 if ($message =~ /^crypt(\s+(.*))?$/i) {
584 my @args = split /\s+/, $2;
586 if (!scalar @args or scalar @args > 2) {
591 if (scalar @args == 2) {
592 # disable cause $1$ will use md5
593 # if (length $args[0] != 2) {
594 # &msg($who, "invalid format...");
598 &pSReply( crypt($args[1], $args[0]) );
600 &pSReply( &mkcrypt($args[0]) );
607 if ($message =~ /^(cycle)(\s+(\S+))?$/i) {
608 return unless (&hasFlag("o"));
612 if ($msgType =~ /public/) {
613 $chan = $talkchannel;
614 &DEBUG("cycle: setting chan to '$chan'.");
621 if (&validChan($chan) == 0) {
622 &msg($who,"error: invalid channel \002$chan\002");
626 &msg($chan, "I'm coming back. (courtesy of $who)");
628 ### &ScheduleThis(5, "getNickInUse") if (@_);
629 &status("Schedule rejoin in 5secs to $chan by $who.");
630 $conn->schedule(5, sub { &joinchan($chan); });
636 if ($message =~ /^reload$/i) {
637 return unless (&hasFlag("n"));
639 &status("USER reload $who");
640 &pSReply("reloading...");
641 my $modules = &reloadAllModules();
642 &pSReply("reloaded:$modules");
647 if ($message =~ /^redir(\s+(.*))?/i) {
648 return unless (&hasFlag("o"));
651 if (!defined $factoid) {
656 my $val = &getFactInfo($factoid, "factoid_value");
657 if (!defined $val or $val eq "") {
658 &msg($who, "error: '$factoid' does not exist.");
661 &DEBUG("val => '$val'.");
662 my @list = &searchTable("factoids", "factoid_key",
663 "factoid_value", "^$val\$");
665 if (scalar @list == 1) {
666 &msg($who, "hrm... '$factoid' is unique.");
669 if (scalar @list > 5) {
670 &msg($who, "A bit too many factoids to be redirected, hey?");
675 &status("Redirect '$factoid' (". ($#list) .")...");
678 next if (/^\Q$factoid\E$/i);
680 &status(" Redirecting '$_'.");
681 my $was = &getFactoid($_);
682 if ($was =~ /<REPLY> see/i) {
683 &status("warn: not redirecting a redirection.");
687 &DEBUG(" was '$was'.");
689 &setFactInfo($x, "factoid_value", "<REPLY> see $factoid");
693 &msg($who, &formListReply(0, "'$factoid' is redirected to by '", @redir));
699 if ($message =~ /^rot13(\s+(.*))?/i) {
702 if (!defined $reply) {
707 $reply =~ y/A-Za-z/N-ZA-Mn-za-m/;
714 if ($message =~ /^cpustats$/i) {
715 if ($^O !~ /linux/) {
716 &ERROR("cpustats: your OS is not supported yet.");
720 ### poor method to get info out of file, please fix.
721 open(STAT,"/proc/$$/stat");
724 my @data = split(/ /, $line);
727 # utime(13) + stime(14).
728 my $cpu_usage = sprintf("%.01f", ($data[13]+$data[14]) / 100 );
729 # cutime(15) + cstime (16).
730 my $cpu_usage2 = sprintf("%.01f", ($data[15]+$data[16]) / 100 );
731 my $time = time() - $^T;
732 my $raw_perc = $cpu_usage*100/$time;
733 my $raw_perc2 = $cpu_usage2*100/$time;
740 $perc = sprintf("%.01f", $raw_perc);
741 $perc2 = sprintf("%.01f", $raw_perc2);
742 $total = sprintf("%.01f", $raw_perc+$raw_perc2);
743 } elsif ($raw_perc > 0.1) {
744 $perc = sprintf("%.02f", $raw_perc);
745 $perc2 = sprintf("%.02f", $raw_perc2);
746 $total = sprintf("%.02f", $raw_perc+$raw_perc2);
748 $perc = sprintf("%.03f", $raw_perc);
749 $perc2 = sprintf("%.03f", $raw_perc2);
750 $total = sprintf("%.03f", $raw_perc+$raw_perc2);
752 $ratio = sprintf("%.01f", 100*$perc/($perc+$perc2) );
754 &pSReply("Total CPU usage: \002$cpu_usage\002 s ... ".
755 "Total used: \002$total\002 % ".
756 "(parent/child ratio: $ratio %)"
763 if ($message =~ /^ircstats?$/i) {
764 $ircstats{'TotalTime'} ||= 0;
765 $ircstats{'OffTime'} ||= 0;
767 my $count = $ircstats{'ConnectCount'};
768 my $format_time = &Time2String(time() - $ircstats{'ConnectTime'});
769 my $total_time = time() - $ircstats{'ConnectTime'} +
770 $ircstats{'TotalTime'};
773 my $connectivity = 100 * ($total_time - $ircstats{'OffTime'}) /
775 my $p = sprintf("%.03f", $connectivity);
776 $p =~ s/(\.\d*)0+$/$1/;
777 if ($p =~ s/\.0$//) {
778 # this should not happen... but why...
783 if ($total_time != (time() - $ircstats{'ConnectTime'}) ) {
784 my $tt_format = &Time2String($total_time);
785 &DEBUG("tt_format => $tt_format");
789 if ($count == 1) { # good.
790 $reply = "I'm connected to $ircstats{'Server'} and have been so".
793 $reply = "Currently I'm hooked up to $ircstats{'Server'} but only".
794 " for $format_time. ".
795 "I had to reconnect \002$count\002 times.".
796 " Connectivity: $p %";
800 my $reason = $ircstats{'DisconnectReason'};
801 if (defined $reason) {
802 $reply .= ". I was last disconnected for '$reason'.";
811 if ($message =~ /^statu?s$/i) {
812 my $startString = scalar(gmtime $^T);
813 my $upString = &Time2String(time() - $^T);
814 my ($puser,$psystem,$cuser,$csystem) = times;
815 my $factoids = &countKeys("factoids");
817 foreach (keys %forked) {
818 $forks += scalar keys %{ $forked{$_} };
821 $count{'Commands'} = 0;
822 foreach (keys %cmdstats) {
823 $count{'Commands'} += $cmdstats{$_};
827 "Since $startString, there have been".
828 " \002$count{'Update'}\002 ".
829 &fixPlural("modification", $count{'Update'}).
830 ", \002$count{'Question'}\002 ".
831 &fixPlural("question",$count{'Question'}).
832 ", \002$count{'Dunno'}\002 ".
833 &fixPlural("dunno",$count{'Dunno'}).
834 ", \002$count{'Moron'}\002 ".
835 &fixPlural("moron",$count{'Moron'}).
836 " and \002$count{'Commands'}\002 ".
837 &fixPlural("command",$count{'Commands'}).
838 ". I have been awake for $upString this session, and ".
839 "currently reference \002$factoids\002 factoids. ".
840 "I'm using about \002$memusage\002 ".
841 "kB of memory. With \002$forks\002 active ".
842 &fixPlural("fork",$forks).
843 ". Process time user/system $puser/$psystem child $cuser/$csystem"
848 my %hash = &sqlSelectColHash("stats", "nick,counter",
849 { type => "cmdstats" }, 1);
850 # ORDER won't be retained in a hash
851 # " ORDER BY counter DESC", 1);
854 foreach (keys %hash) {
856 foreach (keys %{ $hash{$i} }) {
857 &DEBUG("cmdstats: $hash{$i}{$_} = $_");
860 &DEBUG("end of cmdstats.");
867 # FIXME does not try to get nick "back", just switches nicks
868 if ($message =~ /^wantNick\s(.*)?$/i) {
869 return unless (&hasFlag("o"));
870 my $wantnick = lc $1;
871 my $mynick = $conn->nick();
873 if ($mynick eq $wantnick) {
874 &msg($who, "I hope you're right. I'll try anyway (mynick=$mynick, wantnick=$wantnick).");
877 # fallback check, I guess. needed?
878 if (! &IsNickInAnyChan( $wantnick ) ) {
879 my $str = "attempting to change nick from $mynick to $wantnick";
886 # idea from dondelecarlo :)
887 # TODO: use cache{nickserv}
888 if ($param{'nickServ_pass'}) {
889 my $str = "someone is using nick $wantnick; GHOSTing";
892 &msg("NickServ", "GHOST $wantnick $param{'nickServ_pass'}");
894 $conn->schedule(5, sub {
895 &status("going to change nick from $mynick to $wantnick after GHOST.");