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