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{$a} <=> $new{$b} } 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");
242 if (! -x "/usr/bin/ispell") {
243 &msg($who, "no binary found.");
247 if (!&validExec($query)) {
248 &msg($who,"argument appears to be fuzzy.");
252 my $reply = "I can't find alternate spellings for '$query'";
254 foreach (`/bin/echo '$query' | /usr/bin/ispell -a -S`) {
256 last if !length; # end of query.
258 if (/^\@/) { # intro line.
260 } elsif (/^\*/) { # possibly correct.
261 $reply = "'$query' may be spelled correctly";
263 } elsif (/^\&/) { # possible correction(s).
264 s/^\& (\S+) \d+ \d+: //;
265 my @array = split(/,? /);
267 $reply = "possible spellings for $query: @array";
270 &DEBUG("spell: '+' found => '$_'.");
272 } elsif (/^# (.*?) 0$/) {
276 &DEBUG("spell: unknown: '$_'.");
285 &status("DNS Lookup: $query");
291 my ($target, $tell_obj) = ('','');
292 my $dont_tell_me = 0;
295 ### is this fixed elsewhere?
296 $args =~ s/\s+/ /g; # fix up spaces.
297 $args =~ s/^\s+|\s+$//g; # again.
299 # this one catches most of them
300 if ($args =~ /^(\S+) (-?)about (.*)$/i) {
303 $dont_tell_me = ($2) ? 1 : 0;
305 $tell_obj = $who if ($tell_obj =~ /^(me|myself)$/i);
307 } elsif ($args =~ /^(\S+) where (\S+) can (\S+) (.*)$/i) {
308 # i'm sure this could all be nicely collapsed
313 } elsif ($args =~ /^(\S+) (what|where) (.*?) (is|are)[.?!]*$/i) {
318 $query = "$qWord $verb $tell_obj";
320 } elsif ($args =~ /^(.*?) to (\S+)$/i) {
326 # check target type. Deny channel targets.
327 if ($target !~ /^$mask{nick}$/ or $target =~ /^$mask{chan}$/) {
328 &msg($who,"No, $who, I won't. (target invalid?)");
332 $target = $talkchannel if ($target =~ /^us$/i);
333 $target = $who if ($target =~ /^(me|myself)$/i);
335 &status("tell: target = $target, query = $query");
338 # if ($target !~ /^$mask{chan}$/ and !&IsNickInAnyChan($target)) {
339 # &msg($who, "No, $target is not in any of my chans.");
344 if ($target =~ /^\Q$ident\E$/i) {
345 &msg($who, "Isn't that a bit silly?");
350 my $oldmtype = $msgType;
352 my $result = &doQuestion($tell_obj);
353 # ^ returns '0' if nothing was found.
357 if (!defined $result || $result =~ /^0?$/) {
359 $msgType = "private";
361 # support command redirection.
362 # recursive cmdHooks aswell :)
364 $done++ if &parseCmdHook("main", $tell_obj);
365 $done++ if &parseCmdHook("extra", $tell_obj);
366 $message = $tell_obj;
367 $done++ unless (&Modules());
369 &VERB("tell: setting old values of who and msgType.",2);
371 $msgType = $oldmtype;
374 &msg($who, "told $target about CMD '$tell_obj'");
376 &msg($who, "i dunno what is '$tell_obj'.");
383 &status("tell: <$who> telling $target about $tell_obj.");
384 if ($who ne $target) {
386 &msg($who, "told $target about $tell_obj.");
388 &msg($who, "told $target about $tell_obj ($result)");
391 $reply = "$who wants you to know: $result";
393 $reply = "telling yourself: $result";
396 &msg($target, $reply);
401 my($match, $x, $y, $result);
403 $dns =~ s/^\s+|\s+$//g;
405 if (!defined $dns or $dns =~ /^\s*$/ or $dns =~ / /) {
410 if ($dns =~ /(\d+\.\d+\.\d+\.\d+)/) {
412 &status("DNS query by IP address: $match");
414 $y = pack('C4', split(/\./, $match));
415 $x = (gethostbyaddr($y, &AF_INET));
418 $result = $match." is ".$x unless ($x =~ /^\s*$/);
420 $result = "I can't seem to find that address in DNS";
425 &status("DNS query by name: $dns");
426 $x = join('.',unpack('C4',(gethostbyname($dns))[4]));
429 $result = $dns." is ".$x;
431 $result = "I can\'t find that machine name";
435 &performReply($result);
439 if (exists $cache{countryStats}) {
440 &msg($who,"countrystats is already running!");
449 &help("countrystats");
454 $cache{countryStats}{chan} = $chan;
455 $cache{countryStats}{mtype} = $msgType;
456 $cache{countryStats}{who} = $who;
457 $cache{on_who_Hack} = 1;
460 sub do_countrystats {
461 $chan = $cache{countryStats}{chan};
462 $msgType = $cache{countryStats}{mtype};
463 $who = $cache{countryStats}{who};
467 foreach (keys %{ $cache{nuhInfo} }) {
468 my $h = $cache{nuhInfo}{$_}{Host};
470 if ($h =~ /^.*\.(\D+)$/) { # host
473 $cstats{unresolve}++;
478 foreach (keys %cstats) {
479 $count{ $cstats{$_} }{$_} = 1;
483 foreach (sort {$b <=> $a} keys %count) {
484 my $str = join(", ", sort keys %{ $count{$_} });
485 # push(@list, "$str ($_)");
486 my $perc = sprintf("%.01f", 100 * $_ / $total);
488 push(@list, "$str ($_, $perc %)");
491 # TODO: move this into a scheduler like nickometer
492 $msgType = "private";
493 &pSReply( &formListReply(0, "Country Stats ", @list) );
495 delete $cache{countryStats};
496 delete $cache{on_who_Hack};
500 ### amalgamated commands.
505 if ($message =~ /^(asci*|chr) (\d+)$/) {
506 &DEBUG("ascii/chr called ...");
507 return unless (&hasParam("allowConv"));
509 &DEBUG("ascii/chr called");
513 $result = "NULL" if ($arg == 0);
515 &performReply( sprintf("ascii %s is '%s'", $arg, $result) );
521 if ($message =~ /^ord(\s+(.*))$/) {
522 return unless (&hasParam("allowConv"));
526 if (!defined $arg or length $arg != 1) {
531 if (ord($arg) < 32) {
532 $arg = chr(ord($arg) + 64);
533 if ($arg eq chr(64)) {
540 &performReply( sprintf("'%s' is ascii %s", $arg, ord $arg) );
545 if ($message =~ /^hex(\s+(.*))?$/i) {
546 return unless (&hasParam("allowConv"));
554 if (length $arg > 80) {
555 &msg($who, "Too long.");
560 foreach (split //, $arg) {
561 $retval .= sprintf(" %X", ord($_));
564 &pSReply("$arg is$retval");
570 if ($message =~ /^crypt(\s+(.*))?$/i) {
571 my @args = split /\s+/, $2;
573 if (!scalar @args or scalar @args > 2) {
578 if (scalar @args == 2) {
579 if (length $args[0] != 2) {
580 &msg($who, "invalid format...");
584 &pSReply( crypt($args[1], $args[0]) );
586 &pSReply( &mkcrypt($args[0]) );
593 if ($message =~ /^(cycle)(\s+(\S+))?$/i) {
594 return unless (&hasFlag("o"));
598 if ($msgType =~ /public/) {
599 $chan = $talkchannel;
600 &DEBUG("cycle: setting chan to '$chan'.");
607 if (&validChan($chan) == 0) {
608 &msg($who,"error: invalid channel \002$chan\002");
612 &msg($chan, "I'm coming back. (courtesy of $who)");
614 ### &ScheduleThis(5, "getNickInUse") if (@_);
615 &status("Schedule rejoin in 5secs to $chan by $who.");
616 $conn->schedule(5, sub { &joinchan($chan); });
622 if ($message =~ /^reload$/i) {
623 return unless (&hasFlag("n"));
625 &status("USER reload $who");
626 &pSReply("reloading...");
627 my $modules = &reloadAllModules();
628 &pSReply("reloaded:$modules");
633 if ($message =~ /^redir(\s+(.*))?/i) {
634 return unless (&hasFlag("o"));
637 if (!defined $factoid) {
642 my $val = &getFactInfo($factoid, "factoid_value");
643 if (!defined $val or $val eq "") {
644 &msg($who, "error: '$factoid' does not exist.");
647 &DEBUG("val => '$val'.");
648 my @list = &searchTable("factoids", "factoid_key",
649 "factoid_value", "^$val\$");
651 if (scalar @list == 1) {
652 &msg($who, "hrm... '$factoid' is unique.");
655 if (scalar @list > 5) {
656 &msg($who, "A bit too many factoids to be redirected, hey?");
661 &status("Redirect '$factoid' (". ($#list) .")...");
664 next if (/^\Q$factoid\E$/i);
666 &status(" Redirecting '$_'.");
667 my $was = &getFactoid($_);
668 if ($was =~ /<REPLY> see/i) {
669 &status("warn: not redirecting a redirection.");
673 &DEBUG(" was '$was'.");
675 &setFactInfo($x, "factoid_value", "<REPLY> see $factoid");
679 &msg($who, &formListReply(0, "'$factoid' is redirected to by '", @redir));
685 if ($message =~ /^rot13(\s+(.*))?/i) {
688 if (!defined $reply) {
693 $reply =~ y/A-Za-z/N-ZA-Mn-za-m/;
700 if ($message =~ /^cpustats$/i) {
701 if ($^O !~ /linux/) {
702 &ERROR("cpustats: your OS is not supported yet.");
706 ### poor method to get info out of file, please fix.
707 open(STAT,"/proc/$$/stat");
710 my @data = split(/ /, $line);
713 # utime(13) + stime(14).
714 my $cpu_usage = sprintf("%.01f", ($data[13]+$data[14]) / 100 );
715 # cutime(15) + cstime (16).
716 my $cpu_usage2 = sprintf("%.01f", ($data[15]+$data[16]) / 100 );
717 my $time = time() - $^T;
718 my $raw_perc = $cpu_usage*100/$time;
719 my $raw_perc2 = $cpu_usage2*100/$time;
726 $perc = sprintf("%.01f", $raw_perc);
727 $perc2 = sprintf("%.01f", $raw_perc2);
728 $total = sprintf("%.01f", $raw_perc+$raw_perc2);
729 } elsif ($raw_perc > 0.1) {
730 $perc = sprintf("%.02f", $raw_perc);
731 $perc2 = sprintf("%.02f", $raw_perc2);
732 $total = sprintf("%.02f", $raw_perc+$raw_perc2);
734 $perc = sprintf("%.03f", $raw_perc);
735 $perc2 = sprintf("%.03f", $raw_perc2);
736 $total = sprintf("%.03f", $raw_perc+$raw_perc2);
738 $ratio = sprintf("%.01f", 100*$perc/($perc+$perc2) );
740 &pSReply("Total CPU usage: \002$cpu_usage\002 s ... ".
741 "Total used: \002$total\002 % ".
742 "(parent/child ratio: $ratio %)"
749 if ($message =~ /^ircstats?$/i) {
750 $ircstats{'TotalTime'} ||= 0;
751 $ircstats{'OffTime'} ||= 0;
753 my $count = $ircstats{'ConnectCount'};
754 my $format_time = &Time2String(time() - $ircstats{'ConnectTime'});
755 my $total_time = time() - $ircstats{'ConnectTime'} +
756 $ircstats{'TotalTime'};
759 my $connectivity = 100 * ($total_time - $ircstats{'OffTime'}) /
761 my $p = sprintf("%.03f", $connectivity);
762 $p =~ s/(\.\d*)0+$/$1/;
763 if ($p =~ s/\.0$//) {
764 # this should not happen... but why...
769 if ($total_time != (time() - $ircstats{'ConnectTime'}) ) {
770 my $tt_format = &Time2String($total_time);
771 &DEBUG("tt_format => $tt_format");
775 if ($count == 1) { # good.
776 $reply = "I'm connected to $ircstats{'Server'} and have been so".
779 $reply = "Currently I'm hooked up to $ircstats{'Server'} but only".
780 " for $format_time. ".
781 "I had to reconnect \002$count\002 times.".
782 " Connectivity: $p %";
786 my $reason = $ircstats{'DisconnectReason'};
787 if (defined $reason) {
788 $reply .= ". I was last disconnected for '$reason'.";
797 if ($message =~ /^statu?s$/i) {
798 my $startString = scalar(gmtime $^T);
799 my $upString = &Time2String(time() - $^T);
800 my ($puser,$psystem,$cuser,$csystem) = times;
801 my $factoids = &countKeys("factoids");
803 foreach (keys %forked) {
804 $forks += scalar keys %{ $forked{$_} };
807 $count{'Commands'} = 0;
808 foreach (keys %cmdstats) {
809 $count{'Commands'} += $cmdstats{$_};
813 "Since $startString, there have been".
814 " \002$count{'Update'}\002 ".
815 &fixPlural("modification", $count{'Update'}).
816 ", \002$count{'Question'}\002 ".
817 &fixPlural("question",$count{'Question'}).
818 ", \002$count{'Dunno'}\002 ".
819 &fixPlural("dunno",$count{'Dunno'}).
820 ", \002$count{'Moron'}\002 ".
821 &fixPlural("moron",$count{'Moron'}).
822 " and \002$count{'Commands'}\002 ".
823 &fixPlural("command",$count{'Commands'}).
824 ". I have been awake for $upString this session, and ".
825 "currently reference \002$factoids\002 factoids. ".
826 "I'm using about \002$memusage\002 ".
827 "kB of memory. With \002$forks\002 active ".
828 &fixPlural("fork",$forks).
829 ". Process time user/system $puser/$psystem child $cuser/$csystem"
834 my %hash = &sqlSelectColHash("stats", "nick,counter",
835 { type => "cmdstats" }, 1);
836 # ORDER won't be retained in a hash
837 # " ORDER BY counter DESC", 1);
840 foreach (keys %hash) {
842 foreach (keys %{ $hash{$i} }) {
843 &DEBUG("cmdstats: $hash{$i}{$_} = $_");
846 &DEBUG("end of cmdstats.");
853 # if ($message =~ /^wantNick(\+)?$/i) {
854 # my ($force) = ($1) ? 1 : 0;
855 # $force = 0 unless (&IsFlag("n"));
857 # # cannot trust Net::IRC's nick() (TimRiker asks why?)
858 # if ($param{'ircNick'} eq $ident) {
859 # &msg($who, "I hope you're right. I'll try anyway.");
860 # &DEBUG("ircNick => $param{'ircNick'}");
861 # &DEBUG("ident => $ident");
864 # # fallback check, I guess. needed?
865 # if (! &IsNickInAnyChan( $param{'ircNick'} ) ) {
866 # my $str = "attempting to change nick to $param{'ircNick'}";
869 # &nick($param{ 'ircNick' });
873 # # idea from dondelecarlo :)
874 # # TODO: use cache{nickserv}
875 # if ($param{'nickServ_pass'}) {
876 # return if ($param{'ircNick'} eq $ident or $force == 0);
878 # &status("someone is using our nick; GHOSTing");
879 # &msg($who, "using GHOST on $param{'ircNick'}.");
880 # &msg("NickServ", "GHOST $param{'ircNick'} $param{'nickServ_pass'}");
882 # $conn->schedule(5, sub {
883 # &status("going to change nick after GHOST.");
884 # &nick( $param{'ircNick'} );