de11e4cc91cef699544510779c368907afebbe75
[ikiwiki.git] / 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);
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                         @page_types=grep { !/^_/ }
141                                 keys %{$IkiWiki::hooks{htmlize}};
142                 }
143         
144                 # make sure the current extension is in the list
145                 my ($ext) = $pagesources{$page}=~/\.([^.]+)$/;
146                 if (! $IkiWiki::hooks{htmlize}{$ext}) {
147                         unshift(@page_types, $ext);
148                 }
149         
150                 $f->field(name => "type", type => 'select',
151                         options => \@page_types,
152                         value => $ext, force => 1);
153                 
154                 foreach my $p (keys %pagesources) {
155                         if ($pagesources{$p}=~m/^\Q$page\E\//) {
156                                 $f->field(name => "subpages",
157                                         label => "",
158                                         type => "checkbox",
159                                         options => [ [ 1 => gettext("Also rename SubPages and attachments") ] ],
160                                         value => 1,
161                                         force => 1);
162                                 last;
163                         }
164                 }
165         }
166         $f->field(name => "attachment", type => "hidden");
167
168         return $f, ["Rename", "Cancel"];
169 }
170
171 sub rename_start ($$$$) {
172         my $q=shift;
173         my $session=shift;
174         my $attachment=shift;
175         my $page=shift;
176
177         check_canrename($page, $pagesources{$page}, undef, undef,
178                 $q, $session);
179
180         # Save current form state to allow returning to it later
181         # without losing any edits.
182         # (But don't save what button was submitted, to avoid
183         # looping back to here.)
184         # Note: "_submit" is CGI::FormBuilder internals.
185         $q->param(-name => "_submit", -value => "");
186         $session->param(postrename => scalar $q->Vars);
187         IkiWiki::cgi_savesession($session);
188         
189         if (defined $attachment) {
190                 $q->param(-name => "attachment", -value => $attachment);
191         }
192         my ($f, $buttons)=rename_form($q, $session, $page);
193         IkiWiki::showform($f, $buttons, $session, $q);
194         exit 0;
195 }
196
197 sub postrename ($;$$$) {
198         my $session=shift;
199         my $src=shift;
200         my $dest=shift;
201         my $attachment=shift;
202
203         # Load saved form state and return to edit page.
204         my $postrename=CGI->new($session->param("postrename"));
205         $session->clear("postrename");
206         IkiWiki::cgi_savesession($session);
207
208         if (defined $dest) {
209                 if (! $attachment) {
210                         # They renamed the page they were editing. This requires
211                         # fixups to the edit form state.
212                         # Tweak the edit form to be editing the new page.
213                         $postrename->param("page", $dest);
214                 }
215
216                 # Update edit form content to fix any links present
217                 # on it.
218                 $postrename->param("editcontent",
219                         renamepage_hook($dest, $src, $dest,
220                                  $postrename->param("editcontent")));
221
222                 # Get a new edit token; old was likely invalidated.
223                 $postrename->param("rcsinfo",
224                         IkiWiki::rcs_prepedit($pagesources{$dest}));
225         }
226
227         IkiWiki::cgi_editpage($postrename, $session);
228 }
229
230 sub formbuilder (@) {
231         my %params=@_;
232         my $form=$params{form};
233
234         if (defined $form->field("do") && ($form->field("do") eq "edit" ||
235             $form->field("do") eq "create")) {
236                 my $q=$params{cgi};
237                 my $session=$params{session};
238
239                 if ($form->submitted eq "Rename" && $form->field("do") eq "edit") {
240                         rename_start($q, $session, 0, $form->field("page"));
241                 }
242                 elsif ($form->submitted eq "Rename Attachment") {
243                         my @selected=$q->param("attachment_select");
244                         if (@selected > 1) {
245                                 error(gettext("Only one attachment can be renamed at a time."));
246                         }
247                         elsif (! @selected) {
248                                 error(gettext("Please select the attachment to rename."))
249                         }
250                         rename_start($q, $session, 1, $selected[0]);
251                 }
252         }
253 }
254
255 my $renamesummary;
256
257 sub formbuilder_setup (@) {
258         my %params=@_;
259         my $form=$params{form};
260         my $q=$params{cgi};
261
262         if (defined $form->field("do") && ($form->field("do") eq "edit" ||
263             $form->field("do") eq "create")) {
264                 # Rename button for the page, and also for attachments.
265                 push @{$params{buttons}}, "Rename" if $form->field("do") eq "edit";
266                 $form->tmpl_param("field-rename" => '<input name="_submit" type="submit" value="Rename Attachment" />');
267
268                 if (defined $renamesummary) {
269                         $form->tmpl_param(message => $renamesummary);
270                 }
271         }
272 }
273
274 sub sessioncgi ($$) {
275         my $q=shift;
276
277         if ($q->param("do") eq 'rename') {
278                 my $session=shift;
279                 my ($form, $buttons)=rename_form($q, $session, $q->param("page"));
280                 IkiWiki::decode_form_utf8($form);
281
282                 if ($form->submitted eq 'Cancel') {
283                         postrename($session);
284                 }
285                 elsif ($form->submitted eq 'Rename' && $form->validate) {
286                         # Queue of rename actions to perfom.
287                         my @torename;
288
289                         # These untaints are safe because of the checks
290                         # performed in check_canrename later.
291                         my $src=$q->param("page");
292                         my $srcfile=IkiWiki::possibly_foolish_untaint($pagesources{$src});
293                         my $dest=IkiWiki::possibly_foolish_untaint(titlepage($q->param("new_name")));
294                         my $destfile=$dest;
295                         if (! $q->param("attachment")) {
296                                 my $type=$q->param('type');
297                                 if (defined $type && length $type && $IkiWiki::hooks{htmlize}{$type}) {
298                                         $type=IkiWiki::possibly_foolish_untaint($type);
299                                 }
300                                 else {
301                                         my ($ext)=$srcfile=~/\.([^.]+)$/;
302                                         $type=$ext;
303                                 }
304                                 
305                                 $destfile=newpagefile($dest, $type);
306                         }
307                         push @torename, {
308                                 src => $src,
309                                 srcfile => $srcfile,
310                                 dest => $dest,
311                                 destfile => $destfile,
312                                 required => 1,
313                         };
314
315                         @torename=rename_hook(
316                                 torename => \@torename,
317                                 done => {},
318                                 cgi => $q,
319                                 session => $session,
320                         );
321
322                         require IkiWiki::Render;
323                         IkiWiki::disable_commit_hook() if $config{rcs};
324                         my %origpagesources=%pagesources;
325
326                         # First file renaming.
327                         foreach my $rename (@torename) {
328                                 if ($rename->{required}) {
329                                         do_rename($rename, $q, $session);
330                                 }
331                                 else {
332                                         eval {do_rename($rename, $q, $session)};
333                                         if ($@) {
334                                                 $rename->{error}=$@;
335                                                 next;
336                                         }
337                                 }
338
339                                 # Temporarily tweak pagesources to point to
340                                 # the renamed file, in case fixlinks needs
341                                 # to edit it.
342                                 $pagesources{$rename->{src}}=$rename->{destfile};
343                         }
344                         IkiWiki::rcs_commit_staged(
345                                 sprintf(gettext("rename %s to %s"), $srcfile, $destfile),
346                                 $session->param("name"), $ENV{REMOTE_ADDR}) if $config{rcs};
347
348                         # Then link fixups.
349                         foreach my $rename (@torename) {
350                                 next if $rename->{src} eq $rename->{dest};
351                                 next if $rename->{error};
352                                 foreach my $p (fixlinks($rename, $session)) {
353                                         # map old page names to new
354                                         foreach my $r (@torename) {
355                                                 next if $rename->{error};
356                                                 if ($r->{src} eq $p) {
357                                                         $p=$r->{dest};
358                                                         last;
359                                                 }
360                                         }
361                                         push @{$rename->{fixedlinks}}, $p;
362                                 }
363                         }
364
365                         # Then refresh.
366                         %pagesources=%origpagesources;
367                         if ($config{rcs}) {
368                                 IkiWiki::enable_commit_hook();
369                                 IkiWiki::rcs_update();
370                         }
371                         IkiWiki::refresh();
372                         IkiWiki::saveindex();
373
374                         # Find pages with remaining, broken links.
375                         foreach my $rename (@torename) {
376                                 next if $rename->{src} eq $rename->{dest};
377                                 
378                                 foreach my $page (keys %links) {
379                                         my $broken=0;
380                                         foreach my $link (@{$links{$page}}) {
381                                                 my $bestlink=bestlink($page, $link);
382                                                 if ($bestlink eq $rename->{src}) {
383                                                         push @{$rename->{brokenlinks}}, $page;
384                                                         last;
385                                                 }
386                                         }
387                                 }
388                         }
389
390                         # Generate a summary, that will be shown at the top
391                         # of the edit template.
392                         $renamesummary="";
393                         foreach my $rename (@torename) {
394                                 my $template=template("renamesummary.tmpl");
395                                 $template->param(src => $rename->{srcfile});
396                                 $template->param(dest => $rename->{destfile});
397                                 $template->param(error => $rename->{error});
398                                 if ($rename->{src} ne $rename->{dest}) {
399                                         $template->param(brokenlinks_checked => 1);
400                                         $template->param(brokenlinks => linklist($rename->{dest}, $rename->{brokenlinks}));
401                                         $template->param(fixedlinks => linklist($rename->{dest}, $rename->{fixedlinks}));
402                                 }
403                                 $renamesummary.=$template->output;
404                         }
405
406                         postrename($session, $src, $dest, $q->param("attachment"));
407                 }
408                 else {
409                         IkiWiki::showform($form, $buttons, $session, $q);
410                 }
411
412                 exit 0;
413         }
414 }
415
416 # Add subpages to the list of pages to be renamed, if needed.
417 sub rename(@) {
418         my %params = @_;
419
420         my %torename = %{$params{torename}};
421         my $q = $params{cgi};
422         my $src = $torename{src};
423         my $srcfile = $torename{src};
424         my $dest = $torename{dest};
425         my $destfile = $torename{dest};
426
427         return () unless ($q->param("subpages") && $src ne $dest);
428
429         my @ret;
430         foreach my $p (keys %pagesources) {
431                 next unless $pagesources{$p}=~m/^\Q$src\E\//;
432                 # If indexpages is enabled, the srcfile should not be confused
433                 # with a subpage.
434                 next if $pagesources{$p} eq $srcfile;
435
436                 my $d=$pagesources{$p};
437                 $d=~s/^\Q$src\E\//$dest\//;
438                 push @ret, {
439                         src => $p,
440                         srcfile => $pagesources{$p},
441                         dest => pagename($d),
442                         destfile => $d,
443                         required => 0,
444                 };
445         }
446         return @ret;
447 }
448
449 sub linklist {
450         # generates a list of links in a form suitable for FormBuilder
451         my $dest=shift;
452         my $list=shift;
453         # converts a list of pages into a list of links
454         # in a form suitable for FormBuilder.
455
456         [map {
457                 {
458                         page => htmllink($dest, $dest, $_,
459                                         noimageinline => 1,
460                                         linktext => pagetitle($_),
461                                 )
462                 }
463         } @{$list}]
464 }
465
466 sub renamepage_hook ($$$$) {
467         my ($page, $src, $dest, $content)=@_;
468
469         IkiWiki::run_hooks(renamepage => sub {
470                 $content=shift->(
471                         page => $page,
472                         oldpage => $src,
473                         newpage => $dest,
474                         content => $content,
475                 );
476         });
477
478         return $content;
479 }
480
481 sub rename_hook (@) {
482         my %params = @_;
483
484         my @torename=@{$params{torename}};
485         my %done=%{$params{done}};
486         my $q=$params{cgi};
487         my $session=$params{session};
488
489         my @nextset;
490         if (@torename) {
491                 foreach my $torename (@torename) {
492                         unless (exists $done{$torename->{src}} && $done{$torename->{src}}) {
493                                 IkiWiki::run_hooks(rename => sub {
494                                         push @nextset, shift->(
495                                                 torename => $torename,
496                                                 cgi => $q,
497                                                 session => $session,
498                                         );
499                                 });
500                                 $done{$torename->{src}}=1;
501                         }
502                 }
503                 push @torename, rename_hook(
504                         torename => \@nextset,
505                         done => \%done,
506                         cgi => $q,
507                         session => $session,
508                 );
509
510                 # remove duplicates from @torename
511                 my %seen;
512                 return grep { ! $seen{$_->{src}}++ } @torename;
513         }
514         else {
515                 return ();
516         }
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 (! CORE::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