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