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) {
78 foreach (keys %{ $channels{$chan}{''} }) {
79 next if (grep /^\Q$_\E$/, @nicks);
85 if (scalar @nicks != $uucount) {
86 &DEBUG("nicks != uucount...");
89 my $chans = scalar(keys %channels);
91 "i've cached \002$tucount\002 ". &fixPlural("user",$tucount).
92 ", \002$uucount\002 unique ". &fixPlural("user",$uucount).
93 ", distributed over \002$chans\002 ".
94 &fixPlural("channel", $chans)."."
102 if (&validChan($chan) == 0) {
103 &msg($who,"error: invalid channel \002$chan\002");
109 foreach (sort keys %{ $chanstats{$chan} }) {
110 my $int = $chanstats{$chan}{$_};
113 push(@array, "\002$int\002 ". &fixPlural($_,$int));
115 my $reply = "On \002$chan\002, there ".
116 &fixPlural("has",scalar(@array)). " been ".
119 # Step 1b: check channel inconstencies.
120 $chanstats{$chan}{'Join'} ||= 0;
121 $chanstats{$chan}{'SignOff'} ||= 0;
122 $chanstats{$chan}{'Part'} ||= 0;
124 my $delta_stats = $chanstats{$chan}{'Join'}
125 - $chanstats{$chan}{'SignOff'}
126 - $chanstats{$chan}{'Part'};
129 my $total = scalar(keys %{ $channels{$chan}{''} });
130 &status("chaninfo: join ~= signoff + part (drift of $delta_stats < $total).");
132 if ($delta_stats > $total) {
133 &ERROR("chaninfo: delta_stats exceeds total users.");
140 foreach ("v","o","") {
141 my $int = scalar(keys %{ $channels{$chan}{$_} });
144 $type = "Voice" if ($_ eq "v");
145 $type = "Opped" if ($_ eq "o");
146 $type = "Total" if ($_ eq "");
148 push(@array,"\002$int\002 $type");
150 $reply .= ". At the moment, ". &IJoin(@array);
154 foreach (keys %userstats) {
155 next unless (exists $userstats{$_}{'Count'});
156 if ($userstats{$_}{'Count'} =~ /^\D+$/) {
157 &WARN("userstats{$_}{Count} is non-digit.");
161 $new{$_} = $userstats{$_}{'Count'};
164 # TODO: show top 3 with percentages?
165 my($count) = (sort { $new{$b} <=> $new{$a} } keys %new)[0];
167 $reply .= ". \002$count\002 has said the most with a total of \002$new{$count}\002 messages";
169 &performStrictReply("$reply.");
172 # Command statistics.
176 if (!scalar(keys %cmdstats)) {
177 &performReply("no-one has run any commands yet");
182 foreach (keys %cmdstats) {
183 $countstats{ $cmdstats{$_} }{$_} = 1;
186 foreach (sort {$b <=> $a} keys %countstats) {
190 foreach (keys %{ $countstats{$int} }) {
191 push(@array, "\002$int\002 of $_");
194 &performStrictReply("command usage include ". &IJoin(@array).".");
197 # Factoid extension info. xk++
199 my $faqtoid = lc shift(@_);
202 if ($faqtoid =~ /^\-(\S+)(\s+(.*))$/) {
203 &msg($who,"error: individual factoid info queries not supported as yet.");
204 &msg($who,"it's possible that the factoid mistakenly begins with '-'.");
211 &CmdFactInfo($faqtoid, $query);
215 my $type = shift(@_);
217 &Forker("factoids", sub {
218 &performStrictReply( &CmdFactStats($type) );
223 my $target = lc( shift || $who );
224 my $karma = &sqlSelect("stats", "counter",
225 { nick => $target, type => "karma" }) || 0;
228 &performStrictReply("$target has karma of $karma");
230 &performStrictReply("$target has neutral karma");
236 my ($target, $tell_obj) = ('','');
237 my $dont_tell_me = 0;
240 ### is this fixed elsewhere?
241 $args =~ s/\s+/ /g; # fix up spaces.
242 $args =~ s/^\s+|\s+$//g; # again.
244 # this one catches most of them
245 if ($args =~ /^(\S+) (-?)about (.*)$/i) {
248 $dont_tell_me = ($2) ? 1 : 0;
250 $tell_obj = $who if ($tell_obj =~ /^(me|myself)$/i);
252 } elsif ($args =~ /^(\S+) where (\S+) can (\S+) (.*)$/i) {
253 # i'm sure this could all be nicely collapsed
258 } elsif ($args =~ /^(\S+) (what|where) (.*?) (is|are)[.?!]*$/i) {
263 $query = "$qWord $verb $tell_obj";
265 } elsif ($args =~ /^(.*?) to (\S+)$/i) {
271 # check target type. Deny channel targets.
272 if ($target !~ /^$mask{nick}$/ or $target =~ /^$mask{chan}$/) {
273 &msg($who,"No, $who, I won't. (target invalid?)");
277 $target = $talkchannel if ($target =~ /^us$/i);
278 $target = $who if ($target =~ /^(me|myself)$/i);
280 &status("tell: target = $target, query = $query");
283 # if ($target !~ /^$mask{chan}$/ and !&IsNickInAnyChan($target)) {
284 # &msg($who, "No, $target is not in any of my chans.");
289 if ($target =~ /^\Q$ident\E$/i) {
290 &msg($who, "Isn't that a bit silly?");
295 my $oldmtype = $msgType;
297 my $result = &doQuestion($tell_obj);
298 # ^ returns '0' if nothing was found.
302 if (!defined $result || $result =~ /^0?$/) {
304 $msgType = "private";
306 # support command redirection.
307 # recursive cmdHooks aswell :)
309 $done++ if &parseCmdHook("main", $tell_obj);
310 $done++ if &parseCmdHook("extra", $tell_obj);
311 $message = $tell_obj;
312 $done++ unless (&Modules());
314 &VERB("tell: setting old values of who and msgType.",2);
316 $msgType = $oldmtype;
319 &msg($who, "told $target about CMD '$tell_obj'");
321 &msg($who, "i dunno what is '$tell_obj'.");
328 &status("tell: <$who> telling $target about $tell_obj.");
329 if ($who ne $target) {
331 &msg($who, "told $target about $tell_obj.");
333 &msg($who, "told $target about $tell_obj ($result)");
336 $reply = "$who wants you to know: $result";
338 $reply = "telling yourself: $result";
341 &msg($target, $reply);
345 if (exists $cache{countryStats}) {
346 &msg($who,"countrystats is already running!");
355 &help("countrystats");
360 $cache{countryStats}{chan} = $chan;
361 $cache{countryStats}{mtype} = $msgType;
362 $cache{countryStats}{who} = $who;
363 $cache{on_who_Hack} = 1;
366 sub do_countrystats {
367 $chan = $cache{countryStats}{chan};
368 $msgType = $cache{countryStats}{mtype};
369 $who = $cache{countryStats}{who};
373 foreach (keys %{ $cache{nuhInfo} }) {
374 my $h = $cache{nuhInfo}{$_}{Host};
376 if ($h =~ /^.*\.(\D+)$/) { # host
379 $cstats{unresolve}++;
384 foreach (keys %cstats) {
385 $count{ $cstats{$_} }{$_} = 1;
389 foreach (sort {$b <=> $a} keys %count) {
390 my $str = join(", ", sort keys %{ $count{$_} });
391 # push(@list, "$str ($_)");
392 my $perc = sprintf("%.01f", 100 * $_ / $total);
394 push(@list, "$str ($_, $perc %)");
397 # TODO: move this into a scheduler like nickometer
398 $msgType = "private";
399 &performStrictReply( &formListReply(0, "Country Stats ", @list) );
401 delete $cache{countryStats};
402 delete $cache{on_who_Hack};
406 ### amalgamated commands.
411 if ($message =~ /^(asci*|chr) (\d+)$/) {
412 &DEBUG("ascii/chr called ...");
413 return unless (&IsChanConfOrWarn("allowConv"));
415 &DEBUG("ascii/chr called");
419 $result = "NULL" if ($arg == 0);
421 &performReply( sprintf("ascii %s is '%s'", $arg, $result) );
427 if ($message =~ /^ord(\s+(.*))$/) {
428 return unless (&IsChanConfOrWarn("allowConv"));
432 if (!defined $arg or length $arg != 1) {
437 if (ord($arg) < 32) {
438 $arg = chr(ord($arg) + 64);
439 if ($arg eq chr(64)) {
446 &performReply( sprintf("'%s' is ascii %s", $arg, ord $arg) );
451 if ($message =~ /^hex(\s+(.*))?$/i) {
452 return unless (&IsChanConfOrWarn("allowConv"));
460 if (length $arg > 80) {
461 &msg($who, "Too long.");
466 foreach (split //, $arg) {
467 $retval .= sprintf(" %X", ord($_));
470 &performStrictReply("$arg is$retval");
476 if ($message =~ /^crypt(\s+(.*))?$/i) {
477 my @args = split /\s+/, $2;
479 if (!scalar @args or scalar @args > 2) {
484 if (scalar @args == 2) {
485 # disable cause $1$ will use md5
486 # if (length $args[0] != 2) {
487 # &msg($who, "invalid format...");
491 &performStrictReply( crypt($args[1], $args[0]) );
493 &performStrictReply( &mkcrypt($args[0]) );
500 if ($message =~ /^(cycle)(\s+(\S+))?$/i) {
501 return unless (&hasFlag("o"));
505 if ($msgType =~ /public/) {
506 $chan = $talkchannel;
507 &DEBUG("cycle: setting chan to '$chan'.");
514 if (&validChan($chan) == 0) {
515 &msg($who,"error: invalid channel \002$chan\002");
519 &msg($chan, "I'm coming back. (courtesy of $who)");
521 ### &ScheduleThis(5, "getNickInUse") if (@_);
522 &status("Schedule rejoin in 5secs to $chan by $who.");
523 $conn->schedule(5, sub { &joinchan($chan); });
529 if ($message =~ /^reload$/i) {
530 return unless (&hasFlag("n"));
532 &status("USER reload $who");
533 &performStrictReply("reloading...");
534 my $modules = &reloadAllModules();
535 &performStrictReply("reloaded:$modules");
540 if ($message =~ /^redir(\s+(.*))?/i) {
541 return unless (&hasFlag("o"));
544 if (!defined $factoid) {
549 my $val = &getFactInfo($factoid, "factoid_value");
550 if (!defined $val or $val eq "") {
551 &msg($who, "error: '$factoid' does not exist.");
554 &DEBUG("val => '$val'.");
555 my @list = &searchTable("factoids", "factoid_key",
556 "factoid_value", "^$val\$");
558 if (scalar @list == 1) {
559 &msg($who, "hrm... '$factoid' is unique.");
562 if (scalar @list > 5) {
563 &msg($who, "A bit too many factoids to be redirected, hey?");
568 &status("Redirect '$factoid' (". ($#list) .")...");
571 next if (/^\Q$factoid\E$/i);
573 &status(" Redirecting '$_'.");
574 my $was = &getFactoid($_);
575 if ($was =~ /<REPLY> see/i) {
576 &status("warn: not redirecting a redirection.");
580 &DEBUG(" was '$was'.");
582 &setFactInfo($x, "factoid_value", "<REPLY> see $factoid");
586 &msg($who, &formListReply(0, "'$factoid' is redirected to by '", @redir));
592 if ($message =~ /^rot13(\s+(.*))?/i) {
595 if (!defined $reply) {
600 $reply =~ y/A-Za-z/N-ZA-Mn-za-m/;
601 &performStrictReply($reply);
607 if ($message =~ /^cpustats$/i) {
608 if ($^O !~ /linux/) {
609 &ERROR("cpustats: your OS is not supported yet.");
613 ### poor method to get info out of file, please fix.
614 open(STAT,"/proc/$$/stat");
617 my @data = split(/ /, $line);
620 # utime(13) + stime(14).
621 my $cpu_usage = sprintf("%.01f", ($data[13]+$data[14]) / 100 );
622 # cutime(15) + cstime (16).
623 my $cpu_usage2 = sprintf("%.01f", ($data[15]+$data[16]) / 100 );
624 my $time = time() - $^T;
625 my $raw_perc = $cpu_usage*100/$time;
626 my $raw_perc2 = $cpu_usage2*100/$time;
633 $perc = sprintf("%.01f", $raw_perc);
634 $perc2 = sprintf("%.01f", $raw_perc2);
635 $total = sprintf("%.01f", $raw_perc+$raw_perc2);
636 } elsif ($raw_perc > 0.1) {
637 $perc = sprintf("%.02f", $raw_perc);
638 $perc2 = sprintf("%.02f", $raw_perc2);
639 $total = sprintf("%.02f", $raw_perc+$raw_perc2);
641 $perc = sprintf("%.03f", $raw_perc);
642 $perc2 = sprintf("%.03f", $raw_perc2);
643 $total = sprintf("%.03f", $raw_perc+$raw_perc2);
645 $ratio = sprintf("%.01f", 100*$perc/($perc+$perc2) );
647 &performStrictReply("Total CPU usage: \002$cpu_usage\002 s ... ".
648 "Total used: \002$total\002 % ".
649 "(parent/child ratio: $ratio %)"
656 if ($message =~ /^ircstats?$/i) {
657 $ircstats{'TotalTime'} ||= 0;
658 $ircstats{'OffTime'} ||= 0;
660 my $count = $ircstats{'ConnectCount'};
661 my $format_time = &Time2String(time() - $ircstats{'ConnectTime'});
662 my $total_time = time() - $ircstats{'ConnectTime'} +
663 $ircstats{'TotalTime'};
666 my $connectivity = 100 * ($total_time - $ircstats{'OffTime'}) /
668 my $p = sprintf("%.03f", $connectivity);
669 $p =~ s/(\.\d*)0+$/$1/;
670 if ($p =~ s/\.0$//) {
671 # this should not happen... but why...
676 if ($total_time != (time() - $ircstats{'ConnectTime'}) ) {
677 my $tt_format = &Time2String($total_time);
678 &DEBUG("tt_format => $tt_format");
682 if ($count == 1) { # good.
683 $reply = "I'm connected to $ircstats{'Server'} and have been so".
686 $reply = "Currently I'm hooked up to $ircstats{'Server'} but only".
687 " for $format_time. ".
688 "I had to reconnect \002$count\002 times.".
689 " Connectivity: $p %";
693 my $reason = $ircstats{'DisconnectReason'};
694 if (defined $reason) {
695 $reply .= ". I was last disconnected for '$reason'.";
698 &performStrictReply($reply);
704 if ($message =~ /^statu?s$/i) {
705 my $startString = scalar(gmtime $^T);
706 my $upString = &Time2String(time() - $^T);
707 my ($puser,$psystem,$cuser,$csystem) = times;
708 my $factoids = &countKeys("factoids");
710 foreach (keys %forked) {
711 $forks += scalar keys %{ $forked{$_} };
714 $count{'Commands'} = 0;
715 foreach (keys %cmdstats) {
716 $count{'Commands'} += $cmdstats{$_};
720 "Since $startString, there have been".
721 " \002$count{'Update'}\002 ".
722 &fixPlural("modification", $count{'Update'}).
723 ", \002$count{'Question'}\002 ".
724 &fixPlural("question",$count{'Question'}).
725 ", \002$count{'Dunno'}\002 ".
726 &fixPlural("dunno",$count{'Dunno'}).
727 ", \002$count{'Moron'}\002 ".
728 &fixPlural("moron",$count{'Moron'}).
729 " and \002$count{'Commands'}\002 ".
730 &fixPlural("command",$count{'Commands'}).
731 ". I have been awake for $upString this session, and ".
732 "currently reference \002$factoids\002 factoids. ".
733 "I'm using about \002$memusage\002 ".
734 "kB of memory. With \002$forks\002 active ".
735 &fixPlural("fork",$forks).
736 ". Process time user/system $puser/$psystem child $cuser/$csystem"
741 my %hash = &sqlSelectColHash("stats", "nick,counter",
742 { type => "cmdstats" }, 1);
743 # ORDER won't be retained in a hash
744 # " ORDER BY counter DESC", 1);
747 foreach (keys %hash) {
749 foreach (keys %{ $hash{$i} }) {
750 &DEBUG("cmdstats: $hash{$i}{$_} = $_");
753 &DEBUG("end of cmdstats.");
760 # FIXME does not try to get nick "back", just switches nicks
761 if ($message =~ /^wantNick\s(.*)?$/i) {
762 return unless (&hasFlag("o"));
763 my $wantnick = lc $1;
764 my $mynick = $conn->nick();
766 if ($mynick eq $wantnick) {
767 &msg($who, "I hope you're right. I'll try anyway (mynick=$mynick, wantnick=$wantnick).");
770 # fallback check, I guess. needed?
771 if (! &IsNickInAnyChan( $wantnick ) ) {
772 my $str = "attempting to change nick from $mynick to $wantnick";
779 # idea from dondelecarlo :)
780 # TODO: use cache{nickserv}
781 if ($param{'nickServ_pass'}) {
782 my $str = "someone is using nick $wantnick; GHOSTing";
785 &msg("NickServ", "GHOST $wantnick $param{'nickServ_pass'}");
787 $conn->schedule(5, sub {
788 &status("going to change nick from $mynick to $wantnick after GHOST.");