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