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