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