2 # UserExtra.pl: User Commands, Public.
7 use vars qw($message $arg $qWord $verb $lobotomized $who $result $chan
8 $conn $msgType $query $talkchannel $ident $memusage);
9 use vars qw(%channels %chanstats %cmdstats %count %ircstats %param
10 %cache %mask %userstats);
12 ### hooks get added in CommandHooks.pl.
15 ### Start of commands for hooks.
19 my $chan = lc shift(@_);
22 if ($chan eq "") { # all channels.
23 my $i = keys %channels;
24 my $reply = "I'm on \002$i\002 ".&fixPlural("channel",$i);
25 my $tucount = 0; # total user count.
26 my $uucount = 0; # unique user count.
30 foreach (sort keys %channels) {
31 if ( /^\s*$/ or / / ) {
32 &status("chanstats: fe channels: chan == NULL.");
36 next if (/^_default$/);
38 my $str = sprintf("%s/%d", $_, scalar(keys %{ $channels{$_}{''} }));
41 &performStrictReply($reply.": ".join(', ', @array));
44 foreach $chan (keys %channels) {
45 $tucount += scalar(keys %{ $channels{$chan}{''} });
48 ### unique user count.
50 foreach $chan (keys %channels) {
52 foreach $nick (keys %{ $channels{$chan}{''} }) {
56 $uucount = scalar(keys %nicks);
58 my $chans = scalar(keys %channels);
60 "i've cached \002$tucount\002 ". &fixPlural("user",$tucount).
61 ", \002$uucount\002 unique ". &fixPlural("user",$uucount).
62 ", distributed over \002$chans\002 ".
63 &fixPlural("channel", $chans)."."
72 if (&validChan($chan) == 0) {
73 &msg($who,"error: invalid channel \002$chan\002");
79 foreach (sort keys %{ $chanstats{$chan} }) {
80 my $int = $chanstats{$chan}{$_};
83 push(@array, "\002$int\002 ". &fixPlural($_,$int));
85 my $reply = "On \002$chan\002, there ".
86 &fixPlural("has",scalar(@array)). " been ".
89 # Step 1b: check channel inconstencies.
90 $chanstats{$chan}{'Join'} ||= 0;
91 $chanstats{$chan}{'SignOff'} ||= 0;
92 $chanstats{$chan}{'Part'} ||= 0;
94 my $delta_stats = $chanstats{$chan}{'Join'}
95 - $chanstats{$chan}{'SignOff'}
96 - $chanstats{$chan}{'Part'};
99 my $total = scalar(keys %{ $channels{$chan}{''} });
100 &status("chaninfo: join ~= signoff + part (drift of $delta_stats < $total).");
102 if ($delta_stats > $total) {
103 &ERROR("chaninfo: delta_stats exceeds total users.");
110 foreach ("v","o","") {
111 my $int = scalar(keys %{ $channels{$chan}{$_} });
114 $type = "Voice" if ($_ eq "v");
115 $type = "Opped" if ($_ eq "o");
116 $type = "Total" if ($_ eq "");
118 push(@array,"\002$int\002 $type");
120 $reply .= ". At the moment, ". &IJoin(@array);
124 foreach (keys %userstats) {
125 next unless (exists $userstats{$_}{'Count'});
126 if ($userstats{$_}{'Count'} =~ /^\D+$/) {
127 &WARN("userstats{$_}{Count} is non-digit.");
131 $new{$_} = $userstats{$_}{'Count'};
134 # TODO: show top 3 with percentages?
135 my($count) = (sort { $new{$b} <=> $new{$a} } keys %new)[0];
137 $reply .= ". \002$count\002 has said the most with a total of \002$new{$count}\002 messages";
139 &performStrictReply("$reply.");
142 # Command statistics.
146 if (!scalar(keys %cmdstats)) {
147 &performReply("no-one has run any commands yet");
152 foreach (keys %cmdstats) {
153 $countstats{ $cmdstats{$_} }{$_} = 1;
156 foreach (sort {$b <=> $a} keys %countstats) {
160 foreach (keys %{ $countstats{$int} }) {
161 push(@array, "\002$int\002 of $_");
164 &performStrictReply("command usage include ". &IJoin(@array).".");
167 # Factoid extension info. xk++
169 my $faqtoid = lc shift(@_);
172 if ($faqtoid =~ /^\-(\S+)(\s+(.*))$/) {
173 &msg($who,"error: individual factoid info queries not supported as yet.");
174 &msg($who,"it's possible that the factoid mistakenly begins with '-'.");
181 &CmdFactInfo($faqtoid, $query);
185 my $type = shift(@_);
187 &Forker("factoids", sub {
188 &performStrictReply( &CmdFactStats($type) );
193 my $target = lc( shift || $who );
194 my $karma = &sqlSelect("stats", "counter",
195 { nick => $target, type => "karma" }) || 0;
198 &performStrictReply("$target has karma of $karma");
200 &performStrictReply("$target has neutral karma");
206 my ($target, $tell_obj) = ('','');
207 my $dont_tell_me = 0;
210 ### is this fixed elsewhere?
211 $args =~ s/\s+/ /g; # fix up spaces.
212 $args =~ s/^\s+|\s+$//g; # again.
214 # this one catches most of them
215 if ($args =~ /^(\S+) (-?)about (.*)$/i) {
218 $dont_tell_me = ($2) ? 1 : 0;
220 $tell_obj = $who if ($tell_obj =~ /^(me|myself)$/i);
222 } elsif ($args =~ /^(\S+) where (\S+) can (\S+) (.*)$/i) {
223 # i'm sure this could all be nicely collapsed
228 } elsif ($args =~ /^(\S+) (what|where) (.*?) (is|are)[.?!]*$/i) {
233 $query = "$qWord $verb $tell_obj";
235 } elsif ($args =~ /^(.*?) to (\S+)$/i) {
241 # check target type. Deny channel targets.
242 if ($target !~ /^$mask{nick}$/ or $target =~ /^$mask{chan}$/) {
243 &msg($who,"No, $who, I won't. (target invalid?)");
247 $target = $talkchannel if ($target =~ /^us$/i);
248 $target = $who if ($target =~ /^(me|myself)$/i);
250 &status("tell: target = $target, query = $query");
253 # if ($target !~ /^$mask{chan}$/ and !&IsNickInAnyChan($target)) {
254 # &msg($who, "No, $target is not in any of my chans.");
259 if ($target =~ /^\Q$ident\E$/i) {
260 &msg($who, "Isn't that a bit silly?");
265 my $oldmtype = $msgType;
267 my $result = &doQuestion($tell_obj);
268 # ^ returns '0' if nothing was found.
272 if (!defined $result || $result =~ /^0?$/) {
274 $msgType = "private";
276 # support command redirection.
277 # recursive cmdHooks aswell :)
279 $done++ if &parseCmdHook($tell_obj);
280 $message = $tell_obj;
281 $done++ unless (&Modules());
283 &VERB("tell: setting old values of who and msgType.",2);
285 $msgType = $oldmtype;
288 &msg($who, "told $target about CMD '$tell_obj'");
290 &msg($who, "i dunno what is '$tell_obj'.");
297 &status("tell: <$who> telling $target about $tell_obj.");
298 if ($who ne $target) {
300 &msg($who, "told $target about $tell_obj.");
302 &msg($who, "told $target about $tell_obj ($result)");
305 $reply = "$who wants you to know: $result";
307 $reply = "telling yourself: $result";
310 &msg($target, $reply);
314 if (exists $cache{countryStats}) {
315 &msg($who,"countrystats is already running!");
324 &help("countrystats");
329 $cache{countryStats}{chan} = $chan;
330 $cache{countryStats}{mtype} = $msgType;
331 $cache{countryStats}{who} = $who;
332 $cache{on_who_Hack} = 1;
335 sub do_countrystats {
336 $chan = $cache{countryStats}{chan};
337 $msgType = $cache{countryStats}{mtype};
338 $who = $cache{countryStats}{who};
342 foreach (keys %{ $cache{nuhInfo} }) {
343 my $h = $cache{nuhInfo}{$_}{Host};
345 if ($h =~ /^.*\.(\D+)$/) { # host
348 $cstats{unresolve}++;
353 foreach (keys %cstats) {
354 $count{ $cstats{$_} }{$_} = 1;
358 foreach (sort {$b <=> $a} keys %count) {
359 my $str = join(", ", sort keys %{ $count{$_} });
360 # push(@list, "$str ($_)");
361 my $perc = sprintf("%.01f", 100 * $_ / $total);
363 push(@list, "$str ($_, $perc %)");
366 # TODO: move this into a scheduler
367 $msgType = "private";
368 &performStrictReply( &formListReply(0, "Country Stats ", @list) );
370 delete $cache{countryStats};
371 delete $cache{on_who_Hack};
375 ### amalgamated commands.
380 if ($message =~ /^(asci*|chr) (\d+)$/) {
381 &DEBUG("ascii/chr called ...");
382 return unless (&IsChanConfOrWarn("allowConv"));
384 &DEBUG("ascii/chr called");
388 $result = "NULL" if ($arg == 0);
390 &performReply( sprintf("ascii %s is '%s'", $arg, $result) );
396 if ($message =~ /^ord(\s+(.*))$/) {
397 return unless (&IsChanConfOrWarn("allowConv"));
401 if (!defined $arg or length $arg != 1) {
406 if (ord($arg) < 32) {
407 $arg = chr(ord($arg) + 64);
408 if ($arg eq chr(64)) {
415 &performReply( sprintf("'%s' is ascii %s", $arg, ord $arg) );
420 if ($message =~ /^hex(\s+(.*))?$/i) {
421 return unless (&IsChanConfOrWarn("allowConv"));
429 if (length $arg > 80) {
430 &msg($who, "Too long.");
435 foreach (split //, $arg) {
436 $retval .= sprintf(" %X", ord($_));
439 &performStrictReply("$arg is$retval");
445 if ($message =~ /^crypt(\s+(.*))?$/i) {
446 my @args = split /\s+/, $2;
448 if (!scalar @args or scalar @args > 2) {
453 if (scalar @args == 2) {
454 # disable cause $1$ will use md5
455 # if (length $args[0] != 2) {
456 # &msg($who, "invalid format...");
460 &performStrictReply( crypt($args[1], $args[0]) );
462 &performStrictReply( &mkcrypt($args[0]) );
469 if ($message =~ /^(cycle)(\s+(\S+))?$/i) {
470 return unless (&hasFlag("o"));
474 if ($msgType =~ /public/) {
475 $chan = $talkchannel;
476 &DEBUG("cycle: setting chan to '$chan'.");
483 if (&validChan($chan) == 0) {
484 &msg($who,"error: invalid channel \002$chan\002");
488 &msg($chan, "I'm coming back. (courtesy of $who)");
490 ### &ScheduleThis(5, "getNickInUse") if (@_);
491 &status("Schedule rejoin in 5secs to $chan by $who.");
492 $conn->schedule(5, sub { &joinchan($chan); });
498 if ($message =~ /^reload$/i) {
499 return unless (&hasFlag("n"));
501 &status("USER reload $who");
502 &performStrictReply("reloading...");
503 my $modules = &reloadAllModules();
504 &performStrictReply("reloaded:$modules");
509 if ($message =~ /^redir(\s+(.*))?/i) {
510 return unless (&hasFlag("o"));
513 if (!defined $factoid) {
518 my $val = &getFactInfo($factoid, "factoid_value");
519 if (!defined $val or $val eq "") {
520 &msg($who, "error: '$factoid' does not exist.");
523 &DEBUG("val => '$val'.");
524 my @list = &searchTable("factoids", "factoid_key",
525 "factoid_value", "^$val\$");
527 if (scalar @list == 1) {
528 &msg($who, "hrm... '$factoid' is unique.");
531 if (scalar @list > 5) {
532 &msg($who, "A bit too many factoids to be redirected, hey?");
537 &status("Redirect '$factoid' (". ($#list) .")...");
540 next if (/^\Q$factoid\E$/i);
542 &status(" Redirecting '$_'.");
543 my $was = &getFactoid($_);
544 if ($was =~ /<REPLY> see/i) {
545 &status("warn: not redirecting a redirection.");
549 &DEBUG(" was '$was'.");
551 &setFactInfo($x, "factoid_value", "<REPLY> see $factoid");
555 &msg($who, &formListReply(0, "'$factoid' is redirected to by '", @redir));
561 if ($message =~ /^rot([0-9]*)(\s+(.*))?/i) {
564 if (!defined $reply) {
569 my $upper="ABCDEFGHIJKLMNOPQRSTUVWXYZ";
570 my $lower="abcdefghijklmnopqrstuvwxyz";
571 my $to=substr($upper,$num).substr($upper,0,$num).substr($lower,$num).substr($lower,0,$num);
572 eval "\$reply =~ tr/$upper$lower/$to/;";
574 #$reply =~ y/A-Za-z/N-ZA-Mn-za-m/;
575 &performStrictReply($reply);
581 if ($message =~ /^cpustats$/i) {
582 if ($^O !~ /linux/) {
583 &ERROR("cpustats: your OS is not supported yet.");
587 ### poor method to get info out of file, please fix.
588 open(STAT,"/proc/$$/stat");
591 my @data = split(/ /, $line);
594 # utime(13) + stime(14).
595 my $cpu_usage = sprintf("%.01f", ($data[13]+$data[14]) / 100 );
596 # cutime(15) + cstime (16).
597 my $cpu_usage2 = sprintf("%.01f", ($data[15]+$data[16]) / 100 );
598 my $time = time() - $^T;
599 my $raw_perc = $cpu_usage*100/$time;
600 my $raw_perc2 = $cpu_usage2*100/$time;
607 $perc = sprintf("%.01f", $raw_perc);
608 $perc2 = sprintf("%.01f", $raw_perc2);
609 $total = sprintf("%.01f", $raw_perc+$raw_perc2);
610 } elsif ($raw_perc > 0.1) {
611 $perc = sprintf("%.02f", $raw_perc);
612 $perc2 = sprintf("%.02f", $raw_perc2);
613 $total = sprintf("%.02f", $raw_perc+$raw_perc2);
615 $perc = sprintf("%.03f", $raw_perc);
616 $perc2 = sprintf("%.03f", $raw_perc2);
617 $total = sprintf("%.03f", $raw_perc+$raw_perc2);
619 $ratio = sprintf("%.01f", 100*$perc/($perc+$perc2) );
621 &performStrictReply("Total CPU usage: \002$cpu_usage\002 s ... ".
622 "Total used: \002$total\002 % ".
623 "(parent/child ratio: $ratio %)"
630 if ($message =~ /^ircstats?$/i) {
631 $ircstats{'TotalTime'} ||= 0;
632 $ircstats{'OffTime'} ||= 0;
634 my $count = $ircstats{'ConnectCount'};
635 my $format_time = &Time2String(time() - $ircstats{'ConnectTime'});
636 my $total_time = time() - $ircstats{'ConnectTime'} +
637 $ircstats{'TotalTime'};
640 my $connectivity = 100 * ($total_time - $ircstats{'OffTime'}) /
642 my $p = sprintf("%.03f", $connectivity);
643 $p =~ s/(\.\d*)0+$/$1/;
644 if ($p =~ s/\.0$//) {
645 # this should not happen... but why...
650 if ($total_time != (time() - $ircstats{'ConnectTime'}) ) {
651 my $tt_format = &Time2String($total_time);
652 &DEBUG("tt_format => $tt_format");
656 if ($count == 1) { # good.
657 $reply = "I'm connected to $ircstats{'Server'} and have been so".
660 $reply = "Currently I'm hooked up to $ircstats{'Server'} but only".
661 " for $format_time. ".
662 "I had to reconnect \002$count\002 times.".
663 " Connectivity: $p %";
667 my $reason = $ircstats{'DisconnectReason'};
668 if (defined $reason) {
669 $reply .= ". I was last disconnected for '$reason'.";
672 &performStrictReply($reply);
678 if ($message =~ /^statu?s$/i) {
679 my $startString = scalar(gmtime $^T);
680 my $upString = &Time2String(time() - $^T);
681 my ($puser,$psystem,$cuser,$csystem) = times;
682 my $factoids = &countKeys("factoids");
684 foreach (keys %forked) {
685 $forks += scalar keys %{ $forked{$_} };
688 $count{'Commands'} = 0;
689 foreach (keys %cmdstats) {
690 $count{'Commands'} += $cmdstats{$_};
694 "Since $startString, there have been".
695 " \002$count{'Update'}\002 ".
696 &fixPlural("modification", $count{'Update'}).
697 ", \002$count{'Question'}\002 ".
698 &fixPlural("question",$count{'Question'}).
699 ", \002$count{'Dunno'}\002 ".
700 &fixPlural("dunno",$count{'Dunno'}).
701 ", \002$count{'Moron'}\002 ".
702 &fixPlural("moron",$count{'Moron'}).
703 " and \002$count{'Commands'}\002 ".
704 &fixPlural("command",$count{'Commands'}).
705 ". I have been awake for $upString this session, and ".
706 "currently reference \002$factoids\002 factoids. ".
707 "I'm using about \002$memusage\002 ".
708 "kB of memory. With \002$forks\002 active ".
709 &fixPlural("fork",$forks).
710 ". Process time user/system $puser/$psystem child $cuser/$csystem"
715 my %hash = &sqlSelectColHash("stats", "nick,counter",
716 { type => "cmdstats" }, 1);
717 # ORDER won't be retained in a hash
718 # " ORDER BY counter DESC", 1);
721 foreach (keys %hash) {
723 foreach (keys %{ $hash{$i} }) {
724 &DEBUG("cmdstats: $hash{$i}{$_} = $_");
727 &DEBUG("end of cmdstats.");
734 # FIXME does not try to get nick "back", just switches nicks
735 if ($message =~ /^wantNick\s(.*)?$/i) {
736 return unless (&hasFlag("o"));
737 my $wantnick = lc $1;
738 my $mynick = $conn->nick();
740 if ($mynick eq $wantnick) {
741 &msg($who, "I hope you're right. I'll try anyway (mynick=$mynick, wantnick=$wantnick).");
744 # fallback check, I guess. needed?
745 if (! &IsNickInAnyChan( $wantnick ) ) {
746 my $str = "attempting to change nick from $mynick to $wantnick";
753 # idea from dondelecarlo :)
754 # TODO: use cache{nickserv}
755 if ($param{'nickServ_pass'}) {
756 my $str = "someone is using nick $wantnick; GHOSTing";
759 &msg("NickServ", "GHOST $wantnick $param{'nickServ_pass'}");
761 $conn->schedule(5, sub {
762 &status("going to change nick from $mynick to $wantnick after GHOST.");