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