]> git.vanrenterghem.biz Git - git.ikiwiki.info.git/blob - IkiWiki/Plugin/comments.pm
trail: don't generate a costly dependency when forcing sort order
[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         if (pagespec_match($page, $config{comments_closed_pagespec},
442                 location => $page)) {
443                 error(sprintf(gettext(
444                         "comments on page '%s' are closed"),
445                         $page));
446         }
448         # Set a flag to indicate that we're posting a comment,
449         # so that postcomment() can tell it should match.
450         $postcomment=1;
451         IkiWiki::check_canedit($page, $cgi, $session);
452         $postcomment=0;
454         my $content = "[[!comment format=$type\n";
456         if (defined $session->param('name')) {
457                 my $username = $session->param('name');
458                 $username =~ s/"/&quot;/g;
459                 $content .= " username=\"$username\"\n";
460         }
461         if (defined $session->param('nickname')) {
462                 my $nickname = $session->param('nickname');
463                 $nickname =~ s/"/&quot;/g;
464                 $content .= " nickname=\"$nickname\"\n";
465         }
466         elsif (defined $session->remote_addr()) {
467                 $content .= " ip=\"".$session->remote_addr()."\"\n";
468         }
470         if ($config{comments_allowauthor}) {
471                 my $author = $form->field('author');
472                 if (defined $author && length $author) {
473                         $author =~ s/"/&quot;/g;
474                         $content .= " claimedauthor=\"$author\"\n";
475                 }
476                 my $url = $form->field('url');
477                 if (defined $url && length $url) {
478                         $url =~ s/"/&quot;/g;
479                         $content .= " url=\"$url\"\n";
480                 }
481         }
483         my $avatar=getavatar($session->param('name'));
484         if (defined $avatar && length $avatar) {
485                 $avatar =~ s/"/&quot;/g;
486                 $content .= " avatar=\"$avatar\"\n";
487         }
489         my $subject = $form->field('subject');
490         if (defined $subject && length $subject) {
491                 $subject =~ s/"/&quot;/g;
492         }
493         else {
494                 $subject = "comment ".(num_comments($page, $config{srcdir}) + 1);
495         }
496         $content .= " subject=\"$subject\"\n";
498         $content .= " date=\"" . strftime_utf8('%Y-%m-%dT%H:%M:%SZ', gmtime) . "\"\n";
500         my $editcontent = $form->field('editcontent');
501         $editcontent="" if ! defined $editcontent;
502         $editcontent =~ s/\r\n/\n/g;
503         $editcontent =~ s/\r/\n/g;
504         $editcontent =~ s/"/\\"/g;
505         $content .= " content=\"\"\"\n$editcontent\n\"\"\"]]\n";
507         my $location=unique_comment_location($page, $content, $config{srcdir});
509         # This is essentially a simplified version of editpage:
510         # - the user does not control the page that's created, only the parent
511         # - it's always a create operation, never an edit
512         # - this means that conflicts should never happen
513         # - this means that if they do, rocks fall and everyone dies
515         if ($form->submitted eq PREVIEW) {
516                 my $preview=previewcomment($content, $location, $page, time);
517                 IkiWiki::run_hooks(format => sub {
518                         $preview = shift->(page => $page,
519                                 content => $preview);
520                 });
521                 $form->tmpl_param(page_preview => $preview);
522         }
523         else {
524                 $form->tmpl_param(page_preview => "");
525         }
527         if ($form->submitted eq POST_COMMENT && $form->validate) {
528                 IkiWiki::checksessionexpiry($cgi, $session);
530                 if (IkiWiki::Plugin::notifyemail->can("subscribe")) {
531                         my $subspec="comment($page)";
532                         if (defined $username &&
533                             length $form->field("subscribe")) {
534                                 IkiWiki::Plugin::notifyemail::subscribe(
535                                         $username, $subspec);
536                         }
537                         elsif (length $form->field("email") &&
538                                length $form->field("anonsubscribe")) {
539                                 IkiWiki::Plugin::notifyemail::anonsubscribe(
540                                         $form->field("email"), $subspec);
541                         }
542                 }
543                 
544                 $postcomment=1;
545                 my $ok=IkiWiki::check_content(content => $form->field('editcontent'),
546                         subject => $form->field('subject'),
547                         $config{comments_allowauthor} ? (
548                                 author => $form->field('author'),
549                                 url => $form->field('url'),
550                         ) : (),
551                         page => $location,
552                         cgi => $cgi,
553                         session => $session,
554                         nonfatal => 1,
555                 );
556                 $postcomment=0;
558                 if (! $ok) {
559                         $location=unique_comment_location($page, $content, $IkiWiki::Plugin::transient::transientdir, "._comment_pending");
560                         writefile("$location._comment_pending", $IkiWiki::Plugin::transient::transientdir, $content);
562                         # Refresh so anything that deals with pending
563                         # comments can be updated.
564                         require IkiWiki::Render;
565                         IkiWiki::refresh();
566                         IkiWiki::saveindex();
568                         IkiWiki::printheader($session);
569                         print IkiWiki::cgitemplate($cgi, gettext(gettext("comment stored for moderation")),
570                                 "<p>".
571                                 gettext("Your comment will be posted after moderator review").
572                                 "</p>");
573                         exit;
574                 }
576                 # FIXME: could probably do some sort of graceful retry
577                 # on error? Would require significant unwinding though
578                 my $file = "$location._comment";
579                 writefile($file, $config{srcdir}, $content);
581                 my $conflict;
583                 if ($config{rcs} and $config{comments_commit}) {
584                         my $message = gettext("Added a comment");
585                         if (defined $form->field('subject') &&
586                                 length $form->field('subject')) {
587                                 $message = sprintf(
588                                         gettext("Added a comment: %s"),
589                                         $form->field('subject'));
590                         }
592                         IkiWiki::rcs_add($file);
593                         IkiWiki::disable_commit_hook();
594                         $conflict = IkiWiki::rcs_commit_staged(
595                                 message => $message,
596                                 session => $session,
597                         );
598                         IkiWiki::enable_commit_hook();
599                         IkiWiki::rcs_update();
600                 }
602                 # Now we need a refresh
603                 require IkiWiki::Render;
604                 IkiWiki::refresh();
605                 IkiWiki::saveindex();
607                 # this should never happen, unless a committer deliberately
608                 # breaks it or something
609                 error($conflict) if defined $conflict;
611                 # Jump to the new comment on the page.
612                 # The trailing question mark tries to avoid broken
613                 # caches and get the most recent version of the page.
614                 IkiWiki::redirect($cgi, urlto($page).
615                         "?updated#".page_to_id($location));
617         }
618         else {
619                 IkiWiki::showform($form, \@buttons, $session, $cgi,
620                         page => $page);
621         }
623         exit;
626 sub getavatar ($) {
627         my $user=shift;
628         return undef unless defined $user;
630         my $avatar;
631         eval q{use Libravatar::URL};
632         if (! $@) {
633                 my $oiduser = eval { IkiWiki::openiduser($user) };
634                 my $https=defined $config{url} && $config{url}=~/^https:/;
636                 if (defined $oiduser) {
637                         eval {
638                                 $avatar = libravatar_url(openid => $user, https => $https);
639                         }
640                 }
641                 if (! defined $avatar &&
642                     (my $email = IkiWiki::userinfo_get($user, 'email'))) {
643                         eval {
644                                 $avatar = libravatar_url(email => $email, https => $https);
645                         }
646                 }
647         }
648         return $avatar;
652 sub commentmoderation ($$) {
653         my $cgi=shift;
654         my $session=shift;
656         IkiWiki::needsignin($cgi, $session);
657         if (! IkiWiki::is_admin($session->param("name"))) {
658                 error(gettext("you are not logged in as an admin"));
659         }
661         IkiWiki::decode_cgi_utf8($cgi);
662         
663         if (defined $cgi->param('sid')) {
664                 IkiWiki::checksessionexpiry($cgi, $session);
666                 my $rejectalldefer=$cgi->param('rejectalldefer');
668                 my %vars=$cgi->Vars;
669                 my $added=0;
670                 foreach my $id (keys %vars) {
671                         if ($id =~ /(.*)\._comment(?:_pending)?$/) {
672                                 $id=decode_utf8($id);
673                                 my $action=$cgi->param($id);
674                                 next if $action eq 'Defer' && ! $rejectalldefer;
676                                 # Make sure that the id is of a legal
677                                 # pending comment.
678                                 my ($f) = $id =~ /$config{wiki_file_regexp}/;
679                                 if (! defined $f || ! length $f ||
680                                     IkiWiki::file_pruned($f)) {
681                                         error("illegal file");
682                                 }
684                                 my $page=IkiWiki::dirname($f);
685                                 my $filedir=$IkiWiki::Plugin::transient::transientdir;
686                                 my $file="$filedir/$f";
687                                 if (! -e $file) {
688                                         # old location
689                                         $file="$config{srcdir}/$f";
690                                         $filedir=$config{srcdir};
691                                         if (! -e $file) {
692                                                 # older location
693                                                 $file="$config{wikistatedir}/comments_pending/".$f;
694                                                 $filedir="$config{wikistatedir}/comments_pending";
695                                         }
696                                 }
698                                 if ($action eq 'Accept') {
699                                         my $content=eval { readfile($file) };
700                                         next if $@; # file vanished since form was displayed
701                                         my $dest=unique_comment_location($page, $content, $config{srcdir})."._comment";
702                                         writefile($dest, $config{srcdir}, $content);
703                                         if ($config{rcs} and $config{comments_commit}) {
704                                                 IkiWiki::rcs_add($dest);
705                                         }
706                                         $added++;
707                                 }
709                                 require IkiWiki::Render;
710                                 IkiWiki::prune($file, $filedir);
711                         }
712                 }
714                 if ($added) {
715                         my $conflict;
716                         if ($config{rcs} and $config{comments_commit}) {
717                                 my $message = gettext("Comment moderation");
718                                 IkiWiki::disable_commit_hook();
719                                 $conflict=IkiWiki::rcs_commit_staged(
720                                         message => $message,
721                                         session => $session,
722                                 );
723                                 IkiWiki::enable_commit_hook();
724                                 IkiWiki::rcs_update();
725                         }
726                 
727                         # Now we need a refresh
728                         require IkiWiki::Render;
729                         IkiWiki::refresh();
730                         IkiWiki::saveindex();
731                 
732                         error($conflict) if defined $conflict;
733                 }
734         }
736         my @comments=map {
737                 my ($id, $dir, $ctime)=@{$_};
738                 my $content=readfile("$dir/$id");
739                 my $preview=previewcomment($content, $id,
740                         $id, $ctime);
741                 {
742                         id => $id,
743                         view => $preview,
744                 }
745         } sort { $b->[2] <=> $a->[2] } comments_pending();
747         my $template=template("commentmoderation.tmpl");
748         $template->param(
749                 sid => $session->id,
750                 comments => \@comments,
751                 cgiurl => IkiWiki::cgiurl(),
752         );
753         IkiWiki::printheader($session);
754         my $out=$template->output;
755         IkiWiki::run_hooks(format => sub {
756                 $out = shift->(page => "", content => $out);
757         });
758         print IkiWiki::cgitemplate($cgi, gettext("comment moderation"), $out);
759         exit;
762 sub formbuilder_setup (@) {
763         my %params=@_;
765         my $form=$params{form};
766         if ($form->title eq "preferences" &&
767             IkiWiki::is_admin($params{session}->param("name"))) {
768                 push @{$params{buttons}}, "Comment Moderation";
769                 if ($form->submitted && $form->submitted eq "Comment Moderation") {
770                         commentmoderation($params{cgi}, $params{session});
771                 }
772         }
775 sub comments_pending () {
776         my @ret;
778         eval q{use File::Find};
779         error($@) if $@;
780         eval q{use Cwd};
781         error($@) if $@;
782         my $origdir=getcwd();
784         my $find_comments=sub {
785                 my $dir=shift;
786                 my $extension=shift;
787                 return unless -d $dir;
789                 chdir($dir) || die "chdir $dir: $!";
791                 find({
792                         no_chdir => 1,
793                         wanted => sub {
794                                 my $file=decode_utf8($_);
795                                 $file=~s/^\.\///;
796                                 return if ! length $file || IkiWiki::file_pruned($file)
797                                         || -l $_ || -d _ || $file !~ /\Q$extension\E$/;
798                                 my ($f) = $file =~ /$config{wiki_file_regexp}/; # untaint
799                                 if (defined $f) {
800                                         my $ctime=(stat($_))[10];
801                                         push @ret, [$f, $dir, $ctime];
802                                 }
803                         }
804                 }, ".");
806                 chdir($origdir) || die "chdir $origdir: $!";
807         };
808         
809         $find_comments->($IkiWiki::Plugin::transient::transientdir, "._comment_pending");
810         # old location
811         $find_comments->($config{srcdir}, "._comment_pending");
812         # old location
813         $find_comments->("$config{wikistatedir}/comments_pending/",
814                 "._comment");
816         return @ret;
819 sub previewcomment ($$$) {
820         my $content=shift;
821         my $location=shift;
822         my $page=shift;
823         my $time=shift;
825         # Previewing a comment should implicitly enable comment posting mode.
826         my $oldpostcomment=$postcomment;
827         $postcomment=1;
829         my $preview = IkiWiki::htmlize($location, $page, '_comment',
830                         IkiWiki::linkify($location, $page,
831                         IkiWiki::preprocess($location, $page,
832                         IkiWiki::filter($location, $page, $content), 0, 1)));
834         my $template = template("comment.tmpl");
835         $template->param(content => $preview);
836         $template->param(ctime => displaytime($time, undef, 1));
837         $template->param(html5 => $config{html5});
839         IkiWiki::run_hooks(pagetemplate => sub {
840                 shift->(page => $location,
841                         destpage => $page,
842                         template => $template);
843         });
845         $template->param(have_actions => 0);
847         $postcomment=$oldpostcomment;
849         return $template->output;
852 sub commentsshown ($) {
853         my $page=shift;
855         return pagespec_match($page, $config{comments_pagespec},
856                 location => $page);
859 sub commentsopen ($) {
860         my $page = shift;
862         return length $config{cgiurl} > 0 &&
863                (! length $config{comments_closed_pagespec} ||
864                 ! pagespec_match($page, $config{comments_closed_pagespec},
865                                  location => $page));
868 sub pagetemplate (@) {
869         my %params = @_;
871         my $page = $params{page};
872         my $template = $params{template};
873         my $shown = ($template->query(name => 'commentslink') ||
874                      $template->query(name => 'commentsurl') ||
875                      $template->query(name => 'atomcommentsurl') ||
876                      $template->query(name => 'comments')) &&
877                     commentsshown($page);
879         if ($template->query(name => 'comments')) {
880                 my $comments = undef;
881                 if ($shown) {
882                         $comments = IkiWiki::preprocess_inline(
883                                 pages => "comment($page) and !comment($page/*)",
884                                 template => 'comment',
885                                 show => 0,
886                                 reverse => 'yes',
887                                 page => $page,
888                                 destpage => $params{destpage},
889                                 feedfile => 'comments',
890                                 emptyfeeds => 'no',
891                         );
892                 }
894                 if (defined $comments && length $comments) {
895                         $template->param(comments => $comments);
896                 }
898                 if ($shown && commentsopen($page)) {
899                         $template->param(addcommenturl => addcommenturl($page));
900                 }
901         }
903         if ($shown) {
904                 if ($template->query(name => 'commentsurl')) {
905                         $template->param(commentsurl =>
906                                 urlto($page).'#comments');
907                 }
909                 if ($template->query(name => 'atomcommentsurl') && $config{usedirs}) {
910                         # This will 404 until there are some comments, but I
911                         # think that's probably OK...
912                         $template->param(atomcommentsurl =>
913                                 urlto($page).'comments.atom');
914                 }
916                 if ($template->query(name => 'commentslink')) {
917                         my $num=num_comments($page, $config{srcdir});
918                         my $link;
919                         if ($num > 0) {
920                                 $link = htmllink($page, $params{destpage}, $page,
921                                         linktext => sprintf(ngettext("%i comment", "%i comments", $num), $num),
922                                         anchor => "comments",
923                                         noimageinline => 1
924                                 );
925                         }
926                         elsif (commentsopen($page)) {
927                                 $link = "<a href=\"".addcommenturl($page)."\">".
928                                         #translators: Here "Comment" is a verb;
929                                         #translators: the user clicks on it to
930                                         #translators: post a comment.
931                                         gettext("Comment").
932                                         "</a>";
933                         }
934                         $template->param(commentslink => $link)
935                                 if defined $link;
936                 }
937         }
939         # everything below this point is only relevant to the comments
940         # themselves
941         if (!exists $commentstate{$page}) {
942                 return;
943         }
944         
945         if ($template->query(name => 'commentid')) {
946                 $template->param(commentid => page_to_id($page));
947         }
949         if ($template->query(name => 'commentuser')) {
950                 $template->param(commentuser =>
951                         $commentstate{$page}{commentuser});
952         }
954         if ($template->query(name => 'commentopenid')) {
955                 $template->param(commentopenid =>
956                         $commentstate{$page}{commentopenid});
957         }
959         if ($template->query(name => 'commentip')) {
960                 $template->param(commentip =>
961                         $commentstate{$page}{commentip});
962         }
964         if ($template->query(name => 'commentauthor')) {
965                 $template->param(commentauthor =>
966                         $commentstate{$page}{commentauthor});
967         }
969         if ($template->query(name => 'commentauthorurl')) {
970                 $template->param(commentauthorurl =>
971                         $commentstate{$page}{commentauthorurl});
972         }
974         if ($template->query(name => 'commentauthoravatar')) {
975                 $template->param(commentauthoravatar =>
976                         $commentstate{$page}{commentauthoravatar});
977         }
979         if ($template->query(name => 'removeurl') &&
980             IkiWiki::Plugin::remove->can("check_canremove") &&
981             length $config{cgiurl}) {
982                 $template->param(removeurl => IkiWiki::cgiurl(do => 'remove',
983                         page => $page));
984                 $template->param(have_actions => 1);
985         }
988 sub addcommenturl ($) {
989         my $page=shift;
991         return IkiWiki::cgiurl(do => 'comment', page => $page);
994 sub num_comments ($$) {
995         my $page=shift;
996         my $dir=shift;
998         my @comments=glob("$dir/$page/$config{comments_pagename}*._comment");
999         return int @comments;
1002 sub unique_comment_location ($$$$) {
1003         my $page=shift;
1004         eval q{use Digest::MD5 'md5_hex'};
1005         error($@) if $@;
1006         my $content_md5=md5_hex(Encode::encode_utf8(shift));
1007         my $dir=shift;
1008         my $ext=shift || "._comment";
1010         my $location;
1011         my $i = num_comments($page, $dir);
1012         do {
1013                 $i++;
1014                 $location = "$page/$config{comments_pagename}${i}_${content_md5}";
1015         } while (-e "$dir/$location$ext");
1017         return $location;
1020 sub page_to_id ($) {
1021         # Converts a comment page name into a unique, legal html id
1022         # attribute value, that can be used as an anchor to link to the
1023         # comment.
1024         my $page=shift;
1026         eval q{use Digest::MD5 'md5_hex'};
1027         error($@) if $@;
1029         return "comment-".md5_hex(Encode::encode_utf8(($page)));
1031         
1032 package IkiWiki::PageSpec;
1034 sub match_postcomment ($$;@) {
1035         my $page = shift;
1036         my $glob = shift;
1038         if (! $postcomment) {
1039                 return IkiWiki::FailReason->new("not posting a comment");
1040         }
1041         return match_glob($page, $glob, @_);
1044 sub match_comment ($$;@) {
1045         my $page = shift;
1046         my $glob = shift;
1048         if (! $postcomment) {
1049                 # To see if it's a comment, check the source file type.
1050                 # Deal with comments that were just deleted.
1051                 my $source=exists $IkiWiki::pagesources{$page} ?
1052                         $IkiWiki::pagesources{$page} :
1053                         $IkiWiki::delpagesources{$page};
1054                 my $type=defined $source ? IkiWiki::pagetype($source) : undef;
1055                 if (! defined $type || $type ne "_comment") {
1056                         return IkiWiki::FailReason->new("$page is not a comment");
1057                 }
1058         }
1060         return match_glob($page, "$glob/*", internal => 1, @_);
1063 sub match_comment_pending ($$;@) {
1064         my $page = shift;
1065         my $glob = shift;
1066         
1067         my $source=exists $IkiWiki::pagesources{$page} ?
1068                 $IkiWiki::pagesources{$page} :
1069                 $IkiWiki::delpagesources{$page};
1070         my $type=defined $source ? IkiWiki::pagetype($source) : undef;
1071         if (! defined $type || $type ne "_comment_pending") {
1072                 return IkiWiki::FailReason->new("$page is not a pending comment");
1073         }
1075         return match_glob($page, "$glob/*", internal => 1, @_);