editpage: Be more aggressive (and less buggy) about cleaning up temporary files rende...
[ikiwiki.git] / IkiWiki / Plugin / editpage.pm
1 #!/usr/bin/perl
2 package IkiWiki::Plugin::editpage;
3
4 use warnings;
5 use strict;
6 use IkiWiki;
7 use open qw{:utf8 :std};
8
9 sub import { #{{{
10         hook(type => "getsetup", id => "editpage", call => \&getsetup);
11         hook(type => "refresh", id => "editpage", call => \&refresh);
12         hook(type => "sessioncgi", id => "editpage", call => \&IkiWiki::cgi_editpage);
13 } # }}}
14
15 sub getsetup () { #{{{
16         return
17                 plugin => {
18                         safe => 1,
19                         rebuild => 1,
20                 },
21 } #}}}
22
23 sub refresh () {
24         if (exists $wikistate{editpage} && exists $wikistate{editpage}{previews}) {
25                 # Expire old preview files after one hour.
26                 my $expire=time - (60 * 60);
27
28                 my @previews;
29                 foreach my $file (@{$wikistate{editpage}{previews}}) {
30                         my $mtime=(stat("$config{destdir}/$file"))[9];
31                         if (defined $mtime && $mtime <= $expire) {
32                                 debug(sprintf(gettext("removing old preview %s"), $file));
33                                 IkiWiki::prune("$config{destdir}/$file");
34                         }
35                         elsif (defined $mtime) {
36                                 push @previews, $file;
37                         }
38                 }
39                 $wikistate{editpage}{previews}=\@previews;
40         }
41 }
42
43 # Back to ikiwiki namespace for the rest, this code is very much
44 # internal to ikiwiki even though it's separated into a plugin,
45 # and other plugins use the functions below.
46 package IkiWiki;
47
48 sub check_canedit ($$$;$) { #{{{
49         my $page=shift;
50         my $q=shift;
51         my $session=shift;
52         my $nonfatal=shift;
53         
54         my $canedit;
55         run_hooks(canedit => sub {
56                 return if defined $canedit;
57                 my $ret=shift->($page, $q, $session);
58                 if (defined $ret) {
59                         if ($ret eq "") {
60                                 $canedit=1;
61                         }
62                         elsif (ref $ret eq 'CODE') {
63                                 $ret->() unless $nonfatal;
64                                 $canedit=0;
65                         }
66                         elsif (defined $ret) {
67                                 error($ret) unless $nonfatal;
68                                 $canedit=0;
69                         }
70                 }
71         });
72         return $canedit;
73 } #}}}
74
75 sub cgi_editpage ($$) { #{{{
76         my $q=shift;
77         my $session=shift;
78         
79         my $do=$q->param('do');
80         return unless $do eq 'create' || $do eq 'edit';
81
82         decode_cgi_utf8($q);
83
84         my @fields=qw(do rcsinfo subpage from page type editcontent comments);
85         my @buttons=("Save Page", "Preview", "Cancel");
86         eval q{use CGI::FormBuilder};
87         error($@) if $@;
88         my $form = CGI::FormBuilder->new(
89                 fields => \@fields,
90                 charset => "utf-8",
91                 method => 'POST',
92                 required => [qw{editcontent}],
93                 javascript => 0,
94                 params => $q,
95                 action => $config{cgiurl},
96                 header => 0,
97                 table => 0,
98                 template => scalar template_params("editpage.tmpl"),
99                 wikiname => $config{wikiname},
100         );
101         
102         decode_form_utf8($form);
103         run_hooks(formbuilder_setup => sub {
104                 shift->(form => $form, cgi => $q, session => $session,
105                         buttons => \@buttons);
106         });
107         decode_form_utf8($form);
108         
109         # This untaint is safe because we check file_pruned and
110         # wiki_file_regexp.
111         my ($page)=$form->field('page')=~/$config{wiki_file_regexp}/;
112         $page=possibly_foolish_untaint($page);
113         my $absolute=($page =~ s#^/+##);
114         if (! defined $page || ! length $page ||
115             file_pruned($page, $config{srcdir})) {
116                 error("bad page name");
117         }
118
119         my $baseurl = urlto($page, undef, 1);
120
121         my $from;
122         if (defined $form->field('from')) {
123                 ($from)=$form->field('from')=~/$config{wiki_file_regexp}/;
124         }
125         
126         my $file;
127         my $type;
128         if (exists $pagesources{$page} && $form->field("do") ne "create") {
129                 $file=$pagesources{$page};
130                 $type=pagetype($file);
131                 if (! defined $type || $type=~/^_/) {
132                         error(sprintf(gettext("%s is not an editable page"), $page));
133                 }
134                 if (! $form->submitted) {
135                         $form->field(name => "rcsinfo",
136                                 value => rcs_prepedit($file), force => 1);
137                 }
138                 $form->field(name => "editcontent", validate => '/.*/');
139         }
140         else {
141                 $type=$form->param('type');
142                 if (defined $type && length $type && $hooks{htmlize}{$type}) {
143                         $type=possibly_foolish_untaint($type);
144                 }
145                 elsif (defined $from && exists $pagesources{$from}) {
146                         # favor the type of linking page
147                         $type=pagetype($pagesources{$from});
148                 }
149                 $type=$config{default_pageext} unless defined $type;
150                 $file=$page.".".$type;
151                 if (! $form->submitted) {
152                         $form->field(name => "rcsinfo", value => "", force => 1);
153                 }
154                 $form->field(name => "editcontent", validate => '/.+/');
155         }
156
157         $form->field(name => "do", type => 'hidden');
158         $form->field(name => "sid", type => "hidden", value => $session->id,
159                 force => 1);
160         $form->field(name => "from", type => 'hidden');
161         $form->field(name => "rcsinfo", type => 'hidden');
162         $form->field(name => "subpage", type => 'hidden');
163         $form->field(name => "page", value => $page, force => 1);
164         $form->field(name => "type", value => $type, force => 1);
165         $form->field(name => "comments", type => "text", size => 80);
166         $form->field(name => "editcontent", type => "textarea", rows => 20,
167                 cols => 80);
168         $form->tmpl_param("can_commit", $config{rcs});
169         $form->tmpl_param("indexlink", indexlink());
170         $form->tmpl_param("helponformattinglink",
171                 htmllink($page, $page, "ikiwiki/formatting",
172                         noimageinline => 1,
173                         linktext => "FormattingHelp"));
174         
175         if ($form->submitted eq "Cancel") {
176                 if ($form->field("do") eq "create" && defined $from) {
177                         redirect($q, urlto($from, undef, 1));
178                 }
179                 elsif ($form->field("do") eq "create") {
180                         redirect($q, $config{url});
181                 }
182                 else {
183                         redirect($q, urlto($page, undef, 1));
184                 }
185                 exit;
186         }
187         elsif ($form->submitted eq "Preview") {
188                 my $new=not exists $pagesources{$page};
189                 if ($new) {
190                         # temporarily record its type
191                         $pagesources{$page}=$page.".".$type;
192                 }
193                 my %wasrendered=map { $_ => 1 } @{$renderedfiles{$page}};
194
195                 my $content=$form->field('editcontent');
196
197                 run_hooks(editcontent => sub {
198                         $content=shift->(
199                                 content => $content,
200                                 page => $page,
201                                 cgi => $q,
202                                 session => $session,
203                         );
204                 });
205                 my $preview=htmlize($page, $page, $type,
206                         linkify($page, $page,
207                         preprocess($page, $page,
208                         filter($page, $page, $content), 0, 1)));
209                 run_hooks(format => sub {
210                         $preview=shift->(
211                                 page => $page,
212                                 content => $preview,
213                         );
214                 });
215                 $form->tmpl_param("page_preview", $preview);
216                 
217                 if ($new) {
218                         delete $pagesources{$page};
219                 }
220
221                 # Previewing may have created files on disk.
222                 # Keep a list of these to be deleted later.
223                 my %previews = map { $_ => 1 } @{$wikistate{editpage}{previews}};
224                 foreach my $file (@{$renderedfiles{$page}}) {
225                         $previews{$file}=1 unless $wasrendered{$file};
226                 }
227                 @{$wikistate{editpage}{previews}} = keys %previews;
228                 saveindex();
229         }
230         elsif ($form->submitted eq "Save Page") {
231                 $form->tmpl_param("page_preview", "");
232         }
233         
234         if ($form->submitted ne "Save Page" || ! $form->validate) {
235                 if ($form->field("do") eq "create") {
236                         my @page_locs;
237                         my $best_loc;
238                         if (! defined $from || ! length $from ||
239                             $from ne $form->field('from') ||
240                             file_pruned($from, $config{srcdir}) ||
241                             $from=~/^\// || 
242                             $absolute ||
243                             $form->submitted eq "Preview") {
244                                 @page_locs=$best_loc=$page;
245                         }
246                         else {
247                                 my $dir=$from."/";
248                                 $dir=~s![^/]+/+$!!;
249                                 
250                                 if ((defined $form->field('subpage') && length $form->field('subpage')) ||
251                                     $page eq gettext('discussion')) {
252                                         $best_loc="$from/$page";
253                                 }
254                                 else {
255                                         $best_loc=$dir.$page;
256                                 }
257                                 
258                                 push @page_locs, $dir.$page;
259                                 push @page_locs, "$from/$page";
260                                 while (length $dir) {
261                                         $dir=~s![^/]+/+$!!;
262                                         push @page_locs, $dir.$page;
263                                 }
264                         
265                                 push @page_locs, "$config{userdir}/$page"
266                                         if length $config{userdir};
267                         }
268
269                         @page_locs = grep {
270                                 ! exists $pagecase{lc $_}
271                         } @page_locs;
272                         if (! @page_locs) {
273                                 # hmm, someone else made the page in the
274                                 # meantime?
275                                 if ($form->submitted eq "Preview") {
276                                         # let them go ahead with the edit
277                                         # and resolve the conflict at save
278                                         # time
279                                         @page_locs=$page;
280                                 }
281                                 else {
282                                         redirect($q, urlto($page, undef, 1));
283                                         exit;
284                                 }
285                         }
286
287                         my @editable_locs = grep {
288                                 check_canedit($_, $q, $session, 1)
289                         } @page_locs;
290                         if (! @editable_locs) {
291                                 # let it throw an error this time
292                                 map { check_canedit($_, $q, $session) } @page_locs;
293                         }
294                         
295                         my @page_types;
296                         if (exists $hooks{htmlize}) {
297                                 @page_types=grep { !/^_/ }
298                                         keys %{$hooks{htmlize}};
299                         }
300                         
301                         $form->tmpl_param("page_select", 1);
302                         $form->field(name => "page", type => 'select',
303                                 options => [ map { [ $_, pagetitle($_, 1) ] } @editable_locs ],
304                                 value => $best_loc);
305                         $form->field(name => "type", type => 'select',
306                                 options => \@page_types);
307                         $form->title(sprintf(gettext("creating %s"), pagetitle($page)));
308                         
309                 }
310                 elsif ($form->field("do") eq "edit") {
311                         check_canedit($page, $q, $session);
312                         if (! defined $form->field('editcontent') || 
313                             ! length $form->field('editcontent')) {
314                                 my $content="";
315                                 if (exists $pagesources{$page}) {
316                                         $content=readfile(srcfile($pagesources{$page}));
317                                         $content=~s/\n/\r\n/g;
318                                 }
319                                 $form->field(name => "editcontent", value => $content,
320                                         force => 1);
321                         }
322                         $form->tmpl_param("page_select", 0);
323                         $form->field(name => "page", type => 'hidden');
324                         $form->field(name => "type", type => 'hidden');
325                         $form->title(sprintf(gettext("editing %s"), pagetitle($page)));
326                 }
327                 
328                 showform($form, \@buttons, $session, $q, forcebaseurl => $baseurl);
329         }
330         else {
331                 # save page
332                 check_canedit($page, $q, $session);
333         
334                 # The session id is stored on the form and checked to
335                 # guard against CSRF. But only if the user is logged in,
336                 # as anonok can allow anonymous edits.
337                 if (defined $session->param("name")) {
338                         my $sid=$q->param('sid');
339                         if (! defined $sid || $sid ne $session->id) {
340                                 error(gettext("Your login session has expired."));
341                         }
342                 }
343
344                 my $exists=-e "$config{srcdir}/$file";
345
346                 if ($form->field("do") ne "create" && ! $exists &&
347                     ! defined srcfile($file, 1)) {
348                         $form->tmpl_param("message", template("editpagegone.tmpl")->output);
349                         $form->field(name => "do", value => "create", force => 1);
350                         $form->tmpl_param("page_select", 0);
351                         $form->field(name => "page", type => 'hidden');
352                         $form->field(name => "type", type => 'hidden');
353                         $form->title(sprintf(gettext("editing %s"), $page));
354                         showform($form, \@buttons, $session, $q, forcebaseurl => $baseurl);
355                         exit;
356                 }
357                 elsif ($form->field("do") eq "create" && $exists) {
358                         $form->tmpl_param("message", template("editcreationconflict.tmpl")->output);
359                         $form->field(name => "do", value => "edit", force => 1);
360                         $form->tmpl_param("page_select", 0);
361                         $form->field(name => "page", type => 'hidden');
362                         $form->field(name => "type", type => 'hidden');
363                         $form->title(sprintf(gettext("editing %s"), $page));
364                         $form->field("editcontent", 
365                                 value => readfile("$config{srcdir}/$file").
366                                          "\n\n\n".$form->field("editcontent"),
367                                 force => 1);
368                         showform($form, \@buttons, $session, $q, forcebaseurl => $baseurl);
369                         exit;
370                 }
371                 
372                 my $content=$form->field('editcontent');
373                 run_hooks(editcontent => sub {
374                         $content=shift->(
375                                 content => $content,
376                                 page => $page,
377                                 cgi => $q,
378                                 session => $session,
379                         );
380                 });
381                 $content=~s/\r\n/\n/g;
382                 $content=~s/\r/\n/g;
383                 $content.="\n" if $content !~ /\n$/;
384
385                 $config{cgi}=0; # avoid cgi error message
386                 eval { writefile($file, $config{srcdir}, $content) };
387                 $config{cgi}=1;
388                 if ($@) {
389                         $form->field(name => "rcsinfo", value => rcs_prepedit($file),
390                                 force => 1);
391                         my $mtemplate=template("editfailedsave.tmpl");
392                         $mtemplate->param(error_message => $@);
393                         $form->tmpl_param("message", $mtemplate->output);
394                         $form->field("editcontent", value => $content, force => 1);
395                         $form->tmpl_param("page_select", 0);
396                         $form->field(name => "page", type => 'hidden');
397                         $form->field(name => "type", type => 'hidden');
398                         $form->title(sprintf(gettext("editing %s"), $page));
399                         showform($form, \@buttons, $session, $q,
400                                 forcebaseurl => $baseurl);
401                         exit;
402                 }
403                 
404                 my $conflict;
405                 if ($config{rcs}) {
406                         my $message="";
407                         if (defined $form->field('comments') &&
408                             length $form->field('comments')) {
409                                 $message=$form->field('comments');
410                         }
411                         
412                         if (! $exists) {
413                                 rcs_add($file);
414                         }
415
416                         # Prevent deadlock with post-commit hook by
417                         # signaling to it that it should not try to
418                         # do anything.
419                         disable_commit_hook();
420                         $conflict=rcs_commit($file, $message,
421                                 $form->field("rcsinfo"),
422                                 $session->param("name"), $ENV{REMOTE_ADDR});
423                         enable_commit_hook();
424                         rcs_update();
425                 }
426                 
427                 # Refresh even if there was a conflict, since other changes
428                 # may have been committed while the post-commit hook was
429                 # disabled.
430                 require IkiWiki::Render;
431                 refresh();
432                 saveindex();
433
434                 if (defined $conflict) {
435                         $form->field(name => "rcsinfo", value => rcs_prepedit($file),
436                                 force => 1);
437                         $form->tmpl_param("message", template("editconflict.tmpl")->output);
438                         $form->field("editcontent", value => $conflict, force => 1);
439                         $form->field("do", "edit", force => 1);
440                         $form->tmpl_param("page_select", 0);
441                         $form->field(name => "page", type => 'hidden');
442                         $form->field(name => "type", type => 'hidden');
443                         $form->title(sprintf(gettext("editing %s"), $page));
444                         showform($form, \@buttons, $session, $q,
445                                 forcebaseurl => $baseurl);
446                 }
447                 else {
448                         # The trailing question mark tries to avoid broken
449                         # caches and get the most recent version of the page.
450                         redirect($q, urlto($page, undef, 1)."?updated");
451                 }
452         }
453
454         exit;
455 } #}}}
456
457 1