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