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