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 $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 $content = "[[!comment format=$type\n";
382 # FIXME: handling of double quotes probably wrong?
383 if (defined $session->param('name')) {
384 my $username = $session->param('name');
385 $username =~ s/"/"/g;
386 $content .= " username=\"$username\"\n";
388 elsif (defined $ENV{REMOTE_ADDR}) {
389 my $ip = $ENV{REMOTE_ADDR};
390 if ($ip =~ m/^([.0-9]+)$/) {
391 $content .= " ip=\"$1\"\n";
395 if ($config{comments_allowauthor}) {
396 my $author = $form->field('author');
397 if (defined $author && length $author) {
398 $author =~ s/"/"/g;
399 $content .= " claimedauthor=\"$author\"\n";
401 my $url = $form->field('url');
402 if (defined $url && length $url) {
403 $url =~ s/"/"/g;
404 $content .= " url=\"$url\"\n";
408 my $subject = $form->field('subject');
409 if (defined $subject && length $subject) {
410 $subject =~ s/"/"/g;
413 $subject = "comment ".(num_comments($page, $config{srcdir}) + 1);
415 $content .= " subject=\"$subject\"\n";
417 $content .= " date=\"" . decode_utf8(strftime('%Y-%m-%dT%H:%M:%SZ', gmtime)) . "\"\n";
419 my $editcontent = $form->field('editcontent') || '';
420 $editcontent =~ s/\r\n/\n/g;
421 $editcontent =~ s/\r/\n/g;
422 $editcontent =~ s/"/\\"/g;
423 $content .= " content=\"\"\"\n$editcontent\n\"\"\"]]\n";
425 my $location=unique_comment_location($page, $content, $config{srcdir});
427 # This is essentially a simplified version of editpage:
428 # - the user does not control the page that's created, only the parent
429 # - it's always a create operation, never an edit
430 # - this means that conflicts should never happen
431 # - this means that if they do, rocks fall and everyone dies
433 if ($form->submitted eq PREVIEW) {
434 my $preview=previewcomment($content, $location, $page, time);
435 IkiWiki::run_hooks(format => sub {
436 $preview = shift->(page => $page,
437 content => $preview);
439 $form->tmpl_param(page_preview => $preview);
442 $form->tmpl_param(page_preview => "");
445 if ($form->submitted eq POST_COMMENT && $form->validate) {
446 IkiWiki::checksessionexpiry($cgi, $session);
449 my $ok=IkiWiki::check_content(content => $form->field('editcontent'),
450 subject => $form->field('subject'),
451 $config{comments_allowauthor} ? (
452 author => $form->field('author'),
453 url => $form->field('url'),
463 my $penddir=$config{wikistatedir}."/comments_pending";
464 $location=unique_comment_location($page, $content, $penddir);
465 writefile("$location._comment", $penddir, $content);
466 IkiWiki::printheader($session);
467 print IkiWiki::misctemplate(gettext(gettext("comment stored for moderation")),
469 gettext("Your comment will be posted after moderator review").
474 # FIXME: could probably do some sort of graceful retry
475 # on error? Would require significant unwinding though
476 my $file = "$location._comment";
477 writefile($file, $config{srcdir}, $content);
481 if ($config{rcs} and $config{comments_commit}) {
482 my $message = gettext("Added a comment");
483 if (defined $form->field('subject') &&
484 length $form->field('subject')) {
486 gettext("Added a comment: %s"),
487 $form->field('subject'));
490 IkiWiki::rcs_add($file);
491 IkiWiki::disable_commit_hook();
492 $conflict = IkiWiki::rcs_commit_staged($message,
493 $session->param('name'), $ENV{REMOTE_ADDR});
494 IkiWiki::enable_commit_hook();
495 IkiWiki::rcs_update();
498 # Now we need a refresh
499 require IkiWiki::Render;
501 IkiWiki::saveindex();
503 # this should never happen, unless a committer deliberately
504 # breaks it or something
505 error($conflict) if defined $conflict;
507 # Jump to the new comment on the page.
508 # The trailing question mark tries to avoid broken
509 # caches and get the most recent version of the page.
510 IkiWiki::redirect($cgi, urlto($page, undef, 1).
511 "?updated#".page_to_id($location));
515 IkiWiki::showform ($form, \@buttons, $session, $cgi,
516 forcebaseurl => $baseurl);
522 sub commentmoderation ($$) {
526 IkiWiki::needsignin($cgi, $session);
527 if (! IkiWiki::is_admin($session->param("name"))) {
528 error(gettext("you are not logged in as an admin"));
531 IkiWiki::decode_cgi_utf8($cgi);
533 if (defined $cgi->param('sid')) {
534 IkiWiki::checksessionexpiry($cgi, $session);
536 my $rejectalldefer=$cgi->param('rejectalldefer');
540 foreach my $id (keys %vars) {
541 if ($id =~ /(.*)\Q._comment\E$/) {
542 my $action=$cgi->param($id);
543 next if $action eq 'Defer' && ! $rejectalldefer;
545 # Make sure that the id is of a legal
546 # pending comment before untainting.
547 my ($f)= $id =~ /$config{wiki_file_regexp}/;
548 if (! defined $f || ! length $f ||
549 IkiWiki::file_pruned($f, $config{srcdir})) {
550 error("illegal file");
553 my $page=IkiWiki::possibly_foolish_untaint(IkiWiki::dirname($1));
554 my $file="$config{wikistatedir}/comments_pending/".
555 IkiWiki::possibly_foolish_untaint($id);
557 if ($action eq 'Accept') {
558 my $content=eval { readfile($file) };
559 next if $@; # file vanished since form was displayed
560 my $dest=unique_comment_location($page, $content, $config{srcdir})."._comment";
561 writefile($dest, $config{srcdir}, $content);
562 if ($config{rcs} and $config{comments_commit}) {
563 IkiWiki::rcs_add($dest);
568 # This removes empty subdirs, so the
569 # .ikiwiki/comments_pending dir will
570 # go away when all are moderated.
571 require IkiWiki::Render;
572 IkiWiki::prune($file);
578 if ($config{rcs} and $config{comments_commit}) {
579 my $message = gettext("Comment moderation");
580 IkiWiki::disable_commit_hook();
581 $conflict=IkiWiki::rcs_commit_staged($message,
582 $session->param('name'), $ENV{REMOTE_ADDR});
583 IkiWiki::enable_commit_hook();
584 IkiWiki::rcs_update();
587 # Now we need a refresh
588 require IkiWiki::Render;
590 IkiWiki::saveindex();
592 error($conflict) if defined $conflict;
597 my ($id, $ctime)=@{$_};
598 my $file="$config{wikistatedir}/comments_pending/$id";
599 my $content=readfile($file);
600 my $preview=previewcomment($content, $id,
601 IkiWiki::dirname($_), $ctime);
606 } sort { $b->[1] <=> $a->[1] } comments_pending();
608 my $template=template("commentmoderation.tmpl");
611 comments => \@comments,
613 IkiWiki::printheader($session);
614 my $out=$template->output;
615 IkiWiki::run_hooks(format => sub {
616 $out = shift->(page => "", content => $out);
618 print IkiWiki::misctemplate(gettext("comment moderation"), $out);
622 sub formbuilder_setup (@) {
625 my $form=$params{form};
626 if ($form->title eq "preferences" &&
627 IkiWiki::is_admin($params{session}->param("name"))) {
628 push @{$params{buttons}}, "Comment Moderation";
629 if ($form->submitted && $form->submitted eq "Comment Moderation") {
630 commentmoderation($params{cgi}, $params{session});
635 sub comments_pending () {
636 my $dir="$config{wikistatedir}/comments_pending/";
637 return unless -d $dir;
640 eval q{use File::Find};
646 if (IkiWiki::file_pruned($_, $dir)) {
647 $File::Find::prune=1;
649 elsif (! -l $_ && ! -d _) {
650 $File::Find::prune=0;
651 my ($f)=/$config{wiki_file_regexp}/; # untaint
652 if (defined $f && $f =~ /\Q._comment\E$/) {
653 my $ctime=(stat($f))[10];
654 $f=~s/^\Q$dir\E\/?//;
655 push @ret, [$f, $ctime];
664 sub previewcomment ($$$) {
670 my $preview = IkiWiki::htmlize($location, $page, '_comment',
671 IkiWiki::linkify($location, $page,
672 IkiWiki::preprocess($location, $page,
673 IkiWiki::filter($location, $page, $content), 0, 1)));
675 my $template = template("comment.tmpl");
676 $template->param(content => $preview);
677 $template->param(ctime => displaytime($time));
679 IkiWiki::run_hooks(pagetemplate => sub {
680 shift->(page => $location,
682 template => $template);
685 $template->param(have_actions => 0);
687 return $template->output;
690 sub commentsshown ($) {
693 return ! pagespec_match($page, "internal(*/$config{comments_pagename}*)",
694 location => $page) &&
695 pagespec_match($page, $config{comments_pagespec},
699 sub commentsopen ($) {
702 return length $config{cgiurl} > 0 &&
703 (! length $config{comments_closed_pagespec} ||
704 ! pagespec_match($page, $config{comments_closed_pagespec},
708 sub pagetemplate (@) {
711 my $page = $params{page};
712 my $template = $params{template};
713 my $shown = ($template->query(name => 'commentslink') ||
714 $template->query(name => 'commentsurl') ||
715 $template->query(name => 'atomcommentsurl') ||
716 $template->query(name => 'comments')) &&
717 commentsshown($page);
719 if ($template->query(name => 'comments')) {
720 my $comments = undef;
722 $comments = IkiWiki::preprocess_inline(
723 pages => "internal($page/$config{comments_pagename}*)",
724 template => 'comment',
728 destpage => $params{destpage},
729 feedfile => 'comments',
734 if (defined $comments && length $comments) {
735 $template->param(comments => $comments);
738 if ($shown && commentsopen($page)) {
739 $template->param(addcommenturl => addcommenturl($page));
744 if ($template->query(name => 'commentsurl')) {
745 $template->param(commentsurl =>
746 urlto($page, undef, 1).'#comments');
749 if ($template->query(name => 'atomcommentsurl') && $config{usedirs}) {
750 # This will 404 until there are some comments, but I
751 # think that's probably OK...
752 $template->param(atomcommentsurl =>
753 urlto($page, undef, 1).'comments.atom');
756 if ($template->query(name => 'commentslink')) {
757 my $num=num_comments($page, $config{srcdir});
760 $link = htmllink($page, $params{destpage}, $page,
761 linktext => sprintf(ngettext("%i comment", "%i comments", $num), $num),
762 anchor => "comments",
766 elsif (commentsopen($page)) {
767 $link = "<a href=\"".addcommenturl($page)."\">".
768 #translators: Here "Comment" is a verb;
769 #translators: the user clicks on it to
770 #translators: post a comment.
774 $template->param(commentslink => $link)
779 # everything below this point is only relevant to the comments
781 if (!exists $commentstate{$page}) {
785 if ($template->query(name => 'commentid')) {
786 $template->param(commentid => page_to_id($page));
789 if ($template->query(name => 'commentuser')) {
790 $template->param(commentuser =>
791 $commentstate{$page}{commentuser});
794 if ($template->query(name => 'commentopenid')) {
795 $template->param(commentopenid =>
796 $commentstate{$page}{commentopenid});
799 if ($template->query(name => 'commentip')) {
800 $template->param(commentip =>
801 $commentstate{$page}{commentip});
804 if ($template->query(name => 'commentauthor')) {
805 $template->param(commentauthor =>
806 $commentstate{$page}{commentauthor});
809 if ($template->query(name => 'commentauthorurl')) {
810 $template->param(commentauthorurl =>
811 $commentstate{$page}{commentauthorurl});
814 if ($template->query(name => 'removeurl') &&
815 IkiWiki::Plugin::remove->can("check_canremove") &&
816 length $config{cgiurl}) {
817 $template->param(removeurl => IkiWiki::cgiurl(do => 'remove',
819 $template->param(have_actions => 1);
823 sub addcommenturl ($) {
826 return IkiWiki::cgiurl(do => 'comment', page => $page);
829 sub num_comments ($$) {
833 my @comments=glob("$dir/$page/$config{comments_pagename}*._comment");
837 sub unique_comment_location ($$$) {
840 eval q{use Digest::MD5 'md5_hex'};
842 my $content_md5=md5_hex(Encode::encode_utf8(shift));
847 my $i = num_comments($page, $dir);
850 $location = "$page/$config{comments_pagename}${i}_${content_md5}";
851 } while (-e "$dir/$location._comment");
857 # Converts a comment page name into a unique, legal html id
858 # attribute value, that can be used as an anchor to link to the
862 eval q{use Digest::MD5 'md5_hex'};
865 return "comment-".md5_hex(Encode::encode_utf8(($page)));
868 package IkiWiki::PageSpec;
870 sub match_postcomment ($$;@) {
874 if (! $postcomment) {
875 return IkiWiki::FailReason->new("not posting a comment");
877 return match_glob($page, $glob);