]> sipb.mit.edu Git - ikiwiki.git/blob - IkiWiki/Plugin/po.pm
88f8194fbe7cb70bb93c15c74dd14a1dbe96ae5a
[ikiwiki.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;
6
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;
18
19 my %translations;
20 our %filtered;
21
22 ## FIXME: makes some test cases cry once every two tries; this may be
23 ## related to the artificial way the testsuite is run, or not.
24 # memoize("istranslatable");
25 memoize("_istranslation");
26 memoize("percenttranslated");
27
28 # backup references to subs that will be overriden
29 my %origsubs;
30 $origsubs{'bestlink'}=\&IkiWiki::bestlink;
31 $origsubs{'beautify_urlpath'}=\&IkiWiki::beautify_urlpath;
32 $origsubs{'targetpage'}=\&IkiWiki::targetpage;
33
34 sub import {
35         hook(type => "getsetup", id => "po", call => \&getsetup);
36         hook(type => "checkconfig", id => "po", call => \&checkconfig);
37         hook(type => "needsbuild", id => "po", call => \&needsbuild);
38         hook(type => "filter", id => "po", call => \&filter);
39         hook(type => "htmlize", id => "po", call => \&htmlize);
40         hook(type => "pagetemplate", id => "po", call => \&pagetemplate);
41         inject(name => "IkiWiki::bestlink", call => \&mybestlink);
42         inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath);
43         inject(name => "IkiWiki::targetpage", call => \&mytargetpage);
44 }
45
46 sub getsetup () { #{{{
47         return
48                 plugin => {
49                         safe => 0,
50                         rebuild => 1, # format plugin
51                 },
52                 po_master_language => {
53                         type => "string",
54                         example => {
55                                 'code' => 'en',
56                                 'name' => 'English'
57                         },
58                         description => "master language (non-PO files)",
59                         safe => 0,
60                         rebuild => 1,
61                 },
62                 po_slave_languages => {
63                         type => "string",
64                         example => {
65                                 'fr' => 'Français',
66                                 'es' => 'Castellano',
67                                 'de' => 'Deutsch'
68                         },
69                         description => "slave languages (PO files)",
70                         safe => 0,
71                         rebuild => 1,
72                 },
73                 po_translatable_pages => {
74                         type => "pagespec",
75                         example => "!*/Discussion",
76                         description => "PageSpec controlling which pages are translatable",
77                         link => "ikiwiki/PageSpec",
78                         safe => 0,
79                         rebuild => 1,
80                 },
81                 po_link_to => {
82                         type => "string",
83                         example => "current",
84                         description => "internal linking behavior (default/current/negotiated)",
85                         safe => 0,
86                         rebuild => 1,
87                 },
88 } #}}}
89
90 sub checkconfig () { #{{{
91         foreach my $field (qw{po_master_language po_slave_languages}) {
92                 if (! exists $config{$field} || ! defined $config{$field}) {
93                         error(sprintf(gettext("Must specify %s"), $field));
94                 }
95         }
96         if (! exists $config{po_link_to} ||
97             ! defined $config{po_link_to}) {
98             $config{po_link_to}="default";
99         }
100         if (! exists $config{po_translatable_pages} ||
101             ! defined $config{po_translatable_pages}) {
102             $config{po_translatable_pages}="";
103         }
104         if ($config{po_link_to} eq "negotiated" && ! $config{usedirs}) {
105                 error(gettext("po_link_to=negotiated requires usedirs to be set"));
106         }
107         push @{$config{wiki_file_prune_regexps}}, qr/\.pot$/;
108 } #}}}
109
110 sub potfile ($) { #{{{
111         my $masterfile=shift;
112         (my $name, my $dir, my $suffix) = fileparse($masterfile, qr/\.[^.]*/);
113         return File::Spec->catfile($dir, $name . ".pot");
114 } #}}}
115
116 sub pofile ($$) { #{{{
117         my $masterfile=shift;
118         my $lang=shift;
119         (my $name, my $dir, my $suffix) = fileparse($masterfile, qr/\.[^.]*/);
120         return File::Spec->catfile($dir, $name . "." . $lang . ".po");
121 } #}}}
122
123 sub refreshpot ($) { #{{{
124         my $masterfile=shift;
125         my $potfile=potfile($masterfile);
126         my %options = ("markdown" => (pagetype($masterfile) eq 'mdwn') ? 1 : 0);
127         my $doc=Locale::Po4a::Chooser::new('text',%options);
128         $doc->read($masterfile);
129         $doc->{TT}{utf_mode} = 1;
130         $doc->{TT}{file_in_charset} = 'utf-8';
131         $doc->{TT}{file_out_charset} = 'utf-8';
132         # let's cheat a bit to force porefs option to be passed to Locale::Po4a::Po;
133         # this is undocument use of internal Locale::Po4a::TransTractor's data,
134         # compulsory since this module prevents us from using the porefs option.
135         my %po_options = ('porefs' => 'none');
136         $doc->{TT}{po_out}=Locale::Po4a::Po->new(\%po_options);
137         # do the actual work
138         $doc->parse;
139         $doc->writepo($potfile);
140 } #}}}
141
142 sub refreshpofiles ($@) { #{{{
143         my $masterfile=shift;
144         my @pofiles=@_;
145
146         my $potfile=potfile($masterfile);
147         error("[po/refreshpofiles] POT file ($potfile) does not exist") unless (-e $potfile);
148
149         foreach my $pofile (@pofiles) {
150                 if (-e $pofile) {
151                         my $cmd = "msgmerge -U --backup=none $pofile $potfile";
152                         system ($cmd) == 0
153                                 or error("[po/refreshpofiles:$pofile] failed to update");
154                 }
155                 else {
156                         File::Copy::syscopy($potfile,$pofile)
157                                 or error("[po/refreshpofiles:$pofile] failed to copy the POT file");
158                 }
159         }
160 } #}}}
161
162 sub needsbuild () { #{{{
163         my $needsbuild=shift;
164
165         # build %translations, using istranslation's side-effect
166         foreach my $page (keys %pagesources) {
167                 istranslation($page);
168         }
169
170         # refresh/create POT and PO files as needed
171         my $updated_po_files=0;
172         foreach my $page (keys %pagesources) {
173                 my $pageneedsbuild = grep { $_ eq $pagesources{$page} } @$needsbuild;
174                 if (istranslatable($page)) {
175                         my $file=srcfile($pagesources{$page});
176                         if ($pageneedsbuild || ! -e potfile($file)) {
177                                 refreshpot($file);
178                         }
179                         my @pofiles;
180                         foreach my $lang (keys %{$config{po_slave_languages}}) {
181                                 my $pofile=pofile($file, $lang);
182                                 if ($pageneedsbuild || ! -e $pofile) {
183                                         push @pofiles, $pofile;
184                                 }
185                         }
186                         if (@pofiles) {
187                                 refreshpofiles($file, @pofiles) ;
188                                 map { IkiWiki::rcs_add($_); } @pofiles if ($config{rcs});
189                                 $updated_po_files = 1;
190                         }
191                 }
192         }
193
194         # check staged changes in and trigger a wiki refresh.
195         if ($updated_po_files) {
196                 if ($config{rcs}) {
197                         IkiWiki::disable_commit_hook();
198                         IkiWiki::rcs_commit_staged(gettext("updated PO files"),
199                                 "refreshpofiles", "127.0.0.1");
200                         IkiWiki::enable_commit_hook();
201                         IkiWiki::rcs_update();
202                 }
203                 IkiWiki::refresh();
204                 IkiWiki::saveindex();
205                 # refresh module's private variables
206                 %filtered=undef;
207                 %translations=undef;
208                 foreach my $page (keys %pagesources) {
209                         istranslation($page);
210                 }
211         }
212
213
214         # make existing translations depend on the corresponding master page
215         foreach my $master (keys %translations) {
216                 foreach my $slave (values %{$translations{$master}}) {
217                         add_depends($slave, $master);
218                 }
219         }
220 } #}}}
221
222 sub mytargetpage ($$) { #{{{
223         my $page=shift;
224         my $ext=shift;
225
226         if (istranslation($page)) {
227                 my ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
228                 if (! $config{usedirs} || $masterpage eq 'index') {
229                         return $masterpage . "." . $lang . "." . $ext;
230                 }
231                 else {
232                         return $masterpage . "/index." . $lang . "." . $ext;
233                 }
234         }
235         elsif (istranslatable($page)) {
236                 if (! $config{usedirs} || $page eq 'index') {
237                         return $page . "." . $config{po_master_language}{code} . "." . $ext;
238                 }
239                 else {
240                         return $page . "/index." . $config{po_master_language}{code} . "." . $ext;
241                 }
242         }
243         return $origsubs{'targetpage'}->($page, $ext);
244 } #}}}
245
246 sub mybeautify_urlpath ($) { #{{{
247         my $url=shift;
248         my $res=$origsubs{'beautify_urlpath'}->($url);
249         if ($config{po_link_to} eq "negotiated") {
250                 $res =~ s!/index.$config{po_master_language}{code}.$config{htmlext}$!/!;
251         }
252         return $res;
253 } #}}}
254
255 sub mybestlink ($$) { #{{{
256         my $page=shift;
257         my $link=shift;
258         my $res=$origsubs{'bestlink'}->($page, $link);
259         if (length $res) {
260                 if ($config{po_link_to} eq "current"
261                     && istranslatable($res)
262                     && istranslation($page)) {
263                         my ($masterpage, $curlang) = ($page =~ /(.*)[.]([a-z]{2})$/);
264                         return $res . "." . $curlang;
265                 }
266                 else {
267                         return $res;
268                 }
269         }
270         return "";
271 } #}}}
272
273 # We use filter to convert PO to the master page's type,
274 # since other plugins should not work on PO files
275 sub filter (@) { #{{{
276         my %params = @_;
277         my $page = $params{page};
278         my $destpage = $params{destpage};
279         my $content = decode_utf8(encode_utf8($params{content}));
280
281         # decide if this is a PO file that should be converted into a translated document,
282         # and perform various sanity checks
283         if (! istranslation($page) || $filtered{$page}{$destpage}) {
284                 return $content;
285         }
286
287         my ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
288         my $file=srcfile(exists $params{file} ? $params{file} : $IkiWiki::pagesources{$page});
289         my $masterfile = srcfile($pagesources{$masterpage});
290         my (@pos,@masters);
291         push @pos,$file;
292         push @masters,$masterfile;
293         my %options = (
294                         "markdown" => (pagetype($masterfile) eq 'mdwn') ? 1 : 0,
295                         );
296         my $doc=Locale::Po4a::Chooser::new('text',%options);
297         $doc->process(
298                 'po_in_name'    => \@pos,
299                 'file_in_name'  => \@masters,
300                 'file_in_charset'  => 'utf-8',
301                 'file_out_charset' => 'utf-8',
302         ) or error("[po/filter:$file]: failed to translate");
303         my $tmpfh = File::Temp->new(TEMPLATE => "/tmp/ikiwiki-po-filter-out.XXXXXXXXXX");
304         my $tmpout = $tmpfh->filename;
305         $doc->write($tmpout) or error("[po/filter:$file] could not write $tmpout");
306         $content = readfile($tmpout) or error("[po/filter:$file] could not read $tmpout");
307         $filtered{$page}{$destpage}=1;
308         return $content;
309 } #}}}
310
311 sub htmlize (@) { #{{{
312         my %params=@_;
313         my $page = $params{page};
314         my $content = $params{content};
315         my ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
316         my $masterfile = srcfile($pagesources{$masterpage});
317
318         # force content to be htmlize'd as if it was the same type as the master page
319         return IkiWiki::htmlize($page, $page, pagetype($masterfile), $content);
320 } #}}}
321
322 sub percenttranslated ($) { #{{{
323         my $page=shift;
324         return "N/A" unless (istranslation($page));
325         my ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
326         my $file=srcfile($pagesources{$page});
327         my $masterfile = srcfile($pagesources{$masterpage});
328         my (@pos,@masters);
329         push @pos,$file;
330         push @masters,$masterfile;
331         my %options = (
332                         "markdown" => (pagetype($masterfile) eq 'mdwn') ? 1 : 0,
333                         );
334         my $doc=Locale::Po4a::Chooser::new('text',%options);
335         $doc->process(
336                 'po_in_name'    => \@pos,
337                 'file_in_name'  => \@masters,
338                 'file_in_charset'  => 'utf-8',
339                 'file_out_charset' => 'utf-8',
340         ) or error("[po/percenttranslated:$file]: failed to translate");
341         my ($percent,$hit,$queries) = $doc->stats();
342         return $percent;
343 } #}}}
344
345 sub otherlanguages ($) { #{{{
346         my $page=shift;
347         my @ret;
348         if (istranslatable($page)) {
349                 foreach my $lang (sort keys %{$translations{$page}}) {
350                         my $translation = $translations{$page}{$lang};
351                         push @ret, {
352                                 url => urlto($translation, $page),
353                                 code => $lang,
354                                 language => $config{po_slave_languages}{$lang},
355                                 percent => percenttranslated($translation),
356                         };
357                 }
358         }
359         elsif (istranslation($page)) {
360                 my ($masterpage, $curlang) = ($page =~ /(.*)[.]([a-z]{2})$/);
361                 push @ret, {
362                         url => urlto($masterpage, $page),
363                         code => $config{po_master_language}{code},
364                         language => $config{po_master_language}{name},
365                         master => 1,
366                 };
367                 foreach my $lang (sort keys %{$translations{$masterpage}}) {
368                         push @ret, {
369                                 url => urlto($translations{$masterpage}{$lang}, $page),
370                                 code => $lang,
371                                 language => $config{po_slave_languages}{$lang},
372                                 percent => percenttranslated($translations{$masterpage}{$lang}),
373                         } unless ($lang eq $curlang);
374                 }
375         }
376         return @ret;
377 } #}}}
378
379 sub pagetemplate (@) { #{{{
380         my %params=@_;
381         my $page=$params{page};
382         my $template=$params{template};
383
384         if (istranslation($page) && $template->query(name => "percenttranslated")) {
385                 $template->param(percenttranslated => percenttranslated($page));
386         }
387         if ($template->query(name => "istranslation")) {
388                 $template->param(istranslation => istranslation($page));
389         }
390         if ($template->query(name => "istranslatable")) {
391                 $template->param(istranslatable => istranslatable($page));
392         }
393         if ($template->query(name => "otherlanguages")) {
394                 $template->param(otherlanguages => [otherlanguages($page)]);
395                 if (istranslatable($page)) {
396                         foreach my $translation (values %{$translations{$page}}) {
397                                 add_depends($page, $translation);
398                         }
399                 }
400                 elsif (istranslation($page)) {
401                         my ($masterpage, $curlang) = ($page =~ /(.*)[.]([a-z]{2})$/);
402                         add_depends($page, $masterpage);
403                         foreach my $translation (values %{$translations{$masterpage}}) {
404                                 add_depends($page, $translation);
405                         }
406                 }
407         }
408 } # }}}
409
410 sub istranslatable ($) { #{{{
411         my $page=shift;
412         my $file=$pagesources{$page};
413
414         if (! defined $file
415             || (defined pagetype($file) && pagetype($file) eq 'po')
416             || $file =~ /\.pot$/) {
417                 return 0;
418         }
419         return pagespec_match($page, $config{po_translatable_pages});
420 } #}}}
421
422 sub _istranslation ($) { #{{{
423         my $page=shift;
424         my $file=$pagesources{$page};
425         if (! defined $file) {
426                 return IkiWiki::FailReason->new("no file specified");
427         }
428
429         if (! defined $file
430             || ! defined pagetype($file)
431             || ! pagetype($file) eq 'po'
432             || $file =~ /\.pot$/) {
433                 return 0;
434         }
435
436         my ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
437         if (! defined $masterpage || ! defined $lang
438             || ! (length($masterpage) > 0) || ! (length($lang) > 0)
439             || ! defined $pagesources{$masterpage}
440             || ! defined $config{po_slave_languages}{$lang}) {
441                 return 0;
442         }
443
444         return istranslatable($masterpage);
445 } #}}}
446
447 sub istranslation ($) { #{{{
448         my $page=shift;
449         if (_istranslation($page)) {
450                 my ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
451                 $translations{$masterpage}{$lang}=$page unless exists $translations{$masterpage}{$lang};
452                 return 1;
453         }
454         return 0;
455 } #}}}
456
457 package IkiWiki::PageSpec;
458 use warnings;
459 use strict;
460 use IkiWiki 2.00;
461
462 sub match_istranslation ($;@) { #{{{
463         my $page=shift;
464         if (IkiWiki::Plugin::po::istranslation($page)) {
465                 return IkiWiki::SuccessReason->new("is a translation page");
466         }
467         else {
468                 return IkiWiki::FailReason->new("is not a translation page");
469         }
470 } #}}}
471
472 sub match_istranslatable ($;@) { #{{{
473         my $page=shift;
474         if (IkiWiki::Plugin::po::istranslatable($page)) {
475                 return IkiWiki::SuccessReason->new("is set as translatable in po_translatable_pages");
476         }
477         else {
478                 return IkiWiki::FailReason->new("is not set as translatable in po_translatable_pages");
479         }
480 } #}}}
481
482 sub match_lang ($$;@) { #{{{
483         my $page=shift;
484         my $wanted=shift;
485         my $regexp=IkiWiki::glob2re($wanted);
486         my $lang;
487         my $masterpage;
488
489         if (IkiWiki::Plugin::po::istranslation($page)) {
490                 ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
491         }
492         else {
493                 $lang = $config{po_master_language}{code};
494         }
495
496         if ($lang!~/^$regexp$/i) {
497                 return IkiWiki::FailReason->new("file language is $lang, not $wanted");
498         }
499         else {
500                 return IkiWiki::SuccessReason->new("file language is $wanted");
501         }
502 } #}}}
503
504 sub match_currentlang ($$;@) { #{{{
505         my $page=shift;
506         shift;
507         my %params=@_;
508         my ($currentmasterpage, $currentlang, $masterpage, $lang);
509
510         return IkiWiki::FailReason->new("no location provided") unless exists $params{location};
511
512         if (IkiWiki::Plugin::po::istranslation($params{location})) {
513                 ($currentmasterpage, $currentlang) = ($params{location} =~ /(.*)[.]([a-z]{2})$/);
514         }
515         else {
516                 $currentlang = $config{po_master_language}{code};
517         }
518
519         if (IkiWiki::Plugin::po::istranslation($page)) {
520                 ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
521         }
522         else {
523                 $lang = $config{po_master_language}{code};
524         }
525
526         if ($lang eq $currentlang) {
527                 return IkiWiki::SuccessReason->new("file language is the same as current one, i.e. $currentlang");
528         }
529         else {
530                 return IkiWiki::FailReason->new("file language is $lang, whereas current language is $currentlang");
531         }
532 } #}}}
533
534 1