]> sipb.mit.edu Git - ikiwiki.git/blob - IkiWiki/Plugin/comments.pm
comments: use global configuration for allow_directives, commit, and pagename
[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 (not exists $pagesources{$page}) {
241                 error(sprintf(gettext(
242                         "page '%s' doesn't exist, so you can't comment"),
243                         $page));
244         }
245         if (not $pagestate{$page}{comments}{comments}) {
246                 error(sprintf(gettext(
247                         "comments are not enabled on page '%s'"),
248                         $page));
249         }
250
251         if ($form->submitted eq CANCEL) {
252                 # bounce back to the page they wanted to comment on, and exit.
253                 # CANCEL need not be considered in future
254                 IkiWiki::redirect($cgi, urlto($page, undef, 1));
255                 exit;
256         }
257
258         IkiWiki::check_canedit($page . "[postcomment]", $cgi, $session);
259
260         my ($authorurl, $author) = linkuser(getcgiuser($session));
261
262         my $body = $form->field('body') || '';
263         $body =~ s/\r\n/\n/g;
264         $body =~ s/\r/\n/g;
265         $body .= "\n" if $body !~ /\n$/;
266
267         unless ($allow_directives) {
268                 # don't allow new-style directives at all
269                 $body =~ s/(^|[^\\])\[\[!/$1&#91;&#91;!/g;
270
271                 # don't allow [[ unless it begins an old-style
272                 # wikilink, if prefix_directives is off
273                 $body =~ s/(^|[^\\])\[\[(?![^\n\s\]+]\]\])/$1&#91;&#91;!/g
274                         unless $config{prefix_directives};
275         }
276
277         IkiWiki::run_hooks(sanitize => sub {
278                 # $fake is a possible location for this comment. We don't
279                 # know yet what the comment number *actually* is.
280                 my $fake = "$page/_comment_1";
281                 $body=shift->(
282                         page => $fake,
283                         destpage => $fake,
284                         content => $body,
285                 );
286         });
287
288         # In this template, the [[!meta]] directives should stay at the end,
289         # so that they will override anything the user specifies. (For
290         # instance, [[!meta author="I can fake the author"]]...)
291         my $content_tmpl = template('comments_comment.tmpl');
292         $content_tmpl->param(author => $author);
293         $content_tmpl->param(authorurl => $authorurl);
294         $content_tmpl->param(subject => $form->field('subject'));
295         $content_tmpl->param(body => $body);
296
297         my $content = $content_tmpl->output;
298
299         # This is essentially a simplified version of editpage:
300         # - the user does not control the page that's created, only the parent
301         # - it's always a create operation, never an edit
302         # - this means that conflicts should never happen
303         # - this means that if they do, rocks fall and everyone dies
304
305         if ($form->submitted eq PREVIEW) {
306                 # $fake is a possible location for this comment. We don't
307                 # know yet what the comment number *actually* is.
308                 my $fake = "$page/_comment_1";
309                 my $preview = IkiWiki::htmlize($fake, $page, 'mdwn',
310                                 IkiWiki::linkify($page, $page,
311                                         IkiWiki::preprocess($page, $page,
312                                                 IkiWiki::filter($fake, $page,
313                                                         $content),
314                                                 0, 1)));
315                 IkiWiki::run_hooks(format => sub {
316                                 $preview = shift->(page => $page,
317                                         content => $preview);
318                         });
319
320                 my $template = template("comments_display.tmpl");
321                 $template->param(content => $preview);
322                 $template->param(title => $form->field('subject'));
323                 $template->param(ctime => displaytime(time));
324                 $template->param(author => $author);
325                 $template->param(authorurl => $authorurl);
326
327                 $form->tmpl_param(page_preview => $template->output);
328         }
329         else {
330                 $form->tmpl_param(page_preview => "");
331         }
332
333         if ($form->submitted eq POST_COMMENT && $form->validate) {
334                 # Let's get posting. We don't check_canedit here because
335                 # that somewhat defeats the point of this plugin.
336
337                 IkiWiki::checksessionexpiry($session, $cgi->param('sid'));
338
339                 # FIXME: check that the wiki is locked right now, because
340                 # if it's not, there are mad race conditions!
341
342                 # FIXME: rather a simplistic way to make the comments...
343                 my $i = 0;
344                 my $file;
345                 do {
346                         $i++;
347                         $file = "$page/_comment_${i}._comment";
348                 } while (-e "$config{srcdir}/$file");
349
350                 # FIXME: could probably do some sort of graceful retry
351                 # if I could be bothered
352                 writefile($file, $config{srcdir}, $content);
353
354                 my $conflict;
355
356                 if ($config{rcs} and $commit_comments) {
357                         my $message = gettext("Added a comment");
358                         if (defined $form->field('subject') &&
359                                 length $form->field('subject')) {
360                                 $message .= ": ".$form->field('subject');
361                         }
362
363                         IkiWiki::rcs_add($file);
364                         IkiWiki::disable_commit_hook();
365                         $conflict = IkiWiki::rcs_commit_staged($message,
366                                 $session->param('name'), $ENV{REMOTE_ADDR});
367                         IkiWiki::enable_commit_hook();
368                         IkiWiki::rcs_update();
369                 }
370
371                 # Now we need a refresh
372                 require IkiWiki::Render;
373                 IkiWiki::refresh();
374                 IkiWiki::saveindex();
375
376                 # this should never happen, unless a committer deliberately
377                 # breaks it or something
378                 error($conflict) if defined $conflict;
379
380                 # Bounce back to where we were, but defeat broken caches
381                 my $anticache = "?updated=$page/_comment_$i";
382                 IkiWiki::redirect($cgi, urlto($page, undef, 1).$anticache);
383         }
384         else {
385                 IkiWiki::showform ($form, \@buttons, $session, $cgi,
386                         forcebaseurl => $baseurl);
387         }
388
389         exit;
390 } #}}}
391
392 sub pagetemplate (@) { #{{{
393         my %params = @_;
394
395         my $page = $params{page};
396         my $template = $params{template};
397
398         if ($template->query(name => 'comments')) {
399                 my $comments = undef;
400
401                 if (defined $comments && length $comments) {
402                         $template->param(name => $comments);
403                 }
404         }
405 } # }}}
406
407 package IkiWiki::PageSpec;
408
409 sub match_postcomment ($$;@) {
410         my $page = shift;
411         my $glob = shift;
412
413         unless ($page =~ s/\[postcomment\]$//) {
414                 return IkiWiki::FailReason->new("not posting a comment");
415         }
416         return match_glob($page, $glob);
417 }
418
419 1