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