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