]> git.vanrenterghem.biz Git - git.ikiwiki.info.git/blob - IkiWiki/Plugin/comments.pm
rename hash and avoid unnecessary hash ref
[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                 $pagestate{$page}{meta}{title} = $params{subject};
225         }
227         if ($params{page} =~ m/\/\Q$config{comments_pagename}\E\d+_/) {
228                 $pagestate{$page}{meta}{permalink} = urlto(IkiWiki::dirname($params{page}), undef, 1).
229                         "#".page_to_id($params{page});
230         }
232         eval q{use Date::Parse};
233         if (! $@) {
234                 my $time = str2time($params{date});
235                 $IkiWiki::pagectime{$page} = $time if defined $time;
236         }
238         return $content;
241 sub sessioncgi ($$) {
242         my $cgi=shift;
243         my $session=shift;
245         my $do = $cgi->param('do');
246         if ($do eq 'comment') {
247                 editcomment($cgi, $session);
248         }
249         elsif ($do eq 'commentmoderation') {
250                 commentmoderation($cgi, $session);
251         }
254 # Mostly cargo-culted from IkiWiki::plugin::editpage
255 sub editcomment ($$) {
256         my $cgi=shift;
257         my $session=shift;
259         IkiWiki::decode_cgi_utf8($cgi);
261         eval q{use CGI::FormBuilder};
262         error($@) if $@;
264         my @buttons = (POST_COMMENT, PREVIEW, CANCEL);
265         my $form = CGI::FormBuilder->new(
266                 fields => [qw{do sid page subject editcontent type author url}],
267                 charset => 'utf-8',
268                 method => 'POST',
269                 required => [qw{editcontent}],
270                 javascript => 0,
271                 params => $cgi,
272                 action => $config{cgiurl},
273                 header => 0,
274                 table => 0,
275                 template => scalar IkiWiki::template_params('editcomment.tmpl'),
276         );
278         IkiWiki::decode_form_utf8($form);
279         IkiWiki::run_hooks(formbuilder_setup => sub {
280                         shift->(title => "comment", form => $form, cgi => $cgi,
281                                 session => $session, buttons => \@buttons);
282                 });
283         IkiWiki::decode_form_utf8($form);
285         my $type = $form->param('type');
286         if (defined $type && length $type && $IkiWiki::hooks{htmlize}{$type}) {
287                 $type = IkiWiki::possibly_foolish_untaint($type);
288         }
289         else {
290                 $type = $config{default_pageext};
291         }
294         my @page_types;
295         if (exists $IkiWiki::hooks{htmlize}) {
296                 foreach my $key (grep { !/^_/ } keys %{$IkiWiki::hooks{htmlize}}) {
297                         push @page_types, [$key, $IkiWiki::hooks{htmlize}{$key}{longname} || $key];
298                 }
299         }
300         @page_types=sort @page_types;
302         $form->field(name => 'do', type => 'hidden');
303         $form->field(name => 'sid', type => 'hidden', value => $session->id,
304                 force => 1);
305         $form->field(name => 'page', type => 'hidden');
306         $form->field(name => 'subject', type => 'text', size => 72);
307         $form->field(name => 'editcontent', type => 'textarea', rows => 10);
308         $form->field(name => "type", value => $type, force => 1,
309                 type => 'select', options => \@page_types);
311         $form->tmpl_param(username => $session->param('name'));
313         if ($config{comments_allowauthor} and
314             ! defined $session->param('name')) {
315                 $form->tmpl_param(allowauthor => 1);
316                 $form->field(name => 'author', type => 'text', size => '40');
317                 $form->field(name => 'url', type => 'text', size => '40');
318         }
319         else {
320                 $form->tmpl_param(allowauthor => 0);
321                 $form->field(name => 'author', type => 'hidden', value => '',
322                         force => 1);
323                 $form->field(name => 'url', type => 'hidden', value => '',
324                         force => 1);
325         }
327         if (! defined $session->param('name')) {
328                 # Make signinurl work and return here.
329                 $form->tmpl_param(signinurl => IkiWiki::cgiurl(do => 'signin'));
330                 $session->param(postsignin => $ENV{QUERY_STRING});
331                 IkiWiki::cgi_savesession($session);
332         }
334         # The untaint is OK (as in editpage) because we're about to pass
335         # it to file_pruned anyway
336         my $page = $form->field('page');
337         $page = IkiWiki::possibly_foolish_untaint($page);
338         if (! defined $page || ! length $page ||
339                 IkiWiki::file_pruned($page, $config{srcdir})) {
340                 error(gettext("bad page name"));
341         }
343         my $baseurl = urlto($page, undef, 1);
345         $form->title(sprintf(gettext("commenting on %s"),
346                         IkiWiki::pagetitle($page)));
348         $form->tmpl_param('helponformattinglink',
349                 htmllink($page, $page, 'ikiwiki/formatting',
350                         noimageinline => 1,
351                         linktext => 'FormattingHelp'),
352                         allowdirectives => $config{allow_directives});
354         if ($form->submitted eq CANCEL) {
355                 # bounce back to the page they wanted to comment on, and exit.
356                 # CANCEL need not be considered in future
357                 IkiWiki::redirect($cgi, urlto($page, undef, 1));
358                 exit;
359         }
361         if (not exists $pagesources{$page}) {
362                 error(sprintf(gettext(
363                         "page '%s' doesn't exist, so you can't comment"),
364                         $page));
365         }
367         if (pagespec_match($page, $config{comments_closed_pagespec},
368                 location => $page)) {
369                 error(sprintf(gettext(
370                         "comments on page '%s' are closed"),
371                         $page));
372         }
374         # Set a flag to indicate that we're posting a comment,
375         # so that postcomment() can tell it should match.
376         $postcomment=1;
377         IkiWiki::check_canedit($page, $cgi, $session);
378         $postcomment=0;
380         my $content = "[[!comment format=$type\n";
382         # FIXME: handling of double quotes probably wrong?
383         if (defined $session->param('name')) {
384                 my $username = $session->param('name');
385                 $username =~ s/"/&quot;/g;
386                 $content .= " username=\"$username\"\n";
387         }
388         elsif (defined $ENV{REMOTE_ADDR}) {
389                 my $ip = $ENV{REMOTE_ADDR};
390                 if ($ip =~ m/^([.0-9]+)$/) {
391                         $content .= " ip=\"$1\"\n";
392                 }
393         }
395         if ($config{comments_allowauthor}) {
396                 my $author = $form->field('author');
397                 if (defined $author && length $author) {
398                         $author =~ s/"/&quot;/g;
399                         $content .= " claimedauthor=\"$author\"\n";
400                 }
401                 my $url = $form->field('url');
402                 if (defined $url && length $url) {
403                         $url =~ s/"/&quot;/g;
404                         $content .= " url=\"$url\"\n";
405                 }
406         }
408         my $subject = $form->field('subject');
409         if (defined $subject && length $subject) {
410                 $subject =~ s/"/&quot;/g;
411         }
412         else {
413                 $subject = "comment ".(num_comments($page, $config{srcdir}) + 1);
414         }
415         $content .= " subject=\"$subject\"\n";
417         $content .= " date=\"" . decode_utf8(strftime('%Y-%m-%dT%H:%M:%SZ', gmtime)) . "\"\n";
419         my $editcontent = $form->field('editcontent') || '';
420         $editcontent =~ s/\r\n/\n/g;
421         $editcontent =~ s/\r/\n/g;
422         $editcontent =~ s/"/\\"/g;
423         $content .= " content=\"\"\"\n$editcontent\n\"\"\"]]\n";
425         my $location=unique_comment_location($page, $content, $config{srcdir});
427         # This is essentially a simplified version of editpage:
428         # - the user does not control the page that's created, only the parent
429         # - it's always a create operation, never an edit
430         # - this means that conflicts should never happen
431         # - this means that if they do, rocks fall and everyone dies
433         if ($form->submitted eq PREVIEW) {
434                 my $preview=previewcomment($content, $location, $page, time);
435                 IkiWiki::run_hooks(format => sub {
436                         $preview = shift->(page => $page,
437                                 content => $preview);
438                 });
439                 $form->tmpl_param(page_preview => $preview);
440         }
441         else {
442                 $form->tmpl_param(page_preview => "");
443         }
445         if ($form->submitted eq POST_COMMENT && $form->validate) {
446                 IkiWiki::checksessionexpiry($cgi, $session);
447                 
448                 $postcomment=1;
449                 my $ok=IkiWiki::check_content(content => $form->field('editcontent'),
450                         subject => $form->field('subject'),
451                         $config{comments_allowauthor} ? (
452                                 author => $form->field('author'),
453                                 url => $form->field('url'),
454                         ) : (),
455                         page => $location,
456                         cgi => $cgi,
457                         session => $session,
458                         nonfatal => 1,
459                 );
460                 $postcomment=0;
462                 if (! $ok) {
463                         my $penddir=$config{wikistatedir}."/comments_pending";
464                         $location=unique_comment_location($page, $content, $penddir);
465                         writefile("$location._comment", $penddir, $content);
466                         IkiWiki::printheader($session);
467                         print IkiWiki::misctemplate(gettext(gettext("comment stored for moderation")),
468                                 "<p>".
469                                 gettext("Your comment will be posted after moderator review").
470                                 "</p>");
471                         exit;
472                 }
474                 # FIXME: could probably do some sort of graceful retry
475                 # on error? Would require significant unwinding though
476                 my $file = "$location._comment";
477                 writefile($file, $config{srcdir}, $content);
479                 my $conflict;
481                 if ($config{rcs} and $config{comments_commit}) {
482                         my $message = gettext("Added a comment");
483                         if (defined $form->field('subject') &&
484                                 length $form->field('subject')) {
485                                 $message = sprintf(
486                                         gettext("Added a comment: %s"),
487                                         $form->field('subject'));
488                         }
490                         IkiWiki::rcs_add($file);
491                         IkiWiki::disable_commit_hook();
492                         $conflict = IkiWiki::rcs_commit_staged($message,
493                                 $session->param('name'), $ENV{REMOTE_ADDR});
494                         IkiWiki::enable_commit_hook();
495                         IkiWiki::rcs_update();
496                 }
498                 # Now we need a refresh
499                 require IkiWiki::Render;
500                 IkiWiki::refresh();
501                 IkiWiki::saveindex();
503                 # this should never happen, unless a committer deliberately
504                 # breaks it or something
505                 error($conflict) if defined $conflict;
507                 # Jump to the new comment on the page.
508                 # The trailing question mark tries to avoid broken
509                 # caches and get the most recent version of the page.
510                 IkiWiki::redirect($cgi, urlto($page, undef, 1).
511                         "?updated#".page_to_id($location));
513         }
514         else {
515                 IkiWiki::showform ($form, \@buttons, $session, $cgi,
516                         forcebaseurl => $baseurl);
517         }
519         exit;
522 sub commentmoderation ($$) {
523         my $cgi=shift;
524         my $session=shift;
526         IkiWiki::needsignin($cgi, $session);
527         if (! IkiWiki::is_admin($session->param("name"))) {
528                 error(gettext("you are not logged in as an admin"));
529         }
531         IkiWiki::decode_cgi_utf8($cgi);
532         
533         if (defined $cgi->param('sid')) {
534                 IkiWiki::checksessionexpiry($cgi, $session);
536                 my $rejectalldefer=$cgi->param('rejectalldefer');
538                 my %vars=$cgi->Vars;
539                 my $added=0;
540                 foreach my $id (keys %vars) {
541                         if ($id =~ /(.*)\Q._comment\E$/) {
542                                 my $action=$cgi->param($id);
543                                 next if $action eq 'Defer' && ! $rejectalldefer;
545                                 # Make sure that the id is of a legal
546                                 # pending comment before untainting.
547                                 my ($f)= $id =~ /$config{wiki_file_regexp}/;
548                                 if (! defined $f || ! length $f ||
549                                     IkiWiki::file_pruned($f, $config{srcdir})) {
550                                         error("illegal file");
551                                 }
553                                 my $page=IkiWiki::possibly_foolish_untaint(IkiWiki::dirname($1));
554                                 my $file="$config{wikistatedir}/comments_pending/".
555                                         IkiWiki::possibly_foolish_untaint($id);
557                                 if ($action eq 'Accept') {
558                                         my $content=eval { readfile($file) };
559                                         next if $@; # file vanished since form was displayed
560                                         my $dest=unique_comment_location($page, $content, $config{srcdir})."._comment";
561                                         writefile($dest, $config{srcdir}, $content);
562                                         if ($config{rcs} and $config{comments_commit}) {
563                                                 IkiWiki::rcs_add($dest);
564                                         }
565                                         $added++;
566                                 }
568                                 # This removes empty subdirs, so the
569                                 # .ikiwiki/comments_pending dir will
570                                 # go away when all are moderated.
571                                 require IkiWiki::Render;
572                                 IkiWiki::prune($file);
573                         }
574                 }
576                 if ($added) {
577                         my $conflict;
578                         if ($config{rcs} and $config{comments_commit}) {
579                                 my $message = gettext("Comment moderation");
580                                 IkiWiki::disable_commit_hook();
581                                 $conflict=IkiWiki::rcs_commit_staged($message,
582                                         $session->param('name'), $ENV{REMOTE_ADDR});
583                                 IkiWiki::enable_commit_hook();
584                                 IkiWiki::rcs_update();
585                         }
586                 
587                         # Now we need a refresh
588                         require IkiWiki::Render;
589                         IkiWiki::refresh();
590                         IkiWiki::saveindex();
591                 
592                         error($conflict) if defined $conflict;
593                 }
594         }
596         my @comments=map {
597                 my ($id, $ctime)=@{$_};
598                 my $file="$config{wikistatedir}/comments_pending/$id";
599                 my $content=readfile($file);
600                 my $preview=previewcomment($content, $id,
601                         IkiWiki::dirname($_), $ctime);
602                 {
603                         id => $id,
604                         view => $preview,
605                 } 
606         } sort { $b->[1] <=> $a->[1] } comments_pending();
608         my $template=template("commentmoderation.tmpl");
609         $template->param(
610                 sid => $session->id,
611                 comments => \@comments,
612         );
613         IkiWiki::printheader($session);
614         my $out=$template->output;
615         IkiWiki::run_hooks(format => sub {
616                 $out = shift->(page => "", content => $out);
617         });
618         print IkiWiki::misctemplate(gettext("comment moderation"), $out);
619         exit;
622 sub formbuilder_setup (@) {
623         my %params=@_;
625         my $form=$params{form};
626         if ($form->title eq "preferences" &&
627             IkiWiki::is_admin($params{session}->param("name"))) {
628                 push @{$params{buttons}}, "Comment Moderation";
629                 if ($form->submitted && $form->submitted eq "Comment Moderation") {
630                         commentmoderation($params{cgi}, $params{session});
631                 }
632         }
635 sub comments_pending () {
636         my $dir="$config{wikistatedir}/comments_pending/";
637         return unless -d $dir;
639         my @ret;
640         eval q{use File::Find};
641         error($@) if $@;
642         find({
643                 no_chdir => 1,
644                 wanted => sub {
645                         $_=decode_utf8($_);
646                         if (IkiWiki::file_pruned($_, $dir)) {
647                                 $File::Find::prune=1;
648                         }
649                         elsif (! -l $_ && ! -d _) {
650                                 $File::Find::prune=0;
651                                 my ($f)=/$config{wiki_file_regexp}/; # untaint
652                                 if (defined $f && $f =~ /\Q._comment\E$/) {
653                                         my $ctime=(stat($f))[10];
654                                         $f=~s/^\Q$dir\E\/?//;
655                                         push @ret, [$f, $ctime];
656                                 }
657                         }
658                 }
659         }, $dir);
661         return @ret;
664 sub previewcomment ($$$) {
665         my $content=shift;
666         my $location=shift;
667         my $page=shift;
668         my $time=shift;
670         my $preview = IkiWiki::htmlize($location, $page, '_comment',
671                         IkiWiki::linkify($location, $page,
672                         IkiWiki::preprocess($location, $page,
673                         IkiWiki::filter($location, $page, $content), 0, 1)));
675         my $template = template("comment.tmpl");
676         $template->param(content => $preview);
677         $template->param(ctime => displaytime($time));
679         IkiWiki::run_hooks(pagetemplate => sub {
680                 shift->(page => $location,
681                         destpage => $page,
682                         template => $template);
683         });
685         $template->param(have_actions => 0);
687         return $template->output;
690 sub commentsshown ($) {
691         my $page=shift;
693         return ! pagespec_match($page, "internal(*/$config{comments_pagename}*)",
694                                 location => $page) &&
695                pagespec_match($page, $config{comments_pagespec},
696                               location => $page);
699 sub commentsopen ($) {
700         my $page = shift;
702         return length $config{cgiurl} > 0 &&
703                (! length $config{comments_closed_pagespec} ||
704                 ! pagespec_match($page, $config{comments_closed_pagespec},
705                                  location => $page));
708 sub pagetemplate (@) {
709         my %params = @_;
711         my $page = $params{page};
712         my $template = $params{template};
713         my $shown = ($template->query(name => 'commentslink') ||
714                      $template->query(name => 'commentsurl') ||
715                      $template->query(name => 'atomcommentsurl') ||
716                      $template->query(name => 'comments')) &&
717                     commentsshown($page);
719         if ($template->query(name => 'comments')) {
720                 my $comments = undef;
721                 if ($shown) {
722                         $comments = IkiWiki::preprocess_inline(
723                                 pages => "internal($page/$config{comments_pagename}*)",
724                                 template => 'comment',
725                                 show => 0,
726                                 reverse => 'yes',
727                                 page => $page,
728                                 destpage => $params{destpage},
729                                 feedfile => 'comments',
730                                 emptyfeeds => 'no',
731                         );
732                 }
734                 if (defined $comments && length $comments) {
735                         $template->param(comments => $comments);
736                 }
738                 if ($shown && commentsopen($page)) {
739                         $template->param(addcommenturl => addcommenturl($page));
740                 }
741         }
743         if ($shown) {
744                 if ($template->query(name => 'commentsurl')) {
745                         $template->param(commentsurl =>
746                                 urlto($page, undef, 1).'#comments');
747                 }
749                 if ($template->query(name => 'atomcommentsurl') && $config{usedirs}) {
750                         # This will 404 until there are some comments, but I
751                         # think that's probably OK...
752                         $template->param(atomcommentsurl =>
753                                 urlto($page, undef, 1).'comments.atom');
754                 }
756                 if ($template->query(name => 'commentslink')) {
757                         my $num=num_comments($page, $config{srcdir});
758                         my $link;
759                         if ($num > 0) {
760                                 $link = htmllink($page, $params{destpage}, $page,
761                                         linktext => sprintf(ngettext("%i comment", "%i comments", $num), $num),
762                                         anchor => "comments",
763                                         noimageinline => 1
764                                 );
765                         }
766                         elsif (commentsopen($page)) {
767                                 $link = "<a href=\"".addcommenturl($page)."\">".
768                                         #translators: Here "Comment" is a verb;
769                                         #translators: the user clicks on it to
770                                         #translators: post a comment.
771                                         gettext("Comment").
772                                         "</a>";
773                         }
774                         $template->param(commentslink => $link)
775                                 if defined $link;
776                 }
777         }
779         # everything below this point is only relevant to the comments
780         # themselves
781         if (!exists $commentstate{$page}) {
782                 return;
783         }
784         
785         if ($template->query(name => 'commentid')) {
786                 $template->param(commentid => page_to_id($page));
787         }
789         if ($template->query(name => 'commentuser')) {
790                 $template->param(commentuser =>
791                         $commentstate{$page}{commentuser});
792         }
794         if ($template->query(name => 'commentopenid')) {
795                 $template->param(commentopenid =>
796                         $commentstate{$page}{commentopenid});
797         }
799         if ($template->query(name => 'commentip')) {
800                 $template->param(commentip =>
801                         $commentstate{$page}{commentip});
802         }
804         if ($template->query(name => 'commentauthor')) {
805                 $template->param(commentauthor =>
806                         $commentstate{$page}{commentauthor});
807         }
809         if ($template->query(name => 'commentauthorurl')) {
810                 $template->param(commentauthorurl =>
811                         $commentstate{$page}{commentauthorurl});
812         }
814         if ($template->query(name => 'removeurl') &&
815             IkiWiki::Plugin::remove->can("check_canremove") &&
816             length $config{cgiurl}) {
817                 $template->param(removeurl => IkiWiki::cgiurl(do => 'remove',
818                         page => $page));
819                 $template->param(have_actions => 1);
820         }
823 sub addcommenturl ($) {
824         my $page=shift;
826         return IkiWiki::cgiurl(do => 'comment', page => $page);
829 sub num_comments ($$) {
830         my $page=shift;
831         my $dir=shift;
833         my @comments=glob("$dir/$page/$config{comments_pagename}*._comment");
834         return @comments;
837 sub unique_comment_location ($$$) {
838         my $page=shift;
840         eval q{use Digest::MD5 'md5_hex'};
841         error($@) if $@;
842         my $content_md5=md5_hex(Encode::encode_utf8(shift));
844         my $dir=shift;
846         my $location;
847         my $i = num_comments($page, $dir);
848         do {
849                 $i++;
850                 $location = "$page/$config{comments_pagename}${i}_${content_md5}";
851         } while (-e "$dir/$location._comment");
853         return $location;
856 sub page_to_id ($) {
857         # Converts a comment page name into a unique, legal html id
858         # attribute value, that can be used as an anchor to link to the
859         # comment.
860         my $page=shift;
862         eval q{use Digest::MD5 'md5_hex'};
863         error($@) if $@;
865         return "comment-".md5_hex(Encode::encode_utf8(($page)));
867         
868 package IkiWiki::PageSpec;
870 sub match_postcomment ($$;@) {
871         my $page = shift;
872         my $glob = shift;
874         if (! $postcomment) {
875                 return IkiWiki::FailReason->new("not posting a comment");
876         }
877         return match_glob($page, $glob);