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 => "scan", id => "po", call => \&scan, last =>1);
40 hook(type => "filter", id => "po", call => \&filter);
41 hook(type => "htmlize", id => "po", call => \&htmlize);
42 hook(type => "pagetemplate", id => "po", call => \&pagetemplate, last => 1);
43 hook(type => "change", id => "po", call => \&change);
44 hook(type => "editcontent", id => "po", call => \&editcontent);
46 $origsubs{'bestlink'}=\&IkiWiki::bestlink;
47 inject(name => "IkiWiki::bestlink", call => \&mybestlink);
48 $origsubs{'beautify_urlpath'}=\&IkiWiki::beautify_urlpath;
49 inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath);
50 $origsubs{'targetpage'}=\&IkiWiki::targetpage;
51 inject(name => "IkiWiki::targetpage", call => \&mytargetpage);
52 $origsubs{'urlto'}=\&IkiWiki::urlto;
53 inject(name => "IkiWiki::urlto", call => \&myurlto);
56 sub getsetup () { #{{{
60 rebuild => 1, # format plugin & changes html filenames
62 po_master_language => {
68 description => "master language (non-PO files)",
72 po_slave_languages => {
79 description => "slave languages (PO files)",
83 po_translatable_pages => {
85 example => "!*/Discussion",
86 description => "PageSpec controlling which pages are translatable",
87 link => "ikiwiki/PageSpec",
94 description => "internal linking behavior (default/current/negotiated)",
100 sub islanguagecode ($) { #{{{
102 return ($code =~ /^[a-z]{2}$/);
105 sub checkconfig () { #{{{
106 foreach my $field (qw{po_master_language po_slave_languages}) {
107 if (! exists $config{$field} || ! defined $config{$field}) {
108 error(sprintf(gettext("Must specify %s"), $field));
111 if (! (keys %{$config{po_slave_languages}})) {
112 error(gettext("At least one slave language must be defined in po_slave_languages"));
116 or error(sprintf(gettext("%s is not a valid language code"), $_));
117 } ($config{po_master_language}{code}, keys %{$config{po_slave_languages}});
118 if (! exists $config{po_translatable_pages} ||
119 ! defined $config{po_translatable_pages}) {
120 $config{po_translatable_pages}="";
122 if (! exists $config{po_link_to} ||
123 ! defined $config{po_link_to}) {
124 $config{po_link_to}='default';
127 $config{po_link_to} eq $_
128 } ('default', 'current', 'negotiated')) {
129 warn(sprintf(gettext('po_link_to=%s is not a valid setting, falling back to po_link_to=default'),
130 $config{po_link_to}));
131 $config{po_link_to}='default';
133 elsif ($config{po_link_to} eq "negotiated" && ! $config{usedirs}) {
134 warn(gettext('po_link_to=negotiated requires usedirs to be enabled, falling back to po_link_to=default'));
135 $config{po_link_to}='default';
137 push @{$config{wiki_file_prune_regexps}}, qr/\.pot$/;
140 sub otherlanguages($) { #{{{
144 if (istranslatable($page)) {
145 %ret = %{$translations{$page}};
147 elsif (istranslation($page)) {
148 my ($masterpage, $curlang) = ($page =~ /(.*)[.]([a-z]{2})$/);
149 $ret{$config{po_master_language}{code}} = $masterpage;
150 foreach my $lang (sort keys %{$translations{$masterpage}}) {
151 next if $lang eq $curlang;
152 $ret{$lang} = $translations{$masterpage}{$lang};
158 sub potfile ($) { #{{{
159 my $masterfile=shift;
161 (my $name, my $dir, my $suffix) = fileparse($masterfile, qr/\.[^.]*/);
162 $dir='' if $dir eq './';
163 return File::Spec->catpath('', $dir, $name . ".pot");
166 sub pofile ($$) { #{{{
167 my $masterfile=shift;
170 (my $name, my $dir, my $suffix) = fileparse($masterfile, qr/\.[^.]*/);
171 $dir='' if $dir eq './';
172 return File::Spec->catpath('', $dir, $name . "." . $lang . ".po");
175 sub pofiles ($) { #{{{
176 my $masterfile=shift;
177 return map pofile($masterfile, $_), (keys %{$config{po_slave_languages}});
180 sub refreshpot ($) { #{{{
181 my $masterfile=shift;
183 my $potfile=potfile($masterfile);
184 my %options = ("markdown" => (pagetype($masterfile) eq 'mdwn') ? 1 : 0);
185 my $doc=Locale::Po4a::Chooser::new('text',%options);
186 $doc->{TT}{utf_mode} = 1;
187 $doc->{TT}{file_in_charset} = 'utf-8';
188 $doc->{TT}{file_out_charset} = 'utf-8';
189 $doc->read($masterfile);
190 # let's cheat a bit to force porefs option to be passed to Locale::Po4a::Po;
191 # this is undocument use of internal Locale::Po4a::TransTractor's data,
192 # compulsory since this module prevents us from using the porefs option.
193 my %po_options = ('porefs' => 'none');
194 $doc->{TT}{po_out}=Locale::Po4a::Po->new(\%po_options);
195 $doc->{TT}{po_out}->set_charset('utf-8');
198 IkiWiki::prep_writefile(basename($potfile),dirname($potfile));
199 $doc->writepo($potfile);
202 sub refreshpofiles ($@) { #{{{
203 my $masterfile=shift;
206 my $potfile=potfile($masterfile);
207 error("[po/refreshpofiles] POT file ($potfile) does not exist") unless (-e $potfile);
209 foreach my $pofile (@pofiles) {
210 IkiWiki::prep_writefile(basename($pofile),dirname($pofile));
212 system("msgmerge", "-U", "--backup=none", $pofile, $potfile) == 0
213 or error("[po/refreshpofiles:$pofile] failed to update");
216 File::Copy::syscopy($potfile,$pofile)
217 or error("[po/refreshpofiles:$pofile] failed to copy the POT file");
222 sub buildtranslationscache() { #{{{
223 # use istranslation's side-effect
224 map istranslation($_), (keys %pagesources);
227 sub resettranslationscache() { #{{{
231 sub needsbuild () { #{{{
232 my $needsbuild=shift;
234 # backup @needsbuild content so that change() can know whether
235 # a given master page was rendered because its source file was changed
236 @origneedsbuild=(@$needsbuild);
238 buildtranslationscache();
240 # make existing translations depend on the corresponding master page
241 foreach my $master (keys %translations) {
242 map add_depends($_, $master), values %{otherlanguages($master)};
248 my $page=$params{page};
249 my $content=$params{content};
251 return unless UNIVERSAL::can("IkiWiki::Plugin::link", "import");
253 if (istranslation($page)) {
254 my ($masterpage, $curlang) = ($page =~ /(.*)[.]([a-z]{2})$/);
255 foreach my $destpage (@{$links{$page}}) {
256 if (istranslatable($destpage)) {
257 # replace one occurence of $destpage in $links{$page}
258 # (we only want to replace the one that was added by
259 # IkiWiki::Plugin::link::scan, other occurences may be
260 # there for other reasons)
261 for (my $i=0; $i<@{$links{$page}}; $i++) {
262 if (@{$links{$page}}[$i] eq $destpage) {
263 @{$links{$page}}[$i] = $destpage . '.' . $curlang;
270 elsif (! istranslatable($page) && ! istranslation($page)) {
271 foreach my $destpage (@{$links{$page}}) {
272 if (istranslatable($destpage)) {
274 push @{$links{$page}}, $destpage . '.' . $_;
275 } (keys %{$config{po_slave_languages}});
281 sub mytargetpage ($$) { #{{{
285 if (istranslation($page)) {
286 my ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
287 if (! $config{usedirs} || $masterpage eq 'index') {
288 return $masterpage . "." . $lang . "." . $ext;
291 return $masterpage . "/index." . $lang . "." . $ext;
294 elsif (istranslatable($page)) {
295 if (! $config{usedirs} || $page eq 'index') {
296 return $page . "." . $config{po_master_language}{code} . "." . $ext;
299 return $page . "/index." . $config{po_master_language}{code} . "." . $ext;
302 return $origsubs{'targetpage'}->($page, $ext);
305 sub mybeautify_urlpath ($) { #{{{
308 my $res=$origsubs{'beautify_urlpath'}->($url);
309 if ($config{po_link_to} eq "negotiated") {
310 $res =~ s!/\Qindex.$config{po_master_language}{code}.$config{htmlext}\E$!/!;
315 sub urlto_with_orig_beautiful_urlpath($$) { #{{{
319 inject(name => "IkiWiki::beautify_urlpath", call => $origsubs{'beautify_urlpath'});
320 my $res=urlto($to, $from);
321 inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath);
326 sub myurlto ($$;$) { #{{{
331 # workaround hard-coded /index.$config{htmlext} in IkiWiki::urlto()
333 && $config{po_link_to} eq "current"
334 && istranslation($from)
335 && istranslatable('index')) {
336 my ($masterpage, $curlang) = ($from =~ /(.*)[.]([a-z]{2})$/);
337 return IkiWiki::beautify_urlpath(IkiWiki::baseurl($from) . "index." . $curlang . ".$config{htmlext}");
339 return $origsubs{'urlto'}->($to,$from,$absolute);
342 sub mybestlink ($$) { #{{{
346 my $res=$origsubs{'bestlink'}->($page, $link);
348 if ($config{po_link_to} eq "current"
349 && istranslatable($res)
350 && istranslation($page)) {
351 my ($masterpage, $curlang) = ($page =~ /(.*)[.]([a-z]{2})$/);
352 return $res . "." . $curlang;
361 # blackbox for %filtered
365 sub alreadyfiltered($$) { #{{{
369 return ( exists $filtered{$page}{$destpage}
370 && $filtered{$page}{$destpage} eq 1 );
373 sub setalreadyfiltered($$) { #{{{
377 $filtered{$page}{$destpage}=1;
380 sub unsetalreadyfiltered($$) { #{{{
384 if (exists $filtered{$page}{$destpage}) {
385 delete $filtered{$page}{$destpage};
389 sub resetalreadyfiltered() { #{{{
394 # We use filter to convert PO to the master page's format,
395 # since the rest of ikiwiki should not work on PO files.
396 sub filter (@) { #{{{
399 my $page = $params{page};
400 my $destpage = $params{destpage};
401 my $content = decode_utf8(encode_utf8($params{content}));
403 return $content if ( ! istranslation($page)
404 || alreadyfiltered($page, $destpage) );
406 # CRLF line terminators make poor Locale::Po4a feel bad
407 $content=~s/\r\n/\n/g;
409 # Implementation notes
411 # 1. Locale::Po4a reads/writes from/to files, and I'm too lazy
412 # to learn how to disguise a variable as a file.
413 # 2. There are incompatibilities between some File::Temp versions
414 # (including 0.18, bundled with Lenny's perl-modules package)
415 # and others (e.g. 0.20, previously present in the archive as
416 # a standalone package): under certain circumstances, some
417 # return a relative filename, whereas others return an absolute one;
418 # we here use this module in a way that is at least compatible
419 # with 0.18 and 0.20. Beware, hit'n'run refactorers!
420 my $infile = new File::Temp(TEMPLATE => "ikiwiki-po-filter-in.XXXXXXXXXX",
421 DIR => File::Spec->tmpdir,
422 UNLINK => 1)->filename;
423 my $outfile = new File::Temp(TEMPLATE => "ikiwiki-po-filter-out.XXXXXXXXXX",
424 DIR => File::Spec->tmpdir,
425 UNLINK => 1)->filename;
427 writefile(basename($infile), File::Spec->tmpdir, $content);
429 my ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
430 my $masterfile = srcfile($pagesources{$masterpage});
433 push @masters,$masterfile;
435 "markdown" => (pagetype($masterfile) eq 'mdwn') ? 1 : 0,
437 my $doc=Locale::Po4a::Chooser::new('text',%options);
439 'po_in_name' => \@pos,
440 'file_in_name' => \@masters,
441 'file_in_charset' => 'utf-8',
442 'file_out_charset' => 'utf-8',
443 ) or error("[po/filter:$page]: failed to translate");
444 $doc->write($outfile) or error("[po/filter:$page] could not write $outfile");
445 $content = readfile($outfile) or error("[po/filter:$page] could not read $outfile");
447 # Unlinking should happen automatically, thanks to File::Temp,
448 # but it does not work here, probably because of the way writefile()
449 # and Locale::Po4a::write() work.
450 unlink $infile, $outfile;
452 setalreadyfiltered($page, $destpage);
456 sub htmlize (@) { #{{{
459 my $page = $params{page};
460 my $content = $params{content};
461 my ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
462 my $masterfile = srcfile($pagesources{$masterpage});
464 # force content to be htmlize'd as if it was the same type as the master page
465 return IkiWiki::htmlize($page, $page, pagetype($masterfile), $content);
468 sub percenttranslated ($) { #{{{
471 return gettext("N/A") unless (istranslation($page));
472 my ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
473 my $file=srcfile($pagesources{$page});
474 my $masterfile = srcfile($pagesources{$masterpage});
477 push @masters,$masterfile;
479 "markdown" => (pagetype($masterfile) eq 'mdwn') ? 1 : 0,
481 my $doc=Locale::Po4a::Chooser::new('text',%options);
483 'po_in_name' => \@pos,
484 'file_in_name' => \@masters,
485 'file_in_charset' => 'utf-8',
486 'file_out_charset' => 'utf-8',
487 ) or error("[po/percenttranslated:$page]: failed to translate");
488 my ($percent,$hit,$queries) = $doc->stats();
492 sub otherlanguagesloop ($) { #{{{
496 if (istranslatable($page)) {
497 foreach my $lang (sort keys %{$translations{$page}}) {
498 my $translation = $translations{$page}{$lang};
500 url => urlto($translation, $page),
502 language => $config{po_slave_languages}{$lang},
503 percent => percenttranslated($translation),
507 elsif (istranslation($page)) {
508 my ($masterpage, $curlang) = ($page =~ /(.*)[.]([a-z]{2})$/);
510 url => urlto_with_orig_beautiful_urlpath($masterpage, $page),
511 code => $config{po_master_language}{code},
512 language => $config{po_master_language}{name},
515 foreach my $lang (sort keys %{$translations{$masterpage}}) {
517 url => urlto($translations{$masterpage}{$lang}, $page),
519 language => $config{po_slave_languages}{$lang},
520 percent => percenttranslated($translations{$masterpage}{$lang}),
521 } unless ($lang eq $curlang);
527 sub pagetemplate (@) { #{{{
529 my $page=$params{page};
530 my $destpage=$params{destpage};
531 my $template=$params{template};
533 my ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/) if istranslation($page);
535 if (istranslation($page) && $template->query(name => "percenttranslated")) {
536 $template->param(percenttranslated => percenttranslated($page));
538 if ($template->query(name => "istranslation")) {
539 $template->param(istranslation => istranslation($page));
541 if ($template->query(name => "istranslatable")) {
542 $template->param(istranslatable => istranslatable($page));
544 if ($template->query(name => "otherlanguages")) {
545 $template->param(otherlanguages => [otherlanguagesloop($page)]);
546 map add_depends($page, $_), (values %{otherlanguages($page)});
548 # Rely on IkiWiki::Render's genpage() to decide wether
549 # a discussion link should appear on $page; this is not
550 # totally accurate, though: some broken links may be generated
551 # when cgiurl is disabled.
552 # This compromise avoids some code duplication, and will probably
553 # prevent future breakage when ikiwiki internals change.
554 # Known limitations are preferred to future random bugs.
555 if ($template->param('discussionlink') && istranslation($page)) {
556 $template->param('discussionlink' => htmllink(
559 $masterpage . '/' . gettext("Discussion"),
562 linktext => gettext("Discussion"),
565 # Remove broken parentlink to ./index.html on home page's translations.
566 # It works because this hook has the "last" parameter set, to ensure it
567 # runs after parentlinks' own pagetemplate hook.
568 if ($template->param('parentlinks')
569 && istranslation($page)
570 && $masterpage eq "index") {
571 $template->param('parentlinks' => []);
578 my $updated_po_files=0;
580 # Refresh/create POT and PO files as needed.
581 foreach my $page (map pagename($_), @rendered) {
582 next unless istranslatable($page);
583 my $file=srcfile($pagesources{$page});
584 my $updated_pot_file=0;
585 # Only refresh Pot file if it does not exist, or if
586 # $pagesources{$page} was changed: don't if only the HTML was
587 # refreshed, e.g. because of a dependency.
588 if ((grep { $_ eq $pagesources{$page} } @origneedsbuild)
589 || ! -e potfile($file)) {
595 push @pofiles, $_ if ($updated_pot_file || ! -e $_);
598 refreshpofiles($file, @pofiles);
599 map { IkiWiki::rcs_add($_); } @pofiles if ($config{rcs});
604 if ($updated_po_files) {
605 # Check staged changes in.
607 IkiWiki::disable_commit_hook();
608 IkiWiki::rcs_commit_staged(gettext("updated PO files"),
609 "IkiWiki::Plugin::po::change", "127.0.0.1");
610 IkiWiki::enable_commit_hook();
611 IkiWiki::rcs_update();
613 # Reinitialize module's private variables.
614 resetalreadyfiltered();
615 resettranslationscache();
616 # Trigger a wiki refresh.
617 require IkiWiki::Render;
619 IkiWiki::saveindex();
623 sub editcontent () { #{{{
625 # as we're previewing or saving a page, the content may have
626 # changed, so tell the next filter() invocation it must not be lazy
627 unsetalreadyfiltered($params{page}, $params{page});
628 return $params{content};
631 sub istranslatable ($) { #{{{
634 my $file=$pagesources{$page};
637 || (defined pagetype($file) && pagetype($file) eq 'po')
638 || $file =~ /\.pot$/) {
641 return pagespec_match($page, $config{po_translatable_pages});
644 sub _istranslation ($) { #{{{
647 my $file=$pagesources{$page};
648 if (! defined $file) {
649 return IkiWiki::FailReason->new("no file specified");
653 || ! defined pagetype($file)
654 || ! pagetype($file) eq 'po'
655 || $file =~ /\.pot$/) {
659 my ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
660 if (! defined $masterpage || ! defined $lang
661 || ! (length($masterpage) > 0) || ! (length($lang) > 0)
662 || ! defined $pagesources{$masterpage}
663 || ! defined $config{po_slave_languages}{$lang}) {
667 return istranslatable($masterpage);
670 sub istranslation ($) { #{{{
673 if (_istranslation($page)) {
674 my ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
675 $translations{$masterpage}{$lang}=$page unless exists $translations{$masterpage}{$lang};
681 package IkiWiki::PageSpec;
686 sub match_istranslation ($;@) { #{{{
689 if (IkiWiki::Plugin::po::istranslation($page)) {
690 return IkiWiki::SuccessReason->new("is a translation page");
693 return IkiWiki::FailReason->new("is not a translation page");
697 sub match_istranslatable ($;@) { #{{{
700 if (IkiWiki::Plugin::po::istranslatable($page)) {
701 return IkiWiki::SuccessReason->new("is set as translatable in po_translatable_pages");
704 return IkiWiki::FailReason->new("is not set as translatable in po_translatable_pages");
708 sub match_lang ($$;@) { #{{{
712 my $regexp=IkiWiki::glob2re($wanted);
716 if (IkiWiki::Plugin::po::istranslation($page)) {
717 ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
720 $lang = $config{po_master_language}{code};
723 if ($lang!~/^$regexp$/i) {
724 return IkiWiki::FailReason->new("file language is $lang, not $wanted");
727 return IkiWiki::SuccessReason->new("file language is $wanted");
731 sub match_currentlang ($$;@) { #{{{
736 my ($currentmasterpage, $currentlang, $masterpage, $lang);
738 return IkiWiki::FailReason->new("no location provided") unless exists $params{location};
740 if (IkiWiki::Plugin::po::istranslation($params{location})) {
741 ($currentmasterpage, $currentlang) = ($params{location} =~ /(.*)[.]([a-z]{2})$/);
744 $currentlang = $config{po_master_language}{code};
747 if (IkiWiki::Plugin::po::istranslation($page)) {
748 ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
751 $lang = $config{po_master_language}{code};
754 if ($lang eq $currentlang) {
755 return IkiWiki::SuccessReason->new("file language is the same as current one, i.e. $currentlang");
758 return IkiWiki::FailReason->new("file language is $lang, whereas current language is $currentlang");