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