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