calendar, prettydate: Fix strftime encoding bug
[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 }
39
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 }
94
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};
104 }
105
106 sub htmlize {
107         my %params = @_;
108         return $params{content};
109 }
110
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>');
117 }
118
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         }
129 }
130
131 sub preprocess {
132         my %params = @_;
133         my $page = $params{page};
134
135         my $format = $params{format};
136         if (defined $format && ! exists $IkiWiki::hooks{htmlize}{$format}) {
137                 error(sprintf(gettext("unsupported page format %s"), $format));
138         }
139
140         my $content = $params{content};
141         if (! defined $content) {
142                 error(gettext("comment must have content"));
143         }
144         $content =~ s/\\"/"/g;
145
146         if (defined wantarray) {
147                 if ($config{comments_allowdirectives}) {
148                         $content = IkiWiki::preprocess($page, $params{destpage},
149                                 $content);
150                 }
151
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;
155
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         }
167
168         # set metadata, possibly overriding [[!meta]] directives from the
169         # comment itself
170
171         my $commentuser;
172         my $commentip;
173         my $commentauthor;
174         my $commentauthorurl;
175         my $commentopenid;
176         if (defined $params{username}) {
177                 $commentuser = $params{username};
178
179                 my $oiduser = eval { IkiWiki::openiduser($commentuser) };
180
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                         );
192
193                         $commentauthor = $commentuser;
194                 }
195         }
196         else {
197                 if (defined $params{ip}) {
198                         $commentip = $params{ip};
199                 }
200                 $commentauthor = gettext("Anonymous");
201         }
202
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         }
215
216         if ($config{comments_allowauthor}) {
217                 if (defined $params{claimedauthor}) {
218                         $pagestate{$page}{meta}{author} = $params{claimedauthor};
219                 }
220
221                 if (defined $params{url}) {
222                         my $url=$params{url};
223
224                         eval q{use URI::Heuristic}; 
225                         if (! $@) {
226                                 $url=URI::Heuristic::uf_uristr($url);
227                         }
228
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         }
238
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         }
244
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         }
249
250         eval q{use Date::Parse};
251         if (! $@) {
252                 my $time = str2time($params{date});
253                 $IkiWiki::pagectime{$page} = $time if defined $time;
254         }
255
256         return $content;
257 }
258
259 sub preprocess_moderation {
260         my %params = @_;
261
262         $params{desc}=gettext("Comment Moderation")
263                 unless defined $params{desc};
264
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         }
273 }
274
275 sub sessioncgi ($$) {
276         my $cgi=shift;
277         my $session=shift;
278
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         }
290 }
291
292 # Mostly cargo-culted from IkiWiki::plugin::editpage
293 sub editcomment ($$) {
294         my $cgi=shift;
295         my $session=shift;
296
297         IkiWiki::decode_cgi_utf8($cgi);
298
299         eval q{use CGI::FormBuilder};
300         error($@) if $@;
301
302         my @buttons = (POST_COMMENT, PREVIEW, CANCEL);
303         my $form = CGI::FormBuilder->new(
304                 fields => [qw{do sid page subject editcontent type author url}],
305                 charset => 'utf-8',
306                 method => 'POST',
307                 required => [qw{editcontent}],
308                 javascript => 0,
309                 params => $cgi,
310                 action => IkiWiki::cgiurl(),
311                 header => 0,
312                 table => 0,
313                 template => { template('editcomment.tmpl') },
314         );
315
316         IkiWiki::decode_form_utf8($form);
317         IkiWiki::run_hooks(formbuilder_setup => sub {
318                         shift->(title => "comment", form => $form, cgi => $cgi,
319                                 session => $session, buttons => \@buttons);
320                 });
321         IkiWiki::decode_form_utf8($form);
322
323         my $type = $form->param('type');
324         if (defined $type && length $type && $IkiWiki::hooks{htmlize}{$type}) {
325                 $type = IkiWiki::possibly_foolish_untaint($type);
326         }
327         else {
328                 $type = $config{default_pageext};
329         }
330
331
332         my @page_types;
333         if (exists $IkiWiki::hooks{htmlize}) {
334                 foreach my $key (grep { !/^_/ } keys %{$IkiWiki::hooks{htmlize}}) {
335                         push @page_types, [$key, $IkiWiki::hooks{htmlize}{$key}{longname} || $key];
336                 }
337         }
338         @page_types=sort @page_types;
339
340         $form->field(name => 'do', type => 'hidden');
341         $form->field(name => 'sid', type => 'hidden', value => $session->id,
342                 force => 1);
343         $form->field(name => 'page', type => 'hidden');
344         $form->field(name => 'subject', type => 'text', size => 72);
345         $form->field(name => 'editcontent', type => 'textarea', rows => 10);
346         $form->field(name => "type", value => $type, force => 1,
347                 type => 'select', options => \@page_types);
348
349         $form->tmpl_param(username => $session->param('name'));
350
351         if ($config{comments_allowauthor} and
352             ! defined $session->param('name')) {
353                 $form->tmpl_param(allowauthor => 1);
354                 $form->field(name => 'author', type => 'text', size => '40');
355                 $form->field(name => 'url', type => 'text', size => '40');
356         }
357         else {
358                 $form->tmpl_param(allowauthor => 0);
359                 $form->field(name => 'author', type => 'hidden', value => '',
360                         force => 1);
361                 $form->field(name => 'url', type => 'hidden', value => '',
362                         force => 1);
363         }
364
365         if (! defined $session->param('name')) {
366                 # Make signinurl work and return here.
367                 $form->tmpl_param(signinurl => IkiWiki::cgiurl(do => 'commentsignin'));
368                 $session->param(postsignin => $ENV{QUERY_STRING});
369                 IkiWiki::cgi_savesession($session);
370         }
371
372         # The untaint is OK (as in editpage) because we're about to pass
373         # it to file_pruned and wiki_file_regexp anyway.
374         my ($page) = $form->field('page')=~/$config{wiki_file_regexp}/;
375         $page = IkiWiki::possibly_foolish_untaint($page);
376         if (! defined $page || ! length $page ||
377                 IkiWiki::file_pruned($page)) {
378                 error(gettext("bad page name"));
379         }
380
381         $form->title(sprintf(gettext("commenting on %s"),
382                         IkiWiki::pagetitle(IkiWiki::basename($page))));
383
384         $form->tmpl_param('helponformattinglink',
385                 htmllink($page, $page, 'ikiwiki/formatting',
386                         noimageinline => 1,
387                         linktext => 'FormattingHelp'),
388                         allowdirectives => $config{allow_directives});
389
390         if ($form->submitted eq CANCEL) {
391                 # bounce back to the page they wanted to comment on, and exit.
392                 IkiWiki::redirect($cgi, urlto($page));
393                 exit;
394         }
395
396         if (not exists $pagesources{$page}) {
397                 error(sprintf(gettext(
398                         "page '%s' doesn't exist, so you can't comment"),
399                         $page));
400         }
401
402         if (pagespec_match($page, $config{comments_closed_pagespec},
403                 location => $page)) {
404                 error(sprintf(gettext(
405                         "comments on page '%s' are closed"),
406                         $page));
407         }
408
409         # Set a flag to indicate that we're posting a comment,
410         # so that postcomment() can tell it should match.
411         $postcomment=1;
412         IkiWiki::check_canedit($page, $cgi, $session);
413         $postcomment=0;
414
415         my $content = "[[!comment format=$type\n";
416
417         if (defined $session->param('name')) {
418                 my $username = $session->param('name');
419                 $username =~ s/"/&quot;/g;
420                 $content .= " username=\"$username\"\n";
421         }
422         if (defined $session->param('nickname')) {
423                 my $nickname = $session->param('nickname');
424                 $nickname =~ s/"/&quot;/g;
425                 $content .= " nickname=\"$nickname\"\n";
426         }
427         elsif (defined $session->remote_addr()) {
428                 my $ip = $session->remote_addr();
429                 if ($ip =~ m/^([.0-9]+)$/) {
430                         $content .= " ip=\"$1\"\n";
431                 }
432         }
433
434         if ($config{comments_allowauthor}) {
435                 my $author = $form->field('author');
436                 if (defined $author && length $author) {
437                         $author =~ s/"/&quot;/g;
438                         $content .= " claimedauthor=\"$author\"\n";
439                 }
440                 my $url = $form->field('url');
441                 if (defined $url && length $url) {
442                         $url =~ s/"/&quot;/g;
443                         $content .= " url=\"$url\"\n";
444                 }
445         }
446
447         my $avatar=getavatar($session->param('name'));
448         if (defined $avatar && length $avatar) {
449                 $avatar =~ s/"/&quot;/g;
450                 $content .= " avatar=\"$avatar\"\n";
451         }
452
453         my $subject = $form->field('subject');
454         if (defined $subject && length $subject) {
455                 $subject =~ s/"/&quot;/g;
456         }
457         else {
458                 $subject = "comment ".(num_comments($page, $config{srcdir}) + 1);
459         }
460         $content .= " subject=\"$subject\"\n";
461
462         $content .= " date=\"" . strftime_utf8('%Y-%m-%dT%H:%M:%SZ', gmtime) . "\"\n";
463
464         my $editcontent = $form->field('editcontent');
465         $editcontent="" if ! defined $editcontent;
466         $editcontent =~ s/\r\n/\n/g;
467         $editcontent =~ s/\r/\n/g;
468         $editcontent =~ s/"/\\"/g;
469         $content .= " content=\"\"\"\n$editcontent\n\"\"\"]]\n";
470
471         my $location=unique_comment_location($page, $content, $config{srcdir});
472
473         # This is essentially a simplified version of editpage:
474         # - the user does not control the page that's created, only the parent
475         # - it's always a create operation, never an edit
476         # - this means that conflicts should never happen
477         # - this means that if they do, rocks fall and everyone dies
478
479         if ($form->submitted eq PREVIEW) {
480                 my $preview=previewcomment($content, $location, $page, time);
481                 IkiWiki::run_hooks(format => sub {
482                         $preview = shift->(page => $page,
483                                 content => $preview);
484                 });
485                 $form->tmpl_param(page_preview => $preview);
486         }
487         else {
488                 $form->tmpl_param(page_preview => "");
489         }
490
491         if ($form->submitted eq POST_COMMENT && $form->validate) {
492                 IkiWiki::checksessionexpiry($cgi, $session);
493                 
494                 $postcomment=1;
495                 my $ok=IkiWiki::check_content(content => $form->field('editcontent'),
496                         subject => $form->field('subject'),
497                         $config{comments_allowauthor} ? (
498                                 author => $form->field('author'),
499                                 url => $form->field('url'),
500                         ) : (),
501                         page => $location,
502                         cgi => $cgi,
503                         session => $session,
504                         nonfatal => 1,
505                 );
506                 $postcomment=0;
507
508                 if (! $ok) {
509                         $location=unique_comment_location($page, $content, $config{srcdir}, "._comment_pending");
510                         writefile("$location._comment_pending", $config{srcdir}, $content);
511
512                         # Refresh so anything that deals with pending
513                         # comments can be updated.
514                         require IkiWiki::Render;
515                         IkiWiki::refresh();
516                         IkiWiki::saveindex();
517
518                         IkiWiki::printheader($session);
519                         print IkiWiki::cgitemplate($cgi, gettext(gettext("comment stored for moderation")),
520                                 "<p>".
521                                 gettext("Your comment will be posted after moderator review").
522                                 "</p>");
523                         exit;
524                 }
525
526                 # FIXME: could probably do some sort of graceful retry
527                 # on error? Would require significant unwinding though
528                 my $file = "$location._comment";
529                 writefile($file, $config{srcdir}, $content);
530
531                 my $conflict;
532
533                 if ($config{rcs} and $config{comments_commit}) {
534                         my $message = gettext("Added a comment");
535                         if (defined $form->field('subject') &&
536                                 length $form->field('subject')) {
537                                 $message = sprintf(
538                                         gettext("Added a comment: %s"),
539                                         $form->field('subject'));
540                         }
541
542                         IkiWiki::rcs_add($file);
543                         IkiWiki::disable_commit_hook();
544                         $conflict = IkiWiki::rcs_commit_staged(
545                                 message => $message,
546                                 session => $session,
547                         );
548                         IkiWiki::enable_commit_hook();
549                         IkiWiki::rcs_update();
550                 }
551
552                 # Now we need a refresh
553                 require IkiWiki::Render;
554                 IkiWiki::refresh();
555                 IkiWiki::saveindex();
556
557                 # this should never happen, unless a committer deliberately
558                 # breaks it or something
559                 error($conflict) if defined $conflict;
560
561                 # Jump to the new comment on the page.
562                 # The trailing question mark tries to avoid broken
563                 # caches and get the most recent version of the page.
564                 IkiWiki::redirect($cgi, urlto($page).
565                         "?updated#".page_to_id($location));
566
567         }
568         else {
569                 IkiWiki::showform($form, \@buttons, $session, $cgi,
570                         page => $page);
571         }
572
573         exit;
574 }
575
576 sub getavatar ($) {
577         my $user=shift;
578         
579         my $avatar;
580         eval q{use Libravatar::URL};
581         if (! $@) {
582                 my $oiduser = eval { IkiWiki::openiduser($user) };
583                 my $https=defined $config{url} && $config{url}=~/^https:/;
584
585                 if (defined $oiduser) {
586                         eval {
587                                 $avatar = libravatar_url(openid => $user, https => $https);
588                         }
589                 }
590                 if (! defined $avatar &&
591                     (my $email = IkiWiki::userinfo_get($user, 'email'))) {
592                         eval {
593                                 $avatar = libravatar_url(email => $email, https => $https);
594                         }
595                 }
596         }
597         return $avatar;
598 }
599
600
601 sub commentmoderation ($$) {
602         my $cgi=shift;
603         my $session=shift;
604
605         IkiWiki::needsignin($cgi, $session);
606         if (! IkiWiki::is_admin($session->param("name"))) {
607                 error(gettext("you are not logged in as an admin"));
608         }
609
610         IkiWiki::decode_cgi_utf8($cgi);
611         
612         if (defined $cgi->param('sid')) {
613                 IkiWiki::checksessionexpiry($cgi, $session);
614
615                 my $rejectalldefer=$cgi->param('rejectalldefer');
616
617                 my %vars=$cgi->Vars;
618                 my $added=0;
619                 foreach my $id (keys %vars) {
620                         if ($id =~ /(.*)\._comment(?:_pending)?$/) {
621                                 $id=decode_utf8($id);
622                                 my $action=$cgi->param($id);
623                                 next if $action eq 'Defer' && ! $rejectalldefer;
624
625                                 # Make sure that the id is of a legal
626                                 # pending comment.
627                                 my ($f) = $id =~ /$config{wiki_file_regexp}/;
628                                 if (! defined $f || ! length $f ||
629                                     IkiWiki::file_pruned($f)) {
630                                         error("illegal file");
631                                 }
632
633                                 my $page=IkiWiki::dirname($f);
634                                 my $file="$config{srcdir}/$f";
635                                 if (! -e $file) {
636                                         # old location
637                                         $file="$config{wikistatedir}/comments_pending/".$f;
638                                 }
639
640                                 if ($action eq 'Accept') {
641                                         my $content=eval { readfile($file) };
642                                         next if $@; # file vanished since form was displayed
643                                         my $dest=unique_comment_location($page, $content, $config{srcdir})."._comment";
644                                         writefile($dest, $config{srcdir}, $content);
645                                         if ($config{rcs} and $config{comments_commit}) {
646                                                 IkiWiki::rcs_add($dest);
647                                         }
648                                         $added++;
649                                 }
650
651                                 require IkiWiki::Render;
652                                 IkiWiki::prune($file);
653                         }
654                 }
655
656                 if ($added) {
657                         my $conflict;
658                         if ($config{rcs} and $config{comments_commit}) {
659                                 my $message = gettext("Comment moderation");
660                                 IkiWiki::disable_commit_hook();
661                                 $conflict=IkiWiki::rcs_commit_staged(
662                                         message => $message,
663                                         session => $session,
664                                 );
665                                 IkiWiki::enable_commit_hook();
666                                 IkiWiki::rcs_update();
667                         }
668                 
669                         # Now we need a refresh
670                         require IkiWiki::Render;
671                         IkiWiki::refresh();
672                         IkiWiki::saveindex();
673                 
674                         error($conflict) if defined $conflict;
675                 }
676         }
677
678         my @comments=map {
679                 my ($id, $dir, $ctime)=@{$_};
680                 my $content=readfile("$dir/$id");
681                 my $preview=previewcomment($content, $id,
682                         $id, $ctime);
683                 {
684                         id => $id,
685                         view => $preview,
686                 }
687         } sort { $b->[2] <=> $a->[2] } comments_pending();
688
689         my $template=template("commentmoderation.tmpl");
690         $template->param(
691                 sid => $session->id,
692                 comments => \@comments,
693                 cgiurl => IkiWiki::cgiurl(),
694         );
695         IkiWiki::printheader($session);
696         my $out=$template->output;
697         IkiWiki::run_hooks(format => sub {
698                 $out = shift->(page => "", content => $out);
699         });
700         print IkiWiki::cgitemplate($cgi, gettext("comment moderation"), $out);
701         exit;
702 }
703
704 sub formbuilder_setup (@) {
705         my %params=@_;
706
707         my $form=$params{form};
708         if ($form->title eq "preferences" &&
709             IkiWiki::is_admin($params{session}->param("name"))) {
710                 push @{$params{buttons}}, "Comment Moderation";
711                 if ($form->submitted && $form->submitted eq "Comment Moderation") {
712                         commentmoderation($params{cgi}, $params{session});
713                 }
714         }
715 }
716
717 sub comments_pending () {
718         my @ret;
719
720         eval q{use File::Find};
721         error($@) if $@;
722         eval q{use Cwd};
723         error($@) if $@;
724         my $origdir=getcwd();
725
726         my $find_comments=sub {
727                 my $dir=shift;
728                 my $extension=shift;
729                 return unless -d $dir;
730
731                 chdir($dir) || die "chdir $dir: $!";
732
733                 find({
734                         no_chdir => 1,
735                         wanted => sub {
736                                 my $file=decode_utf8($_);
737                                 $file=~s/^\.\///;
738                                 return if ! length $file || IkiWiki::file_pruned($file)
739                                         || -l $_ || -d _ || $file !~ /\Q$extension\E$/;
740                                 my ($f) = $file =~ /$config{wiki_file_regexp}/; # untaint
741                                 if (defined $f) {
742                                         my $ctime=(stat($_))[10];
743                                         push @ret, [$f, $dir, $ctime];
744                                 }
745                         }
746                 }, ".");
747
748                 chdir($origdir) || die "chdir $origdir: $!";
749         };
750         
751         $find_comments->($config{srcdir}, "._comment_pending");
752         # old location
753         $find_comments->("$config{wikistatedir}/comments_pending/",
754                 "._comment");
755
756         return @ret;
757 }
758
759 sub previewcomment ($$$) {
760         my $content=shift;
761         my $location=shift;
762         my $page=shift;
763         my $time=shift;
764
765         # Previewing a comment should implicitly enable comment posting mode.
766         my $oldpostcomment=$postcomment;
767         $postcomment=1;
768
769         my $preview = IkiWiki::htmlize($location, $page, '_comment',
770                         IkiWiki::linkify($location, $page,
771                         IkiWiki::preprocess($location, $page,
772                         IkiWiki::filter($location, $page, $content), 0, 1)));
773
774         my $template = template("comment.tmpl");
775         $template->param(content => $preview);
776         $template->param(ctime => displaytime($time, undef, 1));
777         $template->param(html5 => $config{html5});
778
779         IkiWiki::run_hooks(pagetemplate => sub {
780                 shift->(page => $location,
781                         destpage => $page,
782                         template => $template);
783         });
784
785         $template->param(have_actions => 0);
786
787         $postcomment=$oldpostcomment;
788
789         return $template->output;
790 }
791
792 sub commentsshown ($) {
793         my $page=shift;
794
795         return pagespec_match($page, $config{comments_pagespec},
796                 location => $page);
797 }
798
799 sub commentsopen ($) {
800         my $page = shift;
801
802         return length $config{cgiurl} > 0 &&
803                (! length $config{comments_closed_pagespec} ||
804                 ! pagespec_match($page, $config{comments_closed_pagespec},
805                                  location => $page));
806 }
807
808 sub pagetemplate (@) {
809         my %params = @_;
810
811         my $page = $params{page};
812         my $template = $params{template};
813         my $shown = ($template->query(name => 'commentslink') ||
814                      $template->query(name => 'commentsurl') ||
815                      $template->query(name => 'atomcommentsurl') ||
816                      $template->query(name => 'comments')) &&
817                     commentsshown($page);
818
819         if ($template->query(name => 'comments')) {
820                 my $comments = undef;
821                 if ($shown) {
822                         $comments = IkiWiki::preprocess_inline(
823                                 pages => "comment($page) and !comment($page/*)",
824                                 template => 'comment',
825                                 show => 0,
826                                 reverse => 'yes',
827                                 page => $page,
828                                 destpage => $params{destpage},
829                                 feedfile => 'comments',
830                                 emptyfeeds => 'no',
831                         );
832                 }
833
834                 if (defined $comments && length $comments) {
835                         $template->param(comments => $comments);
836                 }
837
838                 if ($shown && commentsopen($page)) {
839                         $template->param(addcommenturl => addcommenturl($page));
840                 }
841         }
842
843         if ($shown) {
844                 if ($template->query(name => 'commentsurl')) {
845                         $template->param(commentsurl =>
846                                 urlto($page).'#comments');
847                 }
848
849                 if ($template->query(name => 'atomcommentsurl') && $config{usedirs}) {
850                         # This will 404 until there are some comments, but I
851                         # think that's probably OK...
852                         $template->param(atomcommentsurl =>
853                                 urlto($page).'comments.atom');
854                 }
855
856                 if ($template->query(name => 'commentslink')) {
857                         my $num=num_comments($page, $config{srcdir});
858                         my $link;
859                         if ($num > 0) {
860                                 $link = htmllink($page, $params{destpage}, $page,
861                                         linktext => sprintf(ngettext("%i comment", "%i comments", $num), $num),
862                                         anchor => "comments",
863                                         noimageinline => 1
864                                 );
865                         }
866                         elsif (commentsopen($page)) {
867                                 $link = "<a href=\"".addcommenturl($page)."\">".
868                                         #translators: Here "Comment" is a verb;
869                                         #translators: the user clicks on it to
870                                         #translators: post a comment.
871                                         gettext("Comment").
872                                         "</a>";
873                         }
874                         $template->param(commentslink => $link)
875                                 if defined $link;
876                 }
877         }
878
879         # everything below this point is only relevant to the comments
880         # themselves
881         if (!exists $commentstate{$page}) {
882                 return;
883         }
884         
885         if ($template->query(name => 'commentid')) {
886                 $template->param(commentid => page_to_id($page));
887         }
888
889         if ($template->query(name => 'commentuser')) {
890                 $template->param(commentuser =>
891                         $commentstate{$page}{commentuser});
892         }
893
894         if ($template->query(name => 'commentopenid')) {
895                 $template->param(commentopenid =>
896                         $commentstate{$page}{commentopenid});
897         }
898
899         if ($template->query(name => 'commentip')) {
900                 $template->param(commentip =>
901                         $commentstate{$page}{commentip});
902         }
903
904         if ($template->query(name => 'commentauthor')) {
905                 $template->param(commentauthor =>
906                         $commentstate{$page}{commentauthor});
907         }
908
909         if ($template->query(name => 'commentauthorurl')) {
910                 $template->param(commentauthorurl =>
911                         $commentstate{$page}{commentauthorurl});
912         }
913
914         if ($template->query(name => 'commentauthoravatar')) {
915                 $template->param(commentauthoravatar =>
916                         $commentstate{$page}{commentauthoravatar});
917         }
918
919         if ($template->query(name => 'removeurl') &&
920             IkiWiki::Plugin::remove->can("check_canremove") &&
921             length $config{cgiurl}) {
922                 $template->param(removeurl => IkiWiki::cgiurl(do => 'remove',
923                         page => $page));
924                 $template->param(have_actions => 1);
925         }
926 }
927
928 sub addcommenturl ($) {
929         my $page=shift;
930
931         return IkiWiki::cgiurl(do => 'comment', page => $page);
932 }
933
934 sub num_comments ($$) {
935         my $page=shift;
936         my $dir=shift;
937
938         my @comments=glob("$dir/$page/$config{comments_pagename}*._comment");
939         return int @comments;
940 }
941
942 sub unique_comment_location ($$$$) {
943         my $page=shift;
944         eval q{use Digest::MD5 'md5_hex'};
945         error($@) if $@;
946         my $content_md5=md5_hex(Encode::encode_utf8(shift));
947         my $dir=shift;
948         my $ext=shift || "._comment";
949
950         my $location;
951         my $i = num_comments($page, $dir);
952         do {
953                 $i++;
954                 $location = "$page/$config{comments_pagename}${i}_${content_md5}";
955         } while (-e "$dir/$location$ext");
956
957         return $location;
958 }
959
960 sub page_to_id ($) {
961         # Converts a comment page name into a unique, legal html id
962         # attribute value, that can be used as an anchor to link to the
963         # comment.
964         my $page=shift;
965
966         eval q{use Digest::MD5 'md5_hex'};
967         error($@) if $@;
968
969         return "comment-".md5_hex(Encode::encode_utf8(($page)));
970 }
971         
972 package IkiWiki::PageSpec;
973
974 sub match_postcomment ($$;@) {
975         my $page = shift;
976         my $glob = shift;
977
978         if (! $postcomment) {
979                 return IkiWiki::FailReason->new("not posting a comment");
980         }
981         return match_glob($page, $glob, @_);
982 }
983
984 sub match_comment ($$;@) {
985         my $page = shift;
986         my $glob = shift;
987
988         if (! $postcomment) {
989                 # To see if it's a comment, check the source file type.
990                 # Deal with comments that were just deleted.
991                 my $source=exists $IkiWiki::pagesources{$page} ?
992                         $IkiWiki::pagesources{$page} :
993                         $IkiWiki::delpagesources{$page};
994                 my $type=defined $source ? IkiWiki::pagetype($source) : undef;
995                 if (! defined $type || $type ne "_comment") {
996                         return IkiWiki::FailReason->new("$page is not a comment");
997                 }
998         }
999
1000         return match_glob($page, "$glob/*", internal => 1, @_);
1001 }
1002
1003 sub match_comment_pending ($$;@) {
1004         my $page = shift;
1005         my $glob = shift;
1006         
1007         my $source=exists $IkiWiki::pagesources{$page} ?
1008                 $IkiWiki::pagesources{$page} :
1009                 $IkiWiki::delpagesources{$page};
1010         my $type=defined $source ? IkiWiki::pagetype($source) : undef;
1011         if (! defined $type || $type ne "_comment_pending") {
1012                 return IkiWiki::FailReason->new("$page is not a pending comment");
1013         }
1014
1015         return match_glob($page, "$glob/*", internal => 1, @_);
1016 }
1017
1018 1