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", 'factinfo', ('CODEREF' => 'factinfo',
21 'Cmdstats' => 'Factoid Info', Module => 'factoids', ) );
22 &addCmdHook("main", 'factstats?', ('CODEREF' => 'factstats',
23 'Cmdstats' => 'Factoid Stats', Help => "factstats",
24 Forker => 1, 'Identifier' => 'factoids', ) );
25 &addCmdHook("main", 'help', ('CODEREF' => 'help',
26 'Cmdstats' => 'Help', ) );
27 &addCmdHook("main", 'karma', ('CODEREF' => 'karma', ) );
28 &addCmdHook("main", 'i?spell', ('CODEREF' => 'ispell',
29 Help => 'spell', Identifier => 'spell', ) );
30 &addCmdHook("main", 'd?nslookup', ('CODEREF' => 'DNS',
31 Help => 'nslookup', Identifier => 'allowDNS',
32 Forker => "NULL", ) );
33 &addCmdHook("main", 'tell|explain', ('CODEREF' => 'tell',
34 Help => 'tell', Identifier => 'allowTelling',
35 Cmdstats => 'Tell') );
36 &addCmdHook("main", 'news', ('CODEREF' => 'News::Parse',
37 Module => 'news', 'Cmdstats' => 'News' ) );
38 &addCmdHook("main", 'countrystats', ('CODEREF' => 'countryStats',
42 &status("CMD: loaded ".scalar(keys %hooks_main)." MAIN command hooks.");
45 ### Start of commands for hooks.
49 my $chan = lc shift(@_);
52 if ($chan eq "") { # all channels.
53 my $i = keys %channels;
54 my $reply = "i am on \002$i\002 ".&fixPlural("channel",$i);
55 my $tucount = 0; # total user count.
56 my $uucount = 0; # unique user count.
60 foreach (sort keys %channels) {
62 &status("chanstats: fe channels: chan == NULL.");
66 next if (/^_default$/);
68 my $str = sprintf("%s (%d)", $_, scalar(keys %{ $channels{$_}{''} }));
71 &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{$a} <=> $new{$b} } 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");
240 if (! -x "/usr/bin/ispell") {
241 &msg($who, "no binary found.");
245 if (!&validExec($query)) {
246 &msg($who,"argument appears to be fuzzy.");
250 my $reply = "I can't find alternate spellings for '$query'";
252 foreach (`/bin/echo '$query' | /usr/bin/ispell -a -S`) {
254 last if !length; # end of query.
256 if (/^\@/) { # intro line.
258 } elsif (/^\*/) { # possibly correct.
259 $reply = "'$query' may be spelled correctly";
261 } elsif (/^\&/) { # possible correction(s).
262 s/^\& (\S+) \d+ \d+: //;
263 my @array = split(/,? /);
265 $reply = "possible spellings for $query: @array";
268 &DEBUG("spell: '+' found => '$_'.");
270 } elsif (/^# (.*?) 0$/) {
274 &DEBUG("spell: unknown: '$_'.");
283 &status("DNS Lookup: $query");
289 my ($target, $tell_obj) = ('','');
290 my $dont_tell_me = 0;
293 ### is this fixed elsewhere?
294 $args =~ s/\s+/ /g; # fix up spaces.
295 $args =~ s/^\s+|\s+$//g; # again.
297 # this one catches most of them
298 if ($args =~ /^(\S+) (-?)about (.*)$/i) {
301 $dont_tell_me = ($2) ? 1 : 0;
303 $tell_obj = $who if ($tell_obj =~ /^(me|myself)$/i);
305 } elsif ($args =~ /^(\S+) where (\S+) can (\S+) (.*)$/i) {
306 # i'm sure this could all be nicely collapsed
311 } elsif ($args =~ /^(\S+) (what|where) (.*?) (is|are)[.?!]*$/i) {
316 $query = "$qWord $verb $tell_obj";
318 } elsif ($args =~ /^(.*?) to (\S+)$/i) {
324 # check target type. Deny channel targets.
325 if ($target !~ /^$mask{nick}$/ or $target =~ /^$mask{chan}$/) {
326 &msg($who,"No, $who, I won't. (target invalid?)");
330 $target = $talkchannel if ($target =~ /^us$/i);
331 $target = $who if ($target =~ /^(me|myself)$/i);
333 &status("tell: target = $target, query = $query");
336 # if ($target !~ /^$mask{chan}$/ and !&IsNickInAnyChan($target)) {
337 # &msg($who, "No, $target is not in any of my chans.");
342 if ($target =~ /^\Q$ident\E$/i) {
343 &msg($who, "Isn't that a bit silly?");
348 my $oldmtype = $msgType;
350 my $result = &doQuestion($tell_obj);
351 # ^ returns '0' if nothing was found.
355 if (!defined $result || $result =~ /^0?$/) {
357 $msgType = "private";
359 # support command redirection.
360 # recursive cmdHooks aswell :)
362 $done++ if &parseCmdHook("main", $tell_obj);
363 $done++ if &parseCmdHook("extra", $tell_obj);
364 $message = $tell_obj;
365 $done++ unless (&Modules());
367 &VERB("tell: setting old values of who and msgType.",2);
369 $msgType = $oldmtype;
372 &msg($who, "told $target about CMD '$tell_obj'");
374 &msg($who, "i dunno what is '$tell_obj'.");
381 &status("tell: <$who> telling $target about $tell_obj.");
382 if ($who ne $target) {
384 &msg($who, "told $target about $tell_obj.");
386 &msg($who, "told $target about $tell_obj ($result)");
389 $reply = "$who wants you to know: $result";
391 $reply = "telling yourself: $result";
394 &msg($target, $reply);
399 my($match, $x, $y, $result);
401 $dns =~ s/^\s+|\s+$//g;
403 if (!defined $dns or $dns =~ /^\s*$/ or $dns =~ / /) {
408 if ($dns =~ /(\d+\.\d+\.\d+\.\d+)/) {
410 &status("DNS query by IP address: $match");
412 $y = pack('C4', split(/\./, $match));
413 $x = (gethostbyaddr($y, &AF_INET));
416 $result = $match." is ".$x unless ($x =~ /^\s*$/);
418 $result = "I can't seem to find that address in DNS";
423 &status("DNS query by name: $dns");
424 $x = join('.',unpack('C4',(gethostbyname($dns))[4]));
427 $result = $dns." is ".$x;
429 $result = "I can\'t find that machine name";
433 &performReply($result);
437 if (exists $cache{countryStats}) {
438 &msg($who,"countrystats is already running!");
447 &help("countrystats");
452 $cache{countryStats}{chan} = $chan;
453 $cache{countryStats}{mtype} = $msgType;
454 $cache{countryStats}{who} = $who;
455 $cache{on_who_Hack} = 1;
458 sub do_countrystats {
459 $chan = $cache{countryStats}{chan};
460 $msgType = $cache{countryStats}{mtype};
461 $who = $cache{countryStats}{who};
465 foreach (keys %{ $cache{nuhInfo} }) {
466 my $h = $cache{nuhInfo}{$_}{Host};
468 if ($h =~ /^.*\.(\D+)$/) { # host
471 $cstats{unresolve}++;
476 foreach (keys %cstats) {
477 $count{ $cstats{$_} }{$_} = 1;
481 foreach (sort {$b <=> $a} keys %count) {
482 my $str = join(", ", sort keys %{ $count{$_} });
483 # push(@list, "$str ($_)");
484 my $perc = sprintf("%.01f", 100 * $_ / $total);
486 push(@list, "$str ($_, $perc %)");
489 # todo: move this into a scheduler like nickometer
490 $msgType = "private";
491 &pSReply( &formListReply(0, "Country Stats ", @list) );
493 delete $cache{countryStats};
494 delete $cache{on_who_Hack};
498 ### amalgamated commands.
503 if ($message =~ /^(asci*|chr) (\d+)$/) {
504 &DEBUG("ascii/chr called ...");
505 return unless (&hasParam("allowConv"));
507 &DEBUG("ascii/chr called");
511 $result = "NULL" if ($arg == 0);
513 &performReply( sprintf("ascii %s is '%s'", $arg, $result) );
519 if ($message =~ /^ord(\s+(.*))$/) {
520 return unless (&hasParam("allowConv"));
524 if (!defined $arg or length $arg != 1) {
529 if (ord($arg) < 32) {
530 $arg = chr(ord($arg) + 64);
531 if ($arg eq chr(64)) {
538 &performReply( sprintf("'%s' is ascii %s", $arg, ord $1) );
543 if ($message =~ /^hex(\s+(.*))?$/i) {
544 return unless (&hasParam("allowConv"));
552 if (length $arg > 80) {
553 &msg($who, "Too long.");
558 foreach (split //, $arg) {
559 $retval .= sprintf(" %X", ord($_));
562 &pSReply("$arg is$retval");
568 if ($message =~ /^crypt(\s+(.*))?$/i) {
569 my @args = split /\s+/, $2;
571 if (!scalar @args or scalar @args > 2) {
576 if (scalar @args == 2) {
577 if (length $args[0] != 2) {
578 &msg($who, "invalid format...");
582 &pSReply( crypt($args[1], $args[0]) );
584 &pSReply( &mkcrypt($args[0]) );
591 if ($message =~ /^(cycle)(\s+(\S+))?$/i) {
592 return unless (&hasFlag("o"));
596 if ($msgType =~ /public/) {
597 $chan = $talkchannel;
598 &DEBUG("cycle: setting chan to '$chan'.");
605 if (&validChan($chan) == 0) {
606 &msg($who,"error: invalid channel \002$chan\002");
610 &msg($chan, "I'm coming back. (courtesy of $who)");
612 ### &ScheduleThis(5, "getNickInUse") if (@_);
613 &status("Schedule rejoin in 5secs to $chan by $who.");
614 $conn->schedule(5, sub { &joinchan($chan); });
620 if ($message =~ /^reload$/i) {
621 return unless (&hasFlag("n"));
623 &status("USER reload $who");
624 &pSReply("reloading...");
626 &pSReply("reloaded.");
631 if ($message =~ /^redir(\s+(.*))?/i) {
632 return unless (&hasFlag("o"));
635 if (!defined $factoid) {
640 my $val = &getFactInfo($factoid, "factoid_value");
641 if (!defined $val or $val eq "") {
642 &msg($who, "error: '$factoid' does not exist.");
645 &DEBUG("val => '$val'.");
646 my @list = &searchTable("factoids", "factoid_key",
647 "factoid_value", "^$val\$");
649 if (scalar @list == 1) {
650 &msg($who, "hrm... '$factoid' is unique.");
653 if (scalar @list > 5) {
654 &msg($who, "A bit too many factoids to be redirected, hey?");
659 &status("Redirect '$factoid' (". ($#list) .")...");
662 next if (/^\Q$factoid\E$/i);
664 &status(" Redirecting '$_'.");
665 my $was = &getFactoid($_);
666 if ($was =~ /<REPLY> see/i) {
667 &status("warn: not redirecting a redirection.");
671 &DEBUG(" was '$was'.");
673 &setFactInfo($x, "factoid_value", "<REPLY> see $factoid");
677 &msg($who, &formListReply(0, "'$factoid' is redirected to by '", @redir));
683 if ($message =~ /^rot13(\s+(.*))?/i) {
686 if (!defined $reply) {
691 $reply =~ y/A-Za-z/N-ZA-Mn-za-m/;
698 if ($message =~ /^cpustats$/i) {
699 if ($^O !~ /linux/) {
700 &ERROR("cpustats: your OS is not supported yet.");
704 ### poor method to get info out of file, please fix.
705 open(STAT,"/proc/$$/stat");
708 my @data = split(/ /, $line);
711 # utime(13) + stime(14).
712 my $cpu_usage = sprintf("%.01f", ($data[13]+$data[14]) / 100 );
713 # cutime(15) + cstime (16).
714 my $cpu_usage2 = sprintf("%.01f", ($data[15]+$data[16]) / 100 );
715 my $time = time() - $^T;
716 my $raw_perc = $cpu_usage*100/$time;
717 my $raw_perc2 = $cpu_usage2*100/$time;
724 $perc = sprintf("%.01f", $raw_perc);
725 $perc2 = sprintf("%.01f", $raw_perc2);
726 $total = sprintf("%.01f", $raw_perc+$raw_perc2);
727 } elsif ($raw_perc > 0.1) {
728 $perc = sprintf("%.02f", $raw_perc);
729 $perc2 = sprintf("%.02f", $raw_perc2);
730 $total = sprintf("%.02f", $raw_perc+$raw_perc2);
732 $perc = sprintf("%.03f", $raw_perc);
733 $perc2 = sprintf("%.03f", $raw_perc2);
734 $total = sprintf("%.03f", $raw_perc+$raw_perc2);
736 $ratio = sprintf("%.01f", 100*$perc/($perc+$perc2) );
738 &pSReply("Total CPU usage: \002$cpu_usage\002 s ... ".
739 "Total used: \002$total\002 % ".
740 "(parent/child ratio: $ratio %)"
747 if ($message =~ /^ircstats?$/i) {
748 $ircstats{'TotalTime'} ||= 0;
749 $ircstats{'OffTime'} ||= 0;
751 my $count = $ircstats{'ConnectCount'};
752 my $format_time = &Time2String(time() - $ircstats{'ConnectTime'});
753 my $total_time = time() - $ircstats{'ConnectTime'} +
754 $ircstats{'TotalTime'};
757 my $connectivity = 100 * ($total_time - $ircstats{'OffTime'}) /
759 my $p = sprintf("%.03f", $connectivity);
760 $p =~ s/(\.\d*)0+$/$1/;
761 if ($p =~ s/\.0$//) {
762 # this should not happen... but why...
767 if ($total_time != (time() - $ircstats{'ConnectTime'}) ) {
768 my $tt_format = &Time2String($total_time);
769 &DEBUG("tt_format => $tt_format");
773 if ($count == 1) { # good.
774 $reply = "I'm connected to $ircstats{'Server'} and have been so".
777 $reply = "Currently I'm hooked up to $ircstats{'Server'} but only".
778 " for $format_time. ".
779 "I had to reconnect \002$count\002 times.".
780 " Connectivity: $p %";
784 my $reason = $ircstats{'DisconnectReason'};
785 if (defined $reason) {
786 $reply .= ". I was last disconnected for '$reason'.";
795 if ($message =~ /^statu?s$/i) {
796 my $startString = scalar(gmtime $^T);
797 my $upString = &Time2String(time() - $^T);
798 my $factoids = &countKeys("factoids");
800 $count{'Commands'} = 0;
801 foreach (keys %cmdstats) {
802 $count{'Commands'} += $cmdstats{$_};
806 "Since $startString, there have been".
807 " \002$count{'Update'}\002 ".
808 &fixPlural("modification", $count{'Update'}).
809 ", \002$count{'Question'}\002 ".
810 &fixPlural("question",$count{'Question'}).
811 ", \002$count{'Dunno'}\002 ".
812 &fixPlural("dunno",$count{'Dunno'}).
813 ", \002$count{'Moron'}\002 ".
814 &fixPlural("moron",$count{'Moron'}).
815 " and \002$count{'Commands'}\002 ".
816 &fixPlural("command",$count{'Commands'}).
817 ". I have been awake for $upString this session, and ".
818 "currently reference \002$factoids\002 factoids. ".
819 "I'm using about \002$memusage\002 ".
825 my %hash = &sqlSelectColHash("stats", "nick,counter",
826 { type => "cmdstats" }, 1);
827 # ORDER won't be retained in a hash
828 # " ORDER BY counter DESC", 1);
831 foreach (keys %hash) {
833 foreach (keys %{ $hash{$i} }) {
834 &DEBUG("cmdstats: $hash{$i}{$_} = $_");
837 &DEBUG("end of cmdstats.");
844 if ($message =~ /^wantNick(\+)?$/i) {
845 my ($force) = ($1) ? 1 : 0;
846 $force = 0 unless (&IsFlag("n"));
848 # cannot trust Net::IRC's nick()
849 if ($param{'ircNick'} eq $ident) {
850 &msg($who, "I hope you're right. I'll try anyway.");
851 &DEBUG("ircNick => $param{'ircNick'}");
852 &DEBUG("ident => $ident");
855 # fallback check, I guess. needed?
856 if (! &IsNickInAnyChan( $param{'ircNick'} ) ) {
857 my $str = "attempting to change nick to $param{'ircNick'}";
860 &nick($param{ 'ircNick' });
864 # idea from dondelecarlo :)
865 # todo: use cache{nickserv}
866 if ($param{'nickServ_pass'}) {
867 return if ($param{'ircNick'} eq $ident or $force == 0);
869 &status("someone is using our nick; GHOSTing");
870 &msg($who, "using GHOST on $param{'ircNick'}.");
871 &msg("NickServ", "GHOST $param{'ircNick'} $param{'nickServ_pass'}");
873 $conn->schedule(5, sub {
874 &status("going to change nick after GHOST.");
875 &nick( $param{'ircNick'} );