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