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