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