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