Merge branch 'master' into po
[ikiwiki] / IkiWiki / Plugin / rename.pm
1 #!/usr/bin/perl
2 package IkiWiki::Plugin::rename;
3
4 use warnings;
5 use strict;
6 use IkiWiki 3.00;
7
8 sub import {
9         hook(type => "getsetup", id => "rename", call => \&getsetup);
10         hook(type => "formbuilder_setup", id => "rename", call => \&formbuilder_setup);
11         hook(type => "formbuilder", id => "rename", call => \&formbuilder);
12         hook(type => "sessioncgi", id => "rename", call => \&sessioncgi);
13         hook(type => "rename", id => "rename", call => \&rename_subpages);
14 }
15
16 sub getsetup () {
17         return 
18                 plugin => {
19                         safe => 1,
20                         rebuild => 0,
21                 },
22 }
23
24 sub check_canrename ($$$$$$) {
25         my $src=shift;
26         my $srcfile=shift;
27         my $dest=shift;
28         my $destfile=shift;
29         my $q=shift;
30         my $session=shift;
31
32         my $attachment=! defined pagetype($pagesources{$src});
33
34         # Must be a known source file.
35         if (! exists $pagesources{$src}) {
36                 error(sprintf(gettext("%s does not exist"),
37                         htmllink("", "", $src, noimageinline => 1)));
38         }
39         
40         # Must exist on disk, and be a regular file.
41         if (! -e "$config{srcdir}/$srcfile") {
42                 error(sprintf(gettext("%s is not in the srcdir, so it cannot be renamed"), $srcfile));
43         }
44         elsif (-l "$config{srcdir}/$srcfile" && ! -f _) {
45                 error(sprintf(gettext("%s is not a file"), $srcfile));
46         }
47
48         # Must be editable.
49         IkiWiki::check_canedit($src, $q, $session);
50         if ($attachment) {
51                 if (IkiWiki::Plugin::attachment->can("check_canattach")) {
52                         IkiWiki::Plugin::attachment::check_canattach($session, $src, $srcfile);
53                 }
54                 else {
55                         error("renaming of attachments is not allowed");
56                 }
57         }
58         
59         # Dest checks can be omitted by passing undef.
60         if (defined $dest) {
61                 if ($srcfile eq $destfile) {
62                         error(gettext("no change to the file name was specified"));
63                 }
64
65                 # Must be a legal filename, and not absolute.
66                 if (IkiWiki::file_pruned($destfile, $config{srcdir}) || 
67                     $destfile=~/^\//) {
68                         error(sprintf(gettext("illegal name")));
69                 }
70
71                 # Must not be a known source file.
72                 if ($src ne $dest && exists $pagesources{$dest}) {
73                         error(sprintf(gettext("%s already exists"),
74                                 htmllink("", "", $dest, noimageinline => 1)));
75                 }
76         
77                 # Must not exist on disk already.
78                 if (-l "$config{srcdir}/$destfile" || -e _) {
79                         error(sprintf(gettext("%s already exists on disk"), $destfile));
80                 }
81         
82                 # Must be editable.
83                 IkiWiki::check_canedit($dest, $q, $session);
84                 if ($attachment) {
85                         # Note that $srcfile is used here, not $destfile,
86                         # because it wants the current file, to check it.
87                         IkiWiki::Plugin::attachment::check_canattach($session, $dest, $srcfile);
88                 }
89         }
90
91         my $canrename;
92         IkiWiki::run_hooks(canrename => sub {
93                 return if defined $canrename;
94                 my $ret=shift->(cgi => $q, session => $session,
95                         src => $src, srcfile => $srcfile,
96                         dest => $dest, destfile => $destfile);
97                 if (defined $ret) {
98                         if ($ret eq "") {
99                                 $canrename=1;
100                         }
101                         elsif (ref $ret eq 'CODE') {
102                                 $ret->();
103                                 $canrename=0;
104                         }
105                         elsif (defined $ret) {
106                                 error($ret);
107                                 $canrename=0;
108                         }
109                 }
110         });
111 }
112
113 sub rename_form ($$$) {
114         my $q=shift;
115         my $session=shift;
116         my $page=shift;
117
118         eval q{use CGI::FormBuilder};
119         error($@) if $@;
120         my $f = CGI::FormBuilder->new(
121                 name => "rename",
122                 title => sprintf(gettext("rename %s"), pagetitle($page)),
123                 header => 0,
124                 charset => "utf-8",
125                 method => 'POST',
126                 javascript => 0,
127                 params => $q,
128                 action => $config{cgiurl},
129                 stylesheet => IkiWiki::baseurl()."style.css",
130                 fields => [qw{do page new_name attachment}],
131         );
132         
133         $f->field(name => "do", type => "hidden", value => "rename", force => 1);
134         $f->field(name => "page", type => "hidden", value => $page, force => 1);
135         $f->field(name => "new_name", value => pagetitle($page, 1), size => 60);
136         if (!$q->param("attachment")) {
137                 # insert the standard extensions
138                 my @page_types;
139                 if (exists $IkiWiki::hooks{htmlize}) {
140                         foreach my $key (grep { !/^_/ } keys %{$IkiWiki::hooks{htmlize}}) {
141                                 push @page_types, [$key, $IkiWiki::hooks{htmlize}{$key}{longname} || $key];
142                         }
143                 }
144                 @page_types=sort @page_types;
145         
146                 # make sure the current extension is in the list
147                 my ($ext) = $pagesources{$page}=~/\.([^.]+)$/;
148                 if (! $IkiWiki::hooks{htmlize}{$ext}) {
149                         unshift(@page_types, [$ext, $ext]);
150                 }
151         
152                 $f->field(name => "type", type => 'select',
153                         options => \@page_types,
154                         value => $ext, force => 1);
155                 
156                 foreach my $p (keys %pagesources) {
157                         if ($pagesources{$p}=~m/^\Q$page\E\//) {
158                                 $f->field(name => "subpages",
159                                         label => "",
160                                         type => "checkbox",
161                                         options => [ [ 1 => gettext("Also rename SubPages and attachments") ] ],
162                                         value => 1,
163                                         force => 1);
164                                 last;
165                         }
166                 }
167         }
168         $f->field(name => "attachment", type => "hidden");
169
170         return $f, ["Rename", "Cancel"];
171 }
172
173 sub rename_start ($$$$) {
174         my $q=shift;
175         my $session=shift;
176         my $attachment=shift;
177         my $page=shift;
178
179         check_canrename($page, $pagesources{$page}, undef, undef,
180                 $q, $session);
181
182         # Save current form state to allow returning to it later
183         # without losing any edits.
184         # (But don't save what button was submitted, to avoid
185         # looping back to here.)
186         # Note: "_submit" is CGI::FormBuilder internals.
187         $q->param(-name => "_submit", -value => "");
188         $session->param(postrename => scalar $q->Vars);
189         IkiWiki::cgi_savesession($session);
190         
191         if (defined $attachment) {
192                 $q->param(-name => "attachment", -value => $attachment);
193         }
194         my ($f, $buttons)=rename_form($q, $session, $page);
195         IkiWiki::showform($f, $buttons, $session, $q);
196         exit 0;
197 }
198
199 sub postrename ($;$$$) {
200         my $session=shift;
201         my $src=shift;
202         my $dest=shift;
203         my $attachment=shift;
204
205         # Load saved form state and return to edit page.
206         my $postrename=CGI->new($session->param("postrename"));
207         $session->clear("postrename");
208         IkiWiki::cgi_savesession($session);
209
210         if (defined $dest) {
211                 if (! $attachment) {
212                         # They renamed the page they were editing. This requires
213                         # fixups to the edit form state.
214                         # Tweak the edit form to be editing the new page.
215                         $postrename->param("page", $dest);
216                 }
217
218                 # Update edit form content to fix any links present
219                 # on it.
220                 $postrename->param("editcontent",
221                         renamepage_hook($dest, $src, $dest,
222                                  $postrename->param("editcontent")));
223
224                 # Get a new edit token; old was likely invalidated.
225                 $postrename->param("rcsinfo",
226                         IkiWiki::rcs_prepedit($pagesources{$dest}));
227         }
228
229         IkiWiki::cgi_editpage($postrename, $session);
230 }
231
232 sub formbuilder (@) {
233         my %params=@_;
234         my $form=$params{form};
235
236         if (defined $form->field("do") && ($form->field("do") eq "edit" ||
237             $form->field("do") eq "create")) {
238                 my $q=$params{cgi};
239                 my $session=$params{session};
240
241                 if ($form->submitted eq "Rename" && $form->field("do") eq "edit") {
242                         rename_start($q, $session, 0, $form->field("page"));
243                 }
244                 elsif ($form->submitted eq "Rename Attachment") {
245                         my @selected=$q->param("attachment_select");
246                         if (@selected > 1) {
247                                 error(gettext("Only one attachment can be renamed at a time."));
248                         }
249                         elsif (! @selected) {
250                                 error(gettext("Please select the attachment to rename."))
251                         }
252                         rename_start($q, $session, 1, $selected[0]);
253                 }
254         }
255 }
256
257 my $renamesummary;
258
259 sub formbuilder_setup (@) {
260         my %params=@_;
261         my $form=$params{form};
262         my $q=$params{cgi};
263
264         if (defined $form->field("do") && ($form->field("do") eq "edit" ||
265             $form->field("do") eq "create")) {
266                 # Rename button for the page, and also for attachments.
267                 push @{$params{buttons}}, "Rename" if $form->field("do") eq "edit";
268                 $form->tmpl_param("field-rename" => '<input name="_submit" type="submit" value="Rename Attachment" />');
269
270                 if (defined $renamesummary) {
271                         $form->tmpl_param(message => $renamesummary);
272                 }
273         }
274 }
275
276 sub sessioncgi ($$) {
277         my $q=shift;
278
279         if ($q->param("do") eq 'rename') {
280                 my $session=shift;
281                 my ($form, $buttons)=rename_form($q, $session, $q->param("page"));
282                 IkiWiki::decode_form_utf8($form);
283
284                 if ($form->submitted eq 'Cancel') {
285                         postrename($session);
286                 }
287                 elsif ($form->submitted eq 'Rename' && $form->validate) {
288                         # Queue of rename actions to perfom.
289                         my @torename;
290
291                         # These untaints are safe because of the checks
292                         # performed in check_canrename later.
293                         my $src=$q->param("page");
294                         my $srcfile=IkiWiki::possibly_foolish_untaint($pagesources{$src});
295                         my $dest=IkiWiki::possibly_foolish_untaint(titlepage($q->param("new_name")));
296                         my $destfile=$dest;
297                         if (! $q->param("attachment")) {
298                                 my $type=$q->param('type');
299                                 if (defined $type && length $type && $IkiWiki::hooks{htmlize}{$type}) {
300                                         $type=IkiWiki::possibly_foolish_untaint($type);
301                                 }
302                                 else {
303                                         my ($ext)=$srcfile=~/\.([^.]+)$/;
304                                         $type=$ext;
305                                 }
306                                 
307                                 $destfile=newpagefile($dest, $type);
308                         }
309                         push @torename, {
310                                 src => $src,
311                                 srcfile => $srcfile,
312                                 dest => $dest,
313                                 destfile => $destfile,
314                                 required => 1,
315                         };
316
317                         @torename=rename_hook(
318                                 torename => \@torename,
319                                 done => {},
320                                 cgi => $q,
321                                 session => $session,
322                         );
323
324                         require IkiWiki::Render;
325                         IkiWiki::disable_commit_hook() if $config{rcs};
326                         my %origpagesources=%pagesources;
327
328                         # First file renaming.
329                         foreach my $rename (@torename) {
330                                 if ($rename->{required}) {
331                                         do_rename($rename, $q, $session);
332                                 }
333                                 else {
334                                         eval {do_rename($rename, $q, $session)};
335                                         if ($@) {
336                                                 $rename->{error}=$@;
337                                                 next;
338                                         }
339                                 }
340
341                                 # Temporarily tweak pagesources to point to
342                                 # the renamed file, in case fixlinks needs
343                                 # to edit it.
344                                 $pagesources{$rename->{src}}=$rename->{destfile};
345                         }
346                         IkiWiki::rcs_commit_staged(
347                                 sprintf(gettext("rename %s to %s"), $srcfile, $destfile),
348                                 $session->param("name"), $ENV{REMOTE_ADDR}) if $config{rcs};
349
350                         # Then link fixups.
351                         foreach my $rename (@torename) {
352                                 next if $rename->{src} eq $rename->{dest};
353                                 next if $rename->{error};
354                                 foreach my $p (fixlinks($rename, $session)) {
355                                         # map old page names to new
356                                         foreach my $r (@torename) {
357                                                 next if $rename->{error};
358                                                 if ($r->{src} eq $p) {
359                                                         $p=$r->{dest};
360                                                         last;
361                                                 }
362                                         }
363                                         push @{$rename->{fixedlinks}}, $p;
364                                 }
365                         }
366
367                         # Then refresh.
368                         %pagesources=%origpagesources;
369                         if ($config{rcs}) {
370                                 IkiWiki::enable_commit_hook();
371                                 IkiWiki::rcs_update();
372                         }
373                         IkiWiki::refresh();
374                         IkiWiki::saveindex();
375
376                         # Find pages with remaining, broken links.
377                         foreach my $rename (@torename) {
378                                 next if $rename->{src} eq $rename->{dest};
379                                 
380                                 foreach my $page (keys %links) {
381                                         my $broken=0;
382                                         foreach my $link (@{$links{$page}}) {
383                                                 my $bestlink=bestlink($page, $link);
384                                                 if ($bestlink eq $rename->{src}) {
385                                                         push @{$rename->{brokenlinks}}, $page;
386                                                         last;
387                                                 }
388                                         }
389                                 }
390                         }
391
392                         # Generate a summary, that will be shown at the top
393                         # of the edit template.
394                         $renamesummary="";
395                         foreach my $rename (@torename) {
396                                 my $template=template("renamesummary.tmpl");
397                                 $template->param(src => $rename->{srcfile});
398                                 $template->param(dest => $rename->{destfile});
399                                 $template->param(error => $rename->{error});
400                                 if ($rename->{src} ne $rename->{dest}) {
401                                         $template->param(brokenlinks_checked => 1);
402                                         $template->param(brokenlinks => linklist($rename->{dest}, $rename->{brokenlinks}));
403                                         $template->param(fixedlinks => linklist($rename->{dest}, $rename->{fixedlinks}));
404                                 }
405                                 $renamesummary.=$template->output;
406                         }
407
408                         postrename($session, $src, $dest, $q->param("attachment"));
409                 }
410                 else {
411                         IkiWiki::showform($form, $buttons, $session, $q);
412                 }
413
414                 exit 0;
415         }
416 }
417
418 # Add subpages to the list of pages to be renamed, if needed.
419 sub rename_subpages (@) {
420         my %params = @_;
421
422         my %torename = %{$params{torename}};
423         my $q = $params{cgi};
424         my $src = $torename{src};
425         my $srcfile = $torename{src};
426         my $dest = $torename{dest};
427         my $destfile = $torename{dest};
428
429         return () unless ($q->param("subpages") && $src ne $dest);
430
431         my @ret;
432         foreach my $p (keys %pagesources) {
433                 next unless $pagesources{$p}=~m/^\Q$src\E\//;
434                 # If indexpages is enabled, the srcfile should not be confused
435                 # with a subpage.
436                 next if $pagesources{$p} eq $srcfile;
437
438                 my $d=$pagesources{$p};
439                 $d=~s/^\Q$src\E\//$dest\//;
440                 push @ret, {
441                         src => $p,
442                         srcfile => $pagesources{$p},
443                         dest => pagename($d),
444                         destfile => $d,
445                         required => 0,
446                 };
447         }
448         return @ret;
449 }
450
451 sub linklist {
452         # generates a list of links in a form suitable for FormBuilder
453         my $dest=shift;
454         my $list=shift;
455         # converts a list of pages into a list of links
456         # in a form suitable for FormBuilder.
457
458         [map {
459                 {
460                         page => htmllink($dest, $dest, $_,
461                                         noimageinline => 1,
462                                         linktext => pagetitle($_),
463                                 )
464                 }
465         } @{$list}]
466 }
467
468 sub renamepage_hook ($$$$) {
469         my ($page, $src, $dest, $content)=@_;
470
471         IkiWiki::run_hooks(renamepage => sub {
472                 $content=shift->(
473                         page => $page,
474                         oldpage => $src,
475                         newpage => $dest,
476                         content => $content,
477                 );
478         });
479
480         return $content;
481 }
482
483 sub rename_hook (@) {
484         my %params = @_;
485
486         my @torename=@{$params{torename}};
487         my %done=%{$params{done}};
488         my $q=$params{cgi};
489         my $session=$params{session};
490
491         return () unless @torename;
492
493         my @nextset;
494         foreach my $torename (@torename) {
495                 unless (exists $done{$torename->{src}} && $done{$torename->{src}}) {
496                         IkiWiki::run_hooks(rename => sub {
497                                 push @nextset, shift->(
498                                         torename => $torename,
499                                         cgi => $q,
500                                         session => $session,
501                                 );
502                         });
503                         $done{$torename->{src}}=1;
504                 }
505         }
506
507         push @torename, rename_hook(
508                 torename => \@nextset,
509                 done => \%done,
510                 cgi => $q,
511                 session => $session,
512         );
513
514         # dedup
515         my %seen;
516         return grep { ! $seen{$_->{src}}++ } @torename;
517 }
518
519 sub do_rename ($$$) {
520         my $rename=shift;
521         my $q=shift;
522         my $session=shift;
523
524         # First, check if this rename is allowed.
525         check_canrename($rename->{src},
526                 $rename->{srcfile},
527                 $rename->{dest},
528                 $rename->{destfile},
529                 $q, $session);
530
531         # Ensure that the dest directory exists and is ok.
532         IkiWiki::prep_writefile($rename->{destfile}, $config{srcdir});
533
534         if ($config{rcs}) {
535                 IkiWiki::rcs_rename($rename->{srcfile}, $rename->{destfile});
536         }
537         else {
538                 if (! rename($config{srcdir}."/".$rename->{srcfile},
539                              $config{srcdir}."/".$rename->{destfile})) {
540                         error("rename: $!");
541                 }
542         }
543
544 }
545
546 sub fixlinks ($$$) {
547         my $rename=shift;
548         my $session=shift;
549
550         my @fixedlinks;
551
552         foreach my $page (keys %links) {
553                 my $needfix=0;
554                 foreach my $link (@{$links{$page}}) {
555                         my $bestlink=bestlink($page, $link);
556                         if ($bestlink eq $rename->{src}) {
557                                 $needfix=1;
558                                 last;
559                         }
560                 }
561                 if ($needfix) {
562                         my $file=$pagesources{$page};
563                         my $oldcontent=readfile($config{srcdir}."/".$file);
564                         my $content=renamepage_hook($page, $rename->{src}, $rename->{dest}, $oldcontent);
565                         if ($oldcontent ne $content) {
566                                 my $token=IkiWiki::rcs_prepedit($file);
567                                 eval { writefile($file, $config{srcdir}, $content) };
568                                 next if $@;
569                                 my $conflict=IkiWiki::rcs_commit(
570                                         $file,
571                                         sprintf(gettext("update for rename of %s to %s"), $rename->{srcfile}, $rename->{destfile}),
572                                         $token,
573                                         $session->param("name"), 
574                                         $ENV{REMOTE_ADDR}
575                                 );
576                                 push @fixedlinks, $page if ! defined $conflict;
577                         }
578                 }
579         }
580
581         return @fixedlinks;
582 }
583
584 1