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