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'm 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));
70 foreach $chan (keys %channels) {
71 $tucount += scalar(keys %{ $channels{$chan}{''} });
74 ### unique user count.
76 foreach $chan (keys %channels) {
78 foreach $nick (keys %{ $channels{$chan}{''} }) {
82 $uucount = scalar(keys %nicks);
84 my $chans = scalar(keys %channels);
86 "i've cached \002$tucount\002 ". &fixPlural("user",$tucount).
87 ", \002$uucount\002 unique ". &fixPlural("user",$uucount).
88 ", distributed over \002$chans\002 ".
89 &fixPlural("channel", $chans)."."
98 if (&validChan($chan) == 0) {
99 &msg($who,"error: invalid channel \002$chan\002");
105 foreach (sort keys %{ $chanstats{$chan} }) {
106 my $int = $chanstats{$chan}{$_};
109 push(@array, "\002$int\002 ". &fixPlural($_,$int));
111 my $reply = "On \002$chan\002, there ".
112 &fixPlural("has",scalar(@array)). " been ".
115 # Step 1b: check channel inconstencies.
116 $chanstats{$chan}{'Join'} ||= 0;
117 $chanstats{$chan}{'SignOff'} ||= 0;
118 $chanstats{$chan}{'Part'} ||= 0;
120 my $delta_stats = $chanstats{$chan}{'Join'}
121 - $chanstats{$chan}{'SignOff'}
122 - $chanstats{$chan}{'Part'};
125 my $total = scalar(keys %{ $channels{$chan}{''} });
126 &status("chaninfo: join ~= signoff + part (drift of $delta_stats < $total).");
128 if ($delta_stats > $total) {
129 &ERROR("chaninfo: delta_stats exceeds total users.");
136 foreach ("v","o","") {
137 my $int = scalar(keys %{ $channels{$chan}{$_} });
140 $type = "Voice" if ($_ eq "v");
141 $type = "Opped" if ($_ eq "o");
142 $type = "Total" if ($_ eq "");
144 push(@array,"\002$int\002 $type");
146 $reply .= ". At the moment, ". &IJoin(@array);
150 foreach (keys %userstats) {
151 next unless (exists $userstats{$_}{'Count'});
152 if ($userstats{$_}{'Count'} =~ /^\D+$/) {
153 &WARN("userstats{$_}{Count} is non-digit.");
157 $new{$_} = $userstats{$_}{'Count'};
160 # TODO: show top 3 with percentages?
161 my($count) = (sort { $new{$b} <=> $new{$a} } keys %new)[0];
163 $reply .= ". \002$count\002 has said the most with a total of \002$new{$count}\002 messages";
165 &performStrictReply("$reply.");
168 # Command statistics.
172 if (!scalar(keys %cmdstats)) {
173 &performReply("no-one has run any commands yet");
178 foreach (keys %cmdstats) {
179 $countstats{ $cmdstats{$_} }{$_} = 1;
182 foreach (sort {$b <=> $a} keys %countstats) {
186 foreach (keys %{ $countstats{$int} }) {
187 push(@array, "\002$int\002 of $_");
190 &performStrictReply("command usage include ". &IJoin(@array).".");
193 # Factoid extension info. xk++
195 my $faqtoid = lc shift(@_);
198 if ($faqtoid =~ /^\-(\S+)(\s+(.*))$/) {
199 &msg($who,"error: individual factoid info queries not supported as yet.");
200 &msg($who,"it's possible that the factoid mistakenly begins with '-'.");
207 &CmdFactInfo($faqtoid, $query);
211 my $type = shift(@_);
213 &Forker("factoids", sub {
214 &performStrictReply( &CmdFactStats($type) );
219 my $target = lc( shift || $who );
220 my $karma = &sqlSelect("stats", "counter",
221 { nick => $target, type => "karma" }) || 0;
224 &performStrictReply("$target has karma of $karma");
226 &performStrictReply("$target has neutral karma");
232 my ($target, $tell_obj) = ('','');
233 my $dont_tell_me = 0;
236 ### is this fixed elsewhere?
237 $args =~ s/\s+/ /g; # fix up spaces.
238 $args =~ s/^\s+|\s+$//g; # again.
240 # this one catches most of them
241 if ($args =~ /^(\S+) (-?)about (.*)$/i) {
244 $dont_tell_me = ($2) ? 1 : 0;
246 $tell_obj = $who if ($tell_obj =~ /^(me|myself)$/i);
248 } elsif ($args =~ /^(\S+) where (\S+) can (\S+) (.*)$/i) {
249 # i'm sure this could all be nicely collapsed
254 } elsif ($args =~ /^(\S+) (what|where) (.*?) (is|are)[.?!]*$/i) {
259 $query = "$qWord $verb $tell_obj";
261 } elsif ($args =~ /^(.*?) to (\S+)$/i) {
267 # check target type. Deny channel targets.
268 if ($target !~ /^$mask{nick}$/ or $target =~ /^$mask{chan}$/) {
269 &msg($who,"No, $who, I won't. (target invalid?)");
273 $target = $talkchannel if ($target =~ /^us$/i);
274 $target = $who if ($target =~ /^(me|myself)$/i);
276 &status("tell: target = $target, query = $query");
279 # if ($target !~ /^$mask{chan}$/ and !&IsNickInAnyChan($target)) {
280 # &msg($who, "No, $target is not in any of my chans.");
285 if ($target =~ /^\Q$ident\E$/i) {
286 &msg($who, "Isn't that a bit silly?");
291 my $oldmtype = $msgType;
293 my $result = &doQuestion($tell_obj);
294 # ^ returns '0' if nothing was found.
298 if (!defined $result || $result =~ /^0?$/) {
300 $msgType = "private";
302 # support command redirection.
303 # recursive cmdHooks aswell :)
305 $done++ if &parseCmdHook("main", $tell_obj);
306 $done++ if &parseCmdHook("extra", $tell_obj);
307 $message = $tell_obj;
308 $done++ unless (&Modules());
310 &VERB("tell: setting old values of who and msgType.",2);
312 $msgType = $oldmtype;
315 &msg($who, "told $target about CMD '$tell_obj'");
317 &msg($who, "i dunno what is '$tell_obj'.");
324 &status("tell: <$who> telling $target about $tell_obj.");
325 if ($who ne $target) {
327 &msg($who, "told $target about $tell_obj.");
329 &msg($who, "told $target about $tell_obj ($result)");
332 $reply = "$who wants you to know: $result";
334 $reply = "telling yourself: $result";
337 &msg($target, $reply);
341 if (exists $cache{countryStats}) {
342 &msg($who,"countrystats is already running!");
351 &help("countrystats");
356 $cache{countryStats}{chan} = $chan;
357 $cache{countryStats}{mtype} = $msgType;
358 $cache{countryStats}{who} = $who;
359 $cache{on_who_Hack} = 1;
362 sub do_countrystats {
363 $chan = $cache{countryStats}{chan};
364 $msgType = $cache{countryStats}{mtype};
365 $who = $cache{countryStats}{who};
369 foreach (keys %{ $cache{nuhInfo} }) {
370 my $h = $cache{nuhInfo}{$_}{Host};
372 if ($h =~ /^.*\.(\D+)$/) { # host
375 $cstats{unresolve}++;
380 foreach (keys %cstats) {
381 $count{ $cstats{$_} }{$_} = 1;
385 foreach (sort {$b <=> $a} keys %count) {
386 my $str = join(", ", sort keys %{ $count{$_} });
387 # push(@list, "$str ($_)");
388 my $perc = sprintf("%.01f", 100 * $_ / $total);
390 push(@list, "$str ($_, $perc %)");
393 # TODO: move this into a scheduler
394 $msgType = "private";
395 &performStrictReply( &formListReply(0, "Country Stats ", @list) );
397 delete $cache{countryStats};
398 delete $cache{on_who_Hack};
402 ### amalgamated commands.
407 if ($message =~ /^(asci*|chr) (\d+)$/) {
408 &DEBUG("ascii/chr called ...");
409 return unless (&IsChanConfOrWarn("allowConv"));
411 &DEBUG("ascii/chr called");
415 $result = "NULL" if ($arg == 0);
417 &performReply( sprintf("ascii %s is '%s'", $arg, $result) );
423 if ($message =~ /^ord(\s+(.*))$/) {
424 return unless (&IsChanConfOrWarn("allowConv"));
428 if (!defined $arg or length $arg != 1) {
433 if (ord($arg) < 32) {
434 $arg = chr(ord($arg) + 64);
435 if ($arg eq chr(64)) {
442 &performReply( sprintf("'%s' is ascii %s", $arg, ord $arg) );
447 if ($message =~ /^hex(\s+(.*))?$/i) {
448 return unless (&IsChanConfOrWarn("allowConv"));
456 if (length $arg > 80) {
457 &msg($who, "Too long.");
462 foreach (split //, $arg) {
463 $retval .= sprintf(" %X", ord($_));
466 &performStrictReply("$arg is$retval");
472 if ($message =~ /^crypt(\s+(.*))?$/i) {
473 my @args = split /\s+/, $2;
475 if (!scalar @args or scalar @args > 2) {
480 if (scalar @args == 2) {
481 # disable cause $1$ will use md5
482 # if (length $args[0] != 2) {
483 # &msg($who, "invalid format...");
487 &performStrictReply( crypt($args[1], $args[0]) );
489 &performStrictReply( &mkcrypt($args[0]) );
496 if ($message =~ /^(cycle)(\s+(\S+))?$/i) {
497 return unless (&hasFlag("o"));
501 if ($msgType =~ /public/) {
502 $chan = $talkchannel;
503 &DEBUG("cycle: setting chan to '$chan'.");
510 if (&validChan($chan) == 0) {
511 &msg($who,"error: invalid channel \002$chan\002");
515 &msg($chan, "I'm coming back. (courtesy of $who)");
517 ### &ScheduleThis(5, "getNickInUse") if (@_);
518 &status("Schedule rejoin in 5secs to $chan by $who.");
519 $conn->schedule(5, sub { &joinchan($chan); });
525 if ($message =~ /^reload$/i) {
526 return unless (&hasFlag("n"));
528 &status("USER reload $who");
529 &performStrictReply("reloading...");
530 my $modules = &reloadAllModules();
531 &performStrictReply("reloaded:$modules");
536 if ($message =~ /^redir(\s+(.*))?/i) {
537 return unless (&hasFlag("o"));
540 if (!defined $factoid) {
545 my $val = &getFactInfo($factoid, "factoid_value");
546 if (!defined $val or $val eq "") {
547 &msg($who, "error: '$factoid' does not exist.");
550 &DEBUG("val => '$val'.");
551 my @list = &searchTable("factoids", "factoid_key",
552 "factoid_value", "^$val\$");
554 if (scalar @list == 1) {
555 &msg($who, "hrm... '$factoid' is unique.");
558 if (scalar @list > 5) {
559 &msg($who, "A bit too many factoids to be redirected, hey?");
564 &status("Redirect '$factoid' (". ($#list) .")...");
567 next if (/^\Q$factoid\E$/i);
569 &status(" Redirecting '$_'.");
570 my $was = &getFactoid($_);
571 if ($was =~ /<REPLY> see/i) {
572 &status("warn: not redirecting a redirection.");
576 &DEBUG(" was '$was'.");
578 &setFactInfo($x, "factoid_value", "<REPLY> see $factoid");
582 &msg($who, &formListReply(0, "'$factoid' is redirected to by '", @redir));
588 if ($message =~ /^rot13(\s+(.*))?/i) {
591 if (!defined $reply) {
596 $reply =~ y/A-Za-z/N-ZA-Mn-za-m/;
597 &performStrictReply($reply);
603 if ($message =~ /^cpustats$/i) {
604 if ($^O !~ /linux/) {
605 &ERROR("cpustats: your OS is not supported yet.");
609 ### poor method to get info out of file, please fix.
610 open(STAT,"/proc/$$/stat");
613 my @data = split(/ /, $line);
616 # utime(13) + stime(14).
617 my $cpu_usage = sprintf("%.01f", ($data[13]+$data[14]) / 100 );
618 # cutime(15) + cstime (16).
619 my $cpu_usage2 = sprintf("%.01f", ($data[15]+$data[16]) / 100 );
620 my $time = time() - $^T;
621 my $raw_perc = $cpu_usage*100/$time;
622 my $raw_perc2 = $cpu_usage2*100/$time;
629 $perc = sprintf("%.01f", $raw_perc);
630 $perc2 = sprintf("%.01f", $raw_perc2);
631 $total = sprintf("%.01f", $raw_perc+$raw_perc2);
632 } elsif ($raw_perc > 0.1) {
633 $perc = sprintf("%.02f", $raw_perc);
634 $perc2 = sprintf("%.02f", $raw_perc2);
635 $total = sprintf("%.02f", $raw_perc+$raw_perc2);
637 $perc = sprintf("%.03f", $raw_perc);
638 $perc2 = sprintf("%.03f", $raw_perc2);
639 $total = sprintf("%.03f", $raw_perc+$raw_perc2);
641 $ratio = sprintf("%.01f", 100*$perc/($perc+$perc2) );
643 &performStrictReply("Total CPU usage: \002$cpu_usage\002 s ... ".
644 "Total used: \002$total\002 % ".
645 "(parent/child ratio: $ratio %)"
652 if ($message =~ /^ircstats?$/i) {
653 $ircstats{'TotalTime'} ||= 0;
654 $ircstats{'OffTime'} ||= 0;
656 my $count = $ircstats{'ConnectCount'};
657 my $format_time = &Time2String(time() - $ircstats{'ConnectTime'});
658 my $total_time = time() - $ircstats{'ConnectTime'} +
659 $ircstats{'TotalTime'};
662 my $connectivity = 100 * ($total_time - $ircstats{'OffTime'}) /
664 my $p = sprintf("%.03f", $connectivity);
665 $p =~ s/(\.\d*)0+$/$1/;
666 if ($p =~ s/\.0$//) {
667 # this should not happen... but why...
672 if ($total_time != (time() - $ircstats{'ConnectTime'}) ) {
673 my $tt_format = &Time2String($total_time);
674 &DEBUG("tt_format => $tt_format");
678 if ($count == 1) { # good.
679 $reply = "I'm connected to $ircstats{'Server'} and have been so".
682 $reply = "Currently I'm hooked up to $ircstats{'Server'} but only".
683 " for $format_time. ".
684 "I had to reconnect \002$count\002 times.".
685 " Connectivity: $p %";
689 my $reason = $ircstats{'DisconnectReason'};
690 if (defined $reason) {
691 $reply .= ". I was last disconnected for '$reason'.";
694 &performStrictReply($reply);
700 if ($message =~ /^statu?s$/i) {
701 my $startString = scalar(gmtime $^T);
702 my $upString = &Time2String(time() - $^T);
703 my ($puser,$psystem,$cuser,$csystem) = times;
704 my $factoids = &countKeys("factoids");
706 foreach (keys %forked) {
707 $forks += scalar keys %{ $forked{$_} };
710 $count{'Commands'} = 0;
711 foreach (keys %cmdstats) {
712 $count{'Commands'} += $cmdstats{$_};
716 "Since $startString, there have been".
717 " \002$count{'Update'}\002 ".
718 &fixPlural("modification", $count{'Update'}).
719 ", \002$count{'Question'}\002 ".
720 &fixPlural("question",$count{'Question'}).
721 ", \002$count{'Dunno'}\002 ".
722 &fixPlural("dunno",$count{'Dunno'}).
723 ", \002$count{'Moron'}\002 ".
724 &fixPlural("moron",$count{'Moron'}).
725 " and \002$count{'Commands'}\002 ".
726 &fixPlural("command",$count{'Commands'}).
727 ". I have been awake for $upString this session, and ".
728 "currently reference \002$factoids\002 factoids. ".
729 "I'm using about \002$memusage\002 ".
730 "kB of memory. With \002$forks\002 active ".
731 &fixPlural("fork",$forks).
732 ". Process time user/system $puser/$psystem child $cuser/$csystem"
737 my %hash = &sqlSelectColHash("stats", "nick,counter",
738 { type => "cmdstats" }, 1);
739 # ORDER won't be retained in a hash
740 # " ORDER BY counter DESC", 1);
743 foreach (keys %hash) {
745 foreach (keys %{ $hash{$i} }) {
746 &DEBUG("cmdstats: $hash{$i}{$_} = $_");
749 &DEBUG("end of cmdstats.");
756 # FIXME does not try to get nick "back", just switches nicks
757 if ($message =~ /^wantNick\s(.*)?$/i) {
758 return unless (&hasFlag("o"));
759 my $wantnick = lc $1;
760 my $mynick = $conn->nick();
762 if ($mynick eq $wantnick) {
763 &msg($who, "I hope you're right. I'll try anyway (mynick=$mynick, wantnick=$wantnick).");
766 # fallback check, I guess. needed?
767 if (! &IsNickInAnyChan( $wantnick ) ) {
768 my $str = "attempting to change nick from $mynick to $wantnick";
775 # idea from dondelecarlo :)
776 # TODO: use cache{nickserv}
777 if ($param{'nickServ_pass'}) {
778 my $str = "someone is using nick $wantnick; GHOSTing";
781 &msg("NickServ", "GHOST $wantnick $param{'nickServ_pass'}");
783 $conn->schedule(5, sub {
784 &status("going to change nick from $mynick to $wantnick after GHOST.");