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 hook(type => "sessioncgi", id => 'comment', call => \&sessioncgi);
26 hook(type => "htmlize", id => "_comment", call => \&htmlize);
27 hook(type => "pagetemplate", id => "comments", call => \&pagetemplate);
28 hook(type => "cgi", id => "comments", call => \&linkcgi);
29 hook(type => "formbuilder_setup", id => "comments", call => \&formbuilder_setup);
30 IkiWiki::loadplugin("inline");
39 comments_pagespec => {
41 example => 'blog/* and !*/Discussion',
42 description => 'PageSpec of pages where comments are allowed',
43 link => 'ikiwiki/PageSpec',
47 comments_closed_pagespec => {
49 example => 'blog/controversial or blog/flamewar',
50 description => 'PageSpec of pages where posting new comments is not allowed',
51 link => 'ikiwiki/PageSpec',
55 comments_pagename => {
57 default => 'comment_',
58 description => 'Base name for comments, e.g. "comment_" for pages like "sandbox/comment_12"',
59 safe => 0, # manual page moving required
62 comments_allowdirectives => {
65 description => 'Interpret directives in comments?',
69 comments_allowauthor => {
72 description => 'Allow anonymous commenters to set an author name?',
79 description => 'commit comments to the VCS',
80 # old uncommitted comments are likely to cause
81 # confusion if this is changed
88 $config{comments_commit} = 1
89 unless defined $config{comments_commit};
90 $config{comments_pagespec} = ''
91 unless defined $config{comments_pagespec};
92 $config{comments_closed_pagespec} = ''
93 unless defined $config{comments_closed_pagespec};
94 $config{comments_pagename} = 'comment_'
95 unless defined $config{comments_pagename};
100 return $params{content};
103 # FIXME: copied verbatim from meta
106 if (exists $IkiWiki::Plugin::htmlscrubber::{safe_url_regexp} &&
107 defined $IkiWiki::Plugin::htmlscrubber::safe_url_regexp) {
108 return $url=~/$IkiWiki::Plugin::htmlscrubber::safe_url_regexp/;
117 my $page = $params{page};
119 my $format = $params{format};
120 if (defined $format && ! exists $IkiWiki::hooks{htmlize}{$format}) {
121 error(sprintf(gettext("unsupported page format %s"), $format));
124 my $content = $params{content};
125 if (! defined $content) {
126 error(gettext("comment must have content"));
128 $content =~ s/\\"/"/g;
130 $content = IkiWiki::filter($page, $params{destpage}, $content);
132 if ($config{comments_allowdirectives}) {
133 $content = IkiWiki::preprocess($page, $params{destpage},
137 # no need to bother with htmlize if it's just HTML
138 $content = IkiWiki::htmlize($page, $params{destpage}, $format, $content)
141 IkiWiki::run_hooks(sanitize => sub {
144 destpage => $params{destpage},
149 # set metadata, possibly overriding [[!meta]] directives from the
155 my $commentauthorurl;
157 if (defined $params{username}) {
158 $commentuser = $params{username};
160 my $oiduser = eval { IkiWiki::openiduser($commentuser) };
162 if (defined $oiduser) {
163 # looks like an OpenID
164 $commentauthorurl = $commentuser;
165 $commentauthor = $oiduser;
166 $commentopenid = $commentuser;
169 $commentauthorurl = IkiWiki::cgiurl(
171 page => (length $config{userdir}
172 ? "$config{userdir}/$commentuser"
175 $commentauthor = $commentuser;
179 if (defined $params{ip}) {
180 $commentip = $params{ip};
182 $commentauthor = gettext("Anonymous");
185 $commentstate{$page}{commentuser} = $commentuser;
186 $commentstate{$page}{commentopenid} = $commentopenid;
187 $commentstate{$page}{commentip} = $commentip;
188 $commentstate{$page}{commentauthor} = $commentauthor;
189 $commentstate{$page}{commentauthorurl} = $commentauthorurl;
190 if (! defined $pagestate{$page}{meta}{author}) {
191 $pagestate{$page}{meta}{author} = $commentauthor;
193 if (! defined $pagestate{$page}{meta}{authorurl}) {
194 $pagestate{$page}{meta}{authorurl} = $commentauthorurl;
197 if ($config{comments_allowauthor}) {
198 if (defined $params{claimedauthor}) {
199 $pagestate{$page}{meta}{author} = $params{claimedauthor};
202 if (defined $params{url}) {
203 my $url=$params{url};
205 eval q{use URI::Heuristic};
207 $url=URI::Heuristic::uf_uristr($url);
211 $pagestate{$page}{meta}{authorurl} = $url;
216 $pagestate{$page}{meta}{author} = $commentauthor;
217 $pagestate{$page}{meta}{authorurl} = $commentauthorurl;
220 if (defined $params{subject}) {
221 $pagestate{$page}{meta}{title} = $params{subject};
224 if ($params{page} =~ m/\/(\Q$config{comments_pagename}\E\d+)$/) {
225 $pagestate{$page}{meta}{permalink} = urlto(IkiWiki::dirname($params{page}), undef, 1).
229 eval q{use Date::Parse};
231 my $time = str2time($params{date});
232 $IkiWiki::pagectime{$page} = $time if defined $time;
238 # This is exactly the same as recentchanges_link :-(
241 if (defined $cgi->param('do') && $cgi->param('do') eq "commenter") {
243 my $page=decode_utf8($cgi->param("page"));
244 if (! defined $page) {
245 error("missing page parameter");
248 IkiWiki::loadindex();
250 my $link=bestlink("", $page);
251 if (! length $link) {
252 print "Content-type: text/html\n\n";
253 print IkiWiki::misctemplate(gettext(gettext("missing page")),
255 sprintf(gettext("The page %s does not exist."),
256 htmllink("", "", $page)).
260 IkiWiki::redirect($cgi, urlto($link, undef, 1));
267 sub sessioncgi ($$) {
271 my $do = $cgi->param('do');
272 if ($do eq 'comment') {
273 editcomment($cgi, $session);
275 elsif ($do eq 'commentmoderation') {
276 commentmoderation($cgi, $session);
280 # Mostly cargo-culted from IkiWiki::plugin::editpage
281 sub editcomment ($$) {
285 IkiWiki::decode_cgi_utf8($cgi);
287 eval q{use CGI::FormBuilder};
290 my @buttons = (POST_COMMENT, PREVIEW, CANCEL);
291 my $form = CGI::FormBuilder->new(
292 fields => [qw{do sid page subject editcontent type author url}],
295 required => [qw{editcontent}],
298 action => $config{cgiurl},
301 template => scalar IkiWiki::template_params('editcomment.tmpl'),
304 IkiWiki::decode_form_utf8($form);
305 IkiWiki::run_hooks(formbuilder_setup => sub {
306 shift->(title => "comment", form => $form, cgi => $cgi,
307 session => $session, buttons => \@buttons);
309 IkiWiki::decode_form_utf8($form);
311 my $type = $form->param('type');
312 if (defined $type && length $type && $IkiWiki::hooks{htmlize}{$type}) {
313 $type = IkiWiki::possibly_foolish_untaint($type);
316 $type = $config{default_pageext};
319 if (exists $IkiWiki::hooks{htmlize}) {
320 @page_types = grep { ! /^_/ } keys %{$IkiWiki::hooks{htmlize}};
323 $form->field(name => 'do', type => 'hidden');
324 $form->field(name => 'sid', type => 'hidden', value => $session->id,
326 $form->field(name => 'page', type => 'hidden');
327 $form->field(name => 'subject', type => 'text', size => 72);
328 $form->field(name => 'editcontent', type => 'textarea', rows => 10);
329 $form->field(name => "type", value => $type, force => 1,
330 type => 'select', options => \@page_types);
332 $form->tmpl_param(username => $session->param('name'));
334 if ($config{comments_allowauthor} and
335 ! defined $session->param('name')) {
336 $form->tmpl_param(allowauthor => 1);
337 $form->field(name => 'author', type => 'text', size => '40');
338 $form->field(name => 'url', type => 'text', size => '40');
341 $form->tmpl_param(allowauthor => 0);
342 $form->field(name => 'author', type => 'hidden', value => '',
344 $form->field(name => 'url', type => 'hidden', value => '',
348 # The untaint is OK (as in editpage) because we're about to pass
349 # it to file_pruned anyway
350 my $page = $form->field('page');
351 $page = IkiWiki::possibly_foolish_untaint($page);
352 if (! defined $page || ! length $page ||
353 IkiWiki::file_pruned($page, $config{srcdir})) {
354 error(gettext("bad page name"));
357 my $baseurl = urlto($page, undef, 1);
359 $form->title(sprintf(gettext("commenting on %s"),
360 IkiWiki::pagetitle($page)));
362 $form->tmpl_param('helponformattinglink',
363 htmllink($page, $page, 'ikiwiki/formatting',
365 linktext => 'FormattingHelp'),
366 allowdirectives => $config{allow_directives});
368 if ($form->submitted eq CANCEL) {
369 # bounce back to the page they wanted to comment on, and exit.
370 # CANCEL need not be considered in future
371 IkiWiki::redirect($cgi, urlto($page, undef, 1));
375 if (not exists $pagesources{$page}) {
376 error(sprintf(gettext(
377 "page '%s' doesn't exist, so you can't comment"),
381 if (pagespec_match($page, $config{comments_closed_pagespec},
382 location => $page)) {
383 error(sprintf(gettext(
384 "comments on page '%s' are closed"),
388 # Set a flag to indicate that we're posting a comment,
389 # so that postcomment() can tell it should match.
391 IkiWiki::check_canedit($page, $cgi, $session);
394 my $location=unique_comment_location($page, $config{srcdir});
396 my $content = "[[!_comment format=$type\n";
398 # FIXME: handling of double quotes probably wrong?
399 if (defined $session->param('name')) {
400 my $username = $session->param('name');
401 $username =~ s/"/"/g;
402 $content .= " username=\"$username\"\n";
404 elsif (defined $ENV{REMOTE_ADDR}) {
405 my $ip = $ENV{REMOTE_ADDR};
406 if ($ip =~ m/^([.0-9]+)$/) {
407 $content .= " ip=\"$1\"\n";
411 if ($config{comments_allowauthor}) {
412 my $author = $form->field('author');
413 if (defined $author && length $author) {
414 $author =~ s/"/"/g;
415 $content .= " claimedauthor=\"$author\"\n";
417 my $url = $form->field('url');
418 if (defined $url && length $url) {
419 $url =~ s/"/"/g;
420 $content .= " url=\"$url\"\n";
424 my $subject = $form->field('subject');
425 if (defined $subject && length $subject) {
426 $subject =~ s/"/"/g;
427 $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 # This is essentially a simplified version of editpage:
439 # - the user does not control the page that's created, only the parent
440 # - it's always a create operation, never an edit
441 # - this means that conflicts should never happen
442 # - this means that if they do, rocks fall and everyone dies
444 if ($form->submitted eq PREVIEW) {
445 my $preview=previewcomment($content, $location, $page, time);
446 IkiWiki::run_hooks(format => sub {
447 $preview = shift->(page => $page,
448 content => $preview);
450 $form->tmpl_param(page_preview => $preview);
453 $form->tmpl_param(page_preview => "");
456 if ($form->submitted eq POST_COMMENT && $form->validate) {
457 IkiWiki::checksessionexpiry($cgi, $session);
460 my $ok=IkiWiki::check_content(content => $form->field('editcontent'),
461 subject => $form->field('subject'),
462 $config{comments_allowauthor} ? (
463 author => $form->field('author'),
464 url => $form->field('url'),
474 my $penddir=$config{wikistatedir}."/comments_pending";
475 $location=unique_comment_location($page, $penddir);
476 writefile("$location._comment", $penddir, $content);
477 IkiWiki::printheader($session);
478 print IkiWiki::misctemplate(gettext(gettext("comment stored for moderation")),
480 gettext("Your comment will be posted after moderator review"),
485 # FIXME: could probably do some sort of graceful retry
486 # on error? Would require significant unwinding though
487 my $file = "$location._comment";
488 writefile($file, $config{srcdir}, $content);
492 if ($config{rcs} and $config{comments_commit}) {
493 my $message = gettext("Added a comment");
494 if (defined $form->field('subject') &&
495 length $form->field('subject')) {
497 gettext("Added a comment: %s"),
498 $form->field('subject'));
501 IkiWiki::rcs_add($file);
502 IkiWiki::disable_commit_hook();
503 $conflict = IkiWiki::rcs_commit_staged($message,
504 $session->param('name'), $ENV{REMOTE_ADDR});
505 IkiWiki::enable_commit_hook();
506 IkiWiki::rcs_update();
509 # Now we need a refresh
510 require IkiWiki::Render;
512 IkiWiki::saveindex();
514 # this should never happen, unless a committer deliberately
515 # breaks it or something
516 error($conflict) if defined $conflict;
518 # Jump to the new comment on the page.
519 # The trailing question mark tries to avoid broken
520 # caches and get the most recent version of the page.
521 IkiWiki::redirect($cgi, urlto($page, undef, 1)."?updated#$location");
525 IkiWiki::showform ($form, \@buttons, $session, $cgi,
526 forcebaseurl => $baseurl);
532 sub commentmoderation ($$) {
536 IkiWiki::needsignin($cgi, $session);
537 if (! IkiWiki::is_admin($session->param("name"))) {
538 error(gettext("you are not logged in as an admin"));
541 IkiWiki::decode_cgi_utf8($cgi);
543 if (defined $cgi->param('sid')) {
544 IkiWiki::checksessionexpiry($cgi, $session);
546 my $rejectalldefer=$cgi->param('rejectalldefer');
550 foreach my $id (keys %vars) {
551 if ($id =~ /(.*)\Q._comment\E$/) {
552 my $action=$cgi->param($id);
553 next if $action eq 'Defer' && ! $rejectalldefer;
555 # Make sure that the id is of a legal
556 # pending comment before untainting.
557 my ($f)= $id =~ /$config{wiki_file_regexp}/;
558 if (! defined $f || ! length $f ||
559 IkiWiki::file_pruned($f, $config{srcdir})) {
560 error("illegal file");
563 my $page=IkiWiki::possibly_foolish_untaint(IkiWiki::dirname($1));
564 my $file="$config{wikistatedir}/comments_pending/".
565 IkiWiki::possibly_foolish_untaint($id);
567 if ($action eq 'Accept') {
568 my $content=eval { readfile($file) };
569 next if $@; # file vanished since form was displayed
570 my $dest=unique_comment_location($page, $config{srcdir})."._comment";
571 writefile($dest, $config{srcdir}, $content);
572 if ($config{rcs} and $config{comments_commit}) {
573 IkiWiki::rcs_add($dest);
578 # This removes empty subdirs, so the
579 # .ikiwiki/comments_pending dir will
580 # go away when all are moderated.
581 require IkiWiki::Render;
582 IkiWiki::prune($file);
588 if ($config{rcs} and $config{comments_commit}) {
589 my $message = gettext("Comment moderation");
590 IkiWiki::disable_commit_hook();
591 $conflict=IkiWiki::rcs_commit_staged($message,
592 $session->param('name'), $ENV{REMOTE_ADDR});
593 IkiWiki::enable_commit_hook();
594 IkiWiki::rcs_update();
597 # Now we need a refresh
598 require IkiWiki::Render;
600 IkiWiki::saveindex();
602 error($conflict) if defined $conflict;
607 my ($id, $ctime)=@{$_};
608 my $file="$config{wikistatedir}/comments_pending/$id";
609 my $content=readfile($file);
610 my $preview=previewcomment($content, $id,
611 IkiWiki::dirname($_), $ctime);
616 } sort { $b->[1] <=> $a->[1] } comments_pending();
618 my $template=template("commentmoderation.tmpl");
621 comments => \@comments,
623 IkiWiki::printheader($session);
624 my $out=$template->output;
625 IkiWiki::run_hooks(format => sub {
626 $out = shift->(page => "", content => $out);
628 print IkiWiki::misctemplate(gettext("comment moderation"), $out);
632 sub formbuilder_setup (@) {
635 my $form=$params{form};
636 if ($form->title eq "preferences") {
637 push @{$params{buttons}}, "Comment Moderation";
638 if ($form->submitted && $form->submitted eq "Comment Moderation") {
639 commentmoderation($params{cgi}, $params{session});
644 sub comments_pending () {
645 my $dir="$config{wikistatedir}/comments_pending/";
646 return unless -d $dir;
649 eval q{use File::Find};
655 if (IkiWiki::file_pruned($_, $dir)) {
656 $File::Find::prune=1;
658 elsif (! -l $_ && ! -d _) {
659 $File::Find::prune=0;
660 my ($f)=/$config{wiki_file_regexp}/; # untaint
661 if (defined $f && $f =~ /\Q._comment\E$/) {
662 my $ctime=(stat($f))[10];
663 $f=~s/^\Q$dir\E\/?//;
664 push @ret, [$f, $ctime];
673 sub previewcomment ($$$) {
679 my $preview = IkiWiki::htmlize($location, $page, '_comment',
680 IkiWiki::linkify($location, $page,
681 IkiWiki::preprocess($location, $page,
682 IkiWiki::filter($location, $page, $content), 0, 1)));
684 my $template = template("comment.tmpl");
685 $template->param(content => $preview);
686 $template->param(ctime => displaytime($time));
688 IkiWiki::run_hooks(pagetemplate => sub {
689 shift->(page => $location,
691 template => $template);
694 $template->param(have_actions => 0);
696 return $template->output;
699 sub commentsshown ($) {
702 return ! pagespec_match($page, "*/$config{comments_pagename}*",
703 location => $page) &&
704 pagespec_match($page, $config{comments_pagespec},
708 sub commentsopen ($) {
711 return length $config{cgiurl} > 0 &&
712 (! length $config{comments_closed_pagespec} ||
713 ! pagespec_match($page, $config{comments_closed_pagespec},
717 sub pagetemplate (@) {
720 my $page = $params{page};
721 my $template = $params{template};
722 my $shown = ($template->query(name => 'commentslink') ||
723 $template->query(name => 'commentsurl') ||
724 $template->query(name => 'atomcommentsurl') ||
725 $template->query(name => 'comments')) &&
726 commentsshown($page);
728 if ($template->query(name => 'comments')) {
729 my $comments = undef;
731 $comments = IkiWiki::preprocess_inline(
732 pages => "internal($page/$config{comments_pagename}*)",
733 template => 'comment',
737 destpage => $params{destpage},
738 feedfile => 'comments',
743 if (defined $comments && length $comments) {
744 $template->param(comments => $comments);
747 if ($shown && commentsopen($page)) {
748 my $addcommenturl = IkiWiki::cgiurl(do => 'comment',
750 $template->param(addcommenturl => $addcommenturl);
754 if ($template->query(name => 'commentsurl')) {
756 $template->param(commentsurl =>
757 urlto($page, undef, 1).'#comments');
761 if ($template->query(name => 'atomcommentsurl') && $config{usedirs}) {
763 # This will 404 until there are some comments, but I
764 # think that's probably OK...
765 $template->param(atomcommentsurl =>
766 urlto($page, undef, 1).'comments.atom');
770 if ($template->query(name => 'commentslink')) {
771 # XXX Would be nice to say how many comments there are in
772 # the link. But, to update the number, blog pages
773 # would have to update whenever comments of any inlines
774 # page are added, which is not currently done.
776 $template->param(commentslink =>
777 htmllink($page, $params{destpage}, $page,
778 linktext => gettext("Comments"),
779 anchor => "comments",
780 noimageinline => 1));
784 # everything below this point is only relevant to the comments
786 if (!exists $commentstate{$page}) {
790 if ($template->query(name => 'commentuser')) {
791 $template->param(commentuser =>
792 $commentstate{$page}{commentuser});
795 if ($template->query(name => 'commentopenid')) {
796 $template->param(commentopenid =>
797 $commentstate{$page}{commentopenid});
800 if ($template->query(name => 'commentip')) {
801 $template->param(commentip =>
802 $commentstate{$page}{commentip});
805 if ($template->query(name => 'commentauthor')) {
806 $template->param(commentauthor =>
807 $commentstate{$page}{commentauthor});
810 if ($template->query(name => 'commentauthorurl')) {
811 $template->param(commentauthorurl =>
812 $commentstate{$page}{commentauthorurl});
815 if ($template->query(name => 'removeurl') &&
816 IkiWiki::Plugin::remove->can("check_canremove") &&
817 length $config{cgiurl}) {
818 $template->param(removeurl => IkiWiki::cgiurl(do => 'remove',
820 $template->param(have_actions => 1);
824 sub unique_comment_location ($) {
832 $location = "$page/$config{comments_pagename}$i";
833 } while (-e "$dir/$location._comment");
838 package IkiWiki::PageSpec;
840 sub match_postcomment ($$;@) {
844 if (! $postcomment) {
845 return IkiWiki::FailReason->new("not posting a comment");
847 return match_glob($page, $glob);