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