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