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