po: keep masterpage as the rootpage for inline's post form
[ikiwiki] / IkiWiki / Plugin / po.pm
1 #!/usr/bin/perl
2 # .po as a wiki page type
3 # Licensed under GPL v2 or greater
4 # Copyright (C) 2008-2009 intrigeri <intrigeri@boum.org>
5 # inspired by the GPL'd po4a-translate,
6 # which is Copyright 2002, 2003, 2004 by Martin Quinson (mquinson#debian.org)
7 package IkiWiki::Plugin::po;
8
9 use warnings;
10 use strict;
11 use IkiWiki 3.00;
12 use Encode;
13 eval q{use Locale::Po4a::Common qw(nowrapi18n !/.*/)};
14 if ($@) {
15         print STDERR gettext("warning: Old po4a detected! Recommend upgrade to 0.35.")."\n";
16         eval q{use Locale::Po4a::Common qw(!/.*/)};
17         die $@ if $@;
18 }
19 use Locale::Po4a::Chooser;
20 use Locale::Po4a::Po;
21 use File::Basename;
22 use File::Copy;
23 use File::Spec;
24 use File::Temp;
25 use Memoize;
26 use UNIVERSAL;
27
28 my %translations;
29 my @origneedsbuild;
30 my %origsubs;
31
32 memoize("istranslatable");
33 memoize("_istranslation");
34 memoize("percenttranslated");
35
36 sub import {
37         hook(type => "getsetup", id => "po", call => \&getsetup);
38         hook(type => "checkconfig", id => "po", call => \&checkconfig);
39         hook(type => "needsbuild", id => "po", call => \&needsbuild);
40         hook(type => "scan", id => "po", call => \&scan, last => 1);
41         hook(type => "filter", id => "po", call => \&filter);
42         hook(type => "htmlize", id => "po", call => \&htmlize);
43         hook(type => "pagetemplate", id => "po", call => \&pagetemplate, last => 1);
44         hook(type => "rename", id => "po", call => \&renamepages, first => 1);
45         hook(type => "delete", id => "po", call => \&mydelete);
46         hook(type => "change", id => "po", call => \&change);
47         hook(type => "checkcontent", id => "po", call => \&checkcontent);
48         hook(type => "canremove", id => "po", call => \&canremove);
49         hook(type => "canrename", id => "po", call => \&canrename);
50         hook(type => "editcontent", id => "po", call => \&editcontent);
51         hook(type => "formbuilder_setup", id => "po", call => \&formbuilder_setup, last => 1);
52         hook(type => "formbuilder", id => "po", call => \&formbuilder);
53
54         $origsubs{'beautify_urlpath'}=\&IkiWiki::beautify_urlpath;
55         inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath);
56         $origsubs{'targetpage'}=\&IkiWiki::targetpage;
57         inject(name => "IkiWiki::targetpage", call => \&mytargetpage);
58         $origsubs{'urlto'}=\&IkiWiki::urlto;
59         inject(name => "IkiWiki::urlto", call => \&myurlto);
60         $origsubs{'cgiurl'}=\&IkiWiki::cgiurl;
61         inject(name => "IkiWiki::cgiurl", call => \&mycgiurl);
62 }
63
64
65 # ,----
66 # | Table of contents
67 # `----
68
69 # 1. Hooks
70 # 2. Injected functions
71 # 3. Blackboxes for private data
72 # 4. Helper functions
73 # 5. PageSpecs
74
75
76 # ,----
77 # | Hooks
78 # `----
79
80 sub getsetup () {
81         return
82                 plugin => {
83                         safe => 0,
84                         rebuild => 1,
85                 },
86                 po_master_language => {
87                         type => "string",
88                         example => {
89                                 'code' => 'en',
90                                 'name' => 'English'
91                         },
92                         description => "master language (non-PO files)",
93                         safe => 1,
94                         rebuild => 1,
95                 },
96                 po_slave_languages => {
97                         type => "string",
98                         example => {
99                                 'fr' => 'Français',
100                                 'es' => 'Español',
101                                 'de' => 'Deutsch'
102                         },
103                         description => "slave languages (PO files)",
104                         safe => 1,
105                         rebuild => 1,
106                 },
107                 po_translatable_pages => {
108                         type => "pagespec",
109                         example => "* and !*/Discussion",
110                         description => "PageSpec controlling which pages are translatable",
111                         link => "ikiwiki/PageSpec",
112                         safe => 1,
113                         rebuild => 1,
114                 },
115                 po_link_to => {
116                         type => "string",
117                         example => "current",
118                         description => "internal linking behavior (default/current/negotiated)",
119                         safe => 1,
120                         rebuild => 1,
121                 },
122 }
123
124 sub checkconfig () {
125         foreach my $field (qw{po_master_language}) {
126                 if (! exists $config{$field} || ! defined $config{$field}) {
127                         error(sprintf(gettext("Must specify %s when using the %s plugin"),
128                                       $field, 'po'));
129                 }
130         }
131
132         map {
133                 islanguagecode($_)
134                         or error(sprintf(gettext("%s is not a valid language code"), $_));
135         } ($config{po_master_language}{code}, keys %{$config{po_slave_languages}});
136
137         if (! exists $config{po_translatable_pages} ||
138             ! defined $config{po_translatable_pages}) {
139                 $config{po_translatable_pages}="";
140         }
141         if (! exists $config{po_link_to} ||
142             ! defined $config{po_link_to}) {
143                 $config{po_link_to}='default';
144         }
145         elsif ($config{po_link_to} !~ /^(default|current|negotiated)$/) {
146                 warn(sprintf(gettext('%s is not a valid value for po_link_to, falling back to po_link_to=default'),
147                              $config{po_link_to}));
148                 $config{po_link_to}='default';
149         }
150         elsif ($config{po_link_to} eq "negotiated" && ! $config{usedirs}) {
151                 warn(gettext('po_link_to=negotiated requires usedirs to be enabled, falling back to po_link_to=default'));
152                 $config{po_link_to}='default';
153         }
154         unless ($config{po_link_to} eq 'default') {
155                 $origsubs{'bestlink'}=\&IkiWiki::bestlink;
156                 inject(name => "IkiWiki::bestlink", call => \&mybestlink);
157         }
158
159         push @{$config{wiki_file_prune_regexps}}, qr/\.pot$/;
160
161         # Translated versions of the underlays are added if available.
162         foreach my $underlay ("basewiki",
163                               map { m/^\Q$config{underlaydirbase}\E\/*(.*)/ }
164                                   reverse @{$config{underlaydirs}}) {
165                 next if $underlay=~/^locale\//;
166
167                 # Underlays containing the po files for slave languages.
168                 foreach my $ll (keys %{$config{po_slave_languages}}) {
169                         add_underlay("po/$ll/$underlay")
170                                 if -d "$config{underlaydirbase}/po/$ll/$underlay";
171                 }
172         
173                 if ($config{po_master_language}{code} ne 'en') {
174                         # Add underlay containing translated source files
175                         # for the master language.
176                         add_underlay("locale/$config{po_master_language}{code}/$underlay");
177                 }
178         }
179 }
180
181 sub needsbuild () {
182         my $needsbuild=shift;
183
184         # backup @needsbuild content so that change() can know whether
185         # a given master page was rendered because its source file was changed
186         @origneedsbuild=(@$needsbuild);
187
188         flushmemoizecache();
189         buildtranslationscache();
190
191         # make existing translations depend on the corresponding master page
192         foreach my $master (keys %translations) {
193                 map add_depends($_, $master), values %{otherlanguages($master)};
194         }
195 }
196
197 # Massage the recorded state of internal links so that:
198 # - it matches the actually generated links, rather than the links as written
199 #   in the pages' source
200 # - backlinks are consistent in all cases
201 sub scan (@) {
202         my %params=@_;
203         my $page=$params{page};
204         my $content=$params{content};
205
206         if (istranslation($page)) {
207                 foreach my $destpage (@{$links{$page}}) {
208                         if (istranslatable($destpage)) {
209                                 # replace the occurence of $destpage in $links{$page}
210                                 for (my $i=0; $i<@{$links{$page}}; $i++) {
211                                         if (@{$links{$page}}[$i] eq $destpage) {
212                                                 @{$links{$page}}[$i] = $destpage . '.' . lang($page);
213                                                 last;
214                                         }
215                                 }
216                         }
217                 }
218         }
219         elsif (! istranslatable($page) && ! istranslation($page)) {
220                 foreach my $destpage (@{$links{$page}}) {
221                         if (istranslatable($destpage)) {
222                                 # make sure any destpage's translations has
223                                 # $page in its backlinks
224                                 push @{$links{$page}},
225                                         values %{otherlanguages($destpage)};
226                         }
227                 }
228         }
229 }
230
231 # We use filter to convert PO to the master page's format,
232 # since the rest of ikiwiki should not work on PO files.
233 sub filter (@) {
234         my %params = @_;
235
236         my $page = $params{page};
237         my $destpage = $params{destpage};
238         my $content = $params{content};
239         if (istranslation($page) && ! alreadyfiltered($page, $destpage)) {
240                 $content = po_to_markup($page, $content);
241                 setalreadyfiltered($page, $destpage);
242         }
243         return $content;
244 }
245
246 sub htmlize (@) {
247         my %params=@_;
248
249         my $page = $params{page};
250         my $content = $params{content};
251
252         # ignore PO files this plugin did not create
253         return $content unless istranslation($page);
254
255         # force content to be htmlize'd as if it was the same type as the master page
256         return IkiWiki::htmlize($page, $page,
257                 pagetype(srcfile($pagesources{masterpage($page)})),
258                 $content);
259 }
260
261 sub pagetemplate (@) {
262         my %params=@_;
263         my $page=$params{page};
264         my $destpage=$params{destpage};
265         my $template=$params{template};
266
267         my ($masterpage, $lang) = istranslation($page);
268
269         if (istranslation($page) && $template->query(name => "percenttranslated")) {
270                 $template->param(percenttranslated => percenttranslated($page));
271         }
272         if ($template->query(name => "istranslation")) {
273                 $template->param(istranslation => scalar istranslation($page));
274         }
275         if ($template->query(name => "istranslatable")) {
276                 $template->param(istranslatable => istranslatable($page));
277         }
278         if ($template->query(name => "HOMEPAGEURL")) {
279                 $template->param(homepageurl => homepageurl($page));
280         }
281         if ($template->query(name => "otherlanguages")) {
282                 $template->param(otherlanguages => [otherlanguagesloop($page)]);
283                 map add_depends($page, $_), (values %{otherlanguages($page)});
284         }
285         if ($config{discussion} && istranslation($page)) {
286                 if ($page !~ /.*\/\Q$config{discussionpage}\E$/i &&
287                    (length $config{cgiurl} ||
288                     exists $links{$masterpage."/".lc($config{discussionpage})})) {
289                         $template->param('discussionlink' => htmllink(
290                                 $page,
291                                 $destpage,
292                                 $masterpage . '/' . $config{discussionpage},
293                                 noimageinline => 1,
294                                 forcesubpage => 0,
295                                 linktext => $config{discussionpage},
296                 ));
297                 }
298         }
299         # Remove broken parentlink to ./index.html on home page's translations.
300         # It works because this hook has the "last" parameter set, to ensure it
301         # runs after parentlinks' own pagetemplate hook.
302         if ($template->param('parentlinks')
303             && istranslation($page)
304             && $masterpage eq "index") {
305                 $template->param('parentlinks' => []);
306         }
307         if (ishomepage($page) && $template->query(name => "title")) {
308                 $template->param(title => $config{wikiname});
309         }
310 } # }}}
311
312 # Add the renamed page translations to the list of to-be-renamed pages.
313 sub renamepages (@) {
314         my %params = @_;
315
316         my %torename = %{$params{torename}};
317         my $session = $params{session};
318
319         # Save the page(s) the user asked to rename, so that our
320         # canrename hook can tell the difference between:
321         #  - a translation being renamed as a consequence of its master page
322         #    being renamed
323         #  - a user trying to directly rename a translation
324         # This is why this hook has to be run first, before the list of pages
325         # to rename is modified by other plugins.
326         my @orig_torename;
327         @orig_torename=@{$session->param("po_orig_torename")}
328                 if defined $session->param("po_orig_torename");
329         push @orig_torename, $torename{src};
330         $session->param(po_orig_torename => \@orig_torename);
331         IkiWiki::cgi_savesession($session);
332
333         return () unless istranslatable($torename{src});
334
335         my @ret;
336         my %otherpages=%{otherlanguages($torename{src})};
337         while (my ($lang, $otherpage) = each %otherpages) {
338                 push @ret, {
339                         src => $otherpage,
340                         srcfile => $pagesources{$otherpage},
341                         dest => otherlanguage($torename{dest}, $lang),
342                         destfile => $torename{dest}.".".$lang.".po",
343                         required => 0,
344                 };
345         }
346         return @ret;
347 }
348
349 sub mydelete (@) {
350         my @deleted=@_;
351
352         map { deletetranslations($_) } grep istranslatablefile($_), @deleted;
353 }
354
355 sub change (@) {
356         my @rendered=@_;
357
358         # All meta titles are first extracted at scan time, i.e. before we turn
359         # PO files back into translated markdown; escaping of double-quotes in
360         # PO files breaks the meta plugin's parsing enough to save ugly titles
361         # to %pagestate at this time.
362         #
363         # Then, at render time, every page passes in turn through the Great
364         # Rendering Chain (filter->preprocess->linkify->htmlize), and the meta
365         # plugin's preprocess hook is this time in a position to correctly
366         # extract the titles from slave pages.
367         #
368         # This is, unfortunately, too late: if the page A, linking to the page
369         # B, is rendered before B, it will display the wrongly-extracted meta
370         # title as the link text to B.
371         #
372         # On the one hand, such a corner case only happens on rebuild: on
373         # refresh, every rendered page is fixed to contain correct meta titles.
374         # On the other hand, it can take some time to get every page fixed.
375         # We therefore re-render every rendered page after a rebuild to fix them
376         # at once. As this more or less doubles the time needed to rebuild the
377         # wiki, we do so only when really needed.
378
379         if (@rendered
380             && exists $config{rebuild} && defined $config{rebuild} && $config{rebuild}
381             && UNIVERSAL::can("IkiWiki::Plugin::meta", "getsetup")
382             && exists $config{meta_overrides_page_title}
383             && defined $config{meta_overrides_page_title}
384             && $config{meta_overrides_page_title}) {
385                 debug(sprintf(gettext("rebuilding all pages to fix meta titles")));
386                 resetalreadyfiltered();
387                 require IkiWiki::Render;
388                 foreach my $file (@rendered) {
389                         debug(sprintf(gettext("building %s"), $file));
390                         IkiWiki::render($file);
391                 }
392         }
393
394         my $updated_po_files=0;
395
396         # Refresh/create POT and PO files as needed.
397         # (But avoid doing so if they are in an underlay directory.)
398         foreach my $file (grep {istranslatablefile($_)} @rendered) {
399                 my $masterfile=srcfile($file);
400                 my $page=pagename($file);
401                 my $updated_pot_file=0;
402                 # Only refresh POT file if it does not exist, or if
403                 # $pagesources{$page} was changed: don't if only the HTML was
404                 # refreshed, e.g. because of a dependency.
405                 if ($masterfile eq "$config{srcdir}/$file" &&
406                    ((grep { $_ eq $pagesources{$page} } @origneedsbuild)
407                     || ! -e potfile($masterfile))) {
408                         refreshpot($masterfile);
409                         $updated_pot_file=1;
410                 }
411                 my @pofiles;
412                 foreach my $po (pofiles($masterfile)) {
413                         next if ! $updated_pot_file && ! -e $po;
414                         next if grep { $po=~/\Q$_\E/ } @{$config{underlaydirs}};
415                         push @pofiles, $po;
416                 }
417                 if (@pofiles) {
418                         refreshpofiles($masterfile, @pofiles);
419                         map { s/^\Q$config{srcdir}\E\/*//; IkiWiki::rcs_add($_) } @pofiles if $config{rcs};
420                         $updated_po_files=1;
421                 }
422         }
423
424         if ($updated_po_files) {
425                 commit_and_refresh(
426                         gettext("updated PO files"),
427                         "IkiWiki::Plugin::po::change");
428         }
429 }
430
431 sub checkcontent (@) {
432         my %params=@_;
433
434         if (istranslation($params{page})) {
435                 my $res = isvalidpo($params{content});
436                 if ($res) {
437                         return undef;
438                 }
439                 else {
440                         return "$res";
441                 }
442         }
443         return undef;
444 }
445
446 sub canremove (@) {
447         my %params = @_;
448
449         if (istranslation($params{page})) {
450                 return gettext("Can not remove a translation. If the master page is removed, ".
451                                "however, its translations will be removed as well.");
452         }
453         return undef;
454 }
455
456 sub canrename (@) {
457         my %params = @_;
458         my $session = $params{session};
459
460         if (istranslation($params{src})) {
461                 my $masterpage = masterpage($params{src});
462                 # Tell the difference between:
463                 #  - a translation being renamed as a consequence of its master page
464                 #    being renamed, which is allowed
465                 #  - a user trying to directly rename a translation, which is forbidden
466                 # by looking for the master page in the list of to-be-renamed pages we
467                 # saved early in the renaming process.
468                 my $orig_torename = $session->param("po_orig_torename");
469                 unless (grep { $_ eq $masterpage } @{$orig_torename}) {
470                         return gettext("Can not rename a translation. If the master page is renamed, ".
471                                        "however, its translations will be renamed as well.");
472                 }
473         }
474         return undef;
475 }
476
477 # As we're previewing or saving a page, the content may have
478 # changed, so tell the next filter() invocation it must not be lazy.
479 sub editcontent () {
480         my %params=@_;
481
482         unsetalreadyfiltered($params{page}, $params{page});
483         return $params{content};
484 }
485
486 sub formbuilder_setup (@) {
487         my %params=@_;
488         my $form=$params{form};
489         my $q=$params{cgi};
490
491         return unless defined $form->field("do");
492
493         if ($form->field("do") eq "create") {
494                 # Warn the user: new pages must be written in master language.
495                 my $template=template("pocreatepage.tmpl");
496                 $template->param(LANG => $config{po_master_language}{name});
497                 $form->tmpl_param(message => $template->output);
498         }
499         elsif ($form->field("do") eq "edit") {
500                 # Remove the rename/remove buttons on slave pages.
501                 # This has to be done after the rename/remove plugins have added
502                 # their buttons, which is why this hook must be run last.
503                 # The canrename/canremove hooks already ensure this is forbidden
504                 # at the backend level, so this is only UI sugar.
505                 if (istranslation($form->field("page"))) {
506                         map {
507                                 for (my $i = 0; $i < @{$params{buttons}}; $i++) {
508                                         if (@{$params{buttons}}[$i] eq $_) {
509                                                 delete  @{$params{buttons}}[$i];
510                                                 last;
511                                         }
512                                 }
513                         } qw(Rename Remove);
514                 }
515         }
516 }
517
518 sub formbuilder (@) {
519         my %params=@_;
520         my $form=$params{form};
521         my $q=$params{cgi};
522
523         return unless defined $form->field("do");
524
525         # Do not allow to create pages of type po: they are automatically created.
526         # The main reason to do so is to bypass the "favor the type of linking page
527         # on page creation" logic, which is unsuitable when a broken link is clicked
528         # on a slave (PO) page.
529         # This cannot be done in the formbuilder_setup hook as the list of types is
530         # computed later.
531         if ($form->field("do") eq "create") {
532                 foreach my $field ($form->field) {
533                         next unless "$field" eq "type";
534                         next unless $field->type eq 'select';
535                         my $orig_value = $field->value;
536                         # remove po from the list of types
537                         my @types = grep { $_->[0] ne 'po' } $field->options;
538                         $field->options(\@types) if @types;
539                         # favor the type of linking page's masterpage
540                         if ($orig_value eq 'po') {
541                                 my ($from, $type);
542                                 if (defined $form->field('from')) {
543                                         ($from)=$form->field('from')=~/$config{wiki_file_regexp}/;
544                                         $from = masterpage($from);
545                                 }
546                                 if (defined $from && exists $pagesources{$from}) {
547                                         $type=pagetype($pagesources{$from});
548                                 }
549                                 $type=$config{default_pageext} unless defined $type;
550                                 $field->value($type) ;
551                         }
552                 }
553         }
554 }
555
556 # ,----
557 # | Injected functions
558 # `----
559
560 # Implement po_link_to 'current' and 'negotiated' settings.
561 # Not injected otherwise.
562 sub mybestlink ($$) {
563         my $page=shift;
564         my $link=shift;
565
566         my $res=$origsubs{'bestlink'}->(masterpage($page), $link);
567         my @caller = caller(1);
568         if (length $res
569             && istranslatable($res)
570             && istranslation($page)
571             # keep masterpage as the rootpage for inline's post form
572             && !(exists $caller[3] && defined $caller[3]
573                  && ($caller[3] eq "IkiWiki::rootpage"))) {
574                 return $res . "." . lang($page);
575         }
576         return $res;
577 }
578
579 sub mybeautify_urlpath ($) {
580         my $url=shift;
581
582         my $res=$origsubs{'beautify_urlpath'}->($url);
583         if ($config{po_link_to} eq "negotiated") {
584                 $res =~ s!/\Qindex.$config{po_master_language}{code}.$config{htmlext}\E$!/!;
585                 $res =~ s!/\Qindex.$config{htmlext}\E$!/!;
586                 map {
587                         $res =~ s!/\Qindex.$_.$config{htmlext}\E$!/!;
588                 } (keys %{$config{po_slave_languages}});
589         }
590         return $res;
591 }
592
593 sub mytargetpage ($$) {
594         my $page=shift;
595         my $ext=shift;
596
597         if (istranslation($page) || istranslatable($page)) {
598                 my ($masterpage, $lang) = (masterpage($page), lang($page));
599                 if (! $config{usedirs} || $masterpage eq 'index') {
600                         return $masterpage . "." . $lang . "." . $ext;
601                 }
602                 else {
603                         return $masterpage . "/index." . $lang . "." . $ext;
604                 }
605         }
606         return $origsubs{'targetpage'}->($page, $ext);
607 }
608
609 sub myurlto ($$;$) {
610         my $to=shift;
611         my $from=shift;
612         my $absolute=shift;
613
614         # workaround hard-coded /index.$config{htmlext} in IkiWiki::urlto()
615         if (! length $to
616             && $config{po_link_to} eq "current"
617             && istranslatable('index')) {
618                 return IkiWiki::beautify_urlpath(IkiWiki::baseurl($from) . "index." . lang($from) . ".$config{htmlext}");
619         }
620         # avoid using our injected beautify_urlpath if run by cgi_editpage,
621         # so that one is redirected to the just-edited page rather than to the
622         # negociated translation; to prevent unnecessary fiddling with caller/inject,
623         # we only do so when our beautify_urlpath would actually do what we want to
624         # avoid, i.e. when po_link_to = negotiated.
625         # also avoid doing so when run by cgi_goto, so that the links on recentchanges
626         # page actually lead to the exact page they pretend to.
627         if ($config{po_link_to} eq "negotiated") {
628                 my @caller = caller(1);
629                 my $use_orig = 0;
630                 $use_orig = 1 if (exists $caller[3] && defined $caller[3]
631                                  && ($caller[3] eq "IkiWiki::cgi_editpage" ||
632                                      $caller[3] eq "IkiWiki::Plugin::goto::cgi_goto")
633                                  );
634                 inject(name => "IkiWiki::beautify_urlpath", call => $origsubs{'beautify_urlpath'})
635                         if $use_orig;
636                 my $res = $origsubs{'urlto'}->($to,$from,$absolute);
637                 inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath)
638                         if $use_orig;
639                 return $res;
640         }
641         else {
642                 return $origsubs{'urlto'}->($to,$from,$absolute)
643         }
644 }
645
646 sub mycgiurl (@) {
647         my %params=@_;
648
649         # slave pages have no subpages
650         if (istranslation($params{'from'})) {
651                 $params{'from'} = masterpage($params{'from'});
652         }
653         return $origsubs{'cgiurl'}->(%params);
654 }
655
656 # ,----
657 # | Blackboxes for private data
658 # `----
659
660 {
661         my %filtered;
662
663         sub alreadyfiltered($$) {
664                 my $page=shift;
665                 my $destpage=shift;
666
667                 return exists $filtered{$page}{$destpage}
668                          && $filtered{$page}{$destpage} eq 1;
669         }
670
671         sub setalreadyfiltered($$) {
672                 my $page=shift;
673                 my $destpage=shift;
674
675                 $filtered{$page}{$destpage}=1;
676         }
677
678         sub unsetalreadyfiltered($$) {
679                 my $page=shift;
680                 my $destpage=shift;
681
682                 if (exists $filtered{$page}{$destpage}) {
683                         delete $filtered{$page}{$destpage};
684                 }
685         }
686
687         sub resetalreadyfiltered() {
688                 undef %filtered;
689         }
690 }
691
692 # ,----
693 # | Helper functions
694 # `----
695
696 sub maybe_add_leading_slash ($;$) {
697         my $str=shift;
698         my $add=shift;
699         $add=1 unless defined $add;
700         return '/' . $str if $add;
701         return $str;
702 }
703
704 sub istranslatablefile ($) {
705         my $file=shift;
706
707         return 0 unless defined $file;
708         my $type=pagetype($file);
709         return 0 if ! defined $type || $type eq 'po';
710         return 0 if $file =~ /\.pot$/;
711         return 1 if pagespec_match(pagename($file), $config{po_translatable_pages});
712         return;
713 }
714
715 sub istranslatable ($) {
716         my $page=shift;
717
718         $page=~s#^/##;
719         return 1 if istranslatablefile($pagesources{$page});
720         return;
721 }
722
723 sub _istranslation ($) {
724         my $page=shift;
725
726         $page='' unless defined $page && length $page;
727         my $hasleadingslash = ($page=~s#^/##);
728         my $file=$pagesources{$page};
729         return 0 unless defined $file
730                          && defined pagetype($file)
731                          && pagetype($file) eq 'po';
732         return 0 if $file =~ /\.pot$/;
733
734         my ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
735         return 0 unless defined $masterpage && defined $lang
736                          && length $masterpage && length $lang
737                          && defined $pagesources{$masterpage}
738                          && defined $config{po_slave_languages}{$lang};
739
740         return (maybe_add_leading_slash($masterpage, $hasleadingslash), $lang)
741                 if istranslatable($masterpage);
742 }
743
744 sub istranslation ($) {
745         my $page=shift;
746
747         if (1 < (my ($masterpage, $lang) = _istranslation($page))) {
748                 my $hasleadingslash = ($masterpage=~s#^/##);
749                 $translations{$masterpage}{$lang}=$page unless exists $translations{$masterpage}{$lang};
750                 return (maybe_add_leading_slash($masterpage, $hasleadingslash), $lang);
751         }
752         return "";
753 }
754
755 sub masterpage ($) {
756         my $page=shift;
757
758         if ( 1 < (my ($masterpage, $lang) = _istranslation($page))) {
759                 return $masterpage;
760         }
761         return $page;
762 }
763
764 sub lang ($) {
765         my $page=shift;
766
767         if (1 < (my ($masterpage, $lang) = _istranslation($page))) {
768                 return $lang;
769         }
770         return $config{po_master_language}{code};
771 }
772
773 sub islanguagecode ($) {
774         my $code=shift;
775
776         return $code =~ /^[a-z]{2}$/;
777 }
778
779 sub otherlanguage ($$) {
780         my $page=shift;
781         my $code=shift;
782
783         return masterpage($page) if $code eq $config{po_master_language}{code};
784         return masterpage($page) . '.' . $code;
785 }
786
787 sub otherlanguages ($) {
788         my $page=shift;
789
790         my %ret;
791         return \%ret unless istranslation($page) || istranslatable($page);
792         my $curlang=lang($page);
793         foreach my $lang
794                 ($config{po_master_language}{code}, keys %{$config{po_slave_languages}}) {
795                 next if $lang eq $curlang;
796                 $ret{$lang}=otherlanguage($page, $lang);
797         }
798         return \%ret;
799 }
800
801 sub potfile ($) {
802         my $masterfile=shift;
803
804         (my $name, my $dir, my $suffix) = fileparse($masterfile, qr/\.[^.]*/);
805         $dir='' if $dir eq './';
806         return File::Spec->catpath('', $dir, $name . ".pot");
807 }
808
809 sub pofile ($$) {
810         my $masterfile=shift;
811         my $lang=shift;
812
813         (my $name, my $dir, my $suffix) = fileparse($masterfile, qr/\.[^.]*/);
814         $dir='' if $dir eq './';
815         return File::Spec->catpath('', $dir, $name . "." . $lang . ".po");
816 }
817
818 sub pofiles ($) {
819         my $masterfile=shift;
820
821         return map pofile($masterfile, $_), (keys %{$config{po_slave_languages}});
822 }
823
824 sub refreshpot ($) {
825         my $masterfile=shift;
826
827         my $potfile=potfile($masterfile);
828         my %options = ("markdown" => (pagetype($masterfile) eq 'mdwn') ? 1 : 0);
829         my $doc=Locale::Po4a::Chooser::new('text',%options);
830         $doc->{TT}{utf_mode} = 1;
831         $doc->{TT}{file_in_charset} = 'utf-8';
832         $doc->{TT}{file_out_charset} = 'utf-8';
833         $doc->read($masterfile);
834         # let's cheat a bit to force porefs option to be passed to
835         # Locale::Po4a::Po; this is undocument use of internal
836         # Locale::Po4a::TransTractor's data, compulsory since this module
837         # prevents us from using the porefs option.
838         $doc->{TT}{po_out}=Locale::Po4a::Po->new({ 'porefs' => 'none' });
839         $doc->{TT}{po_out}->set_charset('utf-8');
840         # do the actual work
841         $doc->parse;
842         IkiWiki::prep_writefile(basename($potfile),dirname($potfile));
843         $doc->writepo($potfile);
844 }
845
846 sub refreshpofiles ($@) {
847         my $masterfile=shift;
848         my @pofiles=@_;
849
850         my $potfile=potfile($masterfile);
851         if (! -e $potfile) {
852                 error("po(refreshpofiles) ".sprintf(gettext("POT file (%s) does not exist"), $potfile));
853         }
854
855         foreach my $pofile (@pofiles) {
856                 IkiWiki::prep_writefile(basename($pofile),dirname($pofile));
857
858                 if (! -e $pofile) {
859                         # If the po file exists in an underlay, copy it
860                         # from there.
861                         my ($pobase)=$pofile=~/^\Q$config{srcdir}\E\/?(.*)$/;
862                         foreach my $dir (@{$config{underlaydirs}}) {
863                                 if (-e "$dir/$pobase") {
864                                         File::Copy::syscopy("$dir/$pobase",$pofile)
865                                                 or error("po(refreshpofiles) ".
866                                                          sprintf(gettext("failed to copy underlay PO file to %s"),
867                                                                  $pofile));
868                                 }
869                         }
870                 }
871
872                 if (-e $pofile) {
873                         system("msgmerge", "--previous", "-q", "-U", "--backup=none", $pofile, $potfile) == 0
874                                 or error("po(refreshpofiles) ".
875                                          sprintf(gettext("failed to update %s"),
876                                                  $pofile));
877                 }
878                 else {
879                         File::Copy::syscopy($potfile,$pofile)
880                                 or error("po(refreshpofiles) ".
881                                          sprintf(gettext("failed to copy the POT file to %s"),
882                                                  $pofile));
883                 }
884         }
885 }
886
887 sub buildtranslationscache() {
888         # use istranslation's side-effect
889         map istranslation($_), (keys %pagesources);
890 }
891
892 sub resettranslationscache() {
893         undef %translations;
894 }
895
896 sub flushmemoizecache() {
897         Memoize::flush_cache("istranslatable");
898         Memoize::flush_cache("_istranslation");
899         Memoize::flush_cache("percenttranslated");
900 }
901
902 sub urlto_with_orig_beautiful_urlpath($$) {
903         my $to=shift;
904         my $from=shift;
905
906         inject(name => "IkiWiki::beautify_urlpath", call => $origsubs{'beautify_urlpath'});
907         my $res=urlto($to, $from);
908         inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath);
909
910         return $res;
911 }
912
913 sub percenttranslated ($) {
914         my $page=shift;
915
916         $page=~s/^\///;
917         return gettext("N/A") unless istranslation($page);
918         my $file=srcfile($pagesources{$page});
919         my $masterfile = srcfile($pagesources{masterpage($page)});
920         my %options = (
921                 "markdown" => (pagetype($masterfile) eq 'mdwn') ? 1 : 0,
922         );
923         my $doc=Locale::Po4a::Chooser::new('text',%options);
924         $doc->process(
925                 'po_in_name'    => [ $file ],
926                 'file_in_name'  => [ $masterfile ],
927                 'file_in_charset'  => 'utf-8',
928                 'file_out_charset' => 'utf-8',
929         ) or error("po(percenttranslated) ".
930                    sprintf(gettext("failed to translate %s"), $page));
931         my ($percent,$hit,$queries) = $doc->stats();
932         $percent =~ s/\.[0-9]+$//;
933         return $percent;
934 }
935
936 sub languagename ($) {
937         my $code=shift;
938
939         return $config{po_master_language}{name}
940                 if $code eq $config{po_master_language}{code};
941         return $config{po_slave_languages}{$code}
942                 if defined $config{po_slave_languages}{$code};
943         return;
944 }
945
946 sub otherlanguagesloop ($) {
947         my $page=shift;
948
949         my @ret;
950         my %otherpages=%{otherlanguages($page)};
951         while (my ($lang, $otherpage) = each %otherpages) {
952                 if (istranslation($page) && masterpage($page) eq $otherpage) {
953                         push @ret, {
954                                 url => urlto_with_orig_beautiful_urlpath($otherpage, $page),
955                                 code => $lang,
956                                 language => languagename($lang),
957                                 master => 1,
958                         };
959                 }
960                 elsif (istranslation($otherpage)) {
961                         push @ret, {
962                                 url => urlto_with_orig_beautiful_urlpath($otherpage, $page),
963                                 code => $lang,
964                                 language => languagename($lang),
965                                 percent => percenttranslated($otherpage),
966                         }
967                 }
968         }
969         return sort {
970                 return -1 if $a->{code} eq $config{po_master_language}{code};
971                 return 1 if $b->{code} eq $config{po_master_language}{code};
972                 return $a->{language} cmp $b->{language};
973         } @ret;
974 }
975
976 sub homepageurl (;$) {
977         my $page=shift;
978
979         return urlto('', $page);
980 }
981
982 sub ishomepage ($) {
983         my $page = shift;
984
985         return 1 if $page eq 'index';
986         map { return 1 if $page eq 'index.'.$_ } keys %{$config{po_slave_languages}};
987         return undef;
988 }
989
990 sub deletetranslations ($) {
991         my $deletedmasterfile=shift;
992
993         my $deletedmasterpage=pagename($deletedmasterfile);
994         my @todelete;
995         map {
996                 my $file = newpagefile($deletedmasterpage.'.'.$_, 'po');
997                 my $absfile = "$config{srcdir}/$file";
998                 if (-e $absfile && ! -l $absfile && ! -d $absfile) {
999                         push @todelete, $file;
1000                 }
1001         } keys %{$config{po_slave_languages}};
1002
1003         map {
1004                 if ($config{rcs}) {
1005                         IkiWiki::rcs_remove($_);
1006                 }
1007                 else {
1008                         IkiWiki::prune("$config{srcdir}/$_");
1009                 }
1010         } @todelete;
1011
1012         if (@todelete) {
1013                 commit_and_refresh(
1014                         gettext("removed obsolete PO files"),
1015                         "IkiWiki::Plugin::po::deletetranslations");
1016         }
1017 }
1018
1019 sub commit_and_refresh ($$) {
1020         my ($msg, $author) = (shift, shift);
1021
1022         if ($config{rcs}) {
1023                 IkiWiki::disable_commit_hook();
1024                 IkiWiki::rcs_commit_staged($msg, $author, "127.0.0.1");
1025                 IkiWiki::enable_commit_hook();
1026                 IkiWiki::rcs_update();
1027         }
1028         # Reinitialize module's private variables.
1029         resetalreadyfiltered();
1030         resettranslationscache();
1031         flushmemoizecache();
1032         # Trigger a wiki refresh.
1033         require IkiWiki::Render;
1034         # without preliminary saveindex/loadindex, refresh()
1035         # complains about a lot of uninitialized variables
1036         IkiWiki::saveindex();
1037         IkiWiki::loadindex();
1038         IkiWiki::refresh();
1039         IkiWiki::saveindex();
1040 }
1041
1042 # on success, returns the filtered content.
1043 # on error, if $nonfatal, warn and return undef; else, error out.
1044 sub po_to_markup ($$;$) {
1045         my ($page, $content) = (shift, shift);
1046         my $nonfatal = shift;
1047
1048         $content = '' unless defined $content;
1049         $content = decode_utf8(encode_utf8($content));
1050         # CRLF line terminators make poor Locale::Po4a feel bad
1051         $content=~s/\r\n/\n/g;
1052
1053         # There are incompatibilities between some File::Temp versions
1054         # (including 0.18, bundled with Lenny's perl-modules package)
1055         # and others (e.g. 0.20, previously present in the archive as
1056         # a standalone package): under certain circumstances, some
1057         # return a relative filename, whereas others return an absolute one;
1058         # we here use this module in a way that is at least compatible
1059         # with 0.18 and 0.20. Beware, hit'n'run refactorers!
1060         my $infile = new File::Temp(TEMPLATE => "ikiwiki-po-filter-in.XXXXXXXXXX",
1061                                     DIR => File::Spec->tmpdir,
1062                                     UNLINK => 1)->filename;
1063         my $outfile = new File::Temp(TEMPLATE => "ikiwiki-po-filter-out.XXXXXXXXXX",
1064                                      DIR => File::Spec->tmpdir,
1065                                      UNLINK => 1)->filename;
1066
1067         my $fail = sub ($) {
1068                 my $msg = "po(po_to_markup) - $page : " . shift;
1069                 if ($nonfatal) {
1070                         warn $msg;
1071                         return undef;
1072                 }
1073                 error($msg, sub { unlink $infile, $outfile});
1074         };
1075
1076         writefile(basename($infile), File::Spec->tmpdir, $content)
1077                 or return $fail->(sprintf(gettext("failed to write %s"), $infile));
1078
1079         my $masterfile = srcfile($pagesources{masterpage($page)});
1080         my %options = (
1081                 "markdown" => (pagetype($masterfile) eq 'mdwn') ? 1 : 0,
1082         );
1083         my $doc=Locale::Po4a::Chooser::new('text',%options);
1084         $doc->process(
1085                 'po_in_name'    => [ $infile ],
1086                 'file_in_name'  => [ $masterfile ],
1087                 'file_in_charset'  => 'utf-8',
1088                 'file_out_charset' => 'utf-8',
1089         ) or return $fail->(gettext("failed to translate"));
1090         $doc->write($outfile)
1091                 or return $fail->(sprintf(gettext("failed to write %s"), $outfile));
1092
1093         $content = readfile($outfile)
1094                 or return $fail->(sprintf(gettext("failed to read %s"), $outfile));
1095
1096         # Unlinking should happen automatically, thanks to File::Temp,
1097         # but it does not work here, probably because of the way writefile()
1098         # and Locale::Po4a::write() work.
1099         unlink $infile, $outfile;
1100
1101         return $content;
1102 }
1103
1104 # returns a SuccessReason or FailReason object
1105 sub isvalidpo ($) {
1106         my $content = shift;
1107
1108         # NB: we don't use po_to_markup here, since Po4a parser does
1109         # not mind invalid PO content
1110         $content = '' unless defined $content;
1111         $content = decode_utf8(encode_utf8($content));
1112
1113         # There are incompatibilities between some File::Temp versions
1114         # (including 0.18, bundled with Lenny's perl-modules package)
1115         # and others (e.g. 0.20, previously present in the archive as
1116         # a standalone package): under certain circumstances, some
1117         # return a relative filename, whereas others return an absolute one;
1118         # we here use this module in a way that is at least compatible
1119         # with 0.18 and 0.20. Beware, hit'n'run refactorers!
1120         my $infile = new File::Temp(TEMPLATE => "ikiwiki-po-isvalidpo.XXXXXXXXXX",
1121                                     DIR => File::Spec->tmpdir,
1122                                     UNLINK => 1)->filename;
1123
1124         my $fail = sub ($) {
1125                 my $msg = '[po/isvalidpo] ' . shift;
1126                 unlink $infile;
1127                 return IkiWiki::FailReason->new("$msg");
1128         };
1129
1130         writefile(basename($infile), File::Spec->tmpdir, $content)
1131                 or return $fail->(sprintf(gettext("failed to write %s"), $infile));
1132
1133         my $res = (system("msgfmt", "--check", $infile, "-o", "/dev/null") == 0);
1134
1135         # Unlinking should happen automatically, thanks to File::Temp,
1136         # but it does not work here, probably because of the way writefile()
1137         # and Locale::Po4a::write() work.
1138         unlink $infile;
1139
1140         if ($res) {
1141             return IkiWiki::SuccessReason->new("valid gettext data");
1142         }
1143         return IkiWiki::FailReason->new(gettext("invalid gettext data, go back ".
1144                                         "to previous page to continue edit"));
1145 }
1146
1147 # ,----
1148 # | PageSpecs
1149 # `----
1150
1151 package IkiWiki::PageSpec;
1152
1153 sub match_istranslation ($;@) {
1154         my $page=shift;
1155
1156         if (IkiWiki::Plugin::po::istranslation($page)) {
1157                 return IkiWiki::SuccessReason->new("is a translation page");
1158         }
1159         else {
1160                 return IkiWiki::FailReason->new("is not a translation page");
1161         }
1162 }
1163
1164 sub match_istranslatable ($;@) {
1165         my $page=shift;
1166
1167         if (IkiWiki::Plugin::po::istranslatable($page)) {
1168                 return IkiWiki::SuccessReason->new("is set as translatable in po_translatable_pages");
1169         }
1170         else {
1171                 return IkiWiki::FailReason->new("is not set as translatable in po_translatable_pages");
1172         }
1173 }
1174
1175 sub match_lang ($$;@) {
1176         my $page=shift;
1177         my $wanted=shift;
1178
1179         my $regexp=IkiWiki::glob2re($wanted);
1180         my $lang=IkiWiki::Plugin::po::lang($page);
1181         if ($lang !~ /^$regexp$/i) {
1182                 return IkiWiki::FailReason->new("file language is $lang, not $wanted");
1183         }
1184         else {
1185                 return IkiWiki::SuccessReason->new("file language is $wanted");
1186         }
1187 }
1188
1189 sub match_currentlang ($$;@) {
1190         my $page=shift;
1191         shift;
1192         my %params=@_;
1193
1194         return IkiWiki::FailReason->new("no location provided") unless exists $params{location};
1195
1196         my $currentlang=IkiWiki::Plugin::po::lang($params{location});
1197         my $lang=IkiWiki::Plugin::po::lang($page);
1198
1199         if ($lang eq $currentlang) {
1200                 return IkiWiki::SuccessReason->new("file language is the same as current one, i.e. $currentlang");
1201         }
1202         else {
1203                 return IkiWiki::FailReason->new("file language is $lang, whereas current language is $currentlang");
1204         }
1205 }
1206
1207 1