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