]> git.donarmstrong.com Git - infobot.git/blob - src/Misc.pl
- userAdd, if no mask is given, don't add it.
[infobot.git] / src / Misc.pl
1 #
2 #   Misc.pl: Miscellaneous stuff.
3 #    Author: dms
4 #   Version: 20000124
5 #      NOTE: Based on code by Kevin Lenzo & Patrick Cole  (c) 1997
6 #
7
8 if (&IsParam("useStrict")) { use strict; }
9
10 sub help {
11     my $topic = shift;
12     my $file  = $bot_misc_dir."/blootbot.help";
13     my %help  = ();
14
15     # crude hack for pSReply() to work as expected.
16     $msgType = "private" if ($msgType eq "public");
17
18     if (!open(FILE, $file)) {
19         &ERROR("FAILED loadHelp ($file): $!");
20         return;
21     }
22
23     while (defined(my $help = <FILE>)) {
24         $help =~ s/^[\# ].*//;
25         chomp $help;
26         next unless $help;
27         my ($key, $val) = split(/:/, $help, 2);
28
29         $val =~ s/^\s+//;
30         $val =~ s/^D:/\002   Desc\002:/;
31         $val =~ s/^E:/\002Example\002:/;
32         $val =~ s/^N:/\002   NOTE\002:/;
33         $val =~ s/^U:/\002  Usage\002:/;
34         $val =~ s/##/$key/;
35         $val =~ s/__/\037/g;
36         $val =~ s/==/        /;
37
38         $help{$key}  = ""                if (!exists $help{$key});
39         $help{$key} .= $val."\n";
40     }
41     close FILE;
42
43     if (!defined $topic or $topic eq "") {
44         &msg($who, $help{'main'});
45
46         my $i = 0;
47         my @array;
48         my $count = scalar(keys %help);
49         my $reply;
50         foreach (sort keys %help) {
51             push(@array,$_);
52             $reply = scalar(@array) ." topics: ".
53                         join("\002,\002 ", @array);
54             $i++;
55
56             if (length $reply > 400 or $count == $i) {
57                 &msg($who,$reply);
58                 undef @array;
59             }
60         }
61
62         return '';
63     }
64
65     $topic = &fixString(lc $topic);
66
67     if (exists $help{$topic}) {
68         foreach (split /\n/, $help{$topic}) {
69             &performStrictReply($_);
70         }
71     } else {
72         &pSReply("no help on $topic.  Use 'help' without arguments.");
73     }
74
75     return '';
76 }
77
78 sub getPath {
79     my ($pathnfile) = @_;
80
81     ### TODO: gotta hate an if statement.
82     if ($pathnfile =~ /(.*)\/(.*?)$/) {
83         return $1;
84     } else {
85         return ".";
86     }
87 }
88
89 sub timeget {
90     if ($no_timehires) {        # fallback.
91         return time();
92     } else {                    # the real thing.
93         return [gettimeofday()];
94     }
95 }    
96
97 sub timedelta {
98     my($start_time) = shift;
99
100     if ($no_timehires) {        # fallback.
101         return time() - $start_time;
102     } else {                    # the real thing.
103         return tv_interval ($start_time);
104     }
105 }
106
107 ###
108 ### FORM Functions.
109 ###
110
111 ###
112 # Usage; &formListReply($rand, $prefix, @list);
113 sub formListReply {
114     my($rand, $prefix, @list) = @_;
115     my $total   = scalar @list;
116     my $maxshow = $param{'maxListReplyCount'}  || 10;
117     my $maxlen  = $param{'maxListReplyLength'} || 400;
118     my $reply;
119
120     # no results.
121     return $prefix ."returned no results." unless ($total);
122
123     # random.
124     if ($rand) {
125         my @rand;
126         foreach (&makeRandom($total)) {
127             push(@rand, $list[$_]);
128             last if (scalar @rand == $maxshow);
129         }
130         @list = @rand;
131     } elsif ($total > $maxshow) {
132         &status("formListReply: truncating list.");
133
134         @list = @list[0..$maxshow-1];
135     }
136
137     # form the reply.
138     while () {
139         $reply  = $prefix ."(\002". scalar(@list). "\002 shown";
140         $reply .= "; \002$total\002 total" if ($total != scalar @list);
141         $reply .= "): ". join(" \002;;\002 ",@list) .".";
142
143         last if (length($reply) < $maxlen and scalar(@list) <= $maxshow);
144         last if (scalar(@list) == 1);
145
146         pop @list;
147     }
148
149     return $reply;
150 }
151
152 ### Intelligence joining of arrays.
153 # Usage: &IJoin(@array);
154 sub IJoin {
155     if (!scalar @_) {
156         return "NULL";
157     } elsif (scalar @_ == 1) {
158         return $_[0];
159     } else {
160         return join(', ',@{_}[0..$#_-1]) . " and $_[$#_]";
161     }
162 }
163
164 #####
165 # Usage: &Time2String(seconds);
166 sub Time2String {
167     my $time = shift;
168     my $retval;
169
170     return("NULL s") if (!defined $time or $time !~ /\d+/);
171
172     my $prefix = "";
173     if ($time < 0) {
174         $time   = - $time;
175         $prefix = "- ";
176     }
177
178     my $s = int($time) % 60;
179     my $m = int($time / 60) % 60;
180     my $h = int($time / 3600) % 24;
181     my $d = int($time / 86400);
182
183     my @data;
184     push(@data, sprintf("\002%d\002d", $d)) if ($d != 0);
185     push(@data, sprintf("\002%d\002h", $h)) if ($h != 0);
186     push(@data, sprintf("\002%d\002m", $m)) if ($m != 0);
187     push(@data, sprintf("\002%d\002s", $s)) if ($s != 0 or !@data);
188
189     return $prefix.join(' ', @data);
190 }
191
192 ###
193 ### FIX Functions.
194 ###
195
196 # Usage: &fixFileList(@files);
197 sub fixFileList {
198     my @files = @_;
199     my %files;
200
201     # generate a hash list.
202     foreach (@files) {
203         if (/^(.*\/)(.*?)$/) {
204             $files{$1}{$2} = 1;
205         }
206     }
207     @files = ();        # reuse the array.
208
209     # sort the hash list appropriately.
210     foreach (sort keys %files) {
211         my $file = $_;
212         my @keys = sort keys %{ $files{$file} };
213         my $i    = scalar(@keys);
214
215         if ($i > 1) {
216             $file .= "\002{\002". join("\002|\002", @keys) ."\002}\002";
217         } else {
218             $file .= $keys[0];
219         }
220
221         push(@files,$file);
222     }
223
224     return @files;
225 }
226
227 # Usage: &fixString($str);
228 sub fixString {
229     my ($str, $level) = @_;
230     if (!defined $str) {
231         &WARN("fixString: str == NULL.");
232         return '';
233     }
234
235     for ($str) {
236         s/^\s+//;               # remove start whitespaces.
237         s/\s+$//;               # remove end whitespaces.
238         s/\s+/ /g;              # remove excessive whitespaces.
239
240         next unless (defined $level);
241         if (s/[\cA-\c_]//ig) {          # remove control characters.
242             &DEBUG("stripped control chars");
243         }
244     }
245
246     return $str;
247 }
248
249 # Usage: &fixPlural($str,$int);
250 sub fixPlural {
251     my ($str,$int) = @_;
252
253     if (!defined $str) {
254         &WARN("fixPlural: str == NULL.");
255         return;
256     }
257
258     if (!defined $int or $int =~ /^\D+$/) {
259         &WARN("fixPlural: int != defined or int");
260         return $str;
261     }
262
263     if ($str eq "has") {
264         $str = "have"   if ($int > 1);
265     } elsif ($str eq "is") {
266         $str = "are"    if ($int > 1);
267     } elsif ($str eq "was") {
268         $str = "were"   if ($int > 1);
269     } elsif ($str eq "this") {
270         $str = "these"  if ($int > 1);
271     } elsif ($str =~ /y$/) {
272         if ($int > 1) {
273             if ($str =~ /ey$/) {
274                 $str .= "s";    # eg: "money" => "moneys".
275             } else {
276                 $str =~ s/y$/ies/;
277             }
278         }
279     } else {
280         $str .= "s"     if ($int != 1);
281     }
282
283     return $str;
284 }
285
286
287
288 ##########
289 ### get commands.
290 ###
291
292 sub getRandomLineFromFile {
293     my($file) = @_;
294
295     if (! -f $file) {
296         &WARN("gRLfF: file '$file' does not exist.");
297         return;
298     }
299
300     if (open(IN,$file)) {
301         my @lines = <IN>;
302
303         if (!scalar @lines) {
304             &ERROR("GRLF: nothing loaded?");
305             return;
306         }
307
308         while (my $line = &getRandom(@lines)) {
309             chop $line;
310
311             next if ($line =~ /^\#/);
312             next if ($line =~ /^\s*$/);
313
314             return $line;
315         }
316     } else {
317         &WARN("gRLfF: could not open file '$file'.");
318         return;
319     }
320 }
321
322 sub getLineFromFile {
323     my($file,$lineno) = @_;
324
325     if (! -f $file) {
326         &ERROR("getLineFromFile: file '$file' does not exist.");
327         return 0;
328     }
329
330     if (open(IN,$file)) {
331         my @lines = <IN>;
332         close IN;
333
334         if ($lineno > scalar @lines) {
335             &ERROR("getLineFromFile: lineno exceeds line count from file.");
336             return 0;
337         }
338
339         my $line = $lines[$lineno-1];
340         chop $line;
341         return $line;
342     } else {
343         &ERROR("getLineFromFile: could not open file '$file'.");
344         return 0;
345     }
346 }
347
348 # Usage: &getRandom(@array);
349 sub getRandom {
350     my @array = @_;
351
352     srand();
353     return $array[int(rand(scalar @array))];
354 }
355
356 # Usage: &getRandomInt("30-60");
357 sub getRandomInt {
358     my $str = $_[0];
359
360     if (!defined $str) {
361         &WARN("gRI: str == NULL.");
362         return;
363     }
364
365     srand();
366
367     if ($str =~ /^(\d+(\.\d+)?)$/) {
368         my $i = $1;
369         my $fuzzy = int(rand 5);
370         if ($i < 10) {
371             return $i*60;
372         }
373         if (rand > 0.5) {
374             return ($i - $fuzzy)*60;
375         } else {
376             return ($i + $fuzzy)*60;
377         }
378     } elsif ($str =~ /^(\d+)-(\d+)$/) {
379         return ($2 - $1)*int(rand $1)*60;
380     } else {
381         return $str;    # hope we're safe.
382     }
383
384     &ERROR("getRandomInt: invalid arg '$str'.");
385     return 1800;
386 }
387
388 ##########
389 ### Is commands.
390 ###
391
392 sub iseq {
393     my ($left,$right) = @_;
394     return 0 unless defined $right;
395     return 0 unless defined $left;
396     return 1 if ($left =~ /^\Q$right$/i);
397 }
398
399 sub isne {
400     my $retval = &iseq(@_);
401     return 1 unless ($retval);
402     return 0;
403 }
404
405 # Usage: &IsHostMatch($nuh);
406 sub IsHostMatch {
407     my ($thisnuh) = @_;
408     my (%this,%local);
409
410     if ($nuh =~ /^(\S+)!(\S+)@(\S+)/) {
411         $local{'nick'} = lc $1;
412         $local{'user'} = lc $2;
413         $local{'host'} = &makeHostMask(lc $3);
414     }
415
416     if ($thisnuh =~ /^(\S+)!(\S+)@(\S+)/) {
417         $this{'nick'} = lc $1;
418         $this{'user'} = lc $2;
419         $this{'host'} = &makeHostMask(lc $3);
420     } else {
421         &WARN("IHM: thisnuh is invalid '$thisnuh'.");
422         return 1 if ($thisnuh eq "");
423         return 0;
424     }
425
426     # auth if 1) user and host match 2) user and nick match.
427     # this may change in the future.
428
429     if ($this{'user'} =~ /^\Q$local{'user'}\E$/i) {
430         return 2 if ($this{'host'} eq $local{'host'});
431         return 1 if ($this{'nick'} eq $local{'nick'});
432     }
433     return 0;
434 }
435
436 ####
437 # Usage: &isStale($file, $age);
438 sub isStale {
439     my ($file, $age) = @_;
440
441     if (!defined $age) {
442         &WARN("isStale: age == NULL.");
443         return 1;
444     }
445
446     if (!defined $file) {
447         &WARN("isStale: file == NULL.");
448         return 1;
449     }
450
451     &DEBUG("!exist $file") if (! -f $file);
452
453     return 1 unless ( -f $file);
454     if ($file =~ /idx/) {
455         my $age2 = time() - (stat($file))[9];
456         &DEBUG("stale: $age2. (". &Time2String($age2) .")");
457     }
458     $age *= 60*60*24 if ($age >= 0 and $age < 30);
459
460     return 1 if (time() - (stat($file))[9] > $age);
461     return 0;
462 }
463
464 ##########
465 ### make commands.
466 ###
467
468 # Usage: &makeHostMask($host);
469 sub makeHostMask {
470     my ($host)  = @_;
471     my $nu      = "";
472
473     if ($host =~ s/^(\S+!\S+\@)//) {
474         &DEBUG("mHM: detected nick!user\@ for host arg; fixing");
475         $nu = $1;
476     }
477
478     if ($host =~ /^$mask{ip}$/) {
479         return $nu."$1.$2.$3.*";
480     }
481
482     my @array = split(/\./, $host);
483     return $nu.$host if (scalar @array <= 3);
484     return $nu."*.".join('.',@{array}[1..$#array]);
485 }
486
487 # Usage: &makeRandom(int);
488 sub makeRandom {
489     my ($max) = @_;
490     my @retval;
491     my %done;
492
493     if ($max =~ /^\D+$/) {
494         &ERROR("makeRandom: arg ($max) is not integer.");
495         return 0;
496     }
497
498     if ($max < 1) {
499         &ERROR("makeRandom: arg ($max) is not positive.");
500         return 0;
501     }
502
503     srand();
504     while (scalar keys %done < $max) {
505         my $rand = int(rand $max);
506         next if (exists $done{$rand});
507
508         push(@retval,$rand);
509         $done{$rand} = 1;
510     }
511
512     return @retval;
513 }
514
515 sub checkMsgType {
516     my ($reply) = @_;
517     return unless (&IsParam("minLengthBeforePrivate"));
518     return if ($force_public_reply);
519
520     if (length $reply > $param{'minLengthBeforePrivate'}) {
521         &status("Reply: len reply > minLBP ($param{'minLengthBeforePrivate'}); msgType now private.");
522         $msgType = 'private';
523     }
524 }
525
526 ###
527 ### Valid.
528 ###
529
530 # Usage: &validExec($string);
531 sub validExec {
532     my ($str) = @_;
533
534     if ($str =~ /[\'\"\|]/) {   # invalid.
535         return 0;
536     } else {                    # valid.
537         return 1;
538     }
539 }
540
541 # Usage: &validFactoid($lhs,$rhs);
542 sub validFactoid {
543     my ($lhs,$rhs) = @_;
544     my $valid = 0;
545
546     for (lc $lhs) {
547         # allow the following only if they have been made on purpose.
548         if ($rhs ne "" and $rhs !~ /^</) {
549             / \Q$ident$/i and last;     # someone said i'm something.
550             /^i('m)? / and last;
551             /^(it|that|there|what)('s)?(\s+|$)/ and last;
552             /^you('re)?(\s+|$)/ and last;
553
554             /^(where|who|why|when|how)(\s+|$)/ and last;
555             /^(this|that|these|those|they)(\s+|$)/ and last;
556             /^(every(one|body)|we) / and last;
557
558             /^say / and last;
559         }
560
561         # uncaught commands.
562         /^add topic / and last;         # topic management.
563         /( add$| add |^add )/ and last; # borked teach statement.
564         /^learn / and last;             # teach. damn morons.
565         /^tell (\S+) about / and last;  # tell.
566         /\=\~/ and last;                # substituition.
567         /^\S+ to \S+ \S+/ and last;     # babelfish.
568
569         /^\=/ and last;                 # botnick = heh is.
570         /wants you to know/ and last;
571
572         # symbols.
573         /(\"\*)/ and last;
574         /, / and last;
575         /^\'/ and last;
576
577         # delimiters.
578         /\=\>/ and last;                # '=>'.
579         /\;\;/ and last;                # ';;'.
580         /\|\|/ and last;                # '||'.
581
582         /^\Q$ident\E[\'\,\: ]/ and last;# dupe addressed.
583         /^[\-\, ]/ and last;
584         /\\$/ and last;                 # forgot shift for '?'.
585         /^all / and last;
586         /^also / and last;
587         / also$/ and last;
588         / and$/ and last;
589         /^because / and last;
590         /^gives / and last;
591         /^h(is|er) / and last;
592         /^if / and last;
593         / is,/ and last;
594         / it$/ and last;
595         / says$/ and last;
596         /^should / and last;
597         /^so / and last;
598         /^supposedly/ and last;
599         /^to / and last;
600         /^was / and last;
601         / which$/ and last;
602
603         # nasty bug I introduced _somehow_, probably by fixMySQLBug().
604         /\\\%/ and last;
605         /\\\_/ and last;
606
607         # weird/special stuff. also old blootbot or stock infobot bugs.
608         $rhs =~ /( \Q$ident\E's|\Q$ident\E's )/i and last; # ownership.
609
610         # duplication.
611         $rhs =~ /^\Q$lhs /i and last;
612         last if ($rhs =~ /^is /i and / is$/);
613
614         $valid++;
615     }
616
617     return $valid;
618 }
619
620 # Usage: &hasProfanity($string);
621 sub hasProfanity {
622     my ($string) = @_;
623     my $profanity = 1;
624
625     for (lc $string) {
626         /fuck/ and last;
627         /dick|dildo/ and last;
628         /shit|turd|crap/ and last;
629         /pussy|[ck]unt/ and last;
630         /wh[0o]re|bitch|slut/ and last;
631
632         $profanity = 0;
633     }
634
635     return $profanity;
636 }
637
638 sub hasParam {
639     my ($param) = @_;
640
641     if (&IsChanConf($param) or &IsParam($param)) {
642         return 1;
643     } else {
644         ### TODO: specific reason why it failed.
645         &msg($who, "unfortunately, \002$param\002 is disabled in my configuration") unless ($addrchar);
646         return 0;
647     }
648 }
649
650 sub Forker {
651     my ($label, $code) = @_;
652     my $pid;
653
654     &shmFlush();
655     &VERB("double fork detected; not forking.",2) if ($$ != $bot_pid);
656
657     if (&IsParam("forking") and $$ == $bot_pid) {
658         return unless &addForked($label);
659
660         $SIG{CHLD} = 'IGNORE';
661         $pid = eval { fork() };
662         return if $pid;         # parent does nothing
663
664         select(undef, undef, undef, 0.2);
665 #       &status("fork starting for '$label', PID == $$.");
666         &status("--- fork starting for '$label', PID == $$ ---");
667         &shmWrite($shm,"SET FORKPID $label $$");
668
669         sleep 1;
670     }
671
672     ### TODO: use AUTOLOAD
673     ### very lame hack.
674     if ($label !~ /-/ and !&loadMyModule($myModules{$label})) {
675         &DEBUG("Forker: failed?");
676         &delForked($label);
677     }
678
679     if (defined $code) {
680         $code->();                      # weird, hey?
681     } else {
682         &WARN("Forker: code not defined!");
683     }
684
685     &delForked($label);
686 }
687
688 sub closePID {
689     return 1 unless (exists $file{PID});
690     return 1 unless ( -f $file{PID});
691     return 1 if (unlink $file{PID});
692     return 0 if ( -f $file{PID});
693 }
694
695 sub mkcrypt {
696     my($str) = @_;
697     my $salt = join '',('.','/',0..9,'A'..'Z','a'..'z')[rand 64, rand 64];
698
699     return crypt($str, $salt);
700 }
701
702 1;