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 # Sorry, its messy, but it seems to work now. Added $salt and $ciphertext -- troubled
449 ($salt, $ciphertext) = split /\s+(.*)$/, $2;
450 my @args = split /\s+/, $2;
452 # Original was > 2 and thus only allowed 1 word to be passed to crypt.
453 # Although now it will crypt to random salt if only 1 param -- troubled
454 if (!scalar @args or scalar @args < 1) {
459 if (scalar @args >= 2) {
460 # disable cause $1$ will use md5
461 # if (length $args[0] != 2) {
462 # &msg($who, "invalid format...");
466 &performStrictReply( crypt($ciphertext, $salt) );
468 # When does this get called now since above commented out? -- troubled
469 &performStrictReply( &mkcrypt($args[0]) );
476 if ($message =~ /^(cycle)(\s+(\S+))?$/i) {
477 return unless (&hasFlag("o"));
481 if ($msgType =~ /public/) {
482 $chan = $talkchannel;
483 &DEBUG("cycle: setting chan to '$chan'.");
490 if (&validChan($chan) == 0) {
491 &msg($who,"error: invalid channel \002$chan\002");
495 &msg($chan, "I'm coming back. (courtesy of $who)");
497 ### &ScheduleThis(5, "getNickInUse") if (@_);
498 &status("Schedule rejoin in 5secs to $chan by $who.");
499 $conn->schedule(5, sub { &joinchan($chan); });
505 if ($message =~ /^reload$/i) {
506 return unless (&hasFlag("n"));
508 &status("USER reload $who");
509 &performStrictReply("reloading...");
510 my $modules = &reloadAllModules();
511 &performStrictReply("reloaded:$modules");
516 if ($message =~ /^redir(\s+(.*))?/i) {
517 return unless (&hasFlag("o"));
520 if (!defined $factoid) {
525 my $val = &getFactInfo($factoid, "factoid_value");
526 if (!defined $val or $val eq "") {
527 &msg($who, "error: '$factoid' does not exist.");
530 &DEBUG("val => '$val'.");
531 my @list = &searchTable("factoids", "factoid_key",
532 "factoid_value", "^$val\$");
534 if (scalar @list == 1) {
535 &msg($who, "hrm... '$factoid' is unique.");
538 if (scalar @list > 5) {
539 &msg($who, "A bit too many factoids to be redirected, hey?");
544 &status("Redirect '$factoid' (". ($#list) .")...");
547 next if (/^\Q$factoid\E$/i);
549 &status(" Redirecting '$_'.");
550 my $was = &getFactoid($_);
551 if ($was =~ /<REPLY> see/i) {
552 &status("warn: not redirecting a redirection.");
556 &DEBUG(" was '$was'.");
558 &setFactInfo($x, "factoid_value", "<REPLY> see $factoid");
562 &msg($who, &formListReply(0, "'$factoid' is redirected to by '", @redir));
568 if ($message =~ /^rot([0-9]*)(\s+(.*))?/i) {
571 if (!defined $reply) {
576 my $upper="ABCDEFGHIJKLMNOPQRSTUVWXYZ";
577 my $lower="abcdefghijklmnopqrstuvwxyz";
578 my $to=substr($upper,$num).substr($upper,0,$num).substr($lower,$num).substr($lower,0,$num);
579 eval "\$reply =~ tr/$upper$lower/$to/;";
581 #$reply =~ y/A-Za-z/N-ZA-Mn-za-m/;
582 &performStrictReply($reply);
588 if ($message =~ /^cpustats$/i) {
589 if ($^O !~ /linux/) {
590 &ERROR("cpustats: your OS is not supported yet.");
594 ### poor method to get info out of file, please fix.
595 open(STAT,"/proc/$$/stat");
598 my @data = split(/ /, $line);
601 # utime(13) + stime(14).
602 my $cpu_usage = sprintf("%.01f", ($data[13]+$data[14]) / 100 );
603 # cutime(15) + cstime (16).
604 my $cpu_usage2 = sprintf("%.01f", ($data[15]+$data[16]) / 100 );
605 my $time = time() - $^T;
606 my $raw_perc = $cpu_usage*100/$time;
607 my $raw_perc2 = $cpu_usage2*100/$time;
614 $perc = sprintf("%.01f", $raw_perc);
615 $perc2 = sprintf("%.01f", $raw_perc2);
616 $total = sprintf("%.01f", $raw_perc+$raw_perc2);
617 } elsif ($raw_perc > 0.1) {
618 $perc = sprintf("%.02f", $raw_perc);
619 $perc2 = sprintf("%.02f", $raw_perc2);
620 $total = sprintf("%.02f", $raw_perc+$raw_perc2);
622 $perc = sprintf("%.03f", $raw_perc);
623 $perc2 = sprintf("%.03f", $raw_perc2);
624 $total = sprintf("%.03f", $raw_perc+$raw_perc2);
626 $ratio = sprintf("%.01f", 100*$perc/($perc+$perc2) );
628 &performStrictReply("Total CPU usage: \002$cpu_usage\002 s ... ".
629 "Total used: \002$total\002 % ".
630 "(parent/child ratio: $ratio %)"
637 if ($message =~ /^ircstats?$/i) {
638 $ircstats{'TotalTime'} ||= 0;
639 $ircstats{'OffTime'} ||= 0;
641 my $count = $ircstats{'ConnectCount'};
642 my $format_time = &Time2String(time() - $ircstats{'ConnectTime'});
643 my $total_time = time() - $ircstats{'ConnectTime'} +
644 $ircstats{'TotalTime'};
647 my $connectivity = 100 * ($total_time - $ircstats{'OffTime'}) /
649 my $p = sprintf("%.03f", $connectivity);
650 $p =~ s/(\.\d*)0+$/$1/;
651 if ($p =~ s/\.0$//) {
652 # this should not happen... but why...
657 if ($total_time != (time() - $ircstats{'ConnectTime'}) ) {
658 my $tt_format = &Time2String($total_time);
659 &DEBUG("tt_format => $tt_format");
663 if ($count == 1) { # good.
664 $reply = "I'm connected to $ircstats{'Server'} and have been so".
667 $reply = "Currently I'm hooked up to $ircstats{'Server'} but only".
668 " for $format_time. ".
669 "I had to reconnect \002$count\002 times.".
670 " Connectivity: $p %";
674 my $reason = $ircstats{'DisconnectReason'};
675 if (defined $reason) {
676 $reply .= ". I was last disconnected for '$reason'.";
679 &performStrictReply($reply);
685 if ($message =~ /^statu?s$/i) {
686 my $startString = scalar(gmtime $^T);
687 my $upString = &Time2String(time() - $^T);
688 my ($puser,$psystem,$cuser,$csystem) = times;
689 my $factoids = &countKeys("factoids");
691 foreach (keys %forked) {
692 $forks += scalar keys %{ $forked{$_} };
695 $count{'Commands'} = 0;
696 foreach (keys %cmdstats) {
697 $count{'Commands'} += $cmdstats{$_};
701 "Since $startString, there have been".
702 " \002$count{'Update'}\002 ".
703 &fixPlural("modification", $count{'Update'}).
704 ", \002$count{'Question'}\002 ".
705 &fixPlural("question",$count{'Question'}).
706 ", \002$count{'Dunno'}\002 ".
707 &fixPlural("dunno",$count{'Dunno'}).
708 ", \002$count{'Moron'}\002 ".
709 &fixPlural("moron",$count{'Moron'}).
710 " and \002$count{'Commands'}\002 ".
711 &fixPlural("command",$count{'Commands'}).
712 ". I have been awake for $upString this session, and ".
713 "currently reference \002$factoids\002 factoids. ".
714 "I'm using about \002$memusage\002 ".
715 "kB of memory. With \002$forks\002 active ".
716 &fixPlural("fork",$forks).
717 ". Process time user/system $puser/$psystem child $cuser/$csystem"
724 # FIXME does not try to get nick "back", just switches nicks
725 if ($message =~ /^wantNick\s(.*)?$/i) {
726 return unless (&hasFlag("o"));
727 my $wantnick = lc $1;
728 my $mynick = $conn->nick();
730 if ($mynick eq $wantnick) {
731 &msg($who, "I hope you're right. I'll try anyway (mynick=$mynick, wantnick=$wantnick).");
734 # fallback check, I guess. needed?
735 if (! &IsNickInAnyChan( $wantnick ) ) {
736 my $str = "attempting to change nick from $mynick to $wantnick";
743 # idea from dondelecarlo :)
744 # TODO: use cache{nickserv}
745 if ($param{'nickServ_pass'}) {
746 my $str = "someone is using nick $wantnick; GHOSTing";
749 &msg("NickServ", "GHOST $wantnick $param{'nickServ_pass'}");
751 $conn->schedule(5, sub {
752 &status("going to change nick from $mynick to $wantnick after GHOST.");