comments: fix invocation of possibly_foolish_untaint
[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 # FIXME: copied verbatim from meta
34 sub safeurl ($) { #{{{
35         my $url=shift;
36         if (exists $IkiWiki::Plugin::htmlscrubber::{safe_url_regexp} &&
37             defined $IkiWiki::Plugin::htmlscrubber::safe_url_regexp) {
38                 return $url=~/$IkiWiki::Plugin::htmlscrubber::safe_url_regexp/;
39         }
40         else {
41                 return 1;
42         }
43 } #}}}
44
45 sub preprocess { # {{{
46         my %params = @_;
47         my $page = $params{page};
48
49         my $format = $params{format};
50         if (defined $format && !exists $IkiWiki::hooks{htmlize}{$format}) {
51                 error(sprintf(gettext("unsupported page format %s"), $format));
52         }
53
54         my $content = $params{content};
55         if (!defined $content) {
56                 error(gettext("comment must have content"));
57         }
58         $content =~ s/\\"/"/g;
59
60         $content = IkiWiki::filter($page, $params{destpage}, $content);
61
62         if ($config{comments_allowdirectives}) {
63                 $content = IkiWiki::preprocess($page, $params{destpage},
64                         $content);
65         }
66
67         # no need to bother with htmlize if it's just HTML
68         $content = IkiWiki::htmlize($page, $params{destpage}, $format,
69                 $content) if defined $format;
70
71         IkiWiki::run_hooks(sanitize => sub {
72                 $content = shift->(
73                         page => $page,
74                         destpage => $params{destpage},
75                         content => $content,
76                 );
77         });
78
79         # set metadata, possibly overriding [[!meta]] directives from the
80         # comment itself
81
82         my $commentuser;
83         my $commentip;
84         my $commentauthor;
85         my $commentauthorurl;
86
87         if (defined $params{username}) {
88                 $commentuser = $params{username};
89                 ($commentauthorurl, $commentauthor) =
90                         linkuser($params{username});
91         }
92         elsif (defined $params{ip}) {
93                 $commentip = $params{ip};
94                 $commentauthor = sprintf(
95                         gettext("Anonymous (IP: %s)"), $params{ip});
96         }
97         else {
98                 $commentauthor = gettext("Anonymous");
99         }
100
101         $pagestate{$page}{comments}{commentuser} = $commentuser;
102         $pagestate{$page}{comments}{commentip} = $commentip;
103         $pagestate{$page}{comments}{commentauthor} = $commentauthor;
104         $pagestate{$page}{comments}{commentauthorurl} = $commentauthorurl;
105         if (!defined $pagestate{$page}{meta}{author}) {
106                 $pagestate{$page}{meta}{author} = $commentauthor;
107         }
108         if (!defined $pagestate{$page}{meta}{authorurl}) {
109                 $pagestate{$page}{meta}{authorurl} = $commentauthorurl;
110         }
111
112         if ($config{comments_allowauthor}) {
113                 if (defined $params{claimedauthor}) {
114                         $pagestate{$page}{meta}{author} = $params{claimedauthor};
115                 }
116
117                 if (defined $params{url} and safeurl($params{url})) {
118                         $pagestate{$page}{meta}{authorurl} = $params{url};
119                 }
120         }
121         else {
122                 $pagestate{$page}{meta}{author} = $commentauthor;
123                 $pagestate{$page}{meta}{authorurl} = $commentauthorurl;
124         }
125
126         if (defined $params{subject}) {
127                 $pagestate{$page}{meta}{title} = $params{subject};
128         }
129
130         my $baseurl = urlto($params{destpage}, undef, 1);
131         my $anchor = "";
132         my $comments_pagename = $config{comments_pagename};
133         if ($params{page} =~ m/\/(\Q${comments_pagename}\E\d+)$/) {
134                 $anchor = $1;
135         }
136         $pagestate{$page}{meta}{permalink} = "${baseurl}#${anchor}";
137
138         eval q{use Date::Parse};
139         if (! $@) {
140                 my $time = str2time($params{date});
141                 $IkiWiki::pagectime{$page} = $time if defined $time;
142         }
143
144         # FIXME: hard-coded HTML (although it's just to set an ID)
145         return "<div id=\"$anchor\">$content</div>" if $anchor;
146         return $content;
147 } # }}}
148
149 sub getsetup () { #{{{
150         return
151                 plugin => {
152                         safe => 1,
153                         rebuild => 1,
154                 },
155                 # Pages where comments are shown, but new comments are not
156                 # allowed, will show "Comments are closed".
157                 comments_shown_pagespec => {
158                         type => 'pagespec',
159                         example => 'blog/*',
160                         default => '',
161                         description => 'PageSpec for pages where comments will be shown inline',
162                         link => 'ikiwiki/PageSpec',
163                         safe => 1,
164                         rebuild => 1,
165                 },
166                 comments_open_pagespec => {
167                         type => 'pagespec',
168                         example => 'blog/* and created_after(close_old_comments)',
169                         default => '',
170                         description => 'PageSpec for pages where new comments can be posted',
171                         link => 'ikiwiki/PageSpec',
172                         safe => 1,
173                         rebuild => 1,
174                 },
175                 comments_pagename => {
176                         type => 'string',
177                         example => 'comment_',
178                         default => 'comment_',
179                         description => 'Base name for comments, e.g. "comment_" for pages like "sandbox/comment_12"',
180                         safe => 0, # manual page moving will required
181                         rebuild => undef,
182                 },
183                 comments_allowdirectives => {
184                         type => 'boolean',
185                         default => 0,
186                         example => 0,
187                         description => 'Interpret directives in comments?',
188                         safe => 1,
189                         rebuild => 0,
190                 },
191                 comments_allowauthor => {
192                         type => 'boolean',
193                         default => 0,
194                         example => 0,
195                         description => 'Allow anonymous commenters to set an author name?',
196                         safe => 1,
197                         rebuild => 0,
198                 },
199                 comments_commit => {
200                         type => 'boolean',
201                         example => 1,
202                         default => 1,
203                         description => 'commit comments to the VCS',
204                         # old uncommitted comments are likely to cause
205                         # confusion if this is changed
206                         safe => 0,
207                         rebuild => 0,
208                 },
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         my $allow_author = $config{comments_allowauthor};
316
317         $form->field(name => 'do', type => 'hidden');
318         $form->field(name => 'sid', type => 'hidden', value => $session->id,
319                 force => 1);
320         $form->field(name => 'page', type => 'hidden');
321         $form->field(name => 'subject', type => 'text', size => 72);
322         $form->field(name => 'editcontent', type => 'textarea', rows => 10);
323         $form->field(name => "type", value => $type, force => 1,
324                 type => 'select', options => \@page_types);
325
326         $form->tmpl_param(username => $session->param('name'));
327
328         if ($allow_author and !defined $session->param('name')) {
329                 $form->tmpl_param(allowauthor => 1);
330                 $form->field(name => 'author', type => 'text', size => '40');
331                 $form->field(name => 'url', type => 'text', size => '40');
332         }
333         else {
334                 $form->tmpl_param(allowauthor => 0);
335                 $form->field(name => 'author', type => 'hidden', value => '',
336                         force => 1);
337                 $form->field(name => 'url', type => 'hidden', value => '',
338                         force => 1);
339         }
340
341         # The untaint is OK (as in editpage) because we're about to pass
342         # it to file_pruned anyway
343         my $page = $form->field('page');
344         $page = IkiWiki::possibly_foolish_untaint($page);
345         if (!defined $page || !length $page ||
346                 IkiWiki::file_pruned($page, $config{srcdir})) {
347                 error(gettext("bad page name"));
348         }
349
350         my $allow_directives = $config{comments_allowdirectives};
351         my $commit_comments = $config{comments_commit};
352         my $comments_pagename = $config{comments_pagename};
353
354         # FIXME: is this right? Or should we be using the candidate subpage
355         # (whatever that might mean) as the base URL?
356         my $baseurl = urlto($page, undef, 1);
357
358         $form->title(sprintf(gettext("commenting on %s"),
359                         IkiWiki::pagetitle($page)));
360
361         $form->tmpl_param('helponformattinglink',
362                 htmllink($page, $page, 'ikiwiki/formatting',
363                         noimageinline => 1,
364                         linktext => 'FormattingHelp'),
365                         allowdirectives => $allow_directives);
366
367         if ($form->submitted eq CANCEL) {
368                 # bounce back to the page they wanted to comment on, and exit.
369                 # CANCEL need not be considered in future
370                 IkiWiki::redirect($cgi, urlto($page, undef, 1));
371                 exit;
372         }
373
374         if (not exists $pagesources{$page}) {
375                 error(sprintf(gettext(
376                         "page '%s' doesn't exist, so you can't comment"),
377                         $page));
378         }
379
380         if (not pagespec_match($page, $config{comments_open_pagespec},
381                 location => $page)) {
382                 error(sprintf(gettext(
383                         "comments on page '%s' are closed"),
384                         $page));
385         }
386
387         IkiWiki::check_canedit($page . "[postcomment]", $cgi, $session);
388
389         my $editcontent = $form->field('editcontent') || '';
390         $editcontent =~ s/\r\n/\n/g;
391         $editcontent =~ s/\r/\n/g;
392
393         # FIXME: check that the wiki is locked right now, because
394         # if it's not, there are mad race conditions!
395
396         # FIXME: rather a simplistic way to make the comments...
397         my $i = 0;
398         my $file;
399         my $location;
400         do {
401                 $i++;
402                 $location = "$page/${comments_pagename}${i}";
403         } while (-e "$config{srcdir}/$location._comment");
404
405         my $anchor = "${comments_pagename}${i}";
406
407         $editcontent =~ s/"/\\"/g;
408         my $content = "[[!comment format=$type\n";
409
410         # FIXME: handling of double quotes probably wrong?
411         if (defined $session->param('name')) {
412                 my $username = $session->param('name');
413                 $username =~ s/"/&quot;/g;
414                 $content .= " username=\"$username\"\n";
415         }
416         elsif (defined $ENV{REMOTE_ADDR}) {
417                 my $ip = $ENV{REMOTE_ADDR};
418                 if ($ip =~ m/^([.0-9]+)$/) {
419                         $content .= " ip=\"$1\"\n";
420                 }
421         }
422
423         if ($allow_author) {
424                 my $author = $form->field('author');
425                 if (length $author) {
426                         $author =~ s/"/&quot;/g;
427                         $content .= " claimedauthor=\"$author\"\n";
428                 }
429                 my $url = $form->field('url');
430                 if (length $url) {
431                         $url =~ s/"/&quot;/g;
432                         $content .= " url=\"$url\"\n";
433                 }
434         }
435
436         my $subject = $form->field('subject');
437         if (length $subject) {
438                 $subject =~ s/"/&quot;/g;
439                 $content .= " subject=\"$subject\"\n";
440         }
441
442         $content .= " date=\"" . IkiWiki::formattime(time, '%X %x') . "\"\n";
443
444         $content .= " content=\"\"\"\n$editcontent\n\"\"\"]]\n";
445
446         # This is essentially a simplified version of editpage:
447         # - the user does not control the page that's created, only the parent
448         # - it's always a create operation, never an edit
449         # - this means that conflicts should never happen
450         # - this means that if they do, rocks fall and everyone dies
451
452         if ($form->submitted eq PREVIEW) {
453                 my $preview = IkiWiki::htmlize($location, $page, '_comment',
454                                 IkiWiki::linkify($page, $page,
455                                         IkiWiki::preprocess($page, $page,
456                                                 IkiWiki::filter($location,
457                                                         $page, $content),
458                                                 0, 1)));
459                 IkiWiki::run_hooks(format => sub {
460                                 $preview = shift->(page => $page,
461                                         content => $preview);
462                         });
463
464                 my $template = template("comments_display.tmpl");
465                 $template->param(content => $preview);
466                 $template->param(title => $form->field('subject'));
467                 $template->param(ctime => displaytime(time));
468
469                 $form->tmpl_param(page_preview => $template->output);
470         }
471         else {
472                 $form->tmpl_param(page_preview => "");
473         }
474
475         if ($form->submitted eq POST_COMMENT && $form->validate) {
476                 my $file = "$location._comment";
477
478                 IkiWiki::checksessionexpiry($session, $cgi->param('sid'));
479
480                 # FIXME: could probably do some sort of graceful retry
481                 # on error? Would require significant unwinding though
482                 writefile($file, $config{srcdir}, $content);
483
484                 my $conflict;
485
486                 if ($config{rcs} and $commit_comments) {
487                         my $message = gettext("Added a comment");
488                         if (defined $form->field('subject') &&
489                                 length $form->field('subject')) {
490                                 $message = sprintf(
491                                         gettext("Added a comment: %s"),
492                                         $form->field('subject'));
493                         }
494
495                         IkiWiki::rcs_add($file);
496                         IkiWiki::disable_commit_hook();
497                         $conflict = IkiWiki::rcs_commit_staged($message,
498                                 $session->param('name'), $ENV{REMOTE_ADDR});
499                         IkiWiki::enable_commit_hook();
500                         IkiWiki::rcs_update();
501                 }
502
503                 # Now we need a refresh
504                 require IkiWiki::Render;
505                 IkiWiki::refresh();
506                 IkiWiki::saveindex();
507
508                 # this should never happen, unless a committer deliberately
509                 # breaks it or something
510                 error($conflict) if defined $conflict;
511
512                 # Bounce back to where we were, but defeat broken caches
513                 my $anticache = "?updated=$page/${comments_pagename}${i}";
514                 IkiWiki::redirect($cgi, urlto($page, undef, 1).$anticache);
515         }
516         else {
517                 IkiWiki::showform ($form, \@buttons, $session, $cgi,
518                         forcebaseurl => $baseurl);
519         }
520
521         exit;
522 } #}}}
523
524 sub pagetemplate (@) { #{{{
525         my %params = @_;
526
527         my $page = $params{page};
528         my $template = $params{template};
529
530         if ($template->query(name => 'comments')) {
531                 my $comments = undef;
532
533                 my $comments_pagename = $config{comments_pagename};
534
535                 my $open = 0;
536                 my $shown = pagespec_match($page,
537                         $config{comments_shown_pagespec},
538                         location => $page);
539
540                 if (pagespec_match($page, "*/${comments_pagename}*",
541                                 location => $page)) {
542                         $shown = 0;
543                         $open = 0;
544                 }
545
546                 if (length $config{cgiurl}) {
547                         $open = pagespec_match($page,
548                                 $config{comments_open_pagespec},
549                                 location => $page);
550                 }
551
552                 if ($shown) {
553                         eval q{use IkiWiki::Plugin::inline};
554                         error($@) if $@;
555
556                         my @args = (
557                                 pages => "internal($page/${comments_pagename}*)",
558                                 template => 'comments_display',
559                                 show => 0,
560                                 reverse => 'yes',
561                                 page => $page,
562                                 destpage => $params{destpage},
563                         );
564                         $comments = IkiWiki::preprocess_inline(@args);
565                 }
566
567                 if (defined $comments && length $comments) {
568                         $template->param(comments => $comments);
569                 }
570
571                 if ($open) {
572                         my $commenturl = IkiWiki::cgiurl(do => 'comment',
573                                 page => $page);
574                         $template->param(commenturl => $commenturl);
575                 }
576         }
577
578         if ($template->query(name => 'commentuser')) {
579                 $template->param(commentuser =>
580                         $pagestate{$page}{comments}{commentuser});
581         }
582
583         if ($template->query(name => 'commentip')) {
584                 $template->param(commentip =>
585                         $pagestate{$page}{comments}{commentip});
586         }
587
588         if ($template->query(name => 'commentauthor')) {
589                 $template->param(commentauthor =>
590                         $pagestate{$page}{comments}{commentauthor});
591         }
592
593         if ($template->query(name => 'commentauthorurl')) {
594                 $template->param(commentauthorurl =>
595                         $pagestate{$page}{comments}{commentauthorurl});
596         }
597 } # }}}
598
599 package IkiWiki::PageSpec;
600
601 sub match_postcomment ($$;@) {
602         my $page = shift;
603         my $glob = shift;
604
605         unless ($page =~ s/\[postcomment\]$//) {
606                 return IkiWiki::FailReason->new("not posting a comment");
607         }
608         return match_glob($page, $glob);
609 }
610
611 1