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