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