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