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