comments: Remove some dead code
[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 sub preprocess { # {{{
34         my %params = @_;
35         my $page = $params{page};
36
37         my $format = $params{format};
38         if (defined $format && !exists $IkiWiki::hooks{htmlize}{$format}) {
39                 error(sprintf(gettext("unsupported page format %s"), $format));
40         }
41
42         my $content = $params{content};
43         if (!defined $content) {
44                 error(gettext("comment must have content"));
45         }
46         $content =~ s/\\"/"/g;
47
48         $content = IkiWiki::filter($page, $params{destpage}, $content);
49
50         if ($config{comments_allowdirectives}) {
51                 $content = IkiWiki::preprocess($page, $params{destpage},
52                         $content);
53         }
54
55         # no need to bother with htmlize if it's just HTML
56         $content = IkiWiki::htmlize($page, $params{destpage}, $format,
57                 $content) if defined $format;
58
59         IkiWiki::run_hooks(sanitize => sub {
60                 $content = shift->(
61                         page => $page,
62                         destpage => $params{destpage},
63                         content => $content,
64                 );
65         });
66
67         # override any metadata
68
69         if (defined $params{username}) {
70                 my ($authorurl, $author) = linkuser($params{username});
71                 $pagestate{$page}{meta}{author} = $author;
72                 $pagestate{$page}{meta}{authorurl} = $authorurl;
73         }
74         elsif (defined $params{ip}) {
75                 $pagestate{$page}{meta}{author} = sprintf(
76                         gettext("Anonymous (IP: %s)"),
77                         $params{ip});
78                 delete $pagestate{$page}{meta}{authorurl};
79         }
80         else {
81                 $pagestate{$page}{meta}{author} = gettext("Anonymous");
82                 delete $pagestate{$page}{meta}{authorurl};
83         }
84
85         if (defined $params{subject}) {
86                 $pagestate{$page}{meta}{title} = $params{subject};
87         }
88         else {
89                 delete $pagestate{$page}{meta}{title};
90         }
91
92         my $baseurl = urlto($params{destpage}, undef, 1);
93         my $anchor = "";
94         my $comments_pagename = $config{comments_pagename};
95         if ($params{page} =~ m/\/(\Q${comments_pagename}\E\d+)$/) {
96                 $anchor = $1;
97         }
98         $pagestate{$page}{meta}{permalink} = "${baseurl}#${anchor}";
99
100         eval q{use Date::Parse};
101         if (! $@) {
102                 my $time = str2time($params{date});
103                 $IkiWiki::pagectime{$page} = $time if defined $time;
104         }
105
106         # FIXME: hard-coded HTML (although it's just to set an ID)
107         return "<div id=\"$anchor\">$content</div>" if $anchor;
108         return $content;
109 } # }}}
110
111 sub getsetup () { #{{{
112         return
113                 plugin => {
114                         safe => 1,
115                         rebuild => 1,
116                 },
117                 # Pages where comments are shown, but new comments are not
118                 # allowed, will show "Comments are closed".
119                 comments_shown_pagespec => {
120                         type => 'pagespec',
121                         example => 'blog/*',
122                         default => '',
123                         description => 'PageSpec for pages where comments will be shown inline',
124                         link => 'ikiwiki/PageSpec',
125                         safe => 1,
126                         rebuild => 1,
127                 },
128                 comments_open_pagespec => {
129                         type => 'pagespec',
130                         example => 'blog/* and created_after(close_old_comments)',
131                         default => '',
132                         description => 'PageSpec for pages where new comments can be posted',
133                         link => 'ikiwiki/PageSpec',
134                         safe => 1,
135                         rebuild => 1,
136                 },
137                 comments_pagename => {
138                         type => 'string',
139                         example => 'comment_',
140                         default => 'comment_',
141                         description => 'Base name for comments, e.g. "comment_" for pages like "sandbox/comment_12"',
142                         safe => 0, # manual page moving will required
143                         rebuild => undef,
144                 },
145                 comments_allowdirectives => {
146                         type => 'boolean',
147                         default => 0,
148                         example => 0,
149                         description => 'Allow directives in newly posted comments?',
150                         safe => 1,
151                         rebuild => 0,
152                 },
153                 comments_commit => {
154                         type => 'boolean',
155                         example => 1,
156                         default => 1,
157                         description => 'commit comments to the VCS',
158                         # old uncommitted comments are likely to cause
159                         # confusion if this is changed
160                         safe => 0,
161                         rebuild => 0,
162                 },
163 } #}}}
164
165 sub checkconfig () { #{{{
166         $config{comments_commit} = 1 unless defined $config{comments_commit};
167         $config{comments_pagename} = 'comment_'
168                 unless defined $config{comments_pagename};
169 } #}}}
170
171 # This is exactly the same as recentchanges_link :-(
172 sub linkcgi ($) { #{{{
173         my $cgi=shift;
174         if (defined $cgi->param('do') && $cgi->param('do') eq "commenter") {
175
176                 my $page=decode_utf8($cgi->param("page"));
177                 if (!defined $page) {
178                         error("missing page parameter");
179                 }
180
181                 IkiWiki::loadindex();
182
183                 my $link=bestlink("", $page);
184                 if (! length $link) {
185                         print "Content-type: text/html\n\n";
186                         print IkiWiki::misctemplate(gettext(gettext("missing page")),
187                                 "<p>".
188                                 sprintf(gettext("The page %s does not exist."),
189                                         htmllink("", "", $page)).
190                                 "</p>");
191                 }
192                 else {
193                         IkiWiki::redirect($cgi, urlto($link, undef, 1));
194                 }
195
196                 exit;
197         }
198 }
199
200 # FIXME: basically the same logic as recentchanges
201 # returns (author URL, pretty-printed version)
202 sub linkuser ($) { # {{{
203         my $user = shift;
204         my $oiduser = eval { IkiWiki::openiduser($user) };
205
206         if (defined $oiduser) {
207                 return ($user, $oiduser);
208         }
209         # FIXME: it'd be good to avoid having such a link for anonymous
210         # posts
211         else {
212                 return (IkiWiki::cgiurl(
213                                 do => 'commenter',
214                                 page => (length $config{userdir}
215                                         ? "$config{userdir}/$user"
216                                         : "$user")
217                         ), $user);
218         }
219 } # }}}
220
221 # Mostly cargo-culted from IkiWiki::plugin::editpage
222 sub sessioncgi ($$) { #{{{
223         my $cgi=shift;
224         my $session=shift;
225
226         my $do = $cgi->param('do');
227         return unless $do eq 'comment';
228
229         IkiWiki::decode_cgi_utf8($cgi);
230
231         eval q{use CGI::FormBuilder};
232         error($@) if $@;
233
234         my @buttons = (POST_COMMENT, PREVIEW, CANCEL);
235         my $form = CGI::FormBuilder->new(
236                 fields => [qw{do sid page subject editcontent type}],
237                 charset => 'utf-8',
238                 method => 'POST',
239                 required => [qw{editcontent}],
240                 javascript => 0,
241                 params => $cgi,
242                 action => $config{cgiurl},
243                 header => 0,
244                 table => 0,
245                 template => scalar IkiWiki::template_params('comments_form.tmpl'),
246                 # wtf does this do in editpage?
247                 wikiname => $config{wikiname},
248         );
249
250         IkiWiki::decode_form_utf8($form);
251         IkiWiki::run_hooks(formbuilder_setup => sub {
252                         shift->(title => "comment", form => $form, cgi => $cgi,
253                                 session => $session, buttons => \@buttons);
254                 });
255         IkiWiki::decode_form_utf8($form);
256
257         my $type = $form->param('type');
258         if (defined $type && length $type && $IkiWiki::hooks{htmlize}{$type}) {
259                 $type = possibly_foolish_untaint($type);
260         }
261         else {
262                 $type = $config{default_pageext};
263         }
264         my @page_types;
265         if (exists $IkiWiki::hooks{htmlize}) {
266                 @page_types = grep { !/^_/ } keys %{$IkiWiki::hooks{htmlize}};
267         }
268
269         $form->field(name => 'do', type => 'hidden');
270         $form->field(name => 'sid', type => 'hidden', value => $session->id,
271                 force => 1);
272         $form->field(name => 'page', type => 'hidden');
273         $form->field(name => 'subject', type => 'text', size => 72);
274         $form->field(name => 'editcontent', type => 'textarea', rows => 10);
275         $form->field(name => "type", value => $type, force => 1,
276                 type => 'select', options => \@page_types);
277
278         # The untaint is OK (as in editpage) because we're about to pass
279         # it to file_pruned anyway
280         my $page = $form->field('page');
281         $page = IkiWiki::possibly_foolish_untaint($page);
282         if (!defined $page || !length $page ||
283                 IkiWiki::file_pruned($page, $config{srcdir})) {
284                 error(gettext("bad page name"));
285         }
286
287         my $allow_directives = $config{comments_allowdirectives};
288         my $commit_comments = $config{comments_commit};
289         my $comments_pagename = $config{comments_pagename};
290
291         # FIXME: is this right? Or should we be using the candidate subpage
292         # (whatever that might mean) as the base URL?
293         my $baseurl = urlto($page, undef, 1);
294
295         $form->title(sprintf(gettext("commenting on %s"),
296                         IkiWiki::pagetitle($page)));
297
298         $form->tmpl_param('helponformattinglink',
299                 htmllink($page, $page, 'ikiwiki/formatting',
300                         noimageinline => 1,
301                         linktext => 'FormattingHelp'),
302                         allowdirectives => $allow_directives);
303
304         if ($form->submitted eq CANCEL) {
305                 # bounce back to the page they wanted to comment on, and exit.
306                 # CANCEL need not be considered in future
307                 IkiWiki::redirect($cgi, urlto($page, undef, 1));
308                 exit;
309         }
310
311         if (not exists $pagesources{$page}) {
312                 error(sprintf(gettext(
313                         "page '%s' doesn't exist, so you can't comment"),
314                         $page));
315         }
316
317         if (not pagespec_match($page, $config{comments_open_pagespec},
318                 location => $page)) {
319                 error(sprintf(gettext(
320                         "comments on page '%s' are closed"),
321                         $page));
322         }
323
324         IkiWiki::check_canedit($page . "[postcomment]", $cgi, $session);
325
326         my $editcontent = $form->field('editcontent') || '';
327         $editcontent =~ s/\r\n/\n/g;
328         $editcontent =~ s/\r/\n/g;
329
330         # FIXME: check that the wiki is locked right now, because
331         # if it's not, there are mad race conditions!
332
333         # FIXME: rather a simplistic way to make the comments...
334         my $i = 0;
335         my $file;
336         my $location;
337         do {
338                 $i++;
339                 $location = "$page/${comments_pagename}${i}";
340         } while (-e "$config{srcdir}/$location._comment");
341
342         my $anchor = "${comments_pagename}${i}";
343
344         $editcontent =~ s/"/\\"/g;
345         my $content = "[[!comment format=$type\n";
346
347         # FIXME: handling of double quotes probably wrong?
348         if (defined $session->param('name')) {
349                 my $username = $session->param('name');
350                 $username =~ s/"/&quot;/g;
351                 $content .= " username=\"$username\"\n";
352         }
353         elsif (defined $ENV{REMOTE_ADDR}) {
354                 my $ip = $ENV{REMOTE_ADDR};
355                 if ($ip =~ m/^([.0-9]+)$/) {
356                         $content .= " ip=\"$1\"\n";
357                 }
358         }
359
360         my $subject = $form->field('subject');
361         $subject =~ s/"/&quot;/g;
362         $content .= " subject=\"$subject\"\n";
363
364         $content .= " date=\"" . IkiWiki::formattime(time, '%X %x') . "\"\n";
365
366         $content .= " content=\"\"\"\n$editcontent\n\"\"\"]]\n";
367
368         # This is essentially a simplified version of editpage:
369         # - the user does not control the page that's created, only the parent
370         # - it's always a create operation, never an edit
371         # - this means that conflicts should never happen
372         # - this means that if they do, rocks fall and everyone dies
373
374         if ($form->submitted eq PREVIEW) {
375                 my $preview = IkiWiki::htmlize($location, $page, '_comment',
376                                 IkiWiki::linkify($page, $page,
377                                         IkiWiki::preprocess($page, $page,
378                                                 IkiWiki::filter($location,
379                                                         $page, $content),
380                                                 0, 1)));
381                 IkiWiki::run_hooks(format => sub {
382                                 $preview = shift->(page => $page,
383                                         content => $preview);
384                         });
385
386                 my $template = template("comments_display.tmpl");
387                 $template->param(content => $preview);
388                 $template->param(title => $form->field('subject'));
389                 $template->param(ctime => displaytime(time));
390
391                 $form->tmpl_param(page_preview => $template->output);
392         }
393         else {
394                 $form->tmpl_param(page_preview => "");
395         }
396
397         if ($form->submitted eq POST_COMMENT && $form->validate) {
398                 my $file = "$location._comment";
399
400                 IkiWiki::checksessionexpiry($session, $cgi->param('sid'));
401
402                 # FIXME: could probably do some sort of graceful retry
403                 # on error? Would require significant unwinding though
404                 writefile($file, $config{srcdir}, $content);
405
406                 my $conflict;
407
408                 if ($config{rcs} and $commit_comments) {
409                         my $message = gettext("Added a comment");
410                         if (defined $form->field('subject') &&
411                                 length $form->field('subject')) {
412                                 $message = sprintf(
413                                         gettext("Added a comment: %s"),
414                                         $form->field('subject'));
415                         }
416
417                         IkiWiki::rcs_add($file);
418                         IkiWiki::disable_commit_hook();
419                         $conflict = IkiWiki::rcs_commit_staged($message,
420                                 $session->param('name'), $ENV{REMOTE_ADDR});
421                         IkiWiki::enable_commit_hook();
422                         IkiWiki::rcs_update();
423                 }
424
425                 # Now we need a refresh
426                 require IkiWiki::Render;
427                 IkiWiki::refresh();
428                 IkiWiki::saveindex();
429
430                 # this should never happen, unless a committer deliberately
431                 # breaks it or something
432                 error($conflict) if defined $conflict;
433
434                 # Bounce back to where we were, but defeat broken caches
435                 my $anticache = "?updated=$page/${comments_pagename}${i}";
436                 IkiWiki::redirect($cgi, urlto($page, undef, 1).$anticache);
437         }
438         else {
439                 IkiWiki::showform ($form, \@buttons, $session, $cgi,
440                         forcebaseurl => $baseurl);
441         }
442
443         exit;
444 } #}}}
445
446 sub pagetemplate (@) { #{{{
447         my %params = @_;
448
449         my $page = $params{page};
450         my $template = $params{template};
451
452         if ($template->query(name => 'comments')) {
453                 my $comments = undef;
454
455                 my $comments_pagename = $config{comments_pagename};
456
457                 my $open = 0;
458                 my $shown = pagespec_match($page,
459                         $config{comments_shown_pagespec},
460                         location => $page);
461
462                 if (pagespec_match($page, "*/${comments_pagename}*",
463                                 location => $page)) {
464                         $shown = 0;
465                         $open = 0;
466                 }
467
468                 if (length $config{cgiurl}) {
469                         $open = pagespec_match($page,
470                                 $config{comments_open_pagespec},
471                                 location => $page);
472                 }
473
474                 if ($shown) {
475                         eval q{use IkiWiki::Plugin::inline};
476                         error($@) if $@;
477
478                         my @args = (
479                                 pages => "internal($page/${comments_pagename}*)",
480                                 template => 'comments_display',
481                                 show => 0,
482                                 reverse => 'yes',
483                                 page => $page,
484                                 destpage => $params{destpage},
485                         );
486                         $comments = IkiWiki::preprocess_inline(@args);
487                 }
488
489                 if (defined $comments && length $comments) {
490                         $template->param(comments => $comments);
491                 }
492
493                 if ($open) {
494                         my $commenturl = IkiWiki::cgiurl(do => 'comment',
495                                 page => $page);
496                         $template->param(commenturl => $commenturl);
497                 }
498         }
499 } # }}}
500
501 package IkiWiki::PageSpec;
502
503 sub match_postcomment ($$;@) {
504         my $page = shift;
505         my $glob = shift;
506
507         unless ($page =~ s/\[postcomment\]$//) {
508                 return IkiWiki::FailReason->new("not posting a comment");
509         }
510         return match_glob($page, $glob);
511 }
512
513 1