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