summaryrefslogtreecommitdiff
path: root/IkiWiki/Plugin/comments.pm
blob: d34951570da77d1f9a423b874d362bd1b800aec8 (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. # here for backwards compatability with old comments
  22. hook(type => "preprocess", id => '_comment', call => \&preprocess);
  23. hook(type => "sessioncgi", id => 'comment', call => \&sessioncgi);
  24. hook(type => "htmlize", id => "_comment", call => \&htmlize);
  25. hook(type => "htmlize", id => "_comment_pending",
  26. call => \&htmlize_pending);
  27. hook(type => "pagetemplate", id => "comments", call => \&pagetemplate);
  28. hook(type => "formbuilder_setup", id => "comments",
  29. call => \&formbuilder_setup);
  30. # Load goto to fix up user page links for logged-in commenters
  31. IkiWiki::loadplugin("goto");
  32. IkiWiki::loadplugin("inline");
  33. }
  34. sub getsetup () {
  35. return
  36. plugin => {
  37. safe => 1,
  38. rebuild => 1,
  39. section => "web",
  40. },
  41. comments_pagespec => {
  42. type => 'pagespec',
  43. example => 'blog/* and !*/Discussion',
  44. description => 'PageSpec of pages where comments are allowed',
  45. link => 'ikiwiki/PageSpec',
  46. safe => 1,
  47. rebuild => 1,
  48. },
  49. comments_closed_pagespec => {
  50. type => 'pagespec',
  51. example => 'blog/controversial or blog/flamewar',
  52. description => 'PageSpec of pages where posting new comments is not allowed',
  53. link => 'ikiwiki/PageSpec',
  54. safe => 1,
  55. rebuild => 1,
  56. },
  57. comments_pagename => {
  58. type => 'string',
  59. default => 'comment_',
  60. description => 'Base name for comments, e.g. "comment_" for pages like "sandbox/comment_12"',
  61. safe => 0, # manual page moving required
  62. rebuild => undef,
  63. },
  64. comments_allowdirectives => {
  65. type => 'boolean',
  66. example => 0,
  67. description => 'Interpret directives in comments?',
  68. safe => 1,
  69. rebuild => 0,
  70. },
  71. comments_allowauthor => {
  72. type => 'boolean',
  73. example => 0,
  74. description => 'Allow anonymous commenters to set an author name?',
  75. safe => 1,
  76. rebuild => 0,
  77. },
  78. comments_commit => {
  79. type => 'boolean',
  80. example => 1,
  81. description => 'commit comments to the VCS',
  82. # old uncommitted comments are likely to cause
  83. # confusion if this is changed
  84. safe => 0,
  85. rebuild => 0,
  86. },
  87. }
  88. sub checkconfig () {
  89. $config{comments_commit} = 1
  90. unless defined $config{comments_commit};
  91. $config{comments_pagespec} = ''
  92. unless defined $config{comments_pagespec};
  93. $config{comments_closed_pagespec} = ''
  94. unless defined $config{comments_closed_pagespec};
  95. $config{comments_pagename} = 'comment_'
  96. unless defined $config{comments_pagename};
  97. }
  98. sub htmlize {
  99. my %params = @_;
  100. return $params{content};
  101. }
  102. sub htmlize_pending {
  103. my %params = @_;
  104. return sprintf(gettext("this comment needs %s"),
  105. '<a href="'.
  106. IkiWiki::cgiurl(do => "commentmoderation").'">'.
  107. gettext("moderation").'</a>');
  108. }
  109. # FIXME: copied verbatim from meta
  110. sub safeurl ($) {
  111. my $url=shift;
  112. if (exists $IkiWiki::Plugin::htmlscrubber::{safe_url_regexp} &&
  113. defined $IkiWiki::Plugin::htmlscrubber::safe_url_regexp) {
  114. return $url=~/$IkiWiki::Plugin::htmlscrubber::safe_url_regexp/;
  115. }
  116. else {
  117. return 1;
  118. }
  119. }
  120. sub preprocess {
  121. my %params = @_;
  122. 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));
  126. }
  127. my $content = $params{content};
  128. if (! defined $content) {
  129. error(gettext("comment must have content"));
  130. }
  131. $content =~ s/\\"/"/g;
  132. $content = IkiWiki::filter($page, $params{destpage}, $content);
  133. if ($config{comments_allowdirectives}) {
  134. $content = IkiWiki::preprocess($page, $params{destpage},
  135. $content);
  136. }
  137. # no need to bother with htmlize if it's just HTML
  138. $content = IkiWiki::htmlize($page, $params{destpage}, $format, $content)
  139. if defined $format;
  140. IkiWiki::run_hooks(sanitize => sub {
  141. $content = shift->(
  142. page => $page,
  143. destpage => $params{destpage},
  144. content => $content,
  145. );
  146. });
  147. # set metadata, possibly overriding [[!meta]] directives from the
  148. # comment itself
  149. my $commentuser;
  150. my $commentip;
  151. my $commentauthor;
  152. my $commentauthorurl;
  153. my $commentopenid;
  154. if (defined $params{username}) {
  155. $commentuser = $params{username};
  156. my $oiduser = eval { IkiWiki::openiduser($commentuser) };
  157. if (defined $oiduser) {
  158. # looks like an OpenID
  159. $commentauthorurl = $commentuser;
  160. $commentauthor = (defined $params{nickname} && length $params{nickname}) ? $params{nickname} : $oiduser;
  161. $commentopenid = $commentuser;
  162. }
  163. else {
  164. $commentauthorurl = IkiWiki::cgiurl(
  165. do => 'goto',
  166. page => IkiWiki::userpage($commentuser)
  167. );
  168. $commentauthor = $commentuser;
  169. }
  170. }
  171. else {
  172. if (defined $params{ip}) {
  173. $commentip = $params{ip};
  174. }
  175. $commentauthor = gettext("Anonymous");
  176. }
  177. $commentstate{$page}{commentuser} = $commentuser;
  178. $commentstate{$page}{commentopenid} = $commentopenid;
  179. $commentstate{$page}{commentip} = $commentip;
  180. $commentstate{$page}{commentauthor} = $commentauthor;
  181. $commentstate{$page}{commentauthorurl} = $commentauthorurl;
  182. if (! defined $pagestate{$page}{meta}{author}) {
  183. $pagestate{$page}{meta}{author} = $commentauthor;
  184. }
  185. if (! defined $pagestate{$page}{meta}{authorurl}) {
  186. $pagestate{$page}{meta}{authorurl} = $commentauthorurl;
  187. }
  188. if ($config{comments_allowauthor}) {
  189. if (defined $params{claimedauthor}) {
  190. $pagestate{$page}{meta}{author} = $params{claimedauthor};
  191. }
  192. if (defined $params{url}) {
  193. my $url=$params{url};
  194. eval q{use URI::Heuristic};
  195. if (! $@) {
  196. $url=URI::Heuristic::uf_uristr($url);
  197. }
  198. if (safeurl($url)) {
  199. $pagestate{$page}{meta}{authorurl} = $url;
  200. }
  201. }
  202. }
  203. else {
  204. $pagestate{$page}{meta}{author} = $commentauthor;
  205. $pagestate{$page}{meta}{authorurl} = $commentauthorurl;
  206. }
  207. if (defined $params{subject}) {
  208. # decode title the same way meta does
  209. eval q{use HTML::Entities};
  210. $pagestate{$page}{meta}{title} = decode_entities($params{subject});
  211. }
  212. if ($params{page} =~ m/\/\Q$config{comments_pagename}\E\d+_/) {
  213. $pagestate{$page}{meta}{permalink} = urlto(IkiWiki::dirname($params{page}), undef, 1).
  214. "#".page_to_id($params{page});
  215. }
  216. eval q{use Date::Parse};
  217. if (! $@) {
  218. my $time = str2time($params{date});
  219. $IkiWiki::pagectime{$page} = $time if defined $time;
  220. }
  221. return $content;
  222. }
  223. sub sessioncgi ($$) {
  224. my $cgi=shift;
  225. my $session=shift;
  226. my $do = $cgi->param('do');
  227. if ($do eq 'comment') {
  228. editcomment($cgi, $session);
  229. }
  230. elsif ($do eq 'commentmoderation') {
  231. commentmoderation($cgi, $session);
  232. }
  233. elsif ($do eq 'commentsignin') {
  234. IkiWiki::cgi_signin($cgi, $session);
  235. exit;
  236. }
  237. }
  238. # Mostly cargo-culted from IkiWiki::plugin::editpage
  239. sub editcomment ($$) {
  240. my $cgi=shift;
  241. my $session=shift;
  242. IkiWiki::decode_cgi_utf8($cgi);
  243. eval q{use CGI::FormBuilder};
  244. error($@) if $@;
  245. my @buttons = (POST_COMMENT, PREVIEW, CANCEL);
  246. my $form = CGI::FormBuilder->new(
  247. fields => [qw{do sid page subject editcontent type author url}],
  248. charset => 'utf-8',
  249. method => 'POST',
  250. required => [qw{editcontent}],
  251. javascript => 0,
  252. params => $cgi,
  253. action => $config{cgiurl},
  254. header => 0,
  255. table => 0,
  256. template => { template('editcomment.tmpl') },
  257. );
  258. IkiWiki::decode_form_utf8($form);
  259. IkiWiki::run_hooks(formbuilder_setup => sub {
  260. shift->(title => "comment", form => $form, cgi => $cgi,
  261. session => $session, buttons => \@buttons);
  262. });
  263. IkiWiki::decode_form_utf8($form);
  264. my $type = $form->param('type');
  265. if (defined $type && length $type && $IkiWiki::hooks{htmlize}{$type}) {
  266. $type = IkiWiki::possibly_foolish_untaint($type);
  267. }
  268. else {
  269. $type = $config{default_pageext};
  270. }
  271. my @page_types;
  272. if (exists $IkiWiki::hooks{htmlize}) {
  273. foreach my $key (grep { !/^_/ } keys %{$IkiWiki::hooks{htmlize}}) {
  274. push @page_types, [$key, $IkiWiki::hooks{htmlize}{$key}{longname} || $key];
  275. }
  276. }
  277. @page_types=sort @page_types;
  278. $form->field(name => 'do', type => 'hidden');
  279. $form->field(name => 'sid', type => 'hidden', value => $session->id,
  280. force => 1);
  281. $form->field(name => 'page', type => 'hidden');
  282. $form->field(name => 'subject', type => 'text', size => 72);
  283. $form->field(name => 'editcontent', type => 'textarea', rows => 10);
  284. $form->field(name => "type", value => $type, force => 1,
  285. type => 'select', options => \@page_types);
  286. $form->tmpl_param(username => $session->param('name'));
  287. if ($config{comments_allowauthor} and
  288. ! defined $session->param('name')) {
  289. $form->tmpl_param(allowauthor => 1);
  290. $form->field(name => 'author', type => 'text', size => '40');
  291. $form->field(name => 'url', type => 'text', size => '40');
  292. }
  293. else {
  294. $form->tmpl_param(allowauthor => 0);
  295. $form->field(name => 'author', type => 'hidden', value => '',
  296. force => 1);
  297. $form->field(name => 'url', type => 'hidden', value => '',
  298. force => 1);
  299. }
  300. if (! defined $session->param('name')) {
  301. # Make signinurl work and return here.
  302. $form->tmpl_param(signinurl => IkiWiki::cgiurl(do => 'commentsignin'));
  303. $session->param(postsignin => $ENV{QUERY_STRING});
  304. IkiWiki::cgi_savesession($session);
  305. }
  306. # The untaint is OK (as in editpage) because we're about to pass
  307. # it to file_pruned anyway
  308. my $page = $form->field('page');
  309. $page = IkiWiki::possibly_foolish_untaint($page);
  310. if (! defined $page || ! length $page ||
  311. IkiWiki::file_pruned($page)) {
  312. error(gettext("bad page name"));
  313. }
  314. my $baseurl = urlto($page, undef, 1);
  315. $form->title(sprintf(gettext("commenting on %s"),
  316. IkiWiki::pagetitle($page)));
  317. $form->tmpl_param('helponformattinglink',
  318. htmllink($page, $page, 'ikiwiki/formatting',
  319. noimageinline => 1,
  320. linktext => 'FormattingHelp'),
  321. allowdirectives => $config{allow_directives});
  322. if ($form->submitted eq CANCEL) {
  323. # bounce back to the page they wanted to comment on, and exit.
  324. # CANCEL need not be considered in future
  325. IkiWiki::redirect($cgi, urlto($page, undef, 1));
  326. exit;
  327. }
  328. if (not exists $pagesources{$page}) {
  329. error(sprintf(gettext(
  330. "page '%s' doesn't exist, so you can't comment"),
  331. $page));
  332. }
  333. if (pagespec_match($page, $config{comments_closed_pagespec},
  334. location => $page)) {
  335. error(sprintf(gettext(
  336. "comments on page '%s' are closed"),
  337. $page));
  338. }
  339. # Set a flag to indicate that we're posting a comment,
  340. # so that postcomment() can tell it should match.
  341. $postcomment=1;
  342. IkiWiki::check_canedit($page, $cgi, $session);
  343. $postcomment=0;
  344. my $content = "[[!comment format=$type\n";
  345. if (defined $session->param('name')) {
  346. my $username = $session->param('name');
  347. $username =~ s/"/&quot;/g;
  348. $content .= " username=\"$username\"\n";
  349. }
  350. if (defined $session->param('nickname')) {
  351. my $nickname = $session->param('nickname');
  352. $nickname =~ s/"/&quot;/g;
  353. $content .= " nickname=\"$nickname\"\n";
  354. }
  355. elsif (defined $session->remote_addr()) {
  356. my $ip = $session->remote_addr();
  357. if ($ip =~ m/^([.0-9]+)$/) {
  358. $content .= " ip=\"$1\"\n";
  359. }
  360. }
  361. if ($config{comments_allowauthor}) {
  362. my $author = $form->field('author');
  363. if (defined $author && length $author) {
  364. $author =~ s/"/&quot;/g;
  365. $content .= " claimedauthor=\"$author\"\n";
  366. }
  367. my $url = $form->field('url');
  368. if (defined $url && length $url) {
  369. $url =~ s/"/&quot;/g;
  370. $content .= " url=\"$url\"\n";
  371. }
  372. }
  373. my $subject = $form->field('subject');
  374. if (defined $subject && length $subject) {
  375. $subject =~ s/"/&quot;/g;
  376. }
  377. else {
  378. $subject = "comment ".(num_comments($page, $config{srcdir}) + 1);
  379. }
  380. $content .= " subject=\"$subject\"\n";
  381. $content .= " date=\"" . decode_utf8(strftime('%Y-%m-%dT%H:%M:%SZ', gmtime)) . "\"\n";
  382. my $editcontent = $form->field('editcontent');
  383. $editcontent="" if ! defined $editcontent;
  384. $editcontent =~ s/\r\n/\n/g;
  385. $editcontent =~ s/\r/\n/g;
  386. $editcontent =~ s/"/\\"/g;
  387. $content .= " content=\"\"\"\n$editcontent\n\"\"\"]]\n";
  388. my $location=unique_comment_location($page, $content, $config{srcdir});
  389. # This is essentially a simplified version of editpage:
  390. # - the user does not control the page that's created, only the parent
  391. # - it's always a create operation, never an edit
  392. # - this means that conflicts should never happen
  393. # - this means that if they do, rocks fall and everyone dies
  394. if ($form->submitted eq PREVIEW) {
  395. my $preview=previewcomment($content, $location, $page, time);
  396. IkiWiki::run_hooks(format => sub {
  397. $preview = shift->(page => $page,
  398. content => $preview);
  399. });
  400. $form->tmpl_param(page_preview => $preview);
  401. }
  402. else {
  403. $form->tmpl_param(page_preview => "");
  404. }
  405. if ($form->submitted eq POST_COMMENT && $form->validate) {
  406. IkiWiki::checksessionexpiry($cgi, $session);
  407. $postcomment=1;
  408. my $ok=IkiWiki::check_content(content => $form->field('editcontent'),
  409. subject => $form->field('subject'),
  410. $config{comments_allowauthor} ? (
  411. author => $form->field('author'),
  412. url => $form->field('url'),
  413. ) : (),
  414. page => $location,
  415. cgi => $cgi,
  416. session => $session,
  417. nonfatal => 1,
  418. );
  419. $postcomment=0;
  420. if (! $ok) {
  421. $location=unique_comment_location($page, $content, $config{srcdir}, "._comment_pending");
  422. writefile("$location._comment_pending", $config{srcdir}, $content);
  423. # Refresh so anything that deals with pending
  424. # comments can be updated.
  425. require IkiWiki::Render;
  426. IkiWiki::refresh();
  427. IkiWiki::saveindex();
  428. IkiWiki::printheader($session);
  429. print IkiWiki::misctemplate(gettext(gettext("comment stored for moderation")),
  430. "<p>".
  431. gettext("Your comment will be posted after moderator review").
  432. "</p>");
  433. exit;
  434. }
  435. # FIXME: could probably do some sort of graceful retry
  436. # on error? Would require significant unwinding though
  437. my $file = "$location._comment";
  438. writefile($file, $config{srcdir}, $content);
  439. my $conflict;
  440. if ($config{rcs} and $config{comments_commit}) {
  441. my $message = gettext("Added a comment");
  442. if (defined $form->field('subject') &&
  443. length $form->field('subject')) {
  444. $message = sprintf(
  445. gettext("Added a comment: %s"),
  446. $form->field('subject'));
  447. }
  448. IkiWiki::rcs_add($file);
  449. IkiWiki::disable_commit_hook();
  450. $conflict = IkiWiki::rcs_commit_staged(
  451. message => $message,
  452. session => $session,
  453. );
  454. IkiWiki::enable_commit_hook();
  455. IkiWiki::rcs_update();
  456. }
  457. # Now we need a refresh
  458. require IkiWiki::Render;
  459. IkiWiki::refresh();
  460. IkiWiki::saveindex();
  461. # this should never happen, unless a committer deliberately
  462. # breaks it or something
  463. error($conflict) if defined $conflict;
  464. # Jump to the new comment on the page.
  465. # The trailing question mark tries to avoid broken
  466. # caches and get the most recent version of the page.
  467. IkiWiki::redirect($cgi, urlto($page, undef, 1).
  468. "?updated#".page_to_id($location));
  469. }
  470. else {
  471. IkiWiki::showform ($form, \@buttons, $session, $cgi,
  472. forcebaseurl => $baseurl, page => $page);
  473. }
  474. exit;
  475. }
  476. sub commentmoderation ($$) {
  477. my $cgi=shift;
  478. my $session=shift;
  479. IkiWiki::needsignin($cgi, $session);
  480. if (! IkiWiki::is_admin($session->param("name"))) {
  481. error(gettext("you are not logged in as an admin"));
  482. }
  483. IkiWiki::decode_cgi_utf8($cgi);
  484. if (defined $cgi->param('sid')) {
  485. IkiWiki::checksessionexpiry($cgi, $session);
  486. my $rejectalldefer=$cgi->param('rejectalldefer');
  487. my %vars=$cgi->Vars;
  488. my $added=0;
  489. foreach my $id (keys %vars) {
  490. if ($id =~ /(.*)\._comment(?:_pending)?$/) {
  491. my $action=$cgi->param($id);
  492. next if $action eq 'Defer' && ! $rejectalldefer;
  493. # Make sure that the id is of a legal
  494. # pending comment.
  495. my ($f) = $id =~ /$config{wiki_file_regexp}/;
  496. if (! defined $f || ! length $f ||
  497. IkiWiki::file_pruned($f)) {
  498. error("illegal file");
  499. }
  500. my $page=IkiWiki::dirname($f);
  501. my $file="$config{srcdir}/$f";
  502. if (! -e $file) {
  503. # old location
  504. $file="$config{wikistatedir}/comments_pending/".$f;
  505. }
  506. if ($action eq 'Accept') {
  507. my $content=eval { readfile($file) };
  508. next if $@; # file vanished since form was displayed
  509. my $dest=unique_comment_location($page, $content, $config{srcdir})."._comment";
  510. writefile($dest, $config{srcdir}, $content);
  511. if ($config{rcs} and $config{comments_commit}) {
  512. IkiWiki::rcs_add($dest);
  513. }
  514. $added++;
  515. }
  516. require IkiWiki::Render;
  517. IkiWiki::prune($file);
  518. }
  519. }
  520. if ($added) {
  521. my $conflict;
  522. if ($config{rcs} and $config{comments_commit}) {
  523. my $message = gettext("Comment moderation");
  524. IkiWiki::disable_commit_hook();
  525. $conflict=IkiWiki::rcs_commit_staged(
  526. message => $message,
  527. session => $session,
  528. );
  529. IkiWiki::enable_commit_hook();
  530. IkiWiki::rcs_update();
  531. }
  532. # Now we need a refresh
  533. require IkiWiki::Render;
  534. IkiWiki::refresh();
  535. IkiWiki::saveindex();
  536. error($conflict) if defined $conflict;
  537. }
  538. }
  539. my @comments=map {
  540. my ($id, $dir, $ctime)=@{$_};
  541. my $content=readfile("$dir/$id");
  542. my $preview=previewcomment($content, $id,
  543. $id, $ctime);
  544. {
  545. id => $id,
  546. view => $preview,
  547. }
  548. } sort { $b->[2] <=> $a->[2] } comments_pending();
  549. my $template=template("commentmoderation.tmpl");
  550. $template->param(
  551. sid => $session->id,
  552. comments => \@comments,
  553. );
  554. IkiWiki::printheader($session);
  555. my $out=$template->output;
  556. IkiWiki::run_hooks(format => sub {
  557. $out = shift->(page => "", content => $out);
  558. });
  559. print IkiWiki::misctemplate(gettext("comment moderation"), $out);
  560. exit;
  561. }
  562. sub formbuilder_setup (@) {
  563. my %params=@_;
  564. my $form=$params{form};
  565. if ($form->title eq "preferences" &&
  566. IkiWiki::is_admin($params{session}->param("name"))) {
  567. push @{$params{buttons}}, "Comment Moderation";
  568. if ($form->submitted && $form->submitted eq "Comment Moderation") {
  569. commentmoderation($params{cgi}, $params{session});
  570. }
  571. }
  572. }
  573. sub comments_pending () {
  574. my @ret;
  575. eval q{use File::Find};
  576. error($@) if $@;
  577. eval q{use Cwd};
  578. error($@) if $@;
  579. my $origdir=getcwd();
  580. my $find_comments=sub {
  581. my $dir=shift;
  582. my $extension=shift;
  583. return unless -d $dir;
  584. chdir($dir) || die "chdir $dir: $!";
  585. find({
  586. no_chdir => 1,
  587. wanted => sub {
  588. my $file=decode_utf8($_);
  589. $file=~s/^\.\///;
  590. return if ! length $file || IkiWiki::file_pruned($file)
  591. || -l $_ || -d _ || $file !~ /\Q$extension\E$/;
  592. my ($f) = $file =~ /$config{wiki_file_regexp}/; # untaint
  593. if (defined $f) {
  594. my $ctime=(stat($_))[10];
  595. push @ret, [$f, $dir, $ctime];
  596. }
  597. }
  598. }, ".");
  599. chdir($origdir) || die "chdir $origdir: $!";
  600. };
  601. $find_comments->($config{srcdir}, "._comment_pending");
  602. # old location
  603. $find_comments->("$config{wikistatedir}/comments_pending/",
  604. "._comment");
  605. return @ret;
  606. }
  607. sub previewcomment ($$$) {
  608. my $content=shift;
  609. my $location=shift;
  610. my $page=shift;
  611. my $time=shift;
  612. my $preview = IkiWiki::htmlize($location, $page, '_comment',
  613. IkiWiki::linkify($location, $page,
  614. IkiWiki::preprocess($location, $page,
  615. IkiWiki::filter($location, $page, $content), 0, 1)));
  616. my $template = template("comment.tmpl");
  617. $template->param(content => $preview);
  618. $template->param(ctime => displaytime($time, undef, 1));
  619. $template->param(html5 => $config{html5});
  620. IkiWiki::run_hooks(pagetemplate => sub {
  621. shift->(page => $location,
  622. destpage => $page,
  623. template => $template);
  624. });
  625. $template->param(have_actions => 0);
  626. return $template->output;
  627. }
  628. sub commentsshown ($) {
  629. my $page=shift;
  630. return ! pagespec_match($page, "comment(*)",
  631. location => $page) &&
  632. pagespec_match($page, $config{comments_pagespec},
  633. location => $page);
  634. }
  635. sub commentsopen ($) {
  636. my $page = shift;
  637. return length $config{cgiurl} > 0 &&
  638. (! length $config{comments_closed_pagespec} ||
  639. ! pagespec_match($page, $config{comments_closed_pagespec},
  640. location => $page));
  641. }
  642. sub pagetemplate (@) {
  643. my %params = @_;
  644. my $page = $params{page};
  645. my $template = $params{template};
  646. my $shown = ($template->query(name => 'commentslink') ||
  647. $template->query(name => 'commentsurl') ||
  648. $template->query(name => 'atomcommentsurl') ||
  649. $template->query(name => 'comments')) &&
  650. commentsshown($page);
  651. if ($template->query(name => 'comments')) {
  652. my $comments = undef;
  653. if ($shown) {
  654. $comments = IkiWiki::preprocess_inline(
  655. pages => "comment($page)",
  656. template => 'comment',
  657. show => 0,
  658. reverse => 'yes',
  659. page => $page,
  660. destpage => $params{destpage},
  661. feedfile => 'comments',
  662. emptyfeeds => 'no',
  663. );
  664. }
  665. if (defined $comments && length $comments) {
  666. $template->param(comments => $comments);
  667. }
  668. if ($shown && commentsopen($page)) {
  669. $template->param(addcommenturl => addcommenturl($page));
  670. }
  671. }
  672. if ($shown) {
  673. if ($template->query(name => 'commentsurl')) {
  674. $template->param(commentsurl =>
  675. urlto($page, undef, 1).'#comments');
  676. }
  677. if ($template->query(name => 'atomcommentsurl') && $config{usedirs}) {
  678. # This will 404 until there are some comments, but I
  679. # think that's probably OK...
  680. $template->param(atomcommentsurl =>
  681. urlto($page, undef, 1).'comments.atom');
  682. }
  683. if ($template->query(name => 'commentslink')) {
  684. my $num=num_comments($page, $config{srcdir});
  685. my $link;
  686. if ($num > 0) {
  687. $link = htmllink($page, $params{destpage}, $page,
  688. linktext => sprintf(ngettext("%i comment", "%i comments", $num), $num),
  689. anchor => "comments",
  690. noimageinline => 1
  691. );
  692. }
  693. elsif (commentsopen($page)) {
  694. $link = "<a href=\"".addcommenturl($page)."\">".
  695. #translators: Here "Comment" is a verb;
  696. #translators: the user clicks on it to
  697. #translators: post a comment.
  698. gettext("Comment").
  699. "</a>";
  700. }
  701. $template->param(commentslink => $link)
  702. if defined $link;
  703. }
  704. }
  705. # everything below this point is only relevant to the comments
  706. # themselves
  707. if (!exists $commentstate{$page}) {
  708. return;
  709. }
  710. if ($template->query(name => 'commentid')) {
  711. $template->param(commentid => page_to_id($page));
  712. }
  713. if ($template->query(name => 'commentuser')) {
  714. $template->param(commentuser =>
  715. $commentstate{$page}{commentuser});
  716. }
  717. if ($template->query(name => 'commentopenid')) {
  718. $template->param(commentopenid =>
  719. $commentstate{$page}{commentopenid});
  720. }
  721. if ($template->query(name => 'commentip')) {
  722. $template->param(commentip =>
  723. $commentstate{$page}{commentip});
  724. }
  725. if ($template->query(name => 'commentauthor')) {
  726. $template->param(commentauthor =>
  727. $commentstate{$page}{commentauthor});
  728. }
  729. if ($template->query(name => 'commentauthorurl')) {
  730. $template->param(commentauthorurl =>
  731. $commentstate{$page}{commentauthorurl});
  732. }
  733. if ($template->query(name => 'removeurl') &&
  734. IkiWiki::Plugin::remove->can("check_canremove") &&
  735. length $config{cgiurl}) {
  736. $template->param(removeurl => IkiWiki::cgiurl(do => 'remove',
  737. page => $page));
  738. $template->param(have_actions => 1);
  739. }
  740. }
  741. sub addcommenturl ($) {
  742. my $page=shift;
  743. return IkiWiki::cgiurl(do => 'comment', page => $page);
  744. }
  745. sub num_comments ($$) {
  746. my $page=shift;
  747. my $dir=shift;
  748. my @comments=glob("$dir/$page/$config{comments_pagename}*._comment");
  749. return int @comments;
  750. }
  751. sub unique_comment_location ($$$$) {
  752. my $page=shift;
  753. eval q{use Digest::MD5 'md5_hex'};
  754. error($@) if $@;
  755. my $content_md5=md5_hex(Encode::encode_utf8(shift));
  756. my $dir=shift;
  757. my $ext=shift || "._comment";
  758. my $location;
  759. my $i = num_comments($page, $dir);
  760. do {
  761. $i++;
  762. $location = "$page/$config{comments_pagename}${i}_${content_md5}";
  763. } while (-e "$dir/$location$ext");
  764. return $location;
  765. }
  766. sub page_to_id ($) {
  767. # Converts a comment page name into a unique, legal html id
  768. # attribute value, that can be used as an anchor to link to the
  769. # comment.
  770. my $page=shift;
  771. eval q{use Digest::MD5 'md5_hex'};
  772. error($@) if $@;
  773. return "comment-".md5_hex(Encode::encode_utf8(($page)));
  774. }
  775. package IkiWiki::PageSpec;
  776. sub match_postcomment ($$;@) {
  777. my $page = shift;
  778. my $glob = shift;
  779. if (! $postcomment) {
  780. return IkiWiki::FailReason->new("not posting a comment");
  781. }
  782. return match_glob($page, $glob, @_);
  783. }
  784. sub match_comment ($$;@) {
  785. my $page = shift;
  786. my $glob = shift;
  787. # To see if it's a comment, check the source file type.
  788. # Deal with comments that were just deleted.
  789. my $source=exists $IkiWiki::pagesources{$page} ?
  790. $IkiWiki::pagesources{$page} :
  791. $IkiWiki::delpagesources{$page};
  792. my $type=defined $source ? IkiWiki::pagetype($source) : undef;
  793. if (! defined $type || $type ne "_comment") {
  794. return IkiWiki::FailReason->new("$page is not a comment");
  795. }
  796. return match_glob($page, "$glob/*", internal => 1, @_);
  797. }
  798. sub match_comment_pending ($$;@) {
  799. my $page = shift;
  800. my $glob = shift;
  801. my $source=exists $IkiWiki::pagesources{$page} ?
  802. $IkiWiki::pagesources{$page} :
  803. $IkiWiki::delpagesources{$page};
  804. my $type=defined $source ? IkiWiki::pagetype($source) : undef;
  805. if (! defined $type || $type ne "_comment_pending") {
  806. return IkiWiki::FailReason->new("$page is not a pending comment");
  807. }
  808. return match_glob($page, "$glob/*", internal => 1, @_);
  809. }
  810. 1