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 = masterpage($page);
149 $ret{$config{po_master_language}{code}} = $masterpage;
150 foreach my $lang (sort keys %{$translations{$masterpage}}) {
151 next if $lang eq lang($page);
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 foreach my $destpage (@{$links{$page}}) {
255 if (istranslatable($destpage)) {
256 # replace one occurence of $destpage in $links{$page}
257 # (we only want to replace the one that was added by
258 # IkiWiki::Plugin::link::scan, other occurences may be
259 # there for other reasons)
260 for (my $i=0; $i<@{$links{$page}}; $i++) {
261 if (@{$links{$page}}[$i] eq $destpage) {
262 @{$links{$page}}[$i] = $destpage . '.' . lang($page);
269 elsif (! istranslatable($page) && ! istranslation($page)) {
270 foreach my $destpage (@{$links{$page}}) {
271 if (istranslatable($destpage)) {
273 push @{$links{$page}}, $destpage . '.' . $_;
274 } (keys %{$config{po_slave_languages}});
280 sub mytargetpage ($$) { #{{{
284 if (istranslation($page)) {
285 my ($masterpage, $lang) = (masterpage($page), lang($page));
286 if (! $config{usedirs} || $masterpage eq 'index') {
287 return $masterpage . "." . $lang . "." . $ext;
290 return $masterpage . "/index." . $lang . "." . $ext;
293 elsif (istranslatable($page)) {
294 if (! $config{usedirs} || $page eq 'index') {
295 return $page . "." . $config{po_master_language}{code} . "." . $ext;
298 return $page . "/index." . $config{po_master_language}{code} . "." . $ext;
301 return $origsubs{'targetpage'}->($page, $ext);
304 sub mybeautify_urlpath ($) { #{{{
307 my $res=$origsubs{'beautify_urlpath'}->($url);
308 if ($config{po_link_to} eq "negotiated") {
309 $res =~ s!/\Qindex.$config{po_master_language}{code}.$config{htmlext}\E$!/!;
314 sub urlto_with_orig_beautiful_urlpath($$) { #{{{
318 inject(name => "IkiWiki::beautify_urlpath", call => $origsubs{'beautify_urlpath'});
319 my $res=urlto($to, $from);
320 inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath);
325 sub myurlto ($$;$) { #{{{
330 # workaround hard-coded /index.$config{htmlext} in IkiWiki::urlto()
332 && $config{po_link_to} eq "current"
333 && istranslation($from)
334 && istranslatable('index')) {
335 return IkiWiki::beautify_urlpath(IkiWiki::baseurl($from) . "index." . lang($from) . ".$config{htmlext}");
337 return $origsubs{'urlto'}->($to,$from,$absolute);
340 sub mybestlink ($$) { #{{{
344 my $res=$origsubs{'bestlink'}->($page, $link);
346 if ($config{po_link_to} eq "current"
347 && istranslatable($res)
348 && istranslation($page)) {
349 return $res . "." . lang($page);
358 # blackbox for %filtered
362 sub alreadyfiltered($$) { #{{{
366 return ( exists $filtered{$page}{$destpage}
367 && $filtered{$page}{$destpage} eq 1 );
370 sub setalreadyfiltered($$) { #{{{
374 $filtered{$page}{$destpage}=1;
377 sub unsetalreadyfiltered($$) { #{{{
381 if (exists $filtered{$page}{$destpage}) {
382 delete $filtered{$page}{$destpage};
386 sub resetalreadyfiltered() { #{{{
391 # We use filter to convert PO to the master page's format,
392 # since the rest of ikiwiki should not work on PO files.
393 sub filter (@) { #{{{
396 my $page = $params{page};
397 my $destpage = $params{destpage};
398 my $content = decode_utf8(encode_utf8($params{content}));
400 return $content if ( ! istranslation($page)
401 || alreadyfiltered($page, $destpage) );
403 # CRLF line terminators make poor Locale::Po4a feel bad
404 $content=~s/\r\n/\n/g;
406 # Implementation notes
408 # 1. Locale::Po4a reads/writes from/to files, and I'm too lazy
409 # to learn how to disguise a variable as a file.
410 # 2. There are incompatibilities between some File::Temp versions
411 # (including 0.18, bundled with Lenny's perl-modules package)
412 # and others (e.g. 0.20, previously present in the archive as
413 # a standalone package): under certain circumstances, some
414 # return a relative filename, whereas others return an absolute one;
415 # we here use this module in a way that is at least compatible
416 # with 0.18 and 0.20. Beware, hit'n'run refactorers!
417 my $infile = new File::Temp(TEMPLATE => "ikiwiki-po-filter-in.XXXXXXXXXX",
418 DIR => File::Spec->tmpdir,
419 UNLINK => 1)->filename;
420 my $outfile = new File::Temp(TEMPLATE => "ikiwiki-po-filter-out.XXXXXXXXXX",
421 DIR => File::Spec->tmpdir,
422 UNLINK => 1)->filename;
424 writefile(basename($infile), File::Spec->tmpdir, $content);
426 my $masterfile = srcfile($pagesources{masterpage($page)});
429 push @masters,$masterfile;
431 "markdown" => (pagetype($masterfile) eq 'mdwn') ? 1 : 0,
433 my $doc=Locale::Po4a::Chooser::new('text',%options);
435 'po_in_name' => \@pos,
436 'file_in_name' => \@masters,
437 'file_in_charset' => 'utf-8',
438 'file_out_charset' => 'utf-8',
439 ) or error("[po/filter:$page]: failed to translate");
440 $doc->write($outfile) or error("[po/filter:$page] could not write $outfile");
441 $content = readfile($outfile) or error("[po/filter:$page] could not read $outfile");
443 # Unlinking should happen automatically, thanks to File::Temp,
444 # but it does not work here, probably because of the way writefile()
445 # and Locale::Po4a::write() work.
446 unlink $infile, $outfile;
448 setalreadyfiltered($page, $destpage);
452 sub htmlize (@) { #{{{
455 my $page = $params{page};
456 my $content = $params{content};
457 my $masterfile = srcfile($pagesources{masterpage($page)});
459 # force content to be htmlize'd as if it was the same type as the master page
460 return IkiWiki::htmlize($page, $page, pagetype($masterfile), $content);
463 sub percenttranslated ($) { #{{{
466 return gettext("N/A") unless istranslation($page);
467 my $file=srcfile($pagesources{$page});
468 my $masterfile = srcfile($pagesources{masterpage($page)});
471 push @masters,$masterfile;
473 "markdown" => (pagetype($masterfile) eq 'mdwn') ? 1 : 0,
475 my $doc=Locale::Po4a::Chooser::new('text',%options);
477 'po_in_name' => \@pos,
478 'file_in_name' => \@masters,
479 'file_in_charset' => 'utf-8',
480 'file_out_charset' => 'utf-8',
481 ) or error("[po/percenttranslated:$page]: failed to translate");
482 my ($percent,$hit,$queries) = $doc->stats();
486 sub otherlanguagesloop ($) { #{{{
490 if (istranslatable($page)) {
491 my %otherpages=%{otherlanguages($page)};
492 while (my ($lang, $translation) = each %otherpages) {
494 url => urlto($translation, $page),
496 language => $config{po_slave_languages}{$lang},
497 percent => percenttranslated($translation),
501 elsif (istranslation($page)) {
502 my ($masterpage, $curlang) = (masterpage($page), lang($page));
504 url => urlto_with_orig_beautiful_urlpath($masterpage, $page),
505 code => $config{po_master_language}{code},
506 language => $config{po_master_language}{name},
509 foreach my $lang (sort keys %{$translations{$masterpage}}) {
511 url => urlto($translations{$masterpage}{$lang}, $page),
513 language => $config{po_slave_languages}{$lang},
514 percent => percenttranslated($translations{$masterpage}{$lang}),
515 } unless ($lang eq $curlang);
521 sub pagetemplate (@) { #{{{
523 my $page=$params{page};
524 my $destpage=$params{destpage};
525 my $template=$params{template};
527 my ($masterpage, $lang) = istranslation($page);
529 if (istranslation($page) && $template->query(name => "percenttranslated")) {
530 $template->param(percenttranslated => percenttranslated($page));
532 if ($template->query(name => "istranslation")) {
533 $template->param(istranslation => scalar istranslation($page));
535 if ($template->query(name => "istranslatable")) {
536 $template->param(istranslatable => istranslatable($page));
538 if ($template->query(name => "otherlanguages")) {
539 $template->param(otherlanguages => [otherlanguagesloop($page)]);
540 map add_depends($page, $_), (values %{otherlanguages($page)});
542 # Rely on IkiWiki::Render's genpage() to decide wether
543 # a discussion link should appear on $page; this is not
544 # totally accurate, though: some broken links may be generated
545 # when cgiurl is disabled.
546 # This compromise avoids some code duplication, and will probably
547 # prevent future breakage when ikiwiki internals change.
548 # Known limitations are preferred to future random bugs.
549 if ($template->param('discussionlink') && istranslation($page)) {
550 $template->param('discussionlink' => htmllink(
553 $masterpage . '/' . gettext("Discussion"),
556 linktext => gettext("Discussion"),
559 # Remove broken parentlink to ./index.html on home page's translations.
560 # It works because this hook has the "last" parameter set, to ensure it
561 # runs after parentlinks' own pagetemplate hook.
562 if ($template->param('parentlinks')
563 && istranslation($page)
564 && $masterpage eq "index") {
565 $template->param('parentlinks' => []);
572 my $updated_po_files=0;
574 # Refresh/create POT and PO files as needed.
575 foreach my $page (map pagename($_), @rendered) {
576 next unless istranslatable($page);
577 my $file=srcfile($pagesources{$page});
578 my $updated_pot_file=0;
579 # Only refresh Pot file if it does not exist, or if
580 # $pagesources{$page} was changed: don't if only the HTML was
581 # refreshed, e.g. because of a dependency.
582 if ((grep { $_ eq $pagesources{$page} } @origneedsbuild)
583 || ! -e potfile($file)) {
589 push @pofiles, $_ if ($updated_pot_file || ! -e $_);
592 refreshpofiles($file, @pofiles);
593 map { IkiWiki::rcs_add($_); } @pofiles if ($config{rcs});
598 if ($updated_po_files) {
599 # Check staged changes in.
601 IkiWiki::disable_commit_hook();
602 IkiWiki::rcs_commit_staged(gettext("updated PO files"),
603 "IkiWiki::Plugin::po::change", "127.0.0.1");
604 IkiWiki::enable_commit_hook();
605 IkiWiki::rcs_update();
607 # Reinitialize module's private variables.
608 resetalreadyfiltered();
609 resettranslationscache();
610 # Trigger a wiki refresh.
611 require IkiWiki::Render;
613 IkiWiki::saveindex();
617 sub editcontent () { #{{{
619 # as we're previewing or saving a page, the content may have
620 # changed, so tell the next filter() invocation it must not be lazy
621 unsetalreadyfiltered($params{page}, $params{page});
622 return $params{content};
625 sub istranslatable ($) { #{{{
628 my $file=$pagesources{$page};
631 || (defined pagetype($file) && pagetype($file) eq 'po')
632 || $file =~ /\.pot$/) {
635 return pagespec_match($page, $config{po_translatable_pages});
638 sub _istranslation ($) { #{{{
641 my $file=$pagesources{$page};
642 if (! defined $file) {
643 return IkiWiki::FailReason->new("no file specified");
647 || ! defined pagetype($file)
648 || ! pagetype($file) eq 'po'
649 || $file =~ /\.pot$/) {
653 my ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
654 if (! defined $masterpage || ! defined $lang
655 || ! (length($masterpage) > 0) || ! (length($lang) > 0)
656 || ! defined $pagesources{$masterpage}
657 || ! defined $config{po_slave_languages}{$lang}) {
661 return ($masterpage, $lang) if istranslatable($masterpage);
664 sub istranslation ($) { #{{{
667 if (1 < (my ($masterpage, $lang) = _istranslation($page))) {
668 $translations{$masterpage}{$lang}=$page unless exists $translations{$masterpage}{$lang};
669 return ($masterpage, $lang);
674 sub masterpage ($) { #{{{
677 if ( 1 < (my ($masterpage, $lang) = _istranslation($page))) {
686 if (1 < (my ($masterpage, $lang) = _istranslation($page))) {
689 return $config{po_master_language}{code};
692 package IkiWiki::PageSpec;
697 sub match_istranslation ($;@) { #{{{
700 if (IkiWiki::Plugin::po::istranslation($page)) {
701 return IkiWiki::SuccessReason->new("is a translation page");
704 return IkiWiki::FailReason->new("is not a translation page");
708 sub match_istranslatable ($;@) { #{{{
711 if (IkiWiki::Plugin::po::istranslatable($page)) {
712 return IkiWiki::SuccessReason->new("is set as translatable in po_translatable_pages");
715 return IkiWiki::FailReason->new("is not set as translatable in po_translatable_pages");
719 sub match_lang ($$;@) { #{{{
723 my $regexp=IkiWiki::glob2re($wanted);
727 if (IkiWiki::Plugin::po::istranslation($page)) {
728 ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
731 $lang = $config{po_master_language}{code};
734 if ($lang!~/^$regexp$/i) {
735 return IkiWiki::FailReason->new("file language is $lang, not $wanted");
738 return IkiWiki::SuccessReason->new("file language is $wanted");
742 sub match_currentlang ($$;@) { #{{{
747 my ($currentmasterpage, $currentlang, $masterpage, $lang);
749 return IkiWiki::FailReason->new("no location provided") unless exists $params{location};
751 if (IkiWiki::Plugin::po::istranslation($params{location})) {
752 ($currentmasterpage, $currentlang) = ($params{location} =~ /(.*)[.]([a-z]{2})$/);
755 $currentlang = $config{po_master_language}{code};
758 if (IkiWiki::Plugin::po::istranslation($page)) {
759 ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
762 $lang = $config{po_master_language}{code};
765 if ($lang eq $currentlang) {
766 return IkiWiki::SuccessReason->new("file language is the same as current one, i.e. $currentlang");
769 return IkiWiki::FailReason->new("file language is $lang, whereas current language is $currentlang");