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