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", 'tell|explain', ('CODEREF' => 'tell',
30 Help => 'tell', Identifier => 'allowTelling',
31 Cmdstats => 'Tell') );
32 &addCmdHook("main", 'News', ('CODEREF' => 'News::Parse',
33 Module => 'News', 'Cmdstats' => 'News' ) );
34 &addCmdHook("main", 'countrystats', ('CODEREF' => 'countryStats',
38 &status("CMD: loaded ".scalar(keys %hooks_main)." MAIN command hooks.");
41 ### Start of commands for hooks.
45 my $chan = lc shift(@_);
48 if ($chan eq "") { # all channels.
49 my $i = keys %channels;
50 my $reply = "i am on \002$i\002 ".&fixPlural("channel",$i);
51 my $tucount = 0; # total user count.
52 my $uucount = 0; # unique user count.
56 foreach (sort keys %channels) {
57 if ( /^\s*$/ or / / ) {
58 &status("chanstats: fe channels: chan == NULL.");
62 next if (/^_default$/);
64 my $str = sprintf("%s(%d)", $_, scalar(keys %{ $channels{$_}{''} }));
67 &performStrictReply($reply.": ".join(', ', @array));
71 foreach $chan (keys %channels) {
72 $tucount += scalar(keys %{ $channels{$chan}{''} });
75 ### unique user count.
77 foreach $chan (keys %channels) {
79 foreach $nick (keys %{ $channels{$chan}{''} }) {
80 next if (grep /^\Q$nick\E$/, @nicks);
85 &::DEBUG(join ":", @nicks);
87 if (scalar @nicks != $uucount) {
88 &DEBUG("nicks != uucount...");
91 my $chans = scalar(keys %channels);
93 "i've cached \002$tucount\002 ". &fixPlural("user",$tucount).
94 ", \002$uucount\002 unique ". &fixPlural("user",$uucount).
95 ", distributed over \002$chans\002 ".
96 &fixPlural("channel", $chans)."."
104 if (&validChan($chan) == 0) {
105 &msg($who,"error: invalid channel \002$chan\002");
111 foreach (sort keys %{ $chanstats{$chan} }) {
112 my $int = $chanstats{$chan}{$_};
115 push(@array, "\002$int\002 ". &fixPlural($_,$int));
117 my $reply = "On \002$chan\002, there ".
118 &fixPlural("has",scalar(@array)). " been ".
121 # Step 1b: check channel inconstencies.
122 $chanstats{$chan}{'Join'} ||= 0;
123 $chanstats{$chan}{'SignOff'} ||= 0;
124 $chanstats{$chan}{'Part'} ||= 0;
126 my $delta_stats = $chanstats{$chan}{'Join'}
127 - $chanstats{$chan}{'SignOff'}
128 - $chanstats{$chan}{'Part'};
131 my $total = scalar(keys %{ $channels{$chan}{''} });
132 &status("chaninfo: join ~= signoff + part (drift of $delta_stats < $total).");
134 if ($delta_stats > $total) {
135 &ERROR("chaninfo: delta_stats exceeds total users.");
142 foreach ("v","o","") {
143 my $int = scalar(keys %{ $channels{$chan}{$_} });
146 $type = "Voice" if ($_ eq "v");
147 $type = "Opped" if ($_ eq "o");
148 $type = "Total" if ($_ eq "");
150 push(@array,"\002$int\002 $type");
152 $reply .= ". At the moment, ". &IJoin(@array);
156 foreach (keys %userstats) {
157 next unless (exists $userstats{$_}{'Count'});
158 if ($userstats{$_}{'Count'} =~ /^\D+$/) {
159 &WARN("userstats{$_}{Count} is non-digit.");
163 $new{$_} = $userstats{$_}{'Count'};
166 # TODO: show top 3 with percentages?
167 my($count) = (sort { $new{$b} <=> $new{$a} } keys %new)[0];
169 $reply .= ". \002$count\002 has said the most with a total of \002$new{$count}\002 messages";
171 &performStrictReply("$reply.");
174 # Command statistics.
178 if (!scalar(keys %cmdstats)) {
179 &performReply("no-one has run any commands yet");
184 foreach (keys %cmdstats) {
185 $countstats{ $cmdstats{$_} }{$_} = 1;
188 foreach (sort {$b <=> $a} keys %countstats) {
192 foreach (keys %{ $countstats{$int} }) {
193 push(@array, "\002$int\002 of $_");
196 &performStrictReply("command usage include ". &IJoin(@array).".");
199 # Factoid extension info. xk++
201 my $faqtoid = lc shift(@_);
204 if ($faqtoid =~ /^\-(\S+)(\s+(.*))$/) {
205 &msg($who,"error: individual factoid info queries not supported as yet.");
206 &msg($who,"it's possible that the factoid mistakenly begins with '-'.");
213 &CmdFactInfo($faqtoid, $query);
217 my $type = shift(@_);
219 &Forker("factoids", sub {
220 &performStrictReply( &CmdFactStats($type) );
225 my $target = lc( shift || $who );
226 my $karma = &sqlSelect("stats", "counter",
227 { nick => $target, type => "karma" }) || 0;
230 &performStrictReply("$target has karma of $karma");
232 &performStrictReply("$target has neutral karma");
238 my ($target, $tell_obj) = ('','');
239 my $dont_tell_me = 0;
242 ### is this fixed elsewhere?
243 $args =~ s/\s+/ /g; # fix up spaces.
244 $args =~ s/^\s+|\s+$//g; # again.
246 # this one catches most of them
247 if ($args =~ /^(\S+) (-?)about (.*)$/i) {
250 $dont_tell_me = ($2) ? 1 : 0;
252 $tell_obj = $who if ($tell_obj =~ /^(me|myself)$/i);
254 } elsif ($args =~ /^(\S+) where (\S+) can (\S+) (.*)$/i) {
255 # i'm sure this could all be nicely collapsed
260 } elsif ($args =~ /^(\S+) (what|where) (.*?) (is|are)[.?!]*$/i) {
265 $query = "$qWord $verb $tell_obj";
267 } elsif ($args =~ /^(.*?) to (\S+)$/i) {
273 # check target type. Deny channel targets.
274 if ($target !~ /^$mask{nick}$/ or $target =~ /^$mask{chan}$/) {
275 &msg($who,"No, $who, I won't. (target invalid?)");
279 $target = $talkchannel if ($target =~ /^us$/i);
280 $target = $who if ($target =~ /^(me|myself)$/i);
282 &status("tell: target = $target, query = $query");
285 # if ($target !~ /^$mask{chan}$/ and !&IsNickInAnyChan($target)) {
286 # &msg($who, "No, $target is not in any of my chans.");
291 if ($target =~ /^\Q$ident\E$/i) {
292 &msg($who, "Isn't that a bit silly?");
297 my $oldmtype = $msgType;
299 my $result = &doQuestion($tell_obj);
300 # ^ returns '0' if nothing was found.
304 if (!defined $result || $result =~ /^0?$/) {
306 $msgType = "private";
308 # support command redirection.
309 # recursive cmdHooks aswell :)
311 $done++ if &parseCmdHook("main", $tell_obj);
312 $done++ if &parseCmdHook("extra", $tell_obj);
313 $message = $tell_obj;
314 $done++ unless (&Modules());
316 &VERB("tell: setting old values of who and msgType.",2);
318 $msgType = $oldmtype;
321 &msg($who, "told $target about CMD '$tell_obj'");
323 &msg($who, "i dunno what is '$tell_obj'.");
330 &status("tell: <$who> telling $target about $tell_obj.");
331 if ($who ne $target) {
333 &msg($who, "told $target about $tell_obj.");
335 &msg($who, "told $target about $tell_obj ($result)");
338 $reply = "$who wants you to know: $result";
340 $reply = "telling yourself: $result";
343 &msg($target, $reply);
347 if (exists $cache{countryStats}) {
348 &msg($who,"countrystats is already running!");
357 &help("countrystats");
362 $cache{countryStats}{chan} = $chan;
363 $cache{countryStats}{mtype} = $msgType;
364 $cache{countryStats}{who} = $who;
365 $cache{on_who_Hack} = 1;
368 sub do_countrystats {
369 $chan = $cache{countryStats}{chan};
370 $msgType = $cache{countryStats}{mtype};
371 $who = $cache{countryStats}{who};
375 foreach (keys %{ $cache{nuhInfo} }) {
376 my $h = $cache{nuhInfo}{$_}{Host};
378 if ($h =~ /^.*\.(\D+)$/) { # host
381 $cstats{unresolve}++;
386 foreach (keys %cstats) {
387 $count{ $cstats{$_} }{$_} = 1;
391 foreach (sort {$b <=> $a} keys %count) {
392 my $str = join(", ", sort keys %{ $count{$_} });
393 # push(@list, "$str ($_)");
394 my $perc = sprintf("%.01f", 100 * $_ / $total);
396 push(@list, "$str ($_, $perc %)");
399 # TODO: move this into a scheduler
400 $msgType = "private";
401 &performStrictReply( &formListReply(0, "Country Stats ", @list) );
403 delete $cache{countryStats};
404 delete $cache{on_who_Hack};
408 ### amalgamated commands.
413 if ($message =~ /^(asci*|chr) (\d+)$/) {
414 &DEBUG("ascii/chr called ...");
415 return unless (&IsChanConfOrWarn("allowConv"));
417 &DEBUG("ascii/chr called");
421 $result = "NULL" if ($arg == 0);
423 &performReply( sprintf("ascii %s is '%s'", $arg, $result) );
429 if ($message =~ /^ord(\s+(.*))$/) {
430 return unless (&IsChanConfOrWarn("allowConv"));
434 if (!defined $arg or length $arg != 1) {
439 if (ord($arg) < 32) {
440 $arg = chr(ord($arg) + 64);
441 if ($arg eq chr(64)) {
448 &performReply( sprintf("'%s' is ascii %s", $arg, ord $arg) );
453 if ($message =~ /^hex(\s+(.*))?$/i) {
454 return unless (&IsChanConfOrWarn("allowConv"));
462 if (length $arg > 80) {
463 &msg($who, "Too long.");
468 foreach (split //, $arg) {
469 $retval .= sprintf(" %X", ord($_));
472 &performStrictReply("$arg is$retval");
478 if ($message =~ /^crypt(\s+(.*))?$/i) {
479 my @args = split /\s+/, $2;
481 if (!scalar @args or scalar @args > 2) {
486 if (scalar @args == 2) {
487 # disable cause $1$ will use md5
488 # if (length $args[0] != 2) {
489 # &msg($who, "invalid format...");
493 &performStrictReply( crypt($args[1], $args[0]) );
495 &performStrictReply( &mkcrypt($args[0]) );
502 if ($message =~ /^(cycle)(\s+(\S+))?$/i) {
503 return unless (&hasFlag("o"));
507 if ($msgType =~ /public/) {
508 $chan = $talkchannel;
509 &DEBUG("cycle: setting chan to '$chan'.");
516 if (&validChan($chan) == 0) {
517 &msg($who,"error: invalid channel \002$chan\002");
521 &msg($chan, "I'm coming back. (courtesy of $who)");
523 ### &ScheduleThis(5, "getNickInUse") if (@_);
524 &status("Schedule rejoin in 5secs to $chan by $who.");
525 $conn->schedule(5, sub { &joinchan($chan); });
531 if ($message =~ /^reload$/i) {
532 return unless (&hasFlag("n"));
534 &status("USER reload $who");
535 &performStrictReply("reloading...");
536 my $modules = &reloadAllModules();
537 &performStrictReply("reloaded:$modules");
542 if ($message =~ /^redir(\s+(.*))?/i) {
543 return unless (&hasFlag("o"));
546 if (!defined $factoid) {
551 my $val = &getFactInfo($factoid, "factoid_value");
552 if (!defined $val or $val eq "") {
553 &msg($who, "error: '$factoid' does not exist.");
556 &DEBUG("val => '$val'.");
557 my @list = &searchTable("factoids", "factoid_key",
558 "factoid_value", "^$val\$");
560 if (scalar @list == 1) {
561 &msg($who, "hrm... '$factoid' is unique.");
564 if (scalar @list > 5) {
565 &msg($who, "A bit too many factoids to be redirected, hey?");
570 &status("Redirect '$factoid' (". ($#list) .")...");
573 next if (/^\Q$factoid\E$/i);
575 &status(" Redirecting '$_'.");
576 my $was = &getFactoid($_);
577 if ($was =~ /<REPLY> see/i) {
578 &status("warn: not redirecting a redirection.");
582 &DEBUG(" was '$was'.");
584 &setFactInfo($x, "factoid_value", "<REPLY> see $factoid");
588 &msg($who, &formListReply(0, "'$factoid' is redirected to by '", @redir));
594 if ($message =~ /^rot13(\s+(.*))?/i) {
597 if (!defined $reply) {
602 $reply =~ y/A-Za-z/N-ZA-Mn-za-m/;
603 &performStrictReply($reply);
609 if ($message =~ /^cpustats$/i) {
610 if ($^O !~ /linux/) {
611 &ERROR("cpustats: your OS is not supported yet.");
615 ### poor method to get info out of file, please fix.
616 open(STAT,"/proc/$$/stat");
619 my @data = split(/ /, $line);
622 # utime(13) + stime(14).
623 my $cpu_usage = sprintf("%.01f", ($data[13]+$data[14]) / 100 );
624 # cutime(15) + cstime (16).
625 my $cpu_usage2 = sprintf("%.01f", ($data[15]+$data[16]) / 100 );
626 my $time = time() - $^T;
627 my $raw_perc = $cpu_usage*100/$time;
628 my $raw_perc2 = $cpu_usage2*100/$time;
635 $perc = sprintf("%.01f", $raw_perc);
636 $perc2 = sprintf("%.01f", $raw_perc2);
637 $total = sprintf("%.01f", $raw_perc+$raw_perc2);
638 } elsif ($raw_perc > 0.1) {
639 $perc = sprintf("%.02f", $raw_perc);
640 $perc2 = sprintf("%.02f", $raw_perc2);
641 $total = sprintf("%.02f", $raw_perc+$raw_perc2);
643 $perc = sprintf("%.03f", $raw_perc);
644 $perc2 = sprintf("%.03f", $raw_perc2);
645 $total = sprintf("%.03f", $raw_perc+$raw_perc2);
647 $ratio = sprintf("%.01f", 100*$perc/($perc+$perc2) );
649 &performStrictReply("Total CPU usage: \002$cpu_usage\002 s ... ".
650 "Total used: \002$total\002 % ".
651 "(parent/child ratio: $ratio %)"
658 if ($message =~ /^ircstats?$/i) {
659 $ircstats{'TotalTime'} ||= 0;
660 $ircstats{'OffTime'} ||= 0;
662 my $count = $ircstats{'ConnectCount'};
663 my $format_time = &Time2String(time() - $ircstats{'ConnectTime'});
664 my $total_time = time() - $ircstats{'ConnectTime'} +
665 $ircstats{'TotalTime'};
668 my $connectivity = 100 * ($total_time - $ircstats{'OffTime'}) /
670 my $p = sprintf("%.03f", $connectivity);
671 $p =~ s/(\.\d*)0+$/$1/;
672 if ($p =~ s/\.0$//) {
673 # this should not happen... but why...
678 if ($total_time != (time() - $ircstats{'ConnectTime'}) ) {
679 my $tt_format = &Time2String($total_time);
680 &DEBUG("tt_format => $tt_format");
684 if ($count == 1) { # good.
685 $reply = "I'm connected to $ircstats{'Server'} and have been so".
688 $reply = "Currently I'm hooked up to $ircstats{'Server'} but only".
689 " for $format_time. ".
690 "I had to reconnect \002$count\002 times.".
691 " Connectivity: $p %";
695 my $reason = $ircstats{'DisconnectReason'};
696 if (defined $reason) {
697 $reply .= ". I was last disconnected for '$reason'.";
700 &performStrictReply($reply);
706 if ($message =~ /^statu?s$/i) {
707 my $startString = scalar(gmtime $^T);
708 my $upString = &Time2String(time() - $^T);
709 my ($puser,$psystem,$cuser,$csystem) = times;
710 my $factoids = &countKeys("factoids");
712 foreach (keys %forked) {
713 $forks += scalar keys %{ $forked{$_} };
716 $count{'Commands'} = 0;
717 foreach (keys %cmdstats) {
718 $count{'Commands'} += $cmdstats{$_};
722 "Since $startString, there have been".
723 " \002$count{'Update'}\002 ".
724 &fixPlural("modification", $count{'Update'}).
725 ", \002$count{'Question'}\002 ".
726 &fixPlural("question",$count{'Question'}).
727 ", \002$count{'Dunno'}\002 ".
728 &fixPlural("dunno",$count{'Dunno'}).
729 ", \002$count{'Moron'}\002 ".
730 &fixPlural("moron",$count{'Moron'}).
731 " and \002$count{'Commands'}\002 ".
732 &fixPlural("command",$count{'Commands'}).
733 ". I have been awake for $upString this session, and ".
734 "currently reference \002$factoids\002 factoids. ".
735 "I'm using about \002$memusage\002 ".
736 "kB of memory. With \002$forks\002 active ".
737 &fixPlural("fork",$forks).
738 ". Process time user/system $puser/$psystem child $cuser/$csystem"
743 my %hash = &sqlSelectColHash("stats", "nick,counter",
744 { type => "cmdstats" }, 1);
745 # ORDER won't be retained in a hash
746 # " ORDER BY counter DESC", 1);
749 foreach (keys %hash) {
751 foreach (keys %{ $hash{$i} }) {
752 &DEBUG("cmdstats: $hash{$i}{$_} = $_");
755 &DEBUG("end of cmdstats.");
762 # FIXME does not try to get nick "back", just switches nicks
763 if ($message =~ /^wantNick\s(.*)?$/i) {
764 return unless (&hasFlag("o"));
765 my $wantnick = lc $1;
766 my $mynick = $conn->nick();
768 if ($mynick eq $wantnick) {
769 &msg($who, "I hope you're right. I'll try anyway (mynick=$mynick, wantnick=$wantnick).");
772 # fallback check, I guess. needed?
773 if (! &IsNickInAnyChan( $wantnick ) ) {
774 my $str = "attempting to change nick from $mynick to $wantnick";
781 # idea from dondelecarlo :)
782 # TODO: use cache{nickserv}
783 if ($param{'nickServ_pass'}) {
784 my $str = "someone is using nick $wantnick; GHOSTing";
787 &msg("NickServ", "GHOST $wantnick $param{'nickServ_pass'}");
789 $conn->schedule(5, sub {
790 &status("going to change nick from $mynick to $wantnick after GHOST.");