]> git.donarmstrong.com Git - infobot.git/blob - src/IRC/IrcHooks.pl
006f106ad59d6d8af340c22e896fb171b23d4329
[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     } else {
363         &DEBUG("running ircCheck to get chanserv ops.");
364         &ircCheck();
365     }
366
367     return unless (&IsChanConf("chanServ_ops") > 0);
368     return unless ($nickserv);
369
370     if (!exists $channels{$chan}{'o'}{$ident}) {
371         &status("ChanServ ==> Requesting ops for $chan.");
372         &rawout("PRIVMSG ChanServ :OP $chan $ident");
373     }
374 }
375
376 sub on_init {
377     my ($self, $event) = @_;
378     my (@args) = ($event->args);
379     shift @args;
380
381     &status("@args");
382 }
383
384 sub on_invite {
385     my ($self, $event) = @_;
386     my $chan = lc( ($event->args)[0] );
387     my $nick = $event->nick;
388
389     if ($nick =~ /^\Q$ident\E$/) {
390         &DEBUG("on_invite: self invite.");
391         return;
392     }
393
394     ### TODO: join key.
395     if (exists $chanconf{$chan}) {
396         if (&validChan($chan)) {
397             &msg($who, "i'm already in \002$chan\002.");
398             next;
399         }
400
401         &status("invited to $b_blue$_$ob by $b_cyan$who$ob");
402         &joinchan($self, $_);
403     }
404 }
405
406 sub on_join {
407     my ($self, $event) = @_;
408     my ($user,$host) = split(/\@/, $event->userhost);
409     $chan       = lc( ($event->to)[0] );        # CASING!!!!
410     $who        = $event->nick();
411
412     $chanstats{$chan}{'Join'}++;
413     $userstats{lc $who}{'Join'} = time() if (&IsChanConf("seenStats"));
414
415     &joinfloodCheck($who, $chan, $event->userhost);
416
417     # netjoin detection.
418     my $netsplit = 0;
419     if (exists $netsplit{lc $who}) {
420         delete $netsplit{lc $who};
421         $netsplit = 1;
422     }
423
424     if ($netsplit and !$netsplittime) {
425         &DEBUG("on_join: ok.... re-running chanlimitCheck in 60.");
426         $conn->schedule(60, sub {
427                 &chanlimitCheck();
428                 $netsplittime = undef;
429         } );
430
431         $netsplittime = time();
432     }
433
434     # how to tell if there's a netjoin???
435
436     my $netsplitstr = "";
437     $netsplitstr = " $b_yellow\[${ob}NETSPLIT VICTIM$b_yellow]$ob" if ($netsplit);
438     &status(">>> join/$b_blue$chan$ob $b_cyan$who$ob $b_yellow($ob$user\@$host$b_yellow)$ob$netsplitstr");
439
440     $channels{$chan}{''}{$who}++;
441     $nuh          = $who."!".$user."\@".$host;
442     $nuh{lc $who} = $nuh unless (exists $nuh{lc $who});
443
444     ### on-join bans.
445     my @bans;
446     push(@bans, keys %{ $bans{$chan} }) if (exists $bans{$chan});
447     push(@bans, keys %{ $bans{"*"} })  if (exists $bans{"*"});
448     foreach (@bans) {
449         my $ban = $_;
450         s/\?/./g;
451         s/\*/\\S*/g;
452         my $mask        = $_;
453         next unless ($nuh =~ /^$mask$/i);
454
455         ### TODO: check $channels{$chan}{'b'} if ban already exists.
456         foreach (keys %{ $channels{$chan}{'b'} }) {
457             &DEBUG(" bans_on_chan($chan) => $_");
458         }
459
460         my $reason = "no reason";
461         foreach ($chan, "*") {
462             next unless (exists $bans{$_});
463             next unless (exists $bans{$_}{$ban});
464
465             my @array   = @{ $bans{$_}{$ban} };
466
467             $reason     = $array[4] if ($array[4]);
468             last;
469         }
470
471         &ban($ban, $chan);
472         &kick($who, $chan, $reason);
473
474         last;
475     }
476
477     ### ROOTWARN:
478     &rootWarn($who,$user,$host,$chan)
479                 if (&IsChanConf("rootWarn") &&
480                     $user =~ /^r(oo|ew|00)t$/i &&
481                     $channels{$chan}{'o'}{$ident});
482
483     ### NEWS:
484     if (&IsChanConf("news") && &IsChanConf("newsKeepRead")) {
485         my @new;
486         foreach (keys %{ $::news{$chan} }) {
487             my $t = $::newsuser{$chan}{$who};
488             next if (!defined $t);
489             next if ($t > $::news{$chan}{$_}{Time});
490
491             push(@new, $_);
492         }
493
494         if (scalar @new) {
495             &msg($who, "+==== New news for $chan (".scalar(@new)."):");
496             # todo: show how many sec/min/etc ago?
497             my $timestr = &Time2String( time() - $::newsuser{$chan}{$who} );
498             &msg($who, "|= Last time read $timestr ago");
499
500             foreach (@new) {
501                 my $i   = &News::getNewsItem($_);
502                 my $age = time() - $::news{$chan}{$_}{Time};
503                 &msg($who, sprintf("\002[\002%2d\002]\002 %s (%s)",
504                         $i, $_, &Time2String($age) ) );
505             }
506             &msg($who, "to read, do 'news read <#>' or 'news read <keyword>'");
507
508             # lame hack to prevent dupes if we just ignore it.
509             $::newsuser{$chan}{$who} = time();
510         }
511     }
512
513     ### chanlimit check.
514     &chanLimitVerify($chan);
515
516     # used to determine sync time.
517     if ($who =~ /^$ident$/i) {
518         if (defined( my $whojoin = $cache{join}{$chan} )) {
519             &msg($chan, "Okay, I'm here. (courtesy of $whojoin)");
520             delete $cache{join}{$chan};
521         }
522
523         ### TODO: move this to &joinchan()?
524         $cache{jointime}{$chan} = &gettimeofday();
525         rawout("WHO $chan");
526     } else {
527         ### TODO: this may go wild on a netjoin :)
528         ### WINGATE:
529         &wingateCheck();
530     }
531 }
532
533 sub on_kick {
534     my ($self, $event) = @_;
535     my ($chan,$reason) = $event->args;
536     my $kicker  = $event->nick;
537     my $kickee  = ($event->to)[0];
538     my $uh      = $event->userhost();
539
540     &status(">>> kick/$b_blue$chan$ob [$b$kickee!$uh$ob] by $b_cyan$kicker$ob $b_yellow($ob$reason$b_yellow)$ob");
541
542     $chan = lc $chan;   # forgot about this, found by xsdg, 20001229.
543     $chanstats{$chan}{'Kick'}++;
544
545     if ($kickee eq $ident) {
546         &clearChanVars($chan);
547
548         &status("SELF attempting to rejoin lost channel $chan");
549         &joinchan($chan);
550     } else {
551         &DeleteUserInfo($kickee,$chan);
552     }
553 }
554
555 sub on_mode {
556     my ($self, $event)  = @_;
557     my ($user, $host)   = split(/\@/, $event->userhost);
558     my @args = $event->args();
559     my $nick = $event->nick();
560     my $chan = ($event->to)[0];
561
562     $args[0] =~ s/\s$//;
563
564     if ($nick eq $chan) {       # UMODE
565         &status(">>> mode $b_yellow\[$ob$b@args$b_yellow\]$ob by $b_cyan$nick$ob");
566     } else {                    # MODE
567         &status(">>> mode/$b_blue$chan$ob $b_yellow\[$ob$b@args$b_yellow\]$ob by $b_cyan$nick$ob");
568         &hookMode($chan, @args);
569     }
570 }
571
572 sub on_modeis {
573     my ($self, $event) = @_;
574     my $nick = $event->nick();
575     my ($myself,$chan,@args) = $event->args();
576
577     &hookMode(lc $chan, @args);         # CASING.
578 }
579
580 sub on_msg {
581     my ($self, $event) = @_;
582     my $nick = $event->nick;
583     my $msg  = ($event->args)[0];
584
585     ($user,$host) = split(/\@/, $event->userhost);
586     $uh         = $event->userhost();
587     $nuh        = $nick."!".$uh;
588     $msgtime    = time();
589
590     if ($nick eq $ident) { # hopefully ourselves.
591         if ($msg eq "TEST") {
592             &status("Local: Yes, we're alive.");
593             delete $cache{connect};
594             return;
595         }
596     }
597
598     &hookMsg('private', undef, $nick, $msg);
599 }
600
601 sub on_names {
602     my ($self, $event) = @_;
603     my @args = $event->args;
604     my $chan = lc $args[2];             # CASING, the last of them!
605
606     foreach (split / /, @args[3..$#args]) {
607         $channels{$chan}{'o'}{$_}++     if s/\@//;
608         $channels{$chan}{'v'}{$_}++     if s/\+//;
609         $channels{$chan}{''}{$_}++;
610     }
611 }
612
613 sub on_nick {
614     my ($self, $event) = @_;
615     my $nick = $event->nick();
616     my $newnick = ($event->args)[0];
617
618     if (exists $netsplit{lc $newnick}) {
619         &status("Netsplit: $newnick/$nick came back from netsplit and changed to original nick! removing from hash.");
620         delete $netsplit{lc $newnick};
621     }
622
623     my ($chan,$mode);
624     foreach $chan (keys %channels) {
625         foreach $mode (keys %{$channels{$chan}}) {
626             next unless (exists $channels{$chan}{$mode}{$nick});
627
628             $channels{$chan}{$mode}{$newnick} = $channels{$chan}{$mode}{$nick};
629         }
630     }
631     &DeleteUserInfo($nick,keys %channels);
632     $nuh{lc $newnick} = $nuh{lc $nick};
633     delete $nuh{lc $nick};
634
635     # successful self-nick change.
636     if ($nick eq $ident) {
637         &status(">>> I materialized into $b_green$newnick$ob from $nick");
638         $ident = $newnick;
639     } else {
640         &status(">>> $b_cyan$nick$ob materializes into $b_green$newnick$ob");
641     }
642 }
643
644 sub on_nick_taken {
645     my ($self) = @_;
646     my $nick = $self->nick;
647     my $newnick = substr($nick,0,7)."-";
648
649     &status("nick taken; changing to temporary nick.");
650     &nick($newnick);
651     &getNickInUse(1);
652 }
653
654 sub on_notice {
655     my ($self, $event) = @_;
656     my $nick = $event->nick();
657     my $chan = ($event->to)[0];
658     my $args = ($event->args)[0];
659
660     if ($nick =~ /^NickServ$/i) {               # nickserv.
661         &status("NickServ: <== '$args'");
662
663         my $check       = 0;
664         $check++        if ($args =~ /^This nickname is registered/i);
665         $check++        if ($args =~ /nickname.*owned/i);
666
667         if ($check) {
668             &status("nickserv told us to register; doing it.");
669             if (&IsParam("nickServ_pass")) {
670                 &status("NickServ: ==> Identifying.");
671                 &rawout("PRIVMSG NickServ :IDENTIFY $param{'nickServ_pass'}");
672                 return;
673             } else {
674                 &status("We can't tell nickserv a passwd ;(");
675             }
676         }
677
678         # password accepted.
679         if ($args =~ /^Password a/i) {
680             $nickserv++;
681         }
682     } elsif ($nick =~ /^ChanServ$/i) {          # chanserv.
683         &status("ChanServ: <== '$args'.");
684     } else {
685         if ($chan =~ /^$mask{chan}$/) { # channel notice.
686             &status("-$nick/$chan- $args");
687         } else {
688             $server = $nick unless (defined $server);
689             &status("-$nick- $args");   # private or server notice.
690         }
691     }
692 }
693
694 sub on_other {
695     my ($self, $event) = @_;
696     my $chan = ($event->to)[0];
697     my $nick = $event->nick;
698
699     &status("!!! other called.");
700     &status("!!! $event->args");
701 }
702
703 sub on_part {
704     my ($self, $event) = @_;
705     my $chan = lc( ($event->to)[0] );   # CASING!!!
706     my $nick = $event->nick;
707     my $userhost = $event->userhost;
708
709     if (exists $floodjoin{$chan}{$nick}{Time}) {
710         delete $floodjoin{$chan}{$nick};
711     }
712
713     $chanstats{$chan}{'Part'}++;
714     &DeleteUserInfo($nick,$chan);
715     &clearChanVars($chan) if ($nick eq $ident);
716     if (!&IsNickInAnyChan($nick) and &IsChanConf("seenStats")) {
717         delete $userstats{lc $nick};
718     }
719
720     &status(">>> part/$b_blue$chan$ob $b_cyan$nick$ob $b_yellow($ob$userhost$b_yellow)$ob");
721 }
722
723 sub on_ping {
724     my ($self, $event) = @_;
725     my $nick = $event->nick;
726
727     $self->ctcp_reply($nick, join(' ', ($event->args)));
728     &status(">>> ${b_green}CTCP PING$ob request from $b_cyan$nick$ob received.");
729 }
730
731 sub on_ping_reply {
732     my ($self, $event) = @_;
733     my $nick = $event->nick;
734     my $lag = time() - ($event->args)[1];
735
736     &status(">>> ${b_green}CTCP PING$ob reply from $b_cyan$nick$ob: $lag sec.");
737 }
738
739 sub on_public {
740     my ($self, $event) = @_;
741     my $msg  = ($event->args)[0];
742     my $chan = lc( ($event->to)[0] );   # CASING.
743     my $nick = $event->nick;
744     $uh      = $event->userhost();
745     $nuh     = $nick."!".$uh;
746     ($user,$host) = split(/\@/, $uh);
747
748     if ($bot_pid != $$) {
749         &ERROR("run-away fork; exiting.");
750         &delForked($forker);
751     }
752
753     ### DEBUGGING.
754     if ($statcount < 200) {
755         foreach $chan (grep /[A-Z]/, keys %channels) {
756             &DEBUG("leak: chan => '$chan'.");
757             my ($i,$j);
758             foreach $i (keys %{$channels{$chan}}) {  
759                 foreach (keys %{$channels{$chan}{$i}}) {
760                     &DEBUG("leak:   \$channels{$chan}{$i}{$_} ...");
761                 }
762             }
763         }
764     }
765
766     $msgtime = time();
767     $lastWho{$chan} = $nick;
768     ### TODO: use $nick or lc $nick?
769     if (&IsChanConf("seenStats")) {
770         $userstats{lc $nick}{'Count'}++;
771         $userstats{lc $nick}{'Time'} = time();
772     }
773
774 #    if (&IsChanConf("hehCounter")) {
775 #       #...
776 #    }
777
778     &hookMsg('public', $chan, $nick, $msg);
779     $chanstats{$chan}{'PublicMsg'}++;
780 }
781
782 sub on_quit {
783     my ($self, $event) = @_;
784     my $nick = $event->nick();
785     my $reason = ($event->args)[0];
786
787     my $count   = 0;
788     foreach (keys %channels) {
789         # fixes inconsistent chanstats bug #1.
790         if (!&IsNickInChan($nick,$_)) {
791             $count++;
792             next;
793         }
794         $chanstats{$_}{'SignOff'}++;
795     }
796
797     if ($count == scalar keys %channels) {
798         &DEBUG("on_quit: nick $nick was not found in any chan.");
799     }
800
801     &DeleteUserInfo($nick, keys %channels);
802
803     if (exists $nuh{lc $nick}) {
804         delete $nuh{lc $nick};
805     } else {
806         &DEBUG("on_quit: nuh{lc $nick} does not exist! FIXME");
807     }
808     delete $userstats{lc $nick} if (&IsChanConf("seenStats"));
809
810     # should fix chanstats inconsistencies bug #2.
811     if ($reason=~/^($mask{host})\s($mask{host})$/) {    # netsplit.
812         $reason = "NETSPLIT: $1 <=> $2";
813
814         if (&ChanConfList("chanlimitcheck") and !scalar keys %netsplit) {
815             &DEBUG("on_quit: netsplit detected; disabling chan limit.");
816             &rawout("MODE $chan -l");
817         }
818
819         $netsplit{lc $nick} = time();
820         if (!exists $netsplitservers{$1}{$2}) {
821             &status("netsplit detected between $1 and $2.");
822             $netsplitservers{$1}{$2} = time();
823         }
824     }
825
826     &status(">>> $b_cyan$nick$ob has signed off IRC $b_red($ob$reason$b_red)$ob");
827     if ($nick =~ /^\Q$ident\E$/) {
828         &DEBUG("^^^ THIS SHOULD NEVER HAPPEN.");
829     }
830
831     if ($nick !~ /^\Q$ident\E$/ and $nick =~ /^\Q$param{'ircNick'}\E$/i) {
832         &status("own nickname became free; changing.");
833         &nick($param{'ircNick'});
834     }
835 }
836
837 sub on_targettoofast {
838     my ($self, $event) = @_;
839     my $nick = $event->nick();
840     my($me,$chan,$why) = $event->args();
841
842     ### TODO: incomplete.
843 ###    .* wait (\d+) second/) {
844         &status("on_ttf: X1 $msg") if (defined $msg);
845         my $sleep = 5;
846         &status("going to sleep for $sleep...");
847         sleep $sleep;
848         &joinNextChan();
849 ### }
850 }
851
852 sub on_topic {
853     my ($self, $event) = @_;
854
855     if (scalar($event->args) == 1) {    # change.
856         my $topic = ($event->args)[0];
857         my $chan  = ($event->to)[0];
858         my $nick  = $event->nick();
859
860         ###
861         # WARNING:
862         #       race condition here. To fix, change '1' to '0'.
863         #       This will keep track of topics set by bot only.
864         ###
865         # UPDATE:
866         #       this may be fixed at a later date with topic queueing.
867         ###
868
869         $topic{$chan}{'Current'} = $topic if (1);
870         $chanstats{$chan}{'Topic'}++;
871
872         &status(">>> topic/$b_blue$chan$ob by $b_cyan$nick$ob -> $topic");
873     } else {                                            # join.
874         my ($nick, $chan, $topic) = $event->args;
875         if (&IsChanConf("topic")) {
876             $topic{$chan}{'Current'}    = $topic;
877             &topicAddHistory($chan,$topic);
878         }
879
880         $topic = &fixString($topic, 1);
881         &status(">>> topic/$b_blue$chan$ob is $topic");
882     }
883 }
884
885 sub on_topicinfo {
886     my ($self, $event) = @_;
887     my ($myself,$chan,$setby,$time) = $event->args();
888
889     my $timestr;
890     if (time() - $time > 60*60*24) {
891         $timestr        = "at ". localtime $time;
892     } else {
893         $timestr        = &Time2String(time() - $time) ." ago";
894     }
895
896     &status(">>> set by $b_cyan$setby$ob $timestr");
897 }
898
899 sub on_crversion {
900     my ($self, $event) = @_;
901     my $nick    = $event->nick();
902     my $ver;
903
904     if (scalar $event->args() != 1) {   # old.
905         $ver    = join ' ', $event->args();
906         $ver    =~ s/^VERSION //;
907     } else {                            # new.
908         $ver    = ($event->args())[0];
909     }
910
911     if (grep /^\Q$nick\E$/i, @vernick) {
912         &WARN("nick $nick found in vernick; skipping.");
913         return;
914     }
915     push(@vernick, $nick);
916
917     if ($ver =~ /bitchx/i) {
918         $ver{bitchx}{$nick}     = $ver;
919     } elsif ($ver =~ /xc\!|xchat/i) {
920         $ver{xchat}{$nick}      = $ver;
921     } elsif ($ver =~ /irssi/i) {
922         $ver{irssi}{$nick}      = $ver;
923     } elsif ($ver =~ /epic/i) {
924         $ver{epic}{$nick}       = $ver;
925     } elsif ($ver =~ /mirc/i) {
926         $ver{mirc}{$nick}       = $ver;
927     } elsif ($ver =~ /ircle/i) {
928         $ver{ircle}{$nick}      = $ver;
929     } elsif ($ver =~ /ircII/i) {
930         $ver{ircII}{$nick}      = $ver;
931     } elsif ($ver =~ /sirc /i) {
932         $ver{sirc}{$nick}       = $ver;
933     } elsif ($ver =~ /kvirc/i) {
934         $ver{kvirc}{$nick}      = $ver;
935     } elsif ($ver =~ /eggdrop/i) {
936         $ver{eggdrop}{$nick}    = $ver;
937     } elsif ($ver =~ /xircon/i) {
938         $ver{xircon}{$nick}     = $ver;
939     } else {
940         $ver{other}{$nick}      = $ver;
941     }
942 }
943
944 sub on_version {
945     my ($self, $event) = @_;
946     my $nick = $event->nick;
947
948     &status(">>> ${b_green}CTCP VERSION$ob request from $b_cyan$nick$ob");
949     $self->ctcp_reply($nick, "VERSION $bot_version");
950 }
951
952 sub on_who {
953     my ($self, $event) = @_;
954     my @args    = $event->args;
955
956     $nuh{lc $args[5]} = $args[5]."!".$args[2]."\@".$args[3];
957 }
958
959 sub on_whoisuser {
960     my ($self, $event) = @_;
961     my @args    = $event->args;
962
963     &DEBUG("on_whoisuser: @args");
964
965     $nuh{lc $args[1]} = $args[1]."!".$args[2]."\@".$args[3];
966 }
967
968 #######################################################################
969 ####### IRC HOOK HELPERS   IRC HOOK HELPERS   IRC HOOK HELPERS ########
970 #######################################################################
971
972 #####
973 # Usage: &hookMode($chan, $modes, @targets);
974 sub hookMode {
975     my ($chan, $modes, @targets) = @_;
976     my $parity  = 0;
977
978     $chan = lc $chan;           # !!!.
979
980     my $mode;
981     foreach $mode (split(//, $modes)) {
982         # sign.
983         if ($mode =~ /[-+]/) {
984             $parity = 1         if ($mode eq "+");
985             $parity = 0         if ($mode eq "-");
986             next;
987         }
988
989         # mode with target.
990         if ($mode =~ /[bklov]/) {
991             my $target = shift @targets;
992
993             if ($parity) {
994                 $chanstats{$chan}{'Op'}++    if ($mode eq "o");
995                 $chanstats{$chan}{'Ban'}++   if ($mode eq "b");
996             } else {
997                 $chanstats{$chan}{'Deop'}++  if ($mode eq "o");
998                 $chanstats{$chan}{'Unban'}++ if ($mode eq "b");
999             }
1000
1001             # modes w/ target affecting nick => cache it.
1002             if ($mode =~ /[bov]/) {
1003                 $channels{$chan}{$mode}{$target}++      if  $parity;
1004                 delete $channels{$chan}{$mode}{$target} if !$parity;
1005             }
1006
1007             if ($mode =~ /[l]/) {
1008                 $channels{$chan}{$mode} = $target       if  $parity;
1009                 delete $channels{$chan}{$mode}          if !$parity;
1010             }
1011         }
1012
1013         # important channel modes, targetless.
1014         if ($mode =~ /[mt]/) {
1015             $channels{$chan}{$mode}++                   if  $parity;
1016             delete $channels{$chan}{$mode}              if !$parity;
1017         }
1018     }
1019 }
1020
1021 sub hookMsg {
1022     ($msgType, $chan, $who, $message) = @_;
1023     my $skipmessage     = 0;
1024     $addressed          = 0;
1025     $addressedother     = 0;
1026     $orig{message}      = $message;
1027     $orig{who}          = $who;
1028     $addrchar           = 0;
1029
1030     $message    =~ s/[\cA-\c_]//ig;     # strip control characters
1031     $message    =~ s/^\s+//;            # initial whitespaces.
1032     $who        =~ tr/A-Z/a-z/;         # lowercase.
1033
1034     &showProc();
1035
1036     # addressing.
1037     if ($msgType =~ /private/) {
1038         # private messages.
1039         $addressed = 1;
1040     } else {
1041         # public messages.
1042         # addressing revamped by the xk.
1043         ### below needs to be fixed...
1044         if (&IsParam("addressCharacter")) {
1045             if ($message =~ s/^$param{'addressCharacter'}//) {
1046                 $addrchar  = 1;
1047                 $addressed = 1;
1048             }
1049         }
1050
1051         if ($message =~ /^($mask{nick})([\;\:\>\, ]+) */) {
1052             my $newmessage = $';
1053             if ($1 =~ /^\Q$ident\E$/i) {
1054                 $message   = $newmessage;
1055                 $addressed = 1;
1056             } else {
1057                 # ignore messages addressed to other people or unaddressed.
1058                 $skipmessage++ if ($2 ne "" and $2 !~ /^ /);
1059             }
1060         }
1061     }
1062
1063     # Determine floodwho.
1064     my $c       = "_default";
1065     if ($msgType =~ /public/i) {                # public.
1066         $floodwho = $c = lc $chan;
1067     } elsif ($msgType =~ /private/i) {  # private.
1068         $floodwho = lc $who;
1069     } else {                            # dcc?
1070         &DEBUG("FIXME: floodwho = ???");
1071     }
1072
1073     my $val = &getChanConfDefault("floodRepeat", "2:10", $c);
1074     my ($count, $interval) = split /:/, $val;
1075
1076     # flood repeat protection.
1077     if ($addressed) {
1078         my $time = $flood{$floodwho}{$message} || 0;
1079
1080         if ($msgType eq "public" and (time() - $time < $interval)) {
1081             ### public != personal who so the below is kind of pointless.
1082             my @who;
1083             foreach (keys %flood) {
1084                 next if (/^\Q$floodwho\E$/);
1085                 next if (defined $chan and /^\Q$chan\E$/);
1086
1087                 push(@who, grep /^\Q$message\E$/i, keys %{ $flood{$_} });
1088             }
1089
1090             return if ($lobotomized);
1091
1092             if (scalar @who) {
1093                 &msg($who, "you already said what ".
1094                                 join(' ', @who)." have said.");
1095             } else {
1096                 &msg($who,"Someone already said that ". (time - $time) ." seconds ago" );
1097             }
1098
1099             ### TODO: delete old floodwarn{} keys.
1100             my $floodwarn = 0;
1101             if (!exists $floodwarn{$floodwho}) {
1102                 $floodwarn++;
1103             } else {
1104                 $floodwarn++ if (time() - $floodwarn{$floodwho} > $interval);
1105             }
1106
1107             if ($floodwarn) {
1108                 &status("FLOOD repetition detected from $floodwho.");
1109                 $floodwarn{$floodwho} = time();
1110             }
1111
1112             return;
1113         }
1114
1115         if ($addrchar) {
1116             &status("$b_cyan$who$ob is short-addressing me");
1117         } elsif ($msgType eq "private") {       # private.
1118             &status("$b_cyan$who$ob is /msg'ing me");
1119         } else {                                # public?
1120             &status("$b_cyan$who$ob is addressing me");
1121         }
1122
1123         $flood{$floodwho}{$message} = time();
1124     } elsif ($msgType eq "public" and &IsChanConf("kickOnRepeat")) {
1125         # unaddressed, public only.
1126
1127         ### TODO: use a separate "short-time" hash.
1128         my @data;
1129         @data   = keys %{ $flood{$floodwho} } if (exists $flood{$floodwho});
1130     }
1131
1132     $val = &getChanConfDefault("floodMessages", "5:30", $c);
1133     ($count, $interval) = split /:/, $val;
1134
1135     # flood overflow protection.
1136     if ($addressed) {
1137         foreach (keys %{$flood{$floodwho}}) {
1138             next unless (time() - $flood{$floodwho}{$_} > $interval);
1139             delete $flood{$floodwho}{$_};
1140         }
1141
1142         my $i = scalar keys %{$flood{$floodwho}};
1143         if ($i > $count) {
1144             &msg($who,"overflow of messages ($i > $count)");
1145             &status("FLOOD overflow detected from $floodwho; ignoring");
1146
1147             my $expire = $param{'ignoreAutoExpire'} || 5;
1148             &ignoreAdd("*!$uh", $chan, $expire, "flood overflow auto-detected.");
1149             return;
1150         }
1151
1152         $flood{$floodwho}{$message} = time();
1153     }
1154
1155     my @ignore;
1156     if ($msgType =~ /public/i) {                    # public.
1157         $talkchannel    = $chan;
1158         &status("<$orig{who}/$chan> $orig{message}");
1159         push(@ignore, keys %{ $ignore{$chan} }) if (exists $ignore{$chan});
1160     } elsif ($msgType =~ /private/i) {             # private.
1161         &status("[$orig{who}] $orig{message}");
1162         $talkchannel    = undef;
1163         $chan           = "_default";
1164     } else {
1165         &DEBUG("unknown msgType => $msgType.");
1166     }
1167     push(@ignore, keys %{ $ignore{"*"} }) if (exists $ignore{"*"});
1168
1169     if ((!$skipmessage or &IsChanConf("seenStoreAll")) and
1170         &IsChanConf("seen") and
1171         $msgType =~ /public/
1172     ) {
1173         $seencache{$who}{'time'} = time();
1174         $seencache{$who}{'nick'} = $orig{who};
1175         $seencache{$who}{'host'} = $uh;
1176         $seencache{$who}{'chan'} = $talkchannel;
1177         $seencache{$who}{'msg'}  = $orig{message};
1178         $seencache{$who}{'msgcount'}++;
1179     }
1180
1181     return if ($skipmessage);
1182     return unless (&IsParam("minVolunteerLength") or $addressed);
1183
1184     foreach (@ignore) {
1185         s/\*/\\S*/g;
1186
1187         next unless (eval { $nuh =~ /^$_$/i });
1188
1189         &status("IGNORE <$who> $message");
1190         return;
1191     }
1192
1193     if (defined $nuh) {
1194         if (!defined $userHandle) {
1195             &DEBUG("line 1074: need verifyUser?");
1196             &verifyUser($who, $nuh);
1197         }
1198     } else {
1199         &DEBUG("hookMsg: 'nuh' not defined?");
1200     }
1201
1202 ### For extra debugging purposes...
1203     if ($_ = &process()) {
1204 #       &DEBUG("IrcHooks: process returned '$_'.");
1205     }
1206
1207     return;
1208 }
1209
1210 sub chanLimitVerify {
1211     my($chan)   = @_;
1212     my $l       = $channels{$chan}{'l'};
1213
1214     # only change it if it's not set.
1215     if (defined $l and &IsChanConf("chanlimitcheck")) {
1216         my $plus = &getChanConfDefault("chanlimitcheckPlus", 5, $chan);
1217         my $nowl = scalar(keys %{ $channels{$chan}{''} });
1218         my $delta       = $nowl - $l;
1219         $delta          =~ s/^\-//;
1220
1221         if ($plus <= 3) {
1222             &WARN("clc: stupid to have plus at $plus, fix it!");
1223         }
1224
1225         ### todo: check if we have ops.
1226         ### todo: if not, check if nickserv/chanserv is avail.
1227         ### todo: unify code with chanlimitcheck()
1228         if ($delta > 5) {
1229             &status("clc: big change in limit; changing.");
1230             &rawout("MODE $chan +l ".($nowl+$plus) );
1231         }
1232     }
1233 }
1234
1235 1;