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