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