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