]> git.donarmstrong.com Git - infobot.git/blob - src/IRC/Irc.pl
* Add vim formatting comments ( # vim:ts=4:sw=4:expandtab:tw=80 )
[infobot.git] / src / IRC / Irc.pl
1 #
2 #    Irc.pl: IRC core stuff.
3 #    Author: dms
4 #   Version: 20000126
5 #      NOTE: Based on code by Kevin Lenzo & Patrick Cole  (c) 1997
6 #
7
8 use strict;
9
10 no strict 'refs';
11 no strict 'subs'; # IN/STDIN
12
13 use vars qw(%floodjoin %nuh %dcc %cache %conns %channels %param %mask
14         %chanconf %orig %ircPort %ircstats %last %netsplit);
15 use vars qw($irc $nickserv $conn $msgType $who $talkchannel
16         $addressed $postprocess);
17 use vars qw($notcount $nottime $notsize $msgcount $msgtime $msgsize
18                 $pubcount $pubtime $pubsize);
19 use vars qw($b_blue $ob);
20 use vars qw(@ircServers);
21
22 #use open ':utf8';
23 #use open ':std';
24
25 $nickserv       = 0;
26 # It's probably closer to 510, but let's be cautious until we calculate it extensively.
27 my $maxlinelen  = 490;
28
29 # Keep track of last time we displayed Chans: to avoid spam in logs
30 my $lastChansTime = 0;
31
32 sub ircloop {
33     my $error   = 0;
34     my $lastrun = 0;
35
36 loop:;
37     while (my $host = shift @ircServers) {
38         # JUST IN CASE. irq was complaining about this.
39         if ($lastrun == time()) {
40             &DEBUG("ircloop: hrm... lastrun == time()");
41             $error++;
42             sleep 10;
43             next;
44         }
45
46         if (!defined $host) {
47             &DEBUG("ircloop: ircServers[x] = NULL.");
48             $lastrun = time();
49             next;
50         }
51         next unless (exists $ircPort{$host});
52
53         my $retval      = &irc($host, $ircPort{$host});
54         next unless (defined $retval and $retval == 0);
55         $error++;
56
57         if ($error % 3 == 0 and $error != 0) {
58             &status("IRC: Could not connect.");
59             &status("IRC: ");
60             next;
61         }
62
63         if ($error >= 3*2) {
64             &status("IRC: cannot connect to any IRC servers; stopping.");
65             &shutdown();
66             exit 1;
67         }
68     }
69
70     &status("IRC: ok, done one cycle of IRC servers; trying again.");
71
72     &loadIRCServers();
73     goto loop;
74 }
75
76 sub irc {
77     my ($server,$port) = @_;
78
79     $irc = new Net::IRC;
80
81     # TODO: move all this to an sql table
82     my $iaddr = inet_aton($server);
83     my $paddr = sockaddr_in($port, $iaddr);
84     my $proto = getprotobyname('tcp');
85
86     # why was this here?
87     #select STDOUT;
88
89     # host->ip.
90     my $resolve;
91     if ($server =~ /\D$/) {
92         my $packed = scalar(gethostbyname($server));
93
94         if (!defined $packed) {
95             &status("  cannot resolve $server.");
96             return 0;
97         }
98
99         $resolve = inet_ntoa($packed);
100         ### warning in Sys/Hostname line 78???
101         ### caused inside Net::IRC?
102     }
103
104     my %args = (
105                 Nick    => $param{'ircNick'},
106                 Server  => $server,
107                 Port    => $port,
108                 Ircname => $param{'ircName'},
109     );
110     $args{'LocalAddr'} = $param{'ircHost'} if ($param{'ircHost'});
111     $args{'Password'} = $param{'ircPasswd'} if ($param{'ircPasswd'});
112
113     foreach my $mynick (split ',', $param{'ircNick'}) {
114         &status("Connecting to port $port of server $server ($resolve) as $mynick ...");
115         $args{'Nick'} = $mynick;
116         $conns{$mynick} = $irc->newconn(%args);
117         if (!defined $conns{$mynick}) {
118             &ERROR("IRC: connection failed.");
119             &ERROR("add \"set ircHost 0.0.0.0\" to your config. If that does not work");
120             &ERROR("Please check /etc/hosts to see if you have a localhost line like:");
121             &ERROR("127.0.0.1   localhost    localhost");
122             &ERROR("If this is still a problem, please contact the maintainer.");
123         }
124         $conns{$mynick}->maxlinelen($maxlinelen);
125         # handler stuff.
126         $conns{$mynick}->add_global_handler('caction',  \&on_action);
127         $conns{$mynick}->add_global_handler('cdcc',     \&on_dcc);
128         $conns{$mynick}->add_global_handler('cping',    \&on_ping);
129         $conns{$mynick}->add_global_handler('crping',   \&on_ping_reply);
130         $conns{$mynick}->add_global_handler('cversion', \&on_version);
131         $conns{$mynick}->add_global_handler('crversion',        \&on_crversion);
132         $conns{$mynick}->add_global_handler('dcc_open', \&on_dcc_open);
133         $conns{$mynick}->add_global_handler('dcc_close',        \&on_dcc_close);
134         $conns{$mynick}->add_global_handler('chat',     \&on_chat);
135         $conns{$mynick}->add_global_handler('msg',      \&on_msg);
136         $conns{$mynick}->add_global_handler('public',   \&on_public);
137         $conns{$mynick}->add_global_handler('join',     \&on_join);
138         $conns{$mynick}->add_global_handler('part',     \&on_part);
139         $conns{$mynick}->add_global_handler('topic',    \&on_topic);
140         $conns{$mynick}->add_global_handler('invite',   \&on_invite);
141         $conns{$mynick}->add_global_handler('kick',     \&on_kick);
142         $conns{$mynick}->add_global_handler('mode',     \&on_mode);
143         $conns{$mynick}->add_global_handler('nick',     \&on_nick);
144         $conns{$mynick}->add_global_handler('quit',     \&on_quit);
145         $conns{$mynick}->add_global_handler('notice',   \&on_notice);
146         $conns{$mynick}->add_global_handler('whoischannels', \&on_whoischannels);
147         $conns{$mynick}->add_global_handler('useronchannel', \&on_useronchannel);
148         $conns{$mynick}->add_global_handler('whois',    \&on_whois);
149         $conns{$mynick}->add_global_handler('other',    \&on_other);
150         $conns{$mynick}->add_global_handler('disconnect', \&on_disconnect);
151         $conns{$mynick}->add_global_handler([251,252,253,254,255], \&on_init);
152 #       $conns{$mynick}->add_global_handler(302, \&on_init); # userhost
153         $conns{$mynick}->add_global_handler(303, \&on_ison); # notify.
154         $conns{$mynick}->add_global_handler(315, \&on_endofwho);
155         $conns{$mynick}->add_global_handler(422, \&on_endofwho); # nomotd.
156         $conns{$mynick}->add_global_handler(324, \&on_modeis);
157         $conns{$mynick}->add_global_handler(333, \&on_topicinfo);
158         $conns{$mynick}->add_global_handler(352, \&on_who);
159         $conns{$mynick}->add_global_handler(353, \&on_names);
160         $conns{$mynick}->add_global_handler(366, \&on_endofnames);
161         $conns{$mynick}->add_global_handler(376, \&on_endofmotd); # on_connect.
162         $conns{$mynick}->add_global_handler(433, \&on_nick_taken);
163         $conns{$mynick}->add_global_handler(439, \&on_targettoofast);
164         # for proper joinnextChan behaviour
165         $conns{$mynick}->add_global_handler(471, \&on_chanfull);
166         $conns{$mynick}->add_global_handler(473, \&on_inviteonly);
167         $conns{$mynick}->add_global_handler(474, \&on_banned);
168         $conns{$mynick}->add_global_handler(475, \&on_badchankey);
169         $conns{$mynick}->add_global_handler(443, \&on_useronchan);
170         # end of handler stuff.
171     }
172
173     &clearIRCVars();
174
175     # change internal timeout value for scheduler.
176     $irc->{_timeout}    = 10;   # how about 60?
177     # Net::IRC debugging.
178     $irc->{_debug}      = 1;
179
180     $ircstats{'Server'} = "$server:$port";
181
182     # works? needs to actually do something
183     # should likely listen on a tcp port instead
184     #$irc->addfh(STDIN, \&on_stdin, 'r');
185
186     &status("starting main loop");
187
188     $irc->start;
189 }
190
191 ######################################################################
192 ######## IRC ALIASES   IRC ALIASES   IRC ALIASES   IRC ALIASES #######
193 ######################################################################
194
195 sub rawout {
196     my ($buf) = @_;
197     $buf =~ s/\n//gi;
198
199     # slow down a bit if traffic is 'high'.
200     # need to take into account time of last message sent.
201     if ($last{buflen} > 256 and length($buf) > 256) {
202         sleep 1;
203     }
204
205     $conn->sl($buf) if (&whatInterface() =~ /IRC/);
206
207     $last{buflen} = length($buf);
208 }
209
210 sub say {
211     my ($msg) = @_;
212     my $mynick = $conn->nick();
213     if (!defined $msg) {
214         $msg ||= 'NULL';
215         &WARN("say: msg == $msg.");
216         return;
217     }
218
219     if (&getChanConf('silent', $talkchannel) and not
220       (&IsFlag("s") and &verifyUser($who,$nuh{lc $who}))) {
221         &DEBUG("say: silent in $talkchannel, not saying $msg");
222         return;
223     }
224
225     if ( $postprocess ) {
226         undef $postprocess;
227     } elsif ($postprocess = &getChanConf('postprocess', $talkchannel)) {
228         &DEBUG("say: $postprocess $msg");
229         &parseCmdHook($postprocess . ' ' . $msg);
230         undef $postprocess;
231         return;
232     }
233
234     &status("<$mynick/$talkchannel> $msg");
235
236     return unless (&whatInterface() =~ /IRC/);
237
238     $msg = 'zero' if ($msg =~ /^0+$/);
239
240     my $t = time();
241
242     if ($t == $pubtime) {
243         $pubcount++;
244         $pubsize += length $msg;
245
246         my $i = &getChanConfDefault('sendPublicLimitLines', 3, $chan);
247         my $j = &getChanConfDefault('sendPublicLimitBytes', 1000, $chan);
248
249         if ( ($pubcount % $i) == 0 and $pubcount) {
250             sleep 1;
251         } elsif ($pubsize > $j) {
252             sleep 1;
253             $pubsize -= $j;
254         }
255
256     } else {
257         $pubcount       = 0;
258         $pubtime        = $t;
259         $pubsize        = length $msg;
260     }
261
262     $conn->privmsg($talkchannel, $msg);
263 }
264
265 sub msg {
266     my ($nick, $msg) = @_;
267     if (!defined $nick) {
268         &ERROR("msg: nick == NULL.");
269         return;
270     }
271
272     if (!defined $msg) {
273         $msg ||= 'NULL';
274         &WARN("msg: msg == $msg.");
275         return;
276     }
277
278     # some say() end up here (eg +help)
279     if (&getChanConf('silent', $nick) and not
280        (&IsFlag("s") and &verifyUser($who,$nuh{lc $who}))) {
281         &DEBUG("msg: silent in $nick, not saying $msg");
282         return;
283     }
284
285     &status(">$nick< $msg");
286
287     return unless (&whatInterface() =~ /IRC/);
288     my $t = time();
289
290     if ($t == $msgtime) {
291         $msgcount++;
292         $msgsize += length $msg;
293
294         my $i = &getChanConfDefault('sendPrivateLimitLines', 3, $chan);
295         my $j = &getChanConfDefault('sendPrivateLimitBytes', 1000, $chan);
296         if ( ($msgcount % $i) == 0 and $msgcount) {
297             sleep 1;
298         } elsif ($msgsize > $j) {
299             sleep 1;
300             $msgsize -= $j;
301         }
302
303     } else {
304         $msgcount       = 0;
305         $msgtime        = $t;
306         $msgsize        = length $msg;
307     }
308
309     $conn->privmsg($nick, $msg);
310 }
311
312 # Usage: &action(nick || chan, txt);
313 sub action {
314     my $mynick = $conn->nick();
315     my ($target, $txt) = @_;
316     if (!defined $txt) {
317         &WARN("action: txt == NULL.");
318         return;
319     }
320
321     if (&getChanConf('silent', $target) and not
322        (&IsFlag("s") and &verifyUser($who,$nuh{lc $who}))) {
323         &DEBUG("action: silent in $target, not doing $txt");
324         return;
325     }
326
327     if (length $txt > 480) {
328         &status("action: txt too long; truncating.");
329         chop($txt) while (length $txt > 480);
330     }
331
332     &status("* $mynick/$target $txt");
333     $conn->me($target, $txt);
334 }
335
336 # Usage: &notice(nick || chan, txt);
337 sub notice {
338     my ($target, $txt) = @_;
339     if (!defined $txt) {
340         &WARN("notice: txt == NULL.");
341         return;
342     }
343
344     &status("-$target- $txt");
345
346     my $t       = time();
347
348     if ($t == $nottime) {
349         $notcount++;
350         $notsize += length $txt;
351
352         my $i = &getChanConfDefault('sendNoticeLimitLines', 3, $chan);
353         my $j = &getChanConfDefault('sendNoticeLimitBytes', 1000, $chan);
354
355         if ( ($notcount % $i) == 0 and $notcount) {
356             sleep 1;
357         } elsif ($notsize > $j) {
358             sleep 1;
359             $notsize -= $j;
360         }
361
362     } else {
363         $notcount       = 0;
364         $nottime        = $t;
365         $notsize        = length $txt;
366     }
367
368     $conn->notice($target, $txt);
369 }
370
371 sub DCCBroadcast {
372     my ($txt,$flag) = @_;
373
374     ### FIXME: flag not supported yet.
375
376     foreach (keys %{ $dcc{'CHAT'} }) {
377         $conn->privmsg($dcc{'CHAT'}{$_}, $txt);
378     }
379 }
380
381 ##########
382 ### perform commands.
383 ###
384
385 # Usage: &performReply($reply);
386 sub performReply {
387     my ($reply) = @_;
388
389     if (!defined $reply or $reply =~ /^\s*$/) {
390         &DEBUG("performReply: reply == NULL.");
391         return;
392     }
393
394     $reply =~ /([\.\?\s]+)$/;
395
396     # FIXME need real throttling....
397     if (length($reply) > $maxlinelen - 30) {
398         $reply = substr($reply, 0, $maxlinelen - 33);
399         $reply =~ s/ [^ ]*?$/ .../;
400     }
401     &checkMsgType($reply);
402
403     if ($msgType eq 'public') {
404         if (rand() < 0.5 or $reply =~ /[\.\?]$/) {
405             $reply = "$orig{who}: ".$reply;
406         } else {
407             $reply = "$reply, ".$orig{who};
408         }
409         &say($reply);
410
411     } elsif ($msgType eq 'private') {
412         if (rand() > 0.5) {
413             $reply = "$reply, ".$orig{who};
414         }
415         &msg($who, $reply);
416
417     } elsif ($msgType eq 'chat') {
418         if (!exists $dcc{'CHAT'}{$who}) {
419             &VERB("pSR: dcc{'CHAT'}{$who} does not exist.",2);
420             return;
421         }
422         $conn->privmsg($dcc{'CHAT'}{$who}, $reply);
423
424     } else {
425         &ERROR("PR: msgType invalid? ($msgType).");
426     }
427 }
428
429 # ...
430 sub performAddressedReply {
431     return unless ($addressed);
432     &performReply(@_);
433 }
434
435 # Usage: &performStrictReply($reply);
436 sub performStrictReply {
437     my ($reply) = @_;
438
439     # FIXME need real throttling....
440     if (length($reply) > $maxlinelen - 30) {
441         $reply = substr($reply, 0, $maxlinelen - 33);
442         $reply =~ s/ [^ ]*?$/ .../;
443     }
444     &checkMsgType($reply);
445
446     if ($msgType eq 'private') {
447         &msg($who, $reply);
448     } elsif ($msgType eq 'public') {
449         &say($reply);
450     } elsif ($msgType eq 'chat') {
451         &dccsay(lc $who, $reply);
452     } else {
453         &ERROR("pSR: msgType invalid? ($msgType).");
454     }
455 }
456
457 sub dccsay {
458     my($who, $reply) = @_;
459
460     if (!defined $reply or $reply =~ /^\s*$/) {
461         &WARN("dccsay: reply == NULL.");
462         return;
463     }
464
465     if (!exists $dcc{'CHAT'}{$who}) {
466         &VERB("pSR: dcc{'CHAT'}{$who} does not exist. (2)",2);
467         return;
468     }
469
470     &status("=>$who<= $reply");         # dcc chat.
471     $conn->privmsg($dcc{'CHAT'}{$who}, $reply);
472 }
473
474 sub dcc_close {
475     my($who) = @_;
476     my $type;
477
478     foreach $type (keys %dcc) {
479         &FIXME("dcc_close: $who");
480         my @who = grep /^\Q$who\E$/i, keys %{ $dcc{$type} };
481         next unless (scalar @who);
482         $who = $who[0];
483         &DEBUG("dcc_close... close $who!");
484     }
485 }
486
487 sub joinchan {
488     my ($chan, $key) = @_;
489     $key ||= &getChanConf('chankey', $chan);
490     $key ||= '';
491
492     # forgot for about 2 years to implement channel keys when moving
493     # over to Net::IRC...
494
495     # hopefully validChan is right.
496     if (&validChan($chan)) {
497         &status("join: already on $chan?");
498     }
499     #} else {
500         &status("joining $b_blue$chan $key$ob");
501
502         return if ($conn->join($chan, $key));
503         return if (&validChan($chan));
504
505         &DEBUG("joinchan: join failed. trying connect!");
506         &clearIRCVars();
507         $conn->connect();
508     #}
509 }
510
511 sub part {
512     my $chan;
513
514     foreach $chan (@_) {
515         next if ($chan eq '');
516         $chan =~ tr/A-Z/a-z/;   # lowercase.
517
518         if ($chan !~ /^$mask{chan}$/) {
519             &WARN("part: chan is invalid ($chan)");
520             next;
521         }
522
523         &status("parting $chan");
524         if (!&validChan($chan)) {
525             &WARN("part: not on $chan; doing anyway");
526 #           next;
527         }
528
529         $conn->part($chan);
530         # deletion of $channels{chan} is done in &entryEvt().
531     }
532 }
533
534 sub mode {
535     my ($chan, @modes) = @_;
536     my $modes = join(" ", @modes);
537
538     if (&validChan($chan) == 0) {
539         &ERROR("mode: invalid chan => '$chan'.");
540         return;
541     }
542
543     &DEBUG("mode: MODE $chan $modes");
544
545     # should move to use Net::IRC's $conn->mode()... but too lazy.
546     rawout("MODE $chan $modes");
547 }
548
549 sub op {
550     my ($chan, @who) = @_;
551     my $os      = 'o' x scalar(@who);
552
553     &mode($chan, "+$os @who");
554 }
555
556 sub deop {
557     my ($chan, @who) = @_;
558     my $os = 'o' x scalar(@who);
559
560     &mode($chan, "-$os ".@who);
561 }
562
563 sub kick {
564     my ($nick,$chan,$msg) = @_;
565     my (@chans) = ($chan eq '') ? (keys %channels) : lc($chan);
566     my $mynick = $conn->nick();
567
568     if ($chan ne '' and &validChan($chan) == 0) {
569         &ERROR("kick: invalid channel $chan.");
570         return;
571     }
572
573     $nick =~ tr/A-Z/a-z/;
574
575     foreach $chan (@chans) {
576         if (!&IsNickInChan($nick,$chan)) {
577             &status("kick: $nick is not on $chan.") if (scalar @chans == 1);
578             next;
579         }
580
581         if (!exists $channels{$chan}{o}{$mynick}) {
582             &status("kick: do not have ops on $chan :(");
583             next;
584         }
585
586         &status("Kicking $nick from $chan.");
587         $conn->kick($chan, $nick, $msg);
588     }
589 }
590
591 sub ban {
592     my ($mask,$chan) = @_;
593     my (@chans) = ($chan =~ /^\*?$/) ? (keys %channels) : lc($chan);
594     my $mynick = $conn->nick();
595     my $ban     = 0;
596
597     if ($chan !~ /^\*?$/ and &validChan($chan) == 0) {
598         &ERROR("ban: invalid channel $chan.");
599         return;
600     }
601
602     foreach $chan (@chans) {
603         if (!exists $channels{$chan}{o}{$mynick}) {
604             &status("ban: do not have ops on $chan :(");
605             next;
606         }
607
608         &status("Banning $mask from $chan.");
609         &rawout("MODE $chan +b $mask");
610         $ban++;
611     }
612
613     return $ban;
614 }
615
616 sub unban {
617     my ($mask,$chan) = @_;
618     my (@chans) = ($chan =~ /^\*?$/) ? (keys %channels) : lc($chan);
619     my $mynick = $conn->nick();
620     my $ban     = 0;
621
622     &DEBUG("unban: mask = $mask, chan = @chans");
623
624     foreach $chan (@chans) {
625         if (!exists $channels{$chan}{o}{$mynick}) {
626             &status("unBan: do not have ops on $chan :(");
627             next;
628         }
629
630         &status("Removed ban $mask from $chan.");
631         &rawout("MODE $chan -b $mask");
632         $ban++;
633     }
634
635     return $ban;
636 }
637
638 sub quit {
639     my ($quitmsg) = @_;
640     if (defined $conn) {
641         &status("QUIT " . $conn->nick() . " has quit IRC ($quitmsg)");
642         $conn->quit($quitmsg);
643     } else {
644         &WARN("quit: could not quit!");
645     }
646 }
647
648 sub nick {
649     my ($newnick) = @_;
650     my $mynick = $conn->nick();
651
652     if (!defined $newnick) {
653         &ERROR("nick: nick == NULL.");
654         return;
655     }
656
657     if (!defined $mynick) {
658         &WARN("nick: mynick == NULL.");
659         return;
660     }
661
662     my $bad = 0;
663     $bad++ if (exists $nuh{$newnick});
664     $bad++ if (&IsNickInAnyChan($newnick));
665
666     if ($bad) {
667         &WARN("Nick: not going to try to change from $mynick to $newnick. [". scalar(gmtime). "]");
668         # hrm... over time we lose track of our own nick.
669         #return;
670     }
671
672     if ($newnick =~ /^$mask{nick}$/) {
673         &status("nick: Changing nick from $mynick to $newnick");
674         # ->nick() will NOT change cause we are using rawout?
675         &rawout("NICK $newnick");
676         return 1;
677     }
678     &DEBUG("nick: failed... why oh why (mynick=$mynick, newnick=$newnick)");
679     return 0;
680 }
681
682 sub invite {
683     my($who, $chan) = @_;
684     # TODO: check if $who or $chan are invalid.
685
686     $conn->invite($who, $chan);
687 }
688
689 ##########
690 # Channel related functions...
691 #
692
693 # Usage: &joinNextChan();
694 sub joinNextChan {
695     my $joined = 0;
696     foreach (sort keys %conns) {
697         $conn = $conns{$_};
698         my $mynick = $conn->nick();
699         my @join = getJoinChans(1);
700
701         if (scalar @join) {
702             my $chan = shift @join;
703             &joinchan($chan);
704
705             if (my $i = scalar @join) {
706                 &status("joinNextChan: $mynick $i chans to join.");
707             }
708             $joined = 1;
709         }
710     }
711     return if $joined;
712
713     if (exists $cache{joinTime}) {
714         my $delta       = time() - $cache{joinTime} - 5;
715         my $timestr     = &Time2String($delta);
716         # FIXME: @join should be @in instead (hacked to 10)
717         #my $rate       = sprintf("%.1f", $delta / @in);
718         my $rate        = sprintf("%.1f", $delta / 10);
719         delete $cache{joinTime};
720
721         &status("time taken to join all chans: $timestr; rate: $rate sec/join");
722     }
723
724     # chanserv check: global channels, in case we missed one.
725     foreach ( &ChanConfList('chanServ_ops') ) {
726         &chanServCheck($_);
727     }
728 }
729
730 # Usage: &getNickInChans($nick);
731 sub getNickInChans {
732     my ($nick) = @_;
733     my @array;
734
735     foreach (keys %channels) {
736         next unless (grep /^\Q$nick\E$/i, keys %{ $channels{$_}{''} });
737         push(@array, $_);
738     }
739
740     return @array;
741 }
742
743 # Usage: &getNicksInChan($chan);
744 sub getNicksInChan {
745     my ($chan) = @_;
746     my @array;
747
748     return keys %{ $channels{$chan}{''} };
749 }
750
751 sub IsNickInChan {
752     my ($nick,$chan) = @_;
753
754     $chan =~ tr/A-Z/a-z/;       # not lowercase unfortunately.
755
756     if ($chan =~ /^$/) {
757         &DEBUG("INIC: chan == NULL.");
758         return 0;
759     }
760
761     if (&validChan($chan) == 0) {
762         &ERROR("INIC: invalid channel $chan.");
763         return 0;
764     }
765
766     if (grep /^\Q$nick\E$/i, keys %{ $channels{$chan}{''} }) {
767         return 1;
768     } else {
769         foreach (keys %channels) {
770             next unless (/[A-Z]/);
771             &DEBUG("iNIC: hash channels contains mixed cased chan!!!");
772         }
773         return 0;
774     }
775 }
776
777 sub IsNickInAnyChan {
778     my ($nick) = @_;
779     my $chan;
780
781     foreach $chan (keys %channels) {
782         next unless (grep /^\Q$nick\E$/i, keys %{ $channels{$chan}{''}  });
783         return 1;
784     }
785     return 0;
786 }
787
788 # Usage: &validChan($chan);
789 sub validChan {
790     # TODO: use $c instead?
791     my ($chan) = @_;
792
793     if (!defined $chan or $chan =~ /^\s*$/) {
794         return 0;
795     }
796
797     if (lc $chan ne $chan) {
798         &WARN("validChan: lc chan != chan. ($chan); fixing.");
799         $chan =~ tr/A-Z/a-z/;
800     }
801
802     # it's possible that this check creates the hash if empty.
803     if (defined $channels{$chan} or exists $channels{$chan}) {
804         if ($chan =~ /^_?default$/) {
805 #           &WARN("validC: chan cannot be _default! returning 0!");
806             return 0;
807         }
808
809         return 1;
810     } else {
811         return 0;
812     }
813 }
814
815 ###
816 # Usage: &delUserInfo($nick,@chans);
817 sub delUserInfo {
818     my ($nick,@chans) = @_;
819     my ($mode,$chan);
820
821     foreach $chan (@chans) {
822         foreach $mode (keys %{ $channels{$chan} }) {
823             # use grep here?
824             next unless (exists $channels{$chan}{$mode}{$nick});
825
826             delete $channels{$chan}{$mode}{$nick};
827         }
828     }
829 }
830
831 sub clearChanVars {
832     my ($chan) = @_;
833
834     delete $channels{$chan};
835 }
836
837 sub clearIRCVars {
838     undef %channels;
839     undef %floodjoin;
840
841     $cache{joinTime}    = time();
842 }
843
844 sub getJoinChans {
845     # $show should contain the min number of seconds between display
846     # of the Chans: status line. Use 0 to disable
847     my $show = shift;
848
849     my @in;
850     my @skip;
851     my @join;
852
853     # Display "Chans:" only if more than $show seconds since last display
854     if (time() - $lastChansTime > $show) {
855         $lastChansTime = time();
856     } else {
857         $show = 0; # Don't display since < 15min since last
858     }
859
860     # can't join any if not connected
861     return @join if (!$conn);
862
863     my $nick = $conn->nick();
864
865     foreach (keys %chanconf) {
866         next if ($_ eq '_default');
867
868         my $skip = 0;
869         my $val = $chanconf{$_}{autojoin};
870
871         if (defined $val) {
872             $skip++ if ($val eq '0');
873             if ($val eq '1') {
874                 # convert old +autojoin to autojoin <nick>
875                 $val = lc $nick;
876                 $chanconf{$_}{autojoin} = $val;
877             }
878             $skip++ if (lc $val ne lc $nick);
879         } else {
880             $skip++;
881         }
882
883         if ($skip) {
884             push(@skip, $_);
885         } else {
886             if (defined $channels{$_} or exists $channels{$_}) {
887                 push(@in, $_);
888             } else {
889                 push(@join, $_);
890             }
891         }
892     }
893
894     my $str;
895     $str .= ' in:' . join(',', sort @in) if scalar @in;
896     $str .= ' skip:' . join(',', sort @skip) if scalar @skip;
897     $str .= ' join:' . join(',', sort @join) if scalar @join;
898
899     &status("Chans: ($nick)$str") if ($show);
900
901     return sort @join;
902 }
903
904 sub closeDCC {
905 #    &DEBUG("closeDCC called.");
906     my $type;
907
908     foreach $type (keys %dcc) {
909         next if ($type ne uc($type));
910
911         my $nick;
912         foreach $nick (keys %{ $dcc{$type} }) {
913             next unless (defined $nick);
914             &status("DCC CHAT: closing DCC $type to $nick.");
915             next unless (defined $dcc{$type}{$nick});
916
917             my $ref = $dcc{$type}{$nick};
918             &dccsay($nick, "bye bye, $nick") if ($type =~ /^chat$/i);
919             $dcc{$type}{$nick}->close();
920             delete $dcc{$type}{$nick};
921             &DEBUG("after close for $nick");
922         }
923         delete $dcc{$type};
924     }
925 }
926
927 sub joinfloodCheck {
928     my($who,$chan,$userhost) = @_;
929
930     return unless (&IsChanConf('joinfloodCheck') > 0);
931
932     if (exists $netsplit{lc $who}) {    # netsplit join.
933         &DEBUG("joinfloodCheck: $who was in netsplit; not checking.");
934     }
935
936     if (exists $floodjoin{$chan}{$who}{Time}) {
937         &WARN("floodjoin{$chan}{$who} already exists?");
938     }
939
940     $floodjoin{$chan}{$who}{Time} = time();
941     $floodjoin{$chan}{$who}{Host} = $userhost;
942
943     ### Check...
944     foreach (keys %floodjoin) {
945         my $c = $_;
946         my $count = scalar keys %{ $floodjoin{$c} };
947         next unless ($count > 5);
948         &DEBUG("joinflood: count => $count");
949
950         my $time;
951         foreach (keys %{ $floodjoin{$c} }) {
952             my $t = $floodjoin{$c}{$_}{Time};
953             next unless (defined $t);
954
955             $time += $t;
956         }
957         &DEBUG("joinflood: time => $time");
958         $time /= $count;
959
960         &DEBUG("joinflood: new time => $time");
961     }
962
963     ### Clean it up.
964     my $delete = 0;
965     my $time = time();
966     foreach $chan (keys %floodjoin) {
967         foreach $who (keys %{ $floodjoin{$chan} }) {
968             my $t       = $floodjoin{$chan}{$who}{Time};
969             next unless (defined $t);
970
971             my $delta   = $time - $t;
972             next unless ($delta > 10);
973
974             delete $floodjoin{$chan}{$who};
975             $delete++;
976         }
977     }
978
979     &DEBUG("joinfloodCheck: $delete deleted.") if ($delete);
980 }
981
982 sub getHostMask {
983     my($n) = @_;
984
985     if (exists $nuh{$n}) {
986         return &makeHostMask($nuh{$n});
987     } else {
988         $cache{on_who_Hack} = 1;
989         $conn->who($n);
990     }
991 }
992
993 1;
994
995 # vim:ts=4:sw=4:expandtab:tw=80