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