]> sipb.mit.edu Git - ikiwiki.git/blob - IkiWiki/Plugin/po.pm
first pass over code
[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
31 sub import { #{{{
32         hook(type => "getsetup", id => "po", call => \&getsetup);
33         hook(type => "checkconfig", id => "po", call => \&checkconfig);
34         hook(type => "needsbuild", id => "po", call => \&needsbuild);
35         hook(type => "filter", id => "po", call => \&filter);
36         hook(type => "htmlize", id => "po", call => \&htmlize);
37         hook(type => "pagetemplate", id => "po", call => \&pagetemplate);
38
39         $origsubs{'bestlink'}=\&IkiWiki::bestlink;
40         inject(name => "IkiWiki::bestlink", call => \&mybestlink);
41         $origsubs{'beautify_urlpath'}=\&IkiWiki::beautify_urlpath;
42         inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath);
43         $origsubs{'targetpage'}=\&IkiWiki::targetpage;
44         inject(name => "IkiWiki::targetpage", call => \&mytargetpage);
45 } #}}}
46
47 sub getsetup () { #{{{
48         return
49                 plugin => {
50                         safe => 0,
51                         rebuild => 1, # format plugin & changes html filenames
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
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
122         (my $name, my $dir, my $suffix) = fileparse($masterfile, qr/\.[^.]*/);
123         return File::Spec->catfile($dir, $name . "." . $lang . ".po");
124 } #}}}
125
126 sub refreshpot ($) { #{{{
127         my $masterfile=shift;
128
129         my $potfile=potfile($masterfile);
130         my %options = ("markdown" => (pagetype($masterfile) eq 'mdwn') ? 1 : 0);
131         my $doc=Locale::Po4a::Chooser::new('text',%options);
132         $doc->read($masterfile);
133         $doc->{TT}{utf_mode} = 1;
134         $doc->{TT}{file_in_charset} = 'utf-8';
135         $doc->{TT}{file_out_charset} = 'utf-8';
136         # let's cheat a bit to force porefs option to be passed to Locale::Po4a::Po;
137         # this is undocument use of internal Locale::Po4a::TransTractor's data,
138         # compulsory since this module prevents us from using the porefs option.
139         my %po_options = ('porefs' => 'none');
140         $doc->{TT}{po_out}=Locale::Po4a::Po->new(\%po_options);
141         $doc->{TT}{po_out}->set_charset('utf-8');
142         # do the actual work
143         $doc->parse;
144         $doc->writepo($potfile);
145 } #}}}
146
147 sub refreshpofiles ($@) { #{{{
148         my $masterfile=shift;
149         my @pofiles=@_;
150
151         my $potfile=potfile($masterfile);
152         error("[po/refreshpofiles] POT file ($potfile) does not exist") unless (-e $potfile);
153
154         foreach my $pofile (@pofiles) {
155                 if (-e $pofile) {
156                         system("msgmerge", "-U", "--backup=none", $pofile, $potfile) == 0
157                                 or error("[po/refreshpofiles:$pofile] failed to update");
158                 }
159                 else {
160                         File::Copy::syscopy($potfile,$pofile)
161                                 or error("[po/refreshpofiles:$pofile] failed to copy the POT file");
162                 }
163         }
164 } #}}}
165
166 sub needsbuild () { #{{{
167         my $needsbuild=shift;
168
169         # build %translations, using istranslation's side-effect
170         foreach my $page (keys %pagesources) {
171                 istranslation($page);
172         }
173
174         # refresh/create POT and PO files as needed
175         my $updated_po_files=0;
176         foreach my $page (keys %pagesources) {
177                 my $pageneedsbuild = grep { $_ eq $pagesources{$page} } @$needsbuild;
178                 if (istranslatable($page)) {
179                         my $file=srcfile($pagesources{$page});
180                         if ($pageneedsbuild || ! -e potfile($file)) {
181                                 refreshpot($file);
182                         }
183                         my @pofiles;
184                         foreach my $lang (keys %{$config{po_slave_languages}}) {
185                                 my $pofile=pofile($file, $lang);
186                                 if ($pageneedsbuild || ! -e $pofile) {
187                                         push @pofiles, $pofile;
188                                 }
189                         }
190                         if (@pofiles) {
191                                 refreshpofiles($file, @pofiles) ;
192                                 map { IkiWiki::rcs_add($_); } @pofiles if ($config{rcs});
193                                 $updated_po_files = 1;
194                         }
195                 }
196         }
197
198         # check staged changes in and trigger a wiki refresh.
199         if ($updated_po_files) {
200                 if ($config{rcs}) {
201                         IkiWiki::disable_commit_hook();
202                         IkiWiki::rcs_commit_staged(gettext("updated PO files"),
203                                 "refreshpofiles", "127.0.0.1");
204                         IkiWiki::enable_commit_hook();
205                         IkiWiki::rcs_update();
206                 }
207                 IkiWiki::refresh();
208                 IkiWiki::saveindex();
209                 # refresh module's private variables
210                 undef %filtered;
211                 undef %translations;
212                 foreach my $page (keys %pagesources) {
213                         istranslation($page);
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
252         my $res=$origsubs{'beautify_urlpath'}->($url);
253         if ($config{po_link_to} eq "negotiated") {
254                 $res =~ s!/\Qindex.$config{po_master_language}{code}.$config{htmlext}\E$!/!;
255         }
256         return $res;
257 } #}}}
258
259 sub urlto_with_orig_beautiful_urlpath($$) { #{{{
260         my $to=shift;
261         my $from=shift;
262
263         inject(name => "IkiWiki::beautify_urlpath", call => $origsubs{'beautify_urlpath'});
264         my $res=urlto($to, $from);
265         inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath);
266
267         return $res;
268 } #}}}
269
270 sub mybestlink ($$) { #{{{
271         my $page=shift;
272         my $link=shift;
273
274         my $res=$origsubs{'bestlink'}->($page, $link);
275         if (length $res) {
276                 if ($config{po_link_to} eq "current"
277                     && istranslatable($res)
278                     && istranslation($page)) {
279                         my ($masterpage, $curlang) = ($page =~ /(.*)[.]([a-z]{2})$/);
280                         return $res . "." . $curlang;
281                 }
282                 else {
283                         return $res;
284                 }
285         }
286         return "";
287 } #}}}
288
289 # We use filter to convert PO to the master page's type,
290 # since other plugins should not work on PO files
291 sub filter (@) { #{{{
292         my %params = @_;
293
294         my $page = $params{page};
295         my $destpage = $params{destpage};
296         my $content = decode_utf8(encode_utf8($params{content}));
297
298         # decide if this is a PO file that should be converted into a
299         # translated document, and perform various sanity checks
300         if (! istranslation($page) || $filtered{$page}{$destpage}) {
301                 return $content;
302         }
303
304         my ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
305         my $file=srcfile(exists $params{file} ? $params{file} : $IkiWiki::pagesources{$page});
306         my $masterfile = srcfile($pagesources{$masterpage});
307         my (@pos,@masters);
308         push @pos,$file;
309         push @masters,$masterfile;
310         my %options = (
311                 "markdown" => (pagetype($masterfile) eq 'mdwn') ? 1 : 0,
312         );
313         my $doc=Locale::Po4a::Chooser::new('text',%options);
314         $doc->process(
315                 'po_in_name'    => \@pos,
316                 'file_in_name'  => \@masters,
317                 'file_in_charset'  => 'utf-8',
318                 'file_out_charset' => 'utf-8',
319         ) or error("[po/filter:$file]: failed to translate");
320         my $tmpfh = File::Temp->new(TEMPLATE => "/tmp/ikiwiki-po-filter-out.XXXXXXXXXX");
321         my $tmpout = $tmpfh->filename;
322         # XXX is there any way to avoid the useless write to a temp file? --Joey
323         $doc->write($tmpout) or error("[po/filter:$file] could not write $tmpout");
324         $content = readfile($tmpout) or error("[po/filter:$file] could not read $tmpout");
325         $filtered{$page}{$destpage}=1;
326         return $content;
327 } #}}}
328
329 sub htmlize (@) { #{{{
330         my %params=@_;
331
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
344         return gettext("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
368         my @ret;
369         if (istranslatable($page)) {
370                 foreach my $lang (sort keys %{$translations{$page}}) {
371                         my $translation = $translations{$page}{$lang};
372                         push @ret, {
373                                 url => urlto($translation, $page),
374                                 code => $lang,
375                                 language => $config{po_slave_languages}{$lang},
376                                 percent => percenttranslated($translation),
377                         };
378                 }
379         }
380         elsif (istranslation($page)) {
381                 my ($masterpage, $curlang) = ($page =~ /(.*)[.]([a-z]{2})$/);
382                 push @ret, {
383                         url => urlto_with_orig_beautiful_urlpath($masterpage, $page),
384                         code => $config{po_master_language}{code},
385                         language => $config{po_master_language}{name},
386                         master => 1,
387                 };
388                 foreach my $lang (sort keys %{$translations{$masterpage}}) {
389                         push @ret, {
390                                 url => urlto($translations{$masterpage}{$lang}, $page),
391                                 code => $lang,
392                                 language => $config{po_slave_languages}{$lang},
393                                 percent => percenttranslated($translations{$masterpage}{$lang}),
394                         } unless ($lang eq $curlang);
395                 }
396         }
397         return @ret;
398 } #}}}
399
400 sub pagetemplate (@) { #{{{
401         my %params=@_;
402         my $page=$params{page};
403
404         my $destpage=$params{destpage};
405         my $template=$params{template};
406
407         if (istranslation($page) && $template->query(name => "percenttranslated")) {
408                 $template->param(percenttranslated => percenttranslated($page));
409         }
410         if ($template->query(name => "istranslation")) {
411                 $template->param(istranslation => istranslation($page));
412         }
413         if ($template->query(name => "istranslatable")) {
414                 $template->param(istranslatable => istranslatable($page));
415         }
416         if ($template->query(name => "otherlanguages")) {
417                 $template->param(otherlanguages => [otherlanguages($page)]);
418                 if (istranslatable($page)) {
419                         foreach my $translation (values %{$translations{$page}}) {
420                                 add_depends($page, $translation);
421                         }
422                 }
423                 elsif (istranslation($page)) {
424                         my ($masterpage, $curlang) = ($page =~ /(.*)[.]([a-z]{2})$/);
425                         add_depends($page, $masterpage);
426                         foreach my $translation (values %{$translations{$masterpage}}) {
427                                 add_depends($page, $translation);
428                         }
429                 }
430         }
431         # Rely on IkiWiki::Render's genpage() to decide wether
432         # a discussion link should appear on $page; this is not
433         # totally accurate, though: some broken links may be generated
434         # when cgiurl is disabled.
435         # This compromise avoids some code duplication, and will probably
436         # prevent future breakage when ikiwiki internals change.
437         # Known limitations are preferred to future random bugs.
438         if ($template->param('discussionlink') && istranslation($page)) {
439                 my ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
440                 $template->param('discussionlink' => htmllink(
441                                                         $page,
442                                                         $destpage,
443                                                         $masterpage . '/' . gettext("Discussion"),
444                                                         noimageinline => 1,
445                                                         forcesubpage => 0,
446                                                         linktext => gettext("Discussion"),
447                                                         ));
448         }
449 } # }}}
450
451 sub istranslatable ($) { #{{{
452         my $page=shift;
453
454         my $file=$pagesources{$page};
455
456         if (! defined $file
457             || (defined pagetype($file) && pagetype($file) eq 'po')
458             || $file =~ /\.pot$/) {
459                 return 0;
460         }
461         return pagespec_match($page, $config{po_translatable_pages});
462 } #}}}
463
464 sub _istranslation ($) { #{{{
465         my $page=shift;
466
467         my $file=$pagesources{$page};
468         if (! defined $file) {
469                 return IkiWiki::FailReason->new("no file specified");
470         }
471
472         if (! defined $file
473             || ! defined pagetype($file)
474             || ! pagetype($file) eq 'po'
475             || $file =~ /\.pot$/) {
476                 return 0;
477         }
478
479         my ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
480         if (! defined $masterpage || ! defined $lang
481             || ! (length($masterpage) > 0) || ! (length($lang) > 0)
482             || ! defined $pagesources{$masterpage}
483             || ! defined $config{po_slave_languages}{$lang}) {
484                 return 0;
485         }
486
487         return istranslatable($masterpage);
488 } #}}}
489
490 sub istranslation ($) { #{{{
491         my $page=shift;
492
493         if (_istranslation($page)) {
494                 my ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
495                 $translations{$masterpage}{$lang}=$page unless exists $translations{$masterpage}{$lang};
496                 return 1;
497         }
498         return 0;
499 } #}}}
500
501 package IkiWiki::PageSpec;
502 use warnings;
503 use strict;
504 use IkiWiki 2.00;
505
506 sub match_istranslation ($;@) { #{{{
507         my $page=shift;
508
509         if (IkiWiki::Plugin::po::istranslation($page)) {
510                 return IkiWiki::SuccessReason->new("is a translation page");
511         }
512         else {
513                 return IkiWiki::FailReason->new("is not a translation page");
514         }
515 } #}}}
516
517 sub match_istranslatable ($;@) { #{{{
518         my $page=shift;
519
520         if (IkiWiki::Plugin::po::istranslatable($page)) {
521                 return IkiWiki::SuccessReason->new("is set as translatable in po_translatable_pages");
522         }
523         else {
524                 return IkiWiki::FailReason->new("is not set as translatable in po_translatable_pages");
525         }
526 } #}}}
527
528 sub match_lang ($$;@) { #{{{
529         my $page=shift;
530         my $wanted=shift;
531
532         my $regexp=IkiWiki::glob2re($wanted);
533         my $lang;
534         my $masterpage;
535
536         if (IkiWiki::Plugin::po::istranslation($page)) {
537                 ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
538         }
539         else {
540                 $lang = $config{po_master_language}{code};
541         }
542
543         if ($lang!~/^$regexp$/i) {
544                 return IkiWiki::FailReason->new("file language is $lang, not $wanted");
545         }
546         else {
547                 return IkiWiki::SuccessReason->new("file language is $wanted");
548         }
549 } #}}}
550
551 sub match_currentlang ($$;@) { #{{{
552         my $page=shift;
553
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