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