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->read($masterfile);
170 $doc->{TT}{utf_mode} = 1;
171 $doc->{TT}{file_in_charset} = 'utf-8';
172 $doc->{TT}{file_out_charset} = 'utf-8';
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 needsbuild () { #{{{
206 my $needsbuild=shift;
208 # backup @needsbuild content so that change() can know whether
209 # a given master page was rendered because its source file was changed
210 @origneedsbuild=(@$needsbuild);
212 # build %translations, using istranslation's side-effect
213 map istranslation($_), (keys %pagesources);
215 # make existing translations depend on the corresponding master page
216 foreach my $master (keys %translations) {
217 foreach my $slave (values %{$translations{$master}}) {
218 add_depends($slave, $master);
225 my $page=$params{page};
226 my $content=$params{content};
228 return unless UNIVERSAL::can("IkiWiki::Plugin::link", "import");
229 return unless $config{'po_link_to'} eq 'negotiated';
231 if (istranslation($page)) {
232 my ($masterpage, $curlang) = ($page =~ /(.*)[.]([a-z]{2})$/);
233 foreach my $destpage (@{$links{$page}}) {
234 if (istranslatable($destpage)) {
235 # replace one occurence of $destpage in $links{$page}
236 # (we only want to replace the one that was added by
237 # IkiWiki::Plugin::link::scan, other occurences may be
238 # there for other reasons)
239 for (my $i=0; $i<@{$links{$page}}; $i++) {
240 if (@{$links{$page}}[$i] eq $destpage) {
241 @{$links{$page}}[$i] = $destpage . '.' . $curlang;
248 elsif (! istranslatable($page) && ! istranslation($page)) {
249 foreach my $destpage (@{$links{$page}}) {
250 if (istranslatable($destpage)) {
252 push @{$links{$page}}, $destpage . '.' . $_;
253 } (keys %{$config{po_slave_languages}});
259 sub mytargetpage ($$) { #{{{
263 if (istranslation($page)) {
264 my ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
265 if (! $config{usedirs} || $masterpage eq 'index') {
266 return $masterpage . "." . $lang . "." . $ext;
269 return $masterpage . "/index." . $lang . "." . $ext;
272 elsif (istranslatable($page)) {
273 if (! $config{usedirs} || $page eq 'index') {
274 return $page . "." . $config{po_master_language}{code} . "." . $ext;
277 return $page . "/index." . $config{po_master_language}{code} . "." . $ext;
280 return $origsubs{'targetpage'}->($page, $ext);
283 sub mybeautify_urlpath ($) { #{{{
286 my $res=$origsubs{'beautify_urlpath'}->($url);
287 if ($config{po_link_to} eq "negotiated") {
288 $res =~ s!/\Qindex.$config{po_master_language}{code}.$config{htmlext}\E$!/!;
293 sub urlto_with_orig_beautiful_urlpath($$) { #{{{
297 inject(name => "IkiWiki::beautify_urlpath", call => $origsubs{'beautify_urlpath'});
298 my $res=urlto($to, $from);
299 inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath);
304 sub myurlto ($$;$) { #{{{
309 # workaround hard-coded /index.$config{htmlext} in IkiWiki::urlto()
311 && $config{po_link_to} eq "current"
312 && istranslation($from)
313 && istranslatable('index')) {
314 my ($masterpage, $curlang) = ($from =~ /(.*)[.]([a-z]{2})$/);
315 return IkiWiki::beautify_urlpath(IkiWiki::baseurl($from) . "index." . $curlang . ".$config{htmlext}");
317 return $origsubs{'urlto'}->($to,$from,$absolute);
320 sub mybestlink ($$) { #{{{
324 my $res=$origsubs{'bestlink'}->($page, $link);
326 if ($config{po_link_to} eq "current"
327 && istranslatable($res)
328 && istranslation($page)) {
329 my ($masterpage, $curlang) = ($page =~ /(.*)[.]([a-z]{2})$/);
330 return $res . "." . $curlang;
339 # We use filter to convert PO to the master page's format,
340 # since the rest of ikiwiki should not work on PO files.
341 sub filter (@) { #{{{
344 my $page = $params{page};
345 my $destpage = $params{destpage};
346 my $content = decode_utf8(encode_utf8($params{content}));
348 return $content if ( ! istranslation($page)
349 || ( exists $filtered{$page}{$destpage}
350 && $filtered{$page}{$destpage} eq 1 ));
352 # CRLF line terminators make poor Locale::Po4a feel bad
353 $content=~s/\r\n/\n/g;
355 # Implementation notes
357 # 1. Locale::Po4a reads/writes from/to files, and I'm too lazy
358 # to learn how to disguise a variable as a file.
359 # 2. There are incompatibilities between some File::Temp versions
360 # (including 0.18, bundled with Lenny's perl-modules package)
361 # and others (e.g. 0.20, previously present in the archive as
362 # a standalone package): under certain circumstances, some
363 # return a relative filename, whereas others return an absolute one;
364 # we here use this module in a way that is at least compatible
365 # with 0.18 and 0.20. Beware, hit'n'run refactorers!
366 my $infile = new File::Temp(TEMPLATE => "ikiwiki-po-filter-in.XXXXXXXXXX",
367 DIR => File::Spec->tmpdir,
368 UNLINK => 1)->filename;
369 my $outfile = new File::Temp(TEMPLATE => "ikiwiki-po-filter-out.XXXXXXXXXX",
370 DIR => File::Spec->tmpdir,
371 UNLINK => 1)->filename;
373 writefile(basename($infile), File::Spec->tmpdir, $content);
375 my ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
376 my $masterfile = srcfile($pagesources{$masterpage});
379 push @masters,$masterfile;
381 "markdown" => (pagetype($masterfile) eq 'mdwn') ? 1 : 0,
383 my $doc=Locale::Po4a::Chooser::new('text',%options);
385 'po_in_name' => \@pos,
386 'file_in_name' => \@masters,
387 'file_in_charset' => 'utf-8',
388 'file_out_charset' => 'utf-8',
389 ) or error("[po/filter:$infile]: failed to translate");
390 $doc->write($outfile) or error("[po/filter:$infile] could not write $outfile");
391 $content = readfile($outfile) or error("[po/filter:$infile] could not read $outfile");
393 # Unlinking should happen automatically, thanks to File::Temp,
394 # but it does not work here, probably because of the way writefile()
395 # and Locale::Po4a::write() work.
396 unlink $infile, $outfile;
398 $filtered{$page}{$destpage}=1;
402 sub htmlize (@) { #{{{
405 my $page = $params{page};
406 my $content = $params{content};
407 my ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
408 my $masterfile = srcfile($pagesources{$masterpage});
410 # force content to be htmlize'd as if it was the same type as the master page
411 return IkiWiki::htmlize($page, $page, pagetype($masterfile), $content);
414 sub percenttranslated ($) { #{{{
417 return gettext("N/A") unless (istranslation($page));
418 my ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
419 my $file=srcfile($pagesources{$page});
420 my $masterfile = srcfile($pagesources{$masterpage});
423 push @masters,$masterfile;
425 "markdown" => (pagetype($masterfile) eq 'mdwn') ? 1 : 0,
427 my $doc=Locale::Po4a::Chooser::new('text',%options);
429 'po_in_name' => \@pos,
430 'file_in_name' => \@masters,
431 'file_in_charset' => 'utf-8',
432 'file_out_charset' => 'utf-8',
433 ) or error("[po/percenttranslated:$file]: failed to translate");
434 my ($percent,$hit,$queries) = $doc->stats();
438 sub otherlanguages ($) { #{{{
442 if (istranslatable($page)) {
443 foreach my $lang (sort keys %{$translations{$page}}) {
444 my $translation = $translations{$page}{$lang};
446 url => urlto($translation, $page),
448 language => $config{po_slave_languages}{$lang},
449 percent => percenttranslated($translation),
453 elsif (istranslation($page)) {
454 my ($masterpage, $curlang) = ($page =~ /(.*)[.]([a-z]{2})$/);
456 url => urlto_with_orig_beautiful_urlpath($masterpage, $page),
457 code => $config{po_master_language}{code},
458 language => $config{po_master_language}{name},
461 foreach my $lang (sort keys %{$translations{$masterpage}}) {
463 url => urlto($translations{$masterpage}{$lang}, $page),
465 language => $config{po_slave_languages}{$lang},
466 percent => percenttranslated($translations{$masterpage}{$lang}),
467 } unless ($lang eq $curlang);
473 sub pagetemplate (@) { #{{{
475 my $page=$params{page};
476 my $destpage=$params{destpage};
477 my $template=$params{template};
479 my ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/) if istranslation($page);
481 if (istranslation($page) && $template->query(name => "percenttranslated")) {
482 $template->param(percenttranslated => percenttranslated($page));
484 if ($template->query(name => "istranslation")) {
485 $template->param(istranslation => istranslation($page));
487 if ($template->query(name => "istranslatable")) {
488 $template->param(istranslatable => istranslatable($page));
490 if ($template->query(name => "otherlanguages")) {
491 $template->param(otherlanguages => [otherlanguages($page)]);
492 if (istranslatable($page)) {
493 foreach my $translation (values %{$translations{$page}}) {
494 add_depends($page, $translation);
497 elsif (istranslation($page)) {
498 add_depends($page, $masterpage);
499 foreach my $translation (values %{$translations{$masterpage}}) {
500 add_depends($page, $translation);
504 # Rely on IkiWiki::Render's genpage() to decide wether
505 # a discussion link should appear on $page; this is not
506 # totally accurate, though: some broken links may be generated
507 # when cgiurl is disabled.
508 # This compromise avoids some code duplication, and will probably
509 # prevent future breakage when ikiwiki internals change.
510 # Known limitations are preferred to future random bugs.
511 if ($template->param('discussionlink') && istranslation($page)) {
512 $template->param('discussionlink' => htmllink(
515 $masterpage . '/' . gettext("Discussion"),
518 linktext => gettext("Discussion"),
521 # remove broken parentlink to ./index.html on home page's translations
522 if ($template->param('parentlinks')
523 && istranslation($page)
524 && $masterpage eq "index") {
525 $template->param('parentlinks' => []);
532 my $updated_po_files=0;
534 # Refresh/create POT and PO files as needed.
535 foreach my $page (map pagename($_), @rendered) {
536 next unless istranslatable($page);
537 my $file=srcfile($pagesources{$page});
538 my $updated_pot_file=0;
539 if ((grep { $_ eq $pagesources{$page} } @origneedsbuild)
540 || ! -e potfile($file)) {
545 foreach my $lang (keys %{$config{po_slave_languages}}) {
546 my $pofile=pofile($file, $lang);
547 if ($updated_pot_file || ! -e $pofile) {
548 push @pofiles, $pofile;
552 refreshpofiles($file, @pofiles);
553 map { IkiWiki::rcs_add($_); } @pofiles if ($config{rcs});
558 if ($updated_po_files) {
559 # Check staged changes in.
561 IkiWiki::disable_commit_hook();
562 IkiWiki::rcs_commit_staged(gettext("updated PO files"),
563 "IkiWiki::Plugin::po::change", "127.0.0.1");
564 IkiWiki::enable_commit_hook();
565 IkiWiki::rcs_update();
567 # Reinitialize module's private variables.
570 # Trigger a wiki refresh.
571 require IkiWiki::Render;
573 IkiWiki::saveindex();
577 sub editcontent () { #{{{
579 # as we're previewing or saving a page, the content may have
580 # changed, so tell the next filter() invocation it must not be lazy
581 if (exists $filtered{$params{page}}{$params{page}}) {
582 delete $filtered{$params{page}}{$params{page}};
584 return $params{content};
587 sub istranslatable ($) { #{{{
590 my $file=$pagesources{$page};
593 || (defined pagetype($file) && pagetype($file) eq 'po')
594 || $file =~ /\.pot$/) {
597 return pagespec_match($page, $config{po_translatable_pages});
600 sub _istranslation ($) { #{{{
603 my $file=$pagesources{$page};
604 if (! defined $file) {
605 return IkiWiki::FailReason->new("no file specified");
609 || ! defined pagetype($file)
610 || ! pagetype($file) eq 'po'
611 || $file =~ /\.pot$/) {
615 my ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
616 if (! defined $masterpage || ! defined $lang
617 || ! (length($masterpage) > 0) || ! (length($lang) > 0)
618 || ! defined $pagesources{$masterpage}
619 || ! defined $config{po_slave_languages}{$lang}) {
623 return istranslatable($masterpage);
626 sub istranslation ($) { #{{{
629 if (_istranslation($page)) {
630 my ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
631 $translations{$masterpage}{$lang}=$page unless exists $translations{$masterpage}{$lang};
637 package IkiWiki::PageSpec;
642 sub match_istranslation ($;@) { #{{{
645 if (IkiWiki::Plugin::po::istranslation($page)) {
646 return IkiWiki::SuccessReason->new("is a translation page");
649 return IkiWiki::FailReason->new("is not a translation page");
653 sub match_istranslatable ($;@) { #{{{
656 if (IkiWiki::Plugin::po::istranslatable($page)) {
657 return IkiWiki::SuccessReason->new("is set as translatable in po_translatable_pages");
660 return IkiWiki::FailReason->new("is not set as translatable in po_translatable_pages");
664 sub match_lang ($$;@) { #{{{
668 my $regexp=IkiWiki::glob2re($wanted);
672 if (IkiWiki::Plugin::po::istranslation($page)) {
673 ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
676 $lang = $config{po_master_language}{code};
679 if ($lang!~/^$regexp$/i) {
680 return IkiWiki::FailReason->new("file language is $lang, not $wanted");
683 return IkiWiki::SuccessReason->new("file language is $wanted");
687 sub match_currentlang ($$;@) { #{{{
692 my ($currentmasterpage, $currentlang, $masterpage, $lang);
694 return IkiWiki::FailReason->new("no location provided") unless exists $params{location};
696 if (IkiWiki::Plugin::po::istranslation($params{location})) {
697 ($currentmasterpage, $currentlang) = ($params{location} =~ /(.*)[.]([a-z]{2})$/);
700 $currentlang = $config{po_master_language}{code};
703 if (IkiWiki::Plugin::po::istranslation($page)) {
704 ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
707 $lang = $config{po_master_language}{code};
710 if ($lang eq $currentlang) {
711 return IkiWiki::SuccessReason->new("file language is the same as current one, i.e. $currentlang");
714 return IkiWiki::FailReason->new("file language is $lang, whereas current language is $currentlang");