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