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