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