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