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