remove fixme
[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         my $comments_pagename = $config{comments_pagename};
196         if ($params{page} =~ m/\/(\Q${comments_pagename}\E\d+)$/) {
197                 $anchor = $1;
198         }
199         $pagestate{$page}{meta}{permalink} = "${baseurl}#${anchor}";
200
201         eval q{use Date::Parse};
202         if (! $@) {
203                 my $time = str2time($params{date});
204                 $IkiWiki::pagectime{$page} = $time if defined $time;
205         }
206
207         # FIXME: hard-coded HTML (although it's just to set an ID)
208         return "<div id=\"$anchor\">$content</div>" if $anchor;
209         return $content;
210 } # }}}
211
212 sub checkconfig () { #{{{
213         $config{comments_commit} = 1 unless defined $config{comments_commit};
214         $config{comments_pagename} = 'comment_'
215                 unless defined $config{comments_pagename};
216 } #}}}
217
218 # This is exactly the same as recentchanges_link :-(
219 sub linkcgi ($) { #{{{
220         my $cgi=shift;
221         if (defined $cgi->param('do') && $cgi->param('do') eq "commenter") {
222
223                 my $page=decode_utf8($cgi->param("page"));
224                 if (! defined $page) {
225                         error("missing page parameter");
226                 }
227
228                 IkiWiki::loadindex();
229
230                 my $link=bestlink("", $page);
231                 if (! length $link) {
232                         print "Content-type: text/html\n\n";
233                         print IkiWiki::misctemplate(gettext(gettext("missing page")),
234                                 "<p>".
235                                 sprintf(gettext("The page %s does not exist."),
236                                         htmllink("", "", $page)).
237                                 "</p>");
238                 }
239                 else {
240                         IkiWiki::redirect($cgi, urlto($link, undef, 1));
241                 }
242
243                 exit;
244         }
245 }
246
247 # FIXME: basically the same logic as recentchanges
248 # returns (author URL, pretty-printed version)
249 sub linkuser ($) { # {{{
250         my $user = shift;
251         my $oiduser = eval { IkiWiki::openiduser($user) };
252
253         if (defined $oiduser) {
254                 return ($user, $oiduser);
255         }
256         # FIXME: it'd be good to avoid having such a link for anonymous
257         # posts
258         else {
259                 return (IkiWiki::cgiurl(
260                                 do => 'commenter',
261                                 page => (length $config{userdir}
262                                         ? "$config{userdir}/$user"
263                                         : "$user")
264                         ), $user);
265         }
266 } # }}}
267
268 # Mostly cargo-culted from IkiWiki::plugin::editpage
269 sub sessioncgi ($$) { #{{{
270         my $cgi=shift;
271         my $session=shift;
272
273         my $do = $cgi->param('do');
274         return unless $do eq 'comment';
275
276         IkiWiki::decode_cgi_utf8($cgi);
277
278         eval q{use CGI::FormBuilder};
279         error($@) if $@;
280
281         my @buttons = (POST_COMMENT, PREVIEW, CANCEL);
282         my $form = CGI::FormBuilder->new(
283                 fields => [qw{do sid page subject editcontent type author url}],
284                 charset => 'utf-8',
285                 method => 'POST',
286                 required => [qw{editcontent}],
287                 javascript => 0,
288                 params => $cgi,
289                 action => $config{cgiurl},
290                 header => 0,
291                 table => 0,
292                 template => scalar IkiWiki::template_params('comments_form.tmpl'),
293                 # wtf does this do in editpage?
294                 wikiname => $config{wikiname},
295         );
296
297         IkiWiki::decode_form_utf8($form);
298         IkiWiki::run_hooks(formbuilder_setup => sub {
299                         shift->(title => "comment", form => $form, cgi => $cgi,
300                                 session => $session, buttons => \@buttons);
301                 });
302         IkiWiki::decode_form_utf8($form);
303
304         my $type = $form->param('type');
305         if (defined $type && length $type && $IkiWiki::hooks{htmlize}{$type}) {
306                 $type = IkiWiki::possibly_foolish_untaint($type);
307         }
308         else {
309                 $type = $config{default_pageext};
310         }
311         my @page_types;
312         if (exists $IkiWiki::hooks{htmlize}) {
313                 @page_types = grep { ! /^_/ } keys %{$IkiWiki::hooks{htmlize}};
314         }
315
316         my $allow_author = $config{comments_allowauthor};
317
318         $form->field(name => 'do', type => 'hidden');
319         $form->field(name => 'sid', type => 'hidden', value => $session->id,
320                 force => 1);
321         $form->field(name => 'page', type => 'hidden');
322         $form->field(name => 'subject', type => 'text', size => 72);
323         $form->field(name => 'editcontent', type => 'textarea', rows => 10);
324         $form->field(name => "type", value => $type, force => 1,
325                 type => 'select', options => \@page_types);
326
327         $form->tmpl_param(username => $session->param('name'));
328
329         if ($allow_author and ! defined $session->param('name')) {
330                 $form->tmpl_param(allowauthor => 1);
331                 $form->field(name => 'author', type => 'text', size => '40');
332                 $form->field(name => 'url', type => 'text', size => '40');
333         }
334         else {
335                 $form->tmpl_param(allowauthor => 0);
336                 $form->field(name => 'author', type => 'hidden', value => '',
337                         force => 1);
338                 $form->field(name => 'url', type => 'hidden', value => '',
339                         force => 1);
340         }
341
342         # The untaint is OK (as in editpage) because we're about to pass
343         # it to file_pruned anyway
344         my $page = $form->field('page');
345         $page = IkiWiki::possibly_foolish_untaint($page);
346         if (! defined $page || ! length $page ||
347                 IkiWiki::file_pruned($page, $config{srcdir})) {
348                 error(gettext("bad page name"));
349         }
350
351         my $allow_directives = $config{comments_allowdirectives};
352         my $commit_comments = $config{comments_commit};
353         my $comments_pagename = $config{comments_pagename};
354
355         # FIXME: is this right? Or should we be using the candidate subpage
356         # (whatever that might mean) as the base URL?
357         my $baseurl = urlto($page, undef, 1);
358
359         $form->title(sprintf(gettext("commenting on %s"),
360                         IkiWiki::pagetitle($page)));
361
362         $form->tmpl_param('helponformattinglink',
363                 htmllink($page, $page, 'ikiwiki/formatting',
364                         noimageinline => 1,
365                         linktext => 'FormattingHelp'),
366                         allowdirectives => $allow_directives);
367
368         if ($form->submitted eq CANCEL) {
369                 # bounce back to the page they wanted to comment on, and exit.
370                 # CANCEL need not be considered in future
371                 IkiWiki::redirect($cgi, urlto($page, undef, 1));
372                 exit;
373         }
374
375         if (not exists $pagesources{$page}) {
376                 error(sprintf(gettext(
377                         "page '%s' doesn't exist, so you can't comment"),
378                         $page));
379         }
380
381         if (not pagespec_match($page, $config{comments_open_pagespec},
382                 location => $page)) {
383                 error(sprintf(gettext(
384                         "comments on page '%s' are closed"),
385                         $page));
386         }
387
388         # Set a flag to indicate that we're posting a comment,
389         # so that postcomment() can tell it should match.
390         $postcomment=1;
391         IkiWiki::check_canedit($page, $cgi, $session);
392         $postcomment=0;
393
394         # FIXME: rather a simplistic way to make the comments...
395         my $i = 0;
396         my $file;
397         my $location;
398         do {
399                 $i++;
400                 $location = "$page/${comments_pagename}${i}";
401         } while (-e "$config{srcdir}/$location._comment");
402
403         my $content = "[[!_comment format=$type\n";
404
405         # FIXME: handling of double quotes probably wrong?
406         if (defined $session->param('name')) {
407                 my $username = $session->param('name');
408                 $username =~ s/"/&quot;/g;
409                 $content .= " username=\"$username\"\n";
410         }
411         elsif (defined $ENV{REMOTE_ADDR}) {
412                 my $ip = $ENV{REMOTE_ADDR};
413                 if ($ip =~ m/^([.0-9]+)$/) {
414                         $content .= " ip=\"$1\"\n";
415                 }
416         }
417
418         if ($allow_author) {
419                 my $author = $form->field('author');
420                 if (length $author) {
421                         $author =~ s/"/&quot;/g;
422                         $content .= " claimedauthor=\"$author\"\n";
423                 }
424                 my $url = $form->field('url');
425                 if (length $url) {
426                         $url =~ s/"/&quot;/g;
427                         $content .= " url=\"$url\"\n";
428                 }
429         }
430
431         my $subject = $form->field('subject');
432         if (length $subject) {
433                 $subject =~ s/"/&quot;/g;
434                 $content .= " subject=\"$subject\"\n";
435         }
436
437         $content .= " date=\"" . decode_utf8(strftime('%Y-%m-%dT%H:%M:%SZ', gmtime)) . "\"\n";
438
439         my $editcontent = $form->field('editcontent') || '';
440         $editcontent =~ s/\r\n/\n/g;
441         $editcontent =~ s/\r/\n/g;
442         $editcontent =~ s/"/\\"/g;
443         $content .= " content=\"\"\"\n$editcontent\n\"\"\"]]\n";
444
445         # This is essentially a simplified version of editpage:
446         # - the user does not control the page that's created, only the parent
447         # - it's always a create operation, never an edit
448         # - this means that conflicts should never happen
449         # - this means that if they do, rocks fall and everyone dies
450
451         if ($form->submitted eq PREVIEW) {
452                 my $preview = IkiWiki::htmlize($location, $page, '_comment',
453                                 IkiWiki::linkify($page, $page,
454                                         IkiWiki::preprocess($page, $page,
455                                                 IkiWiki::filter($location,
456                                                         $page, $content),
457                                                 0, 1)));
458                 IkiWiki::run_hooks(format => sub {
459                                 $preview = shift->(page => $page,
460                                         content => $preview);
461                         });
462
463                 my $template = template("comments_display.tmpl");
464                 $template->param(content => $preview);
465                 $template->param(title => $form->field('subject'));
466                 $template->param(ctime => displaytime(time));
467
468                 $form->tmpl_param(page_preview => $template->output);
469         }
470         else {
471                 $form->tmpl_param(page_preview => "");
472         }
473
474         if ($form->submitted eq POST_COMMENT && $form->validate) {
475                 my $file = "$location._comment";
476
477                 IkiWiki::checksessionexpiry($session, $cgi->param('sid'));
478
479                 # FIXME: could probably do some sort of graceful retry
480                 # on error? Would require significant unwinding though
481                 writefile($file, $config{srcdir}, $content);
482
483                 my $conflict;
484
485                 if ($config{rcs} and $commit_comments) {
486                         my $message = gettext("Added a comment");
487                         if (defined $form->field('subject') &&
488                                 length $form->field('subject')) {
489                                 $message = sprintf(
490                                         gettext("Added a comment: %s"),
491                                         $form->field('subject'));
492                         }
493
494                         IkiWiki::rcs_add($file);
495                         IkiWiki::disable_commit_hook();
496                         $conflict = IkiWiki::rcs_commit_staged($message,
497                                 $session->param('name'), $ENV{REMOTE_ADDR});
498                         IkiWiki::enable_commit_hook();
499                         IkiWiki::rcs_update();
500                 }
501
502                 # Now we need a refresh
503                 require IkiWiki::Render;
504                 IkiWiki::refresh();
505                 IkiWiki::saveindex();
506
507                 # this should never happen, unless a committer deliberately
508                 # breaks it or something
509                 error($conflict) if defined $conflict;
510
511                 # Bounce back to where we were, but defeat broken caches
512                 my $anticache = "?updated=$page/${comments_pagename}${i}";
513                 IkiWiki::redirect($cgi, urlto($page, undef, 1).$anticache);
514         }
515         else {
516                 IkiWiki::showform ($form, \@buttons, $session, $cgi,
517                         forcebaseurl => $baseurl);
518         }
519
520         exit;
521 } #}}}
522
523 sub pagetemplate (@) { #{{{
524         my %params = @_;
525
526         my $page = $params{page};
527         my $template = $params{template};
528
529         if ($template->query(name => 'comments')) {
530                 my $comments = undef;
531
532                 my $comments_pagename = $config{comments_pagename};
533
534                 my $open = 0;
535                 my $shown = pagespec_match($page,
536                         $config{comments_shown_pagespec},
537                         location => $page);
538
539                 if (pagespec_match($page, "*/${comments_pagename}*",
540                                 location => $page)) {
541                         $shown = 0;
542                         $open = 0;
543                 }
544
545                 if (length $config{cgiurl}) {
546                         $open = pagespec_match($page,
547                                 $config{comments_open_pagespec},
548                                 location => $page);
549                 }
550
551                 if ($shown) {
552                         $comments = IkiWiki::preprocess_inline(
553                                 pages => "internal($page/${comments_pagename}*)",
554                                 template => 'comments_display',
555                                 show => 0,
556                                 reverse => 'yes',
557                                 page => $page,
558                                 destpage => $params{destpage},
559                                 feedfile => 'comments',
560                                 emptyfeeds => 'no',
561                         );
562                 }
563
564                 if (defined $comments && length $comments) {
565                         $template->param(comments => $comments);
566                 }
567
568                 if ($open) {
569                         my $commenturl = IkiWiki::cgiurl(do => 'comment',
570                                 page => $page);
571                         $template->param(commenturl => $commenturl);
572                 }
573         }
574
575         if ($template->query(name => 'commentuser')) {
576                 $template->param(commentuser =>
577                         $pagestate{$page}{comments}{commentuser});
578         }
579
580         if ($template->query(name => 'commentip')) {
581                 $template->param(commentip =>
582                         $pagestate{$page}{comments}{commentip});
583         }
584
585         if ($template->query(name => 'commentauthor')) {
586                 $template->param(commentauthor =>
587                         $pagestate{$page}{comments}{commentauthor});
588         }
589
590         if ($template->query(name => 'commentauthorurl')) {
591                 $template->param(commentauthorurl =>
592                         $pagestate{$page}{comments}{commentauthorurl});
593         }
594 } # }}}
595
596 package IkiWiki::PageSpec;
597
598 sub match_postcomment ($$;@) {
599         my $page = shift;
600         my $glob = shift;
601
602         if (! $postcomment) {
603                 return IkiWiki::FailReason->new("not posting a comment");
604         }
605         return match_glob($page, $glob);
606 }
607
608 1