comments: Store dates in GMT and in ISO-8601
[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 sub import { #{{{
19         hook(type => "checkconfig", id => 'comments',  call => \&checkconfig);
20         hook(type => "getsetup", id => 'comments',  call => \&getsetup);
21         hook(type => "preprocess", id => '_comment', call => \&preprocess);
22         hook(type => "sessioncgi", id => 'comment', call => \&sessioncgi);
23         hook(type => "htmlize", id => "_comment", call => \&htmlize);
24         hook(type => "pagetemplate", id => "comments", call => \&pagetemplate);
25         hook(type => "cgi", id => "comments", call => \&linkcgi);
26         IkiWiki::loadplugin("inline");
27 } # }}}
28
29 sub htmlize { # {{{
30         my %params = @_;
31         return $params{content};
32 } # }}}
33
34 # FIXME: copied verbatim from meta
35 sub safeurl ($) { #{{{
36         my $url=shift;
37         if (exists $IkiWiki::Plugin::htmlscrubber::{safe_url_regexp} &&
38             defined $IkiWiki::Plugin::htmlscrubber::safe_url_regexp) {
39                 return $url=~/$IkiWiki::Plugin::htmlscrubber::safe_url_regexp/;
40         }
41         else {
42                 return 1;
43         }
44 } #}}}
45
46 sub preprocess { # {{{
47         my %params = @_;
48         my $page = $params{page};
49
50         my $format = $params{format};
51         if (defined $format && !exists $IkiWiki::hooks{htmlize}{$format}) {
52                 error(sprintf(gettext("unsupported page format %s"), $format));
53         }
54
55         my $content = $params{content};
56         if (!defined $content) {
57                 error(gettext("comment must have content"));
58         }
59         $content =~ s/\\"/"/g;
60
61         $content = IkiWiki::filter($page, $params{destpage}, $content);
62
63         if ($config{comments_allowdirectives}) {
64                 $content = IkiWiki::preprocess($page, $params{destpage},
65                         $content);
66         }
67
68         # no need to bother with htmlize if it's just HTML
69         $content = IkiWiki::htmlize($page, $params{destpage}, $format,
70                 $content) if defined $format;
71
72         IkiWiki::run_hooks(sanitize => sub {
73                 $content = shift->(
74                         page => $page,
75                         destpage => $params{destpage},
76                         content => $content,
77                 );
78         });
79
80         # set metadata, possibly overriding [[!meta]] directives from the
81         # comment itself
82
83         my $commentuser;
84         my $commentip;
85         my $commentauthor;
86         my $commentauthorurl;
87
88         if (defined $params{username}) {
89                 $commentuser = $params{username};
90                 ($commentauthorurl, $commentauthor) =
91                         linkuser($params{username});
92         }
93         else {
94                 if (defined $params{ip}) {
95                         $commentip = $params{ip};
96                 }
97                 $commentauthor = gettext("Anonymous");
98         }
99
100         $pagestate{$page}{comments}{commentuser} = $commentuser;
101         $pagestate{$page}{comments}{commentip} = $commentip;
102         $pagestate{$page}{comments}{commentauthor} = $commentauthor;
103         $pagestate{$page}{comments}{commentauthorurl} = $commentauthorurl;
104         if (!defined $pagestate{$page}{meta}{author}) {
105                 $pagestate{$page}{meta}{author} = $commentauthor;
106         }
107         if (!defined $pagestate{$page}{meta}{authorurl}) {
108                 $pagestate{$page}{meta}{authorurl} = $commentauthorurl;
109         }
110
111         if ($config{comments_allowauthor}) {
112                 if (defined $params{claimedauthor}) {
113                         $pagestate{$page}{meta}{author} = $params{claimedauthor};
114                 }
115
116                 if (defined $params{url} and safeurl($params{url})) {
117                         $pagestate{$page}{meta}{authorurl} = $params{url};
118                 }
119         }
120         else {
121                 $pagestate{$page}{meta}{author} = $commentauthor;
122                 $pagestate{$page}{meta}{authorurl} = $commentauthorurl;
123         }
124
125         if (defined $params{subject}) {
126                 $pagestate{$page}{meta}{title} = $params{subject};
127         }
128
129         my $baseurl = urlto($params{destpage}, undef, 1);
130         my $anchor = "";
131         my $comments_pagename = $config{comments_pagename};
132         if ($params{page} =~ m/\/(\Q${comments_pagename}\E\d+)$/) {
133                 $anchor = $1;
134         }
135         $pagestate{$page}{meta}{permalink} = "${baseurl}#${anchor}";
136
137         eval q{use Date::Parse};
138         if (! $@) {
139                 my $time = str2time($params{date});
140                 $IkiWiki::pagectime{$page} = $time if defined $time;
141         }
142
143         # FIXME: hard-coded HTML (although it's just to set an ID)
144         return "<div id=\"$anchor\">$content</div>" if $anchor;
145         return $content;
146 } # }}}
147
148 sub getsetup () { #{{{
149         return
150                 plugin => {
151                         safe => 1,
152                         rebuild => 1,
153                 },
154                 # Pages where comments are shown, but new comments are not
155                 # allowed, will show "Comments are closed".
156                 comments_shown_pagespec => {
157                         type => 'pagespec',
158                         example => 'blog/*',
159                         default => '',
160                         description => 'PageSpec for pages where comments will be shown inline',
161                         link => 'ikiwiki/PageSpec',
162                         safe => 1,
163                         rebuild => 1,
164                 },
165                 comments_open_pagespec => {
166                         type => 'pagespec',
167                         example => 'blog/* and created_after(close_old_comments)',
168                         default => '',
169                         description => 'PageSpec for pages where new comments can be posted',
170                         link => 'ikiwiki/PageSpec',
171                         safe => 1,
172                         rebuild => 1,
173                 },
174                 comments_pagename => {
175                         type => 'string',
176                         example => 'comment_',
177                         default => 'comment_',
178                         description => 'Base name for comments, e.g. "comment_" for pages like "sandbox/comment_12"',
179                         safe => 0, # manual page moving will required
180                         rebuild => undef,
181                 },
182                 comments_allowdirectives => {
183                         type => 'boolean',
184                         default => 0,
185                         example => 0,
186                         description => 'Interpret directives in comments?',
187                         safe => 1,
188                         rebuild => 0,
189                 },
190                 comments_allowauthor => {
191                         type => 'boolean',
192                         default => 0,
193                         example => 0,
194                         description => 'Allow anonymous commenters to set an author name?',
195                         safe => 1,
196                         rebuild => 0,
197                 },
198                 comments_commit => {
199                         type => 'boolean',
200                         example => 1,
201                         default => 1,
202                         description => 'commit comments to the VCS',
203                         # old uncommitted comments are likely to cause
204                         # confusion if this is changed
205                         safe => 0,
206                         rebuild => 0,
207                 },
208 } #}}}
209
210 sub checkconfig () { #{{{
211         $config{comments_commit} = 1 unless defined $config{comments_commit};
212         $config{comments_pagename} = 'comment_'
213                 unless defined $config{comments_pagename};
214 } #}}}
215
216 # This is exactly the same as recentchanges_link :-(
217 sub linkcgi ($) { #{{{
218         my $cgi=shift;
219         if (defined $cgi->param('do') && $cgi->param('do') eq "commenter") {
220
221                 my $page=decode_utf8($cgi->param("page"));
222                 if (!defined $page) {
223                         error("missing page parameter");
224                 }
225
226                 IkiWiki::loadindex();
227
228                 my $link=bestlink("", $page);
229                 if (! length $link) {
230                         print "Content-type: text/html\n\n";
231                         print IkiWiki::misctemplate(gettext(gettext("missing page")),
232                                 "<p>".
233                                 sprintf(gettext("The page %s does not exist."),
234                                         htmllink("", "", $page)).
235                                 "</p>");
236                 }
237                 else {
238                         IkiWiki::redirect($cgi, urlto($link, undef, 1));
239                 }
240
241                 exit;
242         }
243 }
244
245 # FIXME: basically the same logic as recentchanges
246 # returns (author URL, pretty-printed version)
247 sub linkuser ($) { # {{{
248         my $user = shift;
249         my $oiduser = eval { IkiWiki::openiduser($user) };
250
251         if (defined $oiduser) {
252                 return ($user, $oiduser);
253         }
254         # FIXME: it'd be good to avoid having such a link for anonymous
255         # posts
256         else {
257                 return (IkiWiki::cgiurl(
258                                 do => 'commenter',
259                                 page => (length $config{userdir}
260                                         ? "$config{userdir}/$user"
261                                         : "$user")
262                         ), $user);
263         }
264 } # }}}
265
266 # Mostly cargo-culted from IkiWiki::plugin::editpage
267 sub sessioncgi ($$) { #{{{
268         my $cgi=shift;
269         my $session=shift;
270
271         my $do = $cgi->param('do');
272         return unless $do eq 'comment';
273
274         IkiWiki::decode_cgi_utf8($cgi);
275
276         eval q{use CGI::FormBuilder};
277         error($@) if $@;
278
279         my @buttons = (POST_COMMENT, PREVIEW, CANCEL);
280         my $form = CGI::FormBuilder->new(
281                 fields => [qw{do sid page subject editcontent type author url}],
282                 charset => 'utf-8',
283                 method => 'POST',
284                 required => [qw{editcontent}],
285                 javascript => 0,
286                 params => $cgi,
287                 action => $config{cgiurl},
288                 header => 0,
289                 table => 0,
290                 template => scalar IkiWiki::template_params('comments_form.tmpl'),
291                 # wtf does this do in editpage?
292                 wikiname => $config{wikiname},
293         );
294
295         IkiWiki::decode_form_utf8($form);
296         IkiWiki::run_hooks(formbuilder_setup => sub {
297                         shift->(title => "comment", form => $form, cgi => $cgi,
298                                 session => $session, buttons => \@buttons);
299                 });
300         IkiWiki::decode_form_utf8($form);
301
302         my $type = $form->param('type');
303         if (defined $type && length $type && $IkiWiki::hooks{htmlize}{$type}) {
304                 $type = IkiWiki::possibly_foolish_untaint($type);
305         }
306         else {
307                 $type = $config{default_pageext};
308         }
309         my @page_types;
310         if (exists $IkiWiki::hooks{htmlize}) {
311                 @page_types = grep { !/^_/ } keys %{$IkiWiki::hooks{htmlize}};
312         }
313
314         my $allow_author = $config{comments_allowauthor};
315
316         $form->field(name => 'do', type => 'hidden');
317         $form->field(name => 'sid', type => 'hidden', value => $session->id,
318                 force => 1);
319         $form->field(name => 'page', type => 'hidden');
320         $form->field(name => 'subject', type => 'text', size => 72);
321         $form->field(name => 'editcontent', type => 'textarea', rows => 10);
322         $form->field(name => "type", value => $type, force => 1,
323                 type => 'select', options => \@page_types);
324
325         $form->tmpl_param(username => $session->param('name'));
326
327         if ($allow_author and !defined $session->param('name')) {
328                 $form->tmpl_param(allowauthor => 1);
329                 $form->field(name => 'author', type => 'text', size => '40');
330                 $form->field(name => 'url', type => 'text', size => '40');
331         }
332         else {
333                 $form->tmpl_param(allowauthor => 0);
334                 $form->field(name => 'author', type => 'hidden', value => '',
335                         force => 1);
336                 $form->field(name => 'url', type => 'hidden', value => '',
337                         force => 1);
338         }
339
340         # The untaint is OK (as in editpage) because we're about to pass
341         # it to file_pruned anyway
342         my $page = $form->field('page');
343         $page = IkiWiki::possibly_foolish_untaint($page);
344         if (!defined $page || !length $page ||
345                 IkiWiki::file_pruned($page, $config{srcdir})) {
346                 error(gettext("bad page name"));
347         }
348
349         my $allow_directives = $config{comments_allowdirectives};
350         my $commit_comments = $config{comments_commit};
351         my $comments_pagename = $config{comments_pagename};
352
353         # FIXME: is this right? Or should we be using the candidate subpage
354         # (whatever that might mean) as the base URL?
355         my $baseurl = urlto($page, undef, 1);
356
357         $form->title(sprintf(gettext("commenting on %s"),
358                         IkiWiki::pagetitle($page)));
359
360         $form->tmpl_param('helponformattinglink',
361                 htmllink($page, $page, 'ikiwiki/formatting',
362                         noimageinline => 1,
363                         linktext => 'FormattingHelp'),
364                         allowdirectives => $allow_directives);
365
366         if ($form->submitted eq CANCEL) {
367                 # bounce back to the page they wanted to comment on, and exit.
368                 # CANCEL need not be considered in future
369                 IkiWiki::redirect($cgi, urlto($page, undef, 1));
370                 exit;
371         }
372
373         if (not exists $pagesources{$page}) {
374                 error(sprintf(gettext(
375                         "page '%s' doesn't exist, so you can't comment"),
376                         $page));
377         }
378
379         if (not pagespec_match($page, $config{comments_open_pagespec},
380                 location => $page)) {
381                 error(sprintf(gettext(
382                         "comments on page '%s' are closed"),
383                         $page));
384         }
385
386         IkiWiki::check_canedit($page . "[postcomment]", $cgi, $session);
387
388         my $editcontent = $form->field('editcontent') || '';
389         $editcontent =~ s/\r\n/\n/g;
390         $editcontent =~ s/\r/\n/g;
391
392         # FIXME: check that the wiki is locked right now, because
393         # if it's not, there are mad race conditions!
394
395         # FIXME: rather a simplistic way to make the comments...
396         my $i = 0;
397         my $file;
398         my $location;
399         do {
400                 $i++;
401                 $location = "$page/${comments_pagename}${i}";
402         } while (-e "$config{srcdir}/$location._comment");
403
404         my $anchor = "${comments_pagename}${i}";
405
406         $editcontent =~ s/"/\\"/g;
407         my $content = "[[!_comment format=$type\n";
408
409         # FIXME: handling of double quotes probably wrong?
410         if (defined $session->param('name')) {
411                 my $username = $session->param('name');
412                 $username =~ s/"/&quot;/g;
413                 $content .= " username=\"$username\"\n";
414         }
415         elsif (defined $ENV{REMOTE_ADDR}) {
416                 my $ip = $ENV{REMOTE_ADDR};
417                 if ($ip =~ m/^([.0-9]+)$/) {
418                         $content .= " ip=\"$1\"\n";
419                 }
420         }
421
422         if ($allow_author) {
423                 my $author = $form->field('author');
424                 if (length $author) {
425                         $author =~ s/"/&quot;/g;
426                         $content .= " claimedauthor=\"$author\"\n";
427                 }
428                 my $url = $form->field('url');
429                 if (length $url) {
430                         $url =~ s/"/&quot;/g;
431                         $content .= " url=\"$url\"\n";
432                 }
433         }
434
435         my $subject = $form->field('subject');
436         if (length $subject) {
437                 $subject =~ s/"/&quot;/g;
438                 $content .= " subject=\"$subject\"\n";
439         }
440
441         $content .= " date=\"" . decode_utf8(strftime('%Y-%m-%dT%H:%M:%SZ', gmtime)) . "\"\n";
442
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                         eval q{use IkiWiki::Plugin::inline};
553                         error($@) if $@;
554
555                         my @args = (
556                                 pages => "internal($page/${comments_pagename}*)",
557                                 template => 'comments_display',
558                                 show => 0,
559                                 reverse => 'yes',
560                                 page => $page,
561                                 destpage => $params{destpage},
562                                 feedfile => 'comments',
563                                 emptyfeeds => 'no',
564                         );
565                         $comments = IkiWiki::preprocess_inline(@args);
566                 }
567
568                 if (defined $comments && length $comments) {
569                         $template->param(comments => $comments);
570                 }
571
572                 if ($open) {
573                         my $commenturl = IkiWiki::cgiurl(do => 'comment',
574                                 page => $page);
575                         $template->param(commenturl => $commenturl);
576                 }
577         }
578
579         if ($template->query(name => 'commentuser')) {
580                 $template->param(commentuser =>
581                         $pagestate{$page}{comments}{commentuser});
582         }
583
584         if ($template->query(name => 'commentip')) {
585                 $template->param(commentip =>
586                         $pagestate{$page}{comments}{commentip});
587         }
588
589         if ($template->query(name => 'commentauthor')) {
590                 $template->param(commentauthor =>
591                         $pagestate{$page}{comments}{commentauthor});
592         }
593
594         if ($template->query(name => 'commentauthorurl')) {
595                 $template->param(commentauthorurl =>
596                         $pagestate{$page}{comments}{commentauthorurl});
597         }
598 } # }}}
599
600 package IkiWiki::PageSpec;
601
602 sub match_postcomment ($$;@) {
603         my $page = shift;
604         my $glob = shift;
605
606         unless ($page =~ s/\[postcomment\]$//) {
607                 return IkiWiki::FailReason->new("not posting a comment");
608         }
609         return match_glob($page, $glob);
610 }
611
612 1