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