]> sipb.mit.edu Git - ikiwiki.git/blob - IkiWiki/Plugin/po.pm
466ffd0b8341ea51d93583ab7d85ba1badd760c9
[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
31 sub import { #{{{
32         hook(type => "getsetup", id => "po", call => \&getsetup);
33         hook(type => "checkconfig", id => "po", call => \&checkconfig);
34         hook(type => "needsbuild", id => "po", call => \&needsbuild);
35         hook(type => "filter", id => "po", call => \&filter);
36         hook(type => "htmlize", id => "po", call => \&htmlize);
37         hook(type => "pagetemplate", id => "po", call => \&pagetemplate);
38
39         $origsubs{'bestlink'}=\&IkiWiki::bestlink;
40         inject(name => "IkiWiki::bestlink", call => \&mybestlink);
41         $origsubs{'beautify_urlpath'}=\&IkiWiki::beautify_urlpath;
42         inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath);
43         $origsubs{'targetpage'}=\&IkiWiki::targetpage;
44         inject(name => "IkiWiki::targetpage", call => \&mytargetpage);
45 } #}}}
46
47 sub getsetup () { #{{{
48         return
49                 plugin => {
50                         safe => 0,
51                         rebuild => 1, # format plugin & changes html filenames
52                 },
53                 po_master_language => {
54                         type => "string",
55                         example => {
56                                 'code' => 'en',
57                                 'name' => 'English'
58                         },
59                         description => "master language (non-PO files)",
60                         safe => 0,
61                         rebuild => 1,
62                 },
63                 po_slave_languages => {
64                         type => "string",
65                         example => {
66                                 'fr' => 'Français',
67                                 'es' => 'Castellano',
68                                 'de' => 'Deutsch'
69                         },
70                         description => "slave languages (PO files)",
71                         safe => 0,
72                         rebuild => 1,
73                 },
74                 po_translatable_pages => {
75                         type => "pagespec",
76                         example => "!*/Discussion",
77                         description => "PageSpec controlling which pages are translatable",
78                         link => "ikiwiki/PageSpec",
79                         safe => 0,
80                         rebuild => 1,
81                 },
82                 po_link_to => {
83                         type => "string",
84                         example => "current",
85                         description => "internal linking behavior (default/current/negotiated)",
86                         safe => 0,
87                         rebuild => 1,
88                 },
89 } #}}}
90
91 sub checkconfig () { #{{{
92         foreach my $field (qw{po_master_language po_slave_languages}) {
93                 if (! exists $config{$field} || ! defined $config{$field}) {
94                         error(sprintf(gettext("Must specify %s"), $field));
95                 }
96         }
97         if (! exists $config{po_link_to} ||
98             ! defined $config{po_link_to}) {
99             $config{po_link_to}="default";
100         }
101         if (! exists $config{po_translatable_pages} ||
102             ! defined $config{po_translatable_pages}) {
103             $config{po_translatable_pages}="";
104         }
105         if ($config{po_link_to} eq "negotiated" && ! $config{usedirs}) {
106                 error(gettext("po_link_to=negotiated requires usedirs to be set"));
107         }
108         push @{$config{wiki_file_prune_regexps}}, qr/\.pot$/;
109 } #}}}
110
111 sub potfile ($) { #{{{
112         my $masterfile=shift;
113         (my $name, my $dir, my $suffix) = fileparse($masterfile, qr/\.[^.]*/);
114         return File::Spec->catfile($dir, $name . ".pot");
115 } #}}}
116
117 sub pofile ($$) { #{{{
118         my $masterfile=shift;
119         my $lang=shift;
120         (my $name, my $dir, my $suffix) = fileparse($masterfile, qr/\.[^.]*/);
121         return File::Spec->catfile($dir, $name . "." . $lang . ".po");
122 } #}}}
123
124 sub refreshpot ($) { #{{{
125         my $masterfile=shift;
126         my $potfile=potfile($masterfile);
127         my %options = ("markdown" => (pagetype($masterfile) eq 'mdwn') ? 1 : 0);
128         my $doc=Locale::Po4a::Chooser::new('text',%options);
129         $doc->read($masterfile);
130         $doc->{TT}{utf_mode} = 1;
131         $doc->{TT}{file_in_charset} = 'utf-8';
132         $doc->{TT}{file_out_charset} = 'utf-8';
133         # let's cheat a bit to force porefs option to be passed to Locale::Po4a::Po;
134         # this is undocument use of internal Locale::Po4a::TransTractor's data,
135         # compulsory since this module prevents us from using the porefs option.
136         my %po_options = ('porefs' => 'none');
137         $doc->{TT}{po_out}=Locale::Po4a::Po->new(\%po_options);
138         $doc->{TT}{po_out}->set_charset('utf-8');
139         # do the actual work
140         $doc->parse;
141         $doc->writepo($potfile);
142 } #}}}
143
144 sub refreshpofiles ($@) { #{{{
145         my $masterfile=shift;
146         my @pofiles=@_;
147
148         my $potfile=potfile($masterfile);
149         error("[po/refreshpofiles] POT file ($potfile) does not exist") unless (-e $potfile);
150
151         foreach my $pofile (@pofiles) {
152                 if (-e $pofile) {
153                         system("msgmerge", "-U", "--backup=none", $pofile, $potfile) == 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                 undef %filtered;
208                 undef %translations;
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
294         # translated document, 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 $destpage=$params{destpage};
395         my $template=$params{template};
396
397         if (istranslation($page) && $template->query(name => "percenttranslated")) {
398                 $template->param(percenttranslated => percenttranslated($page));
399         }
400         if ($template->query(name => "istranslation")) {
401                 $template->param(istranslation => istranslation($page));
402         }
403         if ($template->query(name => "istranslatable")) {
404                 $template->param(istranslatable => istranslatable($page));
405         }
406         if ($template->query(name => "otherlanguages")) {
407                 $template->param(otherlanguages => [otherlanguages($page)]);
408                 if (istranslatable($page)) {
409                         foreach my $translation (values %{$translations{$page}}) {
410                                 add_depends($page, $translation);
411                         }
412                 }
413                 elsif (istranslation($page)) {
414                         my ($masterpage, $curlang) = ($page =~ /(.*)[.]([a-z]{2})$/);
415                         add_depends($page, $masterpage);
416                         foreach my $translation (values %{$translations{$masterpage}}) {
417                                 add_depends($page, $translation);
418                         }
419                 }
420         }
421         # Rely on IkiWiki::Render's genpage() to decide wether
422         # a discussion link should appear on $page; this is not
423         # totally accurate, though: some broken links may be generated
424         # when cgiurl is disabled.
425         # This compromise avoids some code duplication, and will probably
426         # prevent future breakage when ikiwiki internals change.
427         # Known limitations are preferred to future random bugs.
428         if ($template->param('discussionlink') && istranslation($page)) {
429                 my ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
430                 $template->param('discussionlink' => htmllink(
431                                                         $page,
432                                                         $destpage,
433                                                         $masterpage . '/' . gettext("Discussion"),
434                                                         noimageinline => 1,
435                                                         forcesubpage => 0,
436                                                         linktext => gettext("Discussion"),
437                                                         ));
438         }
439 } # }}}
440
441 sub istranslatable ($) { #{{{
442         my $page=shift;
443         my $file=$pagesources{$page};
444
445         if (! defined $file
446             || (defined pagetype($file) && pagetype($file) eq 'po')
447             || $file =~ /\.pot$/) {
448                 return 0;
449         }
450         return pagespec_match($page, $config{po_translatable_pages});
451 } #}}}
452
453 sub _istranslation ($) { #{{{
454         my $page=shift;
455         my $file=$pagesources{$page};
456         if (! defined $file) {
457                 return IkiWiki::FailReason->new("no file specified");
458         }
459
460         if (! defined $file
461             || ! defined pagetype($file)
462             || ! pagetype($file) eq 'po'
463             || $file =~ /\.pot$/) {
464                 return 0;
465         }
466
467         my ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
468         if (! defined $masterpage || ! defined $lang
469             || ! (length($masterpage) > 0) || ! (length($lang) > 0)
470             || ! defined $pagesources{$masterpage}
471             || ! defined $config{po_slave_languages}{$lang}) {
472                 return 0;
473         }
474
475         return istranslatable($masterpage);
476 } #}}}
477
478 sub istranslation ($) { #{{{
479         my $page=shift;
480         if (_istranslation($page)) {
481                 my ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
482                 $translations{$masterpage}{$lang}=$page unless exists $translations{$masterpage}{$lang};
483                 return 1;
484         }
485         return 0;
486 } #}}}
487
488 package IkiWiki::PageSpec;
489 use warnings;
490 use strict;
491 use IkiWiki 2.00;
492
493 sub match_istranslation ($;@) { #{{{
494         my $page=shift;
495         if (IkiWiki::Plugin::po::istranslation($page)) {
496                 return IkiWiki::SuccessReason->new("is a translation page");
497         }
498         else {
499                 return IkiWiki::FailReason->new("is not a translation page");
500         }
501 } #}}}
502
503 sub match_istranslatable ($;@) { #{{{
504         my $page=shift;
505         if (IkiWiki::Plugin::po::istranslatable($page)) {
506                 return IkiWiki::SuccessReason->new("is set as translatable in po_translatable_pages");
507         }
508         else {
509                 return IkiWiki::FailReason->new("is not set as translatable in po_translatable_pages");
510         }
511 } #}}}
512
513 sub match_lang ($$;@) { #{{{
514         my $page=shift;
515         my $wanted=shift;
516         my $regexp=IkiWiki::glob2re($wanted);
517         my $lang;
518         my $masterpage;
519
520         if (IkiWiki::Plugin::po::istranslation($page)) {
521                 ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
522         }
523         else {
524                 $lang = $config{po_master_language}{code};
525         }
526
527         if ($lang!~/^$regexp$/i) {
528                 return IkiWiki::FailReason->new("file language is $lang, not $wanted");
529         }
530         else {
531                 return IkiWiki::SuccessReason->new("file language is $wanted");
532         }
533 } #}}}
534
535 sub match_currentlang ($$;@) { #{{{
536         my $page=shift;
537         shift;
538         my %params=@_;
539         my ($currentmasterpage, $currentlang, $masterpage, $lang);
540
541         return IkiWiki::FailReason->new("no location provided") unless exists $params{location};
542
543         if (IkiWiki::Plugin::po::istranslation($params{location})) {
544                 ($currentmasterpage, $currentlang) = ($params{location} =~ /(.*)[.]([a-z]{2})$/);
545         }
546         else {
547                 $currentlang = $config{po_master_language}{code};
548         }
549
550         if (IkiWiki::Plugin::po::istranslation($page)) {
551                 ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
552         }
553         else {
554                 $lang = $config{po_master_language}{code};
555         }
556
557         if ($lang eq $currentlang) {
558                 return IkiWiki::SuccessReason->new("file language is the same as current one, i.e. $currentlang");
559         }
560         else {
561                 return IkiWiki::FailReason->new("file language is $lang, whereas current language is $currentlang");
562         }
563 } #}}}
564
565 1