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