]> sipb.mit.edu Git - ikiwiki.git/blob - IkiWiki/Plugin/po.pm
59d938d821151a1f9f0ec3bac27c1a18f8c406ec
[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         $doc->{TT}{po_out}->set_charset('utf-8');
138         # do the actual work
139         $doc->parse;
140         $doc->writepo($potfile);
141 } #}}}
142
143 sub refreshpofiles ($@) { #{{{
144         my $masterfile=shift;
145         my @pofiles=@_;
146
147         my $potfile=potfile($masterfile);
148         error("[po/refreshpofiles] POT file ($potfile) does not exist") unless (-e $potfile);
149
150         foreach my $pofile (@pofiles) {
151                 if (-e $pofile) {
152                         my $cmd = "msgmerge -U --backup=none $pofile $potfile";
153                         system ($cmd) == 0
154                                 or error("[po/refreshpofiles:$pofile] failed to update");
155                 }
156                 else {
157                         File::Copy::syscopy($potfile,$pofile)
158                                 or error("[po/refreshpofiles:$pofile] failed to copy the POT file");
159                 }
160         }
161 } #}}}
162
163 sub needsbuild () { #{{{
164         my $needsbuild=shift;
165
166         # build %translations, using istranslation's side-effect
167         foreach my $page (keys %pagesources) {
168                 istranslation($page);
169         }
170
171         # refresh/create POT and PO files as needed
172         my $updated_po_files=0;
173         foreach my $page (keys %pagesources) {
174                 my $pageneedsbuild = grep { $_ eq $pagesources{$page} } @$needsbuild;
175                 if (istranslatable($page)) {
176                         my $file=srcfile($pagesources{$page});
177                         if ($pageneedsbuild || ! -e potfile($file)) {
178                                 refreshpot($file);
179                         }
180                         my @pofiles;
181                         foreach my $lang (keys %{$config{po_slave_languages}}) {
182                                 my $pofile=pofile($file, $lang);
183                                 if ($pageneedsbuild || ! -e $pofile) {
184                                         push @pofiles, $pofile;
185                                 }
186                         }
187                         if (@pofiles) {
188                                 refreshpofiles($file, @pofiles) ;
189                                 map { IkiWiki::rcs_add($_); } @pofiles if ($config{rcs});
190                                 $updated_po_files = 1;
191                         }
192                 }
193         }
194
195         # check staged changes in and trigger a wiki refresh.
196         if ($updated_po_files) {
197                 if ($config{rcs}) {
198                         IkiWiki::disable_commit_hook();
199                         IkiWiki::rcs_commit_staged(gettext("updated PO files"),
200                                 "refreshpofiles", "127.0.0.1");
201                         IkiWiki::enable_commit_hook();
202                         IkiWiki::rcs_update();
203                 }
204                 IkiWiki::refresh();
205                 IkiWiki::saveindex();
206                 # refresh module's private variables
207                 %filtered=undef;
208                 %translations=undef;
209                 foreach my $page (keys %pagesources) {
210                         istranslation($page);
211                 }
212         }
213
214
215         # make existing translations depend on the corresponding master page
216         foreach my $master (keys %translations) {
217                 foreach my $slave (values %{$translations{$master}}) {
218                         add_depends($slave, $master);
219                 }
220         }
221 } #}}}
222
223 sub mytargetpage ($$) { #{{{
224         my $page=shift;
225         my $ext=shift;
226
227         if (istranslation($page)) {
228                 my ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
229                 if (! $config{usedirs} || $masterpage eq 'index') {
230                         return $masterpage . "." . $lang . "." . $ext;
231                 }
232                 else {
233                         return $masterpage . "/index." . $lang . "." . $ext;
234                 }
235         }
236         elsif (istranslatable($page)) {
237                 if (! $config{usedirs} || $page eq 'index') {
238                         return $page . "." . $config{po_master_language}{code} . "." . $ext;
239                 }
240                 else {
241                         return $page . "/index." . $config{po_master_language}{code} . "." . $ext;
242                 }
243         }
244         return $origsubs{'targetpage'}->($page, $ext);
245 } #}}}
246
247 sub mybeautify_urlpath ($) { #{{{
248         my $url=shift;
249         my $res=$origsubs{'beautify_urlpath'}->($url);
250         if ($config{po_link_to} eq "negotiated") {
251                 $res =~ s!/index.$config{po_master_language}{code}.$config{htmlext}$!/!;
252         }
253         return $res;
254 } #}}}
255
256 sub urlto_with_orig_beautiful_urlpath($$) { #{{{
257         my $to=shift;
258         my $from=shift;
259
260         inject(name => "IkiWiki::beautify_urlpath", call => $origsubs{'beautify_urlpath'});
261         my $res=urlto($to, $from);
262         inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath);
263
264         return $res;
265 } #}}}
266
267 sub mybestlink ($$) { #{{{
268         my $page=shift;
269         my $link=shift;
270         my $res=$origsubs{'bestlink'}->($page, $link);
271         if (length $res) {
272                 if ($config{po_link_to} eq "current"
273                     && istranslatable($res)
274                     && istranslation($page)) {
275                         my ($masterpage, $curlang) = ($page =~ /(.*)[.]([a-z]{2})$/);
276                         return $res . "." . $curlang;
277                 }
278                 else {
279                         return $res;
280                 }
281         }
282         return "";
283 } #}}}
284
285 # We use filter to convert PO to the master page's type,
286 # since other plugins should not work on PO files
287 sub filter (@) { #{{{
288         my %params = @_;
289         my $page = $params{page};
290         my $destpage = $params{destpage};
291         my $content = decode_utf8(encode_utf8($params{content}));
292
293         # decide if this is a PO file that should be converted into a translated document,
294         # and perform various sanity checks
295         if (! istranslation($page) || $filtered{$page}{$destpage}) {
296                 return $content;
297         }
298
299         my ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
300         my $file=srcfile(exists $params{file} ? $params{file} : $IkiWiki::pagesources{$page});
301         my $masterfile = srcfile($pagesources{$masterpage});
302         my (@pos,@masters);
303         push @pos,$file;
304         push @masters,$masterfile;
305         my %options = (
306                         "markdown" => (pagetype($masterfile) eq 'mdwn') ? 1 : 0,
307                         );
308         my $doc=Locale::Po4a::Chooser::new('text',%options);
309         $doc->process(
310                 'po_in_name'    => \@pos,
311                 'file_in_name'  => \@masters,
312                 'file_in_charset'  => 'utf-8',
313                 'file_out_charset' => 'utf-8',
314         ) or error("[po/filter:$file]: failed to translate");
315         my $tmpfh = File::Temp->new(TEMPLATE => "/tmp/ikiwiki-po-filter-out.XXXXXXXXXX");
316         my $tmpout = $tmpfh->filename;
317         $doc->write($tmpout) or error("[po/filter:$file] could not write $tmpout");
318         $content = readfile($tmpout) or error("[po/filter:$file] could not read $tmpout");
319         $filtered{$page}{$destpage}=1;
320         return $content;
321 } #}}}
322
323 sub htmlize (@) { #{{{
324         my %params=@_;
325         my $page = $params{page};
326         my $content = $params{content};
327         my ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
328         my $masterfile = srcfile($pagesources{$masterpage});
329
330         # force content to be htmlize'd as if it was the same type as the master page
331         return IkiWiki::htmlize($page, $page, pagetype($masterfile), $content);
332 } #}}}
333
334 sub percenttranslated ($) { #{{{
335         my $page=shift;
336         return "N/A" unless (istranslation($page));
337         my ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
338         my $file=srcfile($pagesources{$page});
339         my $masterfile = srcfile($pagesources{$masterpage});
340         my (@pos,@masters);
341         push @pos,$file;
342         push @masters,$masterfile;
343         my %options = (
344                         "markdown" => (pagetype($masterfile) eq 'mdwn') ? 1 : 0,
345                         );
346         my $doc=Locale::Po4a::Chooser::new('text',%options);
347         $doc->process(
348                 'po_in_name'    => \@pos,
349                 'file_in_name'  => \@masters,
350                 'file_in_charset'  => 'utf-8',
351                 'file_out_charset' => 'utf-8',
352         ) or error("[po/percenttranslated:$file]: failed to translate");
353         my ($percent,$hit,$queries) = $doc->stats();
354         return $percent;
355 } #}}}
356
357 sub otherlanguages ($) { #{{{
358         my $page=shift;
359         my @ret;
360         if (istranslatable($page)) {
361                 foreach my $lang (sort keys %{$translations{$page}}) {
362                         my $translation = $translations{$page}{$lang};
363                         push @ret, {
364                                 url => urlto($translation, $page),
365                                 code => $lang,
366                                 language => $config{po_slave_languages}{$lang},
367                                 percent => percenttranslated($translation),
368                         };
369                 }
370         }
371         elsif (istranslation($page)) {
372                 my ($masterpage, $curlang) = ($page =~ /(.*)[.]([a-z]{2})$/);
373                 push @ret, {
374                         url => urlto_with_orig_beautiful_urlpath($masterpage, $page),
375                         code => $config{po_master_language}{code},
376                         language => $config{po_master_language}{name},
377                         master => 1,
378                 };
379                 foreach my $lang (sort keys %{$translations{$masterpage}}) {
380                         push @ret, {
381                                 url => urlto($translations{$masterpage}{$lang}, $page),
382                                 code => $lang,
383                                 language => $config{po_slave_languages}{$lang},
384                                 percent => percenttranslated($translations{$masterpage}{$lang}),
385                         } unless ($lang eq $curlang);
386                 }
387         }
388         return @ret;
389 } #}}}
390
391 sub pagetemplate (@) { #{{{
392         my %params=@_;
393         my $page=$params{page};
394         my $template=$params{template};
395
396         if (istranslation($page) && $template->query(name => "percenttranslated")) {
397                 $template->param(percenttranslated => percenttranslated($page));
398         }
399         if ($template->query(name => "istranslation")) {
400                 $template->param(istranslation => istranslation($page));
401         }
402         if ($template->query(name => "istranslatable")) {
403                 $template->param(istranslatable => istranslatable($page));
404         }
405         if ($template->query(name => "otherlanguages")) {
406                 $template->param(otherlanguages => [otherlanguages($page)]);
407                 if (istranslatable($page)) {
408                         foreach my $translation (values %{$translations{$page}}) {
409                                 add_depends($page, $translation);
410                         }
411                 }
412                 elsif (istranslation($page)) {
413                         my ($masterpage, $curlang) = ($page =~ /(.*)[.]([a-z]{2})$/);
414                         add_depends($page, $masterpage);
415                         foreach my $translation (values %{$translations{$masterpage}}) {
416                                 add_depends($page, $translation);
417                         }
418                 }
419         }
420 } # }}}
421
422 sub istranslatable ($) { #{{{
423         my $page=shift;
424         my $file=$pagesources{$page};
425
426         if (! defined $file
427             || (defined pagetype($file) && pagetype($file) eq 'po')
428             || $file =~ /\.pot$/) {
429                 return 0;
430         }
431         return pagespec_match($page, $config{po_translatable_pages});
432 } #}}}
433
434 sub _istranslation ($) { #{{{
435         my $page=shift;
436         my $file=$pagesources{$page};
437         if (! defined $file) {
438                 return IkiWiki::FailReason->new("no file specified");
439         }
440
441         if (! defined $file
442             || ! defined pagetype($file)
443             || ! pagetype($file) eq 'po'
444             || $file =~ /\.pot$/) {
445                 return 0;
446         }
447
448         my ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
449         if (! defined $masterpage || ! defined $lang
450             || ! (length($masterpage) > 0) || ! (length($lang) > 0)
451             || ! defined $pagesources{$masterpage}
452             || ! defined $config{po_slave_languages}{$lang}) {
453                 return 0;
454         }
455
456         return istranslatable($masterpage);
457 } #}}}
458
459 sub istranslation ($) { #{{{
460         my $page=shift;
461         if (_istranslation($page)) {
462                 my ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
463                 $translations{$masterpage}{$lang}=$page unless exists $translations{$masterpage}{$lang};
464                 return 1;
465         }
466         return 0;
467 } #}}}
468
469 package IkiWiki::PageSpec;
470 use warnings;
471 use strict;
472 use IkiWiki 2.00;
473
474 sub match_istranslation ($;@) { #{{{
475         my $page=shift;
476         if (IkiWiki::Plugin::po::istranslation($page)) {
477                 return IkiWiki::SuccessReason->new("is a translation page");
478         }
479         else {
480                 return IkiWiki::FailReason->new("is not a translation page");
481         }
482 } #}}}
483
484 sub match_istranslatable ($;@) { #{{{
485         my $page=shift;
486         if (IkiWiki::Plugin::po::istranslatable($page)) {
487                 return IkiWiki::SuccessReason->new("is set as translatable in po_translatable_pages");
488         }
489         else {
490                 return IkiWiki::FailReason->new("is not set as translatable in po_translatable_pages");
491         }
492 } #}}}
493
494 sub match_lang ($$;@) { #{{{
495         my $page=shift;
496         my $wanted=shift;
497         my $regexp=IkiWiki::glob2re($wanted);
498         my $lang;
499         my $masterpage;
500
501         if (IkiWiki::Plugin::po::istranslation($page)) {
502                 ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
503         }
504         else {
505                 $lang = $config{po_master_language}{code};
506         }
507
508         if ($lang!~/^$regexp$/i) {
509                 return IkiWiki::FailReason->new("file language is $lang, not $wanted");
510         }
511         else {
512                 return IkiWiki::SuccessReason->new("file language is $wanted");
513         }
514 } #}}}
515
516 sub match_currentlang ($$;@) { #{{{
517         my $page=shift;
518         shift;
519         my %params=@_;
520         my ($currentmasterpage, $currentlang, $masterpage, $lang);
521
522         return IkiWiki::FailReason->new("no location provided") unless exists $params{location};
523
524         if (IkiWiki::Plugin::po::istranslation($params{location})) {
525                 ($currentmasterpage, $currentlang) = ($params{location} =~ /(.*)[.]([a-z]{2})$/);
526         }
527         else {
528                 $currentlang = $config{po_master_language}{code};
529         }
530
531         if (IkiWiki::Plugin::po::istranslation($page)) {
532                 ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
533         }
534         else {
535                 $lang = $config{po_master_language}{code};
536         }
537
538         if ($lang eq $currentlang) {
539                 return IkiWiki::SuccessReason->new("file language is the same as current one, i.e. $currentlang");
540         }
541         else {
542                 return IkiWiki::FailReason->new("file language is $lang, whereas current language is $currentlang");
543         }
544 } #}}}
545
546 1