]> sipb.mit.edu Git - ikiwiki.git/blob - IkiWiki/Plugin/comments.pm
Delay checking for session expiry til we actually post a comment
[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
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::check_canedit($page . "[postcomment]", $cgi, $session);
268
269         my ($authorurl, $author) = linkuser(getcgiuser($session));
270
271         my $body = $form->field('body') || '';
272         $body =~ s/\r\n/\n/g;
273         $body =~ s/\r/\n/g;
274         $body .= "\n" if $body !~ /\n$/;
275
276         unless ($allow_directives) {
277                 # don't allow new-style directives at all
278                 $body =~ s/(^|[^\\])\[\[!/$1&#91;&#91;!/g;
279
280                 # don't allow [[ unless it begins an old-style
281                 # wikilink, if prefix_directives is off
282                 $body =~ s/(^|[^\\])\[\[(?![^\n\s\]+]\]\])/$1&#91;&#91;!/g
283                         unless $config{prefix_directives};
284         }
285
286         # FIXME: check that the wiki is locked right now, because
287         # if it's not, there are mad race conditions!
288
289         # FIXME: rather a simplistic way to make the comments...
290         my $i = 0;
291         my $file;
292         my $location;
293         do {
294                 $i++;
295                 $location = "$page/${comments_pagename}${i}";
296         } while (-e "$config{srcdir}/$location._comment");
297
298         my $anchor = "${comments_pagename}${i}";
299
300         IkiWiki::run_hooks(sanitize => sub {
301                 $body=shift->(
302                         page => $location,
303                         destpage => $location,
304                         content => $body,
305                 );
306         });
307
308         # In this template, the [[!meta]] directives should stay at the end,
309         # so that they will override anything the user specifies. (For
310         # instance, [[!meta author="I can fake the author"]]...)
311         my $content_tmpl = template('comments_comment.tmpl');
312         $content_tmpl->param(author => $author);
313         $content_tmpl->param(authorurl => $authorurl);
314         $content_tmpl->param(subject => $form->field('subject'));
315         $content_tmpl->param(body => $body);
316         $content_tmpl->param(anchor => "$anchor");
317         $content_tmpl->param(permalink => "$baseurl#$anchor");
318         $content_tmpl->param(date => formattime(time, "%X %x"));
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                 IkiWiki::checksessionexpiry($session, $cgi->param('sid'));
357
358                 # FIXME: could probably do some sort of graceful retry
359                 # on error? Would require significant unwinding though
360                 writefile($file, $config{srcdir}, $content);
361
362                 my $conflict;
363
364                 if ($config{rcs} and $commit_comments) {
365                         my $message = gettext("Added a comment");
366                         if (defined $form->field('subject') &&
367                                 length $form->field('subject')) {
368                                 $message = sprintf(
369                                         gettext("Added a comment: %s"),
370                                         $form->field('subject'));
371                         }
372
373                         IkiWiki::rcs_add($file);
374                         IkiWiki::disable_commit_hook();
375                         $conflict = IkiWiki::rcs_commit_staged($message,
376                                 $session->param('name'), $ENV{REMOTE_ADDR});
377                         IkiWiki::enable_commit_hook();
378                         IkiWiki::rcs_update();
379                 }
380
381                 # Now we need a refresh
382                 require IkiWiki::Render;
383                 IkiWiki::refresh();
384                 IkiWiki::saveindex();
385
386                 # this should never happen, unless a committer deliberately
387                 # breaks it or something
388                 error($conflict) if defined $conflict;
389
390                 # Bounce back to where we were, but defeat broken caches
391                 my $anticache = "?updated=$page/${comments_pagename}${i}";
392                 IkiWiki::redirect($cgi, urlto($page, undef, 1).$anticache);
393         }
394         else {
395                 IkiWiki::showform ($form, \@buttons, $session, $cgi,
396                         forcebaseurl => $baseurl);
397         }
398
399         exit;
400 } #}}}
401
402 sub pagetemplate (@) { #{{{
403         my %params = @_;
404
405         my $page = $params{page};
406         my $template = $params{template};
407
408         if ($template->query(name => 'comments')) {
409                 my $comments = undef;
410
411                 my $comments_pagename = $config{comments_pagename};
412
413                 my $open = 0;
414                 my $shown = pagespec_match($page,
415                         $config{comments_shown_pagespec},
416                         location => $page);
417
418                 if (pagespec_match($page, "*/${comments_pagename}*",
419                                 location => $page)) {
420                         $shown = 0;
421                         $open = 0;
422                 }
423
424                 if (length $config{cgiurl}) {
425                         $open = pagespec_match($page,
426                                 $config{comments_open_pagespec},
427                                 location => $page);
428                 }
429
430                 if ($shown) {
431                         eval q{use IkiWiki::Plugin::inline};
432                         error($@) if $@;
433
434                         my @args = (
435                                 pages => "internal($page/${comments_pagename}*)",
436                                 template => 'comments_display',
437                                 show => 0,
438                                 reverse => 'yes',
439                                 page => $page,
440                                 destpage => $params{destpage},
441                         );
442                         $comments = IkiWiki::preprocess_inline(@args);
443                 }
444
445                 if (defined $comments && length $comments) {
446                         $template->param(comments => $comments);
447                 }
448
449                 if ($open) {
450                         my $commenturl = IkiWiki::cgiurl(do => 'comment',
451                                 page => $page);
452                         $template->param(commenturl => $commenturl);
453                 }
454         }
455 } # }}}
456
457 package IkiWiki::PageSpec;
458
459 sub match_postcomment ($$;@) {
460         my $page = shift;
461         my $glob = shift;
462
463         unless ($page =~ s/\[postcomment\]$//) {
464                 return IkiWiki::FailReason->new("not posting a comment");
465         }
466         return match_glob($page, $glob);
467 }
468
469 1