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