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 IkiWiki::loadplugin("inline");
38 comments_pagespec => {
40 example => 'blog/* and !*/Discussion',
41 description => 'PageSpec of pages where comments are allowed',
42 link => 'ikiwiki/PageSpec',
46 comments_closed_pagespec => {
48 example => 'blog/controversial or blog/flamewar',
49 description => 'PageSpec of pages where posting new comments is not allowed',
50 link => 'ikiwiki/PageSpec',
54 comments_pagename => {
56 default => 'comment_',
57 description => 'Base name for comments, e.g. "comment_" for pages like "sandbox/comment_12"',
58 safe => 0, # manual page moving required
61 comments_allowdirectives => {
64 description => 'Interpret directives in comments?',
68 comments_allowauthor => {
71 description => 'Allow anonymous commenters to set an author name?',
78 description => 'commit comments to the VCS',
79 # old uncommitted comments are likely to cause
80 # confusion if this is changed
87 $config{comments_commit} = 1
88 unless defined $config{comments_commit};
89 $config{comments_pagespec} = ''
90 unless defined $config{comments_pagespec};
91 $config{comments_closed_pagespec} = ''
92 unless defined $config{comments_closed_pagespec};
93 $config{comments_pagename} = 'comment_'
94 unless defined $config{comments_pagename};
99 return $params{content};
102 # FIXME: copied verbatim from meta
105 if (exists $IkiWiki::Plugin::htmlscrubber::{safe_url_regexp} &&
106 defined $IkiWiki::Plugin::htmlscrubber::safe_url_regexp) {
107 return $url=~/$IkiWiki::Plugin::htmlscrubber::safe_url_regexp/;
116 my $page = $params{page};
118 my $format = $params{format};
119 if (defined $format && ! exists $IkiWiki::hooks{htmlize}{$format}) {
120 error(sprintf(gettext("unsupported page format %s"), $format));
123 my $content = $params{content};
124 if (! defined $content) {
125 error(gettext("comment must have content"));
127 $content =~ s/\\"/"/g;
129 $content = IkiWiki::filter($page, $params{destpage}, $content);
131 if ($config{comments_allowdirectives}) {
132 $content = IkiWiki::preprocess($page, $params{destpage},
136 # no need to bother with htmlize if it's just HTML
137 $content = IkiWiki::htmlize($page, $params{destpage}, $format, $content)
140 IkiWiki::run_hooks(sanitize => sub {
143 destpage => $params{destpage},
148 # set metadata, possibly overriding [[!meta]] directives from the
154 my $commentauthorurl;
156 if (defined $params{username}) {
157 $commentuser = $params{username};
159 my $oiduser = eval { IkiWiki::openiduser($commentuser) };
161 if (defined $oiduser) {
162 # looks like an OpenID
163 $commentauthorurl = $commentuser;
164 $commentauthor = $oiduser;
165 $commentopenid = $commentuser;
168 $commentauthorurl = IkiWiki::cgiurl(
170 page => (length $config{userdir}
171 ? "$config{userdir}/$commentuser"
174 $commentauthor = $commentuser;
178 if (defined $params{ip}) {
179 $commentip = $params{ip};
181 $commentauthor = gettext("Anonymous");
184 $commentstate{$page}{commentuser} = $commentuser;
185 $commentstate{$page}{commentopenid} = $commentopenid;
186 $commentstate{$page}{commentip} = $commentip;
187 $commentstate{$page}{commentauthor} = $commentauthor;
188 $commentstate{$page}{commentauthorurl} = $commentauthorurl;
189 if (! defined $pagestate{$page}{meta}{author}) {
190 $pagestate{$page}{meta}{author} = $commentauthor;
192 if (! defined $pagestate{$page}{meta}{authorurl}) {
193 $pagestate{$page}{meta}{authorurl} = $commentauthorurl;
196 if ($config{comments_allowauthor}) {
197 if (defined $params{claimedauthor}) {
198 $pagestate{$page}{meta}{author} = $params{claimedauthor};
201 if (defined $params{url}) {
202 my $url=$params{url};
204 eval q{use URI::Heuristic};
206 $url=URI::Heuristic::uf_uristr($url);
210 $pagestate{$page}{meta}{authorurl} = $url;
215 $pagestate{$page}{meta}{author} = $commentauthor;
216 $pagestate{$page}{meta}{authorurl} = $commentauthorurl;
219 if (defined $params{subject}) {
220 $pagestate{$page}{meta}{title} = $params{subject};
223 if ($params{page} =~ m/\/(\Q$config{comments_pagename}\E\d+)$/) {
224 $pagestate{$page}{meta}{permalink} = urlto(IkiWiki::dirname($params{page}), undef, 1).
228 eval q{use Date::Parse};
230 my $time = str2time($params{date});
231 $IkiWiki::pagectime{$page} = $time if defined $time;
237 # This is exactly the same as recentchanges_link :-(
240 if (defined $cgi->param('do') && $cgi->param('do') eq "commenter") {
242 my $page=decode_utf8($cgi->param("page"));
243 if (! defined $page) {
244 error("missing page parameter");
247 IkiWiki::loadindex();
249 my $link=bestlink("", $page);
250 if (! length $link) {
251 print "Content-type: text/html\n\n";
252 print IkiWiki::misctemplate(gettext(gettext("missing page")),
254 sprintf(gettext("The page %s does not exist."),
255 htmllink("", "", $page)).
259 IkiWiki::redirect($cgi, urlto($link, undef, 1));
266 sub sessioncgi ($$) {
270 my $do = $cgi->param('do');
271 if ($do eq 'comment') {
272 editcomment($cgi, $session);
274 elsif ($do eq 'commentmoderation') {
275 commentmoderation($cgi, $session);
279 # Mostly cargo-culted from IkiWiki::plugin::editpage
280 sub editcomment ($$) {
284 IkiWiki::decode_cgi_utf8($cgi);
286 eval q{use CGI::FormBuilder};
289 my @buttons = (POST_COMMENT, PREVIEW, CANCEL);
290 my $form = CGI::FormBuilder->new(
291 fields => [qw{do sid page subject editcontent type author url}],
294 required => [qw{editcontent}],
297 action => $config{cgiurl},
300 template => scalar IkiWiki::template_params('editcomment.tmpl'),
303 IkiWiki::decode_form_utf8($form);
304 IkiWiki::run_hooks(formbuilder_setup => sub {
305 shift->(title => "comment", form => $form, cgi => $cgi,
306 session => $session, buttons => \@buttons);
308 IkiWiki::decode_form_utf8($form);
310 my $type = $form->param('type');
311 if (defined $type && length $type && $IkiWiki::hooks{htmlize}{$type}) {
312 $type = IkiWiki::possibly_foolish_untaint($type);
315 $type = $config{default_pageext};
318 if (exists $IkiWiki::hooks{htmlize}) {
319 @page_types = grep { ! /^_/ } keys %{$IkiWiki::hooks{htmlize}};
322 $form->field(name => 'do', type => 'hidden');
323 $form->field(name => 'sid', type => 'hidden', value => $session->id,
325 $form->field(name => 'page', type => 'hidden');
326 $form->field(name => 'subject', type => 'text', size => 72);
327 $form->field(name => 'editcontent', type => 'textarea', rows => 10);
328 $form->field(name => "type", value => $type, force => 1,
329 type => 'select', options => \@page_types);
331 $form->tmpl_param(username => $session->param('name'));
333 if ($config{comments_allowauthor} and
334 ! defined $session->param('name')) {
335 $form->tmpl_param(allowauthor => 1);
336 $form->field(name => 'author', type => 'text', size => '40');
337 $form->field(name => 'url', type => 'text', size => '40');
340 $form->tmpl_param(allowauthor => 0);
341 $form->field(name => 'author', type => 'hidden', value => '',
343 $form->field(name => 'url', type => 'hidden', value => '',
347 # The untaint is OK (as in editpage) because we're about to pass
348 # it to file_pruned anyway
349 my $page = $form->field('page');
350 $page = IkiWiki::possibly_foolish_untaint($page);
351 if (! defined $page || ! length $page ||
352 IkiWiki::file_pruned($page, $config{srcdir})) {
353 error(gettext("bad page name"));
356 my $baseurl = urlto($page, undef, 1);
358 $form->title(sprintf(gettext("commenting on %s"),
359 IkiWiki::pagetitle($page)));
361 $form->tmpl_param('helponformattinglink',
362 htmllink($page, $page, 'ikiwiki/formatting',
364 linktext => 'FormattingHelp'),
365 allowdirectives => $config{allow_directives});
367 if ($form->submitted eq CANCEL) {
368 # bounce back to the page they wanted to comment on, and exit.
369 # CANCEL need not be considered in future
370 IkiWiki::redirect($cgi, urlto($page, undef, 1));
374 if (not exists $pagesources{$page}) {
375 error(sprintf(gettext(
376 "page '%s' doesn't exist, so you can't comment"),
380 if (pagespec_match($page, $config{comments_closed_pagespec},
381 location => $page)) {
382 error(sprintf(gettext(
383 "comments on page '%s' are closed"),
387 # Set a flag to indicate that we're posting a comment,
388 # so that postcomment() can tell it should match.
390 IkiWiki::check_canedit($page, $cgi, $session);
393 my $location=unique_comment_location($page, $config{srcdir});
395 my $content = "[[!_comment format=$type\n";
397 # FIXME: handling of double quotes probably wrong?
398 if (defined $session->param('name')) {
399 my $username = $session->param('name');
400 $username =~ s/"/"/g;
401 $content .= " username=\"$username\"\n";
403 elsif (defined $ENV{REMOTE_ADDR}) {
404 my $ip = $ENV{REMOTE_ADDR};
405 if ($ip =~ m/^([.0-9]+)$/) {
406 $content .= " ip=\"$1\"\n";
410 if ($config{comments_allowauthor}) {
411 my $author = $form->field('author');
412 if (defined $author && length $author) {
413 $author =~ s/"/"/g;
414 $content .= " claimedauthor=\"$author\"\n";
416 my $url = $form->field('url');
417 if (defined $url && length $url) {
418 $url =~ s/"/"/g;
419 $content .= " url=\"$url\"\n";
423 my $subject = $form->field('subject');
424 if (defined $subject && length $subject) {
425 $subject =~ s/"/"/g;
426 $content .= " subject=\"$subject\"\n";
429 $content .= " date=\"" . decode_utf8(strftime('%Y-%m-%dT%H:%M:%SZ', gmtime)) . "\"\n";
431 my $editcontent = $form->field('editcontent') || '';
432 $editcontent =~ s/\r\n/\n/g;
433 $editcontent =~ s/\r/\n/g;
434 $editcontent =~ s/"/\\"/g;
435 $content .= " content=\"\"\"\n$editcontent\n\"\"\"]]\n";
437 # This is essentially a simplified version of editpage:
438 # - the user does not control the page that's created, only the parent
439 # - it's always a create operation, never an edit
440 # - this means that conflicts should never happen
441 # - this means that if they do, rocks fall and everyone dies
443 if ($form->submitted eq PREVIEW) {
444 $form->tmpl_param(page_preview =>
445 previewcomment($content, $location, $page, time));
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, $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)."?updated#$location");
520 IkiWiki::showform ($form, \@buttons, $session, $cgi,
521 forcebaseurl => $baseurl);
527 sub commentmoderation ($$) {
531 IkiWiki::needsignin($cgi, $session);
532 if (! IkiWiki::is_admin($session->param("name"))) {
533 error(gettext("you are not logged in as an admin"));
536 IkiWiki::decode_cgi_utf8($cgi);
538 if (defined $cgi->param('sid')) {
539 IkiWiki::checksessionexpiry($cgi, $session);
543 foreach my $id (keys %vars) {
544 if ($id =~ /(.*)\Q._comment\E$/) {
545 my $action=$cgi->param($id);
546 next if $action eq 'Defer';
548 # Make sure that the id is of a legal
549 # pending comment before untainting.
550 my ($f)= $id =~ /$config{wiki_file_regexp}/;
551 if (! defined $f || ! length $f ||
552 IkiWiki::file_pruned($f, $config{srcdir})) {
553 error("illegal file");
556 my $page=IkiWiki::possibly_foolish_untaint(IkiWiki::dirname($1));
557 my $file="$config{wikistatedir}/comments_pending/".
558 IkiWiki::possibly_foolish_untaint($id);
560 if ($action eq 'Accept') {
561 my $content=eval { readfile($file) };
562 next if $@; # file vanished since form was displayed
563 my $dest=unique_comment_location($page, $config{srcdir})."._comment";
564 writefile($dest, $config{srcdir}, $content);
565 if ($config{rcs} and $config{comments_commit}) {
566 IkiWiki::rcs_add($dest);
571 # This removes empty subdirs, so the
572 # .ikiwiki/comments_pending dir will
573 # go away when all are moderated.
574 require IkiWiki::Render;
575 IkiWiki::prune($file);
581 if ($config{rcs} and $config{comments_commit}) {
582 my $message = gettext("Comment moderation");
583 IkiWiki::disable_commit_hook();
584 $conflict=IkiWiki::rcs_commit_staged($message,
585 $session->param('name'), $ENV{REMOTE_ADDR});
586 IkiWiki::enable_commit_hook();
587 IkiWiki::rcs_update();
590 # Now we need a refresh
591 require IkiWiki::Render;
593 IkiWiki::saveindex();
595 error($conflict) if defined $conflict;
601 my $file="$config{wikistatedir}/comments_pending/$id";
602 my $content=readfile($file);
603 my $ctime=(stat($file))[10];
606 view => previewcomment($content, $id,
607 IkiWiki::dirname($_), $ctime),
609 } comments_pending();
611 my $template=template("commentmoderation.tmpl");
614 comments => \@comments,
616 IkiWiki::printheader($session);
617 print IkiWiki::misctemplate(gettext("comment moderation"), $template->output);
621 sub comments_pending () {
622 my $dir="$config{wikistatedir}/comments_pending/";
623 return unless -d $dir;
626 eval q{use File::Find};
632 if (IkiWiki::file_pruned($_, $dir)) {
633 $File::Find::prune=1;
635 elsif (! -l $_ && ! -d _) {
636 $File::Find::prune=0;
637 my ($f)=/$config{wiki_file_regexp}/; # untaint
638 if (defined $f && $f =~ /\Q._comment\E$/) {
639 $f=~s/^\Q$dir\E\/?//;
649 sub previewcomment ($$$) {
655 my $preview = IkiWiki::htmlize($location, $page, '_comment',
656 IkiWiki::linkify($location, $page,
657 IkiWiki::preprocess($location, $page,
658 IkiWiki::filter($location,
661 IkiWiki::run_hooks(format => sub {
662 $preview = shift->(page => $page,
663 content => $preview);
666 my $template = template("comment.tmpl");
667 $template->param(content => $preview);
668 $template->param(ctime => displaytime($time));
670 IkiWiki::run_hooks(pagetemplate => sub {
671 shift->(page => $location,
673 template => $template);
676 return $template->output;
679 sub commentsshown ($) {
682 return ! pagespec_match($page, "*/$config{comments_pagename}*",
683 location => $page) &&
684 pagespec_match($page, $config{comments_pagespec},
688 sub commentsopen ($) {
691 return length $config{cgiurl} > 0 &&
692 (! length $config{comments_closed_pagespec} ||
693 ! pagespec_match($page, $config{comments_closed_pagespec},
697 sub pagetemplate (@) {
700 my $page = $params{page};
701 my $template = $params{template};
702 my $shown = ($template->query(name => 'commentslink') ||
703 $template->query(name => 'commentsurl') ||
704 $template->query(name => 'atomcommentsurl') ||
705 $template->query(name => 'comments')) &&
706 commentsshown($page);
708 if ($template->query(name => 'comments')) {
709 my $comments = undef;
711 $comments = IkiWiki::preprocess_inline(
712 pages => "internal($page/$config{comments_pagename}*)",
713 template => 'comment',
717 destpage => $params{destpage},
718 feedfile => 'comments',
723 if (defined $comments && length $comments) {
724 $template->param(comments => $comments);
727 if ($shown && commentsopen($page)) {
728 my $addcommenturl = IkiWiki::cgiurl(do => 'comment',
730 $template->param(addcommenturl => $addcommenturl);
734 if ($template->query(name => 'commentsurl')) {
736 $template->param(commentsurl =>
737 urlto($page, undef, 1).'#comments');
741 if ($template->query(name => 'atomcommentsurl') && $config{usedirs}) {
743 # This will 404 until there are some comments, but I
744 # think that's probably OK...
745 $template->param(atomcommentsurl =>
746 urlto($page, undef, 1).'comments.atom');
750 if ($template->query(name => 'commentslink')) {
751 # XXX Would be nice to say how many comments there are in
752 # the link. But, to update the number, blog pages
753 # would have to update whenever comments of any inlines
754 # page are added, which is not currently done.
756 $template->param(commentslink =>
757 htmllink($page, $params{destpage}, $page,
758 linktext => gettext("Comments"),
759 anchor => "comments",
760 noimageinline => 1));
764 # everything below this point is only relevant to the comments
766 if (!exists $commentstate{$page}) {
770 if ($template->query(name => 'commentuser')) {
771 $template->param(commentuser =>
772 $commentstate{$page}{commentuser});
775 if ($template->query(name => 'commentopenid')) {
776 $template->param(commentopenid =>
777 $commentstate{$page}{commentopenid});
780 if ($template->query(name => 'commentip')) {
781 $template->param(commentip =>
782 $commentstate{$page}{commentip});
785 if ($template->query(name => 'commentauthor')) {
786 $template->param(commentauthor =>
787 $commentstate{$page}{commentauthor});
790 if ($template->query(name => 'commentauthorurl')) {
791 $template->param(commentauthorurl =>
792 $commentstate{$page}{commentauthorurl});
795 if ($template->query(name => 'removeurl') &&
796 IkiWiki::Plugin::remove->can("check_canremove") &&
797 length $config{cgiurl}) {
798 $template->param(removeurl => IkiWiki::cgiurl(do => 'remove',
800 $template->param(have_actions => 1);
804 sub unique_comment_location ($) {
812 $location = "$page/$config{comments_pagename}$i";
813 } while (-e "$dir/$location._comment");
818 package IkiWiki::PageSpec;
820 sub match_postcomment ($$;@) {
824 if (! $postcomment) {
825 return IkiWiki::FailReason->new("not posting a comment");
827 return match_glob($page, $glob);