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;
12 use POSIX qw(strftime);
14 use constant PREVIEW => "Preview";
15 use constant POST_COMMENT => "Post comment";
16 use constant CANCEL => "Cancel";
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 => "htmlize", id => "_comment_pending",
30 call => \&htmlize_pending);
31 hook(type => "pagetemplate", id => "comments", call => \&pagetemplate);
32 hook(type => "formbuilder_setup", id => "comments",
33 call => \&formbuilder_setup);
34 # Load goto to fix up user page links for logged-in commenters
35 IkiWiki::loadplugin("goto");
36 IkiWiki::loadplugin("inline");
46 comments_pagespec => {
48 example => 'blog/* and !*/Discussion',
49 description => 'PageSpec of pages where comments are allowed',
50 link => 'ikiwiki/PageSpec',
54 comments_closed_pagespec => {
56 example => 'blog/controversial or blog/flamewar',
57 description => 'PageSpec of pages where posting new comments is not allowed',
58 link => 'ikiwiki/PageSpec',
62 comments_pagename => {
64 default => 'comment_',
65 description => 'Base name for comments, e.g. "comment_" for pages like "sandbox/comment_12"',
66 safe => 0, # manual page moving required
69 comments_allowdirectives => {
72 description => 'Interpret directives in comments?',
76 comments_allowauthor => {
79 description => 'Allow anonymous commenters to set an author name?',
86 description => 'commit comments to the VCS',
87 # old uncommitted comments are likely to cause
88 # confusion if this is changed
95 $config{comments_commit} = 1
96 unless defined $config{comments_commit};
97 $config{comments_pagespec} = ''
98 unless defined $config{comments_pagespec};
99 $config{comments_closed_pagespec} = ''
100 unless defined $config{comments_closed_pagespec};
101 $config{comments_pagename} = 'comment_'
102 unless defined $config{comments_pagename};
107 return $params{content};
110 sub htmlize_pending {
112 return sprintf(gettext("this comment needs %s"),
114 IkiWiki::cgiurl(do => "commentmoderation").'">'.
115 gettext("moderation").'</a>');
118 # FIXME: copied verbatim from meta
121 if (exists $IkiWiki::Plugin::htmlscrubber::{safe_url_regexp} &&
122 defined $IkiWiki::Plugin::htmlscrubber::safe_url_regexp) {
123 return $url=~/$IkiWiki::Plugin::htmlscrubber::safe_url_regexp/;
132 my $page = $params{page};
134 my $format = $params{format};
135 if (defined $format && ! exists $IkiWiki::hooks{htmlize}{$format}) {
136 error(sprintf(gettext("unsupported page format %s"), $format));
139 my $content = $params{content};
140 if (! defined $content) {
141 error(gettext("comment must have content"));
143 $content =~ s/\\"/"/g;
145 if ($config{comments_allowdirectives}) {
146 $content = IkiWiki::preprocess($page, $params{destpage},
150 # no need to bother with htmlize if it's just HTML
151 $content = IkiWiki::htmlize($page, $params{destpage}, $format, $content)
154 IkiWiki::run_hooks(sanitize => sub {
157 destpage => $params{destpage},
162 # set metadata, possibly overriding [[!meta]] directives from the
168 my $commentauthorurl;
170 if (defined $params{username}) {
171 $commentuser = $params{username};
173 my $oiduser = eval { IkiWiki::openiduser($commentuser) };
175 if (defined $oiduser) {
176 # looks like an OpenID
177 $commentauthorurl = $commentuser;
178 $commentauthor = (defined $params{nickname} && length $params{nickname}) ? $params{nickname} : $oiduser;
179 $commentopenid = $commentuser;
182 $commentauthorurl = IkiWiki::cgiurl(
184 page => IkiWiki::userpage($commentuser)
187 $commentauthor = $commentuser;
191 if (defined $params{ip}) {
192 $commentip = $params{ip};
194 $commentauthor = gettext("Anonymous");
197 $commentstate{$page}{commentuser} = $commentuser;
198 $commentstate{$page}{commentopenid} = $commentopenid;
199 $commentstate{$page}{commentip} = $commentip;
200 $commentstate{$page}{commentauthor} = $commentauthor;
201 $commentstate{$page}{commentauthorurl} = $commentauthorurl;
202 if (! defined $pagestate{$page}{meta}{author}) {
203 $pagestate{$page}{meta}{author} = $commentauthor;
205 if (! defined $pagestate{$page}{meta}{authorurl}) {
206 $pagestate{$page}{meta}{authorurl} = $commentauthorurl;
209 if ($config{comments_allowauthor}) {
210 if (defined $params{claimedauthor}) {
211 $pagestate{$page}{meta}{author} = $params{claimedauthor};
214 if (defined $params{url}) {
215 my $url=$params{url};
217 eval q{use URI::Heuristic};
219 $url=URI::Heuristic::uf_uristr($url);
223 $pagestate{$page}{meta}{authorurl} = $url;
228 $pagestate{$page}{meta}{author} = $commentauthor;
229 $pagestate{$page}{meta}{authorurl} = $commentauthorurl;
232 if (defined $params{subject}) {
233 # decode title the same way meta does
234 eval q{use HTML::Entities};
235 $pagestate{$page}{meta}{title} = decode_entities($params{subject});
238 if ($params{page} =~ m/\/\Q$config{comments_pagename}\E\d+_/) {
239 $pagestate{$page}{meta}{permalink} = urlto(IkiWiki::dirname($params{page}), undef, 1).
240 "#".page_to_id($params{page});
243 eval q{use Date::Parse};
245 my $time = str2time($params{date});
246 $IkiWiki::pagectime{$page} = $time if defined $time;
252 sub sessioncgi ($$) {
256 my $do = $cgi->param('do');
257 if ($do eq 'comment') {
258 editcomment($cgi, $session);
260 elsif ($do eq 'commentmoderation') {
261 commentmoderation($cgi, $session);
263 elsif ($do eq 'commentsignin') {
264 IkiWiki::cgi_signin($cgi, $session);
269 # Mostly cargo-culted from IkiWiki::plugin::editpage
270 sub editcomment ($$) {
274 IkiWiki::decode_cgi_utf8($cgi);
276 eval q{use CGI::FormBuilder};
279 my @buttons = (POST_COMMENT, PREVIEW, CANCEL);
280 my $form = CGI::FormBuilder->new(
281 fields => [qw{do sid page subject editcontent type author url}],
284 required => [qw{editcontent}],
287 action => $config{cgiurl},
290 template => { template('editcomment.tmpl') },
293 IkiWiki::decode_form_utf8($form);
294 IkiWiki::run_hooks(formbuilder_setup => sub {
295 shift->(title => "comment", form => $form, cgi => $cgi,
296 session => $session, buttons => \@buttons);
298 IkiWiki::decode_form_utf8($form);
300 my $type = $form->param('type');
301 if (defined $type && length $type && $IkiWiki::hooks{htmlize}{$type}) {
302 $type = IkiWiki::possibly_foolish_untaint($type);
305 $type = $config{default_pageext};
310 if (exists $IkiWiki::hooks{htmlize}) {
311 foreach my $key (grep { !/^_/ } keys %{$IkiWiki::hooks{htmlize}}) {
312 push @page_types, [$key, $IkiWiki::hooks{htmlize}{$key}{longname} || $key];
315 @page_types=sort @page_types;
317 $form->field(name => 'do', type => 'hidden');
318 $form->field(name => 'sid', type => 'hidden', value => $session->id,
320 $form->field(name => 'page', type => 'hidden');
321 $form->field(name => 'subject', type => 'text', size => 72);
322 $form->field(name => 'editcontent', type => 'textarea', rows => 10);
323 $form->field(name => "type", value => $type, force => 1,
324 type => 'select', options => \@page_types);
326 $form->tmpl_param(username => $session->param('name'));
328 if ($config{comments_allowauthor} and
329 ! defined $session->param('name')) {
330 $form->tmpl_param(allowauthor => 1);
331 $form->field(name => 'author', type => 'text', size => '40');
332 $form->field(name => 'url', type => 'text', size => '40');
335 $form->tmpl_param(allowauthor => 0);
336 $form->field(name => 'author', type => 'hidden', value => '',
338 $form->field(name => 'url', type => 'hidden', value => '',
342 if (! defined $session->param('name')) {
343 # Make signinurl work and return here.
344 $form->tmpl_param(signinurl => IkiWiki::cgiurl(do => 'commentsignin'));
345 $session->param(postsignin => $ENV{QUERY_STRING});
346 IkiWiki::cgi_savesession($session);
349 # The untaint is OK (as in editpage) because we're about to pass
350 # it to file_pruned anyway
351 my $page = $form->field('page');
352 $page = IkiWiki::possibly_foolish_untaint($page);
353 if (! defined $page || ! length $page ||
354 IkiWiki::file_pruned($page)) {
355 error(gettext("bad page name"));
358 my $baseurl = urlto($page, undef, 1);
360 $form->title(sprintf(gettext("commenting on %s"),
361 IkiWiki::pagetitle($page)));
363 $form->tmpl_param('helponformattinglink',
364 htmllink($page, $page, 'ikiwiki/formatting',
366 linktext => 'FormattingHelp'),
367 allowdirectives => $config{allow_directives});
369 if ($form->submitted eq CANCEL) {
370 # bounce back to the page they wanted to comment on, and exit.
371 # CANCEL need not be considered in future
372 IkiWiki::redirect($cgi, urlto($page, undef, 1));
376 if (not exists $pagesources{$page}) {
377 error(sprintf(gettext(
378 "page '%s' doesn't exist, so you can't comment"),
382 if (pagespec_match($page, $config{comments_closed_pagespec},
383 location => $page)) {
384 error(sprintf(gettext(
385 "comments on page '%s' are closed"),
389 # Set a flag to indicate that we're posting a comment,
390 # so that postcomment() can tell it should match.
392 IkiWiki::check_canedit($page, $cgi, $session);
395 my $content = "[[!comment format=$type\n";
397 if (defined $session->param('name')) {
398 my $username = $session->param('name');
399 $username =~ s/"/"/g;
400 $content .= " username=\"$username\"\n";
402 if (defined $session->param('nickname')) {
403 my $nickname = $session->param('nickname');
404 $nickname =~ s/"/"/g;
405 $content .= " nickname=\"$nickname\"\n";
407 elsif (defined $session->remote_addr()) {
408 my $ip = $session->remote_addr();
409 if ($ip =~ m/^([.0-9]+)$/) {
410 $content .= " ip=\"$1\"\n";
414 if ($config{comments_allowauthor}) {
415 my $author = $form->field('author');
416 if (defined $author && length $author) {
417 $author =~ s/"/"/g;
418 $content .= " claimedauthor=\"$author\"\n";
420 my $url = $form->field('url');
421 if (defined $url && length $url) {
422 $url =~ s/"/"/g;
423 $content .= " url=\"$url\"\n";
427 my $subject = $form->field('subject');
428 if (defined $subject && length $subject) {
429 $subject =~ s/"/"/g;
432 $subject = "comment ".(num_comments($page, $config{srcdir}) + 1);
434 $content .= " subject=\"$subject\"\n";
436 $content .= " date=\"" . decode_utf8(strftime('%Y-%m-%dT%H:%M:%SZ', gmtime)) . "\"\n";
438 my $editcontent = $form->field('editcontent');
439 $editcontent="" if ! defined $editcontent;
440 $editcontent =~ s/\r\n/\n/g;
441 $editcontent =~ s/\r/\n/g;
442 $editcontent =~ s/"/\\"/g;
443 $content .= " content=\"\"\"\n$editcontent\n\"\"\"]]\n";
445 my $location=unique_comment_location($page, $content, $config{srcdir});
447 # This is essentially a simplified version of editpage:
448 # - the user does not control the page that's created, only the parent
449 # - it's always a create operation, never an edit
450 # - this means that conflicts should never happen
451 # - this means that if they do, rocks fall and everyone dies
453 if ($form->submitted eq PREVIEW) {
454 my $preview=previewcomment($content, $location, $page, time);
455 IkiWiki::run_hooks(format => sub {
456 $preview = shift->(page => $page,
457 content => $preview);
459 $form->tmpl_param(page_preview => $preview);
462 $form->tmpl_param(page_preview => "");
465 if ($form->submitted eq POST_COMMENT && $form->validate) {
466 IkiWiki::checksessionexpiry($cgi, $session);
469 my $ok=IkiWiki::check_content(content => $form->field('editcontent'),
470 subject => $form->field('subject'),
471 $config{comments_allowauthor} ? (
472 author => $form->field('author'),
473 url => $form->field('url'),
483 $location=unique_comment_location($page, $content, $config{srcdir}, "._comment_pending");
484 writefile("$location._comment_pending", $config{srcdir}, $content);
486 # Refresh so anything that deals with pending
487 # comments can be updated.
488 require IkiWiki::Render;
490 IkiWiki::saveindex();
492 IkiWiki::printheader($session);
493 print IkiWiki::misctemplate(gettext(gettext("comment stored for moderation")),
495 gettext("Your comment will be posted after moderator review").
500 # FIXME: could probably do some sort of graceful retry
501 # on error? Would require significant unwinding though
502 my $file = "$location._comment";
503 writefile($file, $config{srcdir}, $content);
507 if ($config{rcs} and $config{comments_commit}) {
508 my $message = gettext("Added a comment");
509 if (defined $form->field('subject') &&
510 length $form->field('subject')) {
512 gettext("Added a comment: %s"),
513 $form->field('subject'));
516 IkiWiki::rcs_add($file);
517 IkiWiki::disable_commit_hook();
518 $conflict = IkiWiki::rcs_commit_staged(
522 IkiWiki::enable_commit_hook();
523 IkiWiki::rcs_update();
526 # Now we need a refresh
527 require IkiWiki::Render;
529 IkiWiki::saveindex();
531 # this should never happen, unless a committer deliberately
532 # breaks it or something
533 error($conflict) if defined $conflict;
535 # Jump to the new comment on the page.
536 # The trailing question mark tries to avoid broken
537 # caches and get the most recent version of the page.
538 IkiWiki::redirect($cgi, urlto($page, undef, 1).
539 "?updated#".page_to_id($location));
543 IkiWiki::showform ($form, \@buttons, $session, $cgi,
544 forcebaseurl => $baseurl, page => $page);
550 sub commentmoderation ($$) {
554 IkiWiki::needsignin($cgi, $session);
555 if (! IkiWiki::is_admin($session->param("name"))) {
556 error(gettext("you are not logged in as an admin"));
559 IkiWiki::decode_cgi_utf8($cgi);
561 if (defined $cgi->param('sid')) {
562 IkiWiki::checksessionexpiry($cgi, $session);
564 my $rejectalldefer=$cgi->param('rejectalldefer');
568 foreach my $id (keys %vars) {
569 if ($id =~ /(.*)\._comment(?:_pending)?$/) {
570 my $action=$cgi->param($id);
571 next if $action eq 'Defer' && ! $rejectalldefer;
573 # Make sure that the id is of a legal
575 my ($f) = $id =~ /$config{wiki_file_regexp}/;
576 if (! defined $f || ! length $f ||
577 IkiWiki::file_pruned($f)) {
578 error("illegal file");
581 my $page=IkiWiki::dirname($f);
582 my $file="$config{srcdir}/$f";
585 $file="$config{wikistatedir}/comments_pending/".$f;
588 if ($action eq 'Accept') {
589 my $content=eval { readfile($file) };
590 next if $@; # file vanished since form was displayed
591 my $dest=unique_comment_location($page, $content, $config{srcdir})."._comment";
592 writefile($dest, $config{srcdir}, $content);
593 if ($config{rcs} and $config{comments_commit}) {
594 IkiWiki::rcs_add($dest);
599 require IkiWiki::Render;
600 IkiWiki::prune($file);
606 if ($config{rcs} and $config{comments_commit}) {
607 my $message = gettext("Comment moderation");
608 IkiWiki::disable_commit_hook();
609 $conflict=IkiWiki::rcs_commit_staged(
613 IkiWiki::enable_commit_hook();
614 IkiWiki::rcs_update();
617 # Now we need a refresh
618 require IkiWiki::Render;
620 IkiWiki::saveindex();
622 error($conflict) if defined $conflict;
627 my ($id, $dir, $ctime)=@{$_};
628 my $content=readfile("$dir/$id");
629 my $preview=previewcomment($content, $id,
635 } sort { $b->[2] <=> $a->[2] } comments_pending();
637 my $template=template("commentmoderation.tmpl");
640 comments => \@comments,
642 IkiWiki::printheader($session);
643 my $out=$template->output;
644 IkiWiki::run_hooks(format => sub {
645 $out = shift->(page => "", content => $out);
647 print IkiWiki::misctemplate(gettext("comment moderation"), $out);
651 sub formbuilder_setup (@) {
654 my $form=$params{form};
655 if ($form->title eq "preferences" &&
656 IkiWiki::is_admin($params{session}->param("name"))) {
657 push @{$params{buttons}}, "Comment Moderation";
658 if ($form->submitted && $form->submitted eq "Comment Moderation") {
659 commentmoderation($params{cgi}, $params{session});
664 sub comments_pending () {
667 eval q{use File::Find};
671 my $origdir=getcwd();
673 my $find_comments=sub {
676 return unless -d $dir;
678 chdir($dir) || die "chdir $dir: $!";
683 my $file=decode_utf8($_);
685 return if ! length $file || IkiWiki::file_pruned($file)
686 || -l $_ || -d _ || $file !~ /\Q$extension\E$/;
687 my ($f) = $file =~ /$config{wiki_file_regexp}/; # untaint
689 my $ctime=(stat($_))[10];
690 push @ret, [$f, $dir, $ctime];
695 chdir($origdir) || die "chdir $origdir: $!";
698 $find_comments->($config{srcdir}, "._comment_pending");
700 $find_comments->("$config{wikistatedir}/comments_pending/",
706 sub previewcomment ($$$) {
712 my $preview = IkiWiki::htmlize($location, $page, '_comment',
713 IkiWiki::linkify($location, $page,
714 IkiWiki::preprocess($location, $page,
715 IkiWiki::filter($location, $page, $content), 0, 1)));
717 my $template = template("comment.tmpl");
718 $template->param(content => $preview);
719 $template->param(ctime => displaytime($time, undef, 1));
720 $template->param(html5 => $config{html5});
722 IkiWiki::run_hooks(pagetemplate => sub {
723 shift->(page => $location,
725 template => $template);
728 $template->param(have_actions => 0);
730 return $template->output;
733 sub commentsshown ($) {
736 return ! pagespec_match($page, "comment(*)",
737 location => $page) &&
738 pagespec_match($page, $config{comments_pagespec},
742 sub commentsopen ($) {
745 return length $config{cgiurl} > 0 &&
746 (! length $config{comments_closed_pagespec} ||
747 ! pagespec_match($page, $config{comments_closed_pagespec},
751 sub pagetemplate (@) {
754 my $page = $params{page};
755 my $template = $params{template};
756 my $shown = ($template->query(name => 'commentslink') ||
757 $template->query(name => 'commentsurl') ||
758 $template->query(name => 'atomcommentsurl') ||
759 $template->query(name => 'comments')) &&
760 commentsshown($page);
762 if ($template->query(name => 'comments')) {
763 my $comments = undef;
765 $comments = IkiWiki::preprocess_inline(
766 pages => "comment($page)",
767 template => 'comment',
771 destpage => $params{destpage},
772 feedfile => 'comments',
777 if (defined $comments && length $comments) {
778 $template->param(comments => $comments);
781 if ($shown && commentsopen($page)) {
782 $template->param(addcommenturl => addcommenturl($page));
787 if ($template->query(name => 'commentsurl')) {
788 $template->param(commentsurl =>
789 urlto($page, undef, 1).'#comments');
792 if ($template->query(name => 'atomcommentsurl') && $config{usedirs}) {
793 # This will 404 until there are some comments, but I
794 # think that's probably OK...
795 $template->param(atomcommentsurl =>
796 urlto($page, undef, 1).'comments.atom');
799 if ($template->query(name => 'commentslink')) {
800 my $num=num_comments($page, $config{srcdir});
803 $link = htmllink($page, $params{destpage}, $page,
804 linktext => sprintf(ngettext("%i comment", "%i comments", $num), $num),
805 anchor => "comments",
809 elsif (commentsopen($page)) {
810 $link = "<a href=\"".addcommenturl($page)."\">".
811 #translators: Here "Comment" is a verb;
812 #translators: the user clicks on it to
813 #translators: post a comment.
817 $template->param(commentslink => $link)
822 # everything below this point is only relevant to the comments
824 if (!exists $commentstate{$page}) {
828 if ($template->query(name => 'commentid')) {
829 $template->param(commentid => page_to_id($page));
832 if ($template->query(name => 'commentuser')) {
833 $template->param(commentuser =>
834 $commentstate{$page}{commentuser});
837 if ($template->query(name => 'commentopenid')) {
838 $template->param(commentopenid =>
839 $commentstate{$page}{commentopenid});
842 if ($template->query(name => 'commentip')) {
843 $template->param(commentip =>
844 $commentstate{$page}{commentip});
847 if ($template->query(name => 'commentauthor')) {
848 $template->param(commentauthor =>
849 $commentstate{$page}{commentauthor});
852 if ($template->query(name => 'commentauthorurl')) {
853 $template->param(commentauthorurl =>
854 $commentstate{$page}{commentauthorurl});
857 if ($template->query(name => 'removeurl') &&
858 IkiWiki::Plugin::remove->can("check_canremove") &&
859 length $config{cgiurl}) {
860 $template->param(removeurl => IkiWiki::cgiurl(do => 'remove',
862 $template->param(have_actions => 1);
866 sub addcommenturl ($) {
869 return IkiWiki::cgiurl(do => 'comment', page => $page);
872 sub num_comments ($$) {
876 my @comments=glob("$dir/$page/$config{comments_pagename}*._comment");
877 return int @comments;
880 sub unique_comment_location ($$$$) {
882 eval q{use Digest::MD5 'md5_hex'};
884 my $content_md5=md5_hex(Encode::encode_utf8(shift));
886 my $ext=shift || "._comment";
889 my $i = num_comments($page, $dir);
892 $location = "$page/$config{comments_pagename}${i}_${content_md5}";
893 } while (-e "$dir/$location$ext");
899 # Converts a comment page name into a unique, legal html id
900 # attribute value, that can be used as an anchor to link to the
904 eval q{use Digest::MD5 'md5_hex'};
907 return "comment-".md5_hex(Encode::encode_utf8(($page)));
910 package IkiWiki::PageSpec;
912 sub match_postcomment ($$;@) {
916 if (! $postcomment) {
917 return IkiWiki::FailReason->new("not posting a comment");
919 return match_glob($page, $glob, @_);
922 sub match_comment ($$;@) {
926 # To see if it's a comment, check the source file type.
927 # Deal with comments that were just deleted.
928 my $source=exists $IkiWiki::pagesources{$page} ?
929 $IkiWiki::pagesources{$page} :
930 $IkiWiki::delpagesources{$page};
931 my $type=defined $source ? IkiWiki::pagetype($source) : undef;
932 if (! defined $type || $type ne "_comment") {
933 return IkiWiki::FailReason->new("$page is not a comment");
936 return match_glob($page, "$glob/*", internal => 1, @_);
939 sub match_comment_pending ($$;@) {
943 my $source=exists $IkiWiki::pagesources{$page} ?
944 $IkiWiki::pagesources{$page} :
945 $IkiWiki::delpagesources{$page};
946 my $type=defined $source ? IkiWiki::pagetype($source) : undef;
947 if (! defined $type || $type ne "_comment_pending") {
948 return IkiWiki::FailReason->new("$page is not a pending comment");
951 return match_glob($page, "$glob/*", internal => 1, @_);