Merge branch 'ready/templatebody'
[ikiwiki.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;
7
8 use warnings;
9 use strict;
10 use IkiWiki 3.00;
11 use Encode;
12
13 use constant PREVIEW => "Preview";
14 use constant POST_COMMENT => "Post comment";
15 use constant CANCEL => "Cancel";
16
17 my $postcomment;
18 my %commentstate;
19
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 }
40
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                 },
102
103 }
104
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};
119 }
120
121 sub htmlize {
122         my %params = @_;
123         return $params{content};
124 }
125
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>');
132 }
133
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         }
144 }
145
146 sub isallowed ($) {
147     my $format = shift;
148     return ! $config{comments_allowformats} || $config{comments_allowformats} =~ /\b$format\b/;
149 }
150
151 sub preprocess {
152         my %params = @_;
153         my $page = $params{page};
154
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         }
160
161         my $content = $params{content};
162         if (! defined $content) {
163                 error(gettext("comment must have content"));
164         }
165         $content =~ s/\\"/"/g;
166
167         if (defined wantarray) {
168                 if ($config{comments_allowdirectives}) {
169                         $content = IkiWiki::preprocess($page, $params{destpage},
170                                 $content);
171                 }
172
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;
176
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         }
188
189         # set metadata, possibly overriding [[!meta]] directives from the
190         # comment itself
191
192         my $commentuser;
193         my $commentip;
194         my $commentauthor;
195         my $commentauthorurl;
196         my $commentopenid;
197         if (defined $params{username}) {
198                 $commentuser = $params{username};
199
200                 my $oiduser = eval { IkiWiki::openiduser($commentuser) };
201
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                         );
213
214                         $commentauthor = $commentuser;
215                 }
216         }
217         else {
218                 if (defined $params{ip}) {
219                         $commentip = $params{ip};
220                 }
221                 $commentauthor = gettext("Anonymous");
222         }
223
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         }
236
237         if ($config{comments_allowauthor}) {
238                 if (defined $params{claimedauthor}) {
239                         $pagestate{$page}{meta}{author} = $params{claimedauthor};
240                 }
241
242                 if (defined $params{url}) {
243                         my $url=$params{url};
244
245                         eval q{use URI::Heuristic}; 
246                         if (! $@) {
247                                 $url=URI::Heuristic::uf_uristr($url);
248                         }
249
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         }
259
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         }
265
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         }
270
271         eval q{use Date::Parse};
272         if (! $@) {
273                 my $time = str2time($params{date});
274                 $IkiWiki::pagectime{$page} = $time if defined $time;
275         }
276
277         return $content;
278 }
279
280 sub preprocess_moderation {
281         my %params = @_;
282
283         $params{desc}=gettext("Comment Moderation")
284                 unless defined $params{desc};
285
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         }
294 }
295
296 sub sessioncgi ($$) {
297         my $cgi=shift;
298         my $session=shift;
299
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         }
311 }
312
313 # Mostly cargo-culted from IkiWiki::plugin::editpage
314 sub editcomment ($$) {
315         my $cgi=shift;
316         my $session=shift;
317
318         IkiWiki::decode_cgi_utf8($cgi);
319
320         eval q{use CGI::FormBuilder};
321         error($@) if $@;
322
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         );
337
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);
344
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         }
352
353
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;
361
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);
370
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         }
386
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         }
403
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         }
410
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         }
419
420         $form->title(sprintf(gettext("commenting on %s"),
421                         IkiWiki::pagetitle(IkiWiki::basename($page))));
422
423         $form->tmpl_param('helponformattinglink',
424                 htmllink($page, $page, 'ikiwiki/formatting',
425                         noimageinline => 1,
426                         linktext => 'FormattingHelp'),
427                         allowdirectives => $config{allow_directives});
428
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         }
434
435         if (not exists $pagesources{$page}) {
436                 error(sprintf(gettext(
437                         "page '%s' doesn't exist, so you can't comment"),
438                         $page));
439         }
440
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         }
450
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         }
457
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;
463
464         my $content = "[[!comment format=$type\n";
465
466         if (defined $session->param('name')) {
467                 my $username = $session->param('name');
468                 $username =~ s/"/&quot;/g;
469                 $content .= " username=\"$username\"\n";
470         }
471         if (defined $session->param('nickname')) {
472                 my $nickname = $session->param('nickname');
473                 $nickname =~ s/"/&quot;/g;
474                 $content .= " nickname=\"$nickname\"\n";
475         }
476         elsif (defined $session->remote_addr()) {
477                 $content .= " ip=\"".$session->remote_addr()."\"\n";
478         }
479
480         if ($config{comments_allowauthor}) {
481                 my $author = $form->field('author');
482                 if (defined $author && length $author) {
483                         $author =~ s/"/&quot;/g;
484                         $content .= " claimedauthor=\"$author\"\n";
485                 }
486                 my $url = $form->field('url');
487                 if (defined $url && length $url) {
488                         $url =~ s/"/&quot;/g;
489                         $content .= " url=\"$url\"\n";
490                 }
491         }
492
493         my $avatar=getavatar($session->param('name'));
494         if (defined $avatar && length $avatar) {
495                 $avatar =~ s/"/&quot;/g;
496                 $content .= " avatar=\"$avatar\"\n";
497         }
498
499         my $subject = $form->field('subject');
500         if (defined $subject && length $subject) {
501                 $subject =~ s/"/&quot;/g;
502         }
503         else {
504                 $subject = "comment ".(num_comments($page, $config{srcdir}) + 1);
505         }
506         $content .= " subject=\"$subject\"\n";
507
508         $content .= " date=\"" . strftime_utf8('%Y-%m-%dT%H:%M:%SZ', gmtime) . "\"\n";
509
510         my $editcontent = $form->field('editcontent');
511         $editcontent="" if ! defined $editcontent;
512         $editcontent =~ s/\r\n/\n/g;
513         $editcontent =~ s/\r/\n/g;
514         $editcontent =~ s/"/\\"/g;
515         $content .= " content=\"\"\"\n$editcontent\n\"\"\"]]\n";
516
517         my $location=unique_comment_location($page, $content, $config{srcdir});
518
519         # This is essentially a simplified version of editpage:
520         # - the user does not control the page that's created, only the parent
521         # - it's always a create operation, never an edit
522         # - this means that conflicts should never happen
523         # - this means that if they do, rocks fall and everyone dies
524
525         if ($form->submitted eq PREVIEW) {
526                 my $preview=previewcomment($content, $location, $page, time);
527                 IkiWiki::run_hooks(format => sub {
528                         $preview = shift->(page => $page,
529                                 content => $preview);
530                 });
531                 $form->tmpl_param(page_preview => $preview);
532         }
533         else {
534                 $form->tmpl_param(page_preview => "");
535         }
536
537         if ($form->submitted eq POST_COMMENT && $form->validate) {
538                 IkiWiki::checksessionexpiry($cgi, $session);
539
540                 if (IkiWiki::Plugin::notifyemail->can("subscribe")) {
541                         my $subspec="comment($page)";
542                         if (defined $username &&
543                             length $form->field("subscribe")) {
544                                 IkiWiki::Plugin::notifyemail::subscribe(
545                                         $username, $subspec);
546                         }
547                         elsif (length $form->field("email") &&
548                                length $form->field("anonsubscribe")) {
549                                 IkiWiki::Plugin::notifyemail::anonsubscribe(
550                                         $form->field("email"), $subspec);
551                         }
552                 }
553                 
554                 $postcomment=1;
555                 my $ok=IkiWiki::check_content(content => $form->field('editcontent'),
556                         subject => $form->field('subject'),
557                         $config{comments_allowauthor} ? (
558                                 author => $form->field('author'),
559                                 url => $form->field('url'),
560                         ) : (),
561                         page => $location,
562                         cgi => $cgi,
563                         session => $session,
564                         nonfatal => 1,
565                 );
566                 $postcomment=0;
567
568                 if (! $ok) {
569                         $location=unique_comment_location($page, $content, $IkiWiki::Plugin::transient::transientdir, "._comment_pending");
570                         writefile("$location._comment_pending", $IkiWiki::Plugin::transient::transientdir, $content);
571
572                         # Refresh so anything that deals with pending
573                         # comments can be updated.
574                         require IkiWiki::Render;
575                         IkiWiki::refresh();
576                         IkiWiki::saveindex();
577
578                         IkiWiki::printheader($session);
579                         print IkiWiki::cgitemplate($cgi, gettext(gettext("comment stored for moderation")),
580                                 "<p>".
581                                 gettext("Your comment will be posted after moderator review").
582                                 "</p>");
583                         exit;
584                 }
585
586                 # FIXME: could probably do some sort of graceful retry
587                 # on error? Would require significant unwinding though
588                 my $file = "$location._comment";
589                 writefile($file, $config{srcdir}, $content);
590
591                 my $conflict;
592
593                 if ($config{rcs} and $config{comments_commit}) {
594                         my $message = gettext("Added a comment");
595                         if (defined $form->field('subject') &&
596                                 length $form->field('subject')) {
597                                 $message = sprintf(
598                                         gettext("Added a comment: %s"),
599                                         $form->field('subject'));
600                         }
601
602                         IkiWiki::rcs_add($file);
603                         IkiWiki::disable_commit_hook();
604                         $conflict = IkiWiki::rcs_commit_staged(
605                                 message => $message,
606                                 session => $session,
607                         );
608                         IkiWiki::enable_commit_hook();
609                         IkiWiki::rcs_update();
610                 }
611
612                 # Now we need a refresh
613                 require IkiWiki::Render;
614                 IkiWiki::refresh();
615                 IkiWiki::saveindex();
616
617                 # this should never happen, unless a committer deliberately
618                 # breaks it or something
619                 error($conflict) if defined $conflict;
620
621                 # Jump to the new comment on the page.
622                 # The trailing question mark tries to avoid broken
623                 # caches and get the most recent version of the page.
624                 IkiWiki::redirect($cgi, urlto($page).
625                         "?updated#".page_to_id($location));
626
627         }
628         else {
629                 IkiWiki::showform($form, \@buttons, $session, $cgi,
630                         page => $page);
631         }
632
633         exit;
634 }
635
636 sub getavatar ($) {
637         my $user=shift;
638         return undef unless defined $user;
639
640         my $avatar;
641         eval q{use Libravatar::URL};
642         if (! $@) {
643                 my $oiduser = eval { IkiWiki::openiduser($user) };
644                 my $https=defined $config{url} && $config{url}=~/^https:/;
645
646                 if (defined $oiduser) {
647                         eval {
648                                 $avatar = libravatar_url(openid => $user, https => $https);
649                         }
650                 }
651                 if (! defined $avatar &&
652                     (my $email = IkiWiki::userinfo_get($user, 'email'))) {
653                         eval {
654                                 $avatar = libravatar_url(email => $email, https => $https);
655                         }
656                 }
657         }
658         return $avatar;
659 }
660
661
662 sub commentmoderation ($$) {
663         my $cgi=shift;
664         my $session=shift;
665
666         IkiWiki::needsignin($cgi, $session);
667         if (! IkiWiki::is_admin($session->param("name"))) {
668                 error(gettext("you are not logged in as an admin"));
669         }
670
671         IkiWiki::decode_cgi_utf8($cgi);
672         
673         if (defined $cgi->param('sid')) {
674                 IkiWiki::checksessionexpiry($cgi, $session);
675
676                 my $rejectalldefer=$cgi->param('rejectalldefer');
677
678                 my %vars=$cgi->Vars;
679                 my $added=0;
680                 foreach my $id (keys %vars) {
681                         if ($id =~ /(.*)\._comment(?:_pending)?$/) {
682                                 $id=decode_utf8($id);
683                                 my $action=$cgi->param($id);
684                                 next if $action eq 'Defer' && ! $rejectalldefer;
685
686                                 # Make sure that the id is of a legal
687                                 # pending comment.
688                                 my ($f) = $id =~ /$config{wiki_file_regexp}/;
689                                 if (! defined $f || ! length $f ||
690                                     IkiWiki::file_pruned($f)) {
691                                         error("illegal file");
692                                 }
693
694                                 my $page=IkiWiki::dirname($f);
695                                 my $filedir=$IkiWiki::Plugin::transient::transientdir;
696                                 my $file="$filedir/$f";
697                                 if (! -e $file) {
698                                         # old location
699                                         $file="$config{srcdir}/$f";
700                                         $filedir=$config{srcdir};
701                                         if (! -e $file) {
702                                                 # older location
703                                                 $file="$config{wikistatedir}/comments_pending/".$f;
704                                                 $filedir="$config{wikistatedir}/comments_pending";
705                                         }
706                                 }
707
708                                 if ($action eq 'Accept') {
709                                         my $content=eval { readfile($file) };
710                                         next if $@; # file vanished since form was displayed
711                                         my $dest=unique_comment_location($page, $content, $config{srcdir})."._comment";
712                                         writefile($dest, $config{srcdir}, $content);
713                                         if ($config{rcs} and $config{comments_commit}) {
714                                                 IkiWiki::rcs_add($dest);
715                                         }
716                                         $added++;
717                                 }
718
719                                 require IkiWiki::Render;
720                                 IkiWiki::prune($file, $filedir);
721                         }
722                 }
723
724                 if ($added) {
725                         my $conflict;
726                         if ($config{rcs} and $config{comments_commit}) {
727                                 my $message = gettext("Comment moderation");
728                                 IkiWiki::disable_commit_hook();
729                                 $conflict=IkiWiki::rcs_commit_staged(
730                                         message => $message,
731                                         session => $session,
732                                 );
733                                 IkiWiki::enable_commit_hook();
734                                 IkiWiki::rcs_update();
735                         }
736                 
737                         # Now we need a refresh
738                         require IkiWiki::Render;
739                         IkiWiki::refresh();
740                         IkiWiki::saveindex();
741                 
742                         error($conflict) if defined $conflict;
743                 }
744         }
745
746         my @comments=map {
747                 my ($id, $dir, $ctime)=@{$_};
748                 my $content=readfile("$dir/$id");
749                 my $preview=previewcomment($content, $id,
750                         $id, $ctime);
751                 {
752                         id => $id,
753                         view => $preview,
754                 }
755         } sort { $b->[2] <=> $a->[2] } comments_pending();
756
757         my $template=template("commentmoderation.tmpl");
758         $template->param(
759                 sid => $session->id,
760                 comments => \@comments,
761                 cgiurl => IkiWiki::cgiurl(),
762         );
763         IkiWiki::printheader($session);
764         my $out=$template->output;
765         IkiWiki::run_hooks(format => sub {
766                 $out = shift->(page => "", content => $out);
767         });
768         print IkiWiki::cgitemplate($cgi, gettext("comment moderation"), $out);
769         exit;
770 }
771
772 sub formbuilder_setup (@) {
773         my %params=@_;
774
775         my $form=$params{form};
776         if ($form->title eq "preferences" &&
777             IkiWiki::is_admin($params{session}->param("name"))) {
778                 push @{$params{buttons}}, "Comment Moderation";
779                 if ($form->submitted && $form->submitted eq "Comment Moderation") {
780                         commentmoderation($params{cgi}, $params{session});
781                 }
782         }
783 }
784
785 sub comments_pending () {
786         my @ret;
787
788         eval q{use File::Find};
789         error($@) if $@;
790         eval q{use Cwd};
791         error($@) if $@;
792         my $origdir=getcwd();
793
794         my $find_comments=sub {
795                 my $dir=shift;
796                 my $extension=shift;
797                 return unless -d $dir;
798
799                 chdir($dir) || die "chdir $dir: $!";
800
801                 find({
802                         no_chdir => 1,
803                         wanted => sub {
804                                 my $file=decode_utf8($_);
805                                 $file=~s/^\.\///;
806                                 return if ! length $file || IkiWiki::file_pruned($file)
807                                         || -l $_ || -d _ || $file !~ /\Q$extension\E$/;
808                                 my ($f) = $file =~ /$config{wiki_file_regexp}/; # untaint
809                                 if (defined $f) {
810                                         my $ctime=(stat($_))[10];
811                                         push @ret, [$f, $dir, $ctime];
812                                 }
813                         }
814                 }, ".");
815
816                 chdir($origdir) || die "chdir $origdir: $!";
817         };
818         
819         $find_comments->($IkiWiki::Plugin::transient::transientdir, "._comment_pending");
820         # old location
821         $find_comments->($config{srcdir}, "._comment_pending");
822         # old location
823         $find_comments->("$config{wikistatedir}/comments_pending/",
824                 "._comment");
825
826         return @ret;
827 }
828
829 sub previewcomment ($$$) {
830         my $content=shift;
831         my $location=shift;
832         my $page=shift;
833         my $time=shift;
834
835         # Previewing a comment should implicitly enable comment posting mode.
836         my $oldpostcomment=$postcomment;
837         $postcomment=1;
838
839         my $preview = IkiWiki::htmlize($location, $page, '_comment',
840                         IkiWiki::linkify($location, $page,
841                         IkiWiki::preprocess($location, $page,
842                         IkiWiki::filter($location, $page, $content), 0, 1)));
843
844         my $template = template("comment.tmpl");
845         $template->param(content => $preview);
846         $template->param(ctime => displaytime($time, undef, 1));
847         $template->param(html5 => $config{html5});
848
849         IkiWiki::run_hooks(pagetemplate => sub {
850                 shift->(page => $location,
851                         destpage => $page,
852                         template => $template);
853         });
854
855         $template->param(have_actions => 0);
856
857         $postcomment=$oldpostcomment;
858
859         return $template->output;
860 }
861
862 sub commentsshown ($) {
863         my $page=shift;
864
865         return pagespec_match($page, $config{comments_pagespec},
866                 location => $page);
867 }
868
869 sub commentsopen ($) {
870         my $page = shift;
871
872         return length $config{cgiurl} > 0 &&
873                (! length $config{comments_closed_pagespec} ||
874                 ! pagespec_match($page, $config{comments_closed_pagespec},
875                                  location => $page));
876 }
877
878 sub pagetemplate (@) {
879         my %params = @_;
880
881         my $page = $params{page};
882         my $template = $params{template};
883         my $shown = ($template->query(name => 'commentslink') ||
884                      $template->query(name => 'commentsurl') ||
885                      $template->query(name => 'atomcommentsurl') ||
886                      $template->query(name => 'comments')) &&
887                     commentsshown($page);
888
889         if ($template->query(name => 'comments')) {
890                 my $comments = undef;
891                 if ($shown) {
892                         $comments = IkiWiki::preprocess_inline(
893                                 pages => "comment($page) and !comment($page/*)",
894                                 template => 'comment',
895                                 show => 0,
896                                 reverse => 'yes',
897                                 page => $page,
898                                 destpage => $params{destpage},
899                                 feedfile => 'comments',
900                                 emptyfeeds => 'no',
901                         );
902                 }
903
904                 if (defined $comments && length $comments) {
905                         $template->param(comments => $comments);
906                 }
907
908                 if ($shown && commentsopen($page)) {
909                         $template->param(addcommenturl => addcommenturl($page));
910                 }
911         }
912
913         if ($shown) {
914                 if ($template->query(name => 'commentsurl')) {
915                         $template->param(commentsurl =>
916                                 urlto($page).'#comments');
917                 }
918
919                 if ($template->query(name => 'atomcommentsurl') && $config{usedirs}) {
920                         # This will 404 until there are some comments, but I
921                         # think that's probably OK...
922                         $template->param(atomcommentsurl =>
923                                 urlto($page).'comments.atom');
924                 }
925
926                 if ($template->query(name => 'commentslink')) {
927                         my $num=num_comments($page, $config{srcdir});
928                         my $link;
929                         if ($num > 0) {
930                                 $link = htmllink($page, $params{destpage}, $page,
931                                         linktext => sprintf(ngettext("%i comment", "%i comments", $num), $num),
932                                         anchor => "comments",
933                                         noimageinline => 1
934                                 );
935                         }
936                         elsif (commentsopen($page)) {
937                                 $link = "<a href=\"".addcommenturl($page)."\">".
938                                         #translators: Here "Comment" is a verb;
939                                         #translators: the user clicks on it to
940                                         #translators: post a comment.
941                                         gettext("Comment").
942                                         "</a>";
943                         }
944                         $template->param(commentslink => $link)
945                                 if defined $link;
946                 }
947         }
948
949         # everything below this point is only relevant to the comments
950         # themselves
951         if (!exists $commentstate{$page}) {
952                 return;
953         }
954         
955         if ($template->query(name => 'commentid')) {
956                 $template->param(commentid => page_to_id($page));
957         }
958
959         if ($template->query(name => 'commentuser')) {
960                 $template->param(commentuser =>
961                         $commentstate{$page}{commentuser});
962         }
963
964         if ($template->query(name => 'commentopenid')) {
965                 $template->param(commentopenid =>
966                         $commentstate{$page}{commentopenid});
967         }
968
969         if ($template->query(name => 'commentip')) {
970                 $template->param(commentip =>
971                         $commentstate{$page}{commentip});
972         }
973
974         if ($template->query(name => 'commentauthor')) {
975                 $template->param(commentauthor =>
976                         $commentstate{$page}{commentauthor});
977         }
978
979         if ($template->query(name => 'commentauthorurl')) {
980                 $template->param(commentauthorurl =>
981                         $commentstate{$page}{commentauthorurl});
982         }
983
984         if ($template->query(name => 'commentauthoravatar')) {
985                 $template->param(commentauthoravatar =>
986                         $commentstate{$page}{commentauthoravatar});
987         }
988
989         if ($template->query(name => 'removeurl') &&
990             IkiWiki::Plugin::remove->can("check_canremove") &&
991             length $config{cgiurl}) {
992                 $template->param(removeurl => IkiWiki::cgiurl(do => 'remove',
993                         page => $page));
994                 $template->param(have_actions => 1);
995         }
996 }
997
998 sub addcommenturl ($) {
999         my $page=shift;
1000
1001         return IkiWiki::cgiurl(do => 'comment', page => $page);
1002 }
1003
1004 sub num_comments ($$) {
1005         my $page=shift;
1006         my $dir=shift;
1007
1008         my @comments=glob("$dir/$page/$config{comments_pagename}*._comment");
1009         return int @comments;
1010 }
1011
1012 sub unique_comment_location ($$$$) {
1013         my $page=shift;
1014         eval q{use Digest::MD5 'md5_hex'};
1015         error($@) if $@;
1016         my $content_md5=md5_hex(Encode::encode_utf8(shift));
1017         my $dir=shift;
1018         my $ext=shift || "._comment";
1019
1020         my $location;
1021         my $i = num_comments($page, $dir);
1022         do {
1023                 $i++;
1024                 $location = "$page/$config{comments_pagename}${i}_${content_md5}";
1025         } while (-e "$dir/$location$ext");
1026
1027         return $location;
1028 }
1029
1030 sub page_to_id ($) {
1031         # Converts a comment page name into a unique, legal html id
1032         # attribute value, that can be used as an anchor to link to the
1033         # comment.
1034         my $page=shift;
1035
1036         eval q{use Digest::MD5 'md5_hex'};
1037         error($@) if $@;
1038
1039         return "comment-".md5_hex(Encode::encode_utf8(($page)));
1040 }
1041         
1042 package IkiWiki::PageSpec;
1043
1044 sub match_postcomment ($$;@) {
1045         my $page = shift;
1046         my $glob = shift;
1047
1048         if (! $postcomment) {
1049                 return IkiWiki::FailReason->new("not posting a comment");
1050         }
1051         return match_glob($page, $glob, @_);
1052 }
1053
1054 sub match_comment ($$;@) {
1055         my $page = shift;
1056         my $glob = shift;
1057
1058         if (! $postcomment) {
1059                 # To see if it's a comment, check the source file type.
1060                 # Deal with comments that were just deleted.
1061                 my $source=exists $IkiWiki::pagesources{$page} ?
1062                         $IkiWiki::pagesources{$page} :
1063                         $IkiWiki::delpagesources{$page};
1064                 my $type=defined $source ? IkiWiki::pagetype($source) : undef;
1065                 if (! defined $type || $type ne "_comment") {
1066                         return IkiWiki::FailReason->new("$page is not a comment");
1067                 }
1068         }
1069
1070         return match_glob($page, "$glob/*", internal => 1, @_);
1071 }
1072
1073 sub match_comment_pending ($$;@) {
1074         my $page = shift;
1075         my $glob = shift;
1076         
1077         my $source=exists $IkiWiki::pagesources{$page} ?
1078                 $IkiWiki::pagesources{$page} :
1079                 $IkiWiki::delpagesources{$page};
1080         my $type=defined $source ? IkiWiki::pagetype($source) : undef;
1081         if (! defined $type || $type ne "_comment_pending") {
1082                 return IkiWiki::FailReason->new("$page is not a pending comment");
1083         }
1084
1085         return match_glob($page, "$glob/*", internal => 1, @_);
1086 }
1087
1088 1