]> git.vanrenterghem.biz Git - git.ikiwiki.info.git/blob - IkiWiki/Plugin/po.pm
Merge branch 'prv/po' into pub/po
[git.ikiwiki.info.git] / IkiWiki / Plugin / po.pm
1 #!/usr/bin/perl
2 # .po as a wiki page type
3 # inspired by the GPL'd po4a-translate,
4 # which is Copyright 2002, 2003, 2004 by Martin Quinson (mquinson#debian.org)
5 package IkiWiki::Plugin::po;
7 use warnings;
8 use strict;
9 use IkiWiki 2.00;
10 use Encode;
11 use Locale::Po4a::Chooser;
12 use Locale::Po4a::Po;
13 use File::Basename;
14 use File::Copy;
15 use File::Spec;
16 use File::Temp;
17 use Memoize;
19 my %translations;
20 our %filtered;
22 memoize("_istranslation");
23 memoize("percenttranslated");
24 # FIXME: memoizing istranslatable() makes some test cases fail once every
25 # two tries; this may be related to the artificial way the testsuite is
26 # run, or not.
27 # memoize("istranslatable");
29 # backup references to subs that will be overriden
30 my %origsubs;
31 $origsubs{'bestlink'}=\&IkiWiki::bestlink;
32 $origsubs{'beautify_urlpath'}=\&IkiWiki::beautify_urlpath;
33 $origsubs{'targetpage'}=\&IkiWiki::targetpage;
35 sub import {
36         hook(type => "getsetup", id => "po", call => \&getsetup);
37         hook(type => "checkconfig", id => "po", call => \&checkconfig);
38         hook(type => "needsbuild", id => "po", call => \&needsbuild);
39         hook(type => "filter", id => "po", call => \&filter);
40         hook(type => "htmlize", id => "po", call => \&htmlize);
41         hook(type => "pagetemplate", id => "po", call => \&pagetemplate, last => 1);
42         hook(type => "editcontent", id => "po", call => \&editcontent);
43         inject(name => "IkiWiki::bestlink", call => \&mybestlink);
44         inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath);
45         inject(name => "IkiWiki::targetpage", call => \&mytargetpage);
46 }
48 sub getsetup () { #{{{
49         return
50                 plugin => {
51                         safe => 0,
52                         rebuild => 1, # format plugin
53                 },
54                 po_master_language => {
55                         type => "string",
56                         example => {
57                                 'code' => 'en',
58                                 'name' => 'English'
59                         },
60                         description => "master language (non-PO files)",
61                         safe => 0,
62                         rebuild => 1,
63                 },
64                 po_slave_languages => {
65                         type => "string",
66                         example => {
67                                 'fr' => 'Français',
68                                 'es' => 'Castellano',
69                                 'de' => 'Deutsch'
70                         },
71                         description => "slave languages (PO files)",
72                         safe => 0,
73                         rebuild => 1,
74                 },
75                 po_translatable_pages => {
76                         type => "pagespec",
77                         example => "!*/Discussion",
78                         description => "PageSpec controlling which pages are translatable",
79                         link => "ikiwiki/PageSpec",
80                         safe => 0,
81                         rebuild => 1,
82                 },
83                 po_link_to => {
84                         type => "string",
85                         example => "current",
86                         description => "internal linking behavior (default/current/negotiated)",
87                         safe => 0,
88                         rebuild => 1,
89                 },
90 } #}}}
92 sub checkconfig () { #{{{
93         foreach my $field (qw{po_master_language po_slave_languages}) {
94                 if (! exists $config{$field} || ! defined $config{$field}) {
95                         error(sprintf(gettext("Must specify %s"), $field));
96                 }
97         }
98         if (! exists $config{po_link_to} ||
99             ! defined $config{po_link_to}) {
100             $config{po_link_to}="default";
101         }
102         if (! exists $config{po_translatable_pages} ||
103             ! defined $config{po_translatable_pages}) {
104             $config{po_translatable_pages}="";
105         }
106         if ($config{po_link_to} eq "negotiated" && ! $config{usedirs}) {
107                 error(gettext("po_link_to=negotiated requires usedirs to be set"));
108         }
109         push @{$config{wiki_file_prune_regexps}}, qr/\.pot$/;
110 } #}}}
112 sub potfile ($) { #{{{
113         my $masterfile=shift;
114         (my $name, my $dir, my $suffix) = fileparse($masterfile, qr/\.[^.]*/);
115         $dir='' if $dir eq './';
116         return File::Spec->catpath('', $dir, $name . ".pot");
117 } #}}}
119 sub pofile ($$) { #{{{
120         my $masterfile=shift;
121         my $lang=shift;
122         (my $name, my $dir, my $suffix) = fileparse($masterfile, qr/\.[^.]*/);
123         $dir='' if $dir eq './';
124         return File::Spec->catpath('', $dir, $name . "." . $lang . ".po");
125 } #}}}
127 sub refreshpot ($) { #{{{
128         my $masterfile=shift;
129         my $potfile=potfile($masterfile);
130         my %options = ("markdown" => (pagetype($masterfile) eq 'mdwn') ? 1 : 0);
131         my $doc=Locale::Po4a::Chooser::new('text',%options);
132         $doc->read($masterfile);
133         $doc->{TT}{utf_mode} = 1;
134         $doc->{TT}{file_in_charset} = 'utf-8';
135         $doc->{TT}{file_out_charset} = 'utf-8';
136         # let's cheat a bit to force porefs option to be passed to Locale::Po4a::Po;
137         # this is undocument use of internal Locale::Po4a::TransTractor's data,
138         # compulsory since this module prevents us from using the porefs option.
139         my %po_options = ('porefs' => 'none');
140         $doc->{TT}{po_out}=Locale::Po4a::Po->new(\%po_options);
141         $doc->{TT}{po_out}->set_charset('utf-8');
142         # do the actual work
143         $doc->parse;
144         $doc->writepo($potfile);
145 } #}}}
147 sub refreshpofiles ($@) { #{{{
148         my $masterfile=shift;
149         my @pofiles=@_;
151         my $potfile=potfile($masterfile);
152         error("[po/refreshpofiles] POT file ($potfile) does not exist") unless (-e $potfile);
154         foreach my $pofile (@pofiles) {
155                 if (-e $pofile) {
156                         my $cmd = "msgmerge -U --backup=none $pofile $potfile";
157                         system ($cmd) == 0
158                                 or error("[po/refreshpofiles:$pofile] failed to update");
159                 }
160                 else {
161                         File::Copy::syscopy($potfile,$pofile)
162                                 or error("[po/refreshpofiles:$pofile] failed to copy the POT file");
163                 }
164         }
165 } #}}}
167 sub needsbuild () { #{{{
168         my $needsbuild=shift;
170         # build %translations, using istranslation's side-effect
171         foreach my $page (keys %pagesources) {
172                 istranslation($page);
173         }
175         # refresh/create POT and PO files as needed
176         my $updated_po_files=0;
177         foreach my $page (keys %pagesources) {
178                 if (istranslatable($page)) {
179                         my $pageneedsbuild = grep { $_ eq $pagesources{$page} } @$needsbuild;
180                         my $updated_pot_file=0;
181                         my $file=srcfile($pagesources{$page});
182                         if ($pageneedsbuild || ! -e potfile($file)) {
183                                 refreshpot($file);
184                                 $updated_pot_file=1;
185                         }
186                         my @pofiles;
187                         foreach my $lang (keys %{$config{po_slave_languages}}) {
188                                 my $pofile=pofile($file, $lang);
189                                 my $pofile_rel=pofile($pagesources{$page}, $lang);
190                                 if ($pageneedsbuild || $updated_pot_file || ! -e $pofile) {
191                                         push @pofiles, $pofile;
192                                         push @$needsbuild, $pofile_rel
193                                           unless grep { $_ eq $pofile_rel } @$needsbuild;
194                                 }
195                         }
196                         if (@pofiles) {
197                                 refreshpofiles($file, @pofiles) ;
198                                 map { IkiWiki::rcs_add($_); } @pofiles if ($config{rcs});
199                                 $updated_po_files = 1;
200                         }
201                 }
202         }
204         # check staged changes in
205         if ($updated_po_files) {
206                 if ($config{rcs}) {
207                         IkiWiki::disable_commit_hook();
208                         IkiWiki::rcs_commit_staged(gettext("updated PO files"),
209                                 "refreshpofiles", "127.0.0.1");
210                         IkiWiki::enable_commit_hook();
211                         IkiWiki::rcs_update();
212                 }
213                 # refresh module's private variables
214                 undef %filtered;
215                 undef %translations;
216                 foreach my $page (keys %pagesources) {
217                         istranslation($page);
218                 }
219         }
221         # make existing translations depend on the corresponding master page
222         foreach my $master (keys %translations) {
223                 foreach my $slave (values %{$translations{$master}}) {
224                         add_depends($slave, $master);
225                 }
226         }
227 } #}}}
229 sub mytargetpage ($$) { #{{{
230         my $page=shift;
231         my $ext=shift;
233         if (istranslation($page)) {
234                 my ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
235                 if (! $config{usedirs} || $masterpage eq 'index') {
236                         return $masterpage . "." . $lang . "." . $ext;
237                 }
238                 else {
239                         return $masterpage . "/index." . $lang . "." . $ext;
240                 }
241         }
242         elsif (istranslatable($page)) {
243                 if (! $config{usedirs} || $page eq 'index') {
244                         return $page . "." . $config{po_master_language}{code} . "." . $ext;
245                 }
246                 else {
247                         return $page . "/index." . $config{po_master_language}{code} . "." . $ext;
248                 }
249         }
250         return $origsubs{'targetpage'}->($page, $ext);
251 } #}}}
253 sub mybeautify_urlpath ($) { #{{{
254         my $url=shift;
255         my $res=$origsubs{'beautify_urlpath'}->($url);
256         if ($config{po_link_to} eq "negotiated") {
257                 $res =~ s!/index.$config{po_master_language}{code}.$config{htmlext}$!/!;
258         }
259         return $res;
260 } #}}}
262 sub urlto_with_orig_beautiful_urlpath($$) { #{{{
263         my $to=shift;
264         my $from=shift;
266         inject(name => "IkiWiki::beautify_urlpath", call => $origsubs{'beautify_urlpath'});
267         my $res=urlto($to, $from);
268         inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath);
270         return $res;
271 } #}}}
273 sub mybestlink ($$) { #{{{
274         my $page=shift;
275         my $link=shift;
276         my $res=$origsubs{'bestlink'}->($page, $link);
277         if (length $res) {
278                 if ($config{po_link_to} eq "current"
279                     && istranslatable($res)
280                     && istranslation($page)) {
281                         my ($masterpage, $curlang) = ($page =~ /(.*)[.]([a-z]{2})$/);
282                         return $res . "." . $curlang;
283                 }
284                 else {
285                         return $res;
286                 }
287         }
288         return "";
289 } #}}}
291 # We use filter to convert PO to the master page's format,
292 # since the rest of ikiwiki should not work on PO files.
293 sub filter (@) { #{{{
294         my %params = @_;
295         my $page = $params{page};
296         my $destpage = $params{destpage};
297         my $content = decode_utf8(encode_utf8($params{content}));
299         return $content if ( ! istranslation($page)
300                              || ( exists $filtered{$page}{$destpage}
301                                   && $filtered{$page}{$destpage} eq 1 ));
303         # CRLF line terminators make poor Locale::Po4a feel bad
304         $content=~s/\r\n/\n/g;
306         # Locale::Po4a needs an input file, and I'm too lazy to learn
307         # how to disguise a variable as a file
308         my $infile = File::Temp->new(TEMPLATE => "ikiwiki-po-filter-in.XXXXXXXXXX",
309                                      TMPDIR => 1)->filename;
310         writefile(basename($infile), File::Spec->tmpdir, $content);
312         my ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
313         my $masterfile = srcfile($pagesources{$masterpage});
314         my (@pos,@masters);
315         push @pos,$infile;
316         push @masters,$masterfile;
317         my %options = (
318                         "markdown" => (pagetype($masterfile) eq 'mdwn') ? 1 : 0,
319                         );
320         my $doc=Locale::Po4a::Chooser::new('text',%options);
321         $doc->process(
322                 'po_in_name'    => \@pos,
323                 'file_in_name'  => \@masters,
324                 'file_in_charset'  => 'utf-8',
325                 'file_out_charset' => 'utf-8',
326         ) or error("[po/filter:$infile]: failed to translate");
327         my $tmpout = File::Temp->new(TEMPLATE => "ikiwiki-po-filter-out.XXXXXXXXXX",
328                                      TMPDIR => 1)->filename;
329         $doc->write($tmpout) or error("[po/filter:$infile] could not write $tmpout");
330         $content = readfile($tmpout) or error("[po/filter:$infile] could not read $tmpout");
331         $filtered{$page}{$destpage}=1;
332         return $content;
333 } #}}}
335 sub htmlize (@) { #{{{
336         my %params=@_;
337         my $page = $params{page};
338         my $content = $params{content};
339         my ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
340         my $masterfile = srcfile($pagesources{$masterpage});
342         # force content to be htmlize'd as if it was the same type as the master page
343         return IkiWiki::htmlize($page, $page, pagetype($masterfile), $content);
344 } #}}}
346 sub percenttranslated ($) { #{{{
347         my $page=shift;
348         return "N/A" unless (istranslation($page));
349         my ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
350         my $file=srcfile($pagesources{$page});
351         my $masterfile = srcfile($pagesources{$masterpage});
352         my (@pos,@masters);
353         push @pos,$file;
354         push @masters,$masterfile;
355         my %options = (
356                         "markdown" => (pagetype($masterfile) eq 'mdwn') ? 1 : 0,
357                         );
358         my $doc=Locale::Po4a::Chooser::new('text',%options);
359         $doc->process(
360                 'po_in_name'    => \@pos,
361                 'file_in_name'  => \@masters,
362                 'file_in_charset'  => 'utf-8',
363                 'file_out_charset' => 'utf-8',
364         ) or error("[po/percenttranslated:$file]: failed to translate");
365         my ($percent,$hit,$queries) = $doc->stats();
366         return $percent;
367 } #}}}
369 sub otherlanguages ($) { #{{{
370         my $page=shift;
371         my @ret;
372         if (istranslatable($page)) {
373                 foreach my $lang (sort keys %{$translations{$page}}) {
374                         my $translation = $translations{$page}{$lang};
375                         push @ret, {
376                                 url => urlto($translation, $page),
377                                 code => $lang,
378                                 language => $config{po_slave_languages}{$lang},
379                                 percent => percenttranslated($translation),
380                         };
381                 }
382         }
383         elsif (istranslation($page)) {
384                 my ($masterpage, $curlang) = ($page =~ /(.*)[.]([a-z]{2})$/);
385                 push @ret, {
386                         url => urlto_with_orig_beautiful_urlpath($masterpage, $page),
387                         code => $config{po_master_language}{code},
388                         language => $config{po_master_language}{name},
389                         master => 1,
390                 };
391                 foreach my $lang (sort keys %{$translations{$masterpage}}) {
392                         push @ret, {
393                                 url => urlto($translations{$masterpage}{$lang}, $page),
394                                 code => $lang,
395                                 language => $config{po_slave_languages}{$lang},
396                                 percent => percenttranslated($translations{$masterpage}{$lang}),
397                         } unless ($lang eq $curlang);
398                 }
399         }
400         return @ret;
401 } #}}}
403 sub pagetemplate (@) { #{{{
404         my %params=@_;
405         my $page=$params{page};
406         my $destpage=$params{destpage};
407         my $template=$params{template};
408         my ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/) if istranslation($page);
410         if (istranslation($page) && $template->query(name => "percenttranslated")) {
411                 $template->param(percenttranslated => percenttranslated($page));
412         }
413         if ($template->query(name => "istranslation")) {
414                 $template->param(istranslation => istranslation($page));
415         }
416         if ($template->query(name => "istranslatable")) {
417                 $template->param(istranslatable => istranslatable($page));
418         }
419         if ($template->query(name => "otherlanguages")) {
420                 $template->param(otherlanguages => [otherlanguages($page)]);
421                 if (istranslatable($page)) {
422                         foreach my $translation (values %{$translations{$page}}) {
423                                 add_depends($page, $translation);
424                         }
425                 }
426                 elsif (istranslation($page)) {
427                         add_depends($page, $masterpage);
428                         foreach my $translation (values %{$translations{$masterpage}}) {
429                                 add_depends($page, $translation);
430                         }
431                 }
432         }
433         # Rely on IkiWiki::Render's genpage() to decide wether
434         # a discussion link should appear on $page; this is not
435         # totally accurate, though: some broken links may be generated
436         # when cgiurl is disabled.
437         # This compromise avoids some code duplication, and will probably
438         # prevent future breakage when ikiwiki internals change.
439         # Known limitations are preferred to future random bugs.
440         if ($template->param('discussionlink') && istranslation($page)) {
441                 $template->param('discussionlink' => htmllink(
442                                                         $page,
443                                                         $destpage,
444                                                         $masterpage . '/' . gettext("Discussion"),
445                                                         noimageinline => 1,
446                                                         forcesubpage => 0,
447                                                         linktext => gettext("Discussion"),
448                                                         ));
449         }
450         # remove broken parentlink to ./index.html on home page's translations
451         if ($template->param('parentlinks')
452             && istranslation($page)
453             && $masterpage eq "index") {
454                 $template->param('parentlinks' => []);
455         }
456 } # }}}
458 sub editcontent () { #{{{
459         my %params=@_;
460         # as we're previewing or saving a page, the content may have
461         # changed, so tell the next filter() invocation it must not be lazy
462         if (exists $filtered{$params{page}}{$params{page}}) {
463                 delete $filtered{$params{page}}{$params{page}};
464         }
465         return $params{content};
466 } #}}}
468 sub istranslatable ($) { #{{{
469         my $page=shift;
470         my $file=$pagesources{$page};
472         if (! defined $file
473             || (defined pagetype($file) && pagetype($file) eq 'po')
474             || $file =~ /\.pot$/) {
475                 return 0;
476         }
477         return pagespec_match($page, $config{po_translatable_pages});
478 } #}}}
480 sub _istranslation ($) { #{{{
481         my $page=shift;
482         my $file=$pagesources{$page};
483         if (! defined $file) {
484                 return IkiWiki::FailReason->new("no file specified");
485         }
487         if (! defined $file
488             || ! defined pagetype($file)
489             || ! pagetype($file) eq 'po'
490             || $file =~ /\.pot$/) {
491                 return 0;
492         }
494         my ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
495         if (! defined $masterpage || ! defined $lang
496             || ! (length($masterpage) > 0) || ! (length($lang) > 0)
497             || ! defined $pagesources{$masterpage}
498             || ! defined $config{po_slave_languages}{$lang}) {
499                 return 0;
500         }
502         return istranslatable($masterpage);
503 } #}}}
505 sub istranslation ($) { #{{{
506         my $page=shift;
507         if (_istranslation($page)) {
508                 my ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
509                 $translations{$masterpage}{$lang}=$page unless exists $translations{$masterpage}{$lang};
510                 return 1;
511         }
512         return 0;
513 } #}}}
515 package IkiWiki::PageSpec;
516 use warnings;
517 use strict;
518 use IkiWiki 2.00;
520 sub match_istranslation ($;@) { #{{{
521         my $page=shift;
522         if (IkiWiki::Plugin::po::istranslation($page)) {
523                 return IkiWiki::SuccessReason->new("is a translation page");
524         }
525         else {
526                 return IkiWiki::FailReason->new("is not a translation page");
527         }
528 } #}}}
530 sub match_istranslatable ($;@) { #{{{
531         my $page=shift;
532         if (IkiWiki::Plugin::po::istranslatable($page)) {
533                 return IkiWiki::SuccessReason->new("is set as translatable in po_translatable_pages");
534         }
535         else {
536                 return IkiWiki::FailReason->new("is not set as translatable in po_translatable_pages");
537         }
538 } #}}}
540 sub match_lang ($$;@) { #{{{
541         my $page=shift;
542         my $wanted=shift;
543         my $regexp=IkiWiki::glob2re($wanted);
544         my $lang;
545         my $masterpage;
547         if (IkiWiki::Plugin::po::istranslation($page)) {
548                 ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
549         }
550         else {
551                 $lang = $config{po_master_language}{code};
552         }
554         if ($lang!~/^$regexp$/i) {
555                 return IkiWiki::FailReason->new("file language is $lang, not $wanted");
556         }
557         else {
558                 return IkiWiki::SuccessReason->new("file language is $wanted");
559         }
560 } #}}}
562 sub match_currentlang ($$;@) { #{{{
563         my $page=shift;
564         shift;
565         my %params=@_;
566         my ($currentmasterpage, $currentlang, $masterpage, $lang);
568         return IkiWiki::FailReason->new("no location provided") unless exists $params{location};
570         if (IkiWiki::Plugin::po::istranslation($params{location})) {
571                 ($currentmasterpage, $currentlang) = ($params{location} =~ /(.*)[.]([a-z]{2})$/);
572         }
573         else {
574                 $currentlang = $config{po_master_language}{code};
575         }
577         if (IkiWiki::Plugin::po::istranslation($page)) {
578                 ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
579         }
580         else {
581                 $lang = $config{po_master_language}{code};
582         }
584         if ($lang eq $currentlang) {
585                 return IkiWiki::SuccessReason->new("file language is the same as current one, i.e. $currentlang");
586         }
587         else {
588                 return IkiWiki::FailReason->new("file language is $lang, whereas current language is $currentlang");
589         }
590 } #}}}