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