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