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