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