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