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