]> sipb.mit.edu Git - ikiwiki.git/blob - IkiWiki/Plugin/smcvpostcomment.pm
smcvpostcomment: import other plugins lazily and remove unnecessary use of CGI
[ikiwiki.git] / IkiWiki / Plugin / smcvpostcomment.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::smcvpostcomment;
7
8 use warnings;
9 use strict;
10 use IkiWiki 2.00;
11
12 use constant PLUGIN => "smcvpostcomment";
13 use constant PREVIEW => "Preview";
14 use constant POST_COMMENT => "Post comment";
15 use constant CANCEL => "Cancel";
16
17 sub import { #{{{
18         hook(type => "getsetup", id => PLUGIN,  call => \&getsetup);
19         hook(type => "preprocess", id => PLUGIN, call => \&preprocess);
20         hook(type => "sessioncgi", id => PLUGIN, call => \&sessioncgi);
21         hook(type => "htmlize", id => "_".PLUGIN,
22                 call => \&IkiWiki::Plugin::mdwn::htmlize);
23         IkiWiki::loadplugin("inline");
24         IkiWiki::loadplugin("mdwn");
25 } # }}}
26
27 sub htmlize { # {{{
28         eval { use IkiWiki::Plugin::mdwn; };
29         error($@) if ($@);
30         return IkiWiki::Plugin::mdwn::htmlize(@_)
31 } # }}}
32
33 sub getsetup () { #{{{
34         return
35                 plugin => {
36                         safe => 1,
37                         rebuild => undef,
38                 },
39 } #}}}
40
41 # Somewhat based on IkiWiki::Plugin::inline blog posting support
42 sub preprocess (@) { #{{{
43         my %params=@_;
44
45         unless (length $config{cgiurl}) {
46                 error(sprintf (gettext("[[!%s plugin requires CGI enabled]]"),
47                         PLUGIN));
48         }
49
50         my $page = $params{page};
51         $pagestate{$page}{PLUGIN()}{comments} = 1;
52         $pagestate{$page}{PLUGIN()}{allowhtml} = IkiWiki::yesno($params{allowhtml});
53         $pagestate{$page}{PLUGIN()}{allowdirectives} = IkiWiki::yesno($params{allowdirectives});
54         $pagestate{$page}{PLUGIN()}{commit} = defined $params{commit}
55                 ? IkiWiki::yesno($params{commit})
56                 : 1;
57
58         my $formtemplate = IkiWiki::template(PLUGIN . "_embed.tmpl",
59                 blind_cache => 1);
60         $formtemplate->param(cgiurl => $config{cgiurl});
61         $formtemplate->param(page => $params{page});
62
63         if ($params{preview}) {
64                 $formtemplate->param("disabled" =>
65                         gettext('not available during Preview'));
66         }
67
68         debug("page $params{page} => destpage $params{destpage}");
69
70         my $posts = '';
71         unless (defined $params{inline} && !IkiWiki::yesno($params{inline})) {
72                 eval { use IkiWiki::Plugin::inline; };
73                 error($@) if ($@);
74                 my @args = (
75                         pages => "internal($params{page}/_comment_*)",
76                         template => PLUGIN . "_display",
77                         show => 0,
78                         reverse => "yes",
79                         # special stuff passed through
80                         page => $params{page},
81                         destpage => $params{destpage},
82                         preview => $params{preview},
83                 );
84                 push @args, atom => $params{atom} if defined $params{atom};
85                 push @args, rss => $params{rss} if defined $params{rss};
86                 push @args, feeds => $params{feeds} if defined $params{feeds};
87                 push @args, feedshow => $params{feedshow} if defined $params{feedshow};
88                 push @args, timeformat => $params{timeformat} if defined $params{timeformat};
89                 push @args, feedonly => $params{feedonly} if defined $params{feedonly};
90                 $posts = "\n" . IkiWiki::preprocess_inline(@args);
91         }
92
93         return $formtemplate->output . $posts;
94 } # }}}
95
96 # FIXME: logic taken from editpage, should be common code?
97 sub getcgiuser ($) { # {{{
98         my $session = shift;
99         my $user = $session->param('name');
100         $user = $ENV{REMOTE_ADDR} unless defined $user;
101         debug("getcgiuser() -> $user");
102         return $user;
103 } # }}}
104
105 # FIXME: logic adapted from recentchanges, should be common code?
106 sub linkuser ($) { # {{{
107         my $user = shift;
108         my $oiduser = eval { IkiWiki::openiduser($user) };
109
110         if (defined $oiduser) {
111                 return ($user, $oiduser);
112         }
113         else {
114                 my $page = bestlink('', (length $config{userdir}
115                                 ? "$config{userdir}/"
116                                 : "").$user);
117                 return (urlto($page, undef, 1), $user);
118         }
119 } # }}}
120
121 # FIXME: taken from IkiWiki::Plugin::editpage, should be common?
122 sub checksessionexpiry ($$) { # {{{
123         my $session = shift;
124         my $sid = shift;
125
126         if (defined $session->param("name")) {
127                 if (! defined $sid || $sid ne $session->id) {
128                         error(gettext("Your login session has expired."));
129                 }
130         }
131 } # }}}
132
133 # Mostly cargo-culted from IkiWiki::plugin::editpage
134 sub sessioncgi ($$) { #{{{
135         my $cgi=shift;
136         my $session=shift;
137
138         my $do = $cgi->param('do');
139         return unless $do eq PLUGIN;
140
141         IkiWiki::decode_cgi_utf8($cgi);
142
143         eval q{use CGI::FormBuilder};
144         error($@) if $@;
145
146         my @buttons = (POST_COMMENT, PREVIEW, CANCEL);
147         my $form = CGI::FormBuilder->new(
148                 fields => [qw{do sid page subject body}],
149                 charset => 'utf-8',
150                 method => 'POST',
151                 required => [qw{body}],
152                 javascript => 0,
153                 params => $cgi,
154                 action => $config{cgiurl},
155                 header => 0,
156                 table => 0,
157                 template => scalar IkiWiki::template_params(PLUGIN . '_form.tmpl'),
158                 # wtf does this do in editpage?
159                 wikiname => $config{wikiname},
160         );
161
162         IkiWiki::decode_form_utf8($form);
163         IkiWiki::run_hooks(formbuilder_setup => sub {
164                         shift->(title => PLUGIN, form => $form, cgi => $cgi,
165                                 session => $session, buttons => \@buttons);
166                 });
167         IkiWiki::decode_form_utf8($form);
168
169         $form->field(name => 'do', type => 'hidden');
170         $form->field(name => 'sid', type => 'hidden', value => $session->id,
171                 force => 1);
172         $form->field(name => 'page', type => 'hidden');
173         $form->field(name => 'subject', type => 'text', size => 72);
174         $form->field(name => 'body', type => 'textarea', rows => 5,
175                 cols => 80);
176
177         # The untaint is OK (as in editpage) because we're about to pass
178         # it to file_pruned anyway
179         my $page = $form->field('page');
180         $page = IkiWiki::possibly_foolish_untaint($page);
181         if (!defined $page || !length $page ||
182                 IkiWiki::file_pruned($page, $config{srcdir})) {
183                 error(gettext("bad page name"));
184         }
185
186         my $allow_directives = $pagestate{$page}{PLUGIN()}{allowdirectives};
187         my $allow_html = $pagestate{$page}{PLUGIN()}{allowdirectives};
188         my $commit_comments = defined $pagestate{$page}{PLUGIN()}{commit}
189                 ? $pagestate{$page}{PLUGIN()}{commit}
190                 : 1;
191
192         # FIXME: is this right? Or should we be using the candidate subpage
193         # (whatever that might mean) as the base URL?
194         my $baseurl = urlto($page, undef, 1);
195
196         $form->title(sprintf(gettext("commenting on %s"),
197                         IkiWiki::pagetitle($page)));
198
199         $form->tmpl_param('helponformattinglink',
200                 htmllink($page, $page, 'ikiwiki/formatting',
201                         noimageinline => 1,
202                         linktext => 'FormattingHelp'),
203                         allowhtml => $allow_html,
204                         allowdirectives => $allow_directives);
205
206         if (not exists $pagesources{$page}) {
207                 error(sprintf(gettext(
208                         "page '%s' doesn't exist, so you can't comment"),
209                         $page));
210         }
211         if (not $pagestate{$page}{PLUGIN()}{comments}) {
212                 error(sprintf(gettext(
213                         "comments are not enabled on page '%s'"),
214                         $page));
215         }
216
217         if ($form->submitted eq CANCEL) {
218                 # bounce back to the page they wanted to comment on, and exit.
219                 # CANCEL need not be considered in future
220                 IkiWiki::redirect($cgi, urlto($page, undef, 1));
221                 exit;
222         }
223
224         IkiWiki::check_canedit($page . "[" . PLUGIN . "]", $cgi, $session);
225
226         my ($authorurl, $author) = linkuser(getcgiuser($session));
227
228         my $body = $form->field('body') || '';
229         $body =~ s/\r\n/\n/g;
230         $body =~ s/\r/\n/g;
231         $body = "\n" if $body !~ /\n$/;
232
233         unless ($allow_directives) {
234                 # don't allow new-style directives at all
235                 $body =~ s/(^|[^\\])\[\[!/$1\\[[!/g;
236
237                 # don't allow [[ unless it begins an old-style
238                 # wikilink, if prefix_directives is off
239                 $body =~ s/(^|[^\\])\[\[(?![^\n\s\]+]\]\])/$1\\[[!/g
240                         unless $config{prefix_directives};
241         }
242
243         unless ($allow_html) {
244                 $body =~ s/&(\w|#)/&amp;$1/g;
245                 $body =~ s/</&lt;/g;
246                 $body =~ s/>/&gt;/g;
247         }
248
249         # In this template, the [[!meta]] directives should stay at the end,
250         # so that they will override anything the user specifies. (For
251         # instance, [[!meta author="I can fake the author"]]...)
252         my $content_tmpl = template(PLUGIN . '_comment.tmpl');
253         $content_tmpl->param(author => $author);
254         $content_tmpl->param(authorurl => $authorurl);
255         $content_tmpl->param(subject => $form->field('subject'));
256         $content_tmpl->param(body => $body);
257
258         my $content = $content_tmpl->output;
259
260         # This is essentially a simplified version of editpage:
261         # - the user does not control the page that's created, only the parent
262         # - it's always a create operation, never an edit
263         # - this means that conflicts should never happen
264         # - this means that if they do, rocks fall and everyone dies
265
266         if ($form->submitted eq PREVIEW) {
267                 # $fake is a location that has the same number of slashes
268                 # as the eventual location of this comment.
269                 my $fake = "$page/_" . PLUGIN . "hypothetical";
270                 my $preview = IkiWiki::htmlize($fake, $page, 'mdwn',
271                                 IkiWiki::linkify($page, $page,
272                                         IkiWiki::preprocess($page, $page,
273                                                 IkiWiki::filter($fake, $page,
274                                                         $content),
275                                                 0, 1)));
276                 IkiWiki::run_hooks(format => sub {
277                                 $preview = shift->(page => $page,
278                                         content => $preview);
279                         });
280
281                 my $template = template(PLUGIN . "_display.tmpl");
282                 $template->param(content => $preview);
283                 $template->param(title => $form->field('subject'));
284                 $template->param(ctime => displaytime(time));
285                 $template->param(author => $author);
286                 $template->param(authorurl => $authorurl);
287
288                 $form->tmpl_param(page_preview => $template->output);
289         }
290         else {
291                 $form->tmpl_param(page_preview => "");
292         }
293
294         if ($form->submitted eq POST_COMMENT && $form->validate) {
295                 # Let's get posting. We don't check_canedit here because
296                 # that somewhat defeats the point of this plugin.
297
298                 checksessionexpiry($session, $cgi->param('sid'));
299
300                 # FIXME: check that the wiki is locked right now, because
301                 # if it's not, there are mad race conditions!
302
303                 # FIXME: rather a simplistic way to make the comments...
304                 my $i = 0;
305                 my $file;
306                 do {
307                         $i++;
308                         $file = "$page/_comment_${i}._" . PLUGIN;
309                 } while (-e "$config{srcdir}/$file");
310
311                 # FIXME: could probably do some sort of graceful retry
312                 # if I could be bothered
313                 writefile($file, $config{srcdir}, $content);
314
315                 my $conflict;
316
317                 if ($config{rcs} and $commit_comments) {
318                         my $message = gettext("Added a comment");
319                         if (defined $form->field('subject') &&
320                                 length $form->field('subject')) {
321                                 $message .= ": ".$form->field('subject');
322                         }
323
324                         IkiWiki::rcs_add($file);
325                         IkiWiki::disable_commit_hook();
326                         $conflict = IkiWiki::rcs_commit_staged($message,
327                                 $session->param('name'), $ENV{REMOTE_ADDR});
328                         IkiWiki::enable_commit_hook();
329                         IkiWiki::rcs_update();
330                 }
331
332                 # Now we need a refresh
333                 require IkiWiki::Render;
334                 IkiWiki::refresh();
335                 IkiWiki::saveindex();
336
337                 # this should never happen, unless a committer deliberately
338                 # breaks it or something
339                 error($conflict) if defined $conflict;
340
341                 # Bounce back to where we were, but defeat broken caches
342                 my $anticache = "?updated=$page/_comment_$i";
343                 IkiWiki::redirect($cgi, urlto($page, undef, 1).$anticache);
344         }
345         else {
346                 IkiWiki::showform ($form, \@buttons, $session, $cgi,
347                         forcebaseurl => $baseurl);
348         }
349
350         exit;
351 } #}}}
352
353 package IkiWiki::PageSpec;
354
355 sub match_smcvpostcomment ($$;@) {
356         my $page = shift;
357         my $glob = shift;
358
359         unless ($page =~ s/\[smcvpostcomment\]$//) {
360                 return IkiWiki::FailReason->new("not posting a comment");
361         }
362         return match_glob($page, $glob);
363 }
364
365 1