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