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