]> git.donarmstrong.com Git - infobot.git/blob - src/IRC/IrcHooks.pl
-autojoin on full or inviteonly
[infobot.git] / src / IRC / IrcHooks.pl
1 #
2 # IrcHooks.pl: IRC Hooks stuff.
3 #      Author: dms
4 #     Version: 20000126
5 #        NOTE: Based on code by Kevin Lenzo & Patrick Cole  (c) 1997
6 #
7 use vars qw(%chanconf);
8
9 # GENERIC. TO COPY.
10 sub on_generic {
11     $conn = shift(@_);
12     my ($event) = @_;
13     my $nick    = $event->nick();
14     my $chan    = ( $event->to )[0];
15
16     &DEBUG("on_generic: nick => '$nick'.");
17     &DEBUG("on_generic: chan => '$chan'.");
18
19     foreach ( $event->args ) {
20         &DEBUG("on_generic: args => '$_'.");
21     }
22 }
23
24 sub on_action {
25     $conn = shift(@_);
26     my ($event) = @_;
27     my ( $nick, $args ) = ( $event->nick, $event->args );
28     my $chan = ( $event->to )[0];
29
30     if ( $chan eq $ident ) {
31         &status("* [$nick] $args");
32     }
33     else {
34         &status("* $nick/$chan $args");
35     }
36 }
37
38 sub on_chat {
39     $conn = shift(@_);
40     my ($event) = @_;
41     my $msg     = ( $event->args )[0];
42     my $sock    = ( $event->to )[0];
43     my $nick    = lc $event->nick();
44
45     if ( !exists $nuh{$nick} ) {
46         &DEBUG("chat: nuh{$nick} doesn't exist; trying WHOIS .");
47         $conn->whois($nick);
48         return;
49     }
50
51     ### set vars that would have been set in hookMsg.
52     $userHandle    = '';                        # reset.
53     $who           = lc $nick;
54     $message       = $msg;
55     $orig{who}     = $nick;
56     $orig{message} = $msg;
57     $nuh           = $nuh{$who};
58     $uh            = ( split /\!/, $nuh )[1];
59     $h             = ( split /\@/, $uh )[1];
60     $addressed     = 1;
61     $msgType       = 'chat';
62
63     if ( !exists $dcc{'CHATvrfy'}{$nick} ) {
64         $userHandle = &verifyUser( $who, $nuh );
65         my $crypto  = $users{$userHandle}{PASS};
66         my $success = 0;
67
68         if ( $userHandle eq '_default' ) {
69             &WARN('DCC CHAT: _default/guest not allowed.');
70             return;
71         }
72
73         ### TODO: prevent users without CRYPT chatting.
74         if ( !defined $crypto ) {
75             &TODO('dcc close chat');
76             &msg( $who, 'nope, no guest logins allowed...' );
77             return;
78         }
79
80         if ( &ckpasswd( $msg, $crypto ) ) {
81
82             # stolen from eggdrop.
83             $conn->privmsg( $sock, "Connected to $ident" );
84             $conn->privmsg( $sock,
85                 'Commands start with "." (like ".quit" or ".help")' );
86             $conn->privmsg( $sock,
87                 'Everything else goes out to the party line.' );
88
89             &dccStatus(2) unless ( exists $sched{'dccStatus'}{RUNNING} );
90
91             $success++;
92
93         }
94         else {
95             &status('DCC CHAT: incorrect pass; closing connection.');
96             &DEBUG("chat: sock => '$sock'.");
97 ###         $sock->close();
98             delete $dcc{'CHAT'}{$nick};
99             &FIXME('chat: after closing sock.');
100             ### BUG: close seizes bot. why?
101         }
102
103         if ($success) {
104             &status("DCC CHAT: user $nick is here!");
105             &DCCBroadcast("*** $nick ($uh) joined the party line.");
106
107             $dcc{'CHATvrfy'}{$nick} = $userHandle;
108
109             return if ( $userHandle eq '_default' );
110
111             &dccsay( $nick, "Flags: $users{$userHandle}{FLAGS}" );
112         }
113
114         return;
115     }
116
117     &status("$b_red=$b_cyan$who$b_red=$ob $message");
118
119     if ( $message =~ s/^\.// ) {    # dcc chat commands.
120         ### TODO: make use of &Forker(); here?
121         &loadMyModule('UserDCC');
122
123         &DCCBroadcast( "#$who# $message", 'm' );
124
125         my $retval = &userDCC();
126         return unless ( defined $retval );
127         return if ( $retval eq $noreply );
128
129         $conn->privmsg( $dcc{'CHAT'}{$who}, 'Invalid command.' );
130
131     }
132     else {    # dcc chat arena.
133
134         foreach ( keys %{ $dcc{'CHAT'} } ) {
135             $conn->privmsg( $dcc{'CHAT'}{$_}, "<$who> $orig{message}" );
136         }
137     }
138
139     return 'DCC CHAT MESSAGE';
140 }
141
142 # is there isoff? how do we know if someone signs off?
143 sub on_ison {
144     $conn = shift(@_);
145     my ($event) = @_;
146     my $x1      = ( $event->args )[0];
147     my $x2      = ( $event->args )[1];
148     $x2 =~ s/\s$//;
149
150     &DEBUG("on_ison: x1 = '$x1', x2 => '$x2'");
151 }
152
153 sub on_connected {
154     $conn = shift(@_);
155
156     # update IRCStats.
157     $ident = $conn->nick();
158     $ircstats{'ConnectTime'} = time();
159     $ircstats{'ConnectCount'}++;
160     if ( defined $ircstats{'DisconnectTime'} ) {
161         $ircstats{'OffTime'} += time() - $ircstats{'DisconnectTime'};
162     }
163
164     # first time run.
165     if ( !exists $users{_default} ) {
166         &status('!!! First time run... adding _default user.');
167         $users{_default}{FLAGS} = 'amrt';
168         $users{_default}{HOSTS}{'*!*@*'} = 1;
169     }
170
171     if ( scalar keys %users < 2 ) {
172         &status( '!' x 40 );
173         &status("!!! Ok.  Now type '/msg $ident PASS <pass>' to get master access through DCC CHAT.");
174         &status( '!' x 40 );
175     }
176     # end of first time run.
177
178     if ( &IsChanConf('Wingate') > 0 ) {
179         my $file = "$bot_base_dir/$param{'ircUser'}.wingate";
180         open( IN, $file );
181         while (<IN>) {
182             chop;
183             next unless (/^(\S+)\*$/);
184             push( @wingateBad, $_ );
185         }
186         close IN;
187     }
188
189     if ($firsttime) {
190         &ScheduleThis( 1, 'setupSchedulers' );
191         $firsttime = 0;
192     }
193
194     if ( &IsParam('ircUMode') ) {
195         &VERB( "Attempting change of user modes to $param{'ircUMode'}.", 2 );
196         if ( $param{'ircUMode'} !~ /^[-+]/ ) {
197             &WARN('ircUMode had no +- prefix; adding +');
198             $param{'ircUMode'} = '+' . $param{'ircUMode'};
199         }
200
201         &rawout("MODE $ident $param{'ircUMode'}");
202     }
203
204     # ok, we're free to do whatever we want now. go for it!
205     $running = 1;
206
207     # add ourself to notify.
208     $conn->ison( $conn->nick() );
209
210     # Q, as on quakenet.org.
211     if ( &IsParam('Q_pass') ) {
212         &status('Authing to Q...');
213         &rawout("PRIVMSG Q\@CServe.quakenet.org :AUTH $param{'Q_user'} $param{'Q_pass'}");
214     }
215
216     &status("$ident End of motd. Now lets join some channels...");
217
218     #&joinNextChan();
219 }
220
221 sub on_endofwho {
222     $conn = shift(@_);
223     my ($event) = @_;
224
225     #    &DEBUG("endofwho: chan => $chan");
226     $chan ||= ( $event->args )[1];
227
228     #    &DEBUG("endofwho: chan => $chan");
229
230     if ( exists $cache{countryStats} ) {
231         &do_countrystats();
232     }
233 }
234
235 sub on_dcc {
236     $conn = shift(@_);
237     my ($event) = @_;
238     my $type = uc( ( $event->args )[1] );
239     my $nick = lc $event->nick();
240
241     &status("on_dcc type=$type nick=$nick sock=$sock");
242
243     # pity Net::IRC doesn't store nuh. Here's a hack :)
244     if ( !exists $nuh{ lc $nick } ) {
245         $conn->whois($nick);
246         $nuh{$nick} = 'GETTING-NOW';    # trying.
247     }
248     $type ||= '???';
249
250     if ( $type eq 'SEND' ) {            # GET for us.
251             # incoming DCC SEND. we're receiving a file.
252         my $get = ( $event->args )[2];
253         &status(
254             "DCC: not Initializing GET from $nick to '$param{tempDir}/$get'");
255
256         # FIXME: do we want to get anything?
257         return;
258
259         #open(DCCGET,">$param{tempDir}/$get");
260         #$conn->new_get($event, \*DCCGET);
261
262     }
263     elsif ( $type eq 'GET' ) {    # SEND for us?
264         &status("DCC: not Initializing SEND for $nick.");
265
266         # FIXME: do we want to do anything?
267         return;
268         $conn->new_send( $event->args );
269
270     }
271     elsif ( $type eq 'CHAT' ) {
272         &status("DCC: Initializing CHAT for $nick.");
273         $conn->new_chat($event);
274
275         #       $conn->new_chat(1, $nick, $event->host);
276
277     }
278     else {
279         &WARN("${b_green}DCC $type$ob (1)");
280     }
281 }
282
283 sub on_dcc_close {
284     $conn = shift(@_);
285     my ($event) = @_;
286     my $nick    = $event->nick();
287     my $sock    = ( $event->to )[0];
288
289     # DCC CHAT close on fork exit workaround.
290     if ( $bot_pid != $$ ) {
291         &WARN('run-away fork; exiting.');
292         &delForked($forker);
293     }
294
295     if ( exists $dcc{'SEND'}{$nick} and -f "$param{tempDir}/$nick.txt" ) {
296         &status("${b_green}DCC SEND$ob close from $b_cyan$nick$ob");
297
298         &status("dcc_close: purging DCC send $nick.txt");
299         unlink "$param{tempDir}/$nick.txt";
300
301         delete $dcc{'SEND'}{$nick};
302     }
303     elsif ( exists $dcc{'CHAT'}{$nick} and $dcc{'CHAT'}{$nick} eq $sock ) {
304         &status("${b_green}DCC CHAT$ob close from $b_cyan$nick$ob");
305         delete $dcc{'CHAT'}{$nick};
306         delete $dcc{'CHATvrfy'}{$nick};
307     }
308     else {
309         &status("${b_green}DCC$ob UNKNOWN close from $b_cyan$nick$ob (2)");
310     }
311 }
312
313 sub on_dcc_open {
314     $conn = shift(@_);
315     my ($event) = @_;
316     my $type = uc( ( $event->args )[0] );
317     my $nick = lc $event->nick();
318     my $sock = ( $event->to )[0];
319
320     &status("on_dcc_open type=$type nick=$nick sock=$sock");
321
322     $msgType = 'chat';
323     $type ||= '???';
324     ### BUG: who is set to bot's nick?
325
326     # lets do it.
327     if ( $type eq 'SEND' ) {
328         &status("${b_green}DCC lGET$ob established with $b_cyan$nick$ob");
329
330     }
331     elsif ( $type eq 'CHAT' ) {
332
333         # very cheap hack.
334         ### TODO: run ScheduleThis inside on_dcc_open_chat recursively
335         ###     1,3,5,10 seconds then fail.
336         if ( $nuh{$nick} eq 'GETTING-NOW' ) {
337             &ScheduleThis( 3 / 60, 'on_dcc_open_chat', $nick, $sock );
338         }
339         else {
340             on_dcc_open_chat( undef, $nick, $sock );
341         }
342
343     }
344     elsif ( $type eq 'SEND' ) {
345         &status('Starting DCC receive.');
346         foreach ( $event->args ) {
347             &status("  => '$_'.");
348         }
349
350     }
351     else {
352         &WARN("${b_green}DCC $type$ob (3)");
353     }
354 }
355
356 # really custom sub to get NUH since Net::IRC doesn't appear to support
357 # it.
358 sub on_dcc_open_chat {
359     my ( undef, $nick, $sock ) = @_;
360
361     if ( $nuh{$nick} eq 'GETTING-NOW' ) {
362         &FIXME("getting nuh for $nick failed.");
363         return;
364     }
365
366     &status(
367 "${b_green}DCC CHAT$ob established with $b_cyan$nick$ob $b_yellow($ob$nuh{$nick}$b_yellow)$ob"
368     );
369
370     &verifyUser( $nick, $nuh{ lc $nick } );
371
372     if ( !exists $users{$userHandle}{HOSTS} ) {
373         &performStrictReply(
374             'you have no hosts defined in my user file; rejecting.');
375         $sock->close();
376         return;
377     }
378
379     my $crypto = $users{$userHandle}{PASS};
380     $dcc{'CHAT'}{$nick} = $sock;
381
382     # TODO: don't make DCC CHAT established in the first place.
383     if ( $userHandle eq '_default' ) {
384         &dccsay( $nick, '_default/guest not allowed' );
385         $sock->close();
386         return;
387     }
388
389     if ( defined $crypto ) {
390         &status( "DCC CHAT: going to use $nick\'s crypt." );
391         &dccsay( $nick, 'Enter your password.' );
392     }
393     else {
394
395         #       &dccsay($nick,"Welcome to infobot DCC CHAT interface, $userHandle.");
396     }
397 }
398
399 sub on_disconnect {
400     $conn = shift(@_);
401     my ($event) = @_;
402     my $from    = $event->from();
403     my $what    = ( $event->args )[0];
404     my $mynick  = $conn->nick();
405
406     &status("$mynick disconnect from $from ($what).");
407     $ircstats{'DisconnectTime'}   = time();
408     $ircstats{'DisconnectReason'} = $what;
409     $ircstats{'DisconnectCount'}++;
410     $ircstats{'TotalTime'} += time() - $ircstats{'ConnectTime'}
411       if ( $ircstats{'ConnectTime'} );
412
413     # clear any variables on reconnection.
414     $nickserv = 0;
415
416     &clearIRCVars();
417
418     if ( !defined $conn ) {
419         &WARN('on_disconnect: self is undefined! WTF');
420         &DEBUG('running function irc... lets hope this works.');
421         &irc();
422         return;
423     }
424
425     &WARN('scheduling call ircCheck() in 60s');
426     &clearIRCVars();
427     &ScheduleThis( 1, 'ircCheck' );
428 }
429
430 sub on_endofnames {
431     $conn = shift(@_);
432     my ($event) = @_;
433     my $chan = ( $event->args )[1];
434
435     # sync time should be done in on_endofwho like in BitchX
436     if ( exists $cache{jointime}{$chan} ) {
437         my $delta_time =
438           sprintf( '%.03f', &timedelta( $cache{jointime}{$chan} ) );
439         $delta_time = 0 if ( $delta_time <= 0 );
440         if ( $delta_time > 100 ) {
441             &WARN("endofnames: delta_time > 100 ($delta_time)");
442         }
443
444         &status("$b_blue$chan$ob: sync in ${delta_time}s.");
445     }
446
447     $conn->mode($chan);
448
449     my $txt;
450     my @array;
451     foreach ( 'o', 'v', '' ) {
452         my $count = scalar( keys %{ $channels{$chan}{$_} } );
453         next unless ($count);
454
455         $txt = 'total' if ( $_ eq '' );
456         $txt = 'voice' if ( $_ eq 'v' );
457         $txt = 'ops'   if ( $_ eq 'o' );
458
459         push( @array, "$count $txt" );
460     }
461     my $chanstats = join( ' || ', @array );
462     &status("$b_blue$chan$ob: [$chanstats]");
463
464     &chanServCheck($chan);
465
466     # schedule used to solve ircu (OPN) 'target too fast' problems.
467     $conn->schedule( 5, sub { &joinNextChan(); } );
468 }
469
470 sub on_init {
471     $conn = shift(@_);
472     my ($event) = @_;
473     my (@args)  = ( $event->args );
474     shift @args;
475
476     &status("@args");
477 }
478
479 sub on_invite {
480     $conn = shift(@_);
481     my ($event) = @_;
482     my $chan = lc( ( $event->args )[0] );
483     my $nick = $event->nick;
484
485     if ( $nick =~ /^\Q$ident\E$/ ) {
486         &DEBUG('on_invite: self invite.');
487         return;
488     }
489
490     ### TODO: join key.
491     if ( exists $chanconf{$chan} ) {
492
493         # it's still buggy :/
494         if ( &validChan($chan) ) {
495             &msg( $who, "i'm already in \002$chan\002." );
496
497             #       return;
498         }
499
500         &status("invited to $b_blue$chan$ob by $b_cyan$nick$ob");
501         &joinchan($chan);
502     }
503 }
504
505 sub on_join {
506     $conn = shift(@_);
507     my ($event) = @_;
508     my ( $user, $host ) = split( /\@/, $event->userhost );
509     $chan    = lc( ( $event->to )[0] );    # CASING!!!!
510     $who     = $event->nick();
511     $msgType = 'public';
512     my $i = scalar( keys %{ $channels{$chan} } );
513     my $j = $cache{maxpeeps}{$chan} || 0;
514
515     if ( !&IsParam('noSHM')
516         && time() > ( $sched{shmFlush}{TIME} || time() ) + 3600 )
517     {
518         &DEBUG('looks like schedulers died somewhere... restarting...');
519         &setupSchedulers();
520     }
521
522     $chanstats{$chan}{'Join'}++;
523     $userstats{ lc $who }{'Join'} = time() if ( &IsChanConf('seenStats') > 0 );
524     $cache{maxpeeps}{$chan} = $i if ( $i > $j );
525
526     &joinfloodCheck( $who, $chan, $event->userhost );
527
528     # netjoin detection.
529     my $netsplit = 0;
530     if ( exists $netsplit{ lc $who } ) {
531         delete $netsplit{ lc $who };
532         $netsplit = 1;
533
534         if ( !scalar keys %netsplit ) {
535             &DEBUG('on_join: netsplit hash is now empty!');
536             undef %netsplitservers;
537             &netsplitCheck();    # any point in running this?
538             &chanlimitCheck();
539         }
540     }
541
542     if ( $netsplit and !exists $cache{netsplit} ) {
543         &VERB('on_join: ok.... re-running chanlimitCheck in 60.', 2);
544         $conn->schedule(
545             60,
546             sub {
547                 &chanlimitCheck();
548                 delete $cache{netsplit};
549             }
550         );
551
552         $cache{netsplit} = time();
553     }
554
555     # how to tell if there's a netjoin???
556
557     my $netsplitstr = '';
558     $netsplitstr = " $b_yellow\[${ob}NETSPLIT VICTIM$b_yellow]$ob"
559       if ($netsplit);
560     &status(
561 ">>> join/$b_blue$chan$ob $b_cyan$who$ob $b_yellow($ob$user\@$host$b_yellow)$ob$netsplitstr"
562     );
563
564     $channels{$chan}{''}{$who}++;
565     $nuh = $who . '!' . $user . '@' . $host;
566     $nuh{ lc $who } = $nuh unless ( exists $nuh{ lc $who } );
567
568     ### on-join bans.
569     my @bans;
570     push( @bans, keys %{ $bans{$chan} } ) if ( exists $bans{$chan} );
571     push( @bans, keys %{ $bans{'*'} } )   if ( exists $bans{'*'} );
572
573     foreach (@bans) {
574         my $ban = $_;
575         s/\?/./g;
576         s/\*/\\S*/g;
577         my $mask = $_;
578         next unless ( $nuh =~ /^$mask$/i );
579
580         ### TODO: check $channels{$chan}{'b'} if ban already exists.
581         foreach ( keys %{ $channels{$chan}{'b'} } ) {
582             &DEBUG(" bans_on_chan($chan) => $_");
583         }
584
585         my $reason = 'no reason';
586         foreach ( $chan, '*' ) {
587             next unless ( exists $bans{$_} );
588             next unless ( exists $bans{$_}{$ban} );
589
590             my @array = @{ $bans{$_}{$ban} };
591
592             $reason = $array[4] if ( $array[4] );
593             last;
594         }
595
596         &ban( $ban, $chan );
597         &kick( $who, $chan, $reason );
598
599         last;
600     }
601
602     # no need to go further.
603     return if ($netsplit);
604
605     # who == bot.
606     if ( $who =~ /^\Q$ident\E$/i ) {
607         if ( defined( my $whojoin = $cache{join}{$chan} ) ) {
608             &msg( $chan, "Okay, I'm here. (courtesy of $whojoin)" );
609             delete $cache{join}{$chan};
610             &joinNextChan();    # hack.
611         }
612
613         ### TODO: move this to &joinchan()?
614         $cache{jointime}{$chan} = &timeget();
615         $conn->who($chan);
616
617         return;
618     }
619
620     ### ROOTWARN:
621     &rootWarn( $who, $user, $host, $chan )
622       if ( &IsChanConf('RootWarn') > 0
623         && $user eq 'root' );
624         #&& $user =~ /^~?r(oo|ew|00)t$/i );
625
626     ### emit a message based on who just joined
627     &onjoin( $who, $user, $host, $chan ) if ( &IsChanConf('OnJoin') > 0 );
628
629     ### NEWS:
630     if ( &IsChanConf('News') > 0 && &IsChanConf('newsKeepRead') > 0 ) {
631         if ( !&loadMyModule('News') ) {    # just in case.
632             &DEBUG('could not load news.');
633         }
634         else {
635             &News::latest($chan);
636         }
637     }
638
639     ### botmail:
640     if ( &IsChanConf('botmail') > 0 ) {
641         &botmail::check( lc $who );
642     }
643
644     ### wingate:
645     &wingateCheck();
646 }
647
648 sub on_kick {
649     $conn = shift(@_);
650     my ($event) = @_;
651     my ( $chan, $reason ) = $event->args;
652     my $kicker = $event->nick;
653     my $kickee = ( $event->to )[0];
654     my $uh     = $event->userhost();
655
656     &status(
657 ">>> kick/$b_blue$chan$ob [$b$kickee!$uh$ob] by $b_cyan$kicker$ob $b_yellow($ob$reason$b_yellow)$ob"
658     );
659
660     $chan = lc $chan;    # forgot about this, found by xsdg, 20001229.
661     $chanstats{$chan}{'Kick'}++;
662
663     if ( $kickee eq $ident ) {
664         &clearChanVars($chan);
665
666         &status("SELF attempting to rejoin lost channel $chan");
667         &joinchan($chan);
668     }
669     else {
670         &delUserInfo( $kickee, $chan );
671     }
672 }
673
674 sub on_mode {
675     $conn = shift(@_);
676     my ($event) = @_;
677     my ( $user, $host ) = split( /\@/, $event->userhost );
678     my @args = $event->args();
679     my $nick = $event->nick();
680     $chan = ( $event->to )[0];
681
682     # last element is empty... so nuke it.
683     pop @args while ( $args[$#args] eq '' );
684
685     if ( $nick eq $chan ) {    # UMODE
686         &status(
687             ">>> mode $b_yellow\[$ob$b@args$b_yellow\]$ob by $b_cyan$nick$ob");
688     }
689     else {                     # MODE
690         &status(
691 ">>> mode/$b_blue$chan$ob $b_yellow\[$ob$b@args$b_yellow\]$ob by $b_cyan$nick$ob"
692         );
693         &hookMode( $nick, @args );
694     }
695 }
696
697 sub on_modeis {
698     $conn = shift(@_);
699     my ($event) = @_;
700     my ( $myself, undef, @args ) = $event->args();
701     my $nick = $event->nick();
702     $chan = ( $event->args() )[1];
703
704     &hookMode( $nick, @args );
705 }
706
707 sub on_msg {
708     $conn = shift(@_);
709     my ($event) = @_;
710     my $nick    = $event->nick;
711     my $msg     = ( $event->args )[0];
712
713     ( $user, $host ) = split( /\@/, $event->userhost );
714     $uh      = $event->userhost();
715     $nuh     = $nick . '!' . $uh;
716     $msgtime = time();
717     $h       = $host;
718
719     if ( $nick eq $ident ) {    # hopefully ourselves.
720         if ( $msg eq 'TEST' ) {
721             &status("IRCTEST: Yes, we're alive.");
722             delete $cache{connect};
723             return;
724         }
725     }
726
727     &hookMsg( 'private', undef, $nick, $msg );
728     $who     = '';
729     $chan    = '';
730     $msgType = '';
731 }
732
733 sub on_names {
734     $conn = shift(@_);
735     my ($event) = @_;
736     my @args    = $event->args;
737     my $chan    = lc $args[2];    # CASING, the last of them!
738
739     foreach ( split / /, @args[ 3 .. $#args ] ) {
740         $channels{$chan}{'o'}{$_}++ if s/\@//;
741         $channels{$chan}{'v'}{$_}++ if s/\+//;
742         $channels{$chan}{''}{$_}++;
743     }
744 }
745
746 sub on_nick {
747     $conn = shift(@_);
748     my ($event) = @_;
749     my $nick    = $event->nick();
750     my $newnick = ( $event->args )[0];
751
752     if ( exists $netsplit{ lc $newnick } ) {
753         &status(
754 "Netsplit: $newnick/$nick came back from netsplit and changed to original nick! removing from hash."
755         );
756         delete $netsplit{ lc $newnick };
757         &netsplitCheck() if ( time() != $sched{netsplitCheck}{TIME} );
758     }
759
760     my ( $chan, $mode );
761     foreach $chan ( keys %channels ) {
762         foreach $mode ( keys %{ $channels{$chan} } ) {
763             next unless ( exists $channels{$chan}{$mode}{$nick} );
764
765             $channels{$chan}{$mode}{$newnick} = $channels{$chan}{$mode}{$nick};
766         }
767     }
768
769     # TODO: do %flood* aswell.
770
771     &delUserInfo( $nick, keys %channels );
772     $nuh{ lc $newnick } = $nuh{ lc $nick };
773     delete $nuh{ lc $nick };
774
775     if ( $nick eq $conn->nick() ) {
776         &status(">>> I materialized into $b_green$newnick$ob from $nick");
777         $ident = $newnick;
778         $conn->nick($newnick);
779     }
780     else {
781         &status(">>> $b_cyan$nick$ob materializes into $b_green$newnick$ob");
782         my $mynick = $conn->nick();
783         if ( $nick =~ /^\Q$mynick\E$/i ) {
784             &getNickInUse();
785         }
786     }
787 }
788
789 sub on_nick_taken {
790     $conn = shift(@_);
791     my $nick = $conn->nick();
792
793     #my $newnick = $nick . int(rand 10);
794     my $newnick = $nick . '_';
795
796     &DEBUG("on_nick_taken: nick => $nick");
797
798     &status("nick taken ($nick); preparing nick change.");
799
800     $conn->whois($nick);
801
802     #$conn->schedule(5, sub {
803     &status("nick taken; changing to temporary nick ($nick -> $newnick).");
804     &nick($newnick);
805
806     #} );
807 }
808
809 sub on_notice {
810     $conn = shift(@_);
811     my ($event) = @_;
812     my $nick    = $event->nick();
813     my $chan    = ( $event->to )[0];
814     my $args    = ( $event->args )[0];
815     my $mynick  = $conn->nick();
816
817     if ( $nick =~ /^NickServ$/i ) {    # nickserv.
818         &status("NickServ: $mynick <== '$args'");
819
820         my $check = 0;
821         $check++ if ( $args =~ /^This nickname is registered/i );
822         $check++ if ( $args =~ /nickname.*owned/i );
823
824         if ($check) {
825             &status("nickserv told $mynick to register; doing it.");
826
827             if ( &IsParam('nickServ_pass') ) {
828                 &status("NickServ: ==> Identifying as $mynick.");
829                 &rawout("PRIVMSG NickServ :IDENTIFY $param{'nickServ_pass'}");
830                 return;
831             }
832             else {
833                 &status("$mynick can't tell nickserv a passwd ;(");
834             }
835         }
836
837         # password accepted.
838         if ( $args =~ /^Password a/i ) {
839             my $done = 0;
840
841             foreach ( &ChanConfList('chanServ_ops') ) {
842                 next unless &chanServCheck($_);
843                 next if ($done);
844                 &DEBUG('nickserv activated or restarted; doing chanserv check.');
845                 $done++;
846             }
847
848             $nickserv++;
849         }
850
851     }
852     elsif ( $nick =~ /^ChanServ$/i ) {    # chanserv.
853         &status("ChanServ: <== '$args'.");
854
855     }
856     else {
857         if ( $chan =~ /^$mask{chan}$/ ) {    # channel notice.
858             &status("-$nick/$chan- $args");
859         }
860         else {
861             $server = $nick unless ( defined $server );
862             &status("-$nick- $args");        # private or server notice.
863         }
864     }
865 }
866
867 sub on_other {
868     $conn = shift(@_);
869     my ($event) = @_;
870     my $chan    = ( $event->to )[0];
871     my $nick    = $event->nick;
872
873     &status('!!! other called.');
874     &status("!!! $event->args");
875 }
876
877 sub on_part {
878     $conn = shift(@_);
879     my ($event) = @_;
880     $chan = lc( ( $event->to )[0] );    # CASING!!!
881     my $mynick   = $conn->nick();
882     my $nick     = $event->nick;
883     my $userhost = $event->userhost;
884     $who     = $nick;
885     $msgType = 'public';
886
887     if ( !exists $channels{$chan} ) {
888         &DEBUG("on_part: found out $mynick is on $chan!");
889         $channels{$chan} = 1;
890     }
891
892     if ( exists $floodjoin{$chan}{$nick}{Time} ) {
893         delete $floodjoin{$chan}{$nick};
894     }
895
896     $chanstats{$chan}{'Part'}++;
897     &delUserInfo( $nick, $chan );
898     if ( $nick eq $ident ) {
899         &clearChanVars($chan);
900     }
901
902     if ( !&IsNickInAnyChan($nick) and &IsChanConf('seenStats') > 0 ) {
903         delete $userstats{ lc $nick };
904     }
905
906     &status(
907 ">>> part/$b_blue$chan$ob $b_cyan$nick$ob $b_yellow($ob$userhost$b_yellow)$ob"
908     );
909 }
910
911 sub on_ping {
912     $conn = shift(@_);
913     my ($event) = @_;
914     my $nick = $event->nick;
915
916     $conn->ctcp_reply( $nick, join( ' ', ( $event->args ) ) );
917     &status(
918         ">>> ${b_green}CTCP PING$ob request from $b_cyan$nick$ob received.");
919 }
920
921 sub on_ping_reply {
922     $conn = shift(@_);
923     my ($event) = @_;
924     my $nick    = $event->nick;
925     my $t       = ( $event->args )[1];
926     if ( !defined $t ) {
927         &WARN('on_ping_reply: t == undefined.');
928         return;
929     }
930
931     my $lag = time() - $t;
932
933     &status(">>> ${b_green}CTCP PING$ob reply from $b_cyan$nick$ob: $lag sec.");
934 }
935
936 sub on_public {
937     $conn = shift(@_);
938     my ($event) = @_;
939     my $msg = ( $event->args )[0];
940     $chan = lc( ( $event->to )[0] );    # CASING.
941     my $nick = $event->nick;
942     $who     = $nick;
943     $uh      = $event->userhost();
944     $nuh     = $nick . '!' . $uh;
945     $msgType = 'public';
946
947     # TODO: move this out of hookMsg to here?
948     ( $user, $host ) = split( /\@/, $uh );
949     $h = $host;
950
951     # rare case should this happen - catch it just in case.
952     if ( $bot_pid != $$ ) {
953         &ERROR('run-away fork; exiting.');
954         &delForked($forker);
955     }
956
957     $msgtime = time();
958     $lastWho{$chan} = $nick;
959     ### TODO: use $nick or lc $nick?
960     if ( &IsChanConf('seenStats') > 0 ) {
961         $userstats{ lc $nick }{'Count'}++;
962         $userstats{ lc $nick }{'Time'} = time();
963     }
964
965     # cache it.
966     my $time = time();
967     if ( !$cache{ircTextCounters} ) {
968         &DEBUG('caching ircTextCounters for first time.');
969         my @str = split( /\s+/, &getChanConf('ircTextCounters') );
970         for (@str) { $_ = quotemeta($_); }
971         $cache{ircTextCounters} = join( '|', @str );
972     }
973
974     my $str = $cache{ircTextCounters};
975     if ( $str && $msg =~ /^($str)[\s!\.]?$/i ) {
976         my $x = $1;
977
978         &VERB( "textcounters: $x matched for $who", 2 );
979         my $c = $chan || 'PRIVATE';
980
981         # better to do 'counter=counter+1'.
982         # but that will avoid time check.
983         my ( $v, $t ) = &sqlSelect(
984             'stats',
985             'counter,time',
986             {
987                 nick    => $who,
988                 type    => $x,
989                 channel => $c,
990             }
991         );
992         $v++;
993
994         # don't allow ppl to cheat the stats :-)
995         if ( ( defined $t && $time - $t > 60 ) or ( !defined $t ) ) {
996             &sqlSet(
997                 'stats',
998                 {
999                                 'nick' => $who,
1000                     'type'    => $x,
1001                     'channel' => $c,
1002                 },
1003                 {
1004                     time    => $time,
1005                     counter => $v,
1006                 }
1007             );
1008         }
1009     }
1010
1011     &hookMsg( 'public', $chan, $nick, $msg );
1012     $chanstats{$chan}{'PublicMsg'}++;
1013     $who     = '';
1014     $chan    = '';
1015     $msgType = '';
1016 }
1017
1018 sub on_quit {
1019     $conn = shift(@_);
1020     my ($event) = @_;
1021     my $nick    = $event->nick();
1022     my $reason  = ( $event->args )[0];
1023
1024     # hack for ICC.
1025     $msgType = 'public';
1026     $who     = $nick;
1027 ###    $chan    = $reason;      # no.
1028
1029     my $count = 0;
1030     foreach ( grep !/^_default$/, keys %channels ) {
1031
1032         # fixes inconsistent chanstats bug #1.
1033         if ( !&IsNickInChan( $nick, $_ ) ) {
1034             $count++;
1035             next;
1036         }
1037         $chanstats{$_}{'SignOff'}++;
1038     }
1039
1040     if ( $count == scalar keys %channels ) {
1041         &DEBUG("on_quit: nick $nick was not found in any chan.");
1042     }
1043
1044     # should fix chanstats inconsistencies bug #2.
1045     if ( $reason =~ /^($mask{host})\s($mask{host})$/ ) {    # netsplit.
1046         $reason = "NETSPLIT: $1 <=> $2";
1047
1048         # chanlimit code.
1049         foreach $chan ( &getNickInChans($nick) ) {
1050             next unless ( &IsChanConf('chanlimitcheck') > 0 );
1051             next unless ( exists $channels{$_}{'l'} );
1052
1053             &DEBUG("on_quit: netsplit detected on $_; disabling chan limit.");
1054             $conn->mode( $_, '-l' );
1055         }
1056
1057         $netsplit{ lc $nick } = time();
1058         if ( !exists $netsplitservers{$1}{$2} ) {
1059             &status("netsplit detected between $1 and $2 at ["
1060                   . scalar(gmtime)
1061                   . ']' );
1062             $netsplitservers{$1}{$2} = time();
1063         }
1064     }
1065
1066     my $chans = join( ' ', &getNickInChans($nick) );
1067     &status(
1068 ">>> $b_cyan$nick$ob has signed off IRC $b_red($ob$reason$b_red)$ob [$chans]"
1069     );
1070
1071     ###
1072     ### ok... lets clear out the cache
1073     ###
1074     &delUserInfo( $nick, keys %channels );
1075     if ( exists $nuh{ lc $nick } ) {
1076         delete $nuh{ lc $nick };
1077     }
1078     else {
1079
1080         # well.. it's good but weird that this has happened - lets just
1081         # be quiet about it.
1082     }
1083     delete $userstats{ lc $nick } if ( &IsChanConf('seenStats') > 0 );
1084     delete $chanstats{ lc $nick };
1085     ###
1086
1087     # if we have a temp nick, and whoever is camping on our main nick leaves
1088     # revert to main nick. Note that Net::IRC only knows our main nick
1089     if ( $nick eq $conn->nick() ) {
1090         &status("nickchange: own nick \"$nick\" became free; changing.");
1091         &nick($nick);
1092     }
1093 }
1094
1095 sub on_targettoofast {
1096     $conn = shift(@_);
1097     my ($event) = @_;
1098     my $nick = $event->nick();
1099     my ( $me, $chan, $why ) = $event->args();
1100
1101     ### TODO: incomplete.
1102     if ( $why =~ /.* wait (\d+) second/ ) {
1103         my $sleep = $1;
1104         my $max   = 10;
1105
1106         if ( $sleep > $max ) {
1107             &status("targettoofast: going to sleep for $max ($sleep)...");
1108             $sleep = $max;
1109         }
1110         else {
1111             &status("targettoofast: going to sleep for $sleep");
1112         }
1113
1114         my $delta = time() - ( $cache{sleepTime} || 0 );
1115         if ( $delta > $max + 2 ) {
1116             sleep $sleep;
1117             $cache{sleepTime} = time();
1118         }
1119
1120         return;
1121     }
1122
1123     if ( !exists $cache{TargetTooFast} ) {
1124         &DEBUG("on_ttf: failed: $why");
1125         $cache{TargetTooFast}++;
1126     }
1127 }
1128
1129 sub on_topic {
1130     $conn = shift(@_);
1131     my ($event) = @_;
1132
1133     if ( scalar( $event->args ) == 1 ) {    # change.
1134         my $topic = ( $event->args )[0];
1135         my $chan  = ( $event->to )[0];
1136         my $nick  = $event->nick();
1137
1138         ###
1139         # WARNING:
1140         #       race condition here. To fix, change '1' to '0'.
1141         #       This will keep track of topics set by bot only.
1142         ###
1143         # UPDATE:
1144         #       this may be fixed at a later date with topic queueing.
1145         ###
1146
1147         $topic{$chan}{'Current'} = $topic if (1);
1148         $chanstats{$chan}{'Topic'}++;
1149
1150         &status(">>> topic/$b_blue$chan$ob by $b_cyan$nick$ob -> $topic");
1151     }
1152     else {    # join.
1153         my ( $nick, $chan, $topic ) = $event->args;
1154         if ( &IsChanConf('Topic') > 0 ) {
1155             $topic{$chan}{'Current'} = $topic;
1156             &topicAddHistory( $chan, $topic );
1157         }
1158
1159         $topic = &fixString( $topic, 1 );
1160         &status(">>> topic/$b_blue$chan$ob is $topic");
1161     }
1162 }
1163
1164 sub on_topicinfo {
1165     $conn = shift(@_);
1166     my ($event) = @_;
1167     my ( $myself, $chan, $setby, $time ) = $event->args();
1168
1169     my $timestr;
1170     if ( time() - $time > 60 * 60 * 24 ) {
1171         $timestr = 'at ' . gmtime $time;
1172     }
1173     else {
1174         $timestr = &Time2String( time() - $time ) . ' ago';
1175     }
1176
1177     &status(">>> set by $b_cyan$setby$ob $timestr");
1178 }
1179
1180 sub on_crversion {
1181     $conn = shift(@_);
1182     my ($event) = @_;
1183     my $nick = $event->nick();
1184     my $ver;
1185
1186     if ( scalar $event->args() != 1 ) {    # old.
1187         $ver = join ' ', $event->args();
1188         $ver =~ s/^VERSION //;
1189     }
1190     else {                                 # new.
1191         $ver = ( $event->args() )[0];
1192     }
1193
1194     if ( grep /^\Q$nick\E$/i, @vernick ) {
1195         &WARN("nick $nick found in vernick ($ver); skipping.");
1196         return;
1197     }
1198     push( @vernick, $nick );
1199
1200     &DEBUG("on_crversion: Got '$ver' from $nick");
1201
1202     if ( $ver =~ /bitchx/i ) {
1203         $ver{bitchx}{$nick} = $ver;
1204
1205     }
1206     elsif ( $ver =~ /infobot/i ) {
1207         $ver{infobot}{$nick} = $ver;
1208
1209     }
1210     elsif ( $ver =~ /(xc\!|xchat)/i ) {
1211         $ver{xchat}{$nick} = $ver;
1212
1213     }
1214     elsif ( $ver =~ /irssi/i ) {
1215         $ver{irssi}{$nick} = $ver;
1216
1217     }
1218     elsif ( $ver =~ /(epic|Third Eye)/i ) {
1219         $ver{epic}{$nick} = $ver;
1220
1221     }
1222     elsif ( $ver =~ /(ircII|PhoEniX)/i ) {
1223         $ver{ircII}{$nick} = $ver;
1224
1225     }
1226     elsif ( $ver =~ /mirc/i ) {
1227         # Apparently, mIRC gets the reply as "VERSION " and doesnt like the
1228         # space, so mirc matching is considered bugged.
1229         $ver{mirc}{$nick} = $ver;
1230
1231     }
1232     elsif ( $ver =~ /ircle/i ) {
1233         $ver{ircle}{$nick} = $ver;
1234
1235     }
1236     elsif ( $ver =~ /chatzilla/i ) {
1237         $ver{chatzilla}{$nick} = $ver;
1238
1239     }
1240     elsif ( $ver =~ /pirch/i ) {
1241         $ver{pirch}{$nick} = $ver;
1242
1243     }
1244     elsif ( $ver =~ /sirc /i ) {
1245         $ver{sirc}{$nick} = $ver;
1246
1247     }
1248     elsif ( $ver =~ /kvirc/i ) {
1249         $ver{kvirc}{$nick} = $ver;
1250
1251     }
1252     elsif ( $ver =~ /eggdrop/i ) {
1253         $ver{eggdrop}{$nick} = $ver;
1254
1255     }
1256     elsif ( $ver =~ /xircon/i ) {
1257         $ver{xircon}{$nick} = $ver;
1258
1259     }
1260     else {
1261         &DEBUG("verstats: other: $nick => '$ver'.");
1262         $ver{other}{$nick} = $ver;
1263     }
1264 }
1265
1266 sub on_version {
1267     $conn = shift(@_);
1268     my ($event) = @_;
1269     my $nick = $event->nick;
1270
1271     &status(">>> ${b_green}CTCP VERSION$ob request from $b_cyan$nick$ob");
1272     $conn->ctcp_reply( $nick, "VERSION $bot_version" );
1273 }
1274
1275 sub on_who {
1276     $conn = shift(@_);
1277     my ($event) = @_;
1278     my @args    = $event->args;
1279     my $str     = $args[5] . '!' . $args[2] . '@' . $args[3];
1280
1281     if ( $cache{on_who_Hack} ) {
1282         $cache{nuhInfo}{ lc $args[5] }{Nick} = $args[5];
1283         $cache{nuhInfo}{ lc $args[5] }{User} = $args[2];
1284         $cache{nuhInfo}{ lc $args[5] }{Host} = $args[3];
1285         $cache{nuhInfo}{ lc $args[5] }{NUH}  = "$args[5]!$args[2]\@$args[3]";
1286         return;
1287     }
1288
1289     if ( $args[5] =~ /^nickserv$/i and !$nickserv ) {
1290         &DEBUG('ok... we did a who for nickserv.');
1291         &rawout("PRIVMSG NickServ :IDENTIFY $param{'nickServ_pass'}");
1292     }
1293
1294     $nuh{ lc $args[5] } = $args[5] . '!' . $args[2] . '@' . $args[3];
1295 }
1296
1297 sub on_whois {
1298     $conn = shift(@_);
1299     my ($event) = @_;
1300     my @args = $event->args;
1301
1302     $nuh{ lc $args[1] } = $args[1] . '!' . $args[2] . '@' . $args[3];
1303 }
1304
1305 sub on_whoischannels {
1306     $conn = shift(@_);
1307     my ($event) = @_;
1308     my @args = $event->args;
1309
1310     &DEBUG("on_whoischannels: @args");
1311 }
1312
1313 sub on_useronchannel {
1314     $conn = shift(@_);
1315     my ($event) = @_;
1316     my @args = $event->args;
1317
1318     &DEBUG("on_useronchannel: @args");
1319     &joinNextChan();
1320 }
1321
1322 ###
1323 ### since joinnextchan is hooked onto on_endofnames, these are needed.
1324 ###
1325
1326 sub on_chanfull {
1327     $conn = shift(@_);
1328     my ($event) = @_;
1329     my @args = $event->args;
1330
1331     &status(">>> chanfull/$b_blue$args[1]$ob, removing autojoin");
1332     delete $chanconf{$chan}{autojoin};
1333     &joinNextChan();
1334 }
1335
1336 sub on_inviteonly {
1337     $conn = shift(@_);
1338     my ($event) = @_;
1339     my @args = $event->args;
1340
1341     &status(">>> inviteonly/$b_cyan$args[1]$ob, removing autojoin");
1342     delete $chanconf{$chan}{autojoin};
1343     &joinNextChan();
1344 }
1345
1346 sub on_banned {
1347     $conn = shift(@_);
1348     my ($event) = @_;
1349     my @args    = $event->args;
1350     my $chan    = $args[1];
1351
1352     &status(
1353 ">>> banned/$b_blue$chan$ob $b_cyan$args[0]$ob, removing autojoin for $chan"
1354     );
1355     delete $chanconf{$chan}{autojoin};
1356     &joinNextChan();
1357 }
1358
1359 sub on_badchankey {
1360     $conn = shift(@_);
1361     my ($event) = @_;
1362     my @args    = $event->args;
1363     my $chan    = $args[1];
1364
1365     &DEBUG("on_badchankey: args => @args, removing autojoin for $chan");
1366     delete $chanconf{$chan}{autojoin};
1367     &joinNextChan();
1368 }
1369
1370 sub on_useronchan {
1371     $conn = shift(@_);
1372     my ($event) = @_;
1373     my @args = $event->args;
1374
1375     &DEBUG("on_useronchan: args => @args");
1376     &joinNextChan();
1377 }
1378
1379 # TODO not used yet
1380 sub on_stdin {
1381     my $line = <STDIN>;
1382     chomp($line);
1383     &FIXME("on_stdin: line => \"$line\"");
1384 }
1385
1386 1;
1387
1388 # vim:ts=4:sw=4:expandtab:tw=80