]> sipb.mit.edu Git - ikiwiki.git/blob - IkiWiki/Plugin/comments.pm
58076938bdffdc337719d2aa986cc1373e4b9a16
[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::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         $content_tmpl->param(date => formattime(time, "%X %x"));
320
321         my $content = $content_tmpl->output;
322
323         # This is essentially a simplified version of editpage:
324         # - the user does not control the page that's created, only the parent
325         # - it's always a create operation, never an edit
326         # - this means that conflicts should never happen
327         # - this means that if they do, rocks fall and everyone dies
328
329         if ($form->submitted eq PREVIEW) {
330                 my $preview = IkiWiki::htmlize($location, $page, 'mdwn',
331                                 IkiWiki::linkify($page, $page,
332                                         IkiWiki::preprocess($page, $page,
333                                                 IkiWiki::filter($location,
334                                                         $page, $content),
335                                                 0, 1)));
336                 IkiWiki::run_hooks(format => sub {
337                                 $preview = shift->(page => $page,
338                                         content => $preview);
339                         });
340
341                 my $template = template("comments_display.tmpl");
342                 $template->param(content => $preview);
343                 $template->param(title => $form->field('subject'));
344                 $template->param(ctime => displaytime(time));
345                 $template->param(author => $author);
346                 $template->param(authorurl => $authorurl);
347
348                 $form->tmpl_param(page_preview => $template->output);
349         }
350         else {
351                 $form->tmpl_param(page_preview => "");
352         }
353
354         if ($form->submitted eq POST_COMMENT && $form->validate) {
355                 my $file = "$location._comment";
356
357                 # FIXME: could probably do some sort of graceful retry
358                 # on error? Would require significant unwinding though
359                 writefile($file, $config{srcdir}, $content);
360
361                 my $conflict;
362
363                 if ($config{rcs} and $commit_comments) {
364                         my $message = gettext("Added a comment");
365                         if (defined $form->field('subject') &&
366                                 length $form->field('subject')) {
367                                 $message = sprintf(
368                                         gettext("Added a comment: %s"),
369                                         $form->field('subject'));
370                         }
371
372                         IkiWiki::rcs_add($file);
373                         IkiWiki::disable_commit_hook();
374                         $conflict = IkiWiki::rcs_commit_staged($message,
375                                 $session->param('name'), $ENV{REMOTE_ADDR});
376                         IkiWiki::enable_commit_hook();
377                         IkiWiki::rcs_update();
378                 }
379
380                 # Now we need a refresh
381                 require IkiWiki::Render;
382                 IkiWiki::refresh();
383                 IkiWiki::saveindex();
384
385                 # this should never happen, unless a committer deliberately
386                 # breaks it or something
387                 error($conflict) if defined $conflict;
388
389                 # Bounce back to where we were, but defeat broken caches
390                 my $anticache = "?updated=$page/${comments_pagename}${i}";
391                 IkiWiki::redirect($cgi, urlto($page, undef, 1).$anticache);
392         }
393         else {
394                 IkiWiki::showform ($form, \@buttons, $session, $cgi,
395                         forcebaseurl => $baseurl);
396         }
397
398         exit;
399 } #}}}
400
401 sub pagetemplate (@) { #{{{
402         my %params = @_;
403
404         my $page = $params{page};
405         my $template = $params{template};
406
407         if ($template->query(name => 'comments')) {
408                 my $comments = undef;
409
410                 my $comments_pagename = $config{comments_pagename};
411
412                 my $open = 0;
413                 my $shown = pagespec_match($page,
414                         $config{comments_shown_pagespec},
415                         location => $page);
416
417                 if (pagespec_match($page, "*/${comments_pagename}*",
418                                 location => $page)) {
419                         $shown = 0;
420                         $open = 0;
421                 }
422
423                 if (length $config{cgiurl}) {
424                         $open = pagespec_match($page,
425                                 $config{comments_open_pagespec},
426                                 location => $page);
427                 }
428
429                 if ($shown) {
430                         eval q{use IkiWiki::Plugin::inline};
431                         error($@) if $@;
432
433                         my @args = (
434                                 pages => "internal($page/${comments_pagename}*)",
435                                 template => 'comments_display',
436                                 show => 0,
437                                 reverse => 'yes',
438                                 page => $page,
439                                 destpage => $params{destpage},
440                         );
441                         $comments = IkiWiki::preprocess_inline(@args);
442                 }
443
444                 if (defined $comments && length $comments) {
445                         $template->param(comments => $comments);
446                 }
447
448                 if ($open) {
449                         my $commenturl = IkiWiki::cgiurl(do => 'comment',
450                                 page => $page);
451                         $template->param(commenturl => $commenturl);
452                 }
453         }
454 } # }}}
455
456 package IkiWiki::PageSpec;
457
458 sub match_postcomment ($$;@) {
459         my $page = shift;
460         my $glob = shift;
461
462         unless ($page =~ s/\[postcomment\]$//) {
463                 return IkiWiki::FailReason->new("not posting a comment");
464         }
465         return match_glob($page, $glob);
466 }
467
468 1