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 potfile ($) { #{{{
142 my $masterfile=shift;
144 (my $name, my $dir, my $suffix) = fileparse($masterfile, qr/\.[^.]*/);
145 $dir='' if $dir eq './';
146 return File::Spec->catpath('', $dir, $name . ".pot");
149 sub pofile ($$) { #{{{
150 my $masterfile=shift;
153 (my $name, my $dir, my $suffix) = fileparse($masterfile, qr/\.[^.]*/);
154 $dir='' if $dir eq './';
155 return File::Spec->catpath('', $dir, $name . "." . $lang . ".po");
158 sub pofiles ($) { #{{{
159 my $masterfile=shift;
160 return map pofile($masterfile, $_), (keys %{$config{po_slave_languages}});
163 sub refreshpot ($) { #{{{
164 my $masterfile=shift;
166 my $potfile=potfile($masterfile);
167 my %options = ("markdown" => (pagetype($masterfile) eq 'mdwn') ? 1 : 0);
168 my $doc=Locale::Po4a::Chooser::new('text',%options);
169 $doc->{TT}{utf_mode} = 1;
170 $doc->{TT}{file_in_charset} = 'utf-8';
171 $doc->{TT}{file_out_charset} = 'utf-8';
172 $doc->read($masterfile);
173 # let's cheat a bit to force porefs option to be passed to Locale::Po4a::Po;
174 # this is undocument use of internal Locale::Po4a::TransTractor's data,
175 # compulsory since this module prevents us from using the porefs option.
176 my %po_options = ('porefs' => 'none');
177 $doc->{TT}{po_out}=Locale::Po4a::Po->new(\%po_options);
178 $doc->{TT}{po_out}->set_charset('utf-8');
181 IkiWiki::prep_writefile(basename($potfile),dirname($potfile));
182 $doc->writepo($potfile);
185 sub refreshpofiles ($@) { #{{{
186 my $masterfile=shift;
189 my $potfile=potfile($masterfile);
190 error("[po/refreshpofiles] POT file ($potfile) does not exist") unless (-e $potfile);
192 foreach my $pofile (@pofiles) {
193 IkiWiki::prep_writefile(basename($pofile),dirname($pofile));
195 system("msgmerge", "-U", "--backup=none", $pofile, $potfile) == 0
196 or error("[po/refreshpofiles:$pofile] failed to update");
199 File::Copy::syscopy($potfile,$pofile)
200 or error("[po/refreshpofiles:$pofile] failed to copy the POT file");
205 sub buildtranslationscache() { #{{{
206 # use istranslation's side-effect
207 map istranslation($_), (keys %pagesources);
210 sub resettranslationscache() { #{{{
214 sub needsbuild () { #{{{
215 my $needsbuild=shift;
217 # backup @needsbuild content so that change() can know whether
218 # a given master page was rendered because its source file was changed
219 @origneedsbuild=(@$needsbuild);
221 buildtranslationscache();
223 # make existing translations depend on the corresponding master page
224 foreach my $master (keys %translations) {
225 foreach my $slave (values %{$translations{$master}}) {
226 add_depends($slave, $master);
233 my $page=$params{page};
234 my $content=$params{content};
236 return unless UNIVERSAL::can("IkiWiki::Plugin::link", "import");
238 if (istranslation($page)) {
239 my ($masterpage, $curlang) = ($page =~ /(.*)[.]([a-z]{2})$/);
240 foreach my $destpage (@{$links{$page}}) {
241 if (istranslatable($destpage)) {
242 # replace one occurence of $destpage in $links{$page}
243 # (we only want to replace the one that was added by
244 # IkiWiki::Plugin::link::scan, other occurences may be
245 # there for other reasons)
246 for (my $i=0; $i<@{$links{$page}}; $i++) {
247 if (@{$links{$page}}[$i] eq $destpage) {
248 @{$links{$page}}[$i] = $destpage . '.' . $curlang;
255 elsif (! istranslatable($page) && ! istranslation($page)) {
256 foreach my $destpage (@{$links{$page}}) {
257 if (istranslatable($destpage)) {
259 push @{$links{$page}}, $destpage . '.' . $_;
260 } (keys %{$config{po_slave_languages}});
266 sub mytargetpage ($$) { #{{{
270 if (istranslation($page)) {
271 my ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
272 if (! $config{usedirs} || $masterpage eq 'index') {
273 return $masterpage . "." . $lang . "." . $ext;
276 return $masterpage . "/index." . $lang . "." . $ext;
279 elsif (istranslatable($page)) {
280 if (! $config{usedirs} || $page eq 'index') {
281 return $page . "." . $config{po_master_language}{code} . "." . $ext;
284 return $page . "/index." . $config{po_master_language}{code} . "." . $ext;
287 return $origsubs{'targetpage'}->($page, $ext);
290 sub mybeautify_urlpath ($) { #{{{
293 my $res=$origsubs{'beautify_urlpath'}->($url);
294 if ($config{po_link_to} eq "negotiated") {
295 $res =~ s!/\Qindex.$config{po_master_language}{code}.$config{htmlext}\E$!/!;
300 sub urlto_with_orig_beautiful_urlpath($$) { #{{{
304 inject(name => "IkiWiki::beautify_urlpath", call => $origsubs{'beautify_urlpath'});
305 my $res=urlto($to, $from);
306 inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath);
311 sub myurlto ($$;$) { #{{{
316 # workaround hard-coded /index.$config{htmlext} in IkiWiki::urlto()
318 && $config{po_link_to} eq "current"
319 && istranslation($from)
320 && istranslatable('index')) {
321 my ($masterpage, $curlang) = ($from =~ /(.*)[.]([a-z]{2})$/);
322 return IkiWiki::beautify_urlpath(IkiWiki::baseurl($from) . "index." . $curlang . ".$config{htmlext}");
324 return $origsubs{'urlto'}->($to,$from,$absolute);
327 sub mybestlink ($$) { #{{{
331 my $res=$origsubs{'bestlink'}->($page, $link);
333 if ($config{po_link_to} eq "current"
334 && istranslatable($res)
335 && istranslation($page)) {
336 my ($masterpage, $curlang) = ($page =~ /(.*)[.]([a-z]{2})$/);
337 return $res . "." . $curlang;
346 sub alreadyfiltered($$) { #{{{
350 return ( exists $filtered{$page}{$destpage}
351 && $filtered{$page}{$destpage} eq 1 );
353 sub setalreadyfiltered($$) { #{{{
357 $filtered{$page}{$destpage}=1;
359 sub unsetalreadyfiltered($$) { #{{{
363 if (exists $filtered{$page}{$destpage}) {
364 delete $filtered{$page}{$destpage};
367 sub resetalreadyfiltered() { #{{{
371 # We use filter to convert PO to the master page's format,
372 # since the rest of ikiwiki should not work on PO files.
373 sub filter (@) { #{{{
376 my $page = $params{page};
377 my $destpage = $params{destpage};
378 my $content = decode_utf8(encode_utf8($params{content}));
380 return $content if ( ! istranslation($page)
381 || alreadyfiltered($page, $destpage) );
383 # CRLF line terminators make poor Locale::Po4a feel bad
384 $content=~s/\r\n/\n/g;
386 # Implementation notes
388 # 1. Locale::Po4a reads/writes from/to files, and I'm too lazy
389 # to learn how to disguise a variable as a file.
390 # 2. There are incompatibilities between some File::Temp versions
391 # (including 0.18, bundled with Lenny's perl-modules package)
392 # and others (e.g. 0.20, previously present in the archive as
393 # a standalone package): under certain circumstances, some
394 # return a relative filename, whereas others return an absolute one;
395 # we here use this module in a way that is at least compatible
396 # with 0.18 and 0.20. Beware, hit'n'run refactorers!
397 my $infile = new File::Temp(TEMPLATE => "ikiwiki-po-filter-in.XXXXXXXXXX",
398 DIR => File::Spec->tmpdir,
399 UNLINK => 1)->filename;
400 my $outfile = new File::Temp(TEMPLATE => "ikiwiki-po-filter-out.XXXXXXXXXX",
401 DIR => File::Spec->tmpdir,
402 UNLINK => 1)->filename;
404 writefile(basename($infile), File::Spec->tmpdir, $content);
406 my ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
407 my $masterfile = srcfile($pagesources{$masterpage});
410 push @masters,$masterfile;
412 "markdown" => (pagetype($masterfile) eq 'mdwn') ? 1 : 0,
414 my $doc=Locale::Po4a::Chooser::new('text',%options);
416 'po_in_name' => \@pos,
417 'file_in_name' => \@masters,
418 'file_in_charset' => 'utf-8',
419 'file_out_charset' => 'utf-8',
420 ) or error("[po/filter:$page]: failed to translate");
421 $doc->write($outfile) or error("[po/filter:$page] could not write $outfile");
422 $content = readfile($outfile) or error("[po/filter:$page] could not read $outfile");
424 # Unlinking should happen automatically, thanks to File::Temp,
425 # but it does not work here, probably because of the way writefile()
426 # and Locale::Po4a::write() work.
427 unlink $infile, $outfile;
429 setalreadyfiltered($page, $destpage);
433 sub htmlize (@) { #{{{
436 my $page = $params{page};
437 my $content = $params{content};
438 my ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
439 my $masterfile = srcfile($pagesources{$masterpage});
441 # force content to be htmlize'd as if it was the same type as the master page
442 return IkiWiki::htmlize($page, $page, pagetype($masterfile), $content);
445 sub percenttranslated ($) { #{{{
448 return gettext("N/A") unless (istranslation($page));
449 my ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
450 my $file=srcfile($pagesources{$page});
451 my $masterfile = srcfile($pagesources{$masterpage});
454 push @masters,$masterfile;
456 "markdown" => (pagetype($masterfile) eq 'mdwn') ? 1 : 0,
458 my $doc=Locale::Po4a::Chooser::new('text',%options);
460 'po_in_name' => \@pos,
461 'file_in_name' => \@masters,
462 'file_in_charset' => 'utf-8',
463 'file_out_charset' => 'utf-8',
464 ) or error("[po/percenttranslated:$page]: failed to translate");
465 my ($percent,$hit,$queries) = $doc->stats();
469 sub otherlanguages ($) { #{{{
473 if (istranslatable($page)) {
474 foreach my $lang (sort keys %{$translations{$page}}) {
475 my $translation = $translations{$page}{$lang};
477 url => urlto($translation, $page),
479 language => $config{po_slave_languages}{$lang},
480 percent => percenttranslated($translation),
484 elsif (istranslation($page)) {
485 my ($masterpage, $curlang) = ($page =~ /(.*)[.]([a-z]{2})$/);
487 url => urlto_with_orig_beautiful_urlpath($masterpage, $page),
488 code => $config{po_master_language}{code},
489 language => $config{po_master_language}{name},
492 foreach my $lang (sort keys %{$translations{$masterpage}}) {
494 url => urlto($translations{$masterpage}{$lang}, $page),
496 language => $config{po_slave_languages}{$lang},
497 percent => percenttranslated($translations{$masterpage}{$lang}),
498 } unless ($lang eq $curlang);
504 sub pagetemplate (@) { #{{{
506 my $page=$params{page};
507 my $destpage=$params{destpage};
508 my $template=$params{template};
510 my ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/) if istranslation($page);
512 if (istranslation($page) && $template->query(name => "percenttranslated")) {
513 $template->param(percenttranslated => percenttranslated($page));
515 if ($template->query(name => "istranslation")) {
516 $template->param(istranslation => istranslation($page));
518 if ($template->query(name => "istranslatable")) {
519 $template->param(istranslatable => istranslatable($page));
521 if ($template->query(name => "otherlanguages")) {
522 $template->param(otherlanguages => [otherlanguages($page)]);
523 if (istranslatable($page)) {
524 foreach my $translation (values %{$translations{$page}}) {
525 add_depends($page, $translation);
528 elsif (istranslation($page)) {
529 add_depends($page, $masterpage);
530 foreach my $translation (values %{$translations{$masterpage}}) {
531 add_depends($page, $translation) unless $page eq $translation;
535 # Rely on IkiWiki::Render's genpage() to decide wether
536 # a discussion link should appear on $page; this is not
537 # totally accurate, though: some broken links may be generated
538 # when cgiurl is disabled.
539 # This compromise avoids some code duplication, and will probably
540 # prevent future breakage when ikiwiki internals change.
541 # Known limitations are preferred to future random bugs.
542 if ($template->param('discussionlink') && istranslation($page)) {
543 $template->param('discussionlink' => htmllink(
546 $masterpage . '/' . gettext("Discussion"),
549 linktext => gettext("Discussion"),
552 # Remove broken parentlink to ./index.html on home page's translations.
553 # It works because this hook has the "last" parameter set, to ensure it
554 # runs after parentlinks' own pagetemplate hook.
555 if ($template->param('parentlinks')
556 && istranslation($page)
557 && $masterpage eq "index") {
558 $template->param('parentlinks' => []);
565 my $updated_po_files=0;
567 # Refresh/create POT and PO files as needed.
568 foreach my $page (map pagename($_), @rendered) {
569 next unless istranslatable($page);
570 my $file=srcfile($pagesources{$page});
571 my $updated_pot_file=0;
572 # Only refresh Pot file if it does not exist, or if
573 # $pagesources{$page} was changed: don't if only the HTML was
574 # refreshed, e.g. because of a dependency.
575 if ((grep { $_ eq $pagesources{$page} } @origneedsbuild)
576 || ! -e potfile($file)) {
581 foreach my $lang (keys %{$config{po_slave_languages}}) {
582 my $pofile=pofile($file, $lang);
583 if ($updated_pot_file || ! -e $pofile) {
584 push @pofiles, $pofile;
588 refreshpofiles($file, @pofiles);
589 map { IkiWiki::rcs_add($_); } @pofiles if ($config{rcs});
594 if ($updated_po_files) {
595 # Check staged changes in.
597 IkiWiki::disable_commit_hook();
598 IkiWiki::rcs_commit_staged(gettext("updated PO files"),
599 "IkiWiki::Plugin::po::change", "127.0.0.1");
600 IkiWiki::enable_commit_hook();
601 IkiWiki::rcs_update();
603 # Reinitialize module's private variables.
604 resetalreadyfiltered();
605 resettranslationscache();
606 # Trigger a wiki refresh.
607 require IkiWiki::Render;
609 IkiWiki::saveindex();
613 sub editcontent () { #{{{
615 # as we're previewing or saving a page, the content may have
616 # changed, so tell the next filter() invocation it must not be lazy
617 unsetalreadyfiltered($params{page}, $params{page});
618 return $params{content};
621 sub istranslatable ($) { #{{{
624 my $file=$pagesources{$page};
627 || (defined pagetype($file) && pagetype($file) eq 'po')
628 || $file =~ /\.pot$/) {
631 return pagespec_match($page, $config{po_translatable_pages});
634 sub _istranslation ($) { #{{{
637 my $file=$pagesources{$page};
638 if (! defined $file) {
639 return IkiWiki::FailReason->new("no file specified");
643 || ! defined pagetype($file)
644 || ! pagetype($file) eq 'po'
645 || $file =~ /\.pot$/) {
649 my ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
650 if (! defined $masterpage || ! defined $lang
651 || ! (length($masterpage) > 0) || ! (length($lang) > 0)
652 || ! defined $pagesources{$masterpage}
653 || ! defined $config{po_slave_languages}{$lang}) {
657 return istranslatable($masterpage);
660 sub istranslation ($) { #{{{
663 if (_istranslation($page)) {
664 my ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
665 $translations{$masterpage}{$lang}=$page unless exists $translations{$masterpage}{$lang};
671 package IkiWiki::PageSpec;
676 sub match_istranslation ($;@) { #{{{
679 if (IkiWiki::Plugin::po::istranslation($page)) {
680 return IkiWiki::SuccessReason->new("is a translation page");
683 return IkiWiki::FailReason->new("is not a translation page");
687 sub match_istranslatable ($;@) { #{{{
690 if (IkiWiki::Plugin::po::istranslatable($page)) {
691 return IkiWiki::SuccessReason->new("is set as translatable in po_translatable_pages");
694 return IkiWiki::FailReason->new("is not set as translatable in po_translatable_pages");
698 sub match_lang ($$;@) { #{{{
702 my $regexp=IkiWiki::glob2re($wanted);
706 if (IkiWiki::Plugin::po::istranslation($page)) {
707 ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
710 $lang = $config{po_master_language}{code};
713 if ($lang!~/^$regexp$/i) {
714 return IkiWiki::FailReason->new("file language is $lang, not $wanted");
717 return IkiWiki::SuccessReason->new("file language is $wanted");
721 sub match_currentlang ($$;@) { #{{{
726 my ($currentmasterpage, $currentlang, $masterpage, $lang);
728 return IkiWiki::FailReason->new("no location provided") unless exists $params{location};
730 if (IkiWiki::Plugin::po::istranslation($params{location})) {
731 ($currentmasterpage, $currentlang) = ($params{location} =~ /(.*)[.]([a-z]{2})$/);
734 $currentlang = $config{po_master_language}{code};
737 if (IkiWiki::Plugin::po::istranslation($page)) {
738 ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
741 $lang = $config{po_master_language}{code};
744 if ($lang eq $currentlang) {
745 return IkiWiki::SuccessReason->new("file language is the same as current one, i.e. $currentlang");
748 return IkiWiki::FailReason->new("file language is $lang, whereas current language is $currentlang");