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");
42 comments_pagespec => {
44 example => 'blog/* and !*/Discussion',
45 description => 'PageSpec of pages where comments are allowed',
46 link => 'ikiwiki/PageSpec',
50 comments_closed_pagespec => {
52 example => 'blog/controversial or blog/flamewar',
53 description => 'PageSpec of pages where posting new comments is not allowed',
54 link => 'ikiwiki/PageSpec',
58 comments_pagename => {
60 default => 'comment_',
61 description => 'Base name for comments, e.g. "comment_" for pages like "sandbox/comment_12"',
62 safe => 0, # manual page moving required
65 comments_allowdirectives => {
68 description => 'Interpret directives in comments?',
72 comments_allowauthor => {
75 description => 'Allow anonymous commenters to set an author name?',
82 description => 'commit comments to the VCS',
83 # old uncommitted comments are likely to cause
84 # confusion if this is changed
91 $config{comments_commit} = 1
92 unless defined $config{comments_commit};
93 $config{comments_pagespec} = ''
94 unless defined $config{comments_pagespec};
95 $config{comments_closed_pagespec} = ''
96 unless defined $config{comments_closed_pagespec};
97 $config{comments_pagename} = 'comment_'
98 unless defined $config{comments_pagename};
103 return $params{content};
106 # FIXME: copied verbatim from meta
109 if (exists $IkiWiki::Plugin::htmlscrubber::{safe_url_regexp} &&
110 defined $IkiWiki::Plugin::htmlscrubber::safe_url_regexp) {
111 return $url=~/$IkiWiki::Plugin::htmlscrubber::safe_url_regexp/;
120 my $page = $params{page};
122 my $format = $params{format};
123 if (defined $format && ! exists $IkiWiki::hooks{htmlize}{$format}) {
124 error(sprintf(gettext("unsupported page format %s"), $format));
127 my $content = $params{content};
128 if (! defined $content) {
129 error(gettext("comment must have content"));
131 $content =~ s/\\"/"/g;
133 $content = IkiWiki::filter($page, $params{destpage}, $content);
135 if ($config{comments_allowdirectives}) {
136 $content = IkiWiki::preprocess($page, $params{destpage},
140 # no need to bother with htmlize if it's just HTML
141 $content = IkiWiki::htmlize($page, $params{destpage}, $format, $content)
144 IkiWiki::run_hooks(sanitize => sub {
147 destpage => $params{destpage},
152 # set metadata, possibly overriding [[!meta]] directives from the
158 my $commentauthorurl;
160 if (defined $params{username}) {
161 $commentuser = $params{username};
163 my $oiduser = eval { IkiWiki::openiduser($commentuser) };
165 if (defined $oiduser) {
166 # looks like an OpenID
167 $commentauthorurl = $commentuser;
168 $commentauthor = $oiduser;
169 $commentopenid = $commentuser;
172 $commentauthorurl = IkiWiki::cgiurl(
174 page => (length $config{userdir}
175 ? "$config{userdir}/$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 $pagestate{$page}{meta}{title} = $params{subject};
227 if ($params{page} =~ m/\/(\Q$config{comments_pagename}\E\d+)$/) {
228 $pagestate{$page}{meta}{permalink} = urlto(IkiWiki::dirname($params{page}), undef, 1).
229 "#".page_to_id($params{page});
232 eval q{use Date::Parse};
234 my $time = str2time($params{date});
235 $IkiWiki::pagectime{$page} = $time if defined $time;
241 sub sessioncgi ($$) {
245 my $do = $cgi->param('do');
246 if ($do eq 'comment') {
247 editcomment($cgi, $session);
249 elsif ($do eq 'commentmoderation') {
250 commentmoderation($cgi, $session);
254 # Mostly cargo-culted from IkiWiki::plugin::editpage
255 sub editcomment ($$) {
259 IkiWiki::decode_cgi_utf8($cgi);
261 eval q{use CGI::FormBuilder};
264 my @buttons = (POST_COMMENT, PREVIEW, CANCEL);
265 my $form = CGI::FormBuilder->new(
266 fields => [qw{do sid page subject editcontent type author url}],
269 required => [qw{editcontent}],
272 action => $config{cgiurl},
275 template => scalar IkiWiki::template_params('editcomment.tmpl'),
278 IkiWiki::decode_form_utf8($form);
279 IkiWiki::run_hooks(formbuilder_setup => sub {
280 shift->(title => "comment", form => $form, cgi => $cgi,
281 session => $session, buttons => \@buttons);
283 IkiWiki::decode_form_utf8($form);
285 my $type = $form->param('type');
286 if (defined $type && length $type && $IkiWiki::hooks{htmlize}{$type}) {
287 $type = IkiWiki::possibly_foolish_untaint($type);
290 $type = $config{default_pageext};
295 if (exists $IkiWiki::hooks{htmlize}) {
296 foreach my $key (grep { !/^_/ } keys %{$IkiWiki::hooks{htmlize}}) {
297 push @page_types, [$key, $IkiWiki::hooks{htmlize}{$key}{longname} || $key];
300 @page_types=sort @page_types;
302 $form->field(name => 'do', type => 'hidden');
303 $form->field(name => 'sid', type => 'hidden', value => $session->id,
305 $form->field(name => 'page', type => 'hidden');
306 $form->field(name => 'subject', type => 'text', size => 72);
307 $form->field(name => 'editcontent', type => 'textarea', rows => 10);
308 $form->field(name => "type", value => $type, force => 1,
309 type => 'select', options => \@page_types);
311 $form->tmpl_param(username => $session->param('name'));
313 if ($config{comments_allowauthor} and
314 ! defined $session->param('name')) {
315 $form->tmpl_param(allowauthor => 1);
316 $form->field(name => 'author', type => 'text', size => '40');
317 $form->field(name => 'url', type => 'text', size => '40');
320 $form->tmpl_param(allowauthor => 0);
321 $form->field(name => 'author', type => 'hidden', value => '',
323 $form->field(name => 'url', type => 'hidden', value => '',
327 if (! defined $session->param('name')) {
328 # Make signinurl work and return here.
329 $form->tmpl_param(signinurl => IkiWiki::cgiurl(do => 'signin'));
330 $session->param(postsignin => $ENV{QUERY_STRING});
331 IkiWiki::cgi_savesession($session);
334 # The untaint is OK (as in editpage) because we're about to pass
335 # it to file_pruned anyway
336 my $page = $form->field('page');
337 $page = IkiWiki::possibly_foolish_untaint($page);
338 if (! defined $page || ! length $page ||
339 IkiWiki::file_pruned($page, $config{srcdir})) {
340 error(gettext("bad page name"));
343 my $baseurl = urlto($page, undef, 1);
345 $form->title(sprintf(gettext("commenting on %s"),
346 IkiWiki::pagetitle($page)));
348 $form->tmpl_param('helponformattinglink',
349 htmllink($page, $page, 'ikiwiki/formatting',
351 linktext => 'FormattingHelp'),
352 allowdirectives => $config{allow_directives});
354 if ($form->submitted eq CANCEL) {
355 # bounce back to the page they wanted to comment on, and exit.
356 # CANCEL need not be considered in future
357 IkiWiki::redirect($cgi, urlto($page, undef, 1));
361 if (not exists $pagesources{$page}) {
362 error(sprintf(gettext(
363 "page '%s' doesn't exist, so you can't comment"),
367 if (pagespec_match($page, $config{comments_closed_pagespec},
368 location => $page)) {
369 error(sprintf(gettext(
370 "comments on page '%s' are closed"),
374 # Set a flag to indicate that we're posting a comment,
375 # so that postcomment() can tell it should match.
377 IkiWiki::check_canedit($page, $cgi, $session);
380 my $location=unique_comment_location($page, $config{srcdir});
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;
413 $content .= " subject=\"$subject\"\n";
416 $content .= " date=\"" . decode_utf8(strftime('%Y-%m-%dT%H:%M:%SZ', gmtime)) . "\"\n";
418 my $editcontent = $form->field('editcontent') || '';
419 $editcontent =~ s/\r\n/\n/g;
420 $editcontent =~ s/\r/\n/g;
421 $editcontent =~ s/"/\\"/g;
422 $content .= " content=\"\"\"\n$editcontent\n\"\"\"]]\n";
424 # This is essentially a simplified version of editpage:
425 # - the user does not control the page that's created, only the parent
426 # - it's always a create operation, never an edit
427 # - this means that conflicts should never happen
428 # - this means that if they do, rocks fall and everyone dies
430 if ($form->submitted eq PREVIEW) {
431 my $preview=previewcomment($content, $location, $page, time);
432 IkiWiki::run_hooks(format => sub {
433 $preview = shift->(page => $page,
434 content => $preview);
436 $form->tmpl_param(page_preview => $preview);
439 $form->tmpl_param(page_preview => "");
442 if ($form->submitted eq POST_COMMENT && $form->validate) {
443 IkiWiki::checksessionexpiry($cgi, $session);
446 my $ok=IkiWiki::check_content(content => $form->field('editcontent'),
447 subject => $form->field('subject'),
448 $config{comments_allowauthor} ? (
449 author => $form->field('author'),
450 url => $form->field('url'),
460 my $penddir=$config{wikistatedir}."/comments_pending";
461 $location=unique_comment_location($page, $penddir);
462 writefile("$location._comment", $penddir, $content);
463 IkiWiki::printheader($session);
464 print IkiWiki::misctemplate(gettext(gettext("comment stored for moderation")),
466 gettext("Your comment will be posted after moderator review").
471 # FIXME: could probably do some sort of graceful retry
472 # on error? Would require significant unwinding though
473 my $file = "$location._comment";
474 writefile($file, $config{srcdir}, $content);
478 if ($config{rcs} and $config{comments_commit}) {
479 my $message = gettext("Added a comment");
480 if (defined $form->field('subject') &&
481 length $form->field('subject')) {
483 gettext("Added a comment: %s"),
484 $form->field('subject'));
487 IkiWiki::rcs_add($file);
488 IkiWiki::disable_commit_hook();
489 $conflict = IkiWiki::rcs_commit_staged($message,
490 $session->param('name'), $ENV{REMOTE_ADDR});
491 IkiWiki::enable_commit_hook();
492 IkiWiki::rcs_update();
495 # Now we need a refresh
496 require IkiWiki::Render;
498 IkiWiki::saveindex();
500 # this should never happen, unless a committer deliberately
501 # breaks it or something
502 error($conflict) if defined $conflict;
504 # Jump to the new comment on the page.
505 # The trailing question mark tries to avoid broken
506 # caches and get the most recent version of the page.
507 IkiWiki::redirect($cgi, urlto($page, undef, 1).
508 "?updated#".page_to_id($location));
512 IkiWiki::showform ($form, \@buttons, $session, $cgi,
513 forcebaseurl => $baseurl);
519 sub commentmoderation ($$) {
523 IkiWiki::needsignin($cgi, $session);
524 if (! IkiWiki::is_admin($session->param("name"))) {
525 error(gettext("you are not logged in as an admin"));
528 IkiWiki::decode_cgi_utf8($cgi);
530 if (defined $cgi->param('sid')) {
531 IkiWiki::checksessionexpiry($cgi, $session);
533 my $rejectalldefer=$cgi->param('rejectalldefer');
537 foreach my $id (keys %vars) {
538 if ($id =~ /(.*)\Q._comment\E$/) {
539 my $action=$cgi->param($id);
540 next if $action eq 'Defer' && ! $rejectalldefer;
542 # Make sure that the id is of a legal
543 # pending comment before untainting.
544 my ($f)= $id =~ /$config{wiki_file_regexp}/;
545 if (! defined $f || ! length $f ||
546 IkiWiki::file_pruned($f, $config{srcdir})) {
547 error("illegal file");
550 my $page=IkiWiki::possibly_foolish_untaint(IkiWiki::dirname($1));
551 my $file="$config{wikistatedir}/comments_pending/".
552 IkiWiki::possibly_foolish_untaint($id);
554 if ($action eq 'Accept') {
555 my $content=eval { readfile($file) };
556 next if $@; # file vanished since form was displayed
557 my $dest=unique_comment_location($page, $config{srcdir})."._comment";
558 writefile($dest, $config{srcdir}, $content);
559 if ($config{rcs} and $config{comments_commit}) {
560 IkiWiki::rcs_add($dest);
565 # This removes empty subdirs, so the
566 # .ikiwiki/comments_pending dir will
567 # go away when all are moderated.
568 require IkiWiki::Render;
569 IkiWiki::prune($file);
575 if ($config{rcs} and $config{comments_commit}) {
576 my $message = gettext("Comment moderation");
577 IkiWiki::disable_commit_hook();
578 $conflict=IkiWiki::rcs_commit_staged($message,
579 $session->param('name'), $ENV{REMOTE_ADDR});
580 IkiWiki::enable_commit_hook();
581 IkiWiki::rcs_update();
584 # Now we need a refresh
585 require IkiWiki::Render;
587 IkiWiki::saveindex();
589 error($conflict) if defined $conflict;
594 my ($id, $ctime)=@{$_};
595 my $file="$config{wikistatedir}/comments_pending/$id";
596 my $content=readfile($file);
597 my $preview=previewcomment($content, $id,
598 IkiWiki::dirname($_), $ctime);
603 } sort { $b->[1] <=> $a->[1] } comments_pending();
605 my $template=template("commentmoderation.tmpl");
608 comments => \@comments,
610 IkiWiki::printheader($session);
611 my $out=$template->output;
612 IkiWiki::run_hooks(format => sub {
613 $out = shift->(page => "", content => $out);
615 print IkiWiki::misctemplate(gettext("comment moderation"), $out);
619 sub formbuilder_setup (@) {
622 my $form=$params{form};
623 if ($form->title eq "preferences" &&
624 IkiWiki::is_admin($params{session}->param("name"))) {
625 push @{$params{buttons}}, "Comment Moderation";
626 if ($form->submitted && $form->submitted eq "Comment Moderation") {
627 commentmoderation($params{cgi}, $params{session});
632 sub comments_pending () {
633 my $dir="$config{wikistatedir}/comments_pending/";
634 return unless -d $dir;
637 eval q{use File::Find};
643 if (IkiWiki::file_pruned($_, $dir)) {
644 $File::Find::prune=1;
646 elsif (! -l $_ && ! -d _) {
647 $File::Find::prune=0;
648 my ($f)=/$config{wiki_file_regexp}/; # untaint
649 if (defined $f && $f =~ /\Q._comment\E$/) {
650 my $ctime=(stat($f))[10];
651 $f=~s/^\Q$dir\E\/?//;
652 push @ret, [$f, $ctime];
661 sub previewcomment ($$$) {
667 my $preview = IkiWiki::htmlize($location, $page, '_comment',
668 IkiWiki::linkify($location, $page,
669 IkiWiki::preprocess($location, $page,
670 IkiWiki::filter($location, $page, $content), 0, 1)));
672 my $template = template("comment.tmpl");
673 $template->param(content => $preview);
674 $template->param(ctime => displaytime($time));
676 IkiWiki::run_hooks(pagetemplate => sub {
677 shift->(page => $location,
679 template => $template);
682 $template->param(have_actions => 0);
684 return $template->output;
687 sub commentsshown ($) {
690 return ! pagespec_match($page, "internal(*/$config{comments_pagename}*)",
691 location => $page) &&
692 pagespec_match($page, $config{comments_pagespec},
696 sub commentsopen ($) {
699 return length $config{cgiurl} > 0 &&
700 (! length $config{comments_closed_pagespec} ||
701 ! pagespec_match($page, $config{comments_closed_pagespec},
705 sub pagetemplate (@) {
708 my $page = $params{page};
709 my $template = $params{template};
710 my $shown = ($template->query(name => 'commentslink') ||
711 $template->query(name => 'commentsurl') ||
712 $template->query(name => 'atomcommentsurl') ||
713 $template->query(name => 'comments')) &&
714 commentsshown($page);
716 if ($template->query(name => 'comments')) {
717 my $comments = undef;
719 $comments = IkiWiki::preprocess_inline(
720 pages => "internal($page/$config{comments_pagename}*)",
721 template => 'comment',
725 destpage => $params{destpage},
726 feedfile => 'comments',
731 if (defined $comments && length $comments) {
732 $template->param(comments => $comments);
735 if ($shown && commentsopen($page)) {
736 my $addcommenturl = IkiWiki::cgiurl(do => 'comment',
738 $template->param(addcommenturl => $addcommenturl);
742 if ($template->query(name => 'commentsurl')) {
744 $template->param(commentsurl =>
745 urlto($page, undef, 1).'#comments');
749 if ($template->query(name => 'atomcommentsurl') && $config{usedirs}) {
751 # This will 404 until there are some comments, but I
752 # think that's probably OK...
753 $template->param(atomcommentsurl =>
754 urlto($page, undef, 1).'comments.atom');
758 if ($template->query(name => 'commentslink')) {
759 # XXX Would be nice to say how many comments there are in
760 # the link. But, to update the number, blog pages
761 # would have to update whenever comments of any inlines
762 # page are added, which is not currently done.
764 $template->param(commentslink =>
765 htmllink($page, $params{destpage}, $page,
766 linktext => gettext("Comments"),
767 anchor => "comments",
768 noimageinline => 1));
772 # everything below this point is only relevant to the comments
774 if (!exists $commentstate{$page}) {
778 if ($template->query(name => 'commentid')) {
779 $template->param(commentid => page_to_id($page));
782 if ($template->query(name => 'commentuser')) {
783 $template->param(commentuser =>
784 $commentstate{$page}{commentuser});
787 if ($template->query(name => 'commentopenid')) {
788 $template->param(commentopenid =>
789 $commentstate{$page}{commentopenid});
792 if ($template->query(name => 'commentip')) {
793 $template->param(commentip =>
794 $commentstate{$page}{commentip});
797 if ($template->query(name => 'commentauthor')) {
798 $template->param(commentauthor =>
799 $commentstate{$page}{commentauthor});
802 if ($template->query(name => 'commentauthorurl')) {
803 $template->param(commentauthorurl =>
804 $commentstate{$page}{commentauthorurl});
807 if ($template->query(name => 'removeurl') &&
808 IkiWiki::Plugin::remove->can("check_canremove") &&
809 length $config{cgiurl}) {
810 $template->param(removeurl => IkiWiki::cgiurl(do => 'remove',
812 $template->param(have_actions => 1);
816 sub unique_comment_location ($) {
824 $location = "$page/$config{comments_pagename}$i";
825 } while (-e "$dir/$location._comment");
831 # Converts a comment page name into a unique, legal html id
832 # addtibute value, that can be used as an anchor to link to the
836 eval q{use Digest::MD5 'md5_hex'};
839 return "comment-".md5_hex($page);
842 package IkiWiki::PageSpec;
844 sub match_postcomment ($$;@) {
848 if (! $postcomment) {
849 return IkiWiki::FailReason->new("not posting a comment");
851 return match_glob($page, $glob);