]> git.donarmstrong.com Git - infobot.git/blob - src/IRC/Schedulers.pl
- ircCheck => 120 interval.
[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     &uptimeLoop(1);
20     &randomQuote(2);
21     &randomFactoid(2);
22     &randomFreshmeat(2);
23     &logLoop(1);
24     &chanlimitCheck(1);
25     &netsplitCheck(1);  # mandatory
26     &floodLoop(1);      # mandatory
27     &seenFlush(1);
28     &leakCheck(2);      # mandatory
29     &ignoreCheck(1);    # mandatory
30     &seenFlushOld(1);
31     &ircCheck(1);       # mandatory
32     &miscCheck(2);      # mandatory
33     &shmFlush(1);       # mandatory
34     &slashdotLoop(2);
35     &freshmeatLoop(2);
36     &kernelLoop(2);
37     &wingateWriteFile(1);
38     &factoidCheck(1);
39
40 #    my $count = map { exists $sched{$_}{TIME} } keys %sched;
41     my $count   = 0;
42     foreach (keys %sched) {
43 #       next unless (exists $sched{$_}{TIME});
44         my $time = $sched{$_}{TIME};
45         next unless (defined $time and $time > time());
46
47         $count++;
48     }
49
50     &status("Schedulers: $count will be running.");
51 ###    &scheduleList();
52 }
53
54 sub ScheduleThis {
55     my ($interval, $codename, @args) = @_;
56     my $waittime = &getRandomInt($interval);
57
58     if (!defined $waittime) {
59         &WARN("interval == waittime == UNDEF for $codename.");
60         return;
61     }
62
63     my $time = $sched{$codename}{TIME};
64     if (defined $time and $time > time()) {
65         &WARN("Sched for $codename already exists.");
66         return;
67     }
68
69 #    &VERB("Scheduling \&$codename() for ".&Time2String($waittime),3);
70
71     my $retval = $conn->schedule($waittime, \&$codename, @args);
72     $sched{$codename}{LABEL}    = $retval;
73     $sched{$codename}{TIME}     = time()+$waittime;
74     $sched{$codename}{RUNNING}  = 1;
75 }
76
77 ####
78 #### LET THE FUN BEGIN.
79 ####
80
81 sub randomQuote {
82     my $interval = &getChanConfDefault("randomQuoteInterval", 60);
83     if (@_) {
84         &ScheduleThis($interval, "randomQuote");
85         return if ($_[0] eq "2");       # defer.
86     } else {
87         delete $sched{"randomQuote"}{RUNNING};
88     }
89
90     my $line = &getRandomLineFromFile($bot_misc_dir. "/blootbot.randtext");
91     if (!defined $line) {
92         &ERROR("random Quote: weird error?");
93         return;
94     }
95
96     foreach ( &ChanConfList("randomQuote") ) {
97         next unless (&validChan($_));   # ???
98
99         &status("sending random Quote to $_.");
100         &action($_, "Ponders: ".$line);
101     }
102     ### TODO: if there were no channels, don't reschedule until channel
103     ###         configuration is modified.
104 }
105
106 sub randomFactoid {
107     my ($key,$val);
108     my $error = 0;
109
110     my $interval = &getChanConfDefault("randomFactoidInterval", 60);
111     if (@_) {
112         &ScheduleThis($interval, "randomFactoid");
113         return if ($_[0] eq "2");       # defer.
114     } else {
115         delete $sched{"randomFactoid"}{RUNNING};
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 ($val !~ /^</);
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     } else {
146         delete $sched{"randomFreshmeat"}{RUNNING};
147     }
148
149     my @chans = &ChanConfList("randomFreshmeat");
150     return unless (scalar @chans);
151
152     &Forker("freshmeat", sub {
153         my $retval = &Freshmeat::randPackage();
154
155         foreach (@chans) {
156             next unless (&validChan($_));       # ???
157
158             &status("sending random Freshmeat to $_.");
159             &say($_, $line);
160         }
161     } );
162 }
163
164 sub logLoop {
165     if (@_) {
166         &ScheduleThis(60, "logLoop");
167         return if ($_[0] eq "2");       # defer.
168     } else {
169         delete $sched{"logLoop"}{RUNNING};
170     }
171
172     return unless (defined fileno LOG);
173     return unless (&IsParam("logfile"));
174     return unless (&IsParam("maxLogSize"));
175
176     ### check if current size is too large.
177     if ( -s $file{log} > $param{'maxLogSize'}) {
178         my $date = sprintf("%04d%02d%02d", (localtime)[5,4,3]);
179         $file{log} = $param{'logfile'} ."-". $date;
180         &status("cycling log file.");
181
182         if ( -e $file{log}) {
183             my $i = 1;
184             my $newlog;
185             while () {
186                 $newlog = $file{log}."-".$i;
187                 last if (! -e $newlog);
188                 $i++;
189             }
190             $file{log} = $newlog;
191         }
192
193         &closeLog();
194         system("/bin/mv '$param{'logfile'}' '$file{log}'");
195         &compress($file{log});
196         &openLog();
197         &status("cycling log file.");
198     }
199
200     ### check if all the logs exceed size.
201     my $logdir = "$bot_base_dir/log/";
202     if (opendir(LOGS, $logdir)) {
203         my $tsize = 0;
204         my (%age, %size);
205
206         while (defined($_ = readdir LOGS)) {
207             my $logfile         = "$logdir/$_";
208
209             next unless ( -f $logfile);
210             my $size            = -s $logfile;
211             my $age             = (stat $logfile)[9];
212
213             $age{$age}          = $logfile;
214             $size{$logfile}     = $size;
215
216             $tsize              += $size;
217         }
218         closedir LOGS;
219
220         my $delete      = 0;
221         while ($tsize > $param{'maxLogSize'}) {
222             &status("LOG: current size > max ($tsize > $param{'maxLogSize'})");
223             my $oldest  = (sort {$a <=> $b} keys %age)[0];
224             &status("LOG: unlinking $age{$oldest}.");
225             unlink $age{$oldest};
226             $tsize      -= $oldest;
227             $delete++;
228         }
229
230         ### TODO: add how many b,kb,mb removed?
231         &status("LOG: removed $delete logs.") if ($delete);
232     } else {
233         &WARN("could not open dir $logdir");
234     }
235
236 }
237
238 sub seenFlushOld {
239     if (@_) {
240         &ScheduleThis(1440, "seenFlushOld");
241         return if ($_[0] eq "2");       # defer.
242     } else {
243         delete $sched{"seenFlushOld"}{RUNNING};
244     }
245
246     # is this global-only?
247     return unless (&IsChanConf("seen") > 0);
248     return unless (&IsChanConf("seenFlushInterval") > 0);
249
250     # global setting. does not make sense for per-channel.
251     my $max_time = &getChanConfDefault("seenMaxDays", 30) *60*60*24;
252     my $delete   = 0;
253
254     if ($param{'DBType'} =~ /^pg|postgres|mysql/i) {
255         my $query = "SELECT nick,time FROM seen GROUP BY nick HAVING UNIX_TIMESTAMP() - time > $max_time";
256         my $sth = $dbh->prepare($query);
257         $sth->execute;
258
259         while (my @row = $sth->fetchrow_array) {
260             my ($nick,$time) = @row;
261
262             &dbDel("seen","nick",$nick);
263             $delete++;
264         }
265         $sth->finish;
266     } elsif ($param{'DBType'} =~ /^dbm/i) {
267         my $time = time();
268
269         foreach (keys %seen) {
270             my $delta_time = $time - &dbGet("seen", "NULL", $_, "time");
271             next unless ($delta_time > $max_time);
272
273             &DEBUG("seenFlushOld: ".&Time2String($delta_time) );
274             delete $seen{$_};
275             $delete++;
276         }
277     } else {
278         &FIXME("seenFlushOld: for PG/NO-DB.");
279     }
280     &VERB("SEEN deleted $delete seen entries.",2);
281
282 }
283
284 sub chanlimitCheck {
285     my $interval = &getChanConfDefault("chanlimitcheckInterval", 10);
286
287     if (@_) {
288         &ScheduleThis($interval, "chanlimitCheck");
289         return if ($_[0] eq "2");
290     } else {
291         delete $sched{"chanlimitCheck"}{RUNNING};
292     }
293
294     foreach ( &ChanConfList("chanlimitcheck") ) {
295         next unless (&validChan($_));   # ???
296
297         my $limitplus   = &getChanConfDefault("chanlimitcheckPlus", 5, $_);
298         my $newlimit    = scalar(keys %{$channels{$_}{''}}) + $limitplus;
299         my $limit       = $channels{$_}{'l'};
300
301         if (scalar keys %{$channels{$_}{''}} > $limit) {
302             &status("LIMIT: set too low!!! FIXME");
303             ### run NAMES again and flush it.
304         }
305
306         next unless (!defined $limit or $limit != $newlimit);
307
308         if (!exists $channels{$_}{'o'}{$ident}) {
309             &ERROR("chanlimitcheck: dont have ops on $_.");
310             next;
311         }
312         &rawout("MODE $_ +l $newlimit");
313     }
314
315 }
316
317 sub netsplitCheck {
318     my ($s1,$s2);
319
320     if (@_) {
321         &ScheduleThis(30, "netsplitCheck");
322         return if ($_[0] eq "2");
323     } else {
324         delete $sched{"netsplitCheck"}{RUNNING};
325     }
326
327     foreach $s1 (keys %netsplitservers) {
328         foreach $s2 (keys %{$netsplitservers{$s1}}) {
329             if (time() - $netsplitservers{$s1}{$s2} > 3600) {
330                 &status("netsplit between $s1 and $s2 appears to be stale.");
331                 delete $netsplitservers{$s1}{$s2};
332             }
333         }
334     }
335
336     # %netsplit hash checker.
337     foreach (keys %netsplit) {
338         if (&IsNickInAnyChan($_)) {
339             &DEBUG("netsplitC: $_ is in some chan; removing from netsplit list.");
340             delete $netsplit{$_};
341         }
342         next unless (time() - $netsplit{$_} > 60*60*2); # 2 hours.
343         next if (&IsNickInAnyChan($_));
344
345         &DEBUG("netsplitC: $_ didn't come back from netsplit in 2 hours; removing from netsplit list.");
346         delete $netsplit{$_};
347     }
348 }
349
350 sub floodLoop {
351     my $delete   = 0;
352     my $who;
353
354     if (@_) {
355         &ScheduleThis(60, "floodLoop"); # minutes.
356         return if ($_[0] eq "2");
357     } else {
358         delete $sched{"floodLoop"}{RUNNING};
359     }
360
361     my $time            = time();
362     my $interval        = &getChanConfDefault("floodCycle",60);
363
364     foreach $who (keys %flood) {
365         foreach (keys %{$flood{$who}}) {
366             if (!exists $flood{$who}{$_}) {
367                 &WARN("flood{$who}{$_} undefined?");
368                 next;
369             }
370
371             if ($time - $flood{$who}{$_} > $interval) {
372                 delete $flood{$who}{$_};
373                 $delete++;
374             }
375         }
376     }
377     &VERB("floodLoop: deleted $delete items.",2);
378 }
379
380 sub seenFlush {
381     my %stats;
382     my $nick;
383     my $flushed         = 0;
384     $stats{'count_old'} = &countKeys("seen") || 0;
385     $stats{'new'}       = 0;
386     $stats{'old'}       = 0;
387
388     if (@_) {
389         my $interval = &getChanConfDefault("seenFlushInterval", 60);
390         &ScheduleThis($interval, "seenFlush");
391         return if ($_[0] eq "2");
392     } else {
393         delete $sched{"seenFlush"}{RUNNING};
394     }
395
396     if ($param{'DBType'} =~ /^mysql|pg|postgres/i) {
397         foreach $nick (keys %seencache) {
398             my $exists = &dbGet("seen","nick", $nick, "nick");
399
400             if (defined $exists and $exists) {
401                 &dbUpdate("seen", "nick", $nick, (
402                         "time" => $seencache{$nick}{'time'},
403                         "host" => $seencache{$nick}{'host'},
404                         "channel" => $seencache{$nick}{'chan'},
405                         "message" => $seencache{$nick}{'msg'},
406                 ) );
407                 $stats{'old'}++;
408             } else {
409                 my $retval = &dbInsert("seen", $nick, (
410                         "nick" => $seencache{$nick}{'nick'},
411                         "time" => $seencache{$nick}{'time'},
412                         "host" => $seencache{$nick}{'host'},
413                         "channel" => $seencache{$nick}{'chan'},
414                         "message" => $seencache{$nick}{'msg'},
415                 ) );
416                 $stats{'new'}++;
417
418                 ### TODO: put bad nick into a list and don't do it again!
419                 &FIXME("Should never happen! (nick => $nick)") if !$retval;
420             }
421
422             delete $seencache{$nick};
423             $flushed++;
424         }
425
426     } elsif ($param{'DBType'} =~ /^dbm/i) {
427
428         foreach $nick (keys %seencache) {
429             my $retval = &dbInsert("seen", $nick, (
430                 "nick" => $seencache{$nick}{'nick'},
431                 "time" => $seencache{$nick}{'time'},
432                 "host" => $seencache{$nick}{'host'},
433                 "channel" => $seencache{$nick}{'chan'},
434                 "message" => $seencache{$nick}{'msg'},
435             ) );
436
437             ### TODO: put bad nick into a list and don't do it again!
438             &FIXME("Should never happen! (nick => $nick)") if !$retval;
439
440             delete $seencache{$nick};
441             $flushed++;
442         }
443     } else {
444         &DEBUG("seenFlush: NO VALID FACTOID SUPPORT?");
445     }
446
447     &status("Flushed $flushed seen entries.")           if ($flushed);
448     &VERB(sprintf("  new seen: %03.01f%% (%d/%d)",
449         $stats{'new'}*100/$stats{'count_old'},
450         $stats{'new'}, $stats{'count_old'} ), 2)        if ($stats{'new'});
451     &VERB(sprintf("  now seen: %3.1f%% (%d/%d)",
452         $stats{'old'}*100/&countKeys("seen"),
453         $stats{'old'}, &countKeys("seen") ), 2)         if ($stats{'old'});
454
455     &WARN("scalar keys seenflush != 0!")        if (scalar keys %seenflush);
456
457 }
458
459 sub leakCheck {
460     my ($blah1,$blah2);
461     my $count = 0;
462
463     if (@_) {
464         &ScheduleThis(240, "leakCheck");
465         return if ($_[0] eq "2");
466     } else {
467         delete $sched{"leakCheck"}{RUNNING};
468     }
469
470     # flood.
471     foreach $blah1 (keys %flood) {
472         foreach $blah2 (keys %{$flood{$blah1}}) {
473             $count += scalar(keys %{$flood{$blah1}{$blah2}});
474         }
475     }
476     &VERB("\%flood has $count total keys.",2);
477
478     my $chan;
479     foreach $chan (grep /[A-Z]/, keys %channels) {
480         &DEBUG("leak: chan => '$chan'.");
481         my ($i,$j);
482         foreach $i (keys %{$channels{$chan}}) {
483             foreach (keys %{$channels{$chan}{$i}}) {
484                 &DEBUG("leak:   \$channels{$chan}{$i}{$_} ...");
485             }
486         }
487     }
488
489     my $delete  = 0;
490     foreach (keys %nuh) {
491         next if (&IsNickInAnyChan($_));
492         next if (exists $dcc{CHAT}{$_});
493
494         delete $nuh{$_};
495         $delete++;
496     }
497
498     &DEBUG("$delete nuh{} items deleted; now have ".
499                                 scalar(keys %nuh) ) if ($delete);
500 }
501
502 sub ignoreCheck {
503     if (@_) {
504         &ScheduleThis(60, "ignoreCheck");
505         return if ($_[0] eq "2");       # defer.
506     } else {
507         delete $sched{"ignoreCheck"}{RUNNING};
508     }
509
510     my $time    = time();
511     my $count   = 0;
512
513     foreach (keys %ignore) {
514         my $chan = $_;
515
516         foreach (keys %{ $ignore{$chan} }) {
517             my @array = @{ $ignore{$chan}{$_} };
518
519             next unless ($array[0] and $time > $array[0]);
520
521             delete $ignore{$chan}{$_};
522             &status("ignore: $_/$chan has expired.");
523             $count++;
524         }
525     }
526     &VERB("ignore: $count items deleted.",2);
527 }
528
529 sub ircCheck {
530
531     if (@_) {
532         &ScheduleThis(120, "ircCheck");
533         return if ($_[0] eq "2");       # defer.
534     } else {
535         delete $sched{"ircCheck"}{RUNNING};
536     }
537
538     my @array = grep !/^_default$/, keys %chanconf;
539     my $iconf = scalar(@array);
540     my $inow  = scalar(keys %channels);
541     if ($iconf > 2 and $inow * 2 <= $iconf) {
542         &FIXME("ircCheck: current channels * 2 <= config channels. FIXME.");
543     }
544
545     # chanserv ops.
546     foreach ( &ChanConfList("chanServ_ops") ) {
547         next if (exists $channels{$chan}{'o'}{$ident});
548
549         &status("ChanServ ==> Requesting ops for $chan.");
550         &rawout("PRIVMSG ChanServ :OP $chan $ident");
551     }
552
553     if (!$conn->connected and time - $msgtime > 3600) {
554         &WARN("ircCheck: no msg for 3600 and disco'd! reconnecting!");
555         $msgtime = time();      # just in case.
556         &ircloop();
557     }
558
559     if ($ident !~ /^\Q$param{ircNick}\E$/) {
560         &WARN("ircCheck: ident($ident) != param{ircNick}($param{IrcNick}).");
561         ### TODO: schedule check for own nick if taken?
562     }
563
564     &joinNextChan();
565         # if scalar @joinnext => join more channels
566         # else check for chanserv.
567
568     if (grep /^\s*$/, keys %channels) {
569         &WARN("we have a NULL chan in hash channels? removing!");
570         delete $channels{''};   # ???
571         &DEBUG("channels now:");
572         foreach (keys %channels) {
573             &status("  $_");
574         }
575         &DEBUG("channels END");
576     }
577
578     ### USER FILE.
579     if ($utime_userfile > $wtime_userfile and time() - $wtime_userfile > 3600) {
580         &writeUserFile();
581         $wtime_userfile = time();
582     }
583     ### CHAN FILE.
584     if ($utime_chanfile > $wtime_chanfile and time() - $wtime_chanfile > 3600) {
585         &writeChanFile();
586         $wtime_chanfile = time();
587     }
588 }
589
590 sub miscCheck {
591     if (@_) {
592         &ScheduleThis(240, "miscCheck");
593         return if ($_[0] eq "2");       # defer.
594     } else {
595         delete $sched{"miscCheck"}{RUNNING};
596     }
597
598     # SHM check.
599     my @ipcs;
600     if ( -x "/usr/bin/ipcs") {
601         @ipcs = `/usr/bin/ipcs`;
602     } else {
603         &WARN("ircCheck: no 'ipcs' binary.");
604         return;
605     }
606
607     # shmid stale remove.
608     foreach (@ipcs) {
609         chop;
610
611         # key, shmid, owner, perms, bytes, nattch
612         next unless (/^(0x\d+) (\d+)\s+(\S+)\s+(\d+)\s+(\d+)\s+/);
613
614         my ($shmid, $size) = ($2,$5);
615         next unless ($shmid != $shm and $size == 2000);
616         my $z   = &shmRead($shmid);
617         if ($z =~ /^(\d+): /) {
618             my $time    = $1;
619             next if (time() - $time < 60*60);
620
621         } else {
622             &DEBUG("shm: $shmid is not ours or old blootbot => ($z)");
623             next;
624         }
625
626         &status("SHM: nuking shmid $shmid");
627         system("/usr/bin/ipcrm shm $shmid >/dev/null");
628     }
629
630     # debian check.
631     opendir(DEBIAN, "$bot_base_dir/debian");
632     foreach ( grep /gz$/, readdir(DEBIAN) ) {
633         my $exit = system("gzip -t $bot_base_dir/debian/$_");
634         next unless ($exit);
635
636         &status("debian: unlinking file => $_");
637         unlink "$bot_base_dir/debian/$_";
638     }
639     closedir DEBIAN;
640
641     ### check modules if they've been modified. might be evil.
642     &reloadAllModules();
643 }
644
645 sub shmFlush {
646     return if ($$ != $::bot_pid); # fork protection.
647
648     if (@_) {
649         &ScheduleThis(5, "shmFlush");
650         return if ($_[0] eq "2");
651     } else {
652         delete $sched{"shmFlush"}{RUNNING};
653     }
654
655     my $time;
656     my $shmmsg = &shmRead($shm);
657     $shmmsg =~ s/\0//g;         # remove padded \0's.
658     if ($shmmsg =~ s/^(\d+): //) {
659         $time   = $1;
660     }
661
662     foreach (split '\|\|', $shmmsg) {
663         next if (/^$/);
664         &VERB("shm: Processing '$_'.",2);
665
666         if (/^DCC SEND (\S+) (\S+)$/) {
667             my ($nick,$file) = ($1,$2);
668             if (exists $dcc{'SEND'}{$who}) {
669                 &msg($nick, "DCC already active.");
670             } else {
671                 &DEBUG("shm: dcc sending $2 to $1.");
672                 $conn->new_send($1,$2);
673                 $dcc{'SEND'}{$who} = time();
674             }
675         } elsif (/^SET FORKPID (\S+) (\S+)/) {
676             $forked{$1}{PID} = $2;
677         } elsif (/^DELETE FORK (\S+)$/) {
678             delete $forked{$1};
679         } elsif (/^EVAL (.*)$/) {
680             &DEBUG("evaling '$1'.");
681             eval $1;
682         } else {
683             &DEBUG("shm: unknown msg. ($_)");
684         }
685     }
686
687     &shmWrite($shm,"") if ($shmmsg ne "");
688 }
689
690 ### this is semi-scheduled
691 sub getNickInUse {
692     if (@_) {
693         &ScheduleThis(30, "getNickInUse");
694         return if ($_[0] eq "2");       # defer.
695     } else {
696         delete $sched{"getNickInUse"}{RUNNING};
697     }
698
699     if ($ident eq $param{'ircNick'}) {
700         &status("okay, got my nick back.");
701         return;
702     }
703
704     &status("Trying to get my nick back.");
705     &nick( $param{'ircNick'} );
706 }
707
708 sub uptimeLoop {
709     if (@_) {
710         &ScheduleThis(60, "uptimeLoop");
711         return if ($_[0] eq "2");       # defer.
712     } else {
713         delete $sched{"uptimeLoop"}{RUNNING};
714     }
715
716     &uptimeWriteFile();
717 }
718
719 sub slashdotLoop {
720
721     if (@_) {
722         &ScheduleThis(60, "slashdotLoop");
723         return if ($_[0] eq "2");
724     } else {
725         delete $sched{"slashdotLoop"}{RUNNING};
726     }
727
728     my @chans = &ChanConfList("slashdotAnnounce");
729     return unless (scalar @chans);
730
731     &Forker("slashdot", sub {
732         my $line = &Slashdot::slashdotAnnounce();
733         return unless (defined $line);
734
735         foreach (@chans) {
736             next unless (&::validChan($_));
737
738             &::status("sending slashdot update to $_.");
739             &notice($_, "Slashdot: $line");
740         }
741     } );
742 }
743
744 sub freshmeatLoop {
745     if (@_) {
746         &ScheduleThis(60, "freshmeatLoop");
747         return if ($_[0] eq "2");
748     } else {
749         delete $sched{"freshmeatLoop"}{RUNNING};
750     }
751
752     my @chans = &ChanConfList("freshmeatAnnounce");
753     return unless (scalar @chans);
754
755     &Forker("freshmeat", sub {
756         my $data = &Freshmeat::freshmeatAnnounce();
757
758         foreach (@chans) {
759             next unless (&::validChan($_));
760
761             &::status("sending freshmeat update to $_.");
762             &msg($_, $data);
763         }
764     } );
765 }
766
767 sub kernelLoop {
768     if (@_) {
769         &ScheduleThis(240, "kernelLoop");
770         return if ($_[0] eq "2");
771     } else {
772         delete $sched{"kernelLoop"}{RUNNING};
773     }
774
775     my @chans = &ChanConfList("kernelAnnounce");
776     return unless (scalar @chans);
777
778     &Forker("kernel", sub {
779         my @data = &Kernel::kernelAnnounce();
780
781         foreach (@chans) {
782             next unless (&::validChan($_));
783
784             &::status("sending kernel update to $_.");
785             my $c = $_;
786             foreach (@data) {
787                 &notice($c, "Kernel: $_");
788             }
789         }
790     } );
791 }
792
793 sub wingateCheck {
794     return unless &IsChanConf("wingate");
795
796     ### FILE CACHE OF OFFENDING WINGATES.
797     foreach (grep /^$host$/, @wingateBad) {
798         &status("Wingate: RUNNING ON $host BY $who");
799         &ban("*!*\@$host", "") if &IsChanConf("wingateBan");
800
801         my $reason      = &getChanConf("wingateKick");
802
803         next unless ($reason);
804         &kick($who, "", $reason)
805     }
806
807     ### RUN CACHE OF TRIED WINGATES.
808     if (grep /^$host$/, @wingateCache) {
809         push(@wingateNow, $host);       # per run.
810         push(@wingateCache, $host);     # cache per run.
811     } else {
812         &DEBUG("Already scanned $host. good.");
813     }
814
815     my $interval = &getChanConfDefault("wingateInterval", 60); # seconds.
816     return if (defined $forked{'wingate'});
817     return if (time() - $wingaterun <= $interval);
818     return unless (scalar(keys %wingateToDo));
819
820     $wingaterun = time();
821
822     &Forker("wingate", sub { &Wingate::Wingates(keys %wingateToDo); } );
823     undef @wingateNow;
824 }
825
826 ### TODO.
827 sub wingateWriteFile {
828     if (@_) {
829         &ScheduleThis(60, "wingateWriteFile");
830         return if ($_[0] eq "2");       # defer.
831     } else {
832         delete $sched{"wingateWriteFile"}{RUNNING};
833     }
834
835     return unless (scalar @wingateCache);
836
837     my $file = "$bot_base_dir/$param{'ircUser'}.wingate";
838     if ($bot_pid != $$) {
839         &DEBUG("wingateWriteFile: Reorganising!");
840
841         open(IN, $file);
842         while (<IN>) {
843             chop;
844             push(@wingateNow, $_);
845         }
846         close IN;
847
848         # very lame hack.
849         my %hash = map { $_ => 1 } @wingateNow;
850         @wingateNow = sort keys %hash;
851     }
852
853     &DEBUG("wingateWF: writing...");
854     open(OUT, ">$file");
855     foreach (@wingateNow) {
856         print OUT "$_\n";
857     }
858     close OUT;
859
860 }
861
862 sub factoidCheck {
863     if (@_) {
864         &ScheduleThis(1440, "factoidCheck");
865         return if ($_[0] eq "2");       # defer.
866     } else {
867         delete $sched{"factoidCheck"}{RUNNING};
868     }
869
870     my @list = &searchTable("factoids", "factoid_key", "factoid_key", " #DEL#");
871     my $stale = &getChanConfDefault("factoidDeleteDelay", 7)*60*60*24;
872
873     my $time    = time();
874     foreach (@list) {
875         my $age = &getFactInfo($_, "modified_time");    
876         if (!defined $age or $age !~ /^\d+$/) {
877             &WARN("age == NULL or not numeric.");
878             next;
879         }
880
881         next unless ($time - $age > $stale);
882
883         my $fix = $_;
884         $fix =~ s/ #DEL#$//g;
885         &VERB("safedel: Removing $fix for good.",2);
886         &delFactoid($_);
887     }
888
889 }
890
891 sub dccStatus {
892     return unless (scalar keys %{ $dcc{CHAT} });
893
894     if (@_) {
895         &ScheduleThis(10, "dccStatus");
896         return if ($_[0] eq "2");       # defer.
897     } else {
898         delete $sched{"dccStatus"}{RUNNING};
899     }
900
901     my $time = strftime("%H:%M", localtime(time()) );
902
903     my $c;
904     foreach (keys %channels) {
905         my $c           = $_;
906         my $users       = keys %{ $channels{$c}{''} };
907         my $chops       = keys %{ $channels{$c}{o}  };
908         my $bans        = keys %{ $channels{$c}{b}  };
909
910         my $txt = "[$time] $c: $users members ($chops chops), $bans bans";
911         foreach (keys %{ $dcc{'CHAT'} }) {
912             next unless (exists $channels{$c}{''}{lc $_});
913             $conn->privmsg($dcc{'CHAT'}{$_}, $txt);
914         }
915     }
916 }
917
918 sub scheduleList {
919     ###
920     # custom:
921     #   a - time == now.
922     #   b - weird time.
923     ###
924
925     &DEBUG("sched:");
926     foreach (keys %{ $irc->{_queue} }) {
927         my $q = $_;
928
929         my $sched;
930         foreach (keys %sched) {
931             next unless ($q eq $sched{$_});
932             $sched = $_;
933             last;
934         }
935
936         my $time = $irc->{_queue}->{$q}->[0] - time();
937
938         if (defined $sched) {
939             &DEBUG("   $sched($q): ".&Time2String($time) );
940         } else {
941             &DEBUG("   NULL($q): ".&Time2String($time) );
942         }
943     }
944
945     &DEBUG("end of sList.");
946 }
947
948 sub getChanConfDefault {
949     my($what, $default, $chan) = @_;
950
951     if (exists $param{$what}) {
952         if (!exists $cache{config}{$what}) {
953             &status("gCCD: backward-compat: found param{$what} ($param{$what}) instead.");
954             $cache{config}{$what} = 1;
955         }
956
957         return $param{$what};
958     }
959
960     my $val = &getChanConf($what, $chan);
961     if (defined $val) {
962         return $val;
963     }
964
965     $param{$what}       = $default;
966     &status("gCCD: setting default for param{$what} = $default");
967     $cache{config}{$what} = 1;
968
969     return $default;
970 }
971
972 1;