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