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