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