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