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