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