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