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