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