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