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