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