add a button to prefs page for comment moderation
[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 use POSIX qw(strftime);
13
14 use constant PREVIEW => "Preview";
15 use constant POST_COMMENT => "Post comment";
16 use constant CANCEL => "Cancel";
17
18 my $postcomment;
19 my %commentstate;
20
21 sub import {
22         hook(type => "checkconfig", id => 'comments',  call => \&checkconfig);
23         hook(type => "getsetup", id => 'comments',  call => \&getsetup);
24         hook(type => "preprocess", id => '_comment', call => \&preprocess);
25         hook(type => "sessioncgi", id => 'comment', call => \&sessioncgi);
26         hook(type => "htmlize", id => "_comment", call => \&htmlize);
27         hook(type => "pagetemplate", id => "comments", call => \&pagetemplate);
28         hook(type => "cgi", id => "comments", call => \&linkcgi);
29         hook(type => "formbuilder_setup", id => "comments", call => \&formbuilder_setup);
30         IkiWiki::loadplugin("inline");
31 }
32
33 sub getsetup () {
34         return
35                 plugin => {
36                         safe => 1,
37                         rebuild => 1,
38                 },
39                 comments_pagespec => {
40                         type => 'pagespec',
41                         example => 'blog/* and !*/Discussion',
42                         description => 'PageSpec of pages where comments are allowed',
43                         link => 'ikiwiki/PageSpec',
44                         safe => 1,
45                         rebuild => 1,
46                 },
47                 comments_closed_pagespec => {
48                         type => 'pagespec',
49                         example => 'blog/controversial or blog/flamewar',
50                         description => 'PageSpec of pages where posting new comments is not allowed',
51                         link => 'ikiwiki/PageSpec',
52                         safe => 1,
53                         rebuild => 1,
54                 },
55                 comments_pagename => {
56                         type => 'string',
57                         default => 'comment_',
58                         description => 'Base name for comments, e.g. "comment_" for pages like "sandbox/comment_12"',
59                         safe => 0, # manual page moving required
60                         rebuild => undef,
61                 },
62                 comments_allowdirectives => {
63                         type => 'boolean',
64                         example => 0,
65                         description => 'Interpret directives in comments?',
66                         safe => 1,
67                         rebuild => 0,
68                 },
69                 comments_allowauthor => {
70                         type => 'boolean',
71                         example => 0,
72                         description => 'Allow anonymous commenters to set an author name?',
73                         safe => 1,
74                         rebuild => 0,
75                 },
76                 comments_commit => {
77                         type => 'boolean',
78                         example => 1,
79                         description => 'commit comments to the VCS',
80                         # old uncommitted comments are likely to cause
81                         # confusion if this is changed
82                         safe => 0,
83                         rebuild => 0,
84                 },
85 }
86
87 sub checkconfig () {
88         $config{comments_commit} = 1
89                 unless defined $config{comments_commit};
90         $config{comments_pagespec} = ''
91                 unless defined $config{comments_pagespec};
92         $config{comments_closed_pagespec} = ''
93                 unless defined $config{comments_closed_pagespec};
94         $config{comments_pagename} = 'comment_'
95                 unless defined $config{comments_pagename};
96 }
97
98 sub htmlize {
99         my %params = @_;
100         return $params{content};
101 }
102
103 # FIXME: copied verbatim from meta
104 sub safeurl ($) {
105         my $url=shift;
106         if (exists $IkiWiki::Plugin::htmlscrubber::{safe_url_regexp} &&
107             defined $IkiWiki::Plugin::htmlscrubber::safe_url_regexp) {
108                 return $url=~/$IkiWiki::Plugin::htmlscrubber::safe_url_regexp/;
109         }
110         else {
111                 return 1;
112         }
113 }
114
115 sub preprocess {
116         my %params = @_;
117         my $page = $params{page};
118
119         my $format = $params{format};
120         if (defined $format && ! exists $IkiWiki::hooks{htmlize}{$format}) {
121                 error(sprintf(gettext("unsupported page format %s"), $format));
122         }
123
124         my $content = $params{content};
125         if (! defined $content) {
126                 error(gettext("comment must have content"));
127         }
128         $content =~ s/\\"/"/g;
129
130         $content = IkiWiki::filter($page, $params{destpage}, $content);
131
132         if ($config{comments_allowdirectives}) {
133                 $content = IkiWiki::preprocess($page, $params{destpage},
134                         $content);
135         }
136
137         # no need to bother with htmlize if it's just HTML
138         $content = IkiWiki::htmlize($page, $params{destpage}, $format, $content)
139                 if defined $format;
140
141         IkiWiki::run_hooks(sanitize => sub {
142                 $content = shift->(
143                         page => $page,
144                         destpage => $params{destpage},
145                         content => $content,
146                 );
147         });
148
149         # set metadata, possibly overriding [[!meta]] directives from the
150         # comment itself
151
152         my $commentuser;
153         my $commentip;
154         my $commentauthor;
155         my $commentauthorurl;
156         my $commentopenid;
157         if (defined $params{username}) {
158                 $commentuser = $params{username};
159
160                 my $oiduser = eval { IkiWiki::openiduser($commentuser) };
161
162                 if (defined $oiduser) {
163                         # looks like an OpenID
164                         $commentauthorurl = $commentuser;
165                         $commentauthor = $oiduser;
166                         $commentopenid = $commentuser;
167                 }
168                 else {
169                         $commentauthorurl = IkiWiki::cgiurl(
170                                 do => 'commenter',
171                                 page => (length $config{userdir}
172                                         ? "$config{userdir}/$commentuser"
173                                         : "$commentuser"));
174
175                         $commentauthor = $commentuser;
176                 }
177         }
178         else {
179                 if (defined $params{ip}) {
180                         $commentip = $params{ip};
181                 }
182                 $commentauthor = gettext("Anonymous");
183         }
184
185         $commentstate{$page}{commentuser} = $commentuser;
186         $commentstate{$page}{commentopenid} = $commentopenid;
187         $commentstate{$page}{commentip} = $commentip;
188         $commentstate{$page}{commentauthor} = $commentauthor;
189         $commentstate{$page}{commentauthorurl} = $commentauthorurl;
190         if (! defined $pagestate{$page}{meta}{author}) {
191                 $pagestate{$page}{meta}{author} = $commentauthor;
192         }
193         if (! defined $pagestate{$page}{meta}{authorurl}) {
194                 $pagestate{$page}{meta}{authorurl} = $commentauthorurl;
195         }
196
197         if ($config{comments_allowauthor}) {
198                 if (defined $params{claimedauthor}) {
199                         $pagestate{$page}{meta}{author} = $params{claimedauthor};
200                 }
201
202                 if (defined $params{url}) {
203                         my $url=$params{url};
204
205                         eval q{use URI::Heuristic}; 
206                         if (! $@) {
207                                 $url=URI::Heuristic::uf_uristr($url);
208                         }
209
210                         if (safeurl($url)) {
211                                 $pagestate{$page}{meta}{authorurl} = $url;
212                         }
213                 }
214         }
215         else {
216                 $pagestate{$page}{meta}{author} = $commentauthor;
217                 $pagestate{$page}{meta}{authorurl} = $commentauthorurl;
218         }
219
220         if (defined $params{subject}) {
221                 $pagestate{$page}{meta}{title} = $params{subject};
222         }
223
224         if ($params{page} =~ m/\/(\Q$config{comments_pagename}\E\d+)$/) {
225                 $pagestate{$page}{meta}{permalink} = urlto(IkiWiki::dirname($params{page}), undef, 1).
226                         "#".$params{page};
227         }
228
229         eval q{use Date::Parse};
230         if (! $@) {
231                 my $time = str2time($params{date});
232                 $IkiWiki::pagectime{$page} = $time if defined $time;
233         }
234
235         return $content;
236 }
237
238 # This is exactly the same as recentchanges_link :-(
239 sub linkcgi ($) {
240         my $cgi=shift;
241         if (defined $cgi->param('do') && $cgi->param('do') eq "commenter") {
242
243                 my $page=decode_utf8($cgi->param("page"));
244                 if (! defined $page) {
245                         error("missing page parameter");
246                 }
247
248                 IkiWiki::loadindex();
249
250                 my $link=bestlink("", $page);
251                 if (! length $link) {
252                         print "Content-type: text/html\n\n";
253                         print IkiWiki::misctemplate(gettext(gettext("missing page")),
254                                 "<p>".
255                                 sprintf(gettext("The page %s does not exist."),
256                                         htmllink("", "", $page)).
257                                 "</p>");
258                 }
259                 else {
260                         IkiWiki::redirect($cgi, urlto($link, undef, 1));
261                 }
262
263                 exit;
264         }
265 }
266
267 sub sessioncgi ($$) {
268         my $cgi=shift;
269         my $session=shift;
270
271         my $do = $cgi->param('do');
272         if ($do eq 'comment') {
273                 editcomment($cgi, $session);
274         }
275         elsif ($do eq 'commentmoderation') {
276                 commentmoderation($cgi, $session);
277         }
278 }
279
280 # Mostly cargo-culted from IkiWiki::plugin::editpage
281 sub editcomment ($$) {
282         my $cgi=shift;
283         my $session=shift;
284
285         IkiWiki::decode_cgi_utf8($cgi);
286
287         eval q{use CGI::FormBuilder};
288         error($@) if $@;
289
290         my @buttons = (POST_COMMENT, PREVIEW, CANCEL);
291         my $form = CGI::FormBuilder->new(
292                 fields => [qw{do sid page subject editcontent type author url}],
293                 charset => 'utf-8',
294                 method => 'POST',
295                 required => [qw{editcontent}],
296                 javascript => 0,
297                 params => $cgi,
298                 action => $config{cgiurl},
299                 header => 0,
300                 table => 0,
301                 template => scalar IkiWiki::template_params('editcomment.tmpl'),
302         );
303
304         IkiWiki::decode_form_utf8($form);
305         IkiWiki::run_hooks(formbuilder_setup => sub {
306                         shift->(title => "comment", form => $form, cgi => $cgi,
307                                 session => $session, buttons => \@buttons);
308                 });
309         IkiWiki::decode_form_utf8($form);
310
311         my $type = $form->param('type');
312         if (defined $type && length $type && $IkiWiki::hooks{htmlize}{$type}) {
313                 $type = IkiWiki::possibly_foolish_untaint($type);
314         }
315         else {
316                 $type = $config{default_pageext};
317         }
318         my @page_types;
319         if (exists $IkiWiki::hooks{htmlize}) {
320                 @page_types = grep { ! /^_/ } keys %{$IkiWiki::hooks{htmlize}};
321         }
322
323         $form->field(name => 'do', type => 'hidden');
324         $form->field(name => 'sid', type => 'hidden', value => $session->id,
325                 force => 1);
326         $form->field(name => 'page', type => 'hidden');
327         $form->field(name => 'subject', type => 'text', size => 72);
328         $form->field(name => 'editcontent', type => 'textarea', rows => 10);
329         $form->field(name => "type", value => $type, force => 1,
330                 type => 'select', options => \@page_types);
331
332         $form->tmpl_param(username => $session->param('name'));
333
334         if ($config{comments_allowauthor} and
335             ! defined $session->param('name')) {
336                 $form->tmpl_param(allowauthor => 1);
337                 $form->field(name => 'author', type => 'text', size => '40');
338                 $form->field(name => 'url', type => 'text', size => '40');
339         }
340         else {
341                 $form->tmpl_param(allowauthor => 0);
342                 $form->field(name => 'author', type => 'hidden', value => '',
343                         force => 1);
344                 $form->field(name => 'url', type => 'hidden', value => '',
345                         force => 1);
346         }
347
348         # The untaint is OK (as in editpage) because we're about to pass
349         # it to file_pruned anyway
350         my $page = $form->field('page');
351         $page = IkiWiki::possibly_foolish_untaint($page);
352         if (! defined $page || ! length $page ||
353                 IkiWiki::file_pruned($page, $config{srcdir})) {
354                 error(gettext("bad page name"));
355         }
356
357         my $baseurl = urlto($page, undef, 1);
358
359         $form->title(sprintf(gettext("commenting on %s"),
360                         IkiWiki::pagetitle($page)));
361
362         $form->tmpl_param('helponformattinglink',
363                 htmllink($page, $page, 'ikiwiki/formatting',
364                         noimageinline => 1,
365                         linktext => 'FormattingHelp'),
366                         allowdirectives => $config{allow_directives});
367
368         if ($form->submitted eq CANCEL) {
369                 # bounce back to the page they wanted to comment on, and exit.
370                 # CANCEL need not be considered in future
371                 IkiWiki::redirect($cgi, urlto($page, undef, 1));
372                 exit;
373         }
374
375         if (not exists $pagesources{$page}) {
376                 error(sprintf(gettext(
377                         "page '%s' doesn't exist, so you can't comment"),
378                         $page));
379         }
380
381         if (pagespec_match($page, $config{comments_closed_pagespec},
382                 location => $page)) {
383                 error(sprintf(gettext(
384                         "comments on page '%s' are closed"),
385                         $page));
386         }
387
388         # Set a flag to indicate that we're posting a comment,
389         # so that postcomment() can tell it should match.
390         $postcomment=1;
391         IkiWiki::check_canedit($page, $cgi, $session);
392         $postcomment=0;
393
394         my $location=unique_comment_location($page, $config{srcdir});
395
396         my $content = "[[!_comment format=$type\n";
397
398         # FIXME: handling of double quotes probably wrong?
399         if (defined $session->param('name')) {
400                 my $username = $session->param('name');
401                 $username =~ s/"/&quot;/g;
402                 $content .= " username=\"$username\"\n";
403         }
404         elsif (defined $ENV{REMOTE_ADDR}) {
405                 my $ip = $ENV{REMOTE_ADDR};
406                 if ($ip =~ m/^([.0-9]+)$/) {
407                         $content .= " ip=\"$1\"\n";
408                 }
409         }
410
411         if ($config{comments_allowauthor}) {
412                 my $author = $form->field('author');
413                 if (defined $author && length $author) {
414                         $author =~ s/"/&quot;/g;
415                         $content .= " claimedauthor=\"$author\"\n";
416                 }
417                 my $url = $form->field('url');
418                 if (defined $url && length $url) {
419                         $url =~ s/"/&quot;/g;
420                         $content .= " url=\"$url\"\n";
421                 }
422         }
423
424         my $subject = $form->field('subject');
425         if (defined $subject && length $subject) {
426                 $subject =~ s/"/&quot;/g;
427                 $content .= " subject=\"$subject\"\n";
428         }
429
430         $content .= " date=\"" . decode_utf8(strftime('%Y-%m-%dT%H:%M:%SZ', gmtime)) . "\"\n";
431
432         my $editcontent = $form->field('editcontent') || '';
433         $editcontent =~ s/\r\n/\n/g;
434         $editcontent =~ s/\r/\n/g;
435         $editcontent =~ s/"/\\"/g;
436         $content .= " content=\"\"\"\n$editcontent\n\"\"\"]]\n";
437
438         # This is essentially a simplified version of editpage:
439         # - the user does not control the page that's created, only the parent
440         # - it's always a create operation, never an edit
441         # - this means that conflicts should never happen
442         # - this means that if they do, rocks fall and everyone dies
443
444         if ($form->submitted eq PREVIEW) {
445                 $form->tmpl_param(page_preview => 
446                         previewcomment($content, $location, $page, time));
447         }
448         else {
449                 $form->tmpl_param(page_preview => "");
450         }
451
452         if ($form->submitted eq POST_COMMENT && $form->validate) {
453                 IkiWiki::checksessionexpiry($cgi, $session);
454                 
455                 $postcomment=1;
456                 my $ok=IkiWiki::check_content(content => $form->field('editcontent'),
457                         subject => $form->field('subject'),
458                         $config{comments_allowauthor} ? (
459                                 author => $form->field('author'),
460                                 url => $form->field('url'),
461                         ) : (),
462                         page => $location,
463                         cgi => $cgi,
464                         session => $session,
465                         nonfatal => 1,
466                 );
467                 $postcomment=0;
468
469                 if (! $ok) {
470                         my $penddir=$config{wikistatedir}."/comments_pending";
471                         $location=unique_comment_location($page, $penddir);
472                         writefile("$location._comment", $penddir, $content);
473                         IkiWiki::printheader($session);
474                         print IkiWiki::misctemplate(gettext(gettext("comment stored for moderation")),
475                                 "<p>".
476                                 gettext("Your comment will be posted after moderator review"),
477                                 "</p>");
478                         exit;
479                 }
480
481                 # FIXME: could probably do some sort of graceful retry
482                 # on error? Would require significant unwinding though
483                 my $file = "$location._comment";
484                 writefile($file, $config{srcdir}, $content);
485
486                 my $conflict;
487
488                 if ($config{rcs} and $config{comments_commit}) {
489                         my $message = gettext("Added a comment");
490                         if (defined $form->field('subject') &&
491                                 length $form->field('subject')) {
492                                 $message = sprintf(
493                                         gettext("Added a comment: %s"),
494                                         $form->field('subject'));
495                         }
496
497                         IkiWiki::rcs_add($file);
498                         IkiWiki::disable_commit_hook();
499                         $conflict = IkiWiki::rcs_commit_staged($message,
500                                 $session->param('name'), $ENV{REMOTE_ADDR});
501                         IkiWiki::enable_commit_hook();
502                         IkiWiki::rcs_update();
503                 }
504
505                 # Now we need a refresh
506                 require IkiWiki::Render;
507                 IkiWiki::refresh();
508                 IkiWiki::saveindex();
509
510                 # this should never happen, unless a committer deliberately
511                 # breaks it or something
512                 error($conflict) if defined $conflict;
513
514                 # Jump to the new comment on the page.
515                 # The trailing question mark tries to avoid broken
516                 # caches and get the most recent version of the page.
517                 IkiWiki::redirect($cgi, urlto($page, undef, 1)."?updated#$location");
518
519         }
520         else {
521                 IkiWiki::showform ($form, \@buttons, $session, $cgi,
522                         forcebaseurl => $baseurl);
523         }
524
525         exit;
526 }
527
528 sub commentmoderation ($$) {
529         my $cgi=shift;
530         my $session=shift;
531
532         IkiWiki::needsignin($cgi, $session);
533         if (! IkiWiki::is_admin($session->param("name"))) {
534                 error(gettext("you are not logged in as an admin"));
535         }
536
537         IkiWiki::decode_cgi_utf8($cgi);
538         
539         if (defined $cgi->param('sid')) {
540                 IkiWiki::checksessionexpiry($cgi, $session);
541
542                 my %vars=$cgi->Vars;
543                 my $added=0;
544                 foreach my $id (keys %vars) {
545                         if ($id =~ /(.*)\Q._comment\E$/) {
546                                 my $action=$cgi->param($id);
547                                 next if $action eq 'Defer';
548
549                                 # Make sure that the id is of a legal
550                                 # pending comment before untainting.
551                                 my ($f)= $id =~ /$config{wiki_file_regexp}/;
552                                 if (! defined $f || ! length $f ||
553                                     IkiWiki::file_pruned($f, $config{srcdir})) {
554                                         error("illegal file");
555                                 }
556
557                                 my $page=IkiWiki::possibly_foolish_untaint(IkiWiki::dirname($1));
558                                 my $file="$config{wikistatedir}/comments_pending/".
559                                         IkiWiki::possibly_foolish_untaint($id);
560
561                                 if ($action eq 'Accept') {
562                                         my $content=eval { readfile($file) };
563                                         next if $@; # file vanished since form was displayed
564                                         my $dest=unique_comment_location($page, $config{srcdir})."._comment";
565                                         writefile($dest, $config{srcdir}, $content);
566                                         if ($config{rcs} and $config{comments_commit}) {
567                                                 IkiWiki::rcs_add($dest);
568                                         }
569                                         $added++;
570                                 }
571
572                                 # This removes empty subdirs, so the
573                                 # .ikiwiki/comments_pending dir will
574                                 # go away when all are moderated.
575                                 require IkiWiki::Render;
576                                 IkiWiki::prune($file);
577                         }
578                 }
579
580                 if ($added) {
581                         my $conflict;
582                         if ($config{rcs} and $config{comments_commit}) {
583                                 my $message = gettext("Comment moderation");
584                                 IkiWiki::disable_commit_hook();
585                                 $conflict=IkiWiki::rcs_commit_staged($message,
586                                         $session->param('name'), $ENV{REMOTE_ADDR});
587                                 IkiWiki::enable_commit_hook();
588                                 IkiWiki::rcs_update();
589                         }
590                 
591                         # Now we need a refresh
592                         require IkiWiki::Render;
593                         IkiWiki::refresh();
594                         IkiWiki::saveindex();
595                 
596                         error($conflict) if defined $conflict;
597                 }
598         }
599
600         my @comments=map {
601                 my $id=$_;
602                 my $file="$config{wikistatedir}/comments_pending/$id";
603                 my $content=readfile($file);
604                 my $ctime=(stat($file))[10];
605                 {
606                         id => $id,
607                         view => previewcomment($content, $id,
608                                         IkiWiki::dirname($_), $ctime),
609                 } 
610         } comments_pending();
611
612         my $template=template("commentmoderation.tmpl");
613         $template->param(
614                 sid => $session->id,
615                 comments => \@comments,
616         );
617         IkiWiki::printheader($session);
618         print IkiWiki::misctemplate(gettext("comment moderation"), $template->output);
619         exit;
620 }
621
622 sub formbuilder_setup (@) {
623         my %params=@_;
624
625         my $form=$params{form};
626         if ($form->title eq "preferences") {
627                 push @{$params{buttons}}, "Comment Moderation";
628                 if ($form->submitted && $form->submitted eq "Comment Moderation") {
629                         commentmoderation($params{cgi}, $params{session});
630                 }
631         }
632 }
633
634 sub comments_pending () {
635         my $dir="$config{wikistatedir}/comments_pending/";
636         return unless -d $dir;
637
638         my @ret;
639         eval q{use File::Find};
640         error($@) if $@;
641         find({
642                 no_chdir => 1,
643                 wanted => sub {
644                         $_=decode_utf8($_);
645                         if (IkiWiki::file_pruned($_, $dir)) {
646                                 $File::Find::prune=1;
647                         }
648                         elsif (! -l $_ && ! -d _) {
649                                 $File::Find::prune=0;
650                                 my ($f)=/$config{wiki_file_regexp}/; # untaint
651                                 if (defined $f && $f =~ /\Q._comment\E$/) {
652                                         $f=~s/^\Q$dir\E\/?//;
653                                         push @ret, $f;
654                                 }
655                         }
656                 }
657         }, $dir);
658
659         return @ret;
660 }
661
662 sub previewcomment ($$$) {
663         my $content=shift;
664         my $location=shift;
665         my $page=shift;
666         my $time=shift;
667
668         my $preview = IkiWiki::htmlize($location, $page, '_comment',
669                         IkiWiki::linkify($location, $page,
670                                 IkiWiki::preprocess($location, $page,
671                                         IkiWiki::filter($location,
672                                                 $page, $content),
673                                         0, 1)));
674         IkiWiki::run_hooks(format => sub {
675                         $preview = shift->(page => $page,
676                                 content => $preview);
677                 });
678
679         my $template = template("comment.tmpl");
680         $template->param(content => $preview);
681         $template->param(ctime => displaytime($time));
682
683         IkiWiki::run_hooks(pagetemplate => sub {
684                 shift->(page => $location,
685                         destpage => $page,
686                         template => $template);
687         });
688
689         $template->param(have_actions => 0);
690
691         return $template->output;
692 }
693
694 sub commentsshown ($) {
695         my $page=shift;
696
697         return ! pagespec_match($page, "*/$config{comments_pagename}*",
698                                 location => $page) &&
699                pagespec_match($page, $config{comments_pagespec},
700                               location => $page);
701 }
702
703 sub commentsopen ($) {
704         my $page = shift;
705
706         return length $config{cgiurl} > 0 &&
707                (! length $config{comments_closed_pagespec} ||
708                 ! pagespec_match($page, $config{comments_closed_pagespec},
709                                  location => $page));
710 }
711
712 sub pagetemplate (@) {
713         my %params = @_;
714
715         my $page = $params{page};
716         my $template = $params{template};
717         my $shown = ($template->query(name => 'commentslink') ||
718                      $template->query(name => 'commentsurl') ||
719                      $template->query(name => 'atomcommentsurl') ||
720                      $template->query(name => 'comments')) &&
721                     commentsshown($page);
722
723         if ($template->query(name => 'comments')) {
724                 my $comments = undef;
725                 if ($shown) {
726                         $comments = IkiWiki::preprocess_inline(
727                                 pages => "internal($page/$config{comments_pagename}*)",
728                                 template => 'comment',
729                                 show => 0,
730                                 reverse => 'yes',
731                                 page => $page,
732                                 destpage => $params{destpage},
733                                 feedfile => 'comments',
734                                 emptyfeeds => 'no',
735                         );
736                 }
737
738                 if (defined $comments && length $comments) {
739                         $template->param(comments => $comments);
740                 }
741
742                 if ($shown && commentsopen($page)) {
743                         my $addcommenturl = IkiWiki::cgiurl(do => 'comment',
744                                 page => $page);
745                         $template->param(addcommenturl => $addcommenturl);
746                 }
747         }
748
749         if ($template->query(name => 'commentsurl')) {
750                 if ($shown) {
751                         $template->param(commentsurl =>
752                                 urlto($page, undef, 1).'#comments');
753                 }
754         }
755
756         if ($template->query(name => 'atomcommentsurl') && $config{usedirs}) {
757                 if ($shown) {
758                         # This will 404 until there are some comments, but I
759                         # think that's probably OK...
760                         $template->param(atomcommentsurl =>
761                                 urlto($page, undef, 1).'comments.atom');
762                 }
763         }
764
765         if ($template->query(name => 'commentslink')) {
766                 # XXX Would be nice to say how many comments there are in
767                 # the link. But, to update the number, blog pages
768                 # would have to update whenever comments of any inlines
769                 # page are added, which is not currently done.
770                 if ($shown) {
771                         $template->param(commentslink =>
772                                 htmllink($page, $params{destpage}, $page,
773                                         linktext => gettext("Comments"),
774                                         anchor => "comments",
775                                         noimageinline => 1));
776                 }
777         }
778
779         # everything below this point is only relevant to the comments
780         # themselves
781         if (!exists $commentstate{$page}) {
782                 return;
783         }
784
785         if ($template->query(name => 'commentuser')) {
786                 $template->param(commentuser =>
787                         $commentstate{$page}{commentuser});
788         }
789
790         if ($template->query(name => 'commentopenid')) {
791                 $template->param(commentopenid =>
792                         $commentstate{$page}{commentopenid});
793         }
794
795         if ($template->query(name => 'commentip')) {
796                 $template->param(commentip =>
797                         $commentstate{$page}{commentip});
798         }
799
800         if ($template->query(name => 'commentauthor')) {
801                 $template->param(commentauthor =>
802                         $commentstate{$page}{commentauthor});
803         }
804
805         if ($template->query(name => 'commentauthorurl')) {
806                 $template->param(commentauthorurl =>
807                         $commentstate{$page}{commentauthorurl});
808         }
809
810         if ($template->query(name => 'removeurl') &&
811             IkiWiki::Plugin::remove->can("check_canremove") &&
812             length $config{cgiurl}) {
813                 $template->param(removeurl => IkiWiki::cgiurl(do => 'remove',
814                         page => $page));
815                 $template->param(have_actions => 1);
816         }
817 }
818
819 sub unique_comment_location ($) {
820         my $page=shift;
821         my $dir=shift;
822
823         my $location;
824         my $i = 0;
825         do {
826                 $i++;
827                 $location = "$page/$config{comments_pagename}$i";
828         } while (-e "$dir/$location._comment");
829
830         return $location;
831 }
832
833 package IkiWiki::PageSpec;
834
835 sub match_postcomment ($$;@) {
836         my $page = shift;
837         my $glob = shift;
838
839         if (! $postcomment) {
840                 return IkiWiki::FailReason->new("not posting a comment");
841         }
842         return match_glob($page, $glob);
843 }
844
845 1