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