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