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 => "formbuilder_setup", id => "comments", call => \&formbuilder_setup);
29 # Load goto to fix up user page links for logged-in commenters
30 IkiWiki::loadplugin("goto");
31 IkiWiki::loadplugin("inline");
40 comments_pagespec => {
42 example => 'blog/* and !*/Discussion',
43 description => 'PageSpec of pages where comments are allowed',
44 link => 'ikiwiki/PageSpec',
48 comments_closed_pagespec => {
50 example => 'blog/controversial or blog/flamewar',
51 description => 'PageSpec of pages where posting new comments is not allowed',
52 link => 'ikiwiki/PageSpec',
56 comments_pagename => {
58 default => 'comment_',
59 description => 'Base name for comments, e.g. "comment_" for pages like "sandbox/comment_12"',
60 safe => 0, # manual page moving required
63 comments_allowdirectives => {
66 description => 'Interpret directives in comments?',
70 comments_allowauthor => {
73 description => 'Allow anonymous commenters to set an author name?',
80 description => 'commit comments to the VCS',
81 # old uncommitted comments are likely to cause
82 # confusion if this is changed
89 $config{comments_commit} = 1
90 unless defined $config{comments_commit};
91 $config{comments_pagespec} = ''
92 unless defined $config{comments_pagespec};
93 $config{comments_closed_pagespec} = ''
94 unless defined $config{comments_closed_pagespec};
95 $config{comments_pagename} = 'comment_'
96 unless defined $config{comments_pagename};
101 return $params{content};
104 # FIXME: copied verbatim from meta
107 if (exists $IkiWiki::Plugin::htmlscrubber::{safe_url_regexp} &&
108 defined $IkiWiki::Plugin::htmlscrubber::safe_url_regexp) {
109 return $url=~/$IkiWiki::Plugin::htmlscrubber::safe_url_regexp/;
118 my $page = $params{page};
120 my $format = $params{format};
121 if (defined $format && ! exists $IkiWiki::hooks{htmlize}{$format}) {
122 error(sprintf(gettext("unsupported page format %s"), $format));
125 my $content = $params{content};
126 if (! defined $content) {
127 error(gettext("comment must have content"));
129 $content =~ s/\\"/"/g;
131 $content = IkiWiki::filter($page, $params{destpage}, $content);
133 if ($config{comments_allowdirectives}) {
134 $content = IkiWiki::preprocess($page, $params{destpage},
138 # no need to bother with htmlize if it's just HTML
139 $content = IkiWiki::htmlize($page, $params{destpage}, $format, $content)
142 IkiWiki::run_hooks(sanitize => sub {
145 destpage => $params{destpage},
150 # set metadata, possibly overriding [[!meta]] directives from the
156 my $commentauthorurl;
158 if (defined $params{username}) {
159 $commentuser = $params{username};
161 my $oiduser = eval { IkiWiki::openiduser($commentuser) };
163 if (defined $oiduser) {
164 # looks like an OpenID
165 $commentauthorurl = $commentuser;
166 $commentauthor = $oiduser;
167 $commentopenid = $commentuser;
170 $commentauthorurl = IkiWiki::cgiurl(
172 page => (length $config{userdir}
173 ? "$config{userdir}/$commentuser"
176 $commentauthor = $commentuser;
180 if (defined $params{ip}) {
181 $commentip = $params{ip};
183 $commentauthor = gettext("Anonymous");
186 $commentstate{$page}{commentuser} = $commentuser;
187 $commentstate{$page}{commentopenid} = $commentopenid;
188 $commentstate{$page}{commentip} = $commentip;
189 $commentstate{$page}{commentauthor} = $commentauthor;
190 $commentstate{$page}{commentauthorurl} = $commentauthorurl;
191 if (! defined $pagestate{$page}{meta}{author}) {
192 $pagestate{$page}{meta}{author} = $commentauthor;
194 if (! defined $pagestate{$page}{meta}{authorurl}) {
195 $pagestate{$page}{meta}{authorurl} = $commentauthorurl;
198 if ($config{comments_allowauthor}) {
199 if (defined $params{claimedauthor}) {
200 $pagestate{$page}{meta}{author} = $params{claimedauthor};
203 if (defined $params{url}) {
204 my $url=$params{url};
206 eval q{use URI::Heuristic};
208 $url=URI::Heuristic::uf_uristr($url);
212 $pagestate{$page}{meta}{authorurl} = $url;
217 $pagestate{$page}{meta}{author} = $commentauthor;
218 $pagestate{$page}{meta}{authorurl} = $commentauthorurl;
221 if (defined $params{subject}) {
222 $pagestate{$page}{meta}{title} = $params{subject};
225 if ($params{page} =~ m/\/(\Q$config{comments_pagename}\E\d+)$/) {
226 $pagestate{$page}{meta}{permalink} = urlto(IkiWiki::dirname($params{page}), undef, 1).
230 eval q{use Date::Parse};
232 my $time = str2time($params{date});
233 $IkiWiki::pagectime{$page} = $time if defined $time;
239 sub sessioncgi ($$) {
243 my $do = $cgi->param('do');
244 if ($do eq 'comment') {
245 editcomment($cgi, $session);
247 elsif ($do eq 'commentmoderation') {
248 commentmoderation($cgi, $session);
252 # Mostly cargo-culted from IkiWiki::plugin::editpage
253 sub editcomment ($$) {
257 IkiWiki::decode_cgi_utf8($cgi);
259 eval q{use CGI::FormBuilder};
262 my @buttons = (POST_COMMENT, PREVIEW, CANCEL);
263 my $form = CGI::FormBuilder->new(
264 fields => [qw{do sid page subject editcontent type author url}],
267 required => [qw{editcontent}],
270 action => $config{cgiurl},
273 template => scalar IkiWiki::template_params('editcomment.tmpl'),
276 IkiWiki::decode_form_utf8($form);
277 IkiWiki::run_hooks(formbuilder_setup => sub {
278 shift->(title => "comment", form => $form, cgi => $cgi,
279 session => $session, buttons => \@buttons);
281 IkiWiki::decode_form_utf8($form);
283 my $type = $form->param('type');
284 if (defined $type && length $type && $IkiWiki::hooks{htmlize}{$type}) {
285 $type = IkiWiki::possibly_foolish_untaint($type);
288 $type = $config{default_pageext};
291 if (exists $IkiWiki::hooks{htmlize}) {
292 @page_types = grep { ! /^_/ } keys %{$IkiWiki::hooks{htmlize}};
295 $form->field(name => 'do', type => 'hidden');
296 $form->field(name => 'sid', type => 'hidden', value => $session->id,
298 $form->field(name => 'page', type => 'hidden');
299 $form->field(name => 'subject', type => 'text', size => 72);
300 $form->field(name => 'editcontent', type => 'textarea', rows => 10);
301 $form->field(name => "type", value => $type, force => 1,
302 type => 'select', options => \@page_types);
304 $form->tmpl_param(username => $session->param('name'));
306 if ($config{comments_allowauthor} and
307 ! defined $session->param('name')) {
308 $form->tmpl_param(allowauthor => 1);
309 $form->field(name => 'author', type => 'text', size => '40');
310 $form->field(name => 'url', type => 'text', size => '40');
313 $form->tmpl_param(allowauthor => 0);
314 $form->field(name => 'author', type => 'hidden', value => '',
316 $form->field(name => 'url', type => 'hidden', value => '',
320 # The untaint is OK (as in editpage) because we're about to pass
321 # it to file_pruned anyway
322 my $page = $form->field('page');
323 $page = IkiWiki::possibly_foolish_untaint($page);
324 if (! defined $page || ! length $page ||
325 IkiWiki::file_pruned($page, $config{srcdir})) {
326 error(gettext("bad page name"));
329 my $baseurl = urlto($page, undef, 1);
331 $form->title(sprintf(gettext("commenting on %s"),
332 IkiWiki::pagetitle($page)));
334 $form->tmpl_param('helponformattinglink',
335 htmllink($page, $page, 'ikiwiki/formatting',
337 linktext => 'FormattingHelp'),
338 allowdirectives => $config{allow_directives});
340 if ($form->submitted eq CANCEL) {
341 # bounce back to the page they wanted to comment on, and exit.
342 # CANCEL need not be considered in future
343 IkiWiki::redirect($cgi, urlto($page, undef, 1));
347 if (not exists $pagesources{$page}) {
348 error(sprintf(gettext(
349 "page '%s' doesn't exist, so you can't comment"),
353 if (pagespec_match($page, $config{comments_closed_pagespec},
354 location => $page)) {
355 error(sprintf(gettext(
356 "comments on page '%s' are closed"),
360 # Set a flag to indicate that we're posting a comment,
361 # so that postcomment() can tell it should match.
363 IkiWiki::check_canedit($page, $cgi, $session);
366 my $location=unique_comment_location($page, $config{srcdir});
368 my $content = "[[!_comment format=$type\n";
370 # FIXME: handling of double quotes probably wrong?
371 if (defined $session->param('name')) {
372 my $username = $session->param('name');
373 $username =~ s/"/"/g;
374 $content .= " username=\"$username\"\n";
376 elsif (defined $ENV{REMOTE_ADDR}) {
377 my $ip = $ENV{REMOTE_ADDR};
378 if ($ip =~ m/^([.0-9]+)$/) {
379 $content .= " ip=\"$1\"\n";
383 if ($config{comments_allowauthor}) {
384 my $author = $form->field('author');
385 if (defined $author && length $author) {
386 $author =~ s/"/"/g;
387 $content .= " claimedauthor=\"$author\"\n";
389 my $url = $form->field('url');
390 if (defined $url && length $url) {
391 $url =~ s/"/"/g;
392 $content .= " url=\"$url\"\n";
396 my $subject = $form->field('subject');
397 if (defined $subject && length $subject) {
398 $subject =~ s/"/"/g;
399 $content .= " subject=\"$subject\"\n";
402 $content .= " date=\"" . decode_utf8(strftime('%Y-%m-%dT%H:%M:%SZ', gmtime)) . "\"\n";
404 my $editcontent = $form->field('editcontent') || '';
405 $editcontent =~ s/\r\n/\n/g;
406 $editcontent =~ s/\r/\n/g;
407 $editcontent =~ s/"/\\"/g;
408 $content .= " content=\"\"\"\n$editcontent\n\"\"\"]]\n";
410 # This is essentially a simplified version of editpage:
411 # - the user does not control the page that's created, only the parent
412 # - it's always a create operation, never an edit
413 # - this means that conflicts should never happen
414 # - this means that if they do, rocks fall and everyone dies
416 if ($form->submitted eq PREVIEW) {
417 my $preview=previewcomment($content, $location, $page, time);
418 IkiWiki::run_hooks(format => sub {
419 $preview = shift->(page => $page,
420 content => $preview);
422 $form->tmpl_param(page_preview => $preview);
425 $form->tmpl_param(page_preview => "");
428 if ($form->submitted eq POST_COMMENT && $form->validate) {
429 IkiWiki::checksessionexpiry($cgi, $session);
432 my $ok=IkiWiki::check_content(content => $form->field('editcontent'),
433 subject => $form->field('subject'),
434 $config{comments_allowauthor} ? (
435 author => $form->field('author'),
436 url => $form->field('url'),
446 my $penddir=$config{wikistatedir}."/comments_pending";
447 $location=unique_comment_location($page, $penddir);
448 writefile("$location._comment", $penddir, $content);
449 IkiWiki::printheader($session);
450 print IkiWiki::misctemplate(gettext(gettext("comment stored for moderation")),
452 gettext("Your comment will be posted after moderator review").
457 # FIXME: could probably do some sort of graceful retry
458 # on error? Would require significant unwinding though
459 my $file = "$location._comment";
460 writefile($file, $config{srcdir}, $content);
464 if ($config{rcs} and $config{comments_commit}) {
465 my $message = gettext("Added a comment");
466 if (defined $form->field('subject') &&
467 length $form->field('subject')) {
469 gettext("Added a comment: %s"),
470 $form->field('subject'));
473 IkiWiki::rcs_add($file);
474 IkiWiki::disable_commit_hook();
475 $conflict = IkiWiki::rcs_commit_staged($message,
476 $session->param('name'), $ENV{REMOTE_ADDR});
477 IkiWiki::enable_commit_hook();
478 IkiWiki::rcs_update();
481 # Now we need a refresh
482 require IkiWiki::Render;
484 IkiWiki::saveindex();
486 # this should never happen, unless a committer deliberately
487 # breaks it or something
488 error($conflict) if defined $conflict;
490 # Jump to the new comment on the page.
491 # The trailing question mark tries to avoid broken
492 # caches and get the most recent version of the page.
493 IkiWiki::redirect($cgi, urlto($page, undef, 1)."?updated#$location");
497 IkiWiki::showform ($form, \@buttons, $session, $cgi,
498 forcebaseurl => $baseurl);
504 sub commentmoderation ($$) {
508 IkiWiki::needsignin($cgi, $session);
509 if (! IkiWiki::is_admin($session->param("name"))) {
510 error(gettext("you are not logged in as an admin"));
513 IkiWiki::decode_cgi_utf8($cgi);
515 if (defined $cgi->param('sid')) {
516 IkiWiki::checksessionexpiry($cgi, $session);
518 my $rejectalldefer=$cgi->param('rejectalldefer');
522 foreach my $id (keys %vars) {
523 if ($id =~ /(.*)\Q._comment\E$/) {
524 my $action=$cgi->param($id);
525 next if $action eq 'Defer' && ! $rejectalldefer;
527 # Make sure that the id is of a legal
528 # pending comment before untainting.
529 my ($f)= $id =~ /$config{wiki_file_regexp}/;
530 if (! defined $f || ! length $f ||
531 IkiWiki::file_pruned($f, $config{srcdir})) {
532 error("illegal file");
535 my $page=IkiWiki::possibly_foolish_untaint(IkiWiki::dirname($1));
536 my $file="$config{wikistatedir}/comments_pending/".
537 IkiWiki::possibly_foolish_untaint($id);
539 if ($action eq 'Accept') {
540 my $content=eval { readfile($file) };
541 next if $@; # file vanished since form was displayed
542 my $dest=unique_comment_location($page, $config{srcdir})."._comment";
543 writefile($dest, $config{srcdir}, $content);
544 if ($config{rcs} and $config{comments_commit}) {
545 IkiWiki::rcs_add($dest);
550 # This removes empty subdirs, so the
551 # .ikiwiki/comments_pending dir will
552 # go away when all are moderated.
553 require IkiWiki::Render;
554 IkiWiki::prune($file);
560 if ($config{rcs} and $config{comments_commit}) {
561 my $message = gettext("Comment moderation");
562 IkiWiki::disable_commit_hook();
563 $conflict=IkiWiki::rcs_commit_staged($message,
564 $session->param('name'), $ENV{REMOTE_ADDR});
565 IkiWiki::enable_commit_hook();
566 IkiWiki::rcs_update();
569 # Now we need a refresh
570 require IkiWiki::Render;
572 IkiWiki::saveindex();
574 error($conflict) if defined $conflict;
579 my ($id, $ctime)=@{$_};
580 my $file="$config{wikistatedir}/comments_pending/$id";
581 my $content=readfile($file);
582 my $preview=previewcomment($content, $id,
583 IkiWiki::dirname($_), $ctime);
588 } sort { $b->[1] <=> $a->[1] } comments_pending();
590 my $template=template("commentmoderation.tmpl");
593 comments => \@comments,
595 IkiWiki::printheader($session);
596 my $out=$template->output;
597 IkiWiki::run_hooks(format => sub {
598 $out = shift->(page => "", content => $out);
600 print IkiWiki::misctemplate(gettext("comment moderation"), $out);
604 sub formbuilder_setup (@) {
607 my $form=$params{form};
608 if ($form->title eq "preferences" &&
609 IkiWiki::is_admin($params{session}->param("name"))) {
610 push @{$params{buttons}}, "Comment Moderation";
611 if ($form->submitted && $form->submitted eq "Comment Moderation") {
612 commentmoderation($params{cgi}, $params{session});
617 sub comments_pending () {
618 my $dir="$config{wikistatedir}/comments_pending/";
619 return unless -d $dir;
622 eval q{use File::Find};
628 if (IkiWiki::file_pruned($_, $dir)) {
629 $File::Find::prune=1;
631 elsif (! -l $_ && ! -d _) {
632 $File::Find::prune=0;
633 my ($f)=/$config{wiki_file_regexp}/; # untaint
634 if (defined $f && $f =~ /\Q._comment\E$/) {
635 my $ctime=(stat($f))[10];
636 $f=~s/^\Q$dir\E\/?//;
637 push @ret, [$f, $ctime];
646 sub previewcomment ($$$) {
652 my $preview = IkiWiki::htmlize($location, $page, '_comment',
653 IkiWiki::linkify($location, $page,
654 IkiWiki::preprocess($location, $page,
655 IkiWiki::filter($location, $page, $content), 0, 1)));
657 my $template = template("comment.tmpl");
658 $template->param(content => $preview);
659 $template->param(ctime => displaytime($time));
661 IkiWiki::run_hooks(pagetemplate => sub {
662 shift->(page => $location,
664 template => $template);
667 $template->param(have_actions => 0);
669 return $template->output;
672 sub commentsshown ($) {
675 return ! pagespec_match($page, "*/$config{comments_pagename}*",
676 location => $page) &&
677 pagespec_match($page, $config{comments_pagespec},
681 sub commentsopen ($) {
684 return length $config{cgiurl} > 0 &&
685 (! length $config{comments_closed_pagespec} ||
686 ! pagespec_match($page, $config{comments_closed_pagespec},
690 sub pagetemplate (@) {
693 my $page = $params{page};
694 my $template = $params{template};
695 my $shown = ($template->query(name => 'commentslink') ||
696 $template->query(name => 'commentsurl') ||
697 $template->query(name => 'atomcommentsurl') ||
698 $template->query(name => 'comments')) &&
699 commentsshown($page);
701 if ($template->query(name => 'comments')) {
702 my $comments = undef;
704 $comments = IkiWiki::preprocess_inline(
705 pages => "internal($page/$config{comments_pagename}*)",
706 template => 'comment',
710 destpage => $params{destpage},
711 feedfile => 'comments',
716 if (defined $comments && length $comments) {
717 $template->param(comments => $comments);
720 if ($shown && commentsopen($page)) {
721 my $addcommenturl = IkiWiki::cgiurl(do => 'comment',
723 $template->param(addcommenturl => $addcommenturl);
727 if ($template->query(name => 'commentsurl')) {
729 $template->param(commentsurl =>
730 urlto($page, undef, 1).'#comments');
734 if ($template->query(name => 'atomcommentsurl') && $config{usedirs}) {
736 # This will 404 until there are some comments, but I
737 # think that's probably OK...
738 $template->param(atomcommentsurl =>
739 urlto($page, undef, 1).'comments.atom');
743 if ($template->query(name => 'commentslink')) {
744 # XXX Would be nice to say how many comments there are in
745 # the link. But, to update the number, blog pages
746 # would have to update whenever comments of any inlines
747 # page are added, which is not currently done.
749 $template->param(commentslink =>
750 htmllink($page, $params{destpage}, $page,
751 linktext => gettext("Comments"),
752 anchor => "comments",
753 noimageinline => 1));
757 # everything below this point is only relevant to the comments
759 if (!exists $commentstate{$page}) {
763 if ($template->query(name => 'commentuser')) {
764 $template->param(commentuser =>
765 $commentstate{$page}{commentuser});
768 if ($template->query(name => 'commentopenid')) {
769 $template->param(commentopenid =>
770 $commentstate{$page}{commentopenid});
773 if ($template->query(name => 'commentip')) {
774 $template->param(commentip =>
775 $commentstate{$page}{commentip});
778 if ($template->query(name => 'commentauthor')) {
779 $template->param(commentauthor =>
780 $commentstate{$page}{commentauthor});
783 if ($template->query(name => 'commentauthorurl')) {
784 $template->param(commentauthorurl =>
785 $commentstate{$page}{commentauthorurl});
788 if ($template->query(name => 'removeurl') &&
789 IkiWiki::Plugin::remove->can("check_canremove") &&
790 length $config{cgiurl}) {
791 $template->param(removeurl => IkiWiki::cgiurl(do => 'remove',
793 $template->param(have_actions => 1);
797 sub unique_comment_location ($) {
805 $location = "$page/$config{comments_pagename}$i";
806 } while (-e "$dir/$location._comment");
811 package IkiWiki::PageSpec;
813 sub match_postcomment ($$;@) {
817 if (! $postcomment) {
818 return IkiWiki::FailReason->new("not posting a comment");
820 return match_glob($page, $glob);