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