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