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