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