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);
265 elsif ($do eq 'commentsignin') {
266 IkiWiki::cgi_signin($cgi, $session);
271 # Mostly cargo-culted from IkiWiki::plugin::editpage
272 sub editcomment ($$) {
276 IkiWiki::decode_cgi_utf8($cgi);
278 eval q{use CGI::FormBuilder};
281 my @buttons = (POST_COMMENT, PREVIEW, CANCEL);
282 my $form = CGI::FormBuilder->new(
283 fields => [qw{do sid page subject editcontent type author url}],
286 required => [qw{editcontent}],
289 action => $config{cgiurl},
292 template => { template('editcomment.tmpl') },
295 IkiWiki::decode_form_utf8($form);
296 IkiWiki::run_hooks(formbuilder_setup => sub {
297 shift->(title => "comment", form => $form, cgi => $cgi,
298 session => $session, buttons => \@buttons);
300 IkiWiki::decode_form_utf8($form);
302 my $type = $form->param('type');
303 if (defined $type && length $type && $IkiWiki::hooks{htmlize}{$type}) {
304 $type = IkiWiki::possibly_foolish_untaint($type);
307 $type = $config{default_pageext};
312 if (exists $IkiWiki::hooks{htmlize}) {
313 foreach my $key (grep { !/^_/ } keys %{$IkiWiki::hooks{htmlize}}) {
314 push @page_types, [$key, $IkiWiki::hooks{htmlize}{$key}{longname} || $key];
317 @page_types=sort @page_types;
319 $form->field(name => 'do', type => 'hidden');
320 $form->field(name => 'sid', type => 'hidden', value => $session->id,
322 $form->field(name => 'page', type => 'hidden');
323 $form->field(name => 'subject', type => 'text', size => 72);
324 $form->field(name => 'editcontent', type => 'textarea', rows => 10);
325 $form->field(name => "type", value => $type, force => 1,
326 type => 'select', options => \@page_types);
328 $form->tmpl_param(username => $session->param('name'));
330 if ($config{comments_allowauthor} and
331 ! defined $session->param('name')) {
332 $form->tmpl_param(allowauthor => 1);
333 $form->field(name => 'author', type => 'text', size => '40');
334 $form->field(name => 'url', type => 'text', size => '40');
337 $form->tmpl_param(allowauthor => 0);
338 $form->field(name => 'author', type => 'hidden', value => '',
340 $form->field(name => 'url', type => 'hidden', value => '',
344 if (! defined $session->param('name')) {
345 # Make signinurl work and return here.
346 $form->tmpl_param(signinurl => IkiWiki::cgiurl(do => 'commentsignin'));
347 $session->param(postsignin => $ENV{QUERY_STRING});
348 IkiWiki::cgi_savesession($session);
351 # The untaint is OK (as in editpage) because we're about to pass
352 # it to file_pruned anyway
353 my $page = $form->field('page');
354 $page = IkiWiki::possibly_foolish_untaint($page);
355 if (! defined $page || ! length $page ||
356 IkiWiki::file_pruned($page)) {
357 error(gettext("bad page name"));
360 my $baseurl = urlto($page, undef, 1);
362 $form->title(sprintf(gettext("commenting on %s"),
363 IkiWiki::pagetitle($page)));
365 $form->tmpl_param('helponformattinglink',
366 htmllink($page, $page, 'ikiwiki/formatting',
368 linktext => 'FormattingHelp'),
369 allowdirectives => $config{allow_directives});
371 if ($form->submitted eq CANCEL) {
372 # bounce back to the page they wanted to comment on, and exit.
373 # CANCEL need not be considered in future
374 IkiWiki::redirect($cgi, urlto($page, undef, 1));
378 if (not exists $pagesources{$page}) {
379 error(sprintf(gettext(
380 "page '%s' doesn't exist, so you can't comment"),
384 if (pagespec_match($page, $config{comments_closed_pagespec},
385 location => $page)) {
386 error(sprintf(gettext(
387 "comments on page '%s' are closed"),
391 # Set a flag to indicate that we're posting a comment,
392 # so that postcomment() can tell it should match.
394 IkiWiki::check_canedit($page, $cgi, $session);
397 my $content = "[[!comment format=$type\n";
399 # FIXME: handling of double quotes probably wrong?
400 if (defined $session->param('name')) {
401 my $username = $session->param('name');
402 $username =~ s/"/"/g;
403 $content .= " username=\"$username\"\n";
405 elsif (defined $session->remote_addr()) {
406 my $ip = $session->remote_addr();
407 if ($ip =~ m/^([.0-9]+)$/) {
408 $content .= " ip=\"$1\"\n";
412 if ($config{comments_allowauthor}) {
413 my $author = $form->field('author');
414 if (defined $author && length $author) {
415 $author =~ s/"/"/g;
416 $content .= " claimedauthor=\"$author\"\n";
418 my $url = $form->field('url');
419 if (defined $url && length $url) {
420 $url =~ s/"/"/g;
421 $content .= " url=\"$url\"\n";
425 my $subject = $form->field('subject');
426 if (defined $subject && length $subject) {
427 $subject =~ s/"/"/g;
430 $subject = "comment ".(num_comments($page, $config{srcdir}) + 1);
432 $content .= " subject=\"$subject\"\n";
434 $content .= " date=\"" . decode_utf8(strftime('%Y-%m-%dT%H:%M:%SZ', gmtime)) . "\"\n";
436 my $editcontent = $form->field('editcontent');
437 $editcontent="" if ! defined $editcontent;
438 $editcontent =~ s/\r\n/\n/g;
439 $editcontent =~ s/\r/\n/g;
440 $editcontent =~ s/"/\\"/g;
441 $content .= " content=\"\"\"\n$editcontent\n\"\"\"]]\n";
443 my $location=unique_comment_location($page, $content, $config{srcdir});
445 # This is essentially a simplified version of editpage:
446 # - the user does not control the page that's created, only the parent
447 # - it's always a create operation, never an edit
448 # - this means that conflicts should never happen
449 # - this means that if they do, rocks fall and everyone dies
451 if ($form->submitted eq PREVIEW) {
452 my $preview=previewcomment($content, $location, $page, time);
453 IkiWiki::run_hooks(format => sub {
454 $preview = shift->(page => $page,
455 content => $preview);
457 $form->tmpl_param(page_preview => $preview);
460 $form->tmpl_param(page_preview => "");
463 if ($form->submitted eq POST_COMMENT && $form->validate) {
464 IkiWiki::checksessionexpiry($cgi, $session);
467 my $ok=IkiWiki::check_content(content => $form->field('editcontent'),
468 subject => $form->field('subject'),
469 $config{comments_allowauthor} ? (
470 author => $form->field('author'),
471 url => $form->field('url'),
481 $location=unique_comment_location($page, $content, $config{srcdir}, "._comment_pending");
482 writefile("$location._comment_pending", $config{srcdir}, $content);
484 # Refresh so anything that deals with pending
485 # comments can be updated.
486 require IkiWiki::Render;
488 IkiWiki::saveindex();
490 IkiWiki::printheader($session);
491 print IkiWiki::misctemplate(gettext(gettext("comment stored for moderation")),
493 gettext("Your comment will be posted after moderator review").
498 # FIXME: could probably do some sort of graceful retry
499 # on error? Would require significant unwinding though
500 my $file = "$location._comment";
501 writefile($file, $config{srcdir}, $content);
505 if ($config{rcs} and $config{comments_commit}) {
506 my $message = gettext("Added a comment");
507 if (defined $form->field('subject') &&
508 length $form->field('subject')) {
510 gettext("Added a comment: %s"),
511 $form->field('subject'));
514 IkiWiki::rcs_add($file);
515 IkiWiki::disable_commit_hook();
516 $conflict = IkiWiki::rcs_commit_staged($message,
517 $session->param('name'),
518 $session->remote_addr());
519 IkiWiki::enable_commit_hook();
520 IkiWiki::rcs_update();
523 # Now we need a refresh
524 require IkiWiki::Render;
526 IkiWiki::saveindex();
528 # this should never happen, unless a committer deliberately
529 # breaks it or something
530 error($conflict) if defined $conflict;
532 # Jump to the new comment on the page.
533 # The trailing question mark tries to avoid broken
534 # caches and get the most recent version of the page.
535 IkiWiki::redirect($cgi, urlto($page, undef, 1).
536 "?updated#".page_to_id($location));
540 IkiWiki::showform ($form, \@buttons, $session, $cgi,
541 forcebaseurl => $baseurl, page => $page);
547 sub commentmoderation ($$) {
551 IkiWiki::needsignin($cgi, $session);
552 if (! IkiWiki::is_admin($session->param("name"))) {
553 error(gettext("you are not logged in as an admin"));
556 IkiWiki::decode_cgi_utf8($cgi);
558 if (defined $cgi->param('sid')) {
559 IkiWiki::checksessionexpiry($cgi, $session);
561 my $rejectalldefer=$cgi->param('rejectalldefer');
565 foreach my $id (keys %vars) {
566 if ($id =~ /(.*)\._comment(?:_pending)?$/) {
567 my $action=$cgi->param($id);
568 next if $action eq 'Defer' && ! $rejectalldefer;
570 # Make sure that the id is of a legal
572 my ($f) = $id =~ /$config{wiki_file_regexp}/;
573 if (! defined $f || ! length $f ||
574 IkiWiki::file_pruned($f)) {
575 error("illegal file");
578 my $page=IkiWiki::dirname($f);
579 my $file="$config{srcdir}/$f";
582 $file="$config{wikistatedir}/comments_pending/".$f;
585 if ($action eq 'Accept') {
586 my $content=eval { readfile($file) };
587 next if $@; # file vanished since form was displayed
588 my $dest=unique_comment_location($page, $content, $config{srcdir})."._comment";
589 writefile($dest, $config{srcdir}, $content);
590 if ($config{rcs} and $config{comments_commit}) {
591 IkiWiki::rcs_add($dest);
596 require IkiWiki::Render;
597 IkiWiki::prune($file);
603 if ($config{rcs} and $config{comments_commit}) {
604 my $message = gettext("Comment moderation");
605 IkiWiki::disable_commit_hook();
606 $conflict=IkiWiki::rcs_commit_staged($message,
607 $session->param('name'),
608 $session->remote_addr());
609 IkiWiki::enable_commit_hook();
610 IkiWiki::rcs_update();
613 # Now we need a refresh
614 require IkiWiki::Render;
616 IkiWiki::saveindex();
618 error($conflict) if defined $conflict;
623 my ($id, $dir, $ctime)=@{$_};
624 my $content=readfile("$dir/$id");
625 my $preview=previewcomment($content, $id,
631 } sort { $b->[2] <=> $a->[2] } comments_pending();
633 my $template=template("commentmoderation.tmpl");
636 comments => \@comments,
638 IkiWiki::printheader($session);
639 my $out=$template->output;
640 IkiWiki::run_hooks(format => sub {
641 $out = shift->(page => "", content => $out);
643 print IkiWiki::misctemplate(gettext("comment moderation"), $out);
647 sub formbuilder_setup (@) {
650 my $form=$params{form};
651 if ($form->title eq "preferences" &&
652 IkiWiki::is_admin($params{session}->param("name"))) {
653 push @{$params{buttons}}, "Comment Moderation";
654 if ($form->submitted && $form->submitted eq "Comment Moderation") {
655 commentmoderation($params{cgi}, $params{session});
660 sub comments_pending () {
663 eval q{use File::Find};
667 my $origdir=getcwd();
669 my $find_comments=sub {
672 return unless -d $dir;
674 chdir($dir) || die "chdir $dir: $!";
679 my $file=decode_utf8($_);
681 return if ! length $file || IkiWiki::file_pruned($file)
682 || -l $_ || -d _ || $file !~ /\Q$extension\E$/;
683 my ($f) = $file =~ /$config{wiki_file_regexp}/; # untaint
685 my $ctime=(stat($_))[10];
686 push @ret, [$f, $dir, $ctime];
691 chdir($origdir) || die "chdir $origdir: $!";
694 $find_comments->($config{srcdir}, "._comment_pending");
696 $find_comments->("$config{wikistatedir}/comments_pending/",
702 sub previewcomment ($$$) {
708 my $preview = IkiWiki::htmlize($location, $page, '_comment',
709 IkiWiki::linkify($location, $page,
710 IkiWiki::preprocess($location, $page,
711 IkiWiki::filter($location, $page, $content), 0, 1)));
713 my $template = template("comment.tmpl");
714 $template->param(content => $preview);
715 $template->param(ctime => displaytime($time, undef, 1));
716 $template->param(html5 => $config{html5});
718 IkiWiki::run_hooks(pagetemplate => sub {
719 shift->(page => $location,
721 template => $template);
724 $template->param(have_actions => 0);
726 return $template->output;
729 sub commentsshown ($) {
732 return ! pagespec_match($page, "comment(*)",
733 location => $page) &&
734 pagespec_match($page, $config{comments_pagespec},
738 sub commentsopen ($) {
741 return length $config{cgiurl} > 0 &&
742 (! length $config{comments_closed_pagespec} ||
743 ! pagespec_match($page, $config{comments_closed_pagespec},
747 sub pagetemplate (@) {
750 my $page = $params{page};
751 my $template = $params{template};
752 my $shown = ($template->query(name => 'commentslink') ||
753 $template->query(name => 'commentsurl') ||
754 $template->query(name => 'atomcommentsurl') ||
755 $template->query(name => 'comments')) &&
756 commentsshown($page);
758 if ($template->query(name => 'comments')) {
759 my $comments = undef;
761 $comments = IkiWiki::preprocess_inline(
762 pages => "comment($page)",
763 template => 'comment',
767 destpage => $params{destpage},
768 feedfile => 'comments',
773 if (defined $comments && length $comments) {
774 $template->param(comments => $comments);
777 if ($shown && commentsopen($page)) {
778 $template->param(addcommenturl => addcommenturl($page));
783 if ($template->query(name => 'commentsurl')) {
784 $template->param(commentsurl =>
785 urlto($page, undef, 1).'#comments');
788 if ($template->query(name => 'atomcommentsurl') && $config{usedirs}) {
789 # This will 404 until there are some comments, but I
790 # think that's probably OK...
791 $template->param(atomcommentsurl =>
792 urlto($page, undef, 1).'comments.atom');
795 if ($template->query(name => 'commentslink')) {
796 my $num=num_comments($page, $config{srcdir});
799 $link = htmllink($page, $params{destpage}, $page,
800 linktext => sprintf(ngettext("%i comment", "%i comments", $num), $num),
801 anchor => "comments",
805 elsif (commentsopen($page)) {
806 $link = "<a href=\"".addcommenturl($page)."\">".
807 #translators: Here "Comment" is a verb;
808 #translators: the user clicks on it to
809 #translators: post a comment.
813 $template->param(commentslink => $link)
818 # everything below this point is only relevant to the comments
820 if (!exists $commentstate{$page}) {
824 if ($template->query(name => 'commentid')) {
825 $template->param(commentid => page_to_id($page));
828 if ($template->query(name => 'commentuser')) {
829 $template->param(commentuser =>
830 $commentstate{$page}{commentuser});
833 if ($template->query(name => 'commentopenid')) {
834 $template->param(commentopenid =>
835 $commentstate{$page}{commentopenid});
838 if ($template->query(name => 'commentip')) {
839 $template->param(commentip =>
840 $commentstate{$page}{commentip});
843 if ($template->query(name => 'commentauthor')) {
844 $template->param(commentauthor =>
845 $commentstate{$page}{commentauthor});
848 if ($template->query(name => 'commentauthorurl')) {
849 $template->param(commentauthorurl =>
850 $commentstate{$page}{commentauthorurl});
853 if ($template->query(name => 'removeurl') &&
854 IkiWiki::Plugin::remove->can("check_canremove") &&
855 length $config{cgiurl}) {
856 $template->param(removeurl => IkiWiki::cgiurl(do => 'remove',
858 $template->param(have_actions => 1);
862 sub addcommenturl ($) {
865 return IkiWiki::cgiurl(do => 'comment', page => $page);
868 sub num_comments ($$) {
872 my @comments=glob("$dir/$page/$config{comments_pagename}*._comment");
873 return int @comments;
876 sub unique_comment_location ($$$$) {
878 eval q{use Digest::MD5 'md5_hex'};
880 my $content_md5=md5_hex(Encode::encode_utf8(shift));
882 my $ext=shift || "._comment";
885 my $i = num_comments($page, $dir);
888 $location = "$page/$config{comments_pagename}${i}_${content_md5}";
889 } while (-e "$dir/$location$ext");
895 # Converts a comment page name into a unique, legal html id
896 # attribute value, that can be used as an anchor to link to the
900 eval q{use Digest::MD5 'md5_hex'};
903 return "comment-".md5_hex(Encode::encode_utf8(($page)));
906 package IkiWiki::PageSpec;
908 sub match_postcomment ($$;@) {
912 if (! $postcomment) {
913 return IkiWiki::FailReason->new("not posting a comment");
915 return match_glob($page, $glob, @_);
918 sub match_comment ($$;@) {
922 # To see if it's a comment, check the source file type.
923 # Deal with comments that were just deleted.
924 my $source=exists $IkiWiki::pagesources{$page} ?
925 $IkiWiki::pagesources{$page} :
926 $IkiWiki::delpagesources{$page};
927 my $type=defined $source ? IkiWiki::pagetype($source) : undef;
928 if (! defined $type || $type ne "_comment") {
929 return IkiWiki::FailReason->new("$page is not a comment");
932 return match_glob($page, "$glob/*", internal => 1, @_);
935 sub match_comment_pending ($$;@) {
939 my $source=exists $IkiWiki::pagesources{$page} ?
940 $IkiWiki::pagesources{$page} :
941 $IkiWiki::delpagesources{$page};
942 my $type=defined $source ? IkiWiki::pagetype($source) : undef;
943 if (! defined $type || $type ne "_comment_pending") {
944 return IkiWiki::FailReason->new("$page is not a pending comment");
947 return match_glob($page, "$glob/*", internal => 1, @_);