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;
26 memoize("_istranslation");
27 memoize("percenttranslated");
28 # FIXME: memoizing istranslatable() makes some test cases fail once every
29 # two tries; this may be related to the artificial way the testsuite is
31 # memoize("istranslatable");
33 # backup references to subs that will be overriden
37 hook(type => "getsetup", id => "po", call => \&getsetup);
38 hook(type => "checkconfig", id => "po", call => \&checkconfig);
39 hook(type => "needsbuild", id => "po", call => \&needsbuild);
40 hook(type => "scan", id => "po", call => \&scan, last =>1);
41 hook(type => "filter", id => "po", call => \&filter);
42 hook(type => "htmlize", id => "po", call => \&htmlize);
43 hook(type => "pagetemplate", id => "po", call => \&pagetemplate, last => 1);
44 hook(type => "change", id => "po", call => \&change);
45 hook(type => "editcontent", id => "po", call => \&editcontent);
47 $origsubs{'bestlink'}=\&IkiWiki::bestlink;
48 inject(name => "IkiWiki::bestlink", call => \&mybestlink);
49 $origsubs{'beautify_urlpath'}=\&IkiWiki::beautify_urlpath;
50 inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath);
51 $origsubs{'targetpage'}=\&IkiWiki::targetpage;
52 inject(name => "IkiWiki::targetpage", call => \&mytargetpage);
53 $origsubs{'urlto'}=\&IkiWiki::urlto;
54 inject(name => "IkiWiki::urlto", call => \&myurlto);
57 sub getsetup () { #{{{
61 rebuild => 1, # format plugin & changes html filenames
63 po_master_language => {
69 description => "master language (non-PO files)",
73 po_slave_languages => {
80 description => "slave languages (PO files)",
84 po_translatable_pages => {
86 example => "!*/Discussion",
87 description => "PageSpec controlling which pages are translatable",
88 link => "ikiwiki/PageSpec",
95 description => "internal linking behavior (default/current/negotiated)",
101 sub islanguagecode ($) { #{{{
103 return ($code =~ /^[a-z]{2}$/);
106 sub checkconfig () { #{{{
107 foreach my $field (qw{po_master_language po_slave_languages}) {
108 if (! exists $config{$field} || ! defined $config{$field}) {
109 error(sprintf(gettext("Must specify %s"), $field));
112 if (! (keys %{$config{po_slave_languages}})) {
113 error(gettext("At least one slave language must be defined in po_slave_languages"));
117 or error(sprintf(gettext("%s is not a valid language code"), $_));
118 } ($config{po_master_language}{code}, keys %{$config{po_slave_languages}});
119 if (! exists $config{po_translatable_pages} ||
120 ! defined $config{po_translatable_pages}) {
121 $config{po_translatable_pages}="";
123 if (! exists $config{po_link_to} ||
124 ! defined $config{po_link_to}) {
125 $config{po_link_to}='default';
128 $config{po_link_to} eq $_
129 } ('default', 'current', 'negotiated')) {
130 warn(sprintf(gettext('po_link_to=%s is not a valid setting, falling back to po_link_to=default'),
131 $config{po_link_to}));
132 $config{po_link_to}='default';
134 elsif ($config{po_link_to} eq "negotiated" && ! $config{usedirs}) {
135 warn(gettext('po_link_to=negotiated requires usedirs to be enabled, falling back to po_link_to=default'));
136 $config{po_link_to}='default';
138 push @{$config{wiki_file_prune_regexps}}, qr/\.pot$/;
141 sub otherlanguages($) { #{{{
145 if (istranslatable($page)) {
146 %ret = %{$translations{$page}};
148 elsif (istranslation($page)) {
149 my ($masterpage, $curlang) = ($page =~ /(.*)[.]([a-z]{2})$/);
150 $ret{$config{po_master_language}{code}} = $masterpage;
151 foreach my $lang (sort keys %{$translations{$masterpage}}) {
152 next if $lang eq $curlang;
153 $ret{$lang} = $translations{$masterpage}{$lang};
159 sub potfile ($) { #{{{
160 my $masterfile=shift;
162 (my $name, my $dir, my $suffix) = fileparse($masterfile, qr/\.[^.]*/);
163 $dir='' if $dir eq './';
164 return File::Spec->catpath('', $dir, $name . ".pot");
167 sub pofile ($$) { #{{{
168 my $masterfile=shift;
171 (my $name, my $dir, my $suffix) = fileparse($masterfile, qr/\.[^.]*/);
172 $dir='' if $dir eq './';
173 return File::Spec->catpath('', $dir, $name . "." . $lang . ".po");
176 sub pofiles ($) { #{{{
177 my $masterfile=shift;
178 return map pofile($masterfile, $_), (keys %{$config{po_slave_languages}});
181 sub refreshpot ($) { #{{{
182 my $masterfile=shift;
184 my $potfile=potfile($masterfile);
185 my %options = ("markdown" => (pagetype($masterfile) eq 'mdwn') ? 1 : 0);
186 my $doc=Locale::Po4a::Chooser::new('text',%options);
187 $doc->{TT}{utf_mode} = 1;
188 $doc->{TT}{file_in_charset} = 'utf-8';
189 $doc->{TT}{file_out_charset} = 'utf-8';
190 $doc->read($masterfile);
191 # let's cheat a bit to force porefs option to be passed to Locale::Po4a::Po;
192 # this is undocument use of internal Locale::Po4a::TransTractor's data,
193 # compulsory since this module prevents us from using the porefs option.
194 my %po_options = ('porefs' => 'none');
195 $doc->{TT}{po_out}=Locale::Po4a::Po->new(\%po_options);
196 $doc->{TT}{po_out}->set_charset('utf-8');
199 IkiWiki::prep_writefile(basename($potfile),dirname($potfile));
200 $doc->writepo($potfile);
203 sub refreshpofiles ($@) { #{{{
204 my $masterfile=shift;
207 my $potfile=potfile($masterfile);
208 error("[po/refreshpofiles] POT file ($potfile) does not exist") unless (-e $potfile);
210 foreach my $pofile (@pofiles) {
211 IkiWiki::prep_writefile(basename($pofile),dirname($pofile));
213 system("msgmerge", "-U", "--backup=none", $pofile, $potfile) == 0
214 or error("[po/refreshpofiles:$pofile] failed to update");
217 File::Copy::syscopy($potfile,$pofile)
218 or error("[po/refreshpofiles:$pofile] failed to copy the POT file");
223 sub buildtranslationscache() { #{{{
224 # use istranslation's side-effect
225 map istranslation($_), (keys %pagesources);
228 sub resettranslationscache() { #{{{
232 sub needsbuild () { #{{{
233 my $needsbuild=shift;
235 # backup @needsbuild content so that change() can know whether
236 # a given master page was rendered because its source file was changed
237 @origneedsbuild=(@$needsbuild);
239 buildtranslationscache();
241 # make existing translations depend on the corresponding master page
242 foreach my $master (keys %translations) {
243 map add_depends($_, $master), values %{otherlanguages($master)};
249 my $page=$params{page};
250 my $content=$params{content};
252 return unless UNIVERSAL::can("IkiWiki::Plugin::link", "import");
254 if (istranslation($page)) {
255 my ($masterpage, $curlang) = ($page =~ /(.*)[.]([a-z]{2})$/);
256 foreach my $destpage (@{$links{$page}}) {
257 if (istranslatable($destpage)) {
258 # replace one occurence of $destpage in $links{$page}
259 # (we only want to replace the one that was added by
260 # IkiWiki::Plugin::link::scan, other occurences may be
261 # there for other reasons)
262 for (my $i=0; $i<@{$links{$page}}; $i++) {
263 if (@{$links{$page}}[$i] eq $destpage) {
264 @{$links{$page}}[$i] = $destpage . '.' . $curlang;
271 elsif (! istranslatable($page) && ! istranslation($page)) {
272 foreach my $destpage (@{$links{$page}}) {
273 if (istranslatable($destpage)) {
275 push @{$links{$page}}, $destpage . '.' . $_;
276 } (keys %{$config{po_slave_languages}});
282 sub mytargetpage ($$) { #{{{
286 if (istranslation($page)) {
287 my ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
288 if (! $config{usedirs} || $masterpage eq 'index') {
289 return $masterpage . "." . $lang . "." . $ext;
292 return $masterpage . "/index." . $lang . "." . $ext;
295 elsif (istranslatable($page)) {
296 if (! $config{usedirs} || $page eq 'index') {
297 return $page . "." . $config{po_master_language}{code} . "." . $ext;
300 return $page . "/index." . $config{po_master_language}{code} . "." . $ext;
303 return $origsubs{'targetpage'}->($page, $ext);
306 sub mybeautify_urlpath ($) { #{{{
309 my $res=$origsubs{'beautify_urlpath'}->($url);
310 if ($config{po_link_to} eq "negotiated") {
311 $res =~ s!/\Qindex.$config{po_master_language}{code}.$config{htmlext}\E$!/!;
316 sub urlto_with_orig_beautiful_urlpath($$) { #{{{
320 inject(name => "IkiWiki::beautify_urlpath", call => $origsubs{'beautify_urlpath'});
321 my $res=urlto($to, $from);
322 inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath);
327 sub myurlto ($$;$) { #{{{
332 # workaround hard-coded /index.$config{htmlext} in IkiWiki::urlto()
334 && $config{po_link_to} eq "current"
335 && istranslation($from)
336 && istranslatable('index')) {
337 my ($masterpage, $curlang) = ($from =~ /(.*)[.]([a-z]{2})$/);
338 return IkiWiki::beautify_urlpath(IkiWiki::baseurl($from) . "index." . $curlang . ".$config{htmlext}");
340 return $origsubs{'urlto'}->($to,$from,$absolute);
343 sub mybestlink ($$) { #{{{
347 my $res=$origsubs{'bestlink'}->($page, $link);
349 if ($config{po_link_to} eq "current"
350 && istranslatable($res)
351 && istranslation($page)) {
352 my ($masterpage, $curlang) = ($page =~ /(.*)[.]([a-z]{2})$/);
353 return $res . "." . $curlang;
362 sub alreadyfiltered($$) { #{{{
366 return ( exists $filtered{$page}{$destpage}
367 && $filtered{$page}{$destpage} eq 1 );
369 sub setalreadyfiltered($$) { #{{{
373 $filtered{$page}{$destpage}=1;
375 sub unsetalreadyfiltered($$) { #{{{
379 if (exists $filtered{$page}{$destpage}) {
380 delete $filtered{$page}{$destpage};
383 sub resetalreadyfiltered() { #{{{
387 # We use filter to convert PO to the master page's format,
388 # since the rest of ikiwiki should not work on PO files.
389 sub filter (@) { #{{{
392 my $page = $params{page};
393 my $destpage = $params{destpage};
394 my $content = decode_utf8(encode_utf8($params{content}));
396 return $content if ( ! istranslation($page)
397 || alreadyfiltered($page, $destpage) );
399 # CRLF line terminators make poor Locale::Po4a feel bad
400 $content=~s/\r\n/\n/g;
402 # Implementation notes
404 # 1. Locale::Po4a reads/writes from/to files, and I'm too lazy
405 # to learn how to disguise a variable as a file.
406 # 2. There are incompatibilities between some File::Temp versions
407 # (including 0.18, bundled with Lenny's perl-modules package)
408 # and others (e.g. 0.20, previously present in the archive as
409 # a standalone package): under certain circumstances, some
410 # return a relative filename, whereas others return an absolute one;
411 # we here use this module in a way that is at least compatible
412 # with 0.18 and 0.20. Beware, hit'n'run refactorers!
413 my $infile = new File::Temp(TEMPLATE => "ikiwiki-po-filter-in.XXXXXXXXXX",
414 DIR => File::Spec->tmpdir,
415 UNLINK => 1)->filename;
416 my $outfile = new File::Temp(TEMPLATE => "ikiwiki-po-filter-out.XXXXXXXXXX",
417 DIR => File::Spec->tmpdir,
418 UNLINK => 1)->filename;
420 writefile(basename($infile), File::Spec->tmpdir, $content);
422 my ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
423 my $masterfile = srcfile($pagesources{$masterpage});
426 push @masters,$masterfile;
428 "markdown" => (pagetype($masterfile) eq 'mdwn') ? 1 : 0,
430 my $doc=Locale::Po4a::Chooser::new('text',%options);
432 'po_in_name' => \@pos,
433 'file_in_name' => \@masters,
434 'file_in_charset' => 'utf-8',
435 'file_out_charset' => 'utf-8',
436 ) or error("[po/filter:$page]: failed to translate");
437 $doc->write($outfile) or error("[po/filter:$page] could not write $outfile");
438 $content = readfile($outfile) or error("[po/filter:$page] could not read $outfile");
440 # Unlinking should happen automatically, thanks to File::Temp,
441 # but it does not work here, probably because of the way writefile()
442 # and Locale::Po4a::write() work.
443 unlink $infile, $outfile;
445 setalreadyfiltered($page, $destpage);
449 sub htmlize (@) { #{{{
452 my $page = $params{page};
453 my $content = $params{content};
454 my ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
455 my $masterfile = srcfile($pagesources{$masterpage});
457 # force content to be htmlize'd as if it was the same type as the master page
458 return IkiWiki::htmlize($page, $page, pagetype($masterfile), $content);
461 sub percenttranslated ($) { #{{{
464 return gettext("N/A") unless (istranslation($page));
465 my ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
466 my $file=srcfile($pagesources{$page});
467 my $masterfile = srcfile($pagesources{$masterpage});
470 push @masters,$masterfile;
472 "markdown" => (pagetype($masterfile) eq 'mdwn') ? 1 : 0,
474 my $doc=Locale::Po4a::Chooser::new('text',%options);
476 'po_in_name' => \@pos,
477 'file_in_name' => \@masters,
478 'file_in_charset' => 'utf-8',
479 'file_out_charset' => 'utf-8',
480 ) or error("[po/percenttranslated:$page]: failed to translate");
481 my ($percent,$hit,$queries) = $doc->stats();
485 sub otherlanguagesloop ($) { #{{{
489 if (istranslatable($page)) {
490 foreach my $lang (sort keys %{$translations{$page}}) {
491 my $translation = $translations{$page}{$lang};
493 url => urlto($translation, $page),
495 language => $config{po_slave_languages}{$lang},
496 percent => percenttranslated($translation),
500 elsif (istranslation($page)) {
501 my ($masterpage, $curlang) = ($page =~ /(.*)[.]([a-z]{2})$/);
503 url => urlto_with_orig_beautiful_urlpath($masterpage, $page),
504 code => $config{po_master_language}{code},
505 language => $config{po_master_language}{name},
508 foreach my $lang (sort keys %{$translations{$masterpage}}) {
510 url => urlto($translations{$masterpage}{$lang}, $page),
512 language => $config{po_slave_languages}{$lang},
513 percent => percenttranslated($translations{$masterpage}{$lang}),
514 } unless ($lang eq $curlang);
520 sub pagetemplate (@) { #{{{
522 my $page=$params{page};
523 my $destpage=$params{destpage};
524 my $template=$params{template};
526 my ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/) if istranslation($page);
528 if (istranslation($page) && $template->query(name => "percenttranslated")) {
529 $template->param(percenttranslated => percenttranslated($page));
531 if ($template->query(name => "istranslation")) {
532 $template->param(istranslation => istranslation($page));
534 if ($template->query(name => "istranslatable")) {
535 $template->param(istranslatable => istranslatable($page));
537 if ($template->query(name => "otherlanguages")) {
538 $template->param(otherlanguages => [otherlanguagesloop($page)]);
539 map add_depends($page, $_), (values %{otherlanguages($page)});
541 # Rely on IkiWiki::Render's genpage() to decide wether
542 # a discussion link should appear on $page; this is not
543 # totally accurate, though: some broken links may be generated
544 # when cgiurl is disabled.
545 # This compromise avoids some code duplication, and will probably
546 # prevent future breakage when ikiwiki internals change.
547 # Known limitations are preferred to future random bugs.
548 if ($template->param('discussionlink') && istranslation($page)) {
549 $template->param('discussionlink' => htmllink(
552 $masterpage . '/' . gettext("Discussion"),
555 linktext => gettext("Discussion"),
558 # Remove broken parentlink to ./index.html on home page's translations.
559 # It works because this hook has the "last" parameter set, to ensure it
560 # runs after parentlinks' own pagetemplate hook.
561 if ($template->param('parentlinks')
562 && istranslation($page)
563 && $masterpage eq "index") {
564 $template->param('parentlinks' => []);
571 my $updated_po_files=0;
573 # Refresh/create POT and PO files as needed.
574 foreach my $page (map pagename($_), @rendered) {
575 next unless istranslatable($page);
576 my $file=srcfile($pagesources{$page});
577 my $updated_pot_file=0;
578 # Only refresh Pot file if it does not exist, or if
579 # $pagesources{$page} was changed: don't if only the HTML was
580 # refreshed, e.g. because of a dependency.
581 if ((grep { $_ eq $pagesources{$page} } @origneedsbuild)
582 || ! -e potfile($file)) {
588 push @pofiles, $_ if ($updated_pot_file || ! -e $_);
591 refreshpofiles($file, @pofiles);
592 map { IkiWiki::rcs_add($_); } @pofiles if ($config{rcs});
597 if ($updated_po_files) {
598 # Check staged changes in.
600 IkiWiki::disable_commit_hook();
601 IkiWiki::rcs_commit_staged(gettext("updated PO files"),
602 "IkiWiki::Plugin::po::change", "127.0.0.1");
603 IkiWiki::enable_commit_hook();
604 IkiWiki::rcs_update();
606 # Reinitialize module's private variables.
607 resetalreadyfiltered();
608 resettranslationscache();
609 # Trigger a wiki refresh.
610 require IkiWiki::Render;
612 IkiWiki::saveindex();
616 sub editcontent () { #{{{
618 # as we're previewing or saving a page, the content may have
619 # changed, so tell the next filter() invocation it must not be lazy
620 unsetalreadyfiltered($params{page}, $params{page});
621 return $params{content};
624 sub istranslatable ($) { #{{{
627 my $file=$pagesources{$page};
630 || (defined pagetype($file) && pagetype($file) eq 'po')
631 || $file =~ /\.pot$/) {
634 return pagespec_match($page, $config{po_translatable_pages});
637 sub _istranslation ($) { #{{{
640 my $file=$pagesources{$page};
641 if (! defined $file) {
642 return IkiWiki::FailReason->new("no file specified");
646 || ! defined pagetype($file)
647 || ! pagetype($file) eq 'po'
648 || $file =~ /\.pot$/) {
652 my ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
653 if (! defined $masterpage || ! defined $lang
654 || ! (length($masterpage) > 0) || ! (length($lang) > 0)
655 || ! defined $pagesources{$masterpage}
656 || ! defined $config{po_slave_languages}{$lang}) {
660 return istranslatable($masterpage);
663 sub istranslation ($) { #{{{
666 if (_istranslation($page)) {
667 my ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
668 $translations{$masterpage}{$lang}=$page unless exists $translations{$masterpage}{$lang};
674 package IkiWiki::PageSpec;
679 sub match_istranslation ($;@) { #{{{
682 if (IkiWiki::Plugin::po::istranslation($page)) {
683 return IkiWiki::SuccessReason->new("is a translation page");
686 return IkiWiki::FailReason->new("is not a translation page");
690 sub match_istranslatable ($;@) { #{{{
693 if (IkiWiki::Plugin::po::istranslatable($page)) {
694 return IkiWiki::SuccessReason->new("is set as translatable in po_translatable_pages");
697 return IkiWiki::FailReason->new("is not set as translatable in po_translatable_pages");
701 sub match_lang ($$;@) { #{{{
705 my $regexp=IkiWiki::glob2re($wanted);
709 if (IkiWiki::Plugin::po::istranslation($page)) {
710 ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
713 $lang = $config{po_master_language}{code};
716 if ($lang!~/^$regexp$/i) {
717 return IkiWiki::FailReason->new("file language is $lang, not $wanted");
720 return IkiWiki::SuccessReason->new("file language is $wanted");
724 sub match_currentlang ($$;@) { #{{{
729 my ($currentmasterpage, $currentlang, $masterpage, $lang);
731 return IkiWiki::FailReason->new("no location provided") unless exists $params{location};
733 if (IkiWiki::Plugin::po::istranslation($params{location})) {
734 ($currentmasterpage, $currentlang) = ($params{location} =~ /(.*)[.]([a-z]{2})$/);
737 $currentlang = $config{po_master_language}{code};
740 if (IkiWiki::Plugin::po::istranslation($page)) {
741 ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
744 $lang = $config{po_master_language}{code};
747 if ($lang eq $currentlang) {
748 return IkiWiki::SuccessReason->new("file language is the same as current one, i.e. $currentlang");
751 return IkiWiki::FailReason->new("file language is $lang, whereas current language is $currentlang");