summaryrefslogtreecommitdiff
path: root/IkiWiki/Plugin/comments.pm
blob: 4d225b90ae88b40524b51858edcc9366efd99c01 (plain)
  1. #!/usr/bin/perl
  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;
  7. use warnings;
  8. use strict;
  9. use IkiWiki 3.00;
  10. use Encode;
  11. use POSIX qw(strftime);
  12. use constant PREVIEW => "Preview";
  13. use constant POST_COMMENT => "Post comment";
  14. use constant CANCEL => "Cancel";
  15. my $postcomment;
  16. my %commentstate;
  17. sub import {
  18. hook(type => "checkconfig", id => 'comments', call => \&checkconfig);
  19. hook(type => "getsetup", id => 'comments', call => \&getsetup);
  20. hook(type => "preprocess", id => '_comment', call => \&preprocess);
  21. hook(type => "sessioncgi", id => 'comment', call => \&sessioncgi);
  22. hook(type => "htmlize", id => "_comment", call => \&htmlize);
  23. hook(type => "pagetemplate", id => "comments", call => \&pagetemplate);
  24. hook(type => "cgi", id => "comments", call => \&linkcgi);
  25. IkiWiki::loadplugin("inline");
  26. }
  27. sub getsetup () {
  28. return
  29. plugin => {
  30. safe => 1,
  31. rebuild => 1,
  32. },
  33. comments_pagespec => {
  34. type => 'pagespec',
  35. example => 'blog/* and !*/Discussion',
  36. description => 'PageSpec of pages where comments are allowed',
  37. link => 'ikiwiki/PageSpec',
  38. safe => 1,
  39. rebuild => 1,
  40. },
  41. comments_closed_pagespec => {
  42. type => 'pagespec',
  43. example => 'blog/controversial or blog/flamewar',
  44. description => 'PageSpec of pages where posting new comments is not allowed',
  45. link => 'ikiwiki/PageSpec',
  46. safe => 1,
  47. rebuild => 1,
  48. },
  49. comments_pagename => {
  50. type => 'string',
  51. default => 'comment_',
  52. description => 'Base name for comments, e.g. "comment_" for pages like "sandbox/comment_12"',
  53. safe => 0, # manual page moving required
  54. rebuild => undef,
  55. },
  56. comments_allowdirectives => {
  57. type => 'boolean',
  58. example => 0,
  59. description => 'Interpret directives in comments?',
  60. safe => 1,
  61. rebuild => 0,
  62. },
  63. comments_allowauthor => {
  64. type => 'boolean',
  65. example => 0,
  66. description => 'Allow anonymous commenters to set an author name?',
  67. safe => 1,
  68. rebuild => 0,
  69. },
  70. comments_commit => {
  71. type => 'boolean',
  72. example => 1,
  73. description => 'commit comments to the VCS',
  74. # old uncommitted comments are likely to cause
  75. # confusion if this is changed
  76. safe => 0,
  77. rebuild => 0,
  78. },
  79. }
  80. sub checkconfig () {
  81. $config{comments_commit} = 1
  82. unless defined $config{comments_commit};
  83. $config{comments_pagespec} = ''
  84. unless defined $config{comments_pagespec};
  85. $config{comments_closed_pagespec} = ''
  86. unless defined $config{comments_closed_pagespec};
  87. $config{comments_pagename} = 'comment_'
  88. unless defined $config{comments_pagename};
  89. }
  90. sub htmlize {
  91. my %params = @_;
  92. return $params{content};
  93. }
  94. # FIXME: copied verbatim from meta
  95. sub safeurl ($) {
  96. my $url=shift;
  97. if (exists $IkiWiki::Plugin::htmlscrubber::{safe_url_regexp} &&
  98. defined $IkiWiki::Plugin::htmlscrubber::safe_url_regexp) {
  99. return $url=~/$IkiWiki::Plugin::htmlscrubber::safe_url_regexp/;
  100. }
  101. else {
  102. return 1;
  103. }
  104. }
  105. sub preprocess {
  106. my %params = @_;
  107. my $page = $params{page};
  108. my $format = $params{format};
  109. if (defined $format && ! exists $IkiWiki::hooks{htmlize}{$format}) {
  110. error(sprintf(gettext("unsupported page format %s"), $format));
  111. }
  112. my $content = $params{content};
  113. if (! defined $content) {
  114. error(gettext("comment must have content"));
  115. }
  116. $content =~ s/\\"/"/g;
  117. $content = IkiWiki::filter($page, $params{destpage}, $content);
  118. if ($config{comments_allowdirectives}) {
  119. $content = IkiWiki::preprocess($page, $params{destpage},
  120. $content);
  121. }
  122. # no need to bother with htmlize if it's just HTML
  123. $content = IkiWiki::htmlize($page, $params{destpage}, $format,
  124. $content) if defined $format;
  125. IkiWiki::run_hooks(sanitize => sub {
  126. $content = shift->(
  127. page => $page,
  128. destpage => $params{destpage},
  129. content => $content,
  130. );
  131. });
  132. # set metadata, possibly overriding [[!meta]] directives from the
  133. # comment itself
  134. my $commentuser;
  135. my $commentip;
  136. my $commentauthor;
  137. my $commentauthorurl;
  138. my $commentopenid;
  139. if (defined $params{username}) {
  140. $commentuser = $params{username};
  141. my $oiduser = eval { IkiWiki::openiduser($commentuser) };
  142. if (defined $oiduser) {
  143. # looks like an OpenID
  144. $commentauthorurl = $commentuser;
  145. $commentauthor = $oiduser;
  146. $commentopenid = $commentuser;
  147. }
  148. else {
  149. $commentauthorurl = IkiWiki::cgiurl(
  150. do => 'commenter',
  151. page => (length $config{userdir}
  152. ? "$config{userdir}/$commentuser"
  153. : "$commentuser"));
  154. $commentauthor = $commentuser;
  155. }
  156. }
  157. else {
  158. if (defined $params{ip}) {
  159. $commentip = $params{ip};
  160. }
  161. $commentauthor = gettext("Anonymous");
  162. }
  163. $commentstate{$page}{commentuser} = $commentuser;
  164. $commentstate{$page}{commentopenid} = $commentopenid;
  165. $commentstate{$page}{commentip} = $commentip;
  166. $commentstate{$page}{commentauthor} = $commentauthor;
  167. $commentstate{$page}{commentauthorurl} = $commentauthorurl;
  168. if (! defined $pagestate{$page}{meta}{author}) {
  169. $pagestate{$page}{meta}{author} = $commentauthor;
  170. }
  171. if (! defined $pagestate{$page}{meta}{authorurl}) {
  172. $pagestate{$page}{meta}{authorurl} = $commentauthorurl;
  173. }
  174. if ($config{comments_allowauthor}) {
  175. if (defined $params{claimedauthor}) {
  176. $pagestate{$page}{meta}{author} = $params{claimedauthor};
  177. }
  178. if (defined $params{url}) {
  179. my $url=$params{url};
  180. eval q{use URI::Heuristic};
  181. if (! $@) {
  182. $url=URI::Heuristic::uf_uristr($url);
  183. }
  184. if (safeurl($url)) {
  185. $pagestate{$page}{meta}{authorurl} = $url;
  186. }
  187. }
  188. }
  189. else {
  190. $pagestate{$page}{meta}{author} = $commentauthor;
  191. $pagestate{$page}{meta}{authorurl} = $commentauthorurl;
  192. }
  193. if (defined $params{subject}) {
  194. $pagestate{$page}{meta}{title} = $params{subject};
  195. }
  196. if ($params{page} =~ m/\/(\Q$config{comments_pagename}\E\d+)$/) {
  197. $pagestate{$page}{meta}{permalink} = urlto(IkiWiki::dirname($params{page}), undef, 1).
  198. "#".$params{page};
  199. }
  200. eval q{use Date::Parse};
  201. if (! $@) {
  202. my $time = str2time($params{date});
  203. $IkiWiki::pagectime{$page} = $time if defined $time;
  204. }
  205. return $content;
  206. }
  207. # This is exactly the same as recentchanges_link :-(
  208. sub linkcgi ($) {
  209. my $cgi=shift;
  210. if (defined $cgi->param('do') && $cgi->param('do') eq "commenter") {
  211. my $page=decode_utf8($cgi->param("page"));
  212. if (! defined $page) {
  213. error("missing page parameter");
  214. }
  215. IkiWiki::loadindex();
  216. my $link=bestlink("", $page);
  217. if (! length $link) {
  218. print "Content-type: text/html\n\n";
  219. print IkiWiki::misctemplate(gettext(gettext("missing page")),
  220. "<p>".
  221. sprintf(gettext("The page %s does not exist."),
  222. htmllink("", "", $page)).
  223. "</p>");
  224. }
  225. else {
  226. IkiWiki::redirect($cgi, urlto($link, undef, 1));
  227. }
  228. exit;
  229. }
  230. }
  231. # Mostly cargo-culted from IkiWiki::plugin::editpage
  232. sub sessioncgi ($$) {
  233. my $cgi=shift;
  234. my $session=shift;
  235. my $do = $cgi->param('do');
  236. return unless $do eq 'comment';
  237. IkiWiki::decode_cgi_utf8($cgi);
  238. eval q{use CGI::FormBuilder};
  239. error($@) if $@;
  240. my @buttons = (POST_COMMENT, PREVIEW, CANCEL);
  241. my $form = CGI::FormBuilder->new(
  242. fields => [qw{do sid page subject editcontent type author url}],
  243. charset => 'utf-8',
  244. method => 'POST',
  245. required => [qw{editcontent}],
  246. javascript => 0,
  247. params => $cgi,
  248. action => $config{cgiurl},
  249. header => 0,
  250. table => 0,
  251. template => scalar IkiWiki::template_params('editcomment.tmpl'),
  252. );
  253. IkiWiki::decode_form_utf8($form);
  254. IkiWiki::run_hooks(formbuilder_setup => sub {
  255. shift->(title => "comment", form => $form, cgi => $cgi,
  256. session => $session, buttons => \@buttons);
  257. });
  258. IkiWiki::decode_form_utf8($form);
  259. my $type = $form->param('type');
  260. if (defined $type && length $type && $IkiWiki::hooks{htmlize}{$type}) {
  261. $type = IkiWiki::possibly_foolish_untaint($type);
  262. }
  263. else {
  264. $type = $config{default_pageext};
  265. }
  266. my @page_types;
  267. if (exists $IkiWiki::hooks{htmlize}) {
  268. @page_types = grep { ! /^_/ } keys %{$IkiWiki::hooks{htmlize}};
  269. }
  270. $form->field(name => 'do', type => 'hidden');
  271. $form->field(name => 'sid', type => 'hidden', value => $session->id,
  272. force => 1);
  273. $form->field(name => 'page', type => 'hidden');
  274. $form->field(name => 'subject', type => 'text', size => 72);
  275. $form->field(name => 'editcontent', type => 'textarea', rows => 10);
  276. $form->field(name => "type", value => $type, force => 1,
  277. type => 'select', options => \@page_types);
  278. $form->tmpl_param(username => $session->param('name'));
  279. if ($config{comments_allowauthor} and
  280. ! defined $session->param('name')) {
  281. $form->tmpl_param(allowauthor => 1);
  282. $form->field(name => 'author', type => 'text', size => '40');
  283. $form->field(name => 'url', type => 'text', size => '40');
  284. }
  285. else {
  286. $form->tmpl_param(allowauthor => 0);
  287. $form->field(name => 'author', type => 'hidden', value => '',
  288. force => 1);
  289. $form->field(name => 'url', type => 'hidden', value => '',
  290. force => 1);
  291. }
  292. # The untaint is OK (as in editpage) because we're about to pass
  293. # it to file_pruned anyway
  294. my $page = $form->field('page');
  295. $page = IkiWiki::possibly_foolish_untaint($page);
  296. if (! defined $page || ! length $page ||
  297. IkiWiki::file_pruned($page, $config{srcdir})) {
  298. error(gettext("bad page name"));
  299. }
  300. my $baseurl = urlto($page, undef, 1);
  301. $form->title(sprintf(gettext("commenting on %s"),
  302. IkiWiki::pagetitle($page)));
  303. $form->tmpl_param('helponformattinglink',
  304. htmllink($page, $page, 'ikiwiki/formatting',
  305. noimageinline => 1,
  306. linktext => 'FormattingHelp'),
  307. allowdirectives => $config{allow_directives});
  308. if ($form->submitted eq CANCEL) {
  309. # bounce back to the page they wanted to comment on, and exit.
  310. # CANCEL need not be considered in future
  311. IkiWiki::redirect($cgi, urlto($page, undef, 1));
  312. exit;
  313. }
  314. if (not exists $pagesources{$page}) {
  315. error(sprintf(gettext(
  316. "page '%s' doesn't exist, so you can't comment"),
  317. $page));
  318. }
  319. if (pagespec_match($page, $config{comments_closed_pagespec},
  320. location => $page)) {
  321. error(sprintf(gettext(
  322. "comments on page '%s' are closed"),
  323. $page));
  324. }
  325. # Set a flag to indicate that we're posting a comment,
  326. # so that postcomment() can tell it should match.
  327. $postcomment=1;
  328. IkiWiki::check_canedit($page, $cgi, $session);
  329. $postcomment=0;
  330. my $location=unique_comment_location($page, $config{srcdir});
  331. my $content = "[[!_comment format=$type\n";
  332. # FIXME: handling of double quotes probably wrong?
  333. if (defined $session->param('name')) {
  334. my $username = $session->param('name');
  335. $username =~ s/"/&quot;/g;
  336. $content .= " username=\"$username\"\n";
  337. }
  338. elsif (defined $ENV{REMOTE_ADDR}) {
  339. my $ip = $ENV{REMOTE_ADDR};
  340. if ($ip =~ m/^([.0-9]+)$/) {
  341. $content .= " ip=\"$1\"\n";
  342. }
  343. }
  344. if ($config{comments_allowauthor}) {
  345. my $author = $form->field('author');
  346. if (defined $author && length $author) {
  347. $author =~ s/"/&quot;/g;
  348. $content .= " claimedauthor=\"$author\"\n";
  349. }
  350. my $url = $form->field('url');
  351. if (defined $url && length $url) {
  352. $url =~ s/"/&quot;/g;
  353. $content .= " url=\"$url\"\n";
  354. }
  355. }
  356. my $subject = $form->field('subject');
  357. if (defined $subject && length $subject) {
  358. $subject =~ s/"/&quot;/g;
  359. $content .= " subject=\"$subject\"\n";
  360. }
  361. $content .= " date=\"" . decode_utf8(strftime('%Y-%m-%dT%H:%M:%SZ', gmtime)) . "\"\n";
  362. my $editcontent = $form->field('editcontent') || '';
  363. $editcontent =~ s/\r\n/\n/g;
  364. $editcontent =~ s/\r/\n/g;
  365. $editcontent =~ s/"/\\"/g;
  366. $content .= " content=\"\"\"\n$editcontent\n\"\"\"]]\n";
  367. # This is essentially a simplified version of editpage:
  368. # - the user does not control the page that's created, only the parent
  369. # - it's always a create operation, never an edit
  370. # - this means that conflicts should never happen
  371. # - this means that if they do, rocks fall and everyone dies
  372. if ($form->submitted eq PREVIEW) {
  373. my $preview = IkiWiki::htmlize($location, $page, '_comment',
  374. IkiWiki::linkify($location, $page,
  375. IkiWiki::preprocess($location, $page,
  376. IkiWiki::filter($location,
  377. $page, $content),
  378. 0, 1)));
  379. IkiWiki::run_hooks(format => sub {
  380. $preview = shift->(page => $page,
  381. content => $preview);
  382. });
  383. my $template = template("comment.tmpl");
  384. $template->param(content => $preview);
  385. $template->param(title => $form->field('subject'));
  386. $template->param(ctime => displaytime(time));
  387. IkiWiki::run_hooks(pagetemplate => sub {
  388. shift->(page => $location,
  389. destpage => $page,
  390. template => $template);
  391. });
  392. $form->tmpl_param(page_preview => $template->output);
  393. }
  394. else {
  395. $form->tmpl_param(page_preview => "");
  396. }
  397. if ($form->submitted eq POST_COMMENT && $form->validate) {
  398. IkiWiki::checksessionexpiry($cgi, $session);
  399. $postcomment=1;
  400. my $ok=IkiWiki::check_content(content => $form->field('editcontent'),
  401. subject => $form->field('subject'),
  402. $config{comments_allowauthor} ? (
  403. author => $form->field('author'),
  404. url => $form->field('url'),
  405. ) : (),
  406. page => $location,
  407. cgi => $cgi,
  408. session => $session,
  409. nonfatal => 1,
  410. );
  411. $postcomment=0;
  412. if (! $ok) {
  413. my $penddir=$config{wikistatedir}."/comments_pending";
  414. $location=unique_comment_location($page, $penddir);
  415. writefile("$location._comment", $penddir, $content);
  416. print IkiWiki::misctemplate(gettext(gettext("comment stored for moderation")),
  417. "<p>".
  418. gettext("Your comment will be posted after moderator review"),
  419. "</p>");
  420. exit;
  421. }
  422. # FIXME: could probably do some sort of graceful retry
  423. # on error? Would require significant unwinding though
  424. my $file = "$location._comment";
  425. writefile($file, $config{srcdir}, $content);
  426. my $conflict;
  427. if ($config{rcs} and $config{comments_commit}) {
  428. my $message = gettext("Added a comment");
  429. if (defined $form->field('subject') &&
  430. length $form->field('subject')) {
  431. $message = sprintf(
  432. gettext("Added a comment: %s"),
  433. $form->field('subject'));
  434. }
  435. IkiWiki::rcs_add($file);
  436. IkiWiki::disable_commit_hook();
  437. $conflict = IkiWiki::rcs_commit_staged($message,
  438. $session->param('name'), $ENV{REMOTE_ADDR});
  439. IkiWiki::enable_commit_hook();
  440. IkiWiki::rcs_update();
  441. }
  442. # Now we need a refresh
  443. require IkiWiki::Render;
  444. IkiWiki::refresh();
  445. IkiWiki::saveindex();
  446. # this should never happen, unless a committer deliberately
  447. # breaks it or something
  448. error($conflict) if defined $conflict;
  449. # Jump to the new comment on the page.
  450. # The trailing question mark tries to avoid broken
  451. # caches and get the most recent version of the page.
  452. IkiWiki::redirect($cgi, urlto($page, undef, 1)."?updated#$location");
  453. }
  454. else {
  455. IkiWiki::showform ($form, \@buttons, $session, $cgi,
  456. forcebaseurl => $baseurl);
  457. }
  458. exit;
  459. }
  460. sub commentsshown ($) {
  461. my $page=shift;
  462. return ! pagespec_match($page, "*/$config{comments_pagename}*",
  463. location => $page) &&
  464. pagespec_match($page, $config{comments_pagespec},
  465. location => $page);
  466. }
  467. sub commentsopen ($) {
  468. my $page = shift;
  469. return length $config{cgiurl} > 0 &&
  470. (! length $config{comments_closed_pagespec} ||
  471. ! pagespec_match($page, $config{comments_closed_pagespec},
  472. location => $page));
  473. }
  474. sub pagetemplate (@) {
  475. my %params = @_;
  476. my $page = $params{page};
  477. my $template = $params{template};
  478. my $shown = ($template->query(name => 'commentslink') ||
  479. $template->query(name => 'commentsurl') ||
  480. $template->query(name => 'atomcommentsurl') ||
  481. $template->query(name => 'comments')) &&
  482. commentsshown($page);
  483. if ($template->query(name => 'comments')) {
  484. my $comments = undef;
  485. if ($shown) {
  486. $comments = IkiWiki::preprocess_inline(
  487. pages => "internal($page/$config{comments_pagename}*)",
  488. template => 'comment',
  489. show => 0,
  490. reverse => 'yes',
  491. page => $page,
  492. destpage => $params{destpage},
  493. feedfile => 'comments',
  494. emptyfeeds => 'no',
  495. );
  496. }
  497. if (defined $comments && length $comments) {
  498. $template->param(comments => $comments);
  499. }
  500. if ($shown && commentsopen($page)) {
  501. my $addcommenturl = IkiWiki::cgiurl(do => 'comment',
  502. page => $page);
  503. $template->param(addcommenturl => $addcommenturl);
  504. }
  505. }
  506. if ($template->query(name => 'commentsurl')) {
  507. if ($shown) {
  508. $template->param(commentsurl =>
  509. urlto($page, undef, 1).'#comments');
  510. }
  511. }
  512. if ($template->query(name => 'atomcommentsurl') && $config{usedirs}) {
  513. if ($shown) {
  514. # This will 404 until there are some comments, but I
  515. # think that's probably OK...
  516. $template->param(atomcommentsurl =>
  517. urlto($page, undef, 1).'comments.atom');
  518. }
  519. }
  520. if ($template->query(name => 'commentslink')) {
  521. # XXX Would be nice to say how many comments there are in
  522. # the link. But, to update the number, blog pages
  523. # would have to update whenever comments of any inlines
  524. # page are added, which is not currently done.
  525. if ($shown) {
  526. $template->param(commentslink =>
  527. htmllink($page, $params{destpage}, $page,
  528. linktext => gettext("Comments"),
  529. anchor => "comments",
  530. noimageinline => 1));
  531. }
  532. }
  533. # everything below this point is only relevant to the comments
  534. # themselves
  535. if (!exists $commentstate{$page}) {
  536. return;
  537. }
  538. if ($template->query(name => 'commentuser')) {
  539. $template->param(commentuser =>
  540. $commentstate{$page}{commentuser});
  541. }
  542. if ($template->query(name => 'commentopenid')) {
  543. $template->param(commentopenid =>
  544. $commentstate{$page}{commentopenid});
  545. }
  546. if ($template->query(name => 'commentip')) {
  547. $template->param(commentip =>
  548. $commentstate{$page}{commentip});
  549. }
  550. if ($template->query(name => 'commentauthor')) {
  551. $template->param(commentauthor =>
  552. $commentstate{$page}{commentauthor});
  553. }
  554. if ($template->query(name => 'commentauthorurl')) {
  555. $template->param(commentauthorurl =>
  556. $commentstate{$page}{commentauthorurl});
  557. }
  558. if ($template->query(name => 'removeurl') &&
  559. IkiWiki::Plugin::remove->can("check_canremove") &&
  560. length $config{cgiurl}) {
  561. $template->param(removeurl => IkiWiki::cgiurl(do => 'remove',
  562. page => $page));
  563. $template->param(have_actions => 1);
  564. }
  565. }
  566. sub unique_comment_location ($) {
  567. my $page=shift;
  568. my $dir=shift;
  569. my $location;
  570. my $i = 0;
  571. do {
  572. $i++;
  573. $location = "$page/$config{comments_pagename}$i";
  574. } while (-e "$dir/$location._comment");
  575. return $location;
  576. }
  577. package IkiWiki::PageSpec;
  578. sub match_postcomment ($$;@) {
  579. my $page = shift;
  580. my $glob = shift;
  581. if (! $postcomment) {
  582. return IkiWiki::FailReason->new("not posting a comment");
  583. }
  584. return match_glob($page, $glob);
  585. }
  586. 1