]> git.donarmstrong.com Git - infobot.git/blob - src/Modules/News.pl
- added support/hack for channel +o as "+o" in bot user file.
[infobot.git] / src / Modules / News.pl
1 #
2 # News.pl: Advanced news management
3 #   Author: dms
4 #  Version: v0.3 (20010412)
5 #  Created: 20010326
6 #    Notes: Testing done by greycat, kudos!
7 #
8 ### structure:
9 # news{ channel }{ string } { item }
10 # newsuser{ channel }{ user } = time()
11 ### where item is:
12 #       Time    - when it was added (used for sorting)
13 #       Author  - Who by.
14 #       Expire  - Time to expire.
15 #       Text    - Actual text.
16 ###
17
18 use vars qw($who $chan);
19
20 package News;
21
22 sub Parse {
23     my($what)   = @_;
24     $chan       = undef;
25     $who        = lc $::who;
26
27     if (!keys %::news) {
28         if (!exists $::cache{newsFirst}) {
29             &::DEBUG("news: looks like we enabled news option just then; loading up news file just in case.");
30             $::cache{newsFirst} = 1;
31         }
32
33         &readNews();
34     }
35
36     if ($::msgType ne "private") {
37         $chan = $::chan;
38     }
39
40     if (defined $what and $what =~ s/^($::mask{chan})\s*//) {
41         # todo: check if the channel exists aswell.
42         $chan   = lc $1;
43
44         if (!&::IsNickInChan($who, $chan)) {
45             &::notice($who, "sorry but you're not on $chan.");
46             return;
47         }
48     }
49
50     if (!defined $chan) {
51         my @chans = &::getNickInChans($who);
52
53         if (scalar @chans > 1) {
54             &::notice($who, "error: I dunno which channel you are referring to since you're on more than one. Try 'news #chan ...' instead");
55             return;
56         }
57
58         if (scalar @chans == 0) {
59             &::notice($who, "error: I couldn't find you on any chan. This must be a bug!");
60             return;
61         }
62
63         $chan   = $chans[0];
64         &::VERB("Guessed $who being on chan $chan",2);
65         $::chan = $chan;        # hack for IsChanConf().
66     }
67
68     if (!defined $what or $what =~ /^\s*$/) {
69         &list();
70         return;
71     }
72
73     if ($what =~ /^add(\s+(.*))?$/i) {
74         &add($2);
75
76     } elsif ($what =~ /^del(\s+(.*))?$/i) {
77         &del($2);
78
79     } elsif ($what =~ /^mod(\s+(.*))?$/i) {
80         &mod($2);
81
82     } elsif ($what =~ /^set(\s+(.*))?$/i) {
83         &set($2);
84
85     } elsif ($what =~ /^(\d+)$/i) {
86         &::VERB("News: read shortcut called.",2);
87         &read($1);
88
89     } elsif ($what =~ /^read(\s+(.*))?$/i) {
90         &read($2);
91
92     } elsif ($what =~ /^(latest|new)(\s+(.*))?$/i) {
93         &latest($3 || $chan, 1);
94 #       $::cmdstats{'News latest'}++;
95
96     } elsif ($what =~ /^stats?$/i) {
97         &stats();
98
99     } elsif ($what =~ /^list$/i) {
100         &list();
101
102     } elsif ($what =~ /^(expire|text|desc)(\s+(.*))?$/i) {
103         # shortcut/link.
104         # nice hack.
105         my $cmd = $1;
106         my($arg1,$arg2) = split(/\s+/, $3, 2);
107         &set("$arg1 $cmd $arg2");
108
109     } elsif ($what =~ /^help(\s+(.*))?$/i) {
110         &::help("news $2");
111
112     } elsif ($what =~ /^newsflush$/i) {
113         &::msg($who, "newsflush called... check out the logs!");
114         &::newsFlush();
115
116     } elsif ($what =~ /^(un)?notify$/i) {
117         my $state = ($1) ? 0 : 1;
118
119         # todo: don't notify even if "news" is called.
120         if (!&::IsChanConf("newsNotifyAll")) {
121             &::DEBUG("news: chan => $chan, ::chan => $::chan.");
122             &::notice($who, "not available for this channel or disabled altogether.");
123             return;
124         }
125
126         my $t = $::newsuser{$chan}{$who};
127         if ($state) {   # state = 1
128             if (defined $t and ($t == 0 or $t == -1)) {
129                 &::notice($who, "enabled notify.");
130                 delete $::newsuser{$chan}{$who};
131                 return;
132             }
133             &::notice($who, "already enabled.");
134
135         } else {                # state = 0
136             my $x = $::newsuser{$chan}{$who};
137             if (defined $x and ($x == 0 or $x == -1)) {
138                 &::notice($who, "notify already disabled");
139                 return;
140             }
141             $::newsuser{$chan}{$who} = -1;
142             &::notice($who, "notify is now disabled.");
143         }
144
145     } else {
146         &::notice($who, "unknown command: $what");
147     }
148 }
149
150 sub readNews {
151     my $file = "$::bot_base_dir/blootbot-news.txt";
152     if (! -f $file or -z $file) {
153         return;
154     }
155
156     if (fileno NEWS) {
157         &::DEBUG("readNews: fileno exists, should never happen.");
158         return;
159     }
160
161     my($item,$chan);
162     my($ci,$cu) = (0,0);
163
164     open(NEWS, $file);
165     while (<NEWS>) {
166         chop;
167
168         # todo: allow commands.
169
170         if (/^[\s\t]+(\S+):[\s\t]+(.*)$/) {
171             if (!defined $item) {
172                 &::DEBUG("news: !defined item, never happen!");
173                 next;
174             }
175
176             $::news{$chan}{$item}{$1} = $2;
177             next;
178         }
179
180         # U <chan> <nick> <time>
181         if (/^U\s+(\S+)\s+(\S+)\s+(\d+)$/) {
182             $::newsuser{$1}{$2} = $3;
183             $cu++;
184             next;
185         }
186
187         if (/^(\S+)[\s\t]+(.*)$/) {
188             $chan = $1;
189             $item = $2;
190             $ci++;
191         }
192     }
193     close NEWS;
194
195     my $cn = scalar(keys %::news);
196     return unless ($ci or $cn or $cu);
197
198     &::status("News: read ".
199         $ci. &::fixPlural(" item", $ci). " for ".
200         $cn. &::fixPlural(" chan", $cn). ", ".
201         $cu. &::fixPlural(" user", $cu), " cache"
202     );
203 }
204
205 sub writeNews {
206     if (!scalar keys %::news and !scalar keys %::newsuser) {
207         &::VERB("wN: nothing to write.",2);
208         return;
209     }
210
211     # should define this at the top of file.
212     my $file = "$::bot_base_dir/blootbot-news.txt";
213
214     if (fileno NEWS) {
215         &::ERROR("News: write: fileno NEWS exists, should never happen.");
216         return;
217     }
218
219     # todo: add commands to output file.
220     my $c = 0;
221     my($cc,$ci,$cu) = (0,0,0);
222
223     open(NEWS, ">$file");
224     foreach $chan (sort keys %::news) {
225         $c = scalar keys %{ $::news{$chan} };
226         next unless ($c);
227         $cc++;
228
229         foreach $item (sort keys %{ $::news{$chan} }) {
230             $c = scalar keys %{ $::news{$chan}{$item} };
231             next unless ($c);
232             $ci++;
233
234             print NEWS "$chan $item\n";
235             foreach $what (sort keys %{ $::news{$chan}{$item} }) {
236                 print NEWS "    $what: $::news{$chan}{$item}{$what}\n";
237             }
238             print NEWS "\n";
239         }
240     }
241
242     # todo: show how many users we wrote down.
243     if (&::getChanConfList("newsKeepRead")) {
244         # old users are removed in newsFlush(), perhaps it should be
245         # done here.
246
247         foreach $chan (sort keys %::newsuser) {
248
249             foreach (sort keys %{ $::newsuser{$chan} }) {
250                 print NEWS "U $chan $_ $::newsuser{$chan}{$_}\n";
251                 $cu++;
252             }
253         }
254     }
255
256     close NEWS;
257
258     &::status("News: Wrote $ci items for $cc chans, $cu user cache.");
259 }
260
261 sub add {
262     my($str) = @_;
263
264     if (!defined $chan or !defined $str or $str =~ /^\s*$/) {
265         &::help("news add");
266         return;
267     }
268
269     if (length $str > 64) {
270         &::notice($who, "That's not really an item (>64chars)");
271         return;
272     }
273
274     if (exists $::news{$chan}{$str}{Time}) {
275         &::notice($who, "'$str' for $chan already exists!");
276         return;
277     }
278
279     $::news{$chan}{$str}{Time}  = time();
280     my $expire = &::getChanConfDefault("newsDefaultExpire",7);
281     $::news{$chan}{$str}{Expire}        = time() + $expire*60*60*24;
282     $::news{$chan}{$str}{Author}        = $::who;       # case!
283
284     my $agestr  = &::Time2String($::news{$chan}{$str}{Expire} - time() );
285     my $item    = &newsS2N($str);
286     &::notice($who, "Added '\037$str\037' at [".localtime(time).
287                 "] by \002$::who\002 for item #\002$item\002.");
288     &::notice($who, "Now do 'news text $item <your_description>'");
289     &::notice($who, "This item will expire at \002".
290         localtime($::news{$chan}{$str}{Expire})."\002 [$agestr from now] "
291     );
292
293     &writeNews();
294 }
295
296 sub del {
297     my($what)   = @_;
298     my $item    = 0;
299
300     if (!defined $what) {
301         &::help("news del");
302         return;
303     }
304
305     if ($what =~ /^\d+$/) {
306         my $count = scalar keys %{ $::news{$chan} };
307         if (!$count) {
308             &::notice($who, "No news for $chan.");
309             return;
310         }
311
312         if ($what > $count or $what < 0) {
313             &::notice($who, "$what is out of range (max $count)");
314             return;
315         }
316
317         $item   = &getNewsItem($what);
318         $what   = $item;                # hack hack hack.
319
320     } else {
321         $_      = &getNewsItem($what);  # hack hack hack.
322         $what   = $_ if (defined $_);
323
324         if (!exists $::news{$chan}{$what}) {
325             my @found;
326             foreach (keys %{ $::news{$chan} }) {
327                 next unless (/\Q$what\E/);
328                 push(@found, $_);
329             }
330
331             if (!scalar @found) {
332                 &::notice($who, "could not find $what.");
333                 return;
334             }
335
336             if (scalar @found > 1) {
337                 &::notice($who, "too many matches for $what.");
338                 return;
339             }
340
341             $what       = $found[0];
342             &::DEBUG("news: del: str: guessed what => $what");
343         }
344     }
345
346     if (exists $::news{$chan}{$what}) {
347         my $auth = 0;
348         $auth++ if ($::who eq $::news{$chan}{$what}{Author});
349         $auth++ if (&::IsFlag("o"));
350
351         if (!$auth) {
352             # todo: show when it'll expire.
353             &::notice($who, "Sorry, you cannot remove items; just let them expire on their own.");
354             return;
355         }
356
357         &::notice($who, "ok, deleted '$what' from \002$chan\002...");
358         delete $::news{$chan}{$what};
359     } else {
360         &::notice($who, "error: not found $what in news for $chan.");
361     }
362 }
363
364 sub list {
365     if (!scalar keys %{ $::news{$chan} }) {
366         &::notice($who, "No News for \002$chan\002.");
367         return;
368     }
369
370     if (&::IsChanConf("newsKeepRead")) {
371         my $x = $::newsuser{$chan}{$who};
372
373         if (defined $x and ($x == 0 or $x == -1)) {
374             &::DEBUG("news: not updating time for $who.");
375         } else {
376             if (!scalar keys %{ $::news{$chan} }) {
377                 &::DEBUG("news: should not add $chan/$who to cache!");
378             }
379
380             $::newsuser{$chan}{$who} = time();
381         }
382     }
383
384     # &notice() breaks OPN :( - using msg() instead!
385     my $count = scalar keys %{ $::news{$chan} };
386     &::msg($who, "|==== News for \002$chan\002: ($count items)");
387     my $newest  = 0;
388     my $expire  = 0;
389     my $eno     = 0;
390     foreach (keys %{ $::news{$chan} }) {
391         my $t   = $::news{$chan}{$_}{Time};
392         my $e   = $::news{$chan}{$_}{Expire};
393         $newest = $t if ($t > $newest);
394         if ($e > 1 and $e < $expire) {
395             $expire     = $e;
396             $eno        = &newsS2N($item);
397         }
398     }
399     my $timestr = &::Time2String(time() - $newest);
400     &::msg($who, "|= Last updated $timestr ago.");
401     &::msg($who, " \037Num\037  \037Item ".(" "x40)." \037");
402
403 #    &::DEBUG("news: list: expire = $expire");
404 #    &::DEBUG("news: list: eno    = $eno");
405
406     my $i = 1;
407     foreach ( &getNewsAll() ) {
408         my $subtopic    = $_;
409         my $setby       = $::news{$chan}{$subtopic}{Author};
410         my $chr         = (exists $::News{$chan}{$subtopic}{Text}) ? "" : "*";
411
412         if (!defined $subtopic) {
413             &::DEBUG("news: warn: subtopic == undef.");
414             next;
415         }
416
417         # todo: show request stats aswell.
418         &::msg($who, sprintf("\002[\002%2d\002]\002%s %s",
419                                 $i, $chr, $subtopic));
420         $i++;
421     }
422
423     my $z = $::newsuser{$who};
424     if (defined $z) {
425         &::DEBUG("cache $who: $z");
426     } else {
427         &::DEBUG("cache: $who doesn't have newscache set.");
428     }
429
430     &::msg($who, "|= End of News.");
431     &::msg($who, "use 'news read <#>' or 'news read <keyword>'");
432 }
433
434 sub read {
435     my($str) = @_;
436
437     if (!defined $chan or !defined $str or $str =~ /^\s*$/) {
438         &::help("news read");
439         return;
440     }
441
442     if (!scalar keys %{ $::news{$chan} }) {
443         &::notice($who, "No News for \002$chan\002.");
444         return;
445     }
446
447     my $item    = &getNewsItem($str);
448     if (!defined $item or !scalar keys %{ $::news{$chan}{$item} }) {
449         # todo: numerical check.
450         if ($str =~ /^(\d+)[-, ](\d+)$/ or
451             $str =~ /^-(\d+)$/ or
452             $str =~ /^(\d+)-$/ or 0
453         ) {
454             &::notice($who, "We don't support multiple requests of news items yet.  Sorry.");
455             return;
456         }
457
458         &::notice($who, "No news item called '$str'");
459         return;
460     }
461
462     if (!exists $::news{$chan}{$item}{Text}) {
463         &::notice($who, "Someone forgot to add info to this news item");
464         return;
465     }
466
467     my $t       = localtime( $::news{$chan}{$item}{Time} );
468     my $a       = $::news{$chan}{$item}{Author};
469     my $text    = $::news{$chan}{$item}{Text};
470     my $num     = &newsS2N($item);
471     my $rwho    = $::news{$chan}{$item}{Request_By} || $::who;
472     my $rcount  = $::news{$chan}{$item}{Request_Count} || 0;
473
474     if (length $text < $::param{maxKeySize}) {
475         &::VERB("NEWS: Possible news->factoid redirection.",2);
476         my $f   = &::getFactoid($text);
477
478         if (defined $f) {
479             &::VERB("NEWS: ok, $text is factoid redirection.",2);
480             $f =~ s/^<REPLY>\s*//i;     # anything else?
481             $text = $f;
482         }
483     }
484
485     $_ = $::news{$chan}{$item}{'Expire'};
486     my $e;
487     if ($_) {
488         $e = sprintf("\037%s\037  [%s from now]",
489                 scalar(localtime($_)),
490                 &::Time2String($_ - time())
491         );
492     }
493
494     &::notice($who, "+- News \002$chan\002 #$num: $item");
495     &::notice($who, "| Added by $a at \037$t\037");
496     &::notice($who, "| Expire: $e") if (defined $e);
497     &::notice($who, $text);
498     &::notice($who, "| Requested \002$rcount\002 times, last by \002$rwho\002") if ($rcount and $rwho);
499
500     $::news{$chan}{$item}{'Request_By'}   = $::who;
501     $::news{$chan}{$item}{'Request_Time'} = time();
502     $::news{$chan}{$item}{'Request_Count'}++;
503 }
504
505 sub mod {
506     my($item, $str) = split /\s+/, $_[0], 2;
507
508     if (!defined $item or $item eq "" or $str =~ /^\s*$/) {
509         &::help("news mod");
510         return;
511     }
512
513     my $news = &getNewsItem($item);
514
515     if (!defined $news) {
516         &::DEBUG("news: error: mod: news == undefined.");
517         return;
518     }
519     my $nnews = $::news{$chan}{$news}{Text};
520     my $mod_news  = $news;
521     my $mod_nnews = $nnews;
522
523     # SAR patch. mu++
524     if ($str =~ m|^\s*s([/,#\|])(.+?)\1(.*?)\1([a-z]*);?\s*$|) {
525         my ($delim, $op, $np, $flags) = ($1,$2,$3,$4);
526
527         if ($flags !~ /^(g)?$/) {
528             &::notice($who, "error: Invalid flags to regex.");
529             return;
530         }
531
532         ### TODO: use m### to make code safe!
533         # todo: make code safer.
534         my $done = 0;
535         # todo: use eval to deal with flags easily.
536         if ($flags eq "") {
537             $done++ if (!$done and $mod_news  =~ s/\Q$op\E/$np/);
538             $done++ if (!$done and $mod_nnews =~ s/\Q$op\E/$np/);
539         } elsif ($flags eq "g") {
540             $done++ if ($mod_news  =~ s/\Q$op\E/$np/g);
541             $done++ if ($mod_nnews =~ s/\Q$op\E/$np/g);
542         }
543
544         if (!$done) {
545             &::notice($who, "warning: regex not found in news.");
546             return;
547         }
548
549         if ($mod_news ne $news) { # news item.
550             if (exists $::news{$chan}{$mod_news}) {
551                 &::notice($who, "item '$mod_news' already exists.");
552                 return;
553             }
554
555             &::notice($who, "Moving item '$news' to '$mod_news' with SAR s/$op/$np/.");
556             foreach (keys %{ $::news{$chan}{$news} }) {
557                 $::news{$chan}{$mod_news}{$_} = $::news{$chan}{$news}{$_};
558                 delete $::news{$chan}{$news}{$_};
559             }
560             # needed?
561             delete $::news{$chan}{$news};
562         }
563
564         if ($mod_nnews ne $nnews) { # news Text/Description.
565             &::notice($who, "Changing text for '$news' SAR s/$op/$np/.");
566             if ($mod_news ne $news) {
567                 $::news{$chan}{$mod_news}{Text} = $mod_nnews;
568             } else {
569                 $::news{$chan}{$news}{Text}     = $mod_nnews;
570             }
571         }
572
573         return;
574     } else {
575         &::notice($who, "error: that regex failed ;(");
576         return;
577     }
578
579     &::notice($who, "error: Invalid regex. Try s/1/2/, s#3#4#...");
580 }
581
582 sub set {
583     my($args) = @_;
584     my($item, $what, $value);
585
586     if (!defined $args) {
587         &::DEBUG("news: set: args == NULL.");
588         return;
589     }
590
591     $item = $1 if ($args =~ s/^(\S+)\s*//);
592     $what = $1 if ($args =~ s/^(\S+)\s*//);
593     $value = $args;
594
595     if ($item eq "") {
596         &::help("news set");
597         return;
598     }
599
600     my $news = &getNewsItem($item);
601
602     if (!defined $news) {
603         &::notice($who, "Could not find item '$item' substring or # in news list.");
604         return;
605     }
606
607     # list all values for chan.
608     if (!defined $what or $what =~ /^\s*$/) {
609         &::msg($who, "set: you didn't fill me on the arguments! (what and values)");
610         return;
611     }
612
613     my $ok = 0;
614     my @elements = ("Expire","Text");
615     foreach (@elements) {
616         next unless ($what =~ /^$_$/i);
617         $what = $_;
618         $ok++;
619         last;
620     }
621
622     if (!$ok) {
623         &::notice($who, "Invalid set.  Try: @elements");
624         return;
625     }
626
627     # show (read) what.
628     if (!defined $value or $value =~ /^\s*$/) {
629         &::msg($who, "set: you didn't fill me on the arguments! (value)");
630         return;
631     }
632
633     if (!exists $::news{$chan}{$news}) {
634         &::notice($who, "news '$news' does not exist");
635         return;
636     }
637
638     if ($what eq "Expire") {
639         # todo: use do_set().
640
641         my $time = 0;
642         my $plus = ($value =~ s/^\+//g);
643         while ($value =~ s/^(\d+)(\S*)\s*//) {
644             my($int,$unit) = ($1,$2);
645             $time += $int       if ($unit =~ /^s(ecs?)?$/i);
646             $time += $int*60    if ($unit =~ /^m(in(utes?)?)?$/i);
647             $time += $int*60*60 if ($unit =~ /^h(ours?)?$/i);
648             $time += $int*60*60*24 if (!$unit or $unit =~ /^d(ays?)?$/i);
649             $time += $int*60*60*24*7 if ($unit =~ /^w(eeks?)?$/i);
650             $time += $int*60*60*24*30 if ($unit =~ /^mon(th)?$/i);
651         }
652
653         if ($value =~ s/^never$//i) {
654             # never.
655             $time = -1;
656         } elsif ($plus) {
657             # from now.
658             $time += time();
659         } else {
660             # from creation of item.
661             $time += $::news{$chan}{$news}{Time};
662         }
663
664         if (!$time or ($value and $value !~ /^never$/i)) {
665             &::DEBUG("news: set: Expire... need to parse.");
666             &::msg($who, "hrm... couldn't parse that.");
667             return;
668         }
669
670         if ($time == -1) {
671             &::notice($who, "Set never expire for \002$item\002." );
672         } elsif ($time < -1) {
673             &::DEBUG("news: time should never be negative ($time).");
674             return;
675         } else {
676             &::notice($who, "Set expire for \002$item\002, to ".
677                 localtime($time) ." [".&::Time2String($time - time())."]" );
678
679             if (time() > $time) {
680                 &::DEBUG("news: hrm... time() > $time, should expire.");
681             }
682         }
683
684
685         $::news{$chan}{$news}{Expire} = $time;
686
687         return;
688     }
689
690     my $auth = 0;
691 #    &::DEBUG("news: who => '$who'");
692     my $author = $::news{$chan}{$news}{Author};
693     $auth++ if ($::who eq $author);
694     $auth++ if (&::IsFlag("o"));
695     if (!defined $author) {
696         &::DEBUG("news: news{$chan}{$news}{Author} is not defined! auth'd anyway");
697         $::news{$chan}{$news}{Author} = $::who;
698         $author = $::who;
699         $auth++;
700     }
701
702     if (!$auth) {
703         # todo: show when it'll expire.
704         &::notice($who, "Sorry, you cannot set items. (author $author owns it)");
705         return;
706     }
707
708     # todo: clean this up.
709     my $old = $::news{$chan}{$news}{$what};
710     if (defined $old) {
711         &::DEBUG("news: old => $old.");
712     }
713     $::news{$chan}{$news}{$what} = $value;
714     &::notice($who, "Setting [$chan]/{$news}/<$what> to '$value'.");
715 }
716
717 sub latest {
718     my($tchan, $flag) = @_;
719
720     # hack hack hack.
721     $chan ||= $tchan;
722     $who    = $::who;
723
724     # todo: if chan = undefined, guess.
725 #    if (!exists $::news{$chan}) {
726     if (!exists $::channels{$chan}) {
727         &::notice($who, "invalid chan $chan") if ($flag);
728         return;
729     }
730
731     my $t = $::newsuser{$chan}{$who};
732 #    if (defined $t) {
733 #       &::DEBUG("newsuser: $chan/$who == $t");
734 #    } else {
735 #       &::DEBUG("newsuser: $chan/$who == undefined");
736 #    }
737
738     if (defined $t and ($t == 0 or $t == -1)) {
739         if ($flag) {
740             &::notice($who, "if you want to read news, try \002/msg $::ident news $chan\002 or \002/msg $::ident news $chan notify\002");
741         } else {
742             &::DEBUG("news: not displaying any new news for $who");
743             return;
744         }
745     }
746
747     $::chan     = $chan;
748     my $x = &::IsChanConf("newsNotifyAll");
749     if (&::IsChanConf("newsNotifyAll") and !defined $t) {
750         $t = 1;
751     }
752
753     if (!defined $t) {
754         &::DEBUG("news: something went really wrong.");
755         &::DEBUG("news: chan => $chan, ::chan => $::chan");
756 #       &::notice($who, "something went really wrong.");
757         return;
758     }
759
760     my @new;
761     foreach (keys %{ $::news{$chan} }) {
762         next if (!defined $t);
763         next if ($t > $::news{$chan}{$_}{Time});
764
765         # don't list new items if they don't have Text.
766         if (!exists $::news{$chan}{$_}{Text}) {
767             if (time() - $::news{$chan}{$_}{Time} > 60*60*24*3) {
768                 &::DEBUG("deleting news{$chan}{$_} because it was too old and had no text info.");
769                 delete $::news{$chan}{$_};
770             }
771
772             next;
773         }
774
775         push(@new, $_);
776     }
777
778     # !scalar @new, $flag
779     if (!scalar @new and $flag) {
780         &::notice($who, "no new news for $chan for $who.");
781         # valid to set this?
782         $::newsuser{$chan}{$who} = time();
783         return;
784     }
785
786     # scalar @new, !$flag
787     my $unread  = scalar @new;
788     my $total   = scalar keys %{ $::news{$chan} };
789     if (!$flag) {
790         return unless ($unread);
791
792         if ($::cache{newsTime} - time() < 5) {
793             &::status("news: not displaying latest notice to $who/$chan.");
794             return;
795         }
796
797         $::cache{newsTime} = time();
798         my $reply = "There are unread news in $chan ($unread unread, $total total). /msg $::ident news $::chan latest";
799         $reply   .= "  If you don't want further news notification, /msg $::ident news unnotify" if ($unread == $total);
800         &::notice($who, $reply);
801
802         return;
803     }
804
805     # scalar @new, $flag
806     if (scalar @new) {
807         &::notice($who, "+==== New news for \002$chan\002 ($unread new; $total total):");
808
809         my $t = $::newsuser{$chan}{$who};
810         if (defined $t and $t > 1) {
811             my $timestr = &::Time2String( time() - $t );
812             &::notice($who, "|= Last time read $timestr ago");
813         }
814
815         my $i;
816         my @sorted;
817         foreach (@new) {
818             $i   = &newsS2N($_);
819             $sorted[$i] = $_;
820         }
821         
822         for ($i=0; $i<=scalar(@sorted); $i++) {
823             my $news = $sorted[$i];
824             next unless (defined $news);
825
826             my $age = time() - $::news{$chan}{$news}{Time};
827             $::conn->schedule(int((2+$i)/2), sub {
828                 &::notice($who, sprintf("\002[\002%2d\002]\002 %s",
829                         $i, $news) );
830 #                       $i, $_, &::Time2String($age) ) );
831             } );
832         }
833
834         # todo: implement throttling via schedule into &notice() / &msg().
835         $::conn->schedule(int((2+$i)/2), sub {
836             &::notice($who, "|= to read, do \002news $chan read <#>\002 or \002news $chan read <keyword>\002");
837         } );
838
839         # lame hack to prevent dupes if we just ignore it.
840         my $x = $::newsuser{$chan}{$who};
841         if (defined $x and ($x == 0 or $x == -1)) {
842             &::DEBUG("news: not updating time for $who. (2)");
843         } else {
844             $::newsuser{$chan}{$who} = time();
845         }
846     }
847 }
848
849 ###
850 ### helpers...
851 ###
852
853 sub getNewsAll {
854     my %time;
855     foreach (keys %{ $::news{$chan} }) {
856         $time{ $::news{$chan}{$_}{Time} } = $_;
857     }
858
859     my @items;
860     foreach (sort { $a <=> $b } keys %time) {
861         push(@items, $time{$_});
862     }
863
864     return @items;
865 }
866
867 sub newsS2N {
868     my($what)   = @_;
869     my $item    = 0;
870     my @items;
871     my $no;
872
873     my %time;
874     foreach (keys %{ $::news{$chan} }) {
875         my $t = $::news{$chan}{$_}{Time};
876
877         if (!defined $t or $t !~ /^\d+$/) {
878             &::DEBUG("news: warn: t is undefined for news{$chan}{$_}{Time}; removing item.");
879             delete $::news{$chan}{$_};
880             next;
881         }
882
883         $time{$t} = $_;
884     }
885
886     foreach (sort { $a <=> $b } keys %time) {
887         $item++;
888         return $item if ($time{$_} eq $what);
889     }
890
891     &::DEBUG("newsS2N($what): failed...");
892 }
893
894 sub getNewsItem {
895     my($what)   = @_;
896     my $item    = 0;
897
898     my %time;
899     foreach (keys %{ $::news{$chan} }) {
900         my $t = $::news{$chan}{$_}{Time};
901
902         if (!defined $t or $t !~ /^\d+$/) {
903             &::DEBUG("news: warn: t is undefined for news{$chan}{$_}{Time}; removing item.");
904             delete $::news{$chan}{$_};
905             next;
906         }
907
908         $time{$t} = $_;
909     }
910
911     # number to string resolution.
912     if ($what =~ /^\d+$/) {
913         foreach (sort { $a <=> $b } keys %time) {
914             $item++;
915             return $time{$_} if ($item == $what);
916         }
917
918     } else {
919         # partial string to full string resolution
920         # in some cases, string->number resolution.
921
922         my @items;
923         my $no;
924         foreach (sort { $a <=> $b } keys %time) {
925             $item++;
926 #           $no = $item if ($time{$_} eq $what);
927 ##          if ($time{$_} eq $what) {
928 ##              $no = $item;
929 ##              next;
930 ##          }
931
932             push(@items, $time{$_}) if ($time{$_} =~ /\Q$what\E/i);
933         }
934
935 ##      if (defined $no and !@items) {
936 ##          &::DEBUG("news: string->number resolution: $what->$no.");
937 ##          return $no;
938 ##      }
939
940         if (scalar @items > 1) {
941             &::DEBUG("news: Multiple matches, not guessing.");
942             &::notice($who, "Multiple matches, not guessing.");
943             return;
944         }
945
946         if (@items) {
947 #           &::DEBUG("news: gNI: part_string->full_string: $what->$items[0]");
948             return $items[0];
949         } else {
950             &::DEBUG("news: gNI: No match for '$what'");
951             return;
952         }
953     }
954
955     &::ERROR("news: gNI: should not happen (what = $what)");
956     return;
957 }
958
959 sub do_set {
960     my($what,$value) = @_;
961
962     if (!defined $chan) {
963         &::DEBUG("news: do_set: chan not defined.");
964         return;
965     }
966
967     if (!defined $what or $what =~ /^\s*$/) {
968         &::DEBUG("news: what $what is not defined.");
969         return;
970     }
971
972     if (!defined $value or $value =~ /^\s*$/) {
973         &::DEBUG("news: value $value is not defined.");
974         return;
975     }
976
977     &::DEBUG("news: do_set: TODO...");
978 }
979
980 sub stats {
981     &::DEBUG("News: stats called.");
982     &::msg($who, "check my logs/console.");
983     my($i,$j) = (0,0);
984
985     # total request count.
986     foreach $chan (keys %::news) {
987         foreach (keys %{ $::news{$chan} }) {
988             $i += $::news{$chan}{$_}{Request_Count};
989         }
990     }
991     &::DEBUG("news: stats: total request count => $i");
992     $i = 0;
993
994     # total user cached.
995     foreach $chan (keys %::newsuser) {
996         $i += $::newsuser{$chan}{$_};
997     }
998     &::DEBUG("news: stats: total user cache => $i");
999     $i = 0;
1000
1001     # average latest time read.
1002     my $t = time();
1003     foreach $chan (keys %::newsuser) {
1004         $i += $t - $::newsuser{$chan}{$_};
1005         &::DEBUG(" i = $i");
1006         $j++;
1007     }
1008     &::DEBUG("news: stats: average latest time read: total time: $i");
1009     &::DEBUG("news: ... count: $j");
1010     &::DEBUG("news:   average: ".sprintf("%.02f", $i/($j||1))." sec/user");
1011     $i = $j = 0;
1012 }
1013
1014 sub AUTOLOAD { &::AUTOLOAD(@_); }
1015
1016 1;