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