]> git.donarmstrong.com Git - infobot.git/blob - src/IRC/Schedulers.pl
- bot stats: "blah has blah... is ranked xx/yy (zz percentile)"
[infobot.git] / src / IRC / Schedulers.pl
1 #
2 # ProcessExtra.pl: Extensions to Process.pl
3 #          Author: dms
4 #         Version: v0.5 (20010124)
5 #         Created: 20000117
6 #
7
8 if (&IsParam("useStrict")) { use strict; }
9
10 use POSIX qw(strftime);
11 use vars qw(%sched);
12
13 sub setupSchedulers {
14     &VERB("Starting schedulers...",2);
15
16     # ONCE OFF.
17
18     # REPETITIVE.
19     # 1 for run straight away, 2 for on next-run.
20     &uptimeLoop(1);
21     &randomQuote(2);
22     &randomFactoid(2);
23     &randomFreshmeat(2);
24     &logLoop(1);
25     &chanlimitCheck(1);
26     &netsplitCheck(1);  # mandatory
27     &floodLoop(1);      # mandatory
28     &seenFlush(2);
29     &leakCheck(2);      # mandatory
30     &ignoreCheck(1);    # mandatory
31     &seenFlushOld(2);
32 #    &ircCheck(2);      # mandatory
33     &ircCheck(1);       # mandatory
34     &miscCheck(1);      # mandatory
35     &miscCheck2(2);     # mandatory
36     &shmFlush(1);       # mandatory
37     &slashdotLoop(2);
38     &freshmeatLoop(2);
39     &kernelLoop(2);
40     &wingateWriteFile(2);
41     &factoidCheck(1);
42     &newsFlush(1);
43
44 #    my $count = map { exists $sched{$_}{TIME} } keys %sched;
45     my $count   = 0;
46     foreach (keys %sched) {
47 #       next unless (exists $sched{$_}{TIME});
48         my $time = $sched{$_}{TIME};
49         next unless (defined $time and $time > time());
50
51         $count++;
52     }
53
54     &status("Schedulers: $count will be running.");
55 ###    &scheduleList();
56 }
57
58 sub ScheduleThis {
59     my ($interval, $codename, @args) = @_;
60     my $waittime = &getRandomInt($interval);
61
62     if (!defined $waittime) {
63         &WARN("interval == waittime == UNDEF for $codename.");
64         return;
65     }
66
67     my $time = $sched{$codename}{TIME};
68     if (defined $time and $time > time()) {
69         &WARN("Sched for $codename already exists.");
70         return;
71     }
72
73 #    &VERB("Scheduling \&$codename() for ".&Time2String($waittime),3);
74
75     my $retval = $conn->schedule($waittime, \&$codename, @args);
76     $sched{$codename}{LABEL}    = $retval;
77     $sched{$codename}{TIME}     = time()+$waittime;
78     $sched{$codename}{LOOP}     = 1;
79 }
80
81 ####
82 #### LET THE FUN BEGIN.
83 ####
84
85 sub randomQuote {
86     my $interval = &getChanConfDefault("randomQuoteInterval", 60);
87     if (@_) {
88         &ScheduleThis($interval, "randomQuote");
89         return if ($_[0] eq "2");       # defer.
90     }
91
92     my $line = &getRandomLineFromFile($bot_misc_dir. "/blootbot.randtext");
93     if (!defined $line) {
94         &ERROR("random Quote: weird error?");
95         return;
96     }
97
98     foreach ( &ChanConfList("randomQuote") ) {
99         next unless (&validChan($_));
100
101         &status("sending random Quote to $_.");
102         &action($_, "Ponders: ".$line);
103     }
104     ### TODO: if there were no channels, don't reschedule until channel
105     ###         configuration is modified.
106 }
107
108 sub randomFactoid {
109     my ($key,$val);
110     my $error = 0;
111
112     my $interval = &getChanConfDefault("randomFactoidInterval", 60);
113     if (@_) {
114         &ScheduleThis($interval, "randomFactoid");
115         return if ($_[0] eq "2");       # defer.
116     }
117
118     while (1) {
119         ($key,$val) = &randKey("factoids","factoid_key,factoid_value");
120 ###     $val =~ tr/^[A-Z]/[a-z]/;       # blah is Good => blah is good.
121         last if (defined $val and $val !~ /^</);
122
123         $error++;
124         if ($error == 5) {
125             &ERROR("rF: tried 5 times but failed.");
126             return;
127         }
128     }
129
130     foreach ( &ChanConfList("randomFactoid") ) {
131         next unless (&validChan($_));
132
133         &status("sending random Factoid to $_.");
134         &action($_, "Thinks: \037$key\037 is $val");
135         ### FIXME: Use &getReply() on above to format factoid properly?
136         $good++;
137     }
138 }
139
140 sub randomFreshmeat {
141     my $interval = &getChanConfDefault("randomFresheatInterval", 60);
142
143     if (@_) {
144         &ScheduleThis($interval, "randomFreshmeat");
145         return if ($_[0] eq "2");       # defer.
146     }
147
148     my @chans = &ChanConfList("randomFreshmeat");
149     return unless (scalar @chans);
150
151     &Forker("freshmeat", sub {
152         my $retval = &Freshmeat::randPackage();
153
154         foreach (@chans) {
155             next unless (&validChan($_));
156
157             &status("sending random Freshmeat to $_.");
158             &say($_, $line);
159         }
160     } );
161 }
162
163 sub logLoop {
164     if (@_) {
165         &ScheduleThis(60, "logLoop");
166         return if ($_[0] eq "2");       # defer.
167     }
168
169     return unless (defined fileno LOG);
170     return unless (&IsParam("logfile"));
171     return unless (&IsParam("maxLogSize"));
172
173     ### check if current size is too large.
174     if ( -s $file{log} > $param{'maxLogSize'}) {
175         my $date = sprintf("%04d%02d%02d", (localtime)[5,4,3]);
176         $file{log} = $param{'logfile'} ."-". $date;
177         &status("cycling log file.");
178
179         if ( -e $file{log}) {
180             my $i = 1;
181             my $newlog;
182             while () {
183                 $newlog = $file{log}."-".$i;
184                 last if (! -e $newlog);
185                 $i++;
186             }
187             $file{log} = $newlog;
188         }
189
190         &closeLog();
191         CORE::system("/bin/mv '$param{'logfile'}' '$file{log}'");
192         &compress($file{log});
193         &openLog();
194         &status("cycling log file.");
195     }
196
197     ### check if all the logs exceed size.
198     my $logdir = "$bot_base_dir/log/";
199     if (opendir(LOGS, $logdir)) {
200         my $tsize = 0;
201         my (%age, %size);
202
203         while (defined($_ = readdir LOGS)) {
204             my $logfile         = "$logdir/$_";
205
206             next unless ( -f $logfile);
207             my $size            = -s $logfile;
208             my $age             = (stat $logfile)[9];
209
210             $age{$age}          = $logfile;
211             $size{$logfile}     = $size;
212
213             $tsize              += $size;
214         }
215         closedir LOGS;
216
217         my $delete      = 0;
218         while ($tsize > $param{'maxLogSize'}) {
219             &status("LOG: current size > max ($tsize > $param{'maxLogSize'})");
220             my $oldest  = (sort {$a <=> $b} keys %age)[0];
221             &status("LOG: unlinking $age{$oldest}.");
222             unlink $age{$oldest};
223             $tsize      -= $oldest;
224             $delete++;
225         }
226
227         ### TODO: add how many b,kb,mb removed?
228         &status("LOG: removed $delete logs.") if ($delete);
229     } else {
230         &WARN("could not open dir $logdir");
231     }
232
233 }
234
235 sub seenFlushOld {
236     if (@_) {
237         &ScheduleThis(1440, "seenFlushOld");
238         return if ($_[0] eq "2");       # defer.
239     }
240
241     # is this global-only?
242     return unless (&IsChanConf("seen") > 0);
243     return unless (&IsChanConf("seenFlushInterval") > 0);
244
245     # global setting. does not make sense for per-channel.
246     my $max_time = &getChanConfDefault("seenMaxDays", 30) *60*60*24;
247     my $delete   = 0;
248
249     if ($param{'DBType'} =~ /^pg|postgres|mysql/i) {
250         my $query = "SELECT nick,time FROM seen GROUP BY nick HAVING UNIX_TIMESTAMP() - time > $max_time";
251         my $sth = $dbh->prepare($query);
252         $sth->execute;
253
254         while (my @row = $sth->fetchrow_array) {
255             my ($nick,$time) = @row;
256
257             &dbDel("seen","nick",$nick);
258             $delete++;
259         }
260         $sth->finish;
261     } elsif ($param{'DBType'} =~ /^dbm/i) {
262         my $time = time();
263
264         foreach (keys %seen) {
265             my $delta_time = $time - &dbGet("seen", "time", "nick", $_);
266             next unless ($delta_time > $max_time);
267
268             &DEBUG("seenFlushOld: ".&Time2String($delta_time) );
269             delete $seen{$_};
270             $delete++;
271         }
272     } else {
273         &FIXME("seenFlushOld: for PG/NO-DB.");
274     }
275     &VERB("SEEN deleted $delete seen entries.",2);
276
277 }
278
279 sub newsFlush {
280     if (@_) {
281         &ScheduleThis(60, "newsFlush");
282         return if ($_[0] eq "2");       # defer.
283     }
284
285     if (!&ChanConfList("news")) {
286         &DEBUG("newsFlush: news disabled? (chan => $chan)");
287         return;
288     }
289
290     my $delete  = 0;
291     my $oldest  = time();
292     my %none;
293     foreach $chan (keys %::news) {
294         my $i           = 0;
295         my $total       = scalar(keys %{ $::news{$chan} });
296
297         if (!$total) {
298             delete $::news{$chan};
299             next;
300         }
301
302         foreach $item (keys %{ $::news{$chan} }) {
303             my $t = $::news{$chan}{$item}{Expire};
304
305             my $tadd    = $::news{$chan}{$item}{Time};
306             $oldest     = $tadd if ($oldest > $tadd);
307
308             next if ($t == 0 or $t == -1);
309             if ($t < 1000) {
310                 &status("newsFlush: Fixed Expire time for $chan/$item, should not happen anyway.");
311                 $::news{$chan}{$item}{Expire} = time() + $t*60*60*24;
312                 next;
313             }
314
315             my $delta = $t - time();
316
317             next unless (time() > $t);
318
319             # todo: show how old it was.
320             delete $::news{$chan}{$item};
321             &status("NEWS: (newsflush) deleted '$item'");
322             $delete++;
323             $i++;
324         }
325
326         &status("NEWS (newsflush) {$chan}: deleted [$i/$total] news entries.") if ($i);
327         $none{$chan} = 1 if ($total == $i);
328     }
329
330     # todo: flush users aswell.
331     my $duser   = 0;
332     foreach $chan (keys %::newsuser) {
333         next if (exists $none{$chan});
334
335         foreach (keys %{ $::newsuser{$chan} }) {
336             my $t = $::newsuser{$chan}{$_};
337             if (!defined $t or ($t > 2 and $t < 1000)) {
338                 &DEBUG("something wrong with newsuser{$chan}{$_} => $t");
339                 next;
340             }
341
342             next unless ($oldest > $t);
343
344             delete $::newsuser{$chan}{$_};
345             $duser++;
346         }
347
348         my $i = scalar(keys %{ $::newsuser{$chan} });
349         delete $::newsuser{$chan} unless ($i);
350     }
351
352     if ($delete or $duser) {
353         &News::writeNews();
354         &status("NewsFlush: deleted: $delete news entries; $duser user cache.");
355     }
356 }
357
358 sub chanlimitCheck {
359     my $interval = &getChanConfDefault("chanlimitcheckInterval", 10);
360
361     if (@_) {
362         &ScheduleThis($interval, "chanlimitCheck");
363         return if ($_[0] eq "2");
364     }
365
366     my $str = join(' ', &ChanConfList("chanlimitcheck") );
367     &DEBUG("chanlimitCheck: str => $str");
368
369     foreach $chan ( &ChanConfList("chanlimitcheck") ) {
370         next unless (&validChan($chan));
371
372         if ($chan eq "_default") {
373             &WARN("chanlimit: we're doing $chan!! HELP ME!");
374             next;
375         }
376
377         my $limitplus   = &getChanConfDefault("chanlimitcheckPlus", 5, $chan);
378         my $newlimit    = scalar(keys %{ $channels{$chan}{''} }) + $limitplus;
379         my $limit       = $channels{$chan}{'l'};
380
381         if (scalar keys %netsplitservers) {
382             if (defined $limit) {
383                 &status("chanlimit: netsplit; removing it for $chan.");
384                 &rawout("MODE $chan -l");
385                 $cache{chanlimitChange}{$chan} = time();
386             }
387
388             next;
389         }
390
391         if (defined $limit and scalar keys %{ $channels{$chan}{''} } > $limit) {
392             &FIXME("LIMIT: set too low!!! FIXME");
393             ### run NAMES again and flush it.
394         }
395
396         if (defined $limit and $limit == $newlimit) {
397             $cache{chanlimitChange}{$chan} = time();
398             next;
399         }
400
401         if (!exists $channels{$chan}{'o'}{$ident}) {
402             &status("ChanLimit: dont have ops on $chan.") unless (exists $cache{warn}{chanlimit}{$chan});
403             $cache{warn}{chanlimit}{$chan} = 1;
404             &chanServCheck($chan);
405             next;
406         }
407         delete $cache{warn}{chanlimit}{$chan};
408
409         if (!defined $limit) {
410             &status("chanLimit: setting for first time or from netsplit, for $chan");
411         }
412
413         if (exists $cache{chanlimitChange}{$chan}) {
414             my $delta = time() - $cache{chanlimitChange}{$chan};
415             if ($delta < $interval*60) {
416                 &DEBUG("chanLimit: not going to change chanlimit! ($delta<$interval*60)");
417                 return;
418             }
419         }
420
421         &rawout("MODE $chan +l $newlimit");
422         $cache{chanlimitChange}{$chan} = time();
423     }
424 }
425
426 sub netsplitCheck {
427     my ($s1,$s2);
428
429     if (@_) {
430         &ScheduleThis(15, "netsplitCheck");
431         return if ($_[0] eq "2");
432     }
433
434     $cache{'netsplitCache'}++;
435     &DEBUG("running netsplitCheck... $cache{netsplitCache}");
436
437     if (!scalar %netsplit and scalar %netsplitservers) {
438         &DEBUG("nsC: !hash netsplit but hash netsplitservers <- removing!");
439         undef %netsplitservers;
440         return;
441     }
442
443     # well... this shouldn't happen since %netsplit code does it anyway.
444     foreach $s1 (keys %netsplitservers) {
445
446         foreach $s2 (keys %{ $netsplitservers{$s1} }) {
447             my $delta = time() - $netsplitservers{$s1}{$s2};
448
449             if ($delta > 60*30) {
450                 &status("netsplit between $s1 and $s2 appears to be stale.");
451                 delete $netsplitservers{$s1}{$s2};
452                 &chanlimitCheck();
453             }
454         }
455
456         my $i = scalar(keys %{ $netsplitservers{$s1} });
457         delete $netsplitservers{$s1} unless ($i);
458     }
459
460     # %netsplit hash checker.
461     my $count   = scalar keys %netsplit;
462     my $delete  = 0;
463     foreach (keys %netsplit) {
464         if (&IsNickInAnyChan($_)) {     # why would this happen?
465 #           &DEBUG("nsC: $_ is in some chan; removing from netsplit list.");
466             delete $netsplit{$_};
467             $delete++;
468             next;
469         }
470
471         next unless (time() - $netsplit{$_} > 60*15);
472
473         $delete++;
474         delete $netsplit{$_};
475     }
476
477     # yet another hack.
478     foreach (keys %channels) {
479         my $i = $cache{maxpeeps}{$chan} || 0;
480         my $j = scalar(keys %{ $channels{$chan} });
481         next unless ($i > 10 and 0.25*$i > $j);
482
483         &DEBUG("netsplit: 0.25*max($i) > current($j); possible netsplit?");
484     }
485
486     if ($delete) {
487         my $j = scalar(keys %netsplit);
488         &DEBUG("nsC: removed from netsplit list: (before: $count; after: $j)");
489     }
490
491     if (!scalar %netsplit and scalar %netsplitservers) {
492         &DEBUG("nsC: ok hash netsplit is NULL; purging hash netsplitservers");
493         undef %netsplitservers;
494     }
495
496     if ($count and !scalar keys %netsplit) {
497         &DEBUG("nsC: netsplit is hopefully gone. reinstating chanlimit check.");
498         &chanlimitCheck();
499     }
500 }
501
502 sub floodLoop {
503     my $delete   = 0;
504     my $who;
505
506     if (@_) {
507         &ScheduleThis(60, "floodLoop"); # minutes.
508         return if ($_[0] eq "2");
509     }
510
511     my $time            = time();
512     my $interval        = &getChanConfDefault("floodCycle",60);
513
514     foreach $who (keys %flood) {
515         foreach (keys %{ $flood{$who} }) {
516             if (!exists $flood{$who}{$_}) {
517                 &WARN("flood{$who}{$_} undefined?");
518                 next;
519             }
520
521             if ($time - $flood{$who}{$_} > $interval) {
522                 delete $flood{$who}{$_};
523                 $delete++;
524             }
525         }
526     }
527     &VERB("floodLoop: deleted $delete items.",2);
528 }
529
530 sub seenFlush {
531     if (@_) {
532         my $interval = &getChanConfDefault("seenFlushInterval", 60);
533         &ScheduleThis($interval, "seenFlush");
534         return if ($_[0] eq "2");
535     }
536
537     my %stats;
538     my $nick;
539     my $flushed         = 0;
540     $stats{'count_old'} = &countKeys("seen") || 0;
541     $stats{'new'}       = 0;
542     $stats{'old'}       = 0;
543
544     if ($param{'DBType'} =~ /^mysql|pg|postgres/i) {
545         foreach $nick (keys %seencache) {
546             my $retval = &dbReplace("seen", (
547                         "nick" => $seencache{$nick}{'nick'},
548                         "time" => $seencache{$nick}{'time'},
549                         "host" => $seencache{$nick}{'host'},
550                         "channel" => $seencache{$nick}{'chan'},
551                         "message" => $seencache{$nick}{'msg'},
552             ) );
553             delete $seencache{$nick};
554             $flushed++;
555
556             next;
557
558             ###
559             ### old code.
560             ###
561
562             my $exists = &dbGet("seen", "nick", "nick=".&dbQuote($nick) );
563
564             if (defined $exists and $exists) {
565                 &dbUpdate("seen", "nick", $nick, (
566                         "time" => $seencache{$nick}{'time'},
567                         "host" => $seencache{$nick}{'host'},
568                         "channel" => $seencache{$nick}{'chan'},
569                         "message" => $seencache{$nick}{'msg'},
570                 ) );
571                 $stats{'old'}++;
572             } else {
573                 my $retval = &dbInsert("seen", $nick, (
574                         "nick" => $seencache{$nick}{'nick'},
575                         "time" => $seencache{$nick}{'time'},
576                         "host" => $seencache{$nick}{'host'},
577                         "channel" => $seencache{$nick}{'chan'},
578                         "message" => $seencache{$nick}{'msg'},
579                 ) );
580                 $stats{'new'}++;
581
582                 ### TODO: put bad nick into a list and don't do it again!
583                 &FIXME("Should never happen! (nick => $nick)") if !$retval;
584             }
585
586             delete $seencache{$nick};
587             $flushed++;
588         }
589
590     } elsif ($param{'DBType'} =~ /^dbm/i) {
591
592         foreach $nick (keys %seencache) {
593             my $retval = &dbInsert("seen", $nick, (
594                 "nick" => $seencache{$nick}{'nick'},
595                 "time" => $seencache{$nick}{'time'},
596                 "host" => $seencache{$nick}{'host'},
597                 "channel" => $seencache{$nick}{'chan'},
598                 "message" => $seencache{$nick}{'msg'},
599             ) );
600
601             ### TODO: put bad nick into a list and don't do it again!
602             &FIXME("Should never happen! (nick => $nick)") if !$retval;
603
604             delete $seencache{$nick};
605             $flushed++;
606         }
607     } else {
608         &DEBUG("seenFlush: NO VALID FACTOID SUPPORT?");
609     }
610
611     &status("Seen: Flushed $flushed entries.")  if ($flushed);
612     &VERB(sprintf("  new seen: %03.01f%% (%d/%d)",
613         $stats{'new'}*100/($stats{'count_old'} || 1),
614         $stats{'new'}, ( $stats{'count_old'} || 1) ), 2) if ($stats{'new'});
615     &VERB(sprintf("  now seen: %3.1f%% (%d/%d)",
616         $stats{'old'}*100 / ( &countKeys("seen") || 1),
617         $stats{'old'}, &countKeys("seen") ), 2)         if ($stats{'old'});
618
619     &WARN("scalar keys seenflush != 0!")        if (scalar keys %seenflush);
620 }
621
622 sub leakCheck {
623     my ($blah1,$blah2);
624     my $count = 0;
625
626     if (@_) {
627         &ScheduleThis(240, "leakCheck");
628         return if ($_[0] eq "2");
629     }
630
631     # flood. this is dealt with in floodLoop()
632     foreach $blah1 (keys %flood) {
633         foreach $blah2 (keys %{ $flood{$blah1} }) {
634             $count += scalar(keys %{ $flood{$blah1}{$blah2} });
635         }
636     }
637     &DEBUG("leak: hash flood has $count total keys.",2);
638
639     # floodjoin.
640     $count = 0;
641     foreach $blah1 (keys %floodjoin) {
642         foreach $blah2 (keys %{ $floodjoin{$blah1} }) {
643             $count += scalar(keys %{ $floodjoin{$blah1}{$blah2} });
644         }
645     }
646     &DEBUG("leak: hash floodjoin has $count total keys.",2);
647
648     # floodwarn.
649     $count = scalar(keys %floodwarn);
650     &DEBUG("leak: hash floodwarn has $count total keys.",2);
651
652     my $chan;
653     foreach $chan (grep /[A-Z]/, keys %channels) {
654         &DEBUG("leak: chan => '$chan'.");
655         my ($i,$j);
656         foreach $i (keys %{ $channels{$chan} }) {
657             foreach (keys %{ $channels{$chan}{$i} }) {
658                 &DEBUG("leak:   \$channels{$chan}{$i}{$_} ...");
659             }
660         }
661     }
662
663     # chanstats
664     $count = scalar(keys %chanstats);
665     &DEBUG("leak: hash chanstats has $count total keys.",2);
666
667     # nuh.
668     my $delete  = 0;
669     foreach (keys %nuh) {
670         next if (&IsNickInAnyChan($_));
671         next if (exists $dcc{CHAT}{$_});
672
673         delete $nuh{$_};
674         $delete++;
675     }
676
677     &status("leak: $delete nuh{} items deleted; now have ".
678                                 scalar(keys %nuh) ) if ($delete);
679 }
680
681 sub ignoreCheck {
682     if (@_) {
683         &ScheduleThis(60, "ignoreCheck");
684         return if ($_[0] eq "2");       # defer.
685     }
686
687     my $time    = time();
688     my $count   = 0;
689
690     foreach (keys %ignore) {
691         my $chan = $_;
692
693         foreach (keys %{ $ignore{$chan} }) {
694             my @array = @{ $ignore{$chan}{$_} };
695
696             next unless ($array[0] and $time > $array[0]);
697
698             delete $ignore{$chan}{$_};
699             &status("ignore: $_/$chan has expired.");
700             $count++;
701         }
702     }
703     &VERB("ignore: $count items deleted.",2);
704 }
705
706 sub ircCheck {
707     if (@_) {
708         &ScheduleThis(15, "ircCheck");
709         return if ($_[0] eq "2");       # defer.
710     }
711
712     my @x       = &getJoinChans();
713     my $iconf   = scalar( @x );
714     my $inow    = scalar( keys %channels );
715     if ($iconf > 2 and $inow * 2 <= $iconf) {
716         &FIXME("ircCheck: current channels * 2 <= config channels. FIXME.");
717         @joinchan       = @x;
718         &joinNextChan();
719     }
720
721     if (!$conn->connected or time() - $msgtime > 3600) {
722         # todo: shouldn't we use cache{connect} somewhere?
723         if (exists $cache{connect}) {
724             &WARN("ircCheck: no msg for 3600 and disco'd! reconnecting!");
725             $msgtime = time();  # just in case.
726             &ircloop();
727             delete $cache{connect};
728         } else {
729             &status("IRCTEST: possible lost in space; checking. ".
730                 scalar(localtime) );
731             &msg($ident, "TEST");
732             $cache{connect} = time();
733         }
734     }
735
736     if ($ident !~ /^\Q$param{ircNick}\E$/) {
737         # this does not work unfortunately.
738         &WARN("ircCheck: ident($ident) != param{ircNick}($param{IrcNick}).");
739
740         # this check is misleading... perhaps we should do a notify.
741         if (! &IsNickInAnyChan( $param{ircNick} ) ) {
742             &DEBUG("$param{ircNick} not in use... changing!");
743             &nick( $param{ircNick} );
744         } else {
745             &WARN("$param{ircNick} is still in use...");
746         }
747     }
748
749     if (grep /^\s*$/, keys %channels) {
750         &WARN("ircCheck: we have a NULL chan in hash channels? removing!");
751         if (exists $channels{''}) {
752             &DEBUG("ircCheck: ok it existed!");
753         } else {
754             &DEBUG("ircCheck: this hsould never happen!");
755         }
756
757         delete $channels{''};
758     }
759
760     ### USER FILE.
761     if ($utime_userfile > $wtime_userfile and time() - $wtime_userfile > 3600) {
762         &writeUserFile();
763         $wtime_userfile = time();
764     }
765     ### CHAN FILE.
766     if ($utime_chanfile > $wtime_chanfile and time() - $wtime_chanfile > 3600) {
767         &writeChanFile();
768         $wtime_chanfile = time();
769     }
770 }
771
772 sub miscCheck {
773     if (@_) {
774         &ScheduleThis(240, "miscCheck");
775         return if ($_[0] eq "2");       # defer.
776     }
777
778     # SHM check.
779     my @ipcs;
780     if ( -x "/usr/bin/ipcs") {
781         @ipcs = `/usr/bin/ipcs`;
782     } else {
783         &WARN("ircCheck: no 'ipcs' binary.");
784         return;
785     }
786
787     # shmid stale remove.
788     foreach (@ipcs) {
789         chop;
790
791         # key, shmid, owner, perms, bytes, nattch
792         next unless (/^(0x\d+) (\d+)\s+(\S+)\s+(\d+)\s+(\d+)\s+/);
793
794         my ($shmid, $size) = ($2,$5);
795         next unless ($shmid != $shm and $size == 2000);
796         my $z   = &shmRead($shmid);
797         if ($z =~ /^(\d+): /) {
798             my $time    = $1;
799             next if (time() - $time < 60*60);
800
801         } else {
802 #           &DEBUG("shm: $shmid is not ours or old blootbot => ($z)");
803 #           next;
804         }
805
806         &status("SHM: nuking shmid $shmid");
807         CORE::system("/usr/bin/ipcrm shm $shmid >/dev/null");
808     }
809
810     # make backup of important files.
811     &mkBackup( $bot_misc_dir."/blootbot.chan", 60*60*24*3);
812     &mkBackup( $bot_misc_dir."/blootbot.users", 60*60*24*3);
813     &mkBackup( $bot_base_dir."/blootbot-news.txt", 60*60*24*1);
814
815     # flush cache{lobotomy}
816     foreach (keys %{ $cache{lobotomy} }) {
817         next unless (time() - $cache{lobotomy}{$_} > 60*60);
818         delete $cache{lobotomy}{$_};
819     }
820
821     ### check modules if they've been modified. might be evil.
822     &reloadAllModules();
823 }
824
825 sub miscCheck2 {
826     if (@_) {
827         &ScheduleThis(240, "miscCheck2");
828         return if ($_[0] eq "2");       # defer.
829     }
830
831     # debian check.
832     opendir(DEBIAN, "$bot_base_dir/debian");
833     foreach ( grep /gz$/, readdir(DEBIAN) ) {
834         my $exit = CORE::system("gzip -t $bot_base_dir/debian/$_");
835         next unless ($exit);
836
837         &status("debian: unlinking file => $_");
838         unlink "$bot_base_dir/debian/$_";
839     }
840     closedir DEBIAN;
841
842     # compress logs that should have been compressed.
843     # todo: use strftime?
844     my ($day,$month,$year) = (localtime(time()))[3,4,5];
845     my $date = sprintf("%04d%02d%02d",$year+1900,$month+1,$day);
846
847     opendir(DIR,"$bot_base_dir/log");
848     while (my $f = readdir(DIR)) {
849         next unless ( -f "$bot_base_dir/log/$f");
850         next if ($f =~ /gz|bz2/);
851         next unless ($f =~ /(\d{8})/);
852         next if ($date eq $1);
853
854         &compress("$bot_base_dir/log/$f");
855     }
856     closedir DIR;
857 }
858
859 sub shmFlush {
860     return if ($$ != $::bot_pid); # fork protection.
861
862     if (@_) {
863         &ScheduleThis(5, "shmFlush");
864         return if ($_[0] eq "2");
865     }
866
867     my $time;
868     my $shmmsg = &shmRead($shm);
869     $shmmsg =~ s/\0//g;         # remove padded \0's.
870     if ($shmmsg =~ s/^(\d+): //) {
871         $time   = $1;
872     }
873
874     foreach (split '\|\|', $shmmsg) {
875         next if (/^$/);
876         &VERB("shm: Processing '$_'.",2);
877
878         if (/^DCC SEND (\S+) (\S+)$/) {
879             my ($nick,$file) = ($1,$2);
880             if (exists $dcc{'SEND'}{$who}) {
881                 &msg($nick, "DCC already active.");
882             } else {
883                 &DEBUG("shm: dcc sending $2 to $1.");
884                 $conn->new_send($1,$2);
885                 $dcc{'SEND'}{$who} = time();
886             }
887         } elsif (/^SET FORKPID (\S+) (\S+)/) {
888             $forked{$1}{PID} = $2;
889         } elsif (/^DELETE FORK (\S+)$/) {
890             delete $forked{$1};
891         } elsif (/^EVAL (.*)$/) {
892             &DEBUG("evaling '$1'.");
893             eval $1;
894         } else {
895             &DEBUG("shm: unknown msg. ($_)");
896         }
897     }
898
899     &shmWrite($shm,"") if ($shmmsg ne "");
900 }
901
902 ### this is semi-scheduled
903 sub getNickInUse {
904     if ($ident eq $param{'ircNick'}) {
905         &status("okay, got my nick back.");
906         return;
907     }
908
909     if (@_) {
910         &ScheduleThis(30, "getNickInUse");
911         return if ($_[0] eq "2");       # defer.
912     }
913
914     &nick( $param{'ircNick'} );
915 }
916
917 sub uptimeLoop {
918     return unless &IsChanConf("uptime");
919
920     if (@_) {
921         &ScheduleThis(60, "uptimeLoop");
922         return if ($_[0] eq "2");       # defer.
923     }
924
925     &uptimeWriteFile();
926 }
927
928 sub slashdotLoop {
929
930     if (@_) {
931         &ScheduleThis(60, "slashdotLoop");
932         return if ($_[0] eq "2");
933     }
934
935     my @chans = &ChanConfList("slashdotAnnounce");
936     return unless (scalar @chans);
937
938     &Forker("slashdot", sub {
939         my $line = &Slashdot::slashdotAnnounce();
940         return unless (defined $line);
941
942         foreach (@chans) {
943             next unless (&::validChan($_));
944
945             &::status("sending slashdot update to $_.");
946             &notice($_, "Slashdot: $line");
947         }
948     } );
949 }
950
951 sub freshmeatLoop {
952     if (@_) {
953         &ScheduleThis(60, "freshmeatLoop");
954         return if ($_[0] eq "2");
955     }
956
957     my @chans = &ChanConfList("freshmeatAnnounce");
958     return unless (scalar @chans);
959
960     &Forker("freshmeat", sub {
961         my $data = &Freshmeat::freshmeatAnnounce();
962
963         foreach (@chans) {
964             next unless (&::validChan($_));
965
966             &::status("sending freshmeat update to $_.");
967             &msg($_, $data);
968         }
969     } );
970 }
971
972 sub kernelLoop {
973     if (@_) {
974         &ScheduleThis(240, "kernelLoop");
975         return if ($_[0] eq "2");
976     }
977
978     my @chans = &ChanConfList("kernelAnnounce");
979     return unless (scalar @chans);
980
981     &Forker("kernel", sub {
982         my @data = &Kernel::kernelAnnounce();
983
984         foreach (@chans) {
985             next unless (&::validChan($_));
986
987             &::status("sending kernel update to $_.");
988             my $c = $_;
989             foreach (@data) {
990                 &notice($c, "Kernel: $_");
991             }
992         }
993     } );
994 }
995
996 sub wingateCheck {
997     return unless &IsChanConf("wingate");
998
999     ### FILE CACHE OF OFFENDING WINGATES.
1000     foreach (grep /^$host$/, @wingateBad) {
1001         &status("Wingate: RUNNING ON $host BY $who");
1002         &ban("*!*\@$host", "") if &IsChanConf("wingateBan");
1003
1004         my $reason      = &getChanConf("wingateKick");
1005
1006         next unless ($reason);
1007         &kick($who, "", $reason)
1008     }
1009
1010     ### RUN CACHE OF TRIED WINGATES.
1011     if (grep /^$host$/, @wingateCache) {
1012         push(@wingateNow, $host);       # per run.
1013         push(@wingateCache, $host);     # cache per run.
1014     } else {
1015         &DEBUG("Already scanned $host. good.");
1016     }
1017
1018     my $interval = &getChanConfDefault("wingateInterval", 60); # seconds.
1019     return if (defined $forked{'wingate'});
1020     return if (time() - $wingaterun <= $interval);
1021     return unless (scalar(keys %wingateToDo));
1022
1023     $wingaterun = time();
1024
1025     &Forker("wingate", sub { &Wingate::Wingates(keys %wingateToDo); } );
1026     undef @wingateNow;
1027 }
1028
1029 ### TODO.
1030 sub wingateWriteFile {
1031     if (@_) {
1032         &ScheduleThis(60, "wingateWriteFile");
1033         return if ($_[0] eq "2");       # defer.
1034     }
1035
1036     return unless (scalar @wingateCache);
1037
1038     my $file = "$bot_base_dir/$param{'ircUser'}.wingate";
1039     if ($bot_pid != $$) {
1040         &DEBUG("wingateWriteFile: Reorganising!");
1041
1042         open(IN, $file);
1043         while (<IN>) {
1044             chop;
1045             push(@wingateNow, $_);
1046         }
1047         close IN;
1048
1049         # very lame hack.
1050         my %hash = map { $_ => 1 } @wingateNow;
1051         @wingateNow = sort keys %hash;
1052     }
1053
1054     &DEBUG("wingateWF: writing...");
1055     open(OUT, ">$file");
1056     foreach (@wingateNow) {
1057         print OUT "$_\n";
1058     }
1059     close OUT;
1060 }
1061
1062 sub factoidCheck {
1063     if (@_) {
1064         &ScheduleThis(720, "factoidCheck");
1065         return if ($_[0] eq "2");       # defer.
1066     }
1067
1068     my @list    = &searchTable("factoids", "factoid_key", "factoid_key", " #DEL#");
1069     my $stale   = &getChanConfDefault("factoidDeleteDelay", 14) *60*60*24;
1070     if ($stale < 1) {
1071         # disable it since it's "illegal".
1072         return;
1073     }
1074
1075     my $time    = time();
1076
1077     foreach (@list) {
1078         my $age = &getFactInfo($_, "modified_time");    
1079
1080         if (!defined $age or $age !~ /^\d+$/) {
1081             if (scalar @list > 50) {
1082                 if (!$cache{warnDel}) {
1083                     &WARN("list is over 50 (".scalar(@list)."... giving it a miss.");
1084                     $cache{warnDel} = 1;
1085                     last;
1086                 }
1087             }
1088
1089             &WARN("del factoid: old cruft (no time): $_");
1090             &delFactoid($_);
1091             next;
1092         }
1093
1094         next unless ($time - $age > $stale);
1095
1096         my $fix = $_;
1097         $fix =~ s/ #DEL#$//g;
1098         my $agestr = &Time2String($time - $age);
1099         &status("safedel: Removing '$_' for good. [$agestr old]");
1100
1101         &delFactoid($_);
1102     }
1103 }
1104
1105 sub dccStatus {
1106     return unless (scalar keys %{ $dcc{CHAT} });
1107
1108     if (@_) {
1109         &ScheduleThis(10, "dccStatus");
1110         return if ($_[0] eq "2");       # defer.
1111     }
1112
1113     my $time = strftime("%H:%M", localtime(time()) );
1114
1115     my $c;
1116     foreach (keys %channels) {
1117         my $c           = $_;
1118         my $users       = keys %{ $channels{$c}{''} };
1119         my $chops       = keys %{ $channels{$c}{o}  };
1120         my $bans        = keys %{ $channels{$c}{b}  };
1121
1122         my $txt = "[$time] $c: $users members ($chops chops), $bans bans";
1123         foreach (keys %{ $dcc{'CHAT'} }) {
1124             next unless (exists $channels{$c}{''}{lc $_});
1125             $conn->privmsg($dcc{'CHAT'}{$_}, $txt);
1126         }
1127     }
1128 }
1129
1130 sub scheduleList {
1131     ###
1132     # custom:
1133     #   a - time == now.
1134     #   b - weird time.
1135     ###
1136
1137     &DEBUG("sched:");
1138     foreach (keys %{ $irc->{_queue} }) {
1139         my $q = $_;
1140
1141         my $sched;
1142         foreach (keys %sched) {
1143             next unless ($q eq $sched{$_});
1144             $sched = $_;
1145             last;
1146         }
1147
1148         my $time = $irc->{_queue}->{$q}->[0] - time();
1149
1150         if (defined $sched) {
1151             &DEBUG("   $sched($q): ".&Time2String($time) );
1152         } else {
1153             &DEBUG("   NULL($q): ".&Time2String($time) );
1154         }
1155     }
1156
1157     &DEBUG("end of sList.");
1158 }
1159
1160 sub getChanConfDefault {
1161     my($what, $default, $chan) = @_;
1162
1163     if (exists $param{$what}) {
1164         if (!exists $cache{config}{$what}) {
1165             &status("conf: backward-compat: found param{$what} ($param{$what}) instead.");
1166             $cache{config}{$what} = 1;
1167         }
1168
1169         return $param{$what};
1170     }
1171
1172     my $val = &getChanConf($what, $chan);
1173     if (defined $val) {
1174         return $val;
1175     }
1176
1177     $param{$what}       = $default;
1178     &status("conf: auto-setting param{$what} = $default");
1179     $cache{config}{$what} = 1;
1180
1181     return $default;
1182 }
1183
1184 sub mkBackup {
1185     my($file, $time)    = @_;
1186     my $backup          = 0;
1187
1188     if (! -f $file) {
1189         &VERB("mkB: file '$file' does not exist.",2);
1190         return;
1191     }
1192
1193     my $age     = "New";
1194     if ( -e "$file~" ) {
1195         $backup++       if ((stat $file)[9] - (stat "$file~")[9] > $time);
1196         my $delta       = time() - (stat "$file~")[9];
1197         $age            = &Time2String($delta);
1198     } else {
1199         $backup++;
1200     }
1201
1202     return unless ($backup);
1203
1204     ### TODO: do internal copying.
1205     &status("Backup: $file ($age)");
1206     CORE::system("/bin/cp $file $file~");
1207 }
1208
1209 1;