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