]> sipb.mit.edu Git - ikiwiki.git/blob - IkiWiki/Plugin/comments.pm
po: better rootpage logic for inline's post form
[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 use POSIX qw(strftime);
13
14 use constant PREVIEW => "Preview";
15 use constant POST_COMMENT => "Post comment";
16 use constant CANCEL => "Cancel";
17
18 my $postcomment;
19 my %commentstate;
20
21 sub import {
22         hook(type => "checkconfig", id => 'comments',  call => \&checkconfig);
23         hook(type => "getsetup", id => 'comments',  call => \&getsetup);
24         hook(type => "preprocess", id => 'comment', call => \&preprocess);
25         # here for backwards compatability with old comments
26         hook(type => "preprocess", id => '_comment', call => \&preprocess);
27         hook(type => "sessioncgi", id => 'comment', call => \&sessioncgi);
28         hook(type => "htmlize", id => "_comment", call => \&htmlize);
29         hook(type => "pagetemplate", id => "comments", call => \&pagetemplate);
30         hook(type => "formbuilder_setup", id => "comments", call => \&formbuilder_setup);
31         # Load goto to fix up user page links for logged-in commenters
32         IkiWiki::loadplugin("goto");
33         IkiWiki::loadplugin("inline");
34 }
35
36 sub getsetup () {
37         return
38                 plugin => {
39                         safe => 1,
40                         rebuild => 1,
41                 },
42                 comments_pagespec => {
43                         type => 'pagespec',
44                         example => 'blog/* and !*/Discussion',
45                         description => 'PageSpec of pages where comments are allowed',
46                         link => 'ikiwiki/PageSpec',
47                         safe => 1,
48                         rebuild => 1,
49                 },
50                 comments_closed_pagespec => {
51                         type => 'pagespec',
52                         example => 'blog/controversial or blog/flamewar',
53                         description => 'PageSpec of pages where posting new comments is not allowed',
54                         link => 'ikiwiki/PageSpec',
55                         safe => 1,
56                         rebuild => 1,
57                 },
58                 comments_pagename => {
59                         type => 'string',
60                         default => 'comment_',
61                         description => 'Base name for comments, e.g. "comment_" for pages like "sandbox/comment_12"',
62                         safe => 0, # manual page moving required
63                         rebuild => undef,
64                 },
65                 comments_allowdirectives => {
66                         type => 'boolean',
67                         example => 0,
68                         description => 'Interpret directives in comments?',
69                         safe => 1,
70                         rebuild => 0,
71                 },
72                 comments_allowauthor => {
73                         type => 'boolean',
74                         example => 0,
75                         description => 'Allow anonymous commenters to set an author name?',
76                         safe => 1,
77                         rebuild => 0,
78                 },
79                 comments_commit => {
80                         type => 'boolean',
81                         example => 1,
82                         description => 'commit comments to the VCS',
83                         # old uncommitted comments are likely to cause
84                         # confusion if this is changed
85                         safe => 0,
86                         rebuild => 0,
87                 },
88 }
89
90 sub checkconfig () {
91         $config{comments_commit} = 1
92                 unless defined $config{comments_commit};
93         $config{comments_pagespec} = ''
94                 unless defined $config{comments_pagespec};
95         $config{comments_closed_pagespec} = ''
96                 unless defined $config{comments_closed_pagespec};
97         $config{comments_pagename} = 'comment_'
98                 unless defined $config{comments_pagename};
99 }
100
101 sub htmlize {
102         my %params = @_;
103         return $params{content};
104 }
105
106 # FIXME: copied verbatim from meta
107 sub safeurl ($) {
108         my $url=shift;
109         if (exists $IkiWiki::Plugin::htmlscrubber::{safe_url_regexp} &&
110             defined $IkiWiki::Plugin::htmlscrubber::safe_url_regexp) {
111                 return $url=~/$IkiWiki::Plugin::htmlscrubber::safe_url_regexp/;
112         }
113         else {
114                 return 1;
115         }
116 }
117
118 sub preprocess {
119         my %params = @_;
120         my $page = $params{page};
121
122         my $format = $params{format};
123         if (defined $format && ! exists $IkiWiki::hooks{htmlize}{$format}) {
124                 error(sprintf(gettext("unsupported page format %s"), $format));
125         }
126
127         my $content = $params{content};
128         if (! defined $content) {
129                 error(gettext("comment must have content"));
130         }
131         $content =~ s/\\"/"/g;
132
133         $content = IkiWiki::filter($page, $params{destpage}, $content);
134
135         if ($config{comments_allowdirectives}) {
136                 $content = IkiWiki::preprocess($page, $params{destpage},
137                         $content);
138         }
139
140         # no need to bother with htmlize if it's just HTML
141         $content = IkiWiki::htmlize($page, $params{destpage}, $format, $content)
142                 if defined $format;
143
144         IkiWiki::run_hooks(sanitize => sub {
145                 $content = shift->(
146                         page => $page,
147                         destpage => $params{destpage},
148                         content => $content,
149                 );
150         });
151
152         # set metadata, possibly overriding [[!meta]] directives from the
153         # comment itself
154
155         my $commentuser;
156         my $commentip;
157         my $commentauthor;
158         my $commentauthorurl;
159         my $commentopenid;
160         if (defined $params{username}) {
161                 $commentuser = $params{username};
162
163                 my $oiduser = eval { IkiWiki::openiduser($commentuser) };
164
165                 if (defined $oiduser) {
166                         # looks like an OpenID
167                         $commentauthorurl = $commentuser;
168                         $commentauthor = $oiduser;
169                         $commentopenid = $commentuser;
170                 }
171                 else {
172                         $commentauthorurl = IkiWiki::cgiurl(
173                                 do => 'goto',
174                                 page => (length $config{userdir}
175                                         ? "$config{userdir}/$commentuser"
176                                         : "$commentuser"));
177
178                         $commentauthor = $commentuser;
179                 }
180         }
181         else {
182                 if (defined $params{ip}) {
183                         $commentip = $params{ip};
184                 }
185                 $commentauthor = gettext("Anonymous");
186         }
187
188         $commentstate{$page}{commentuser} = $commentuser;
189         $commentstate{$page}{commentopenid} = $commentopenid;
190         $commentstate{$page}{commentip} = $commentip;
191         $commentstate{$page}{commentauthor} = $commentauthor;
192         $commentstate{$page}{commentauthorurl} = $commentauthorurl;
193         if (! defined $pagestate{$page}{meta}{author}) {
194                 $pagestate{$page}{meta}{author} = $commentauthor;
195         }
196         if (! defined $pagestate{$page}{meta}{authorurl}) {
197                 $pagestate{$page}{meta}{authorurl} = $commentauthorurl;
198         }
199
200         if ($config{comments_allowauthor}) {
201                 if (defined $params{claimedauthor}) {
202                         $pagestate{$page}{meta}{author} = $params{claimedauthor};
203                 }
204
205                 if (defined $params{url}) {
206                         my $url=$params{url};
207
208                         eval q{use URI::Heuristic}; 
209                         if (! $@) {
210                                 $url=URI::Heuristic::uf_uristr($url);
211                         }
212
213                         if (safeurl($url)) {
214                                 $pagestate{$page}{meta}{authorurl} = $url;
215                         }
216                 }
217         }
218         else {
219                 $pagestate{$page}{meta}{author} = $commentauthor;
220                 $pagestate{$page}{meta}{authorurl} = $commentauthorurl;
221         }
222
223         if (defined $params{subject}) {
224                 $pagestate{$page}{meta}{title} = $params{subject};
225         }
226
227         if ($params{page} =~ m/\/(\Q$config{comments_pagename}\E\d+)$/) {
228                 $pagestate{$page}{meta}{permalink} = urlto(IkiWiki::dirname($params{page}), undef, 1).
229                         "#".page_to_id($params{page});
230         }
231
232         eval q{use Date::Parse};
233         if (! $@) {
234                 my $time = str2time($params{date});
235                 $IkiWiki::pagectime{$page} = $time if defined $time;
236         }
237
238         return $content;
239 }
240
241 sub sessioncgi ($$) {
242         my $cgi=shift;
243         my $session=shift;
244
245         my $do = $cgi->param('do');
246         if ($do eq 'comment') {
247                 editcomment($cgi, $session);
248         }
249         elsif ($do eq 'commentmoderation') {
250                 commentmoderation($cgi, $session);
251         }
252 }
253
254 # Mostly cargo-culted from IkiWiki::plugin::editpage
255 sub editcomment ($$) {
256         my $cgi=shift;
257         my $session=shift;
258
259         IkiWiki::decode_cgi_utf8($cgi);
260
261         eval q{use CGI::FormBuilder};
262         error($@) if $@;
263
264         my @buttons = (POST_COMMENT, PREVIEW, CANCEL);
265         my $form = CGI::FormBuilder->new(
266                 fields => [qw{do sid page subject editcontent type author url}],
267                 charset => 'utf-8',
268                 method => 'POST',
269                 required => [qw{editcontent}],
270                 javascript => 0,
271                 params => $cgi,
272                 action => $config{cgiurl},
273                 header => 0,
274                 table => 0,
275                 template => scalar IkiWiki::template_params('editcomment.tmpl'),
276         );
277
278         IkiWiki::decode_form_utf8($form);
279         IkiWiki::run_hooks(formbuilder_setup => sub {
280                         shift->(title => "comment", form => $form, cgi => $cgi,
281                                 session => $session, buttons => \@buttons);
282                 });
283         IkiWiki::decode_form_utf8($form);
284
285         my $type = $form->param('type');
286         if (defined $type && length $type && $IkiWiki::hooks{htmlize}{$type}) {
287                 $type = IkiWiki::possibly_foolish_untaint($type);
288         }
289         else {
290                 $type = $config{default_pageext};
291         }
292
293
294         my @page_types;
295         if (exists $IkiWiki::hooks{htmlize}) {
296                 foreach my $key (grep { !/^_/ } keys %{$IkiWiki::hooks{htmlize}}) {
297                         push @page_types, [$key, $IkiWiki::hooks{htmlize}{$key}{longname} || $key];
298                 }
299         }
300         @page_types=sort @page_types;
301
302         $form->field(name => 'do', type => 'hidden');
303         $form->field(name => 'sid', type => 'hidden', value => $session->id,
304                 force => 1);
305         $form->field(name => 'page', type => 'hidden');
306         $form->field(name => 'subject', type => 'text', size => 72);
307         $form->field(name => 'editcontent', type => 'textarea', rows => 10);
308         $form->field(name => "type", value => $type, force => 1,
309                 type => 'select', options => \@page_types);
310
311         $form->tmpl_param(username => $session->param('name'));
312
313         if ($config{comments_allowauthor} and
314             ! defined $session->param('name')) {
315                 $form->tmpl_param(allowauthor => 1);
316                 $form->field(name => 'author', type => 'text', size => '40');
317                 $form->field(name => 'url', type => 'text', size => '40');
318         }
319         else {
320                 $form->tmpl_param(allowauthor => 0);
321                 $form->field(name => 'author', type => 'hidden', value => '',
322                         force => 1);
323                 $form->field(name => 'url', type => 'hidden', value => '',
324                         force => 1);
325         }
326
327         if (! defined $session->param('name')) {
328                 # Make signinurl work and return here.
329                 $form->tmpl_param(signinurl => IkiWiki::cgiurl(do => 'signin'));
330                 $session->param(postsignin => $ENV{QUERY_STRING});
331                 IkiWiki::cgi_savesession($session);
332         }
333
334         # The untaint is OK (as in editpage) because we're about to pass
335         # it to file_pruned anyway
336         my $page = $form->field('page');
337         $page = IkiWiki::possibly_foolish_untaint($page);
338         if (! defined $page || ! length $page ||
339                 IkiWiki::file_pruned($page, $config{srcdir})) {
340                 error(gettext("bad page name"));
341         }
342
343         my $baseurl = urlto($page, undef, 1);
344
345         $form->title(sprintf(gettext("commenting on %s"),
346                         IkiWiki::pagetitle($page)));
347
348         $form->tmpl_param('helponformattinglink',
349                 htmllink($page, $page, 'ikiwiki/formatting',
350                         noimageinline => 1,
351                         linktext => 'FormattingHelp'),
352                         allowdirectives => $config{allow_directives});
353
354         if ($form->submitted eq CANCEL) {
355                 # bounce back to the page they wanted to comment on, and exit.
356                 # CANCEL need not be considered in future
357                 IkiWiki::redirect($cgi, urlto($page, undef, 1));
358                 exit;
359         }
360
361         if (not exists $pagesources{$page}) {
362                 error(sprintf(gettext(
363                         "page '%s' doesn't exist, so you can't comment"),
364                         $page));
365         }
366
367         if (pagespec_match($page, $config{comments_closed_pagespec},
368                 location => $page)) {
369                 error(sprintf(gettext(
370                         "comments on page '%s' are closed"),
371                         $page));
372         }
373
374         # Set a flag to indicate that we're posting a comment,
375         # so that postcomment() can tell it should match.
376         $postcomment=1;
377         IkiWiki::check_canedit($page, $cgi, $session);
378         $postcomment=0;
379
380         my $location=unique_comment_location($page, $config{srcdir});
381
382         my $content = "[[!comment format=$type\n";
383
384         # FIXME: handling of double quotes probably wrong?
385         if (defined $session->param('name')) {
386                 my $username = $session->param('name');
387                 $username =~ s/"/&quot;/g;
388                 $content .= " username=\"$username\"\n";
389         }
390         elsif (defined $ENV{REMOTE_ADDR}) {
391                 my $ip = $ENV{REMOTE_ADDR};
392                 if ($ip =~ m/^([.0-9]+)$/) {
393                         $content .= " ip=\"$1\"\n";
394                 }
395         }
396
397         if ($config{comments_allowauthor}) {
398                 my $author = $form->field('author');
399                 if (defined $author && length $author) {
400                         $author =~ s/"/&quot;/g;
401                         $content .= " claimedauthor=\"$author\"\n";
402                 }
403                 my $url = $form->field('url');
404                 if (defined $url && length $url) {
405                         $url =~ s/"/&quot;/g;
406                         $content .= " url=\"$url\"\n";
407                 }
408         }
409
410         my $subject = $form->field('subject');
411         if (defined $subject && length $subject) {
412                 $subject =~ s/"/&quot;/g;
413                 $content .= " subject=\"$subject\"\n";
414         }
415
416         $content .= " date=\"" . decode_utf8(strftime('%Y-%m-%dT%H:%M:%SZ', gmtime)) . "\"\n";
417
418         my $editcontent = $form->field('editcontent') || '';
419         $editcontent =~ s/\r\n/\n/g;
420         $editcontent =~ s/\r/\n/g;
421         $editcontent =~ s/"/\\"/g;
422         $content .= " content=\"\"\"\n$editcontent\n\"\"\"]]\n";
423
424         # This is essentially a simplified version of editpage:
425         # - the user does not control the page that's created, only the parent
426         # - it's always a create operation, never an edit
427         # - this means that conflicts should never happen
428         # - this means that if they do, rocks fall and everyone dies
429
430         if ($form->submitted eq PREVIEW) {
431                 my $preview=previewcomment($content, $location, $page, time);
432                 IkiWiki::run_hooks(format => sub {
433                         $preview = shift->(page => $page,
434                                 content => $preview);
435                 });
436                 $form->tmpl_param(page_preview => $preview);
437         }
438         else {
439                 $form->tmpl_param(page_preview => "");
440         }
441
442         if ($form->submitted eq POST_COMMENT && $form->validate) {
443                 IkiWiki::checksessionexpiry($cgi, $session);
444                 
445                 $postcomment=1;
446                 my $ok=IkiWiki::check_content(content => $form->field('editcontent'),
447                         subject => $form->field('subject'),
448                         $config{comments_allowauthor} ? (
449                                 author => $form->field('author'),
450                                 url => $form->field('url'),
451                         ) : (),
452                         page => $location,
453                         cgi => $cgi,
454                         session => $session,
455                         nonfatal => 1,
456                 );
457                 $postcomment=0;
458
459                 if (! $ok) {
460                         my $penddir=$config{wikistatedir}."/comments_pending";
461                         $location=unique_comment_location($page, $penddir);
462                         writefile("$location._comment", $penddir, $content);
463                         IkiWiki::printheader($session);
464                         print IkiWiki::misctemplate(gettext(gettext("comment stored for moderation")),
465                                 "<p>".
466                                 gettext("Your comment will be posted after moderator review").
467                                 "</p>");
468                         exit;
469                 }
470
471                 # FIXME: could probably do some sort of graceful retry
472                 # on error? Would require significant unwinding though
473                 my $file = "$location._comment";
474                 writefile($file, $config{srcdir}, $content);
475
476                 my $conflict;
477
478                 if ($config{rcs} and $config{comments_commit}) {
479                         my $message = gettext("Added a comment");
480                         if (defined $form->field('subject') &&
481                                 length $form->field('subject')) {
482                                 $message = sprintf(
483                                         gettext("Added a comment: %s"),
484                                         $form->field('subject'));
485                         }
486
487                         IkiWiki::rcs_add($file);
488                         IkiWiki::disable_commit_hook();
489                         $conflict = IkiWiki::rcs_commit_staged($message,
490                                 $session->param('name'), $ENV{REMOTE_ADDR});
491                         IkiWiki::enable_commit_hook();
492                         IkiWiki::rcs_update();
493                 }
494
495                 # Now we need a refresh
496                 require IkiWiki::Render;
497                 IkiWiki::refresh();
498                 IkiWiki::saveindex();
499
500                 # this should never happen, unless a committer deliberately
501                 # breaks it or something
502                 error($conflict) if defined $conflict;
503
504                 # Jump to the new comment on the page.
505                 # The trailing question mark tries to avoid broken
506                 # caches and get the most recent version of the page.
507                 IkiWiki::redirect($cgi, urlto($page, undef, 1).
508                         "?updated#".page_to_id($location));
509
510         }
511         else {
512                 IkiWiki::showform ($form, \@buttons, $session, $cgi,
513                         forcebaseurl => $baseurl);
514         }
515
516         exit;
517 }
518
519 sub commentmoderation ($$) {
520         my $cgi=shift;
521         my $session=shift;
522
523         IkiWiki::needsignin($cgi, $session);
524         if (! IkiWiki::is_admin($session->param("name"))) {
525                 error(gettext("you are not logged in as an admin"));
526         }
527
528         IkiWiki::decode_cgi_utf8($cgi);
529         
530         if (defined $cgi->param('sid')) {
531                 IkiWiki::checksessionexpiry($cgi, $session);
532
533                 my $rejectalldefer=$cgi->param('rejectalldefer');
534
535                 my %vars=$cgi->Vars;
536                 my $added=0;
537                 foreach my $id (keys %vars) {
538                         if ($id =~ /(.*)\Q._comment\E$/) {
539                                 my $action=$cgi->param($id);
540                                 next if $action eq 'Defer' && ! $rejectalldefer;
541
542                                 # Make sure that the id is of a legal
543                                 # pending comment before untainting.
544                                 my ($f)= $id =~ /$config{wiki_file_regexp}/;
545                                 if (! defined $f || ! length $f ||
546                                     IkiWiki::file_pruned($f, $config{srcdir})) {
547                                         error("illegal file");
548                                 }
549
550                                 my $page=IkiWiki::possibly_foolish_untaint(IkiWiki::dirname($1));
551                                 my $file="$config{wikistatedir}/comments_pending/".
552                                         IkiWiki::possibly_foolish_untaint($id);
553
554                                 if ($action eq 'Accept') {
555                                         my $content=eval { readfile($file) };
556                                         next if $@; # file vanished since form was displayed
557                                         my $dest=unique_comment_location($page, $config{srcdir})."._comment";
558                                         writefile($dest, $config{srcdir}, $content);
559                                         if ($config{rcs} and $config{comments_commit}) {
560                                                 IkiWiki::rcs_add($dest);
561                                         }
562                                         $added++;
563                                 }
564
565                                 # This removes empty subdirs, so the
566                                 # .ikiwiki/comments_pending dir will
567                                 # go away when all are moderated.
568                                 require IkiWiki::Render;
569                                 IkiWiki::prune($file);
570                         }
571                 }
572
573                 if ($added) {
574                         my $conflict;
575                         if ($config{rcs} and $config{comments_commit}) {
576                                 my $message = gettext("Comment moderation");
577                                 IkiWiki::disable_commit_hook();
578                                 $conflict=IkiWiki::rcs_commit_staged($message,
579                                         $session->param('name'), $ENV{REMOTE_ADDR});
580                                 IkiWiki::enable_commit_hook();
581                                 IkiWiki::rcs_update();
582                         }
583                 
584                         # Now we need a refresh
585                         require IkiWiki::Render;
586                         IkiWiki::refresh();
587                         IkiWiki::saveindex();
588                 
589                         error($conflict) if defined $conflict;
590                 }
591         }
592
593         my @comments=map {
594                 my ($id, $ctime)=@{$_};
595                 my $file="$config{wikistatedir}/comments_pending/$id";
596                 my $content=readfile($file);
597                 my $preview=previewcomment($content, $id,
598                         IkiWiki::dirname($_), $ctime);
599                 {
600                         id => $id,
601                         view => $preview,
602                 } 
603         } sort { $b->[1] <=> $a->[1] } comments_pending();
604
605         my $template=template("commentmoderation.tmpl");
606         $template->param(
607                 sid => $session->id,
608                 comments => \@comments,
609         );
610         IkiWiki::printheader($session);
611         my $out=$template->output;
612         IkiWiki::run_hooks(format => sub {
613                 $out = shift->(page => "", content => $out);
614         });
615         print IkiWiki::misctemplate(gettext("comment moderation"), $out);
616         exit;
617 }
618
619 sub formbuilder_setup (@) {
620         my %params=@_;
621
622         my $form=$params{form};
623         if ($form->title eq "preferences" &&
624             IkiWiki::is_admin($params{session}->param("name"))) {
625                 push @{$params{buttons}}, "Comment Moderation";
626                 if ($form->submitted && $form->submitted eq "Comment Moderation") {
627                         commentmoderation($params{cgi}, $params{session});
628                 }
629         }
630 }
631
632 sub comments_pending () {
633         my $dir="$config{wikistatedir}/comments_pending/";
634         return unless -d $dir;
635
636         my @ret;
637         eval q{use File::Find};
638         error($@) if $@;
639         find({
640                 no_chdir => 1,
641                 wanted => sub {
642                         $_=decode_utf8($_);
643                         if (IkiWiki::file_pruned($_, $dir)) {
644                                 $File::Find::prune=1;
645                         }
646                         elsif (! -l $_ && ! -d _) {
647                                 $File::Find::prune=0;
648                                 my ($f)=/$config{wiki_file_regexp}/; # untaint
649                                 if (defined $f && $f =~ /\Q._comment\E$/) {
650                                         my $ctime=(stat($f))[10];
651                                         $f=~s/^\Q$dir\E\/?//;
652                                         push @ret, [$f, $ctime];
653                                 }
654                         }
655                 }
656         }, $dir);
657
658         return @ret;
659 }
660
661 sub previewcomment ($$$) {
662         my $content=shift;
663         my $location=shift;
664         my $page=shift;
665         my $time=shift;
666
667         my $preview = IkiWiki::htmlize($location, $page, '_comment',
668                         IkiWiki::linkify($location, $page,
669                         IkiWiki::preprocess($location, $page,
670                         IkiWiki::filter($location, $page, $content), 0, 1)));
671
672         my $template = template("comment.tmpl");
673         $template->param(content => $preview);
674         $template->param(ctime => displaytime($time));
675
676         IkiWiki::run_hooks(pagetemplate => sub {
677                 shift->(page => $location,
678                         destpage => $page,
679                         template => $template);
680         });
681
682         $template->param(have_actions => 0);
683
684         return $template->output;
685 }
686
687 sub commentsshown ($) {
688         my $page=shift;
689
690         return ! pagespec_match($page, "internal(*/$config{comments_pagename}*)",
691                                 location => $page) &&
692                pagespec_match($page, $config{comments_pagespec},
693                               location => $page);
694 }
695
696 sub commentsopen ($) {
697         my $page = shift;
698
699         return length $config{cgiurl} > 0 &&
700                (! length $config{comments_closed_pagespec} ||
701                 ! pagespec_match($page, $config{comments_closed_pagespec},
702                                  location => $page));
703 }
704
705 sub pagetemplate (@) {
706         my %params = @_;
707
708         my $page = $params{page};
709         my $template = $params{template};
710         my $shown = ($template->query(name => 'commentslink') ||
711                      $template->query(name => 'commentsurl') ||
712                      $template->query(name => 'atomcommentsurl') ||
713                      $template->query(name => 'comments')) &&
714                     commentsshown($page);
715
716         if ($template->query(name => 'comments')) {
717                 my $comments = undef;
718                 if ($shown) {
719                         $comments = IkiWiki::preprocess_inline(
720                                 pages => "internal($page/$config{comments_pagename}*)",
721                                 template => 'comment',
722                                 show => 0,
723                                 reverse => 'yes',
724                                 page => $page,
725                                 destpage => $params{destpage},
726                                 feedfile => 'comments',
727                                 emptyfeeds => 'no',
728                         );
729                 }
730
731                 if (defined $comments && length $comments) {
732                         $template->param(comments => $comments);
733                 }
734
735                 if ($shown && commentsopen($page)) {
736                         my $addcommenturl = IkiWiki::cgiurl(do => 'comment',
737                                 page => $page);
738                         $template->param(addcommenturl => $addcommenturl);
739                 }
740         }
741
742         if ($template->query(name => 'commentsurl')) {
743                 if ($shown) {
744                         $template->param(commentsurl =>
745                                 urlto($page, undef, 1).'#comments');
746                 }
747         }
748
749         if ($template->query(name => 'atomcommentsurl') && $config{usedirs}) {
750                 if ($shown) {
751                         # This will 404 until there are some comments, but I
752                         # think that's probably OK...
753                         $template->param(atomcommentsurl =>
754                                 urlto($page, undef, 1).'comments.atom');
755                 }
756         }
757
758         if ($template->query(name => 'commentslink')) {
759                 # XXX Would be nice to say how many comments there are in
760                 # the link. But, to update the number, blog pages
761                 # would have to update whenever comments of any inlines
762                 # page are added, which is not currently done.
763                 if ($shown) {
764                         $template->param(commentslink =>
765                                 htmllink($page, $params{destpage}, $page,
766                                         linktext => gettext("Comments"),
767                                         anchor => "comments",
768                                         noimageinline => 1));
769                 }
770         }
771
772         # everything below this point is only relevant to the comments
773         # themselves
774         if (!exists $commentstate{$page}) {
775                 return;
776         }
777         
778         if ($template->query(name => 'commentid')) {
779                 $template->param(commentid => page_to_id($page));
780         }
781
782         if ($template->query(name => 'commentuser')) {
783                 $template->param(commentuser =>
784                         $commentstate{$page}{commentuser});
785         }
786
787         if ($template->query(name => 'commentopenid')) {
788                 $template->param(commentopenid =>
789                         $commentstate{$page}{commentopenid});
790         }
791
792         if ($template->query(name => 'commentip')) {
793                 $template->param(commentip =>
794                         $commentstate{$page}{commentip});
795         }
796
797         if ($template->query(name => 'commentauthor')) {
798                 $template->param(commentauthor =>
799                         $commentstate{$page}{commentauthor});
800         }
801
802         if ($template->query(name => 'commentauthorurl')) {
803                 $template->param(commentauthorurl =>
804                         $commentstate{$page}{commentauthorurl});
805         }
806
807         if ($template->query(name => 'removeurl') &&
808             IkiWiki::Plugin::remove->can("check_canremove") &&
809             length $config{cgiurl}) {
810                 $template->param(removeurl => IkiWiki::cgiurl(do => 'remove',
811                         page => $page));
812                 $template->param(have_actions => 1);
813         }
814 }
815
816 sub unique_comment_location ($) {
817         my $page=shift;
818         my $dir=shift;
819
820         my $location;
821         my $i = 0;
822         do {
823                 $i++;
824                 $location = "$page/$config{comments_pagename}$i";
825         } while (-e "$dir/$location._comment");
826
827         return $location;
828 }
829
830 sub page_to_id ($) {
831         # Converts a comment page name into a unique, legal html id
832         # addtibute value, that can be used as an anchor to link to the
833         # comment.
834         my $page=shift;
835
836         eval q{use Digest::MD5 'md5_hex'};
837         error($@) if $@;
838
839         return "comment-".md5_hex($page);
840 }
841         
842 package IkiWiki::PageSpec;
843
844 sub match_postcomment ($$;@) {
845         my $page = shift;
846         my $glob = shift;
847
848         if (! $postcomment) {
849                 return IkiWiki::FailReason->new("not posting a comment");
850         }
851         return match_glob($page, $glob);
852 }
853
854 1