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 => "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");
43 comments_pagespec => {
45 example => 'blog/* and !*/Discussion',
46 description => 'PageSpec of pages where comments are allowed',
47 link => 'ikiwiki/PageSpec',
51 comments_closed_pagespec => {
53 example => 'blog/controversial or blog/flamewar',
54 description => 'PageSpec of pages where posting new comments is not allowed',
55 link => 'ikiwiki/PageSpec',
59 comments_pagename => {
61 default => 'comment_',
62 description => 'Base name for comments, e.g. "comment_" for pages like "sandbox/comment_12"',
63 safe => 0, # manual page moving required
66 comments_allowdirectives => {
69 description => 'Interpret directives in comments?',
73 comments_allowauthor => {
76 description => 'Allow anonymous commenters to set an author name?',
83 description => 'commit comments to the VCS',
84 # old uncommitted comments are likely to cause
85 # confusion if this is changed
92 $config{comments_commit} = 1
93 unless defined $config{comments_commit};
94 $config{comments_pagespec} = ''
95 unless defined $config{comments_pagespec};
96 $config{comments_closed_pagespec} = ''
97 unless defined $config{comments_closed_pagespec};
98 $config{comments_pagename} = 'comment_'
99 unless defined $config{comments_pagename};
104 return $params{content};
107 # FIXME: copied verbatim from meta
110 if (exists $IkiWiki::Plugin::htmlscrubber::{safe_url_regexp} &&
111 defined $IkiWiki::Plugin::htmlscrubber::safe_url_regexp) {
112 return $url=~/$IkiWiki::Plugin::htmlscrubber::safe_url_regexp/;
121 my $page = $params{page};
123 my $format = $params{format};
124 if (defined $format && ! exists $IkiWiki::hooks{htmlize}{$format}) {
125 error(sprintf(gettext("unsupported page format %s"), $format));
128 my $content = $params{content};
129 if (! defined $content) {
130 error(gettext("comment must have content"));
132 $content =~ s/\\"/"/g;
134 $content = IkiWiki::filter($page, $params{destpage}, $content);
136 if ($config{comments_allowdirectives}) {
137 $content = IkiWiki::preprocess($page, $params{destpage},
141 # no need to bother with htmlize if it's just HTML
142 $content = IkiWiki::htmlize($page, $params{destpage}, $format, $content)
145 IkiWiki::run_hooks(sanitize => sub {
148 destpage => $params{destpage},
153 # set metadata, possibly overriding [[!meta]] directives from the
159 my $commentauthorurl;
161 if (defined $params{username}) {
162 $commentuser = $params{username};
164 my $oiduser = eval { IkiWiki::openiduser($commentuser) };
166 if (defined $oiduser) {
167 # looks like an OpenID
168 $commentauthorurl = $commentuser;
169 $commentauthor = $oiduser;
170 $commentopenid = $commentuser;
173 $commentauthorurl = IkiWiki::cgiurl(
175 page => IkiWiki::userpage($commentuser)
178 $commentauthor = $commentuser;
182 if (defined $params{ip}) {
183 $commentip = $params{ip};
185 $commentauthor = gettext("Anonymous");
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;
196 if (! defined $pagestate{$page}{meta}{authorurl}) {
197 $pagestate{$page}{meta}{authorurl} = $commentauthorurl;
200 if ($config{comments_allowauthor}) {
201 if (defined $params{claimedauthor}) {
202 $pagestate{$page}{meta}{author} = $params{claimedauthor};
205 if (defined $params{url}) {
206 my $url=$params{url};
208 eval q{use URI::Heuristic};
210 $url=URI::Heuristic::uf_uristr($url);
214 $pagestate{$page}{meta}{authorurl} = $url;
219 $pagestate{$page}{meta}{author} = $commentauthor;
220 $pagestate{$page}{meta}{authorurl} = $commentauthorurl;
223 if (defined $params{subject}) {
224 # decode title the same way meta does
225 eval q{use HTML::Entities};
226 $pagestate{$page}{meta}{title} = decode_entities($params{subject});
229 if ($params{page} =~ m/\/\Q$config{comments_pagename}\E\d+_/) {
230 $pagestate{$page}{meta}{permalink} = urlto(IkiWiki::dirname($params{page}), undef, 1).
231 "#".page_to_id($params{page});
234 eval q{use Date::Parse};
236 my $time = str2time($params{date});
237 $IkiWiki::pagectime{$page} = $time if defined $time;
243 sub sessioncgi ($$) {
247 my $do = $cgi->param('do');
248 if ($do eq 'comment') {
249 editcomment($cgi, $session);
251 elsif ($do eq 'commentmoderation') {
252 commentmoderation($cgi, $session);
256 # Mostly cargo-culted from IkiWiki::plugin::editpage
257 sub editcomment ($$) {
261 IkiWiki::decode_cgi_utf8($cgi);
263 eval q{use CGI::FormBuilder};
266 my @buttons = (POST_COMMENT, PREVIEW, CANCEL);
267 my $form = CGI::FormBuilder->new(
268 fields => [qw{do sid page subject editcontent type author url}],
271 required => [qw{editcontent}],
274 action => $config{cgiurl},
277 template => scalar IkiWiki::template_params('editcomment.tmpl'),
280 IkiWiki::decode_form_utf8($form);
281 IkiWiki::run_hooks(formbuilder_setup => sub {
282 shift->(title => "comment", form => $form, cgi => $cgi,
283 session => $session, buttons => \@buttons);
285 IkiWiki::decode_form_utf8($form);
287 my $type = $form->param('type');
288 if (defined $type && length $type && $IkiWiki::hooks{htmlize}{$type}) {
289 $type = IkiWiki::possibly_foolish_untaint($type);
292 $type = $config{default_pageext};
297 if (exists $IkiWiki::hooks{htmlize}) {
298 foreach my $key (grep { !/^_/ } keys %{$IkiWiki::hooks{htmlize}}) {
299 push @page_types, [$key, $IkiWiki::hooks{htmlize}{$key}{longname} || $key];
302 @page_types=sort @page_types;
304 $form->field(name => 'do', type => 'hidden');
305 $form->field(name => 'sid', type => 'hidden', value => $session->id,
307 $form->field(name => 'page', type => 'hidden');
308 $form->field(name => 'subject', type => 'text', size => 72);
309 $form->field(name => 'editcontent', type => 'textarea', rows => 10);
310 $form->field(name => "type", value => $type, force => 1,
311 type => 'select', options => \@page_types);
313 $form->tmpl_param(username => $session->param('name'));
315 if ($config{comments_allowauthor} and
316 ! defined $session->param('name')) {
317 $form->tmpl_param(allowauthor => 1);
318 $form->field(name => 'author', type => 'text', size => '40');
319 $form->field(name => 'url', type => 'text', size => '40');
322 $form->tmpl_param(allowauthor => 0);
323 $form->field(name => 'author', type => 'hidden', value => '',
325 $form->field(name => 'url', type => 'hidden', value => '',
329 if (! defined $session->param('name')) {
330 # Make signinurl work and return here.
331 $form->tmpl_param(signinurl => IkiWiki::cgiurl(do => 'signin'));
332 $session->param(postsignin => $ENV{QUERY_STRING});
333 IkiWiki::cgi_savesession($session);
336 # The untaint is OK (as in editpage) because we're about to pass
337 # it to file_pruned anyway
338 my $page = $form->field('page');
339 $page = IkiWiki::possibly_foolish_untaint($page);
340 if (! defined $page || ! length $page ||
341 IkiWiki::file_pruned($page)) {
342 error(gettext("bad page name"));
345 my $baseurl = urlto($page, undef, 1);
347 $form->title(sprintf(gettext("commenting on %s"),
348 IkiWiki::pagetitle($page)));
350 $form->tmpl_param('helponformattinglink',
351 htmllink($page, $page, 'ikiwiki/formatting',
353 linktext => 'FormattingHelp'),
354 allowdirectives => $config{allow_directives});
356 if ($form->submitted eq CANCEL) {
357 # bounce back to the page they wanted to comment on, and exit.
358 # CANCEL need not be considered in future
359 IkiWiki::redirect($cgi, urlto($page, undef, 1));
363 if (not exists $pagesources{$page}) {
364 error(sprintf(gettext(
365 "page '%s' doesn't exist, so you can't comment"),
369 if (pagespec_match($page, $config{comments_closed_pagespec},
370 location => $page)) {
371 error(sprintf(gettext(
372 "comments on page '%s' are closed"),
376 # Set a flag to indicate that we're posting a comment,
377 # so that postcomment() can tell it should match.
379 IkiWiki::check_canedit($page, $cgi, $session);
382 my $content = "[[!comment format=$type\n";
384 # FIXME: handling of double quotes probably wrong?
385 if (defined $session->param('name')) {
386 my $username = $session->param('name');
387 $username =~ s/"/"/g;
388 $content .= " username=\"$username\"\n";
390 elsif (defined $ENV{REMOTE_ADDR}) {
391 my $ip = $ENV{REMOTE_ADDR};
392 if ($ip =~ m/^([.0-9]+)$/) {
393 $content .= " ip=\"$1\"\n";
397 if ($config{comments_allowauthor}) {
398 my $author = $form->field('author');
399 if (defined $author && length $author) {
400 $author =~ s/"/"/g;
401 $content .= " claimedauthor=\"$author\"\n";
403 my $url = $form->field('url');
404 if (defined $url && length $url) {
405 $url =~ s/"/"/g;
406 $content .= " url=\"$url\"\n";
410 my $subject = $form->field('subject');
411 if (defined $subject && length $subject) {
412 $subject =~ s/"/"/g;
415 $subject = "comment ".(num_comments($page, $config{srcdir}) + 1);
417 $content .= " subject=\"$subject\"\n";
419 $content .= " date=\"" . decode_utf8(strftime('%Y-%m-%dT%H:%M:%SZ', gmtime)) . "\"\n";
421 my $editcontent = $form->field('editcontent') || '';
422 $editcontent =~ s/\r\n/\n/g;
423 $editcontent =~ s/\r/\n/g;
424 $editcontent =~ s/"/\\"/g;
425 $content .= " content=\"\"\"\n$editcontent\n\"\"\"]]\n";
427 my $location=unique_comment_location($page, $content, $config{srcdir});
429 # This is essentially a simplified version of editpage:
430 # - the user does not control the page that's created, only the parent
431 # - it's always a create operation, never an edit
432 # - this means that conflicts should never happen
433 # - this means that if they do, rocks fall and everyone dies
435 if ($form->submitted eq PREVIEW) {
436 my $preview=previewcomment($content, $location, $page, time);
437 IkiWiki::run_hooks(format => sub {
438 $preview = shift->(page => $page,
439 content => $preview);
441 $form->tmpl_param(page_preview => $preview);
444 $form->tmpl_param(page_preview => "");
447 if ($form->submitted eq POST_COMMENT && $form->validate) {
448 IkiWiki::checksessionexpiry($cgi, $session);
451 my $ok=IkiWiki::check_content(content => $form->field('editcontent'),
452 subject => $form->field('subject'),
453 $config{comments_allowauthor} ? (
454 author => $form->field('author'),
455 url => $form->field('url'),
465 my $penddir=$config{wikistatedir}."/comments_pending";
466 $location=unique_comment_location($page, $content, $penddir);
467 writefile("$location._comment", $penddir, $content);
468 IkiWiki::printheader($session);
469 print IkiWiki::misctemplate(gettext(gettext("comment stored for moderation")),
471 gettext("Your comment will be posted after moderator review").
476 # FIXME: could probably do some sort of graceful retry
477 # on error? Would require significant unwinding though
478 my $file = "$location._comment";
479 writefile($file, $config{srcdir}, $content);
483 if ($config{rcs} and $config{comments_commit}) {
484 my $message = gettext("Added a comment");
485 if (defined $form->field('subject') &&
486 length $form->field('subject')) {
488 gettext("Added a comment: %s"),
489 $form->field('subject'));
492 IkiWiki::rcs_add($file);
493 IkiWiki::disable_commit_hook();
494 $conflict = IkiWiki::rcs_commit_staged($message,
495 $session->param('name'), $ENV{REMOTE_ADDR});
496 IkiWiki::enable_commit_hook();
497 IkiWiki::rcs_update();
500 # Now we need a refresh
501 require IkiWiki::Render;
503 IkiWiki::saveindex();
505 # this should never happen, unless a committer deliberately
506 # breaks it or something
507 error($conflict) if defined $conflict;
509 # Jump to the new comment on the page.
510 # The trailing question mark tries to avoid broken
511 # caches and get the most recent version of the page.
512 IkiWiki::redirect($cgi, urlto($page, undef, 1).
513 "?updated#".page_to_id($location));
517 IkiWiki::showform ($form, \@buttons, $session, $cgi,
518 forcebaseurl => $baseurl);
524 sub commentmoderation ($$) {
528 IkiWiki::needsignin($cgi, $session);
529 if (! IkiWiki::is_admin($session->param("name"))) {
530 error(gettext("you are not logged in as an admin"));
533 IkiWiki::decode_cgi_utf8($cgi);
535 if (defined $cgi->param('sid')) {
536 IkiWiki::checksessionexpiry($cgi, $session);
538 my $rejectalldefer=$cgi->param('rejectalldefer');
542 foreach my $id (keys %vars) {
543 if ($id =~ /(.*)\Q._comment\E$/) {
544 my $action=$cgi->param($id);
545 next if $action eq 'Defer' && ! $rejectalldefer;
547 # Make sure that the id is of a legal
548 # pending comment before untainting.
549 my ($f)= $id =~ /$config{wiki_file_regexp}/;
550 if (! defined $f || ! length $f ||
551 IkiWiki::file_pruned($f)) {
552 error("illegal file");
555 my $page=IkiWiki::possibly_foolish_untaint(IkiWiki::dirname($1));
556 my $file="$config{wikistatedir}/comments_pending/".
557 IkiWiki::possibly_foolish_untaint($id);
559 if ($action eq 'Accept') {
560 my $content=eval { readfile($file) };
561 next if $@; # file vanished since form was displayed
562 my $dest=unique_comment_location($page, $content, $config{srcdir})."._comment";
563 writefile($dest, $config{srcdir}, $content);
564 if ($config{rcs} and $config{comments_commit}) {
565 IkiWiki::rcs_add($dest);
570 # This removes empty subdirs, so the
571 # .ikiwiki/comments_pending dir will
572 # go away when all are moderated.
573 require IkiWiki::Render;
574 IkiWiki::prune($file);
580 if ($config{rcs} and $config{comments_commit}) {
581 my $message = gettext("Comment moderation");
582 IkiWiki::disable_commit_hook();
583 $conflict=IkiWiki::rcs_commit_staged($message,
584 $session->param('name'), $ENV{REMOTE_ADDR});
585 IkiWiki::enable_commit_hook();
586 IkiWiki::rcs_update();
589 # Now we need a refresh
590 require IkiWiki::Render;
592 IkiWiki::saveindex();
594 error($conflict) if defined $conflict;
599 my ($id, $ctime)=@{$_};
600 my $file="$config{wikistatedir}/comments_pending/$id";
601 my $content=readfile($file);
602 my $preview=previewcomment($content, $id,
603 IkiWiki::dirname($_), $ctime);
608 } sort { $b->[1] <=> $a->[1] } comments_pending();
610 my $template=template("commentmoderation.tmpl");
613 comments => \@comments,
615 IkiWiki::printheader($session);
616 my $out=$template->output;
617 IkiWiki::run_hooks(format => sub {
618 $out = shift->(page => "", content => $out);
620 print IkiWiki::misctemplate(gettext("comment moderation"), $out);
624 sub formbuilder_setup (@) {
627 my $form=$params{form};
628 if ($form->title eq "preferences" &&
629 IkiWiki::is_admin($params{session}->param("name"))) {
630 push @{$params{buttons}}, "Comment Moderation";
631 if ($form->submitted && $form->submitted eq "Comment Moderation") {
632 commentmoderation($params{cgi}, $params{session});
637 sub comments_pending () {
638 my $dir="$config{wikistatedir}/comments_pending/";
639 return unless -d $dir;
642 eval q{use File::Find};
647 my $file=decode_utf8($_);
648 $file=~s/^\Q$dir\E\/?//;
649 return if ! length $file || IkiWiki::file_pruned($file)
650 || -l $_ || -d _ || $file !~ /\Q._comment\E$/;
651 my ($f) = $file =~ /$config{wiki_file_regexp}/; # untaint
653 my $ctime=(stat($_))[10];
654 push @ret, [$f, $ctime];
662 sub previewcomment ($$$) {
668 my $preview = IkiWiki::htmlize($location, $page, '_comment',
669 IkiWiki::linkify($location, $page,
670 IkiWiki::preprocess($location, $page,
671 IkiWiki::filter($location, $page, $content), 0, 1)));
673 my $template = template("comment.tmpl");
674 $template->param(content => $preview);
675 $template->param(ctime => displaytime($time));
677 IkiWiki::run_hooks(pagetemplate => sub {
678 shift->(page => $location,
680 template => $template);
683 $template->param(have_actions => 0);
685 return $template->output;
688 sub commentsshown ($) {
691 return ! pagespec_match($page, "internal(*/$config{comments_pagename}*)",
692 location => $page) &&
693 pagespec_match($page, $config{comments_pagespec},
697 sub commentsopen ($) {
700 return length $config{cgiurl} > 0 &&
701 (! length $config{comments_closed_pagespec} ||
702 ! pagespec_match($page, $config{comments_closed_pagespec},
706 sub pagetemplate (@) {
709 my $page = $params{page};
710 my $template = $params{template};
711 my $shown = ($template->query(name => 'commentslink') ||
712 $template->query(name => 'commentsurl') ||
713 $template->query(name => 'atomcommentsurl') ||
714 $template->query(name => 'comments')) &&
715 commentsshown($page);
717 if ($template->query(name => 'comments')) {
718 my $comments = undef;
720 $comments = IkiWiki::preprocess_inline(
721 pages => "internal($page/$config{comments_pagename}*)",
722 template => 'comment',
726 destpage => $params{destpage},
727 feedfile => 'comments',
732 if (defined $comments && length $comments) {
733 $template->param(comments => $comments);
736 if ($shown && commentsopen($page)) {
737 $template->param(addcommenturl => addcommenturl($page));
742 if ($template->query(name => 'commentsurl')) {
743 $template->param(commentsurl =>
744 urlto($page, undef, 1).'#comments');
747 if ($template->query(name => 'atomcommentsurl') && $config{usedirs}) {
748 # This will 404 until there are some comments, but I
749 # think that's probably OK...
750 $template->param(atomcommentsurl =>
751 urlto($page, undef, 1).'comments.atom');
754 if ($template->query(name => 'commentslink')) {
755 my $num=num_comments($page, $config{srcdir});
758 $link = htmllink($page, $params{destpage}, $page,
759 linktext => sprintf(ngettext("%i comment", "%i comments", $num), $num),
760 anchor => "comments",
764 elsif (commentsopen($page)) {
765 $link = "<a href=\"".addcommenturl($page)."\">".
766 #translators: Here "Comment" is a verb;
767 #translators: the user clicks on it to
768 #translators: post a comment.
772 $template->param(commentslink => $link)
777 # everything below this point is only relevant to the comments
779 if (!exists $commentstate{$page}) {
783 if ($template->query(name => 'commentid')) {
784 $template->param(commentid => page_to_id($page));
787 if ($template->query(name => 'commentuser')) {
788 $template->param(commentuser =>
789 $commentstate{$page}{commentuser});
792 if ($template->query(name => 'commentopenid')) {
793 $template->param(commentopenid =>
794 $commentstate{$page}{commentopenid});
797 if ($template->query(name => 'commentip')) {
798 $template->param(commentip =>
799 $commentstate{$page}{commentip});
802 if ($template->query(name => 'commentauthor')) {
803 $template->param(commentauthor =>
804 $commentstate{$page}{commentauthor});
807 if ($template->query(name => 'commentauthorurl')) {
808 $template->param(commentauthorurl =>
809 $commentstate{$page}{commentauthorurl});
812 if ($template->query(name => 'removeurl') &&
813 IkiWiki::Plugin::remove->can("check_canremove") &&
814 length $config{cgiurl}) {
815 $template->param(removeurl => IkiWiki::cgiurl(do => 'remove',
817 $template->param(have_actions => 1);
821 sub addcommenturl ($) {
824 return IkiWiki::cgiurl(do => 'comment', page => $page);
827 sub num_comments ($$) {
831 my @comments=glob("$dir/$page/$config{comments_pagename}*._comment");
835 sub unique_comment_location ($$$) {
838 eval q{use Digest::MD5 'md5_hex'};
840 my $content_md5=md5_hex(Encode::encode_utf8(shift));
845 my $i = num_comments($page, $dir);
848 $location = "$page/$config{comments_pagename}${i}_${content_md5}";
849 } while (-e "$dir/$location._comment");
855 # Converts a comment page name into a unique, legal html id
856 # attribute value, that can be used as an anchor to link to the
860 eval q{use Digest::MD5 'md5_hex'};
863 return "comment-".md5_hex(Encode::encode_utf8(($page)));
866 package IkiWiki::PageSpec;
868 sub match_postcomment ($$;@) {
872 if (! $postcomment) {
873 return IkiWiki::FailReason->new("not posting a comment");
875 return match_glob($page, $glob);