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