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