]> sipb.mit.edu Git - ikiwiki.git/blob - IkiWiki/Plugin/po.pm
0902322e31be9fbe5d41dba47fe75e3384f37e48
[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 urlto_with_orig_beautiful_urlpath($$) { #{{{
256         my $to=shift;
257         my $from=shift;
258
259         inject(name => "IkiWiki::beautify_urlpath", call => $origsubs{'beautify_urlpath'});
260         my $res=urlto($to, $from);
261         inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath);
262
263         return $res;
264 } #}}}
265
266 sub mybestlink ($$) { #{{{
267         my $page=shift;
268         my $link=shift;
269         my $res=$origsubs{'bestlink'}->($page, $link);
270         if (length $res) {
271                 if ($config{po_link_to} eq "current"
272                     && istranslatable($res)
273                     && istranslation($page)) {
274                         my ($masterpage, $curlang) = ($page =~ /(.*)[.]([a-z]{2})$/);
275                         return $res . "." . $curlang;
276                 }
277                 else {
278                         return $res;
279                 }
280         }
281         return "";
282 } #}}}
283
284 # We use filter to convert PO to the master page's type,
285 # since other plugins should not work on PO files
286 sub filter (@) { #{{{
287         my %params = @_;
288         my $page = $params{page};
289         my $destpage = $params{destpage};
290         my $content = decode_utf8(encode_utf8($params{content}));
291
292         # decide if this is a PO file that should be converted into a translated document,
293         # and perform various sanity checks
294         if (! istranslation($page) || $filtered{$page}{$destpage}) {
295                 return $content;
296         }
297
298         my ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
299         my $file=srcfile(exists $params{file} ? $params{file} : $IkiWiki::pagesources{$page});
300         my $masterfile = srcfile($pagesources{$masterpage});
301         my (@pos,@masters);
302         push @pos,$file;
303         push @masters,$masterfile;
304         my %options = (
305                         "markdown" => (pagetype($masterfile) eq 'mdwn') ? 1 : 0,
306                         );
307         my $doc=Locale::Po4a::Chooser::new('text',%options);
308         $doc->process(
309                 'po_in_name'    => \@pos,
310                 'file_in_name'  => \@masters,
311                 'file_in_charset'  => 'utf-8',
312                 'file_out_charset' => 'utf-8',
313         ) or error("[po/filter:$file]: failed to translate");
314         my $tmpfh = File::Temp->new(TEMPLATE => "/tmp/ikiwiki-po-filter-out.XXXXXXXXXX");
315         my $tmpout = $tmpfh->filename;
316         $doc->write($tmpout) or error("[po/filter:$file] could not write $tmpout");
317         $content = readfile($tmpout) or error("[po/filter:$file] could not read $tmpout");
318         $filtered{$page}{$destpage}=1;
319         return $content;
320 } #}}}
321
322 sub htmlize (@) { #{{{
323         my %params=@_;
324         my $page = $params{page};
325         my $content = $params{content};
326         my ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
327         my $masterfile = srcfile($pagesources{$masterpage});
328
329         # force content to be htmlize'd as if it was the same type as the master page
330         return IkiWiki::htmlize($page, $page, pagetype($masterfile), $content);
331 } #}}}
332
333 sub percenttranslated ($) { #{{{
334         my $page=shift;
335         return "N/A" unless (istranslation($page));
336         my ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
337         my $file=srcfile($pagesources{$page});
338         my $masterfile = srcfile($pagesources{$masterpage});
339         my (@pos,@masters);
340         push @pos,$file;
341         push @masters,$masterfile;
342         my %options = (
343                         "markdown" => (pagetype($masterfile) eq 'mdwn') ? 1 : 0,
344                         );
345         my $doc=Locale::Po4a::Chooser::new('text',%options);
346         $doc->process(
347                 'po_in_name'    => \@pos,
348                 'file_in_name'  => \@masters,
349                 'file_in_charset'  => 'utf-8',
350                 'file_out_charset' => 'utf-8',
351         ) or error("[po/percenttranslated:$file]: failed to translate");
352         my ($percent,$hit,$queries) = $doc->stats();
353         return $percent;
354 } #}}}
355
356 sub otherlanguages ($) { #{{{
357         my $page=shift;
358         my @ret;
359         if (istranslatable($page)) {
360                 foreach my $lang (sort keys %{$translations{$page}}) {
361                         my $translation = $translations{$page}{$lang};
362                         push @ret, {
363                                 url => urlto($translation, $page),
364                                 code => $lang,
365                                 language => $config{po_slave_languages}{$lang},
366                                 percent => percenttranslated($translation),
367                         };
368                 }
369         }
370         elsif (istranslation($page)) {
371                 my ($masterpage, $curlang) = ($page =~ /(.*)[.]([a-z]{2})$/);
372                 push @ret, {
373                         url => urlto_with_orig_beautiful_urlpath($masterpage, $page),
374                         code => $config{po_master_language}{code},
375                         language => $config{po_master_language}{name},
376                         master => 1,
377                 };
378                 foreach my $lang (sort keys %{$translations{$masterpage}}) {
379                         push @ret, {
380                                 url => urlto($translations{$masterpage}{$lang}, $page),
381                                 code => $lang,
382                                 language => $config{po_slave_languages}{$lang},
383                                 percent => percenttranslated($translations{$masterpage}{$lang}),
384                         } unless ($lang eq $curlang);
385                 }
386         }
387         return @ret;
388 } #}}}
389
390 sub pagetemplate (@) { #{{{
391         my %params=@_;
392         my $page=$params{page};
393         my $template=$params{template};
394
395         if (istranslation($page) && $template->query(name => "percenttranslated")) {
396                 $template->param(percenttranslated => percenttranslated($page));
397         }
398         if ($template->query(name => "istranslation")) {
399                 $template->param(istranslation => istranslation($page));
400         }
401         if ($template->query(name => "istranslatable")) {
402                 $template->param(istranslatable => istranslatable($page));
403         }
404         if ($template->query(name => "otherlanguages")) {
405                 $template->param(otherlanguages => [otherlanguages($page)]);
406                 if (istranslatable($page)) {
407                         foreach my $translation (values %{$translations{$page}}) {
408                                 add_depends($page, $translation);
409                         }
410                 }
411                 elsif (istranslation($page)) {
412                         my ($masterpage, $curlang) = ($page =~ /(.*)[.]([a-z]{2})$/);
413                         add_depends($page, $masterpage);
414                         foreach my $translation (values %{$translations{$masterpage}}) {
415                                 add_depends($page, $translation);
416                         }
417                 }
418         }
419 } # }}}
420
421 sub istranslatable ($) { #{{{
422         my $page=shift;
423         my $file=$pagesources{$page};
424
425         if (! defined $file
426             || (defined pagetype($file) && pagetype($file) eq 'po')
427             || $file =~ /\.pot$/) {
428                 return 0;
429         }
430         return pagespec_match($page, $config{po_translatable_pages});
431 } #}}}
432
433 sub _istranslation ($) { #{{{
434         my $page=shift;
435         my $file=$pagesources{$page};
436         if (! defined $file) {
437                 return IkiWiki::FailReason->new("no file specified");
438         }
439
440         if (! defined $file
441             || ! defined pagetype($file)
442             || ! pagetype($file) eq 'po'
443             || $file =~ /\.pot$/) {
444                 return 0;
445         }
446
447         my ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
448         if (! defined $masterpage || ! defined $lang
449             || ! (length($masterpage) > 0) || ! (length($lang) > 0)
450             || ! defined $pagesources{$masterpage}
451             || ! defined $config{po_slave_languages}{$lang}) {
452                 return 0;
453         }
454
455         return istranslatable($masterpage);
456 } #}}}
457
458 sub istranslation ($) { #{{{
459         my $page=shift;
460         if (_istranslation($page)) {
461                 my ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
462                 $translations{$masterpage}{$lang}=$page unless exists $translations{$masterpage}{$lang};
463                 return 1;
464         }
465         return 0;
466 } #}}}
467
468 package IkiWiki::PageSpec;
469 use warnings;
470 use strict;
471 use IkiWiki 2.00;
472
473 sub match_istranslation ($;@) { #{{{
474         my $page=shift;
475         if (IkiWiki::Plugin::po::istranslation($page)) {
476                 return IkiWiki::SuccessReason->new("is a translation page");
477         }
478         else {
479                 return IkiWiki::FailReason->new("is not a translation page");
480         }
481 } #}}}
482
483 sub match_istranslatable ($;@) { #{{{
484         my $page=shift;
485         if (IkiWiki::Plugin::po::istranslatable($page)) {
486                 return IkiWiki::SuccessReason->new("is set as translatable in po_translatable_pages");
487         }
488         else {
489                 return IkiWiki::FailReason->new("is not set as translatable in po_translatable_pages");
490         }
491 } #}}}
492
493 sub match_lang ($$;@) { #{{{
494         my $page=shift;
495         my $wanted=shift;
496         my $regexp=IkiWiki::glob2re($wanted);
497         my $lang;
498         my $masterpage;
499
500         if (IkiWiki::Plugin::po::istranslation($page)) {
501                 ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
502         }
503         else {
504                 $lang = $config{po_master_language}{code};
505         }
506
507         if ($lang!~/^$regexp$/i) {
508                 return IkiWiki::FailReason->new("file language is $lang, not $wanted");
509         }
510         else {
511                 return IkiWiki::SuccessReason->new("file language is $wanted");
512         }
513 } #}}}
514
515 sub match_currentlang ($$;@) { #{{{
516         my $page=shift;
517         shift;
518         my %params=@_;
519         my ($currentmasterpage, $currentlang, $masterpage, $lang);
520
521         return IkiWiki::FailReason->new("no location provided") unless exists $params{location};
522
523         if (IkiWiki::Plugin::po::istranslation($params{location})) {
524                 ($currentmasterpage, $currentlang) = ($params{location} =~ /(.*)[.]([a-z]{2})$/);
525         }
526         else {
527                 $currentlang = $config{po_master_language}{code};
528         }
529
530         if (IkiWiki::Plugin::po::istranslation($page)) {
531                 ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
532         }
533         else {
534                 $lang = $config{po_master_language}{code};
535         }
536
537         if ($lang eq $currentlang) {
538                 return IkiWiki::SuccessReason->new("file language is the same as current one, i.e. $currentlang");
539         }
540         else {
541                 return IkiWiki::FailReason->new("file language is $lang, whereas current language is $currentlang");
542         }
543 } #}}}
544
545 1