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