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 $content = IkiWiki::filter($page, $params{destpage}, $content);
147 if ($config{comments_allowdirectives}) {
148 $content = IkiWiki::preprocess($page, $params{destpage},
152 # no need to bother with htmlize if it's just HTML
153 $content = IkiWiki::htmlize($page, $params{destpage}, $format, $content)
156 IkiWiki::run_hooks(sanitize => sub {
159 destpage => $params{destpage},
164 # set metadata, possibly overriding [[!meta]] directives from the
170 my $commentauthorurl;
172 if (defined $params{username}) {
173 $commentuser = $params{username};
175 my $oiduser = eval { IkiWiki::openiduser($commentuser) };
177 if (defined $oiduser) {
178 # looks like an OpenID
179 $commentauthorurl = $commentuser;
180 $commentauthor = $oiduser;
181 $commentopenid = $commentuser;
184 $commentauthorurl = IkiWiki::cgiurl(
186 page => IkiWiki::userpage($commentuser)
189 $commentauthor = $commentuser;
193 if (defined $params{ip}) {
194 $commentip = $params{ip};
196 $commentauthor = gettext("Anonymous");
199 $commentstate{$page}{commentuser} = $commentuser;
200 $commentstate{$page}{commentopenid} = $commentopenid;
201 $commentstate{$page}{commentip} = $commentip;
202 $commentstate{$page}{commentauthor} = $commentauthor;
203 $commentstate{$page}{commentauthorurl} = $commentauthorurl;
204 if (! defined $pagestate{$page}{meta}{author}) {
205 $pagestate{$page}{meta}{author} = $commentauthor;
207 if (! defined $pagestate{$page}{meta}{authorurl}) {
208 $pagestate{$page}{meta}{authorurl} = $commentauthorurl;
211 if ($config{comments_allowauthor}) {
212 if (defined $params{claimedauthor}) {
213 $pagestate{$page}{meta}{author} = $params{claimedauthor};
216 if (defined $params{url}) {
217 my $url=$params{url};
219 eval q{use URI::Heuristic};
221 $url=URI::Heuristic::uf_uristr($url);
225 $pagestate{$page}{meta}{authorurl} = $url;
230 $pagestate{$page}{meta}{author} = $commentauthor;
231 $pagestate{$page}{meta}{authorurl} = $commentauthorurl;
234 if (defined $params{subject}) {
235 # decode title the same way meta does
236 eval q{use HTML::Entities};
237 $pagestate{$page}{meta}{title} = decode_entities($params{subject});
240 if ($params{page} =~ m/\/\Q$config{comments_pagename}\E\d+_/) {
241 $pagestate{$page}{meta}{permalink} = urlto(IkiWiki::dirname($params{page}), undef, 1).
242 "#".page_to_id($params{page});
245 eval q{use Date::Parse};
247 my $time = str2time($params{date});
248 $IkiWiki::pagectime{$page} = $time if defined $time;
254 sub sessioncgi ($$) {
258 my $do = $cgi->param('do');
259 if ($do eq 'comment') {
260 editcomment($cgi, $session);
262 elsif ($do eq 'commentmoderation') {
263 commentmoderation($cgi, $session);
267 # Mostly cargo-culted from IkiWiki::plugin::editpage
268 sub editcomment ($$) {
272 IkiWiki::decode_cgi_utf8($cgi);
274 eval q{use CGI::FormBuilder};
277 my @buttons = (POST_COMMENT, PREVIEW, CANCEL);
278 my $form = CGI::FormBuilder->new(
279 fields => [qw{do sid page subject editcontent type author url}],
282 required => [qw{editcontent}],
285 action => $config{cgiurl},
288 template => { template('editcomment.tmpl') },
291 IkiWiki::decode_form_utf8($form);
292 IkiWiki::run_hooks(formbuilder_setup => sub {
293 shift->(title => "comment", form => $form, cgi => $cgi,
294 session => $session, buttons => \@buttons);
296 IkiWiki::decode_form_utf8($form);
298 my $type = $form->param('type');
299 if (defined $type && length $type && $IkiWiki::hooks{htmlize}{$type}) {
300 $type = IkiWiki::possibly_foolish_untaint($type);
303 $type = $config{default_pageext};
308 if (exists $IkiWiki::hooks{htmlize}) {
309 foreach my $key (grep { !/^_/ } keys %{$IkiWiki::hooks{htmlize}}) {
310 push @page_types, [$key, $IkiWiki::hooks{htmlize}{$key}{longname} || $key];
313 @page_types=sort @page_types;
315 $form->field(name => 'do', type => 'hidden');
316 $form->field(name => 'sid', type => 'hidden', value => $session->id,
318 $form->field(name => 'page', type => 'hidden');
319 $form->field(name => 'subject', type => 'text', size => 72);
320 $form->field(name => 'editcontent', type => 'textarea', rows => 10);
321 $form->field(name => "type", value => $type, force => 1,
322 type => 'select', options => \@page_types);
324 $form->tmpl_param(username => $session->param('name'));
326 if ($config{comments_allowauthor} and
327 ! defined $session->param('name')) {
328 $form->tmpl_param(allowauthor => 1);
329 $form->field(name => 'author', type => 'text', size => '40');
330 $form->field(name => 'url', type => 'text', size => '40');
333 $form->tmpl_param(allowauthor => 0);
334 $form->field(name => 'author', type => 'hidden', value => '',
336 $form->field(name => 'url', type => 'hidden', value => '',
340 if (! defined $session->param('name')) {
341 # Make signinurl work and return here.
342 $form->tmpl_param(signinurl => IkiWiki::cgiurl(do => 'signin'));
343 $session->param(postsignin => $ENV{QUERY_STRING});
344 IkiWiki::cgi_savesession($session);
347 # The untaint is OK (as in editpage) because we're about to pass
348 # it to file_pruned anyway
349 my $page = $form->field('page');
350 $page = IkiWiki::possibly_foolish_untaint($page);
351 if (! defined $page || ! length $page ||
352 IkiWiki::file_pruned($page)) {
353 error(gettext("bad page name"));
356 my $baseurl = urlto($page, undef, 1);
358 $form->title(sprintf(gettext("commenting on %s"),
359 IkiWiki::pagetitle($page)));
361 $form->tmpl_param('helponformattinglink',
362 htmllink($page, $page, 'ikiwiki/formatting',
364 linktext => 'FormattingHelp'),
365 allowdirectives => $config{allow_directives});
367 if ($form->submitted eq CANCEL) {
368 # bounce back to the page they wanted to comment on, and exit.
369 # CANCEL need not be considered in future
370 IkiWiki::redirect($cgi, urlto($page, undef, 1));
374 if (not exists $pagesources{$page}) {
375 error(sprintf(gettext(
376 "page '%s' doesn't exist, so you can't comment"),
380 if (pagespec_match($page, $config{comments_closed_pagespec},
381 location => $page)) {
382 error(sprintf(gettext(
383 "comments on page '%s' are closed"),
387 # Set a flag to indicate that we're posting a comment,
388 # so that postcomment() can tell it should match.
390 IkiWiki::check_canedit($page, $cgi, $session);
393 my $content = "[[!comment format=$type\n";
395 # FIXME: handling of double quotes probably wrong?
396 if (defined $session->param('name')) {
397 my $username = $session->param('name');
398 $username =~ s/"/"/g;
399 $content .= " username=\"$username\"\n";
401 elsif (defined $ENV{REMOTE_ADDR}) {
402 my $ip = $ENV{REMOTE_ADDR};
403 if ($ip =~ m/^([.0-9]+)$/) {
404 $content .= " ip=\"$1\"\n";
408 if ($config{comments_allowauthor}) {
409 my $author = $form->field('author');
410 if (defined $author && length $author) {
411 $author =~ s/"/"/g;
412 $content .= " claimedauthor=\"$author\"\n";
414 my $url = $form->field('url');
415 if (defined $url && length $url) {
416 $url =~ s/"/"/g;
417 $content .= " url=\"$url\"\n";
421 my $subject = $form->field('subject');
422 if (defined $subject && length $subject) {
423 $subject =~ s/"/"/g;
426 $subject = "comment ".(num_comments($page, $config{srcdir}) + 1);
428 $content .= " subject=\"$subject\"\n";
430 $content .= " date=\"" . decode_utf8(strftime('%Y-%m-%dT%H:%M:%SZ', gmtime)) . "\"\n";
432 my $editcontent = $form->field('editcontent') || '';
433 $editcontent =~ s/\r\n/\n/g;
434 $editcontent =~ s/\r/\n/g;
435 $editcontent =~ s/"/\\"/g;
436 $content .= " content=\"\"\"\n$editcontent\n\"\"\"]]\n";
438 my $location=unique_comment_location($page, $content, $config{srcdir});
440 # This is essentially a simplified version of editpage:
441 # - the user does not control the page that's created, only the parent
442 # - it's always a create operation, never an edit
443 # - this means that conflicts should never happen
444 # - this means that if they do, rocks fall and everyone dies
446 if ($form->submitted eq PREVIEW) {
447 my $preview=previewcomment($content, $location, $page, time);
448 IkiWiki::run_hooks(format => sub {
449 $preview = shift->(page => $page,
450 content => $preview);
452 $form->tmpl_param(page_preview => $preview);
455 $form->tmpl_param(page_preview => "");
458 if ($form->submitted eq POST_COMMENT && $form->validate) {
459 IkiWiki::checksessionexpiry($cgi, $session);
462 my $ok=IkiWiki::check_content(content => $form->field('editcontent'),
463 subject => $form->field('subject'),
464 $config{comments_allowauthor} ? (
465 author => $form->field('author'),
466 url => $form->field('url'),
476 $location=unique_comment_location($page, $content, $config{srcdir}, "._comment_pending");
477 writefile("$location._comment_pending", $config{srcdir}, $content);
479 # Refresh so anything that deals with pending
480 # comments can be updated.
481 require IkiWiki::Render;
483 IkiWiki::saveindex();
485 IkiWiki::printheader($session);
486 print IkiWiki::misctemplate(gettext(gettext("comment stored for moderation")),
488 gettext("Your comment will be posted after moderator review").
493 # FIXME: could probably do some sort of graceful retry
494 # on error? Would require significant unwinding though
495 my $file = "$location._comment";
496 writefile($file, $config{srcdir}, $content);
500 if ($config{rcs} and $config{comments_commit}) {
501 my $message = gettext("Added a comment");
502 if (defined $form->field('subject') &&
503 length $form->field('subject')) {
505 gettext("Added a comment: %s"),
506 $form->field('subject'));
509 IkiWiki::rcs_add($file);
510 IkiWiki::disable_commit_hook();
511 $conflict = IkiWiki::rcs_commit_staged($message,
512 $session->param('name'), $ENV{REMOTE_ADDR});
513 IkiWiki::enable_commit_hook();
514 IkiWiki::rcs_update();
517 # Now we need a refresh
518 require IkiWiki::Render;
520 IkiWiki::saveindex();
522 # this should never happen, unless a committer deliberately
523 # breaks it or something
524 error($conflict) if defined $conflict;
526 # Jump to the new comment on the page.
527 # The trailing question mark tries to avoid broken
528 # caches and get the most recent version of the page.
529 IkiWiki::redirect($cgi, urlto($page, undef, 1).
530 "?updated#".page_to_id($location));
534 IkiWiki::showform ($form, \@buttons, $session, $cgi,
535 forcebaseurl => $baseurl);
541 sub commentmoderation ($$) {
545 IkiWiki::needsignin($cgi, $session);
546 if (! IkiWiki::is_admin($session->param("name"))) {
547 error(gettext("you are not logged in as an admin"));
550 IkiWiki::decode_cgi_utf8($cgi);
552 if (defined $cgi->param('sid')) {
553 IkiWiki::checksessionexpiry($cgi, $session);
555 my $rejectalldefer=$cgi->param('rejectalldefer');
559 foreach my $id (keys %vars) {
560 if ($id =~ /(.*)\._comment(?:_pending)?$/) {
561 my $action=$cgi->param($id);
562 next if $action eq 'Defer' && ! $rejectalldefer;
564 # Make sure that the id is of a legal
566 my ($f) = $id =~ /$config{wiki_file_regexp}/;
567 if (! defined $f || ! length $f ||
568 IkiWiki::file_pruned($f)) {
569 error("illegal file");
572 my $page=IkiWiki::dirname($f);
573 my $file="$config{srcdir}/$f";
576 $file="$config{wikistatedir}/comments_pending/".$f;
579 if ($action eq 'Accept') {
580 my $content=eval { readfile($file) };
581 next if $@; # file vanished since form was displayed
582 my $dest=unique_comment_location($page, $content, $config{srcdir})."._comment";
583 writefile($dest, $config{srcdir}, $content);
584 if ($config{rcs} and $config{comments_commit}) {
585 IkiWiki::rcs_add($dest);
590 require IkiWiki::Render;
591 IkiWiki::prune($file);
597 if ($config{rcs} and $config{comments_commit}) {
598 my $message = gettext("Comment moderation");
599 IkiWiki::disable_commit_hook();
600 $conflict=IkiWiki::rcs_commit_staged($message,
601 $session->param('name'), $ENV{REMOTE_ADDR});
602 IkiWiki::enable_commit_hook();
603 IkiWiki::rcs_update();
606 # Now we need a refresh
607 require IkiWiki::Render;
609 IkiWiki::saveindex();
611 error($conflict) if defined $conflict;
616 my ($id, $dir, $ctime)=@{$_};
617 my $content=readfile("$dir/$id");
618 my $preview=previewcomment($content, $id,
624 } sort { $b->[2] <=> $a->[2] } comments_pending();
626 my $template=template("commentmoderation.tmpl");
629 comments => \@comments,
631 IkiWiki::printheader($session);
632 my $out=$template->output;
633 IkiWiki::run_hooks(format => sub {
634 $out = shift->(page => "", content => $out);
636 print IkiWiki::misctemplate(gettext("comment moderation"), $out);
640 sub formbuilder_setup (@) {
643 my $form=$params{form};
644 if ($form->title eq "preferences" &&
645 IkiWiki::is_admin($params{session}->param("name"))) {
646 push @{$params{buttons}}, "Comment Moderation";
647 if ($form->submitted && $form->submitted eq "Comment Moderation") {
648 commentmoderation($params{cgi}, $params{session});
653 sub comments_pending () {
656 eval q{use File::Find};
659 my $find_comments=sub {
662 return unless -d $dir;
666 my $file=decode_utf8($_);
667 $file=~s/^\Q$dir\E\/?//;
668 return if ! length $file || IkiWiki::file_pruned($file)
669 || -l $_ || -d _ || $file !~ /\Q$extension\E$/;
670 my ($f) = $file =~ /$config{wiki_file_regexp}/; # untaint
672 my $ctime=(stat($_))[10];
673 push @ret, [$f, $dir, $ctime];
679 $find_comments->($config{srcdir}, "._comment_pending");
681 $find_comments->("$config{wikistatedir}/comments_pending/",
687 sub previewcomment ($$$) {
693 my $preview = IkiWiki::htmlize($location, $page, '_comment',
694 IkiWiki::linkify($location, $page,
695 IkiWiki::preprocess($location, $page,
696 IkiWiki::filter($location, $page, $content), 0, 1)));
698 my $template = template("comment.tmpl");
699 $template->param(content => $preview);
700 $template->param(ctime => displaytime($time, undef, 1));
701 $template->param(html5 => $config{html5});
703 IkiWiki::run_hooks(pagetemplate => sub {
704 shift->(page => $location,
706 template => $template);
709 $template->param(have_actions => 0);
711 return $template->output;
714 sub commentsshown ($) {
717 return ! pagespec_match($page, "comment(*)",
718 location => $page) &&
719 pagespec_match($page, $config{comments_pagespec},
723 sub commentsopen ($) {
726 return length $config{cgiurl} > 0 &&
727 (! length $config{comments_closed_pagespec} ||
728 ! pagespec_match($page, $config{comments_closed_pagespec},
732 sub pagetemplate (@) {
735 my $page = $params{page};
736 my $template = $params{template};
737 my $shown = ($template->query(name => 'commentslink') ||
738 $template->query(name => 'commentsurl') ||
739 $template->query(name => 'atomcommentsurl') ||
740 $template->query(name => 'comments')) &&
741 commentsshown($page);
743 if ($template->query(name => 'comments')) {
744 my $comments = undef;
746 $comments = IkiWiki::preprocess_inline(
747 pages => "comment($page)",
748 template => 'comment',
752 destpage => $params{destpage},
753 feedfile => 'comments',
758 if (defined $comments && length $comments) {
759 $template->param(comments => $comments);
762 if ($shown && commentsopen($page)) {
763 $template->param(addcommenturl => addcommenturl($page));
768 if ($template->query(name => 'commentsurl')) {
769 $template->param(commentsurl =>
770 urlto($page, undef, 1).'#comments');
773 if ($template->query(name => 'atomcommentsurl') && $config{usedirs}) {
774 # This will 404 until there are some comments, but I
775 # think that's probably OK...
776 $template->param(atomcommentsurl =>
777 urlto($page, undef, 1).'comments.atom');
780 if ($template->query(name => 'commentslink')) {
781 my $num=num_comments($page, $config{srcdir});
784 $link = htmllink($page, $params{destpage}, $page,
785 linktext => sprintf(ngettext("%i comment", "%i comments", $num), $num),
786 anchor => "comments",
790 elsif (commentsopen($page)) {
791 $link = "<a href=\"".addcommenturl($page)."\">".
792 #translators: Here "Comment" is a verb;
793 #translators: the user clicks on it to
794 #translators: post a comment.
798 $template->param(commentslink => $link)
803 # everything below this point is only relevant to the comments
805 if (!exists $commentstate{$page}) {
809 if ($template->query(name => 'commentid')) {
810 $template->param(commentid => page_to_id($page));
813 if ($template->query(name => 'commentuser')) {
814 $template->param(commentuser =>
815 $commentstate{$page}{commentuser});
818 if ($template->query(name => 'commentopenid')) {
819 $template->param(commentopenid =>
820 $commentstate{$page}{commentopenid});
823 if ($template->query(name => 'commentip')) {
824 $template->param(commentip =>
825 $commentstate{$page}{commentip});
828 if ($template->query(name => 'commentauthor')) {
829 $template->param(commentauthor =>
830 $commentstate{$page}{commentauthor});
833 if ($template->query(name => 'commentauthorurl')) {
834 $template->param(commentauthorurl =>
835 $commentstate{$page}{commentauthorurl});
838 if ($template->query(name => 'removeurl') &&
839 IkiWiki::Plugin::remove->can("check_canremove") &&
840 length $config{cgiurl}) {
841 $template->param(removeurl => IkiWiki::cgiurl(do => 'remove',
843 $template->param(have_actions => 1);
847 sub addcommenturl ($) {
850 return IkiWiki::cgiurl(do => 'comment', page => $page);
853 sub num_comments ($$) {
857 my @comments=glob("$dir/$page/$config{comments_pagename}*._comment");
861 sub unique_comment_location ($$$$) {
863 eval q{use Digest::MD5 'md5_hex'};
865 my $content_md5=md5_hex(Encode::encode_utf8(shift));
867 my $ext=shift || "._comment";
870 my $i = num_comments($page, $dir);
873 $location = "$page/$config{comments_pagename}${i}_${content_md5}";
874 } while (-e "$dir/$location$ext");
880 # Converts a comment page name into a unique, legal html id
881 # attribute value, that can be used as an anchor to link to the
885 eval q{use Digest::MD5 'md5_hex'};
888 return "comment-".md5_hex(Encode::encode_utf8(($page)));
891 package IkiWiki::PageSpec;
893 sub match_postcomment ($$;@) {
897 if (! $postcomment) {
898 return IkiWiki::FailReason->new("not posting a comment");
900 return match_glob($page, $glob, @_);
903 sub match_comment ($$;@) {
907 if (! IkiWiki::isinternal($page)) {
908 return IkiWiki::FailReason->new("$page is not a comment");
910 my $type=IkiWiki::pagetype($IkiWiki::pagesources{$page});
911 if (defined $type && $type ne "_comment") {
912 return IkiWiki::FailReason->new("$page is not a comment");
915 return match_glob($page, "$glob/*", internal => 1, @_);
918 sub match_comment_pending ($$;@) {
922 if (! IkiWiki::isinternal($page)) {
923 return IkiWiki::FailReason->new("$page is not a pending comment");
925 my $type=IkiWiki::pagetype($IkiWiki::pagesources{$page});
926 if (defined $type && $type ne "_comment_pending") {
927 return IkiWiki::FailReason->new("$page is not a pending comment");
930 return match_glob($page, "$glob/*", internal => 1, @_);