652ddfad3f0f6e7000c472793db58dc13ce5ca64
[onis.git] / lib / Onis / Plugins / Topics.pm
1 package Onis::Plugins::Topics;
2
3 use strict;
4 use warnings;
5
6 use Onis::Config (qw(get_config));
7 use Onis::Html (qw(html_escape get_filehandle));
8 use Onis::Language (qw(translate));
9 use Onis::Data::Core (qw(register_plugin nick_to_name));
10 use Onis::Data::Persistent ();
11
12 our $TopicCache = Onis::Data::Persistent->new ('TopicCache', 'time', qw(text nick));
13 our $TopicData = [];
14
15 register_plugin ('TOPIC', \&add);
16 register_plugin ('OUTPUT', \&output);
17
18 our $MAX = 10;
19 if (get_config ('plugin_max'))
20 {
21         my $tmp = get_config ('plugin_max');
22         $tmp =~ s/\D//g;
23
24         $MAX = $tmp if ($tmp);
25 }
26
27 my $VERSION = '$Id$';
28 print STDERR $/, __FILE__, ": $VERSION" if ($::DEBUG);
29
30 return (1);
31
32 sub add
33 {
34         my $data = shift;
35         my $text = $data->{'text'};
36         my $nick = $data->{'nick'};
37         my $time = $data->{'epoch'};
38
39         $TopicCache->put ($time, $text, $nick);
40 }
41
42 sub calculate
43 {
44         my $i = 0;
45         for (sort { $b <=> $a } ($TopicCache->keys ()))
46         {
47                 my $time = $_;
48                 last if ($i++ >= $MAX);
49                 
50                 my ($text, $nick) = $TopicCache->get ($time);
51                 die unless (defined ($nick));
52
53                 $nick = get_main_nick ($nick);
54                 push (@$TopicData, [$text, $nick, $time]);
55         }
56 }
57
58 sub output
59 {
60         calculate ();
61         
62         my $fh = get_filehandle ();
63         
64         my $topic = translate ('Topic');
65         my $setby = translate ('Set by');
66
67         print $fh <<EOF;
68 <table class="plugin topics">
69   <tr>
70     <td class="invis">&nbsp;</td>
71     <th>$topic</th>
72     <th>$setby</th>
73   </tr>
74 EOF
75
76         my $i = 0;
77         for (@$TopicData)
78         {
79                 $i++;
80                 my ($topic, $nick) = @$_;
81                 my $name = nick_to_name ($nick) || $nick;
82
83                 $topic = html_escape ($topic);
84                 
85                 print $fh "  <tr>\n",
86                 qq#    <td class="numeration">$i</td>\n#,
87                 qq#    <td>$topic</td>\n#,
88                 qq#    <td class="nick">$name</td>\n#,
89                 qq#  </tr>\n#;
90         }
91
92         print $fh "</table>\n\n";
93 }