]> sipb.mit.edu Git - ikiwiki.git/blob - IkiWiki/Plugin/comments.pm
fix PageSpec ref
[ikiwiki.git] / IkiWiki / Plugin / comments.pm
1 #!/usr/bin/perl
2 # Copyright © 2006-2008 Joey Hess <joey@ikiwiki.info>
3 # Copyright © 2008 Simon McVittie <http://smcv.pseudorandom.co.uk/>
4 # Licensed under the GNU GPL, version 2, or any later version published by the
5 # Free Software Foundation
6 package IkiWiki::Plugin::comments;
7
8 use warnings;
9 use strict;
10 use IkiWiki 3.00;
11 use Encode;
12
13 use constant PREVIEW => "Preview";
14 use constant POST_COMMENT => "Post comment";
15 use constant CANCEL => "Cancel";
16
17 my $postcomment;
18 my %commentstate;
19
20 sub import {
21         hook(type => "checkconfig", id => 'comments',  call => \&checkconfig);
22         hook(type => "getsetup", id => 'comments',  call => \&getsetup);
23         hook(type => "preprocess", id => 'comment', call => \&preprocess,
24                 scan => 1);
25         hook(type => "preprocess", id => 'commentmoderation', call => \&preprocess_moderation);
26         # here for backwards compatability with old comments
27         hook(type => "preprocess", id => '_comment', call => \&preprocess);
28         hook(type => "sessioncgi", id => 'comment', call => \&sessioncgi);
29         hook(type => "htmlize", id => "_comment", call => \&htmlize);
30         hook(type => "htmlize", id => "_comment_pending",
31                 call => \&htmlize_pending);
32         hook(type => "pagetemplate", id => "comments", call => \&pagetemplate);
33         hook(type => "formbuilder_setup", id => "comments",
34                 call => \&formbuilder_setup);
35         # Load goto to fix up user page links for logged-in commenters
36         IkiWiki::loadplugin("goto");
37         IkiWiki::loadplugin("inline");
38 }
39
40 sub getsetup () {
41         return
42                 plugin => {
43                         safe => 1,
44                         rebuild => 1,
45                         section => "web",
46                 },
47                 comments_pagespec => {
48                         type => 'pagespec',
49                         example => 'blog/* and !*/Discussion',
50                         description => 'PageSpec of pages where comments are allowed',
51                         link => 'ikiwiki/PageSpec',
52                         safe => 1,
53                         rebuild => 1,
54                 },
55                 comments_closed_pagespec => {
56                         type => 'pagespec',
57                         example => 'blog/controversial or blog/flamewar',
58                         description => 'PageSpec of pages where posting new comments is not allowed',
59                         link => 'ikiwiki/PageSpec',
60                         safe => 1,
61                         rebuild => 1,
62                 },
63                 comments_pagename => {
64                         type => 'string',
65                         default => 'comment_',
66                         description => 'Base name for comments, e.g. "comment_" for pages like "sandbox/comment_12"',
67                         safe => 0, # manual page moving required
68                         rebuild => undef,
69                 },
70                 comments_allowdirectives => {
71                         type => 'boolean',
72                         example => 0,
73                         description => 'Interpret directives in comments?',
74                         safe => 1,
75                         rebuild => 0,
76                 },
77                 comments_allowauthor => {
78                         type => 'boolean',
79                         example => 0,
80                         description => 'Allow anonymous commenters to set an author name?',
81                         safe => 1,
82                         rebuild => 0,
83                 },
84                 comments_commit => {
85                         type => 'boolean',
86                         example => 1,
87                         description => 'commit comments to the VCS',
88                         # old uncommitted comments are likely to cause
89                         # confusion if this is changed
90                         safe => 0,
91                         rebuild => 0,
92                 },
93 }
94
95 sub checkconfig () {
96         $config{comments_commit} = 1
97                 unless defined $config{comments_commit};
98         $config{comments_pagespec} = ''
99                 unless defined $config{comments_pagespec};
100         $config{comments_closed_pagespec} = ''
101                 unless defined $config{comments_closed_pagespec};
102         $config{comments_pagename} = 'comment_'
103                 unless defined $config{comments_pagename};
104 }
105
106 sub htmlize {
107         my %params = @_;
108         return $params{content};
109 }
110
111 sub htmlize_pending {
112         my %params = @_;
113         return sprintf(gettext("this comment needs %s"),
114                 '<a href="'.
115                 IkiWiki::cgiurl(do => "commentmoderation").'">'.
116                 gettext("moderation").'</a>');
117 }
118
119 # FIXME: copied verbatim from meta
120 sub safeurl ($) {
121         my $url=shift;
122         if (exists $IkiWiki::Plugin::htmlscrubber::{safe_url_regexp} &&
123             defined $IkiWiki::Plugin::htmlscrubber::safe_url_regexp) {
124                 return $url=~/$IkiWiki::Plugin::htmlscrubber::safe_url_regexp/;
125         }
126         else {
127                 return 1;
128         }
129 }
130
131 sub preprocess {
132         my %params = @_;
133         my $page = $params{page};
134
135         my $format = $params{format};
136         if (defined $format && ! exists $IkiWiki::hooks{htmlize}{$format}) {
137                 error(sprintf(gettext("unsupported page format %s"), $format));
138         }
139
140         my $content = $params{content};
141         if (! defined $content) {
142                 error(gettext("comment must have content"));
143         }
144         $content =~ s/\\"/"/g;
145
146         if (defined wantarray) {
147                 if ($config{comments_allowdirectives}) {
148                         $content = IkiWiki::preprocess($page, $params{destpage},
149                                 $content);
150                 }
151
152                 # no need to bother with htmlize if it's just HTML
153                 $content = IkiWiki::htmlize($page, $params{destpage}, $format, $content)
154                         if defined $format;
155
156                 IkiWiki::run_hooks(sanitize => sub {
157                         $content = shift->(
158                                 page => $page,
159                                 destpage => $params{destpage},
160                                 content => $content,
161                         );
162                 });
163         }
164         else {
165                 IkiWiki::preprocess($page, $params{destpage}, $content, 1);
166         }
167
168         # set metadata, possibly overriding [[!meta]] directives from the
169         # comment itself
170
171         my $commentuser;
172         my $commentip;
173         my $commentauthor;
174         my $commentauthorurl;
175         my $commentopenid;
176         if (defined $params{username}) {
177                 $commentuser = $params{username};
178
179                 my $oiduser = eval { IkiWiki::openiduser($commentuser) };
180
181                 if (defined $oiduser) {
182                         # looks like an OpenID
183                         $commentauthorurl = $commentuser;
184                         $commentauthor = (defined $params{nickname} && length $params{nickname}) ? $params{nickname} : $oiduser;
185                         $commentopenid = $commentuser;
186                 }
187                 else {
188                         $commentauthorurl = IkiWiki::cgiurl(
189                                 do => 'goto',
190                                 page => IkiWiki::userpage($commentuser)
191                         );
192
193                         $commentauthor = $commentuser;
194                 }
195         }
196         else {
197                 if (defined $params{ip}) {
198                         $commentip = $params{ip};
199                 }
200                 $commentauthor = gettext("Anonymous");
201         }
202
203         $commentstate{$page}{commentuser} = $commentuser;
204         $commentstate{$page}{commentopenid} = $commentopenid;
205         $commentstate{$page}{commentip} = $commentip;
206         $commentstate{$page}{commentauthor} = $commentauthor;
207         $commentstate{$page}{commentauthorurl} = $commentauthorurl;
208         $commentstate{$page}{commentauthoravatar} = $params{avatar};
209         if (! defined $pagestate{$page}{meta}{author}) {
210                 $pagestate{$page}{meta}{author} = $commentauthor;
211         }
212         if (! defined $pagestate{$page}{meta}{authorurl}) {
213                 $pagestate{$page}{meta}{authorurl} = $commentauthorurl;
214         }
215
216         if ($config{comments_allowauthor}) {
217                 if (defined $params{claimedauthor}) {
218                         $pagestate{$page}{meta}{author} = $params{claimedauthor};
219                 }
220
221                 if (defined $params{url}) {
222                         my $url=$params{url};
223
224                         eval q{use URI::Heuristic}; 
225                         if (! $@) {
226                                 $url=URI::Heuristic::uf_uristr($url);
227                         }
228
229                         if (safeurl($url)) {
230                                 $pagestate{$page}{meta}{authorurl} = $url;
231                         }
232                 }
233         }
234         else {
235                 $pagestate{$page}{meta}{author} = $commentauthor;
236                 $pagestate{$page}{meta}{authorurl} = $commentauthorurl;
237         }
238
239         if (defined $params{subject}) {
240                 # decode title the same way meta does
241                 eval q{use HTML::Entities};
242                 $pagestate{$page}{meta}{title} = decode_entities($params{subject});
243         }
244
245         if ($params{page} =~ m/\/\Q$config{comments_pagename}\E\d+_/) {
246                 $pagestate{$page}{meta}{permalink} = urlto(IkiWiki::dirname($params{page})).
247                         "#".page_to_id($params{page});
248         }
249
250         eval q{use Date::Parse};
251         if (! $@) {
252                 my $time = str2time($params{date});
253                 $IkiWiki::pagectime{$page} = $time if defined $time;
254         }
255
256         return $content;
257 }
258
259 sub preprocess_moderation {
260         my %params = @_;
261
262         $params{desc}=gettext("Comment Moderation")
263                 unless defined $params{desc};
264
265         if (length $config{cgiurl}) {
266                 return '<a href="'.
267                         IkiWiki::cgiurl(do => 'commentmoderation').
268                         '">'.$params{desc}.'</a>';
269         }
270         else {
271                 return $params{desc};
272         }
273 }
274
275 sub sessioncgi ($$) {
276         my $cgi=shift;
277         my $session=shift;
278
279         my $do = $cgi->param('do');
280         if ($do eq 'comment') {
281                 editcomment($cgi, $session);
282         }
283         elsif ($do eq 'commentmoderation') {
284                 commentmoderation($cgi, $session);
285         }
286         elsif ($do eq 'commentsignin') {
287                 IkiWiki::cgi_signin($cgi, $session);
288                 exit;
289         }
290 }
291
292 # Mostly cargo-culted from IkiWiki::plugin::editpage
293 sub editcomment ($$) {
294         my $cgi=shift;
295         my $session=shift;
296
297         IkiWiki::decode_cgi_utf8($cgi);
298
299         eval q{use CGI::FormBuilder};
300         error($@) if $@;
301
302         my @buttons = (POST_COMMENT, PREVIEW, CANCEL);
303         my $form = CGI::FormBuilder->new(
304                 fields => [qw{do sid page subject editcontent type author
305                         url subscribe}],
306                 charset => 'utf-8',
307                 method => 'POST',
308                 required => [qw{editcontent}],
309                 javascript => 0,
310                 params => $cgi,
311                 action => IkiWiki::cgiurl(),
312                 header => 0,
313                 table => 0,
314                 template => { template('editcomment.tmpl') },
315         );
316
317         IkiWiki::decode_form_utf8($form);
318         IkiWiki::run_hooks(formbuilder_setup => sub {
319                         shift->(title => "comment", form => $form, cgi => $cgi,
320                                 session => $session, buttons => \@buttons);
321                 });
322         IkiWiki::decode_form_utf8($form);
323
324         my $type = $form->param('type');
325         if (defined $type && length $type && $IkiWiki::hooks{htmlize}{$type}) {
326                 $type = IkiWiki::possibly_foolish_untaint($type);
327         }
328         else {
329                 $type = $config{default_pageext};
330         }
331
332
333         my @page_types;
334         if (exists $IkiWiki::hooks{htmlize}) {
335                 foreach my $key (grep { !/^_/ } keys %{$IkiWiki::hooks{htmlize}}) {
336                         push @page_types, [$key, $IkiWiki::hooks{htmlize}{$key}{longname} || $key];
337                 }
338         }
339         @page_types=sort @page_types;
340
341         $form->field(name => 'do', type => 'hidden');
342         $form->field(name => 'sid', type => 'hidden', value => $session->id,
343                 force => 1);
344         $form->field(name => 'page', type => 'hidden');
345         $form->field(name => 'subject', type => 'text', size => 72);
346         $form->field(name => 'editcontent', type => 'textarea', rows => 10);
347         $form->field(name => "type", value => $type, force => 1,
348                 type => 'select', options => \@page_types);
349
350         my $username=$session->param('name');
351         $form->tmpl_param(username => $username);
352         if (defined $username && IkiWiki::Plugin::notifyemail->can("subscribe")) {
353                 $form->field(name => "subscribe",
354                         options => [gettext("email replies to me")]);
355         }
356         else {
357                 $form->field(name => "subscribe", type => 'hidden');
358         }
359
360         if ($config{comments_allowauthor} and
361             ! defined $session->param('name')) {
362                 $form->tmpl_param(allowauthor => 1);
363                 $form->field(name => 'author', type => 'text', size => '40');
364                 $form->field(name => 'url', type => 'text', size => '40');
365         }
366         else {
367                 $form->tmpl_param(allowauthor => 0);
368                 $form->field(name => 'author', type => 'hidden', value => '',
369                         force => 1);
370                 $form->field(name => 'url', type => 'hidden', value => '',
371                         force => 1);
372         }
373
374         if (! defined $session->param('name')) {
375                 # Make signinurl work and return here.
376                 $form->tmpl_param(signinurl => IkiWiki::cgiurl(do => 'commentsignin'));
377                 $session->param(postsignin => $ENV{QUERY_STRING});
378                 IkiWiki::cgi_savesession($session);
379         }
380
381         # The untaint is OK (as in editpage) because we're about to pass
382         # it to file_pruned and wiki_file_regexp anyway.
383         my ($page) = $form->field('page')=~/$config{wiki_file_regexp}/;
384         $page = IkiWiki::possibly_foolish_untaint($page);
385         if (! defined $page || ! length $page ||
386                 IkiWiki::file_pruned($page)) {
387                 error(gettext("bad page name"));
388         }
389
390         $form->title(sprintf(gettext("commenting on %s"),
391                         IkiWiki::pagetitle(IkiWiki::basename($page))));
392
393         $form->tmpl_param('helponformattinglink',
394                 htmllink($page, $page, 'ikiwiki/formatting',
395                         noimageinline => 1,
396                         linktext => 'FormattingHelp'),
397                         allowdirectives => $config{allow_directives});
398
399         if ($form->submitted eq CANCEL) {
400                 # bounce back to the page they wanted to comment on, and exit.
401                 IkiWiki::redirect($cgi, urlto($page));
402                 exit;
403         }
404
405         if (not exists $pagesources{$page}) {
406                 error(sprintf(gettext(
407                         "page '%s' doesn't exist, so you can't comment"),
408                         $page));
409         }
410
411         if (pagespec_match($page, $config{comments_closed_pagespec},
412                 location => $page)) {
413                 error(sprintf(gettext(
414                         "comments on page '%s' are closed"),
415                         $page));
416         }
417
418         # Set a flag to indicate that we're posting a comment,
419         # so that postcomment() can tell it should match.
420         $postcomment=1;
421         IkiWiki::check_canedit($page, $cgi, $session);
422         $postcomment=0;
423
424         my $content = "[[!comment format=$type\n";
425
426         if (defined $session->param('name')) {
427                 my $username = $session->param('name');
428                 $username =~ s/"/&quot;/g;
429                 $content .= " username=\"$username\"\n";
430         }
431         if (defined $session->param('nickname')) {
432                 my $nickname = $session->param('nickname');
433                 $nickname =~ s/"/&quot;/g;
434                 $content .= " nickname=\"$nickname\"\n";
435         }
436         elsif (defined $session->remote_addr()) {
437                 my $ip = $session->remote_addr();
438                 if ($ip =~ m/^([.0-9]+)$/) {
439                         $content .= " ip=\"$1\"\n";
440                 }
441         }
442
443         if ($config{comments_allowauthor}) {
444                 my $author = $form->field('author');
445                 if (defined $author && length $author) {
446                         $author =~ s/"/&quot;/g;
447                         $content .= " claimedauthor=\"$author\"\n";
448                 }
449                 my $url = $form->field('url');
450                 if (defined $url && length $url) {
451                         $url =~ s/"/&quot;/g;
452                         $content .= " url=\"$url\"\n";
453                 }
454         }
455
456         my $avatar=getavatar($session->param('name'));
457         if (defined $avatar && length $avatar) {
458                 $avatar =~ s/"/&quot;/g;
459                 $content .= " avatar=\"$avatar\"\n";
460         }
461
462         my $subject = $form->field('subject');
463         if (defined $subject && length $subject) {
464                 $subject =~ s/"/&quot;/g;
465         }
466         else {
467                 $subject = "comment ".(num_comments($page, $config{srcdir}) + 1);
468         }
469         $content .= " subject=\"$subject\"\n";
470
471         $content .= " date=\"" . strftime_utf8('%Y-%m-%dT%H:%M:%SZ', gmtime) . "\"\n";
472
473         my $editcontent = $form->field('editcontent');
474         $editcontent="" if ! defined $editcontent;
475         $editcontent =~ s/\r\n/\n/g;
476         $editcontent =~ s/\r/\n/g;
477         $editcontent =~ s/"/\\"/g;
478         $content .= " content=\"\"\"\n$editcontent\n\"\"\"]]\n";
479
480         my $location=unique_comment_location($page, $content, $config{srcdir});
481
482         # This is essentially a simplified version of editpage:
483         # - the user does not control the page that's created, only the parent
484         # - it's always a create operation, never an edit
485         # - this means that conflicts should never happen
486         # - this means that if they do, rocks fall and everyone dies
487
488         if ($form->submitted eq PREVIEW) {
489                 my $preview=previewcomment($content, $location, $page, time);
490                 IkiWiki::run_hooks(format => sub {
491                         $preview = shift->(page => $page,
492                                 content => $preview);
493                 });
494                 $form->tmpl_param(page_preview => $preview);
495         }
496         else {
497                 $form->tmpl_param(page_preview => "");
498         }
499
500         if ($form->submitted eq POST_COMMENT && $form->validate) {
501                 IkiWiki::checksessionexpiry($cgi, $session);
502
503                 if (defined $username && length $form->field("subscribe") &&
504                     IkiWiki::Plugin::notifyemail->can("subscribe")) {
505                         IkiWiki::Plugin::notifyemail::subscribe($username,
506                                 "comment($page)");
507                 }
508                 
509                 $postcomment=1;
510                 my $ok=IkiWiki::check_content(content => $form->field('editcontent'),
511                         subject => $form->field('subject'),
512                         $config{comments_allowauthor} ? (
513                                 author => $form->field('author'),
514                                 url => $form->field('url'),
515                         ) : (),
516                         page => $location,
517                         cgi => $cgi,
518                         session => $session,
519                         nonfatal => 1,
520                 );
521                 $postcomment=0;
522
523                 if (! $ok) {
524                         $location=unique_comment_location($page, $content, $config{srcdir}, "._comment_pending");
525                         writefile("$location._comment_pending", $config{srcdir}, $content);
526
527                         # Refresh so anything that deals with pending
528                         # comments can be updated.
529                         require IkiWiki::Render;
530                         IkiWiki::refresh();
531                         IkiWiki::saveindex();
532
533                         IkiWiki::printheader($session);
534                         print IkiWiki::cgitemplate($cgi, gettext(gettext("comment stored for moderation")),
535                                 "<p>".
536                                 gettext("Your comment will be posted after moderator review").
537                                 "</p>");
538                         exit;
539                 }
540
541                 # FIXME: could probably do some sort of graceful retry
542                 # on error? Would require significant unwinding though
543                 my $file = "$location._comment";
544                 writefile($file, $config{srcdir}, $content);
545
546                 my $conflict;
547
548                 if ($config{rcs} and $config{comments_commit}) {
549                         my $message = gettext("Added a comment");
550                         if (defined $form->field('subject') &&
551                                 length $form->field('subject')) {
552                                 $message = sprintf(
553                                         gettext("Added a comment: %s"),
554                                         $form->field('subject'));
555                         }
556
557                         IkiWiki::rcs_add($file);
558                         IkiWiki::disable_commit_hook();
559                         $conflict = IkiWiki::rcs_commit_staged(
560                                 message => $message,
561                                 session => $session,
562                         );
563                         IkiWiki::enable_commit_hook();
564                         IkiWiki::rcs_update();
565                 }
566
567                 # Now we need a refresh
568                 require IkiWiki::Render;
569                 IkiWiki::refresh();
570                 IkiWiki::saveindex();
571
572                 # this should never happen, unless a committer deliberately
573                 # breaks it or something
574                 error($conflict) if defined $conflict;
575
576                 # Jump to the new comment on the page.
577                 # The trailing question mark tries to avoid broken
578                 # caches and get the most recent version of the page.
579                 IkiWiki::redirect($cgi, urlto($page).
580                         "?updated#".page_to_id($location));
581
582         }
583         else {
584                 IkiWiki::showform($form, \@buttons, $session, $cgi,
585                         page => $page);
586         }
587
588         exit;
589 }
590
591 sub getavatar ($) {
592         my $user=shift;
593         
594         my $avatar;
595         eval q{use Libravatar::URL};
596         if (! $@) {
597                 my $oiduser = eval { IkiWiki::openiduser($user) };
598                 my $https=defined $config{url} && $config{url}=~/^https:/;
599
600                 if (defined $oiduser) {
601                         eval {
602                                 $avatar = libravatar_url(openid => $user, https => $https);
603                         }
604                 }
605                 if (! defined $avatar &&
606                     (my $email = IkiWiki::userinfo_get($user, 'email'))) {
607                         eval {
608                                 $avatar = libravatar_url(email => $email, https => $https);
609                         }
610                 }
611         }
612         return $avatar;
613 }
614
615
616 sub commentmoderation ($$) {
617         my $cgi=shift;
618         my $session=shift;
619
620         IkiWiki::needsignin($cgi, $session);
621         if (! IkiWiki::is_admin($session->param("name"))) {
622                 error(gettext("you are not logged in as an admin"));
623         }
624
625         IkiWiki::decode_cgi_utf8($cgi);
626         
627         if (defined $cgi->param('sid')) {
628                 IkiWiki::checksessionexpiry($cgi, $session);
629
630                 my $rejectalldefer=$cgi->param('rejectalldefer');
631
632                 my %vars=$cgi->Vars;
633                 my $added=0;
634                 foreach my $id (keys %vars) {
635                         if ($id =~ /(.*)\._comment(?:_pending)?$/) {
636                                 $id=decode_utf8($id);
637                                 my $action=$cgi->param($id);
638                                 next if $action eq 'Defer' && ! $rejectalldefer;
639
640                                 # Make sure that the id is of a legal
641                                 # pending comment.
642                                 my ($f) = $id =~ /$config{wiki_file_regexp}/;
643                                 if (! defined $f || ! length $f ||
644                                     IkiWiki::file_pruned($f)) {
645                                         error("illegal file");
646                                 }
647
648                                 my $page=IkiWiki::dirname($f);
649                                 my $file="$config{srcdir}/$f";
650                                 if (! -e $file) {
651                                         # old location
652                                         $file="$config{wikistatedir}/comments_pending/".$f;
653                                 }
654
655                                 if ($action eq 'Accept') {
656                                         my $content=eval { readfile($file) };
657                                         next if $@; # file vanished since form was displayed
658                                         my $dest=unique_comment_location($page, $content, $config{srcdir})."._comment";
659                                         writefile($dest, $config{srcdir}, $content);
660                                         if ($config{rcs} and $config{comments_commit}) {
661                                                 IkiWiki::rcs_add($dest);
662                                         }
663                                         $added++;
664                                 }
665
666                                 require IkiWiki::Render;
667                                 IkiWiki::prune($file);
668                         }
669                 }
670
671                 if ($added) {
672                         my $conflict;
673                         if ($config{rcs} and $config{comments_commit}) {
674                                 my $message = gettext("Comment moderation");
675                                 IkiWiki::disable_commit_hook();
676                                 $conflict=IkiWiki::rcs_commit_staged(
677                                         message => $message,
678                                         session => $session,
679                                 );
680                                 IkiWiki::enable_commit_hook();
681                                 IkiWiki::rcs_update();
682                         }
683                 
684                         # Now we need a refresh
685                         require IkiWiki::Render;
686                         IkiWiki::refresh();
687                         IkiWiki::saveindex();
688                 
689                         error($conflict) if defined $conflict;
690                 }
691         }
692
693         my @comments=map {
694                 my ($id, $dir, $ctime)=@{$_};
695                 my $content=readfile("$dir/$id");
696                 my $preview=previewcomment($content, $id,
697                         $id, $ctime);
698                 {
699                         id => $id,
700                         view => $preview,
701                 }
702         } sort { $b->[2] <=> $a->[2] } comments_pending();
703
704         my $template=template("commentmoderation.tmpl");
705         $template->param(
706                 sid => $session->id,
707                 comments => \@comments,
708                 cgiurl => IkiWiki::cgiurl(),
709         );
710         IkiWiki::printheader($session);
711         my $out=$template->output;
712         IkiWiki::run_hooks(format => sub {
713                 $out = shift->(page => "", content => $out);
714         });
715         print IkiWiki::cgitemplate($cgi, gettext("comment moderation"), $out);
716         exit;
717 }
718
719 sub formbuilder_setup (@) {
720         my %params=@_;
721
722         my $form=$params{form};
723         if ($form->title eq "preferences" &&
724             IkiWiki::is_admin($params{session}->param("name"))) {
725                 push @{$params{buttons}}, "Comment Moderation";
726                 if ($form->submitted && $form->submitted eq "Comment Moderation") {
727                         commentmoderation($params{cgi}, $params{session});
728                 }
729         }
730 }
731
732 sub comments_pending () {
733         my @ret;
734
735         eval q{use File::Find};
736         error($@) if $@;
737         eval q{use Cwd};
738         error($@) if $@;
739         my $origdir=getcwd();
740
741         my $find_comments=sub {
742                 my $dir=shift;
743                 my $extension=shift;
744                 return unless -d $dir;
745
746                 chdir($dir) || die "chdir $dir: $!";
747
748                 find({
749                         no_chdir => 1,
750                         wanted => sub {
751                                 my $file=decode_utf8($_);
752                                 $file=~s/^\.\///;
753                                 return if ! length $file || IkiWiki::file_pruned($file)
754                                         || -l $_ || -d _ || $file !~ /\Q$extension\E$/;
755                                 my ($f) = $file =~ /$config{wiki_file_regexp}/; # untaint
756                                 if (defined $f) {
757                                         my $ctime=(stat($_))[10];
758                                         push @ret, [$f, $dir, $ctime];
759                                 }
760                         }
761                 }, ".");
762
763                 chdir($origdir) || die "chdir $origdir: $!";
764         };
765         
766         $find_comments->($config{srcdir}, "._comment_pending");
767         # old location
768         $find_comments->("$config{wikistatedir}/comments_pending/",
769                 "._comment");
770
771         return @ret;
772 }
773
774 sub previewcomment ($$$) {
775         my $content=shift;
776         my $location=shift;
777         my $page=shift;
778         my $time=shift;
779
780         # Previewing a comment should implicitly enable comment posting mode.
781         my $oldpostcomment=$postcomment;
782         $postcomment=1;
783
784         my $preview = IkiWiki::htmlize($location, $page, '_comment',
785                         IkiWiki::linkify($location, $page,
786                         IkiWiki::preprocess($location, $page,
787                         IkiWiki::filter($location, $page, $content), 0, 1)));
788
789         my $template = template("comment.tmpl");
790         $template->param(content => $preview);
791         $template->param(ctime => displaytime($time, undef, 1));
792         $template->param(html5 => $config{html5});
793
794         IkiWiki::run_hooks(pagetemplate => sub {
795                 shift->(page => $location,
796                         destpage => $page,
797                         template => $template);
798         });
799
800         $template->param(have_actions => 0);
801
802         $postcomment=$oldpostcomment;
803
804         return $template->output;
805 }
806
807 sub commentsshown ($) {
808         my $page=shift;
809
810         return pagespec_match($page, $config{comments_pagespec},
811                 location => $page);
812 }
813
814 sub commentsopen ($) {
815         my $page = shift;
816
817         return length $config{cgiurl} > 0 &&
818                (! length $config{comments_closed_pagespec} ||
819                 ! pagespec_match($page, $config{comments_closed_pagespec},
820                                  location => $page));
821 }
822
823 sub pagetemplate (@) {
824         my %params = @_;
825
826         my $page = $params{page};
827         my $template = $params{template};
828         my $shown = ($template->query(name => 'commentslink') ||
829                      $template->query(name => 'commentsurl') ||
830                      $template->query(name => 'atomcommentsurl') ||
831                      $template->query(name => 'comments')) &&
832                     commentsshown($page);
833
834         if ($template->query(name => 'comments')) {
835                 my $comments = undef;
836                 if ($shown) {
837                         $comments = IkiWiki::preprocess_inline(
838                                 pages => "comment($page) and !comment($page/*)",
839                                 template => 'comment',
840                                 show => 0,
841                                 reverse => 'yes',
842                                 page => $page,
843                                 destpage => $params{destpage},
844                                 feedfile => 'comments',
845                                 emptyfeeds => 'no',
846                         );
847                 }
848
849                 if (defined $comments && length $comments) {
850                         $template->param(comments => $comments);
851                 }
852
853                 if ($shown && commentsopen($page)) {
854                         $template->param(addcommenturl => addcommenturl($page));
855                 }
856         }
857
858         if ($shown) {
859                 if ($template->query(name => 'commentsurl')) {
860                         $template->param(commentsurl =>
861                                 urlto($page).'#comments');
862                 }
863
864                 if ($template->query(name => 'atomcommentsurl') && $config{usedirs}) {
865                         # This will 404 until there are some comments, but I
866                         # think that's probably OK...
867                         $template->param(atomcommentsurl =>
868                                 urlto($page).'comments.atom');
869                 }
870
871                 if ($template->query(name => 'commentslink')) {
872                         my $num=num_comments($page, $config{srcdir});
873                         my $link;
874                         if ($num > 0) {
875                                 $link = htmllink($page, $params{destpage}, $page,
876                                         linktext => sprintf(ngettext("%i comment", "%i comments", $num), $num),
877                                         anchor => "comments",
878                                         noimageinline => 1
879                                 );
880                         }
881                         elsif (commentsopen($page)) {
882                                 $link = "<a href=\"".addcommenturl($page)."\">".
883                                         #translators: Here "Comment" is a verb;
884                                         #translators: the user clicks on it to
885                                         #translators: post a comment.
886                                         gettext("Comment").
887                                         "</a>";
888                         }
889                         $template->param(commentslink => $link)
890                                 if defined $link;
891                 }
892         }
893
894         # everything below this point is only relevant to the comments
895         # themselves
896         if (!exists $commentstate{$page}) {
897                 return;
898         }
899         
900         if ($template->query(name => 'commentid')) {
901                 $template->param(commentid => page_to_id($page));
902         }
903
904         if ($template->query(name => 'commentuser')) {
905                 $template->param(commentuser =>
906                         $commentstate{$page}{commentuser});
907         }
908
909         if ($template->query(name => 'commentopenid')) {
910                 $template->param(commentopenid =>
911                         $commentstate{$page}{commentopenid});
912         }
913
914         if ($template->query(name => 'commentip')) {
915                 $template->param(commentip =>
916                         $commentstate{$page}{commentip});
917         }
918
919         if ($template->query(name => 'commentauthor')) {
920                 $template->param(commentauthor =>
921                         $commentstate{$page}{commentauthor});
922         }
923
924         if ($template->query(name => 'commentauthorurl')) {
925                 $template->param(commentauthorurl =>
926                         $commentstate{$page}{commentauthorurl});
927         }
928
929         if ($template->query(name => 'commentauthoravatar')) {
930                 $template->param(commentauthoravatar =>
931                         $commentstate{$page}{commentauthoravatar});
932         }
933
934         if ($template->query(name => 'removeurl') &&
935             IkiWiki::Plugin::remove->can("check_canremove") &&
936             length $config{cgiurl}) {
937                 $template->param(removeurl => IkiWiki::cgiurl(do => 'remove',
938                         page => $page));
939                 $template->param(have_actions => 1);
940         }
941 }
942
943 sub addcommenturl ($) {
944         my $page=shift;
945
946         return IkiWiki::cgiurl(do => 'comment', page => $page);
947 }
948
949 sub num_comments ($$) {
950         my $page=shift;
951         my $dir=shift;
952
953         my @comments=glob("$dir/$page/$config{comments_pagename}*._comment");
954         return int @comments;
955 }
956
957 sub unique_comment_location ($$$$) {
958         my $page=shift;
959         eval q{use Digest::MD5 'md5_hex'};
960         error($@) if $@;
961         my $content_md5=md5_hex(Encode::encode_utf8(shift));
962         my $dir=shift;
963         my $ext=shift || "._comment";
964
965         my $location;
966         my $i = num_comments($page, $dir);
967         do {
968                 $i++;
969                 $location = "$page/$config{comments_pagename}${i}_${content_md5}";
970         } while (-e "$dir/$location$ext");
971
972         return $location;
973 }
974
975 sub page_to_id ($) {
976         # Converts a comment page name into a unique, legal html id
977         # attribute value, that can be used as an anchor to link to the
978         # comment.
979         my $page=shift;
980
981         eval q{use Digest::MD5 'md5_hex'};
982         error($@) if $@;
983
984         return "comment-".md5_hex(Encode::encode_utf8(($page)));
985 }
986         
987 package IkiWiki::PageSpec;
988
989 sub match_postcomment ($$;@) {
990         my $page = shift;
991         my $glob = shift;
992
993         if (! $postcomment) {
994                 return IkiWiki::FailReason->new("not posting a comment");
995         }
996         return match_glob($page, $glob, @_);
997 }
998
999 sub match_comment ($$;@) {
1000         my $page = shift;
1001         my $glob = shift;
1002
1003         if (! $postcomment) {
1004                 # To see if it's a comment, check the source file type.
1005                 # Deal with comments that were just deleted.
1006                 my $source=exists $IkiWiki::pagesources{$page} ?
1007                         $IkiWiki::pagesources{$page} :
1008                         $IkiWiki::delpagesources{$page};
1009                 my $type=defined $source ? IkiWiki::pagetype($source) : undef;
1010                 if (! defined $type || $type ne "_comment") {
1011                         return IkiWiki::FailReason->new("$page is not a comment");
1012                 }
1013         }
1014
1015         return match_glob($page, "$glob/*", internal => 1, @_);
1016 }
1017
1018 sub match_comment_pending ($$;@) {
1019         my $page = shift;
1020         my $glob = shift;
1021         
1022         my $source=exists $IkiWiki::pagesources{$page} ?
1023                 $IkiWiki::pagesources{$page} :
1024                 $IkiWiki::delpagesources{$page};
1025         my $type=defined $source ? IkiWiki::pagetype($source) : undef;
1026         if (! defined $type || $type ne "_comment_pending") {
1027                 return IkiWiki::FailReason->new("$page is not a pending comment");
1028         }
1029
1030         return match_glob($page, "$glob/*", internal => 1, @_);
1031 }
1032
1033 1