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