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