]> git.donarmstrong.com Git - infobot.git/blob - src/IRC/IrcHooks.pl
more multinick
[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 =~ /^~?r(oo|ew|00)t$/i );
624
625     ### emit a message based on who just joined
626     &onjoin( $who, $user, $host, $chan ) if ( &IsChanConf('OnJoin') > 0 );
627
628     ### NEWS:
629     if ( &IsChanConf('News') > 0 && &IsChanConf('newsKeepRead') > 0 ) {
630         if ( !&loadMyModule('News') ) {    # just in case.
631             &DEBUG('could not load news.');
632         }
633         else {
634             &News::latest($chan);
635         }
636     }
637
638     ### botmail:
639     if ( &IsChanConf('botmail') > 0 ) {
640         &botmail::check( lc $who );
641     }
642
643     ### wingate:
644     &wingateCheck();
645 }
646
647 sub on_kick {
648     $conn = shift(@_);
649     my ($event) = @_;
650     my ( $chan, $reason ) = $event->args;
651     my $kicker = $event->nick;
652     my $kickee = ( $event->to )[0];
653     my $uh     = $event->userhost();
654
655     &status(
656 ">>> kick/$b_blue$chan$ob [$b$kickee!$uh$ob] by $b_cyan$kicker$ob $b_yellow($ob$reason$b_yellow)$ob"
657     );
658
659     $chan = lc $chan;    # forgot about this, found by xsdg, 20001229.
660     $chanstats{$chan}{'Kick'}++;
661
662     if ( $kickee eq $ident ) {
663         &clearChanVars($chan);
664
665         &status("SELF attempting to rejoin lost channel $chan");
666         &joinchan($chan);
667     }
668     else {
669         &delUserInfo( $kickee, $chan );
670     }
671 }
672
673 sub on_mode {
674     $conn = shift(@_);
675     my ($event) = @_;
676     my ( $user, $host ) = split( /\@/, $event->userhost );
677     my @args = $event->args();
678     my $nick = $event->nick();
679     $chan = ( $event->to )[0];
680
681     # last element is empty... so nuke it.
682     pop @args while ( $args[$#args] eq '' );
683
684     if ( $nick eq $chan ) {    # UMODE
685         &status(
686             ">>> mode $b_yellow\[$ob$b@args$b_yellow\]$ob by $b_cyan$nick$ob");
687     }
688     else {                     # MODE
689         &status(
690 ">>> mode/$b_blue$chan$ob $b_yellow\[$ob$b@args$b_yellow\]$ob by $b_cyan$nick$ob"
691         );
692         &hookMode( $nick, @args );
693     }
694 }
695
696 sub on_modeis {
697     $conn = shift(@_);
698     my ($event) = @_;
699     my ( $myself, undef, @args ) = $event->args();
700     my $nick = $event->nick();
701     $chan = ( $event->args() )[1];
702
703     &hookMode( $nick, @args );
704 }
705
706 sub on_msg {
707     $conn = shift(@_);
708     my ($event) = @_;
709     my $nick    = $event->nick;
710     my $msg     = ( $event->args )[0];
711
712     ( $user, $host ) = split( /\@/, $event->userhost );
713     $uh      = $event->userhost();
714     $nuh     = $nick . '!' . $uh;
715     $msgtime = time();
716     $h       = $host;
717
718     if ( $nick eq $ident ) {    # hopefully ourselves.
719         if ( $msg eq 'TEST' ) {
720             &status("IRCTEST: Yes, we're alive.");
721             delete $cache{connect};
722             return;
723         }
724     }
725
726     &hookMsg( 'private', undef, $nick, $msg );
727     $who     = '';
728     $chan    = '';
729     $msgType = '';
730 }
731
732 sub on_names {
733     $conn = shift(@_);
734     my ($event) = @_;
735     my @args    = $event->args;
736     my $chan    = lc $args[2];    # CASING, the last of them!
737
738     foreach ( split / /, @args[ 3 .. $#args ] ) {
739         $channels{$chan}{'o'}{$_}++ if s/\@//;
740         $channels{$chan}{'v'}{$_}++ if s/\+//;
741         $channels{$chan}{''}{$_}++;
742     }
743 }
744
745 sub on_nick {
746     $conn = shift(@_);
747     my ($event) = @_;
748     my $nick    = $event->nick();
749     my $newnick = ( $event->args )[0];
750
751     if ( exists $netsplit{ lc $newnick } ) {
752         &status(
753 "Netsplit: $newnick/$nick came back from netsplit and changed to original nick! removing from hash."
754         );
755         delete $netsplit{ lc $newnick };
756         &netsplitCheck() if ( time() != $sched{netsplitCheck}{TIME} );
757     }
758
759     my ( $chan, $mode );
760     foreach $chan ( keys %channels ) {
761         foreach $mode ( keys %{ $channels{$chan} } ) {
762             next unless ( exists $channels{$chan}{$mode}{$nick} );
763
764             $channels{$chan}{$mode}{$newnick} = $channels{$chan}{$mode}{$nick};
765         }
766     }
767
768     # TODO: do %flood* aswell.
769
770     &delUserInfo( $nick, keys %channels );
771     $nuh{ lc $newnick } = $nuh{ lc $nick };
772     delete $nuh{ lc $nick };
773
774     if ( $nick eq $conn->nick() ) {
775         &status(">>> I materialized into $b_green$newnick$ob from $nick");
776         $ident = $newnick;
777         $conn->nick($newnick);
778     }
779     else {
780         &status(">>> $b_cyan$nick$ob materializes into $b_green$newnick$ob");
781         my $mynick = $conn->nick();
782         if ( $nick =~ /^\Q$mynick\E$/i ) {
783             &getNickInUse();
784         }
785     }
786 }
787
788 sub on_nick_taken {
789     $conn = shift(@_);
790     my $nick = $conn->nick();
791
792     #my $newnick = $nick . int(rand 10);
793     my $newnick = $nick . '_';
794
795     &DEBUG("on_nick_taken: nick => $nick");
796
797     &status("nick taken ($nick); preparing nick change.");
798
799     $conn->whois($nick);
800
801     #$conn->schedule(5, sub {
802     &status("nick taken; changing to temporary nick ($nick -> $newnick).");
803     &nick($newnick);
804
805     #} );
806 }
807
808 sub on_notice {
809     $conn = shift(@_);
810     my ($event) = @_;
811     my $nick    = $event->nick();
812     my $chan    = ( $event->to )[0];
813     my $args    = ( $event->args )[0];
814     my $mynick  = $conn->nick();
815
816     if ( $nick =~ /^NickServ$/i ) {    # nickserv.
817         &status("NickServ: $mynick <== '$args'");
818
819         my $check = 0;
820         $check++ if ( $args =~ /^This nickname is registered/i );
821         $check++ if ( $args =~ /nickname.*owned/i );
822
823         if ($check) {
824             &status("nickserv told $mynick to register; doing it.");
825
826             if ( &IsParam('nickServ_pass') ) {
827                 &status("NickServ: ==> Identifying as $mynick.");
828                 &rawout("PRIVMSG NickServ :IDENTIFY $param{'nickServ_pass'}");
829                 return;
830             }
831             else {
832                 &status("$mynick can't tell nickserv a passwd ;(");
833             }
834         }
835
836         # password accepted.
837         if ( $args =~ /^Password a/i ) {
838             my $done = 0;
839
840             foreach ( &ChanConfList('chanServ_ops') ) {
841                 next unless &chanServCheck($_);
842                 next if ($done);
843                 &DEBUG('nickserv activated or restarted; doing chanserv check.');
844                 $done++;
845             }
846
847             $nickserv++;
848         }
849
850     }
851     elsif ( $nick =~ /^ChanServ$/i ) {    # chanserv.
852         &status("ChanServ: <== '$args'.");
853
854     }
855     else {
856         if ( $chan =~ /^$mask{chan}$/ ) {    # channel notice.
857             &status("-$nick/$chan- $args");
858         }
859         else {
860             $server = $nick unless ( defined $server );
861             &status("-$nick- $args");        # private or server notice.
862         }
863     }
864 }
865
866 sub on_other {
867     $conn = shift(@_);
868     my ($event) = @_;
869     my $chan    = ( $event->to )[0];
870     my $nick    = $event->nick;
871
872     &status('!!! other called.');
873     &status("!!! $event->args");
874 }
875
876 sub on_part {
877     $conn = shift(@_);
878     my ($event) = @_;
879     $chan = lc( ( $event->to )[0] );    # CASING!!!
880     my $mynick   = $conn->nick();
881     my $nick     = $event->nick;
882     my $userhost = $event->userhost;
883     $who     = $nick;
884     $msgType = 'public';
885
886     if ( !exists $channels{$chan} ) {
887         &DEBUG("on_part: found out $mynick is on $chan!");
888         $channels{$chan} = 1;
889     }
890
891     if ( exists $floodjoin{$chan}{$nick}{Time} ) {
892         delete $floodjoin{$chan}{$nick};
893     }
894
895     $chanstats{$chan}{'Part'}++;
896     &delUserInfo( $nick, $chan );
897     if ( $nick eq $ident ) {
898         &clearChanVars($chan);
899     }
900
901     if ( !&IsNickInAnyChan($nick) and &IsChanConf('seenStats') > 0 ) {
902         delete $userstats{ lc $nick };
903     }
904
905     &status(
906 ">>> part/$b_blue$chan$ob $b_cyan$nick$ob $b_yellow($ob$userhost$b_yellow)$ob"
907     );
908 }
909
910 sub on_ping {
911     $conn = shift(@_);
912     my ($event) = @_;
913     my $nick = $event->nick;
914
915     $conn->ctcp_reply( $nick, join( ' ', ( $event->args ) ) );
916     &status(
917         ">>> ${b_green}CTCP PING$ob request from $b_cyan$nick$ob received.");
918 }
919
920 sub on_ping_reply {
921     $conn = shift(@_);
922     my ($event) = @_;
923     my $nick    = $event->nick;
924     my $t       = ( $event->args )[1];
925     if ( !defined $t ) {
926         &WARN('on_ping_reply: t == undefined.');
927         return;
928     }
929
930     my $lag = time() - $t;
931
932     &status(">>> ${b_green}CTCP PING$ob reply from $b_cyan$nick$ob: $lag sec.");
933 }
934
935 sub on_public {
936     $conn = shift(@_);
937     my ($event) = @_;
938     my $msg = ( $event->args )[0];
939     $chan = lc( ( $event->to )[0] );    # CASING.
940     my $nick = $event->nick;
941     $who     = $nick;
942     $uh      = $event->userhost();
943     $nuh     = $nick . '!' . $uh;
944     $msgType = 'public';
945
946     # TODO: move this out of hookMsg to here?
947     ( $user, $host ) = split( /\@/, $uh );
948     $h = $host;
949
950     # rare case should this happen - catch it just in case.
951     if ( $bot_pid != $$ ) {
952         &ERROR('run-away fork; exiting.');
953         &delForked($forker);
954     }
955
956     $msgtime = time();
957     $lastWho{$chan} = $nick;
958     ### TODO: use $nick or lc $nick?
959     if ( &IsChanConf('seenStats') > 0 ) {
960         $userstats{ lc $nick }{'Count'}++;
961         $userstats{ lc $nick }{'Time'} = time();
962     }
963
964     # cache it.
965     my $time = time();
966     if ( !$cache{ircTextCounters} ) {
967         &DEBUG('caching ircTextCounters for first time.');
968         my @str = split( /\s+/, &getChanConf('ircTextCounters') );
969         for (@str) { $_ = quotemeta($_); }
970         $cache{ircTextCounters} = join( '|', @str );
971     }
972
973     my $str = $cache{ircTextCounters};
974     if ( $str && $msg =~ /^($str)[\s!\.]?$/i ) {
975         my $x = $1;
976
977         &VERB( "textcounters: $x matched for $who", 2 );
978         my $c = $chan || 'PRIVATE';
979
980         # better to do 'counter=counter+1'.
981         # but that will avoid time check.
982         my ( $v, $t ) = &sqlSelect(
983             'stats',
984             'counter,time',
985             {
986                 nick    => $who,
987                 type    => $x,
988                 channel => $c,
989             }
990         );
991         $v++;
992
993         # don't allow ppl to cheat the stats :-)
994         if ( ( defined $t && $time - $t > 60 ) or ( !defined $t ) ) {
995             &sqlSet(
996                 'stats',
997                 {
998                                 'nick' => $who,
999                     'type'    => $x,
1000                     'channel' => $c,
1001                 },
1002                 {
1003                     time    => $time,
1004                     counter => $v,
1005                 }
1006             );
1007         }
1008     }
1009
1010     &hookMsg( 'public', $chan, $nick, $msg );
1011     $chanstats{$chan}{'PublicMsg'}++;
1012     $who     = '';
1013     $chan    = '';
1014     $msgType = '';
1015 }
1016
1017 sub on_quit {
1018     $conn = shift(@_);
1019     my ($event) = @_;
1020     my $nick    = $event->nick();
1021     my $reason  = ( $event->args )[0];
1022
1023     # hack for ICC.
1024     $msgType = 'public';
1025     $who     = $nick;
1026 ###    $chan    = $reason;      # no.
1027
1028     my $count = 0;
1029     foreach ( grep !/^_default$/, keys %channels ) {
1030
1031         # fixes inconsistent chanstats bug #1.
1032         if ( !&IsNickInChan( $nick, $_ ) ) {
1033             $count++;
1034             next;
1035         }
1036         $chanstats{$_}{'SignOff'}++;
1037     }
1038
1039     if ( $count == scalar keys %channels ) {
1040         &DEBUG("on_quit: nick $nick was not found in any chan.");
1041     }
1042
1043     # should fix chanstats inconsistencies bug #2.
1044     if ( $reason =~ /^($mask{host})\s($mask{host})$/ ) {    # netsplit.
1045         $reason = "NETSPLIT: $1 <=> $2";
1046
1047         # chanlimit code.
1048         foreach $chan ( &getNickInChans($nick) ) {
1049             next unless ( &IsChanConf('chanlimitcheck') > 0 );
1050             next unless ( exists $channels{$_}{'l'} );
1051
1052             &DEBUG("on_quit: netsplit detected on $_; disabling chan limit.");
1053             $conn->mode( $_, '-l' );
1054         }
1055
1056         $netsplit{ lc $nick } = time();
1057         if ( !exists $netsplitservers{$1}{$2} ) {
1058             &status("netsplit detected between $1 and $2 at ["
1059                   . scalar(gmtime)
1060                   . ']' );
1061             $netsplitservers{$1}{$2} = time();
1062         }
1063     }
1064
1065     my $chans = join( ' ', &getNickInChans($nick) );
1066     &status(
1067 ">>> $b_cyan$nick$ob has signed off IRC $b_red($ob$reason$b_red)$ob [$chans]"
1068     );
1069
1070     ###
1071     ### ok... lets clear out the cache
1072     ###
1073     &delUserInfo( $nick, keys %channels );
1074     if ( exists $nuh{ lc $nick } ) {
1075         delete $nuh{ lc $nick };
1076     }
1077     else {
1078
1079         # well.. it's good but weird that this has happened - lets just
1080         # be quiet about it.
1081     }
1082     delete $userstats{ lc $nick } if ( &IsChanConf('seenStats') > 0 );
1083     delete $chanstats{ lc $nick };
1084     ###
1085
1086     # if we have a temp nick, and whoever is camping on our main nick leaves
1087     # revert to main nick. Note that Net::IRC only knows our main nick
1088     if ( $nick eq $conn->nick() ) {
1089         &status("nickchange: own nick \"$nick\" became free; changing.");
1090         &nick($mynick);
1091     }
1092 }
1093
1094 sub on_targettoofast {
1095     $conn = shift(@_);
1096     my ($event) = @_;
1097     my $nick = $event->nick();
1098     my ( $me, $chan, $why ) = $event->args();
1099
1100     ### TODO: incomplete.
1101     if ( $why =~ /.* wait (\d+) second/ ) {
1102         my $sleep = $1;
1103         my $max   = 10;
1104
1105         if ( $sleep > $max ) {
1106             &status("targettoofast: going to sleep for $max ($sleep)...");
1107             $sleep = $max;
1108         }
1109         else {
1110             &status("targettoofast: going to sleep for $sleep");
1111         }
1112
1113         my $delta = time() - ( $cache{sleepTime} || 0 );
1114         if ( $delta > $max + 2 ) {
1115             sleep $sleep;
1116             $cache{sleepTime} = time();
1117         }
1118
1119         return;
1120     }
1121
1122     if ( !exists $cache{TargetTooFast} ) {
1123         &DEBUG("on_ttf: failed: $why");
1124         $cache{TargetTooFast}++;
1125     }
1126 }
1127
1128 sub on_topic {
1129     $conn = shift(@_);
1130     my ($event) = @_;
1131
1132     if ( scalar( $event->args ) == 1 ) {    # change.
1133         my $topic = ( $event->args )[0];
1134         my $chan  = ( $event->to )[0];
1135         my $nick  = $event->nick();
1136
1137         ###
1138         # WARNING:
1139         #       race condition here. To fix, change '1' to '0'.
1140         #       This will keep track of topics set by bot only.
1141         ###
1142         # UPDATE:
1143         #       this may be fixed at a later date with topic queueing.
1144         ###
1145
1146         $topic{$chan}{'Current'} = $topic if (1);
1147         $chanstats{$chan}{'Topic'}++;
1148
1149         &status(">>> topic/$b_blue$chan$ob by $b_cyan$nick$ob -> $topic");
1150     }
1151     else {    # join.
1152         my ( $nick, $chan, $topic ) = $event->args;
1153         if ( &IsChanConf('Topic') > 0 ) {
1154             $topic{$chan}{'Current'} = $topic;
1155             &topicAddHistory( $chan, $topic );
1156         }
1157
1158         $topic = &fixString( $topic, 1 );
1159         &status(">>> topic/$b_blue$chan$ob is $topic");
1160     }
1161 }
1162
1163 sub on_topicinfo {
1164     $conn = shift(@_);
1165     my ($event) = @_;
1166     my ( $myself, $chan, $setby, $time ) = $event->args();
1167
1168     my $timestr;
1169     if ( time() - $time > 60 * 60 * 24 ) {
1170         $timestr = 'at ' . gmtime $time;
1171     }
1172     else {
1173         $timestr = &Time2String( time() - $time ) . ' ago';
1174     }
1175
1176     &status(">>> set by $b_cyan$setby$ob $timestr");
1177 }
1178
1179 sub on_crversion {
1180     $conn = shift(@_);
1181     my ($event) = @_;
1182     my $nick = $event->nick();
1183     my $ver;
1184
1185     if ( scalar $event->args() != 1 ) {    # old.
1186         $ver = join ' ', $event->args();
1187         $ver =~ s/^VERSION //;
1188     }
1189     else {                                 # new.
1190         $ver = ( $event->args() )[0];
1191     }
1192
1193     if ( grep /^\Q$nick\E$/i, @vernick ) {
1194         &WARN("nick $nick found in vernick ($ver); skipping.");
1195         return;
1196     }
1197     push( @vernick, $nick );
1198
1199     &DEBUG("on_crversion: Got '$ver' from $nick");
1200
1201     if ( $ver =~ /bitchx/i ) {
1202         $ver{bitchx}{$nick} = $ver;
1203
1204     }
1205     elsif ( $ver =~ /infobot/i ) {
1206         $ver{infobot}{$nick} = $ver;
1207
1208     }
1209     elsif ( $ver =~ /(xc\!|xchat)/i ) {
1210         $ver{xchat}{$nick} = $ver;
1211
1212     }
1213     elsif ( $ver =~ /irssi/i ) {
1214         $ver{irssi}{$nick} = $ver;
1215
1216     }
1217     elsif ( $ver =~ /(epic|Third Eye)/i ) {
1218         $ver{epic}{$nick} = $ver;
1219
1220     }
1221     elsif ( $ver =~ /(ircII|PhoEniX)/i ) {
1222         $ver{ircII}{$nick} = $ver;
1223
1224     }
1225     elsif ( $ver =~ /mirc/i ) {
1226         # Apparently, mIRC gets the reply as "VERSION " and doesnt like the
1227         # space, so mirc matching is considered bugged.
1228         $ver{mirc}{$nick} = $ver;
1229
1230     }
1231     elsif ( $ver =~ /ircle/i ) {
1232         $ver{ircle}{$nick} = $ver;
1233
1234     }
1235     elsif ( $ver =~ /chatzilla/i ) {
1236         $ver{chatzilla}{$nick} = $ver;
1237
1238     }
1239     elsif ( $ver =~ /pirch/i ) {
1240         $ver{pirch}{$nick} = $ver;
1241
1242     }
1243     elsif ( $ver =~ /sirc /i ) {
1244         $ver{sirc}{$nick} = $ver;
1245
1246     }
1247     elsif ( $ver =~ /kvirc/i ) {
1248         $ver{kvirc}{$nick} = $ver;
1249
1250     }
1251     elsif ( $ver =~ /eggdrop/i ) {
1252         $ver{eggdrop}{$nick} = $ver;
1253
1254     }
1255     elsif ( $ver =~ /xircon/i ) {
1256         $ver{xircon}{$nick} = $ver;
1257
1258     }
1259     else {
1260         &DEBUG("verstats: other: $nick => '$ver'.");
1261         $ver{other}{$nick} = $ver;
1262     }
1263 }
1264
1265 sub on_version {
1266     $conn = shift(@_);
1267     my ($event) = @_;
1268     my $nick = $event->nick;
1269
1270     &status(">>> ${b_green}CTCP VERSION$ob request from $b_cyan$nick$ob");
1271     $conn->ctcp_reply( $nick, "VERSION $bot_version" );
1272 }
1273
1274 sub on_who {
1275     $conn = shift(@_);
1276     my ($event) = @_;
1277     my @args    = $event->args;
1278     my $str     = $args[5] . '!' . $args[2] . '@' . $args[3];
1279
1280     if ( $cache{on_who_Hack} ) {
1281         $cache{nuhInfo}{ lc $args[5] }{Nick} = $args[5];
1282         $cache{nuhInfo}{ lc $args[5] }{User} = $args[2];
1283         $cache{nuhInfo}{ lc $args[5] }{Host} = $args[3];
1284         $cache{nuhInfo}{ lc $args[5] }{NUH}  = "$args[5]!$args[2]\@$args[3]";
1285         return;
1286     }
1287
1288     if ( $args[5] =~ /^nickserv$/i and !$nickserv ) {
1289         &DEBUG('ok... we did a who for nickserv.');
1290         &rawout("PRIVMSG NickServ :IDENTIFY $param{'nickServ_pass'}");
1291     }
1292
1293     $nuh{ lc $args[5] } = $args[5] . '!' . $args[2] . '@' . $args[3];
1294 }
1295
1296 sub on_whois {
1297     $conn = shift(@_);
1298     my ($event) = @_;
1299     my @args = $event->args;
1300
1301     $nuh{ lc $args[1] } = $args[1] . '!' . $args[2] . '@' . $args[3];
1302 }
1303
1304 sub on_whoischannels {
1305     $conn = shift(@_);
1306     my ($event) = @_;
1307     my @args = $event->args;
1308
1309     &DEBUG("on_whoischannels: @args");
1310 }
1311
1312 sub on_useronchannel {
1313     $conn = shift(@_);
1314     my ($event) = @_;
1315     my @args = $event->args;
1316
1317     &DEBUG("on_useronchannel: @args");
1318     &joinNextChan();
1319 }
1320
1321 ###
1322 ### since joinnextchan is hooked onto on_endofnames, these are needed.
1323 ###
1324
1325 sub on_chanfull {
1326     $conn = shift(@_);
1327     my ($event) = @_;
1328     my @args = $event->args;
1329
1330     &status(">>> chanfull/$b_blue$args[1]$ob");
1331
1332     &joinNextChan();
1333 }
1334
1335 sub on_inviteonly {
1336     $conn = shift(@_);
1337     my ($event) = @_;
1338     my @args = $event->args;
1339
1340     &status(">>> inviteonly/$b_cyan$args[1]$ob");
1341
1342     &joinNextChan();
1343 }
1344
1345 sub on_banned {
1346     $conn = shift(@_);
1347     my ($event) = @_;
1348     my @args    = $event->args;
1349     my $chan    = $args[1];
1350
1351     &status(
1352 ">>> banned/$b_blue$chan$ob $b_cyan$args[0]$ob, removing autojoin for $chan"
1353     );
1354     delete $chanconf{$chan}{autojoin};
1355     &joinNextChan();
1356 }
1357
1358 sub on_badchankey {
1359     $conn = shift(@_);
1360     my ($event) = @_;
1361     my @args    = $event->args;
1362     my $chan    = $args[1];
1363
1364     &DEBUG("on_badchankey: args => @args, removing autojoin for $chan");
1365     delete $chanconf{$chan}{autojoin};
1366     &joinNextChan();
1367 }
1368
1369 sub on_useronchan {
1370     $conn = shift(@_);
1371     my ($event) = @_;
1372     my @args = $event->args;
1373
1374     &DEBUG("on_useronchan: args => @args");
1375     &joinNextChan();
1376 }
1377
1378 # TODO not used yet
1379 sub on_stdin {
1380     my $line = <STDIN>;
1381     chomp($line);
1382     &FIXME("on_stdin: line => \"$line\"");
1383 }
1384
1385 1;
1386
1387 # vim:ts=4:sw=4:expandtab:tw=80