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