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