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