]> git.donarmstrong.com Git - infobot.git/blob - src/IRC/Irc.pl
4ce64f66e247e4856c594614a1c03b9bdba41d51
[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 ( $postprocess ) {
217         undef $postprocess;
218     } elsif ($postprocess = &getChanConf('postprocess', $talkchannel)) {
219         &DEBUG("say: $postprocess $msg");
220         &parseCmdHook($postprocess . ' ' . $msg);
221         undef $postprocess;
222         return;
223     }
224
225     &status("<$mynick/$talkchannel> $msg");
226
227     return unless (&whatInterface() =~ /IRC/);
228
229     $msg = "zero" if ($msg =~ /^0+$/);
230
231     my $t = time();
232
233     if ($t == $pubtime) {
234         $pubcount++;
235         $pubsize += length $msg;
236
237         my $i = &getChanConfDefault("sendPublicLimitLines", 3, $chan);
238         my $j = &getChanConfDefault("sendPublicLimitBytes", 1000, $chan);
239
240         if ( ($pubcount % $i) == 0 and $pubcount) {
241             sleep 1;
242         } elsif ($pubsize > $j) {
243             sleep 1;
244             $pubsize -= $j;
245         }
246
247     } else {
248         $pubcount       = 0;
249         $pubtime        = $t;
250         $pubsize        = length $msg;
251     }
252
253     $conn->privmsg($talkchannel, $msg);
254 }
255
256 sub msg {
257     my ($nick, $msg) = @_;
258     if (!defined $nick) {
259         &ERROR("msg: nick == NULL.");
260         return;
261     }
262
263     if (!defined $msg) {
264         $msg ||= "NULL";
265         &WARN("msg: msg == $msg.");
266         return;
267     }
268
269     &status(">$nick< $msg");
270
271     return unless (&whatInterface() =~ /IRC/);
272     my $t = time();
273
274     if ($t == $msgtime) {
275         $msgcount++;
276         $msgsize += length $msg;
277
278         my $i = &getChanConfDefault("sendPrivateLimitLines", 3, $chan);
279         my $j = &getChanConfDefault("sendPrivateLimitBytes", 1000, $chan);
280         if ( ($msgcount % $i) == 0 and $msgcount) {
281             sleep 1;
282         } elsif ($msgsize > $j) {
283             sleep 1;
284             $msgsize -= $j;
285         }
286
287     } else {
288         $msgcount       = 0;
289         $msgtime        = $t;
290         $msgsize        = length $msg;
291     }
292
293     $conn->privmsg($nick, $msg);
294 }
295
296 # Usage: &action(nick || chan, txt);
297 sub action {
298     my $mynick = $conn->nick();
299     my ($target, $txt) = @_;
300     if (!defined $txt) {
301         &WARN("action: txt == NULL.");
302         return;
303     }
304
305     if (length $txt > 480) {
306         &status("action: txt too long; truncating.");
307         chop($txt) while (length $txt > 480);
308     }
309
310     &status("* $mynick/$target $txt");
311     $conn->me($target, $txt);
312 }
313
314 # Usage: &notice(nick || chan, txt);
315 sub notice {
316     my ($target, $txt) = @_;
317     if (!defined $txt) {
318         &WARN("notice: txt == NULL.");
319         return;
320     }
321
322     &status("-$target- $txt");
323
324     my $t       = time();
325
326     if ($t == $nottime) {
327         $notcount++;
328         $notsize += length $txt;
329
330         my $i = &getChanConfDefault("sendNoticeLimitLines", 3, $chan);
331         my $j = &getChanConfDefault("sendNoticeLimitBytes", 1000, $chan);
332
333         if ( ($notcount % $i) == 0 and $notcount) {
334             sleep 1;
335         } elsif ($notsize > $j) {
336             sleep 1;
337             $notsize -= $j;
338         }
339
340     } else {
341         $notcount       = 0;
342         $nottime        = $t;
343         $notsize        = length $txt;
344     }
345
346     $conn->notice($target, $txt);
347 }
348
349 sub DCCBroadcast {
350     my ($txt,$flag) = @_;
351
352     ### FIXME: flag not supported yet.
353
354     foreach (keys %{ $dcc{'CHAT'} }) {
355         $conn->privmsg($dcc{'CHAT'}{$_}, $txt);
356     }
357 }
358
359 ##########
360 ### perform commands.
361 ###
362
363 # Usage: &performReply($reply);
364 sub performReply {
365     my ($reply) = @_;
366
367     if (!defined $reply or $reply =~ /^\s*$/) {
368         &DEBUG("performReply: reply == NULL.");
369         return;
370     }
371
372     $reply =~ /([\.\?\s]+)$/;
373
374     # FIXME need real throttling....
375     if (length($reply) > $maxlinelen - 30) {
376         $reply = substr($reply, 0, $maxlinelen - 33);
377         $reply =~ s/ [^ ]*?$/ .../;
378     }
379     &checkMsgType($reply);
380
381     if ($msgType eq 'public') {
382         if (rand() < 0.5 or $reply =~ /[\.\?]$/) {
383             $reply = "$orig{who}: ".$reply;
384         } else {
385             $reply = "$reply, ".$orig{who};
386         }
387         &say($reply);
388
389     } elsif ($msgType eq 'private') {
390         if (rand() > 0.5) {
391             $reply = "$reply, ".$orig{who};
392         }
393         &msg($who, $reply);
394
395     } elsif ($msgType eq 'chat') {
396         if (!exists $dcc{'CHAT'}{$who}) {
397             &VERB("pSR: dcc{'CHAT'}{$who} does not exist.",2);
398             return;
399         }
400         $conn->privmsg($dcc{'CHAT'}{$who}, $reply);
401
402     } else {
403         &ERROR("PR: msgType invalid? ($msgType).");
404     }
405 }
406
407 # ...
408 sub performAddressedReply {
409     return unless ($addressed);
410     &performReply(@_);
411 }
412
413 # Usage: &performStrictReply($reply);
414 sub performStrictReply {
415     my ($reply) = @_;
416
417     # FIXME need real throttling....
418     if (length($reply) > $maxlinelen - 30) {
419         $reply = substr($reply, 0, $maxlinelen - 33);
420         $reply =~ s/ [^ ]*?$/ .../;
421     }
422     &checkMsgType($reply);
423
424     if ($msgType eq 'private') {
425         &msg($who, $reply);
426     } elsif ($msgType eq 'public') {
427         &say($reply);
428     } elsif ($msgType eq 'chat') {
429         &dccsay(lc $who, $reply);
430     } else {
431         &ERROR("pSR: msgType invalid? ($msgType).");
432     }
433 }
434
435 sub dccsay {
436     my($who, $reply) = @_;
437
438     if (!defined $reply or $reply =~ /^\s*$/) {
439         &WARN("dccsay: reply == NULL.");
440         return;
441     }
442
443     if (!exists $dcc{'CHAT'}{$who}) {
444         &VERB("pSR: dcc{'CHAT'}{$who} does not exist. (2)",2);
445         return;
446     }
447
448     &status("=>$who<= $reply");         # dcc chat.
449     $conn->privmsg($dcc{'CHAT'}{$who}, $reply);
450 }
451
452 sub dcc_close {
453     my($who) = @_;
454     my $type;
455
456     foreach $type (keys %dcc) {
457         &FIXME("dcc_close: $who");
458         my @who = grep /^\Q$who\E$/i, keys %{ $dcc{$type} };
459         next unless (scalar @who);
460         $who = $who[0];
461         &DEBUG("dcc_close... close $who!");
462     }
463 }
464
465 sub joinchan {
466     my ($chan, $key) = @_;
467     $key ||= &getChanConf("chankey", $chan);
468     $key ||= "";
469
470     # forgot for about 2 years to implement channel keys when moving
471     # over to Net::IRC...
472
473     # hopefully validChan is right.
474     if (&validChan($chan)) {
475         &status("join: already on $chan?");
476     }
477     #} else {
478         &status("joining $b_blue$chan $key$ob");
479
480         return if ($conn->join($chan, $key));
481         return if (&validChan($chan));
482
483         &DEBUG("joinchan: join failed. trying connect!");
484         &clearIRCVars();
485         $conn->connect();
486     #}
487 }
488
489 sub part {
490     my $chan;
491
492     foreach $chan (@_) {
493         next if ($chan eq "");
494         $chan =~ tr/A-Z/a-z/;   # lowercase.
495
496         if ($chan !~ /^$mask{chan}$/) {
497             &WARN("part: chan is invalid ($chan)");
498             next;
499         }
500
501         &status("parting $chan");
502         if (!&validChan($chan)) {
503             &WARN("part: not on $chan; doing anyway");
504 #           next;
505         }
506
507         $conn->part($chan);
508         # deletion of $channels{chan} is done in &entryEvt().
509     }
510 }
511
512 sub mode {
513     my ($chan, @modes) = @_;
514     my $modes = join(" ", @modes);
515
516     if (&validChan($chan) == 0) {
517         &ERROR("mode: invalid chan => '$chan'.");
518         return;
519     }
520
521     &DEBUG("mode: MODE $chan $modes");
522
523     # should move to use Net::IRC's $conn->mode()... but too lazy.
524     rawout("MODE $chan $modes");
525 }
526
527 sub op {
528     my ($chan, @who) = @_;
529     my $os      = "o" x scalar(@who);
530
531     &mode($chan, "+$os @who");
532 }
533
534 sub deop {
535     my ($chan, @who) = @_;
536     my $os = "o" x scalar(@who);
537
538     &mode($chan, "-$os ".@who);
539 }
540
541 sub kick {
542     my ($nick,$chan,$msg) = @_;
543     my (@chans) = ($chan eq "") ? (keys %channels) : lc($chan);
544     my $mynick = $conn->nick();
545
546     if ($chan ne "" and &validChan($chan) == 0) {
547         &ERROR("kick: invalid channel $chan.");
548         return;
549     }
550
551     $nick =~ tr/A-Z/a-z/;
552
553     foreach $chan (@chans) {
554         if (!&IsNickInChan($nick,$chan)) {
555             &status("kick: $nick is not on $chan.") if (scalar @chans == 1);
556             next;
557         }
558
559         if (!exists $channels{$chan}{o}{$mynick}) {
560             &status("kick: do not have ops on $chan :(");
561             next;
562         }
563
564         &status("Kicking $nick from $chan.");
565         $conn->kick($chan, $nick, $msg);
566     }
567 }
568
569 sub ban {
570     my ($mask,$chan) = @_;
571     my (@chans) = ($chan =~ /^\*?$/) ? (keys %channels) : lc($chan);
572     my $mynick = $conn->nick();
573     my $ban     = 0;
574
575     if ($chan !~ /^\*?$/ and &validChan($chan) == 0) {
576         &ERROR("ban: invalid channel $chan.");
577         return;
578     }
579
580     foreach $chan (@chans) {
581         if (!exists $channels{$chan}{o}{$mynick}) {
582             &status("ban: do not have ops on $chan :(");
583             next;
584         }
585
586         &status("Banning $mask from $chan.");
587         &rawout("MODE $chan +b $mask");
588         $ban++;
589     }
590
591     return $ban;
592 }
593
594 sub unban {
595     my ($mask,$chan) = @_;
596     my (@chans) = ($chan =~ /^\*?$/) ? (keys %channels) : lc($chan);
597     my $mynick = $conn->nick();
598     my $ban     = 0;
599
600     &DEBUG("unban: mask = $mask, chan = @chans");
601
602     foreach $chan (@chans) {
603         if (!exists $channels{$chan}{o}{$mynick}) {
604             &status("unBan: do not have ops on $chan :(");
605             next;
606         }
607
608         &status("Removed ban $mask from $chan.");
609         &rawout("MODE $chan -b $mask");
610         $ban++;
611     }
612
613     return $ban;
614 }
615
616 sub quit {
617     my ($quitmsg) = @_;
618     if (defined $conn) {
619         &status("QUIT " . $conn->nick() . " has quit IRC ($quitmsg)");
620         $conn->quit($quitmsg);
621     } else {
622         &WARN("quit: could not quit!");
623     }
624 }
625
626 sub nick {
627     my ($newnick) = @_;
628     my $mynick = $conn->nick();
629
630     if (!defined $newnick) {
631         &ERROR("nick: nick == NULL.");
632         return;
633     }
634
635     if (!defined $mynick) {
636         &WARN("nick: mynick == NULL.");
637         return;
638     }
639
640     my $bad = 0;
641     $bad++ if (exists $nuh{$newnick});
642     $bad++ if (&IsNickInAnyChan($newnick));
643
644     if ($bad) {
645         &WARN("Nick: not going to try to change from $mynick to $newnick. [". scalar(gmtime). "]");
646         # hrm... over time we lose track of our own nick.
647         #return;
648     }
649
650     if ($newnick =~ /^$mask{nick}$/) {
651         &status("nick: Changing nick from $mynick to $newnick");
652         # ->nick() will NOT change cause we are using rawout?
653         &rawout("NICK $newnick");
654         return 1;
655     }
656     &DEBUG("nick: failed... why oh why (mynick=$mynick, newnick=$newnick)");
657     return 0;
658 }
659
660 sub invite {
661     my($who, $chan) = @_;
662     # TODO: check if $who or $chan are invalid.
663
664     $conn->invite($who, $chan);
665 }
666
667 ##########
668 # Channel related functions...
669 #
670
671 # Usage: &joinNextChan();
672 sub joinNextChan {
673     my $joined = 0;
674     foreach (sort keys %conns) {
675         $conn = $conns{$_};
676         my $mynick = $conn->nick();
677         my @join = getJoinChans(1);
678
679         if (scalar @join) {
680             my $chan = shift @join;
681             &joinchan($chan);
682
683             if (my $i = scalar @join) {
684                 &status("joinNextChan: $mynick $i chans to join.");
685             }
686             $joined = 1;
687         }
688     }
689     return if $joined;
690
691     if (exists $cache{joinTime}) {
692         my $delta       = time() - $cache{joinTime} - 5;
693         my $timestr     = &Time2String($delta);
694         # FIXME: @join should be @in instead (hacked to 10)
695         #my $rate       = sprintf("%.1f", $delta / @in);
696         my $rate        = sprintf("%.1f", $delta / 10);
697         delete $cache{joinTime};
698
699         &status("time taken to join all chans: $timestr; rate: $rate sec/join");
700     }
701
702     # chanserv check: global channels, in case we missed one.
703     foreach ( &ChanConfList("chanServ_ops") ) {
704         &chanServCheck($_);
705     }
706 }
707
708 # Usage: &getNickInChans($nick);
709 sub getNickInChans {
710     my ($nick) = @_;
711     my @array;
712
713     foreach (keys %channels) {
714         next unless (grep /^\Q$nick\E$/i, keys %{ $channels{$_}{''} });
715         push(@array, $_);
716     }
717
718     return @array;
719 }
720
721 # Usage: &getNicksInChan($chan);
722 sub getNicksInChan {
723     my ($chan) = @_;
724     my @array;
725
726     return keys %{ $channels{$chan}{''} };
727 }
728
729 sub IsNickInChan {
730     my ($nick,$chan) = @_;
731
732     $chan =~ tr/A-Z/a-z/;       # not lowercase unfortunately.
733
734     if ($chan =~ /^$/) {
735         &DEBUG("INIC: chan == NULL.");
736         return 0;
737     }
738
739     if (&validChan($chan) == 0) {
740         &ERROR("INIC: invalid channel $chan.");
741         return 0;
742     }
743
744     if (grep /^\Q$nick\E$/i, keys %{ $channels{$chan}{''} }) {
745         return 1;
746     } else {
747         foreach (keys %channels) {
748             next unless (/[A-Z]/);
749             &DEBUG("iNIC: hash channels contains mixed cased chan!!!");
750         }
751         return 0;
752     }
753 }
754
755 sub IsNickInAnyChan {
756     my ($nick) = @_;
757     my $chan;
758
759     foreach $chan (keys %channels) {
760         next unless (grep /^\Q$nick\E$/i, keys %{ $channels{$chan}{''}  });
761         return 1;
762     }
763     return 0;
764 }
765
766 # Usage: &validChan($chan);
767 sub validChan {
768     # TODO: use $c instead?
769     my ($chan) = @_;
770
771     if (!defined $chan or $chan =~ /^\s*$/) {
772         return 0;
773     }
774
775     if (lc $chan ne $chan) {
776         &WARN("validChan: lc chan != chan. ($chan); fixing.");
777         $chan =~ tr/A-Z/a-z/;
778     }
779
780     # it's possible that this check creates the hash if empty.
781     if (defined $channels{$chan} or exists $channels{$chan}) {
782         if ($chan =~ /^_?default$/) {
783 #           &WARN("validC: chan cannot be _default! returning 0!");
784             return 0;
785         }
786
787         return 1;
788     } else {
789         return 0;
790     }
791 }
792
793 ###
794 # Usage: &delUserInfo($nick,@chans);
795 sub delUserInfo {
796     my ($nick,@chans) = @_;
797     my ($mode,$chan);
798
799     foreach $chan (@chans) {
800         foreach $mode (keys %{ $channels{$chan} }) {
801             # use grep here?
802             next unless (exists $channels{$chan}{$mode}{$nick});
803
804             delete $channels{$chan}{$mode}{$nick};
805         }
806     }
807 }
808
809 sub clearChanVars {
810     my ($chan) = @_;
811
812     delete $channels{$chan};
813 }
814
815 sub clearIRCVars {
816     undef %channels;
817     undef %floodjoin;
818
819     $cache{joinTime}    = time();
820 }
821
822 sub getJoinChans {
823     my($show)   = @_;
824
825     my @in;
826     my @skip;
827     my @join;
828
829     # can't join any if not connected
830     return @join if (!$conn);
831
832     my $nick = $conn->nick();
833
834     foreach (keys %chanconf) {
835         next if ($_ eq "_default");
836
837         my $skip = 0;
838         my $val = $chanconf{$_}{autojoin};
839
840         if (defined $val) {
841             $skip++ if ($val eq "0");
842             if ($val eq "1") {
843                 # convert old +autojoin to autojoin <nick>
844                 $val = lc $nick;
845                 $chanconf{$_}{autojoin} = $val;
846             }
847             $skip++ if (lc $val ne lc $nick);
848         } else {
849             $skip++;
850         }
851
852         if ($skip) {
853             push(@skip, $_);
854         } else {
855             if (defined $channels{$_} or exists $channels{$_}) {
856                 push(@in, $_);
857             } else {
858                 push(@join, $_);
859             }
860         }
861     }
862
863     my $str;
864     #$str .= ' in:' . join(',', sort @in) if scalar @in;
865     #$str .= ' skip:' . join(',', sort @skip) if scalar @skip;
866     $str .= ' join:' . join(',', sort @join) if scalar @join;
867
868     &status("Chans: ($nick)$str") if ($show);
869
870     return sort @join;
871 }
872
873 sub closeDCC {
874 #    &DEBUG("closeDCC called.");
875     my $type;
876
877     foreach $type (keys %dcc) {
878         next if ($type ne uc($type));
879
880         my $nick;
881         foreach $nick (keys %{ $dcc{$type} }) {
882             next unless (defined $nick);
883             &status("DCC CHAT: closing DCC $type to $nick.");
884             next unless (defined $dcc{$type}{$nick});
885
886             my $ref = $dcc{$type}{$nick};
887             &dccsay($nick, "bye bye, $nick") if ($type =~ /^chat$/i);
888             $dcc{$type}{$nick}->close();
889             delete $dcc{$type}{$nick};
890             &DEBUG("after close for $nick");
891         }
892         delete $dcc{$type};
893     }
894 }
895
896 sub joinfloodCheck {
897     my($who,$chan,$userhost) = @_;
898
899     return unless (&IsChanConf("joinfloodCheck") > 0);
900
901     if (exists $netsplit{lc $who}) {    # netsplit join.
902         &DEBUG("joinfloodCheck: $who was in netsplit; not checking.");
903     }
904
905     if (exists $floodjoin{$chan}{$who}{Time}) {
906         &WARN("floodjoin{$chan}{$who} already exists?");
907     }
908
909     $floodjoin{$chan}{$who}{Time} = time();
910     $floodjoin{$chan}{$who}{Host} = $userhost;
911
912     ### Check...
913     foreach (keys %floodjoin) {
914         my $c = $_;
915         my $count = scalar keys %{ $floodjoin{$c} };
916         next unless ($count > 5);
917         &DEBUG("joinflood: count => $count");
918
919         my $time;
920         foreach (keys %{ $floodjoin{$c} }) {
921             my $t = $floodjoin{$c}{$_}{Time};
922             next unless (defined $t);
923
924             $time += $t;
925         }
926         &DEBUG("joinflood: time => $time");
927         $time /= $count;
928
929         &DEBUG("joinflood: new time => $time");
930     }
931
932     ### Clean it up.
933     my $delete = 0;
934     my $time = time();
935     foreach $chan (keys %floodjoin) {
936         foreach $who (keys %{ $floodjoin{$chan} }) {
937             my $t       = $floodjoin{$chan}{$who}{Time};
938             next unless (defined $t);
939
940             my $delta   = $time - $t;
941             next unless ($delta > 10);
942
943             delete $floodjoin{$chan}{$who};
944             $delete++;
945         }
946     }
947
948     &DEBUG("joinfloodCheck: $delete deleted.") if ($delete);
949 }
950
951 sub getHostMask {
952     my($n) = @_;
953
954     if (exists $nuh{$n}) {
955         return &makeHostMask($nuh{$n});
956     } else {
957         $cache{on_who_Hack} = 1;
958         $conn->who($n);
959     }
960 }
961
962 1;