]> git.vanrenterghem.biz Git - git.ikiwiki.info.git/blob - IkiWiki/Plugin/comments.pm
46e1b268f1c2f503890ef17194728935112faef4
[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 rel="nofollow" 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) };
201                 if (defined $oiduser) {
202                         # looks like an OpenID
203                         $commentauthorurl = $commentuser;
204                         $commentauthor = (defined $params{nickname} && length $params{nickname}) ? $params{nickname} : $oiduser;
205                         $commentopenid = $commentuser;
206                 }
207                 else {
208                         my $emailuser = IkiWiki::emailuser($commentuser);
209                         if (defined $emailuser) {
210                                 $commentuser=$emailuser;
211                         }
213                         if (length $config{cgiurl}) {
214                                 $commentauthorurl = IkiWiki::cgiurl(
215                                         do => 'goto',
216                                         page => IkiWiki::userpage($commentuser)
217                                 );
218                         }
220                         $commentauthor = $commentuser;
221                 }
222         }
223         else {
224                 if (defined $params{ip}) {
225                         $commentip = $params{ip};
226                 }
227                 $commentauthor = gettext("Anonymous");
228         }
230         if ($config{comments_allowauthor}) {
231                 if (defined $params{claimedauthor}) {
232                         $commentauthor = $params{claimedauthor};
233                 }
235                 if (defined $params{url}) {
236                         my $url=$params{url};
238                         eval q{use URI::Heuristic}; 
239                         if (! $@) {
240                                 $url=URI::Heuristic::uf_uristr($url);
241                         }
243                         if (safeurl($url)) {
244                                 $commentauthorurl = $url;
245                         }
246                 }
247         }
249         $commentstate{$page}{commentuser} = $commentuser;
250         $commentstate{$page}{commentopenid} = $commentopenid;
251         $commentstate{$page}{commentip} = $commentip;
252         $commentstate{$page}{commentauthor} = $commentauthor;
253         $commentstate{$page}{commentauthorurl} = $commentauthorurl;
254         $commentstate{$page}{commentauthoravatar} = $params{avatar};
255         if (! defined $pagestate{$page}{meta}{author}) {
256                 $pagestate{$page}{meta}{author} = $commentauthor;
257         }
258         if (! defined $pagestate{$page}{meta}{authorurl}) {
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 rel="nofollow" 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                                 unless $IkiWiki::hooks{htmlize}{$key}{nocreate};
361                 }
362         }
363         @page_types=sort @page_types;
365         $form->field(name => 'do', type => 'hidden');
366         $form->field(name => 'sid', type => 'hidden', value => $session->id,
367                 force => 1);
368         $form->field(name => 'page', type => 'hidden');
369         $form->field(name => 'subject', type => 'text', size => 72);
370         $form->field(name => 'editcontent', type => 'textarea', rows => 10);
371         $form->field(name => "type", value => $type, force => 1,
372                 type => 'select', options => \@page_types);
374         my $username=$session->param('name');
375         $form->tmpl_param(username => $username);
376                 
377         $form->field(name => "subscribe", type => 'hidden');
378         $form->field(name => "anonsubscribe", type => 'hidden');
379         if (IkiWiki::Plugin::notifyemail->can("subscribe")) {
380                 if (defined $username) {
381                         $form->field(name => "subscribe", type => "checkbox",
382                                 options => [gettext("email replies to me")]);
383                 }
384                 elsif (IkiWiki::Plugin::passwordauth->can("anonuser")) {
385                         $form->field(name => "anonsubscribe", type => "checkbox",
386                                 options => [gettext("email replies to me")]);
387                 }
388         }
390         if ($config{comments_allowauthor} and
391             ! defined $session->param('name')) {
392                 $form->tmpl_param(allowauthor => 1);
393                 $form->field(name => 'author', type => 'text', size => '40');
394                 $form->field(name => 'email', type => 'text', size => '40');
395                 $form->field(name => 'url', type => 'text', size => '40');
396         }
397         else {
398                 $form->tmpl_param(allowauthor => 0);
399                 $form->field(name => 'author', type => 'hidden', value => '',
400                         force => 1);
401                 $form->field(name => 'email', type => 'hidden', value => '',
402                         force => 1);
403                 $form->field(name => 'url', type => 'hidden', value => '',
404                         force => 1);
405         }
407         if (! defined $session->param('name')) {
408                 # Make signinurl work and return here.
409                 $form->tmpl_param(signinurl => IkiWiki::cgiurl(do => 'commentsignin'));
410                 $session->param(postsignin => $ENV{QUERY_STRING});
411                 IkiWiki::cgi_savesession($session);
412         }
414         # The untaint is OK (as in editpage) because we're about to pass
415         # it to file_pruned and wiki_file_regexp anyway.
416         my ($page) = $form->field('page')=~/$config{wiki_file_regexp}/;
417         $page = IkiWiki::possibly_foolish_untaint($page);
418         if (! defined $page || ! length $page ||
419                 IkiWiki::file_pruned($page)) {
420                 error(gettext("bad page name"));
421         }
423         $form->title(sprintf(gettext("commenting on %s"),
424                         IkiWiki::pagetitle(IkiWiki::basename($page))));
426         $form->tmpl_param('helponformattinglink',
427                 htmllink($page, $page, 'ikiwiki/formatting',
428                         noimageinline => 1,
429                         linktext => 'FormattingHelp'),
430                         allowdirectives => $config{allow_directives});
432         if ($form->submitted eq CANCEL) {
433                 # bounce back to the page they wanted to comment on, and exit.
434                 IkiWiki::redirect($cgi, urlto($page));
435                 exit;
436         }
438         if (not exists $pagesources{$page}) {
439                 error(sprintf(gettext(
440                         "page '%s' doesn't exist, so you can't comment"),
441                         $page));
442         }
444         # There's no UI to get here, but someone might construct the URL,
445         # leading to a comment that exists in the repository but isn't
446         # shown
447         if (!pagespec_match($page, $config{comments_pagespec},
448                 location => $page)) {
449                 error(sprintf(gettext(
450                         "comments on page '%s' are not allowed"),
451                         $page));
452         }
454         if (pagespec_match($page, $config{comments_closed_pagespec},
455                 location => $page)) {
456                 error(sprintf(gettext(
457                         "comments on page '%s' are closed"),
458                         $page));
459         }
461         # Set a flag to indicate that we're posting a comment,
462         # so that postcomment() can tell it should match.
463         $postcomment=1;
464         IkiWiki::check_canedit($page, $cgi, $session);
465         $postcomment=0;
467         my $content = "[[!comment format=$type\n";
469         if (defined $session->param('name')) {
470                 my $username = IkiWiki::cloak($session->param('name'));
471                 $username =~ s/"/&quot;/g;
472                 $content .= " username=\"$username\"\n";
473         }
475         if (defined $session->param('nickname')) {
476                 my $nickname = $session->param('nickname');
477                 $nickname =~ s/"/&quot;/g;
478                 $content .= " nickname=\"$nickname\"\n";
479         }
481         if (!(defined $session->param('name') || defined $session->param('nickname')) &&
482                 defined $session->remote_addr()) {
483                 $content .= " ip=\"".IkiWiki::cloak($session->remote_addr())."\"\n";
484         }
486         if ($config{comments_allowauthor}) {
487                 my $author = $form->field('author');
488                 if (defined $author && length $author) {
489                         $author =~ s/"/&quot;/g;
490                         $content .= " claimedauthor=\"$author\"\n";
491                 }
492                 my $url = $form->field('url');
493                 if (defined $url && length $url) {
494                         $url =~ s/"/&quot;/g;
495                         $content .= " url=\"$url\"\n";
496                 }
497         }
499         my $avatar=getavatar($session->param('name'));
500         if (defined $avatar && length $avatar) {
501                 $avatar =~ s/"/&quot;/g;
502                 $content .= " avatar=\"$avatar\"\n";
503         }
505         my $subject = $form->field('subject');
506         if (defined $subject && length $subject) {
507                 $subject =~ s/"/&quot;/g;
508         }
509         else {
510                 $subject = "comment ".(num_comments($page, $config{srcdir}) + 1);
511         }
512         $content .= " subject=\"$subject\"\n";
513         $content .= " date=\"" . commentdate() . "\"\n";
515         my $editcontent = $form->field('editcontent');
516         $editcontent="" if ! defined $editcontent;
517         $editcontent =~ s/\r\n/\n/g;
518         $editcontent =~ s/\r/\n/g;
519         $editcontent =~ s/"/\\"/g;
520         $content .= " content=\"\"\"\n$editcontent\n\"\"\"]]\n";
522         my $location=unique_comment_location($page, $content, $config{srcdir});
524         # This is essentially a simplified version of editpage:
525         # - the user does not control the page that's created, only the parent
526         # - it's always a create operation, never an edit
527         # - this means that conflicts should never happen
528         # - this means that if they do, rocks fall and everyone dies
530         if ($form->submitted eq PREVIEW) {
531                 my $preview=previewcomment($content, $location, $page, time);
532                 IkiWiki::run_hooks(format => sub {
533                         $preview = shift->(page => $page,
534                                 content => $preview);
535                 });
536                 $form->tmpl_param(page_preview => $preview);
537         }
538         else {
539                 $form->tmpl_param(page_preview => "");
540         }
542         if ($form->submitted eq POST_COMMENT && $form->validate) {
543                 IkiWiki::checksessionexpiry($cgi, $session);
545                 if (IkiWiki::Plugin::notifyemail->can("subscribe")) {
546                         my $subspec="comment($page)";
547                         if (defined $username &&
548                             length $form->field("subscribe")) {
549                                 IkiWiki::Plugin::notifyemail::subscribe(
550                                         $username, $subspec);
551                         }
552                         elsif (length $form->field("email") &&
553                                length $form->field("anonsubscribe")) {
554                                 IkiWiki::Plugin::notifyemail::anonsubscribe(
555                                         $form->field("email"), $subspec);
556                         }
557                 }
558                 
559                 $postcomment=1;
560                 my $ok=IkiWiki::check_content(
561                         content => scalar $form->field('editcontent'),
562                         subject => scalar $form->field('subject'),
563                         $config{comments_allowauthor} ? (
564                                 author => scalar $form->field('author'),
565                                 url => scalar $form->field('url'),
566                         ) : (),
567                         page => $location,
568                         cgi => $cgi,
569                         session => $session,
570                         nonfatal => 1,
571                 );
572                 $postcomment=0;
574                 if (! $ok) {
575                         $location=unique_comment_location($page, $content, $IkiWiki::Plugin::transient::transientdir, "._comment_pending");
576                         writefile("$location._comment_pending", $IkiWiki::Plugin::transient::transientdir, $content);
578                         # Refresh so anything that deals with pending
579                         # comments can be updated.
580                         require IkiWiki::Render;
581                         IkiWiki::refresh();
582                         IkiWiki::saveindex();
584                         IkiWiki::printheader($session);
585                         print IkiWiki::cgitemplate($cgi, gettext(gettext("comment stored for moderation")),
586                                 "<p>".
587                                 gettext("Your comment will be posted after moderator review").
588                                 "</p>");
589                         exit;
590                 }
592                 # FIXME: could probably do some sort of graceful retry
593                 # on error? Would require significant unwinding though
594                 my $file = "$location._comment";
595                 writefile($file, $config{srcdir}, $content);
597                 my $conflict;
599                 if ($config{rcs} and $config{comments_commit}) {
600                         my $message = gettext("Added a comment");
601                         if (defined $form->field('subject') &&
602                                 length $form->field('subject')) {
603                                 $message = sprintf(
604                                         gettext("Added a comment: %s"),
605                                         scalar $form->field('subject'));
606                         }
608                         IkiWiki::rcs_add($file);
609                         IkiWiki::disable_commit_hook();
610                         $conflict = IkiWiki::rcs_commit_staged(
611                                 message => $message,
612                                 session => $session,
613                         );
614                         IkiWiki::enable_commit_hook();
615                         IkiWiki::rcs_update();
616                 }
618                 # Now we need a refresh
619                 require IkiWiki::Render;
620                 IkiWiki::refresh();
621                 IkiWiki::saveindex();
623                 # this should never happen, unless a committer deliberately
624                 # breaks it or something
625                 error($conflict) if defined $conflict;
627                 # Jump to the new comment on the page.
628                 # The trailing question mark tries to avoid broken
629                 # caches and get the most recent version of the page.
630                 IkiWiki::redirect($cgi, urlto($page).
631                         "?updated#".page_to_id($location));
633         }
634         else {
635                 IkiWiki::showform($form, \@buttons, $session, $cgi,
636                         page => $page);
637         }
639         exit;
642 sub commentdate () {
643         strftime_utf8('%Y-%m-%dT%H:%M:%SZ', gmtime);
646 sub getavatar ($) {
647         my $user=shift;
648         return undef unless defined $user;
650         my $avatar;
651         eval q{use Libravatar::URL};
652         if (! $@) {
653                 my $oiduser = eval { IkiWiki::openiduser($user) };
654                 my $https=defined $config{url} && $config{url}=~/^https:/;
656                 if (defined $oiduser) {
657                         eval {
658                                 $avatar = libravatar_url(openid => $user, https => $https);
659                         }
660                 }
661                 if (! defined $avatar &&
662                     (my $email = IkiWiki::userinfo_get($user, 'email'))) {
663                         eval {
664                                 $avatar = libravatar_url(email => $email, https => $https);
665                         }
666                 }
667         }
668         return $avatar;
672 sub commentmoderation ($$) {
673         my $cgi=shift;
674         my $session=shift;
676         IkiWiki::needsignin($cgi, $session);
677         if (! IkiWiki::is_admin($session->param("name"))) {
678                 error(gettext("you are not logged in as an admin"));
679         }
681         IkiWiki::decode_cgi_utf8($cgi);
682         
683         if (defined $cgi->param('sid')) {
684                 IkiWiki::checksessionexpiry($cgi, $session);
686                 my $rejectalldefer=$cgi->param('rejectalldefer');
688                 my %vars=$cgi->Vars;
689                 my $added=0;
690                 foreach my $id (keys %vars) {
691                         if ($id =~ /(.*)\._comment(?:_pending)?$/) {
692                                 $id=decode_utf8($id);
693                                 my $action=$cgi->param($id);
694                                 next if $action eq 'Defer' && ! $rejectalldefer;
696                                 # Make sure that the id is of a legal
697                                 # pending comment.
698                                 my ($f) = $id =~ /$config{wiki_file_regexp}/;
699                                 if (! defined $f || ! length $f ||
700                                     IkiWiki::file_pruned($f)) {
701                                         error("illegal file");
702                                 }
704                                 my $page=IkiWiki::dirname($f);
705                                 my $filedir=$IkiWiki::Plugin::transient::transientdir;
706                                 my $file="$filedir/$f";
707                                 if (! -e $file) {
708                                         # old location
709                                         $file="$config{srcdir}/$f";
710                                         $filedir=$config{srcdir};
711                                         if (! -e $file) {
712                                                 # older location
713                                                 $file="$config{wikistatedir}/comments_pending/".$f;
714                                                 $filedir="$config{wikistatedir}/comments_pending";
715                                         }
716                                 }
718                                 if ($action eq 'Accept') {
719                                         my $content=eval { readfile($file) };
720                                         next if $@; # file vanished since form was displayed
721                                         my $dest=unique_comment_location($page, $content, $config{srcdir})."._comment";
722                                         writefile($dest, $config{srcdir}, $content);
723                                         if ($config{rcs} and $config{comments_commit}) {
724                                                 IkiWiki::rcs_add($dest);
725                                         }
726                                         $added++;
727                                 }
729                                 require IkiWiki::Render;
730                                 IkiWiki::prune($file, $filedir);
731                         }
732                 }
734                 if ($added) {
735                         my $conflict;
736                         if ($config{rcs} and $config{comments_commit}) {
737                                 my $message = gettext("Comment moderation");
738                                 IkiWiki::disable_commit_hook();
739                                 $conflict=IkiWiki::rcs_commit_staged(
740                                         message => $message,
741                                         session => $session,
742                                 );
743                                 IkiWiki::enable_commit_hook();
744                                 IkiWiki::rcs_update();
745                         }
746                 
747                         # Now we need a refresh
748                         require IkiWiki::Render;
749                         IkiWiki::refresh();
750                         IkiWiki::saveindex();
751                 
752                         error($conflict) if defined $conflict;
753                 }
754         }
756         my @comments=map {
757                 my ($id, $dir, $ctime)=@{$_};
758                 my $content=readfile("$dir/$id");
759                 my $preview=previewcomment($content, $id,
760                         $id, $ctime);
761                 {
762                         id => $id,
763                         view => $preview,
764                 }
765         } sort { $b->[2] <=> $a->[2] } comments_pending();
767         my $template=template("commentmoderation.tmpl");
768         $template->param(
769                 sid => $session->id,
770                 comments => \@comments,
771                 cgiurl => IkiWiki::cgiurl(),
772         );
773         IkiWiki::printheader($session);
774         my $out=$template->output;
775         IkiWiki::run_hooks(format => sub {
776                 $out = shift->(page => "", content => $out);
777         });
778         print IkiWiki::cgitemplate($cgi, gettext("comment moderation"), $out);
779         exit;
782 sub formbuilder_setup (@) {
783         my %params=@_;
785         my $form=$params{form};
786         if ($form->title eq "preferences" &&
787             IkiWiki::is_admin($params{session}->param("name"))) {
788                 push @{$params{buttons}}, "Comment Moderation";
789                 if ($form->submitted && $form->submitted eq "Comment Moderation") {
790                         commentmoderation($params{cgi}, $params{session});
791                 }
792         }
795 sub comments_pending () {
796         my @ret;
798         eval q{use File::Find};
799         error($@) if $@;
800         eval q{use Cwd};
801         error($@) if $@;
802         my $origdir=getcwd();
804         my $find_comments=sub {
805                 my $dir=shift;
806                 my $extension=shift;
807                 return unless -d $dir;
809                 chdir($dir) || die "chdir $dir: $!";
811                 find({
812                         no_chdir => 1,
813                         wanted => sub {
814                                 my $file=decode_utf8($_);
815                                 $file=~s/^\.\///;
816                                 return if ! length $file || IkiWiki::file_pruned($file)
817                                         || -l $_ || -d _ || $file !~ /\Q$extension\E$/;
818                                 my ($f) = $file =~ /$config{wiki_file_regexp}/; # untaint
819                                 if (defined $f) {
820                                         my $ctime=(stat($_))[10];
821                                         push @ret, [$f, $dir, $ctime];
822                                 }
823                         }
824                 }, ".");
826                 chdir($origdir) || die "chdir $origdir: $!";
827         };
828         
829         $find_comments->($IkiWiki::Plugin::transient::transientdir, "._comment_pending");
830         # old location
831         $find_comments->($config{srcdir}, "._comment_pending");
832         # old location
833         $find_comments->("$config{wikistatedir}/comments_pending/",
834                 "._comment");
836         return @ret;
839 sub previewcomment ($$$) {
840         my $content=shift;
841         my $location=shift;
842         my $page=shift;
843         my $time=shift;
845         # Previewing a comment should implicitly enable comment posting mode.
846         my $oldpostcomment=$postcomment;
847         $postcomment=1;
849         my $preview = IkiWiki::htmlize($location, $page, '_comment',
850                         IkiWiki::linkify($location, $page,
851                         IkiWiki::preprocess($location, $page,
852                         IkiWiki::filter($location, $page, $content), 0, 1)));
854         my $template = template("comment.tmpl");
855         $template->param(content => $preview);
856         $template->param(ctime => displaytime($time, undef, 1));
857         $template->param(html5 => $config{html5});
859         IkiWiki::run_hooks(pagetemplate => sub {
860                 shift->(page => $location,
861                         destpage => $page,
862                         template => $template);
863         });
865         $template->param(have_actions => 0);
867         $postcomment=$oldpostcomment;
869         return $template->output;
872 sub commentsshown ($) {
873         my $page=shift;
875         return pagespec_match($page, $config{comments_pagespec},
876                 location => $page);
879 sub commentsopen ($) {
880         my $page = shift;
882         return length $config{cgiurl} > 0 &&
883                (! length $config{comments_closed_pagespec} ||
884                 ! pagespec_match($page, $config{comments_closed_pagespec},
885                                  location => $page));
888 sub pagetemplate (@) {
889         my %params = @_;
891         my $page = $params{page};
892         my $template = $params{template};
893         my $shown = ($template->query(name => 'commentslink') ||
894                      $template->query(name => 'commentsurl') ||
895                      $template->query(name => 'atomcommentsurl') ||
896                      $template->query(name => 'comments')) &&
897                     commentsshown($page);
899         if ($template->query(name => 'comments')) {
900                 my $comments = undef;
901                 if ($shown) {
902                         $comments = IkiWiki::preprocess_inline(
903                                 pages => "comment($page) and !comment($page/*)",
904                                 template => 'comment',
905                                 show => 0,
906                                 reverse => 'yes',
907                                 page => $page,
908                                 destpage => $params{destpage},
909                                 feedfile => 'comments',
910                                 emptyfeeds => 'no',
911                         );
912                 }
914                 if (defined $comments && length $comments) {
915                         $template->param(comments => $comments);
916                 }
918                 if ($shown && commentsopen($page)) {
919                         $template->param(addcommenturl => addcommenturl($page));
920                 }
921         }
923         if ($shown) {
924                 my $absolute = $template->param('wants_absolute_urls');
926                 if ($template->query(name => 'commentsurl')) {
927                         $template->param(commentsurl =>
928                                 urlto($page, undef, $absolute).'#comments');
929                 }
931                 if ($template->query(name => 'atomcommentsurl') && $config{usedirs}) {
932                         # This will 404 until there are some comments, but I
933                         # think that's probably OK...
934                         $template->param(atomcommentsurl =>
935                                 urlto($page, undef, $absolute).'comments.atom');
936                 }
938                 if ($template->query(name => 'commentslink')) {
939                         my $num=num_comments($page, $config{srcdir});
940                         my $link;
941                         if ($num > 0) {
942                                 $link = htmllink($page, $params{destpage}, $page,
943                                         linktext => sprintf(ngettext("%i comment", "%i comments", $num), $num),
944                                         anchor => "comments",
945                                         noimageinline => 1
946                                 );
947                         }
948                         elsif (commentsopen($page)) {
949                                 $link = "<a rel=\"nofollow\" href=\"".addcommenturl($page)."\">".
950                                         #translators: Here "Comment" is a verb;
951                                         #translators: the user clicks on it to
952                                         #translators: post a comment.
953                                         gettext("Comment").
954                                         "</a>";
955                         }
956                         $template->param(commentslink => $link)
957                                 if defined $link;
958                 }
959         }
961         # everything below this point is only relevant to the comments
962         # themselves
963         if (!exists $commentstate{$page}) {
964                 return;
965         }
966         
967         if ($template->query(name => 'commentid')) {
968                 $template->param(commentid => page_to_id($page));
969         }
971         if ($template->query(name => 'commentuser')) {
972                 $template->param(commentuser =>
973                         $commentstate{$page}{commentuser});
974         }
976         if ($template->query(name => 'commentopenid')) {
977                 $template->param(commentopenid =>
978                         $commentstate{$page}{commentopenid});
979         }
981         if ($template->query(name => 'commentip')) {
982                 $template->param(commentip =>
983                         $commentstate{$page}{commentip});
984         }
986         if ($template->query(name => 'commentauthor')) {
987                 $template->param(commentauthor =>
988                         $commentstate{$page}{commentauthor});
989         }
991         if ($template->query(name => 'commentauthorurl')) {
992                 $template->param(commentauthorurl =>
993                         $commentstate{$page}{commentauthorurl});
994         }
996         if ($template->query(name => 'commentauthoravatar')) {
997                 $template->param(commentauthoravatar =>
998                         $commentstate{$page}{commentauthoravatar});
999         }
1001         if ($template->query(name => 'removeurl') &&
1002             IkiWiki::Plugin::remove->can("check_canremove") &&
1003             length $config{cgiurl}) {
1004                 $template->param(removeurl => IkiWiki::cgiurl(do => 'remove',
1005                         page => $page));
1006                 $template->param(have_actions => 1);
1007         }
1010 sub addcommenturl ($) {
1011         my $page=shift;
1013         return IkiWiki::cgiurl(do => 'comment', page => $page);
1016 sub num_comments ($$) {
1017         my $page=shift;
1018         my $dir=shift;
1020         my @comments=glob("$dir/$page/$config{comments_pagename}*._comment");
1021         return int @comments;
1024 sub unique_comment_location ($$$;$) {
1025         my $page=shift;
1026         eval q{use Digest::MD5 'md5_hex'};
1027         error($@) if $@;
1028         my $content_md5=md5_hex(Encode::encode_utf8(shift));
1029         my $dir=shift;
1030         my $ext=shift || "._comment";
1032         my $location;
1033         my $i = num_comments($page, $dir);
1034         do {
1035                 $i++;
1036                 $location = "$page/$config{comments_pagename}${i}_${content_md5}";
1037         } while (-e "$dir/$location$ext");
1039         return $location;
1042 sub page_to_id ($) {
1043         # Converts a comment page name into a unique, legal html id
1044         # attribute value, that can be used as an anchor to link to the
1045         # comment.
1046         my $page=shift;
1048         eval q{use Digest::MD5 'md5_hex'};
1049         error($@) if $@;
1051         return "comment-".md5_hex(Encode::encode_utf8(($page)));
1053         
1054 package IkiWiki::PageSpec;
1056 sub match_postcomment ($$;@) {
1057         my $page = shift;
1058         my $glob = shift;
1060         if (! $postcomment) {
1061                 return IkiWiki::FailReason->new("not posting a comment");
1062         }
1063         return match_glob($page, $glob, @_);
1066 sub match_comment ($$;@) {
1067         my $page = shift;
1068         my $glob = shift;
1070         if (! $postcomment) {
1071                 # To see if it's a comment, check the source file type.
1072                 # Deal with comments that were just deleted.
1073                 my $source=exists $IkiWiki::pagesources{$page} ?
1074                         $IkiWiki::pagesources{$page} :
1075                         $IkiWiki::delpagesources{$page};
1076                 my $type=defined $source ? IkiWiki::pagetype($source) : undef;
1077                 if (! defined $type || $type ne "_comment") {
1078                         return IkiWiki::FailReason->new("$page is not a comment");
1079                 }
1080         }
1082         return match_glob($page, "$glob/*", internal => 1, @_);
1085 sub match_comment_pending ($$;@) {
1086         my $page = shift;
1087         my $glob = shift;
1088         
1089         my $source=exists $IkiWiki::pagesources{$page} ?
1090                 $IkiWiki::pagesources{$page} :
1091                 $IkiWiki::delpagesources{$page};
1092         my $type=defined $source ? IkiWiki::pagetype($source) : undef;
1093         if (! defined $type || $type ne "_comment_pending") {
1094                 return IkiWiki::FailReason->new("$page is not a pending comment");
1095         }
1097         return match_glob($page, "$glob/*", internal => 1, @_);