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