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