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