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