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