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