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