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);
254 elsif ($do eq 'commentsignin') {
255 IkiWiki::cgi_signin($cgi, $session);
260 # Mostly cargo-culted from IkiWiki::plugin::editpage
261 sub editcomment ($$) {
265 IkiWiki::decode_cgi_utf8($cgi);
267 eval q{use CGI::FormBuilder};
270 my @buttons = (POST_COMMENT, PREVIEW, CANCEL);
271 my $form = CGI::FormBuilder->new(
272 fields => [qw{do sid page subject editcontent type author url}],
275 required => [qw{editcontent}],
278 action => $config{cgiurl},
281 template => { template('editcomment.tmpl') },
284 IkiWiki::decode_form_utf8($form);
285 IkiWiki::run_hooks(formbuilder_setup => sub {
286 shift->(title => "comment", form => $form, cgi => $cgi,
287 session => $session, buttons => \@buttons);
289 IkiWiki::decode_form_utf8($form);
291 my $type = $form->param('type');
292 if (defined $type && length $type && $IkiWiki::hooks{htmlize}{$type}) {
293 $type = IkiWiki::possibly_foolish_untaint($type);
296 $type = $config{default_pageext};
301 if (exists $IkiWiki::hooks{htmlize}) {
302 foreach my $key (grep { !/^_/ } keys %{$IkiWiki::hooks{htmlize}}) {
303 push @page_types, [$key, $IkiWiki::hooks{htmlize}{$key}{longname} || $key];
306 @page_types=sort @page_types;
308 $form->field(name => 'do', type => 'hidden');
309 $form->field(name => 'sid', type => 'hidden', value => $session->id,
311 $form->field(name => 'page', type => 'hidden');
312 $form->field(name => 'subject', type => 'text', size => 72);
313 $form->field(name => 'editcontent', type => 'textarea', rows => 10);
314 $form->field(name => "type", value => $type, force => 1,
315 type => 'select', options => \@page_types);
317 $form->tmpl_param(username => $session->param('name'));
319 if ($config{comments_allowauthor} and
320 ! defined $session->param('name')) {
321 $form->tmpl_param(allowauthor => 1);
322 $form->field(name => 'author', type => 'text', size => '40');
323 $form->field(name => 'url', type => 'text', size => '40');
326 $form->tmpl_param(allowauthor => 0);
327 $form->field(name => 'author', type => 'hidden', value => '',
329 $form->field(name => 'url', type => 'hidden', value => '',
333 if (! defined $session->param('name')) {
334 # Make signinurl work and return here.
335 $form->tmpl_param(signinurl => IkiWiki::cgiurl(do => 'commentsignin'));
336 $session->param(postsignin => $ENV{QUERY_STRING});
337 IkiWiki::cgi_savesession($session);
340 # The untaint is OK (as in editpage) because we're about to pass
341 # it to file_pruned anyway
342 my $page = $form->field('page');
343 $page = IkiWiki::possibly_foolish_untaint($page);
344 if (! defined $page || ! length $page ||
345 IkiWiki::file_pruned($page)) {
346 error(gettext("bad page name"));
349 my $baseurl = urlto($page, undef, 1);
351 $form->title(sprintf(gettext("commenting on %s"),
352 IkiWiki::pagetitle($page)));
354 $form->tmpl_param('helponformattinglink',
355 htmllink($page, $page, 'ikiwiki/formatting',
357 linktext => 'FormattingHelp'),
358 allowdirectives => $config{allow_directives});
360 if ($form->submitted eq CANCEL) {
361 # bounce back to the page they wanted to comment on, and exit.
362 # CANCEL need not be considered in future
363 IkiWiki::redirect($cgi, urlto($page, undef, 1));
367 if (not exists $pagesources{$page}) {
368 error(sprintf(gettext(
369 "page '%s' doesn't exist, so you can't comment"),
373 if (pagespec_match($page, $config{comments_closed_pagespec},
374 location => $page)) {
375 error(sprintf(gettext(
376 "comments on page '%s' are closed"),
380 # Set a flag to indicate that we're posting a comment,
381 # so that postcomment() can tell it should match.
383 IkiWiki::check_canedit($page, $cgi, $session);
386 my $content = "[[!comment format=$type\n";
388 # FIXME: handling of double quotes probably wrong?
389 if (defined $session->param('name')) {
390 my $username = $session->param('name');
391 $username =~ s/"/"/g;
392 $content .= " username=\"$username\"\n";
394 elsif (defined $ENV{REMOTE_ADDR}) {
395 my $ip = $ENV{REMOTE_ADDR};
396 if ($ip =~ m/^([.0-9]+)$/) {
397 $content .= " ip=\"$1\"\n";
401 if ($config{comments_allowauthor}) {
402 my $author = $form->field('author');
403 if (defined $author && length $author) {
404 $author =~ s/"/"/g;
405 $content .= " claimedauthor=\"$author\"\n";
407 my $url = $form->field('url');
408 if (defined $url && length $url) {
409 $url =~ s/"/"/g;
410 $content .= " url=\"$url\"\n";
414 my $subject = $form->field('subject');
415 if (defined $subject && length $subject) {
416 $subject =~ s/"/"/g;
419 $subject = "comment ".(num_comments($page, $config{srcdir}) + 1);
421 $content .= " subject=\"$subject\"\n";
423 $content .= " date=\"" . decode_utf8(strftime('%Y-%m-%dT%H:%M:%SZ', gmtime)) . "\"\n";
425 my $editcontent = $form->field('editcontent') || '';
426 $editcontent =~ s/\r\n/\n/g;
427 $editcontent =~ s/\r/\n/g;
428 $editcontent =~ s/"/\\"/g;
429 $content .= " content=\"\"\"\n$editcontent\n\"\"\"]]\n";
431 my $location=unique_comment_location($page, $content, $config{srcdir});
433 # This is essentially a simplified version of editpage:
434 # - the user does not control the page that's created, only the parent
435 # - it's always a create operation, never an edit
436 # - this means that conflicts should never happen
437 # - this means that if they do, rocks fall and everyone dies
439 if ($form->submitted eq PREVIEW) {
440 my $preview=previewcomment($content, $location, $page, time);
441 IkiWiki::run_hooks(format => sub {
442 $preview = shift->(page => $page,
443 content => $preview);
445 $form->tmpl_param(page_preview => $preview);
448 $form->tmpl_param(page_preview => "");
451 if ($form->submitted eq POST_COMMENT && $form->validate) {
452 IkiWiki::checksessionexpiry($cgi, $session);
455 my $ok=IkiWiki::check_content(content => $form->field('editcontent'),
456 subject => $form->field('subject'),
457 $config{comments_allowauthor} ? (
458 author => $form->field('author'),
459 url => $form->field('url'),
469 my $penddir=$config{wikistatedir}."/comments_pending";
470 $location=unique_comment_location($page, $content, $penddir);
471 writefile("$location._comment", $penddir, $content);
472 IkiWiki::printheader($session);
473 print IkiWiki::misctemplate(gettext(gettext("comment stored for moderation")),
475 gettext("Your comment will be posted after moderator review").
480 # FIXME: could probably do some sort of graceful retry
481 # on error? Would require significant unwinding though
482 my $file = "$location._comment";
483 writefile($file, $config{srcdir}, $content);
487 if ($config{rcs} and $config{comments_commit}) {
488 my $message = gettext("Added a comment");
489 if (defined $form->field('subject') &&
490 length $form->field('subject')) {
492 gettext("Added a comment: %s"),
493 $form->field('subject'));
496 IkiWiki::rcs_add($file);
497 IkiWiki::disable_commit_hook();
498 $conflict = IkiWiki::rcs_commit_staged($message,
499 $session->param('name'), $ENV{REMOTE_ADDR});
500 IkiWiki::enable_commit_hook();
501 IkiWiki::rcs_update();
504 # Now we need a refresh
505 require IkiWiki::Render;
507 IkiWiki::saveindex();
509 # this should never happen, unless a committer deliberately
510 # breaks it or something
511 error($conflict) if defined $conflict;
513 # Jump to the new comment on the page.
514 # The trailing question mark tries to avoid broken
515 # caches and get the most recent version of the page.
516 IkiWiki::redirect($cgi, urlto($page, undef, 1).
517 "?updated#".page_to_id($location));
521 IkiWiki::showform ($form, \@buttons, $session, $cgi,
522 forcebaseurl => $baseurl);
528 sub commentmoderation ($$) {
532 IkiWiki::needsignin($cgi, $session);
533 if (! IkiWiki::is_admin($session->param("name"))) {
534 error(gettext("you are not logged in as an admin"));
537 IkiWiki::decode_cgi_utf8($cgi);
539 if (defined $cgi->param('sid')) {
540 IkiWiki::checksessionexpiry($cgi, $session);
542 my $rejectalldefer=$cgi->param('rejectalldefer');
546 foreach my $id (keys %vars) {
547 if ($id =~ /(.*)\Q._comment\E$/) {
548 my $action=$cgi->param($id);
549 next if $action eq 'Defer' && ! $rejectalldefer;
551 # Make sure that the id is of a legal
552 # pending comment before untainting.
553 my ($f)= $id =~ /$config{wiki_file_regexp}/;
554 if (! defined $f || ! length $f ||
555 IkiWiki::file_pruned($f)) {
556 error("illegal file");
559 my $page=IkiWiki::possibly_foolish_untaint(IkiWiki::dirname($1));
560 my $file="$config{wikistatedir}/comments_pending/".
561 IkiWiki::possibly_foolish_untaint($id);
563 if ($action eq 'Accept') {
564 my $content=eval { readfile($file) };
565 next if $@; # file vanished since form was displayed
566 my $dest=unique_comment_location($page, $content, $config{srcdir})."._comment";
567 writefile($dest, $config{srcdir}, $content);
568 if ($config{rcs} and $config{comments_commit}) {
569 IkiWiki::rcs_add($dest);
574 # This removes empty subdirs, so the
575 # .ikiwiki/comments_pending dir will
576 # go away when all are moderated.
577 require IkiWiki::Render;
578 IkiWiki::prune($file);
584 if ($config{rcs} and $config{comments_commit}) {
585 my $message = gettext("Comment moderation");
586 IkiWiki::disable_commit_hook();
587 $conflict=IkiWiki::rcs_commit_staged($message,
588 $session->param('name'), $ENV{REMOTE_ADDR});
589 IkiWiki::enable_commit_hook();
590 IkiWiki::rcs_update();
593 # Now we need a refresh
594 require IkiWiki::Render;
596 IkiWiki::saveindex();
598 error($conflict) if defined $conflict;
603 my ($id, $ctime)=@{$_};
604 my $file="$config{wikistatedir}/comments_pending/$id";
605 my $content=readfile($file);
606 my $preview=previewcomment($content, $id,
607 IkiWiki::dirname($_), $ctime);
612 } sort { $b->[1] <=> $a->[1] } comments_pending();
614 my $template=template("commentmoderation.tmpl");
617 comments => \@comments,
619 IkiWiki::printheader($session);
620 my $out=$template->output;
621 IkiWiki::run_hooks(format => sub {
622 $out = shift->(page => "", content => $out);
624 print IkiWiki::misctemplate(gettext("comment moderation"), $out);
628 sub formbuilder_setup (@) {
631 my $form=$params{form};
632 if ($form->title eq "preferences" &&
633 IkiWiki::is_admin($params{session}->param("name"))) {
634 push @{$params{buttons}}, "Comment Moderation";
635 if ($form->submitted && $form->submitted eq "Comment Moderation") {
636 commentmoderation($params{cgi}, $params{session});
641 sub comments_pending () {
642 my $dir="$config{wikistatedir}/comments_pending/";
643 return unless -d $dir;
646 eval q{use File::Find};
651 my $file=decode_utf8($_);
652 $file=~s/^\Q$dir\E\/?//;
653 return if ! length $file || IkiWiki::file_pruned($file)
654 || -l $_ || -d _ || $file !~ /\Q._comment\E$/;
655 my ($f) = $file =~ /$config{wiki_file_regexp}/; # untaint
657 my $ctime=(stat($_))[10];
658 push @ret, [$f, $ctime];
666 sub previewcomment ($$$) {
672 my $preview = IkiWiki::htmlize($location, $page, '_comment',
673 IkiWiki::linkify($location, $page,
674 IkiWiki::preprocess($location, $page,
675 IkiWiki::filter($location, $page, $content), 0, 1)));
677 my $template = template("comment.tmpl");
678 $template->param(content => $preview);
679 $template->param(ctime => displaytime($time, undef, 1));
680 $template->param(html5 => $config{html5});
682 IkiWiki::run_hooks(pagetemplate => sub {
683 shift->(page => $location,
685 template => $template);
688 $template->param(have_actions => 0);
690 return $template->output;
693 sub commentsshown ($) {
696 return ! pagespec_match($page, "internal(*/$config{comments_pagename}*)",
697 location => $page) &&
698 pagespec_match($page, $config{comments_pagespec},
702 sub commentsopen ($) {
705 return length $config{cgiurl} > 0 &&
706 (! length $config{comments_closed_pagespec} ||
707 ! pagespec_match($page, $config{comments_closed_pagespec},
711 sub pagetemplate (@) {
714 my $page = $params{page};
715 my $template = $params{template};
716 my $shown = ($template->query(name => 'commentslink') ||
717 $template->query(name => 'commentsurl') ||
718 $template->query(name => 'atomcommentsurl') ||
719 $template->query(name => 'comments')) &&
720 commentsshown($page);
722 if ($template->query(name => 'comments')) {
723 my $comments = undef;
725 $comments = IkiWiki::preprocess_inline(
726 pages => "internal($page/$config{comments_pagename}*)",
727 template => 'comment',
731 destpage => $params{destpage},
732 feedfile => 'comments',
737 if (defined $comments && length $comments) {
738 $template->param(comments => $comments);
741 if ($shown && commentsopen($page)) {
742 $template->param(addcommenturl => addcommenturl($page));
747 if ($template->query(name => 'commentsurl')) {
748 $template->param(commentsurl =>
749 urlto($page, undef, 1).'#comments');
752 if ($template->query(name => 'atomcommentsurl') && $config{usedirs}) {
753 # This will 404 until there are some comments, but I
754 # think that's probably OK...
755 $template->param(atomcommentsurl =>
756 urlto($page, undef, 1).'comments.atom');
759 if ($template->query(name => 'commentslink')) {
760 my $num=num_comments($page, $config{srcdir});
763 $link = htmllink($page, $params{destpage}, $page,
764 linktext => sprintf(ngettext("%i comment", "%i comments", $num), $num),
765 anchor => "comments",
769 elsif (commentsopen($page)) {
770 $link = "<a href=\"".addcommenturl($page)."\">".
771 #translators: Here "Comment" is a verb;
772 #translators: the user clicks on it to
773 #translators: post a comment.
777 $template->param(commentslink => $link)
782 # everything below this point is only relevant to the comments
784 if (!exists $commentstate{$page}) {
788 if ($template->query(name => 'commentid')) {
789 $template->param(commentid => page_to_id($page));
792 if ($template->query(name => 'commentuser')) {
793 $template->param(commentuser =>
794 $commentstate{$page}{commentuser});
797 if ($template->query(name => 'commentopenid')) {
798 $template->param(commentopenid =>
799 $commentstate{$page}{commentopenid});
802 if ($template->query(name => 'commentip')) {
803 $template->param(commentip =>
804 $commentstate{$page}{commentip});
807 if ($template->query(name => 'commentauthor')) {
808 $template->param(commentauthor =>
809 $commentstate{$page}{commentauthor});
812 if ($template->query(name => 'commentauthorurl')) {
813 $template->param(commentauthorurl =>
814 $commentstate{$page}{commentauthorurl});
817 if ($template->query(name => 'removeurl') &&
818 IkiWiki::Plugin::remove->can("check_canremove") &&
819 length $config{cgiurl}) {
820 $template->param(removeurl => IkiWiki::cgiurl(do => 'remove',
822 $template->param(have_actions => 1);
826 sub addcommenturl ($) {
829 return IkiWiki::cgiurl(do => 'comment', page => $page);
832 sub num_comments ($$) {
836 my @comments=glob("$dir/$page/$config{comments_pagename}*._comment");
840 sub unique_comment_location ($$$) {
843 eval q{use Digest::MD5 'md5_hex'};
845 my $content_md5=md5_hex(Encode::encode_utf8(shift));
850 my $i = num_comments($page, $dir);
853 $location = "$page/$config{comments_pagename}${i}_${content_md5}";
854 } while (-e "$dir/$location._comment");
860 # Converts a comment page name into a unique, legal html id
861 # attribute value, that can be used as an anchor to link to the
865 eval q{use Digest::MD5 'md5_hex'};
868 return "comment-".md5_hex(Encode::encode_utf8(($page)));
871 package IkiWiki::PageSpec;
873 sub match_postcomment ($$;@) {
877 if (! $postcomment) {
878 return IkiWiki::FailReason->new("not posting a comment");
880 return match_glob($page, $glob);