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