comments: Use a checkconfig hook to get the default value of comments_pagename
[ikiwiki] / 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
12 use constant PREVIEW => "Preview";
13 use constant POST_COMMENT => "Post comment";
14 use constant CANCEL => "Cancel";
15
16 sub import { #{{{
17         hook(type => "checkconfig", id => 'comments',  call => \&checkconfig);
18         hook(type => "getsetup", id => 'comments',  call => \&getsetup);
19         hook(type => "preprocess", id => 'comments', call => \&preprocess);
20         hook(type => "sessioncgi", id => 'comment', call => \&sessioncgi);
21         hook(type => "htmlize", id => "_comment", call => \&htmlize);
22         hook(type => "pagetemplate", id => "comments", call => \&pagetemplate);
23         IkiWiki::loadplugin("inline");
24         IkiWiki::loadplugin("mdwn");
25 } # }}}
26
27 sub htmlize { # {{{
28         eval q{use IkiWiki::Plugin::mdwn};
29         error($@) if ($@);
30         return IkiWiki::Plugin::mdwn::htmlize(@_)
31 } # }}}
32
33 sub getsetup () { #{{{
34         return
35                 plugin => {
36                         safe => 1,
37                         rebuild => 1,
38                 },
39                 # Pages where comments are shown, but new comments are not
40                 # allowed, will show "Comments are closed".
41                 comments_shown_pagespec => {
42                         type => 'pagespec',
43                         example => 'blog/*',
44                         default => '',
45                         description => 'PageSpec for pages where comments will be shown inline',
46                         link => 'ikiwiki/PageSpec',
47                         safe => 1,
48                         rebuild => 1,
49                 },
50                 comments_open_pagespec => {
51                         type => 'pagespec',
52                         example => 'blog/* and created_after(close_old_comments)',
53                         default => '',
54                         description => 'PageSpec for pages where new comments can be posted',
55                         link => 'ikiwiki/PageSpec',
56                         safe => 1,
57                         rebuild => 1,
58                 },
59                 comments_pagename => {
60                         type => 'string',
61                         example => 'comment_',
62                         default => 'comment_',
63                         description => 'Base name for comments, e.g. "comment_" for pages like "sandbox/comment_12"',
64                         safe => 0, # manual page moving will required
65                         rebuild => undef,
66                 },
67                 comments_allowdirectives => {
68                         type => 'boolean',
69                         default => 0,
70                         example => 0,
71                         description => 'Allow directives in newly posted comments?',
72                         safe => 1,
73                         rebuild => 0,
74                 },
75                 comments_commit => {
76                         type => 'boolean',
77                         example => 1,
78                         default => 1,
79                         description => 'commit comments to the VCS',
80                         # old uncommitted comments are likely to cause
81                         # confusion if this is changed
82                         safe => 0,
83                         rebuild => 0,
84                 },
85 } #}}}
86
87 sub checkconfig () { #{{{
88         $config{comments_commit} = 1 unless defined $config{comments_commit};
89         $config{comments_pagename} = 'comment_'
90                 unless defined $config{comments_pagename};
91 } #}}}
92
93 # Somewhat based on IkiWiki::Plugin::inline blog posting support
94 sub preprocess (@) { #{{{
95         my %params=@_;
96
97         return "";
98
99         my $page = $params{page};
100         $pagestate{$page}{comments}{comments} = defined $params{closed}
101                 ? (not IkiWiki::yesno($params{closed}))
102                 : 1;
103         $pagestate{$page}{comments}{allowdirectives} = IkiWiki::yesno($params{allowdirectives});
104         $pagestate{$page}{comments}{commit} = defined $params{commit}
105                 ? IkiWiki::yesno($params{commit})
106                 : 1;
107
108         my $formtemplate = IkiWiki::template("comments_embed.tmpl",
109                 blind_cache => 1);
110         $formtemplate->param(cgiurl => $config{cgiurl});
111         $formtemplate->param(page => $params{page});
112
113         if (not $pagestate{$page}{comments}{comments}) {
114                 $formtemplate->param("disabled" =>
115                         gettext('comments are closed'));
116         }
117         elsif ($params{preview}) {
118                 $formtemplate->param("disabled" =>
119                         gettext('not available during Preview'));
120         }
121
122         debug("page $params{page} => destpage $params{destpage}");
123
124         unless (defined $params{inline} && !IkiWiki::yesno($params{inline})) {
125                 my $posts = '';
126                 eval q{use IkiWiki::Plugin::inline};
127                 error($@) if ($@);
128                 my @args = (
129                         pages => "internal($params{page}/_comment_*)",
130                         template => "comments_display",
131                         show => 0,
132                         reverse => "yes",
133                         # special stuff passed through
134                         page => $params{page},
135                         destpage => $params{destpage},
136                         preview => $params{preview},
137                 );
138                 push @args, atom => $params{atom} if defined $params{atom};
139                 push @args, rss => $params{rss} if defined $params{rss};
140                 push @args, feeds => $params{feeds} if defined $params{feeds};
141                 push @args, feedshow => $params{feedshow} if defined $params{feedshow};
142                 push @args, timeformat => $params{timeformat} if defined $params{timeformat};
143                 push @args, feedonly => $params{feedonly} if defined $params{feedonly};
144                 $posts = IkiWiki::preprocess_inline(@args);
145                 $formtemplate->param("comments" => $posts);
146         }
147
148         return $formtemplate->output;
149 } # }}}
150
151 # FIXME: logic taken from editpage, should be common code?
152 sub getcgiuser ($) { # {{{
153         my $session = shift;
154         my $user = $session->param('name');
155         $user = $ENV{REMOTE_ADDR} unless defined $user;
156         debug("getcgiuser() -> $user");
157         return $user;
158 } # }}}
159
160 # FIXME: logic adapted from recentchanges, should be common code?
161 # returns (author URL, pretty-printed version)
162 sub linkuser ($) { # {{{
163         my $user = shift;
164         my $oiduser = eval { IkiWiki::openiduser($user) };
165
166         if (defined $oiduser) {
167                 return ($user, $oiduser);
168         }
169         else {
170                 my $page = bestlink('', (length $config{userdir}
171                                 ? "$config{userdir}/"
172                                 : "").$user);
173                 return (urlto($page, undef, 1), $user);
174         }
175 } # }}}
176
177 # Mostly cargo-culted from IkiWiki::plugin::editpage
178 sub sessioncgi ($$) { #{{{
179         my $cgi=shift;
180         my $session=shift;
181
182         my $do = $cgi->param('do');
183         return unless $do eq 'comment';
184
185         IkiWiki::decode_cgi_utf8($cgi);
186
187         eval q{use CGI::FormBuilder};
188         error($@) if $@;
189
190         my @buttons = (POST_COMMENT, PREVIEW, CANCEL);
191         my $form = CGI::FormBuilder->new(
192                 fields => [qw{do sid page subject body}],
193                 charset => 'utf-8',
194                 method => 'POST',
195                 required => [qw{body}],
196                 javascript => 0,
197                 params => $cgi,
198                 action => $config{cgiurl},
199                 header => 0,
200                 table => 0,
201                 template => scalar IkiWiki::template_params('comments_form.tmpl'),
202                 # wtf does this do in editpage?
203                 wikiname => $config{wikiname},
204         );
205
206         IkiWiki::decode_form_utf8($form);
207         IkiWiki::run_hooks(formbuilder_setup => sub {
208                         shift->(title => "comment", form => $form, cgi => $cgi,
209                                 session => $session, buttons => \@buttons);
210                 });
211         IkiWiki::decode_form_utf8($form);
212
213         $form->field(name => 'do', type => 'hidden');
214         $form->field(name => 'sid', type => 'hidden', value => $session->id,
215                 force => 1);
216         $form->field(name => 'page', type => 'hidden');
217         $form->field(name => 'subject', type => 'text', size => 72);
218         $form->field(name => 'body', type => 'textarea', rows => 5,
219                 cols => 80);
220
221         # The untaint is OK (as in editpage) because we're about to pass
222         # it to file_pruned anyway
223         my $page = $form->field('page');
224         $page = IkiWiki::possibly_foolish_untaint($page);
225         if (!defined $page || !length $page ||
226                 IkiWiki::file_pruned($page, $config{srcdir})) {
227                 error(gettext("bad page name"));
228         }
229
230         my $allow_directives = $config{comments_allowdirectives};
231         my $commit_comments = $config{comments_commit};
232         my $comments_pagename = $config{comments_pagename};
233
234         # FIXME: is this right? Or should we be using the candidate subpage
235         # (whatever that might mean) as the base URL?
236         my $baseurl = urlto($page, undef, 1);
237
238         $form->title(sprintf(gettext("commenting on %s"),
239                         IkiWiki::pagetitle($page)));
240
241         $form->tmpl_param('helponformattinglink',
242                 htmllink($page, $page, 'ikiwiki/formatting',
243                         noimageinline => 1,
244                         linktext => 'FormattingHelp'),
245                         allowdirectives => $allow_directives);
246
247         if ($form->submitted eq CANCEL) {
248                 # bounce back to the page they wanted to comment on, and exit.
249                 # CANCEL need not be considered in future
250                 IkiWiki::redirect($cgi, urlto($page, undef, 1));
251                 exit;
252         }
253
254         if (not exists $pagesources{$page}) {
255                 error(sprintf(gettext(
256                         "page '%s' doesn't exist, so you can't comment"),
257                         $page));
258         }
259
260         if (not pagespec_match($page, $config{comments_open_pagespec},
261                 location => $page)) {
262                 error(sprintf(gettext(
263                         "comments on page '%s' are closed"),
264                         $page));
265         }
266
267         IkiWiki::checksessionexpiry($session, $cgi->param('sid'));
268         IkiWiki::check_canedit($page . "[postcomment]", $cgi, $session);
269
270         my ($authorurl, $author) = linkuser(getcgiuser($session));
271
272         my $body = $form->field('body') || '';
273         $body =~ s/\r\n/\n/g;
274         $body =~ s/\r/\n/g;
275         $body .= "\n" if $body !~ /\n$/;
276
277         unless ($allow_directives) {
278                 # don't allow new-style directives at all
279                 $body =~ s/(^|[^\\])\[\[!/$1&#91;&#91;!/g;
280
281                 # don't allow [[ unless it begins an old-style
282                 # wikilink, if prefix_directives is off
283                 $body =~ s/(^|[^\\])\[\[(?![^\n\s\]+]\]\])/$1&#91;&#91;!/g
284                         unless $config{prefix_directives};
285         }
286
287         # FIXME: check that the wiki is locked right now, because
288         # if it's not, there are mad race conditions!
289
290         # FIXME: rather a simplistic way to make the comments...
291         my $i = 0;
292         my $file;
293         my $location;
294         do {
295                 $i++;
296                 $location = "$page/${comments_pagename}${i}";
297         } while (-e "$config{srcdir}/$location._comment");
298
299         my $anchor = "${comments_pagename}${i}";
300
301         IkiWiki::run_hooks(sanitize => sub {
302                 $body=shift->(
303                         page => $location,
304                         destpage => $location,
305                         content => $body,
306                 );
307         });
308
309         # In this template, the [[!meta]] directives should stay at the end,
310         # so that they will override anything the user specifies. (For
311         # instance, [[!meta author="I can fake the author"]]...)
312         my $content_tmpl = template('comments_comment.tmpl');
313         $content_tmpl->param(author => $author);
314         $content_tmpl->param(authorurl => $authorurl);
315         $content_tmpl->param(subject => $form->field('subject'));
316         $content_tmpl->param(body => $body);
317         $content_tmpl->param(anchor => "$anchor");
318         $content_tmpl->param(permalink => "$baseurl#$anchor");
319
320         my $content = $content_tmpl->output;
321
322         # This is essentially a simplified version of editpage:
323         # - the user does not control the page that's created, only the parent
324         # - it's always a create operation, never an edit
325         # - this means that conflicts should never happen
326         # - this means that if they do, rocks fall and everyone dies
327
328         if ($form->submitted eq PREVIEW) {
329                 my $preview = IkiWiki::htmlize($location, $page, 'mdwn',
330                                 IkiWiki::linkify($page, $page,
331                                         IkiWiki::preprocess($page, $page,
332                                                 IkiWiki::filter($location,
333                                                         $page, $content),
334                                                 0, 1)));
335                 IkiWiki::run_hooks(format => sub {
336                                 $preview = shift->(page => $page,
337                                         content => $preview);
338                         });
339
340                 my $template = template("comments_display.tmpl");
341                 $template->param(content => $preview);
342                 $template->param(title => $form->field('subject'));
343                 $template->param(ctime => displaytime(time));
344                 $template->param(author => $author);
345                 $template->param(authorurl => $authorurl);
346
347                 $form->tmpl_param(page_preview => $template->output);
348         }
349         else {
350                 $form->tmpl_param(page_preview => "");
351         }
352
353         if ($form->submitted eq POST_COMMENT && $form->validate) {
354                 my $file = "$location._comment";
355
356                 # FIXME: could probably do some sort of graceful retry
357                 # on error? Would require significant unwinding though
358                 writefile($file, $config{srcdir}, $content);
359
360                 my $conflict;
361
362                 if ($config{rcs} and $commit_comments) {
363                         my $message = gettext("Added a comment");
364                         if (defined $form->field('subject') &&
365                                 length $form->field('subject')) {
366                                 $message = sprintf(
367                                         gettext("Added a comment: %s"),
368                                         $form->field('subject'));
369                         }
370
371                         IkiWiki::rcs_add($file);
372                         IkiWiki::disable_commit_hook();
373                         $conflict = IkiWiki::rcs_commit_staged($message,
374                                 $session->param('name'), $ENV{REMOTE_ADDR});
375                         IkiWiki::enable_commit_hook();
376                         IkiWiki::rcs_update();
377                 }
378
379                 # Now we need a refresh
380                 require IkiWiki::Render;
381                 IkiWiki::refresh();
382                 IkiWiki::saveindex();
383
384                 # this should never happen, unless a committer deliberately
385                 # breaks it or something
386                 error($conflict) if defined $conflict;
387
388                 # Bounce back to where we were, but defeat broken caches
389                 my $anticache = "?updated=$page/${comments_pagename}${i}";
390                 IkiWiki::redirect($cgi, urlto($page, undef, 1).$anticache);
391         }
392         else {
393                 IkiWiki::showform ($form, \@buttons, $session, $cgi,
394                         forcebaseurl => $baseurl);
395         }
396
397         exit;
398 } #}}}
399
400 sub pagetemplate (@) { #{{{
401         my %params = @_;
402
403         my $page = $params{page};
404         my $template = $params{template};
405
406         if ($template->query(name => 'comments')) {
407                 my $comments = undef;
408
409                 my $comments_pagename = $config{comments_pagename};
410
411                 my $open = 0;
412                 my $shown = pagespec_match($page,
413                         $config{comments_shown_pagespec},
414                         location => $page);
415
416                 if (pagespec_match($page, "*/${comments_pagename}*",
417                                 location => $page)) {
418                         $shown = 0;
419                         $open = 0;
420                 }
421
422                 if (length $config{cgiurl}) {
423                         $open = pagespec_match($page,
424                                 $config{comments_open_pagespec},
425                                 location => $page);
426                 }
427
428                 if ($shown) {
429                         eval q{use IkiWiki::Plugin::inline};
430                         error($@) if $@;
431
432                         my @args = (
433                                 pages => "internal($page/${comments_pagename}*)",
434                                 template => 'comments_display',
435                                 show => 0,
436                                 reverse => 'yes',
437                                 page => $page,
438                                 destpage => $params{destpage},
439                         );
440                         $comments = IkiWiki::preprocess_inline(@args);
441                 }
442
443                 if (defined $comments && length $comments) {
444                         $template->param(comments => $comments);
445                 }
446
447                 if ($open) {
448                         my $commenturl = IkiWiki::cgiurl(do => 'comment',
449                                 page => $page);
450                         $template->param(commenturl => $commenturl);
451                 }
452         }
453 } # }}}
454
455 package IkiWiki::PageSpec;
456
457 sub match_postcomment ($$;@) {
458         my $page = shift;
459         my $glob = shift;
460
461         unless ($page =~ s/\[postcomment\]$//) {
462                 return IkiWiki::FailReason->new("not posting a comment");
463         }
464         return match_glob($page, $glob);
465 }
466
467 1