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;
13 use Locale::Po4a::Chooser;
25 memoize("_istranslation");
26 memoize("percenttranslated");
27 # FIXME: memoizing istranslatable() makes some test cases fail once every
28 # two tries; this may be related to the artificial way the testsuite is
30 # memoize("istranslatable");
32 # backup references to subs that will be overriden
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, last => 1);
42 hook(type => "change", id => "po", call => \&change);
43 hook(type => "editcontent", id => "po", call => \&editcontent);
45 $origsubs{'bestlink'}=\&IkiWiki::bestlink;
46 inject(name => "IkiWiki::bestlink", call => \&mybestlink);
47 $origsubs{'beautify_urlpath'}=\&IkiWiki::beautify_urlpath;
48 inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath);
49 $origsubs{'targetpage'}=\&IkiWiki::targetpage;
50 inject(name => "IkiWiki::targetpage", call => \&mytargetpage);
53 sub getsetup () { #{{{
57 rebuild => 1, # format plugin & changes html filenames
59 po_master_language => {
65 description => "master language (non-PO files)",
69 po_slave_languages => {
76 description => "slave languages (PO files)",
80 po_translatable_pages => {
82 example => "!*/Discussion",
83 description => "PageSpec controlling which pages are translatable",
84 link => "ikiwiki/PageSpec",
91 description => "internal linking behavior (default/current/negotiated)",
97 sub islanguagecode ($) { #{{{
99 return ($code =~ /^[a-z]{2}$/);
102 sub checkconfig () { #{{{
103 foreach my $field (qw{po_master_language po_slave_languages}) {
104 if (! exists $config{$field} || ! defined $config{$field}) {
105 error(sprintf(gettext("Must specify %s"), $field));
108 if (! (keys %{$config{po_slave_languages}})) {
109 error(gettext("At least one slave language must be defined in po_slave_languages"));
113 or error(sprintf(gettext("%s is not a valid language code"), $_));
114 } ($config{po_master_language}{code}, keys %{$config{po_slave_languages}});
115 if (! exists $config{po_translatable_pages} ||
116 ! defined $config{po_translatable_pages}) {
117 $config{po_translatable_pages}="";
119 if (! exists $config{po_link_to} ||
120 ! defined $config{po_link_to}) {
121 $config{po_link_to}='default';
124 $config{po_link_to} eq $_
125 } ('default', 'current', 'negotiated')) {
126 warn(sprintf(gettext('po_link_to=%s is not a valid setting, falling back to po_link_to=default'),
127 $config{po_link_to}));
128 $config{po_link_to}='default';
130 elsif ($config{po_link_to} eq "negotiated" && ! $config{usedirs}) {
131 warn(gettext('po_link_to=negotiated requires usedirs to be enabled, falling back to po_link_to=default'));
132 $config{po_link_to}='default';
134 push @{$config{wiki_file_prune_regexps}}, qr/\.pot$/;
137 sub potfile ($) { #{{{
138 my $masterfile=shift;
140 (my $name, my $dir, my $suffix) = fileparse($masterfile, qr/\.[^.]*/);
141 $dir='' if $dir eq './';
142 return File::Spec->catpath('', $dir, $name . ".pot");
145 sub pofile ($$) { #{{{
146 my $masterfile=shift;
149 (my $name, my $dir, my $suffix) = fileparse($masterfile, qr/\.[^.]*/);
150 $dir='' if $dir eq './';
151 return File::Spec->catpath('', $dir, $name . "." . $lang . ".po");
154 sub refreshpot ($) { #{{{
155 my $masterfile=shift;
157 my $potfile=potfile($masterfile);
158 my %options = ("markdown" => (pagetype($masterfile) eq 'mdwn') ? 1 : 0);
159 my $doc=Locale::Po4a::Chooser::new('text',%options);
160 $doc->read($masterfile);
161 $doc->{TT}{utf_mode} = 1;
162 $doc->{TT}{file_in_charset} = 'utf-8';
163 $doc->{TT}{file_out_charset} = 'utf-8';
164 # let's cheat a bit to force porefs option to be passed to Locale::Po4a::Po;
165 # this is undocument use of internal Locale::Po4a::TransTractor's data,
166 # compulsory since this module prevents us from using the porefs option.
167 my %po_options = ('porefs' => 'none');
168 $doc->{TT}{po_out}=Locale::Po4a::Po->new(\%po_options);
169 $doc->{TT}{po_out}->set_charset('utf-8');
172 IkiWiki::prep_writefile(basename($potfile),dirname($potfile));
173 $doc->writepo($potfile);
176 sub refreshpofiles ($@) { #{{{
177 my $masterfile=shift;
180 my $potfile=potfile($masterfile);
181 error("[po/refreshpofiles] POT file ($potfile) does not exist") unless (-e $potfile);
183 foreach my $pofile (@pofiles) {
184 IkiWiki::prep_writefile(basename($pofile),dirname($pofile));
186 system("msgmerge", "-U", "--backup=none", $pofile, $potfile) == 0
187 or error("[po/refreshpofiles:$pofile] failed to update");
190 File::Copy::syscopy($potfile,$pofile)
191 or error("[po/refreshpofiles:$pofile] failed to copy the POT file");
196 sub needsbuild () { #{{{
197 my $needsbuild=shift;
199 # backup @needsbuild content so that change() can know whether
200 # a given master page was rendered because its source file was changed
201 @origneedsbuild=(@$needsbuild);
203 # build %translations, using istranslation's side-effect
204 map istranslation($_), (keys %pagesources);
206 # make existing translations depend on the corresponding master page
207 foreach my $master (keys %translations) {
208 foreach my $slave (values %{$translations{$master}}) {
209 add_depends($slave, $master);
214 sub mytargetpage ($$) { #{{{
218 if (istranslation($page)) {
219 my ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
220 if (! $config{usedirs} || $masterpage eq 'index') {
221 return $masterpage . "." . $lang . "." . $ext;
224 return $masterpage . "/index." . $lang . "." . $ext;
227 elsif (istranslatable($page)) {
228 if (! $config{usedirs} || $page eq 'index') {
229 return $page . "." . $config{po_master_language}{code} . "." . $ext;
232 return $page . "/index." . $config{po_master_language}{code} . "." . $ext;
235 return $origsubs{'targetpage'}->($page, $ext);
238 sub mybeautify_urlpath ($) { #{{{
241 my $res=$origsubs{'beautify_urlpath'}->($url);
242 if ($config{po_link_to} eq "negotiated") {
243 $res =~ s!/\Qindex.$config{po_master_language}{code}.$config{htmlext}\E$!/!;
248 sub urlto_with_orig_beautiful_urlpath($$) { #{{{
252 inject(name => "IkiWiki::beautify_urlpath", call => $origsubs{'beautify_urlpath'});
253 my $res=urlto($to, $from);
254 inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath);
259 sub mybestlink ($$) { #{{{
263 my $res=$origsubs{'bestlink'}->($page, $link);
265 if ($config{po_link_to} eq "current"
266 && istranslatable($res)
267 && istranslation($page)) {
268 my ($masterpage, $curlang) = ($page =~ /(.*)[.]([a-z]{2})$/);
269 return $res . "." . $curlang;
278 # We use filter to convert PO to the master page's format,
279 # since the rest of ikiwiki should not work on PO files.
280 sub filter (@) { #{{{
283 my $page = $params{page};
284 my $destpage = $params{destpage};
285 my $content = decode_utf8(encode_utf8($params{content}));
287 return $content if ( ! istranslation($page)
288 || ( exists $filtered{$page}{$destpage}
289 && $filtered{$page}{$destpage} eq 1 ));
291 # CRLF line terminators make poor Locale::Po4a feel bad
292 $content=~s/\r\n/\n/g;
294 # Implementation notes
296 # 1. Locale::Po4a reads/writes from/to files, and I'm too lazy
297 # to learn how to disguise a variable as a file.
298 # 2. There are incompatibilities between some File::Temp versions
299 # (including 0.18, bundled with Lenny's perl-modules package)
300 # and others (e.g. 0.20, previously present in the archive as
301 # a standalone package): under certain circumstances, some
302 # return a relative filename, whereas others return an absolute one;
303 # we here use this module in a way that is at least compatible
304 # with 0.18 and 0.20. Beware, hit'n'run refactorers!
305 my $infile = new File::Temp(TEMPLATE => "ikiwiki-po-filter-in.XXXXXXXXXX",
306 DIR => File::Spec->tmpdir,
307 UNLINK => 1)->filename;
308 my $outfile = new File::Temp(TEMPLATE => "ikiwiki-po-filter-out.XXXXXXXXXX",
309 DIR => File::Spec->tmpdir,
310 UNLINK => 1)->filename;
312 writefile(basename($infile), File::Spec->tmpdir, $content);
314 my ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
315 my $masterfile = srcfile($pagesources{$masterpage});
318 push @masters,$masterfile;
320 "markdown" => (pagetype($masterfile) eq 'mdwn') ? 1 : 0,
322 my $doc=Locale::Po4a::Chooser::new('text',%options);
324 'po_in_name' => \@pos,
325 'file_in_name' => \@masters,
326 'file_in_charset' => 'utf-8',
327 'file_out_charset' => 'utf-8',
328 ) or error("[po/filter:$infile]: failed to translate");
329 $doc->write($outfile) or error("[po/filter:$infile] could not write $outfile");
330 $content = readfile($outfile) or error("[po/filter:$infile] could not read $outfile");
332 # Unlinking should happen automatically, thanks to File::Temp,
333 # but it does not work here, probably because of the way writefile()
334 # and Locale::Po4a::write() work.
335 unlink $infile, $outfile;
337 $filtered{$page}{$destpage}=1;
341 sub htmlize (@) { #{{{
344 my $page = $params{page};
345 my $content = $params{content};
346 my ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
347 my $masterfile = srcfile($pagesources{$masterpage});
349 # force content to be htmlize'd as if it was the same type as the master page
350 return IkiWiki::htmlize($page, $page, pagetype($masterfile), $content);
353 sub percenttranslated ($) { #{{{
356 return gettext("N/A") unless (istranslation($page));
357 my ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
358 my $file=srcfile($pagesources{$page});
359 my $masterfile = srcfile($pagesources{$masterpage});
362 push @masters,$masterfile;
364 "markdown" => (pagetype($masterfile) eq 'mdwn') ? 1 : 0,
366 my $doc=Locale::Po4a::Chooser::new('text',%options);
368 'po_in_name' => \@pos,
369 'file_in_name' => \@masters,
370 'file_in_charset' => 'utf-8',
371 'file_out_charset' => 'utf-8',
372 ) or error("[po/percenttranslated:$file]: failed to translate");
373 my ($percent,$hit,$queries) = $doc->stats();
377 sub otherlanguages ($) { #{{{
381 if (istranslatable($page)) {
382 foreach my $lang (sort keys %{$translations{$page}}) {
383 my $translation = $translations{$page}{$lang};
385 url => urlto($translation, $page),
387 language => $config{po_slave_languages}{$lang},
388 percent => percenttranslated($translation),
392 elsif (istranslation($page)) {
393 my ($masterpage, $curlang) = ($page =~ /(.*)[.]([a-z]{2})$/);
395 url => urlto_with_orig_beautiful_urlpath($masterpage, $page),
396 code => $config{po_master_language}{code},
397 language => $config{po_master_language}{name},
400 foreach my $lang (sort keys %{$translations{$masterpage}}) {
402 url => urlto($translations{$masterpage}{$lang}, $page),
404 language => $config{po_slave_languages}{$lang},
405 percent => percenttranslated($translations{$masterpage}{$lang}),
406 } unless ($lang eq $curlang);
412 sub pagetemplate (@) { #{{{
414 my $page=$params{page};
415 my $destpage=$params{destpage};
416 my $template=$params{template};
418 my ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/) if istranslation($page);
420 if (istranslation($page) && $template->query(name => "percenttranslated")) {
421 $template->param(percenttranslated => percenttranslated($page));
423 if ($template->query(name => "istranslation")) {
424 $template->param(istranslation => istranslation($page));
426 if ($template->query(name => "istranslatable")) {
427 $template->param(istranslatable => istranslatable($page));
429 if ($template->query(name => "otherlanguages")) {
430 $template->param(otherlanguages => [otherlanguages($page)]);
431 if (istranslatable($page)) {
432 foreach my $translation (values %{$translations{$page}}) {
433 add_depends($page, $translation);
436 elsif (istranslation($page)) {
437 add_depends($page, $masterpage);
438 foreach my $translation (values %{$translations{$masterpage}}) {
439 add_depends($page, $translation);
443 # Rely on IkiWiki::Render's genpage() to decide wether
444 # a discussion link should appear on $page; this is not
445 # totally accurate, though: some broken links may be generated
446 # when cgiurl is disabled.
447 # This compromise avoids some code duplication, and will probably
448 # prevent future breakage when ikiwiki internals change.
449 # Known limitations are preferred to future random bugs.
450 if ($template->param('discussionlink') && istranslation($page)) {
451 $template->param('discussionlink' => htmllink(
454 $masterpage . '/' . gettext("Discussion"),
457 linktext => gettext("Discussion"),
460 # remove broken parentlink to ./index.html on home page's translations
461 if ($template->param('parentlinks')
462 && istranslation($page)
463 && $masterpage eq "index") {
464 $template->param('parentlinks' => []);
471 my $updated_po_files=0;
473 # Refresh/create POT and PO files as needed.
474 foreach my $page (map pagename($_), @rendered) {
475 next unless istranslatable($page);
476 my $file=srcfile($pagesources{$page});
477 my $updated_pot_file=0;
478 if ((grep { $_ eq $pagesources{$page} } @origneedsbuild)
479 || ! -e potfile($file)) {
484 foreach my $lang (keys %{$config{po_slave_languages}}) {
485 my $pofile=pofile($file, $lang);
486 if ($updated_pot_file || ! -e $pofile) {
487 push @pofiles, $pofile;
491 refreshpofiles($file, @pofiles);
492 map { IkiWiki::rcs_add($_); } @pofiles if ($config{rcs});
497 if ($updated_po_files) {
498 # Check staged changes in.
500 IkiWiki::disable_commit_hook();
501 IkiWiki::rcs_commit_staged(gettext("updated PO files"),
502 "IkiWiki::Plugin::po::change", "127.0.0.1");
503 IkiWiki::enable_commit_hook();
504 IkiWiki::rcs_update();
506 # Reinitialize module's private variables.
509 # Trigger a wiki refresh.
510 require IkiWiki::Render;
512 IkiWiki::saveindex();
516 sub editcontent () { #{{{
518 # as we're previewing or saving a page, the content may have
519 # changed, so tell the next filter() invocation it must not be lazy
520 if (exists $filtered{$params{page}}{$params{page}}) {
521 delete $filtered{$params{page}}{$params{page}};
523 return $params{content};
526 sub istranslatable ($) { #{{{
529 my $file=$pagesources{$page};
532 || (defined pagetype($file) && pagetype($file) eq 'po')
533 || $file =~ /\.pot$/) {
536 return pagespec_match($page, $config{po_translatable_pages});
539 sub _istranslation ($) { #{{{
542 my $file=$pagesources{$page};
543 if (! defined $file) {
544 return IkiWiki::FailReason->new("no file specified");
548 || ! defined pagetype($file)
549 || ! pagetype($file) eq 'po'
550 || $file =~ /\.pot$/) {
554 my ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
555 if (! defined $masterpage || ! defined $lang
556 || ! (length($masterpage) > 0) || ! (length($lang) > 0)
557 || ! defined $pagesources{$masterpage}
558 || ! defined $config{po_slave_languages}{$lang}) {
562 return istranslatable($masterpage);
565 sub istranslation ($) { #{{{
568 if (_istranslation($page)) {
569 my ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
570 $translations{$masterpage}{$lang}=$page unless exists $translations{$masterpage}{$lang};
576 package IkiWiki::PageSpec;
581 sub match_istranslation ($;@) { #{{{
584 if (IkiWiki::Plugin::po::istranslation($page)) {
585 return IkiWiki::SuccessReason->new("is a translation page");
588 return IkiWiki::FailReason->new("is not a translation page");
592 sub match_istranslatable ($;@) { #{{{
595 if (IkiWiki::Plugin::po::istranslatable($page)) {
596 return IkiWiki::SuccessReason->new("is set as translatable in po_translatable_pages");
599 return IkiWiki::FailReason->new("is not set as translatable in po_translatable_pages");
603 sub match_lang ($$;@) { #{{{
607 my $regexp=IkiWiki::glob2re($wanted);
611 if (IkiWiki::Plugin::po::istranslation($page)) {
612 ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
615 $lang = $config{po_master_language}{code};
618 if ($lang!~/^$regexp$/i) {
619 return IkiWiki::FailReason->new("file language is $lang, not $wanted");
622 return IkiWiki::SuccessReason->new("file language is $wanted");
626 sub match_currentlang ($$;@) { #{{{
631 my ($currentmasterpage, $currentlang, $masterpage, $lang);
633 return IkiWiki::FailReason->new("no location provided") unless exists $params{location};
635 if (IkiWiki::Plugin::po::istranslation($params{location})) {
636 ($currentmasterpage, $currentlang) = ($params{location} =~ /(.*)[.]([a-z]{2})$/);
639 $currentlang = $config{po_master_language}{code};
642 if (IkiWiki::Plugin::po::istranslation($page)) {
643 ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
646 $lang = $config{po_master_language}{code};
649 if ($lang eq $currentlang) {
650 return IkiWiki::SuccessReason->new("file language is the same as current one, i.e. $currentlang");
653 return IkiWiki::FailReason->new("file language is $lang, whereas current language is $currentlang");