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