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 => "filter", id => "po", call => \&filter);
40 hook(type => "htmlize", id => "po", call => \&htmlize);
41 hook(type => "pagetemplate", id => "po", call => \&pagetemplate, last => 1);
42 hook(type => "change", id => "po", call => \&change);
43 hook(type => "editcontent", id => "po", call => \&editcontent);
45 $origsubs{'bestlink'}=\&IkiWiki::bestlink;
46 inject(name => "IkiWiki::bestlink", call => \&mybestlink);
47 $origsubs{'beautify_urlpath'}=\&IkiWiki::beautify_urlpath;
48 inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath);
49 $origsubs{'targetpage'}=\&IkiWiki::targetpage;
50 inject(name => "IkiWiki::targetpage", call => \&mytargetpage);
51 $origsubs{'urlto'}=\&IkiWiki::urlto;
52 inject(name => "IkiWiki::urlto", call => \&myurlto);
55 sub getsetup () { #{{{
59 rebuild => 1, # format plugin & changes html filenames
61 po_master_language => {
67 description => "master language (non-PO files)",
71 po_slave_languages => {
78 description => "slave languages (PO files)",
82 po_translatable_pages => {
84 example => "!*/Discussion",
85 description => "PageSpec controlling which pages are translatable",
86 link => "ikiwiki/PageSpec",
93 description => "internal linking behavior (default/current/negotiated)",
99 sub islanguagecode ($) { #{{{
101 return ($code =~ /^[a-z]{2}$/);
104 sub checkconfig () { #{{{
105 foreach my $field (qw{po_master_language po_slave_languages}) {
106 if (! exists $config{$field} || ! defined $config{$field}) {
107 error(sprintf(gettext("Must specify %s"), $field));
110 if (! (keys %{$config{po_slave_languages}})) {
111 error(gettext("At least one slave language must be defined in po_slave_languages"));
115 or error(sprintf(gettext("%s is not a valid language code"), $_));
116 } ($config{po_master_language}{code}, keys %{$config{po_slave_languages}});
117 if (! exists $config{po_translatable_pages} ||
118 ! defined $config{po_translatable_pages}) {
119 $config{po_translatable_pages}="";
121 if (! exists $config{po_link_to} ||
122 ! defined $config{po_link_to}) {
123 $config{po_link_to}='default';
126 $config{po_link_to} eq $_
127 } ('default', 'current', 'negotiated')) {
128 warn(sprintf(gettext('po_link_to=%s is not a valid setting, falling back to po_link_to=default'),
129 $config{po_link_to}));
130 $config{po_link_to}='default';
132 elsif ($config{po_link_to} eq "negotiated" && ! $config{usedirs}) {
133 warn(gettext('po_link_to=negotiated requires usedirs to be enabled, falling back to po_link_to=default'));
134 $config{po_link_to}='default';
136 push @{$config{wiki_file_prune_regexps}}, qr/\.pot$/;
139 sub potfile ($) { #{{{
140 my $masterfile=shift;
142 (my $name, my $dir, my $suffix) = fileparse($masterfile, qr/\.[^.]*/);
143 $dir='' if $dir eq './';
144 return File::Spec->catpath('', $dir, $name . ".pot");
147 sub pofile ($$) { #{{{
148 my $masterfile=shift;
151 (my $name, my $dir, my $suffix) = fileparse($masterfile, qr/\.[^.]*/);
152 $dir='' if $dir eq './';
153 return File::Spec->catpath('', $dir, $name . "." . $lang . ".po");
156 sub refreshpot ($) { #{{{
157 my $masterfile=shift;
159 my $potfile=potfile($masterfile);
160 my %options = ("markdown" => (pagetype($masterfile) eq 'mdwn') ? 1 : 0);
161 my $doc=Locale::Po4a::Chooser::new('text',%options);
162 $doc->read($masterfile);
163 $doc->{TT}{utf_mode} = 1;
164 $doc->{TT}{file_in_charset} = 'utf-8';
165 $doc->{TT}{file_out_charset} = 'utf-8';
166 # let's cheat a bit to force porefs option to be passed to Locale::Po4a::Po;
167 # this is undocument use of internal Locale::Po4a::TransTractor's data,
168 # compulsory since this module prevents us from using the porefs option.
169 my %po_options = ('porefs' => 'none');
170 $doc->{TT}{po_out}=Locale::Po4a::Po->new(\%po_options);
171 $doc->{TT}{po_out}->set_charset('utf-8');
174 IkiWiki::prep_writefile(basename($potfile),dirname($potfile));
175 $doc->writepo($potfile);
178 sub refreshpofiles ($@) { #{{{
179 my $masterfile=shift;
182 my $potfile=potfile($masterfile);
183 error("[po/refreshpofiles] POT file ($potfile) does not exist") unless (-e $potfile);
185 foreach my $pofile (@pofiles) {
186 IkiWiki::prep_writefile(basename($pofile),dirname($pofile));
188 system("msgmerge", "-U", "--backup=none", $pofile, $potfile) == 0
189 or error("[po/refreshpofiles:$pofile] failed to update");
192 File::Copy::syscopy($potfile,$pofile)
193 or error("[po/refreshpofiles:$pofile] failed to copy the POT file");
198 sub needsbuild () { #{{{
199 my $needsbuild=shift;
201 # backup @needsbuild content so that change() can know whether
202 # a given master page was rendered because its source file was changed
203 @origneedsbuild=(@$needsbuild);
205 # build %translations, using istranslation's side-effect
206 map istranslation($_), (keys %pagesources);
208 # make existing translations depend on the corresponding master page
209 foreach my $master (keys %translations) {
210 foreach my $slave (values %{$translations{$master}}) {
211 add_depends($slave, $master);
216 sub mytargetpage ($$) { #{{{
220 if (istranslation($page)) {
221 my ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
222 if (! $config{usedirs} || $masterpage eq 'index') {
223 return $masterpage . "." . $lang . "." . $ext;
226 return $masterpage . "/index." . $lang . "." . $ext;
229 elsif (istranslatable($page)) {
230 if (! $config{usedirs} || $page eq 'index') {
231 return $page . "." . $config{po_master_language}{code} . "." . $ext;
234 return $page . "/index." . $config{po_master_language}{code} . "." . $ext;
237 return $origsubs{'targetpage'}->($page, $ext);
240 sub mybeautify_urlpath ($) { #{{{
243 my $res=$origsubs{'beautify_urlpath'}->($url);
244 if ($config{po_link_to} eq "negotiated") {
245 $res =~ s!/\Qindex.$config{po_master_language}{code}.$config{htmlext}\E$!/!;
250 sub urlto_with_orig_beautiful_urlpath($$) { #{{{
254 inject(name => "IkiWiki::beautify_urlpath", call => $origsubs{'beautify_urlpath'});
255 my $res=urlto($to, $from);
256 inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath);
261 sub myurlto ($$;$) { #{{{
267 && $config{po_link_to} eq "current"
268 && istranslation($from)
269 && istranslatable('index')) {
270 my ($masterpage, $curlang) = ($from =~ /(.*)[.]([a-z]{2})$/);
271 return IkiWiki::beautify_urlpath(IkiWiki::baseurl($from) . "index." . $curlang . ".$config{htmlext}");
273 return $origsubs{'urlto'}->($to,$from,$absolute);
276 sub mybestlink ($$) { #{{{
280 my $res=$origsubs{'bestlink'}->($page, $link);
282 if ($config{po_link_to} eq "current"
283 && istranslatable($res)
284 && istranslation($page)) {
285 my ($masterpage, $curlang) = ($page =~ /(.*)[.]([a-z]{2})$/);
286 return $res . "." . $curlang;
295 # We use filter to convert PO to the master page's format,
296 # since the rest of ikiwiki should not work on PO files.
297 sub filter (@) { #{{{
300 my $page = $params{page};
301 my $destpage = $params{destpage};
302 my $content = decode_utf8(encode_utf8($params{content}));
304 return $content if ( ! istranslation($page)
305 || ( exists $filtered{$page}{$destpage}
306 && $filtered{$page}{$destpage} eq 1 ));
308 # CRLF line terminators make poor Locale::Po4a feel bad
309 $content=~s/\r\n/\n/g;
311 # Implementation notes
313 # 1. Locale::Po4a reads/writes from/to files, and I'm too lazy
314 # to learn how to disguise a variable as a file.
315 # 2. There are incompatibilities between some File::Temp versions
316 # (including 0.18, bundled with Lenny's perl-modules package)
317 # and others (e.g. 0.20, previously present in the archive as
318 # a standalone package): under certain circumstances, some
319 # return a relative filename, whereas others return an absolute one;
320 # we here use this module in a way that is at least compatible
321 # with 0.18 and 0.20. Beware, hit'n'run refactorers!
322 my $infile = new File::Temp(TEMPLATE => "ikiwiki-po-filter-in.XXXXXXXXXX",
323 DIR => File::Spec->tmpdir,
324 UNLINK => 1)->filename;
325 my $outfile = new File::Temp(TEMPLATE => "ikiwiki-po-filter-out.XXXXXXXXXX",
326 DIR => File::Spec->tmpdir,
327 UNLINK => 1)->filename;
329 writefile(basename($infile), File::Spec->tmpdir, $content);
331 my ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
332 my $masterfile = srcfile($pagesources{$masterpage});
335 push @masters,$masterfile;
337 "markdown" => (pagetype($masterfile) eq 'mdwn') ? 1 : 0,
339 my $doc=Locale::Po4a::Chooser::new('text',%options);
341 'po_in_name' => \@pos,
342 'file_in_name' => \@masters,
343 'file_in_charset' => 'utf-8',
344 'file_out_charset' => 'utf-8',
345 ) or error("[po/filter:$infile]: failed to translate");
346 $doc->write($outfile) or error("[po/filter:$infile] could not write $outfile");
347 $content = readfile($outfile) or error("[po/filter:$infile] could not read $outfile");
349 # Unlinking should happen automatically, thanks to File::Temp,
350 # but it does not work here, probably because of the way writefile()
351 # and Locale::Po4a::write() work.
352 unlink $infile, $outfile;
354 $filtered{$page}{$destpage}=1;
358 sub htmlize (@) { #{{{
361 my $page = $params{page};
362 my $content = $params{content};
363 my ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
364 my $masterfile = srcfile($pagesources{$masterpage});
366 # force content to be htmlize'd as if it was the same type as the master page
367 return IkiWiki::htmlize($page, $page, pagetype($masterfile), $content);
370 sub percenttranslated ($) { #{{{
373 return gettext("N/A") unless (istranslation($page));
374 my ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
375 my $file=srcfile($pagesources{$page});
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/percenttranslated:$file]: failed to translate");
390 my ($percent,$hit,$queries) = $doc->stats();
394 sub otherlanguages ($) { #{{{
398 if (istranslatable($page)) {
399 foreach my $lang (sort keys %{$translations{$page}}) {
400 my $translation = $translations{$page}{$lang};
402 url => urlto($translation, $page),
404 language => $config{po_slave_languages}{$lang},
405 percent => percenttranslated($translation),
409 elsif (istranslation($page)) {
410 my ($masterpage, $curlang) = ($page =~ /(.*)[.]([a-z]{2})$/);
412 url => urlto_with_orig_beautiful_urlpath($masterpage, $page),
413 code => $config{po_master_language}{code},
414 language => $config{po_master_language}{name},
417 foreach my $lang (sort keys %{$translations{$masterpage}}) {
419 url => urlto($translations{$masterpage}{$lang}, $page),
421 language => $config{po_slave_languages}{$lang},
422 percent => percenttranslated($translations{$masterpage}{$lang}),
423 } unless ($lang eq $curlang);
429 sub pagetemplate (@) { #{{{
431 my $page=$params{page};
432 my $destpage=$params{destpage};
433 my $template=$params{template};
435 my ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/) if istranslation($page);
437 if (istranslation($page) && $template->query(name => "percenttranslated")) {
438 $template->param(percenttranslated => percenttranslated($page));
440 if ($template->query(name => "istranslation")) {
441 $template->param(istranslation => istranslation($page));
443 if ($template->query(name => "istranslatable")) {
444 $template->param(istranslatable => istranslatable($page));
446 if ($template->query(name => "otherlanguages")) {
447 $template->param(otherlanguages => [otherlanguages($page)]);
448 if (istranslatable($page)) {
449 foreach my $translation (values %{$translations{$page}}) {
450 add_depends($page, $translation);
453 elsif (istranslation($page)) {
454 add_depends($page, $masterpage);
455 foreach my $translation (values %{$translations{$masterpage}}) {
456 add_depends($page, $translation);
460 # Rely on IkiWiki::Render's genpage() to decide wether
461 # a discussion link should appear on $page; this is not
462 # totally accurate, though: some broken links may be generated
463 # when cgiurl is disabled.
464 # This compromise avoids some code duplication, and will probably
465 # prevent future breakage when ikiwiki internals change.
466 # Known limitations are preferred to future random bugs.
467 if ($template->param('discussionlink') && istranslation($page)) {
468 $template->param('discussionlink' => htmllink(
471 $masterpage . '/' . gettext("Discussion"),
474 linktext => gettext("Discussion"),
477 # remove broken parentlink to ./index.html on home page's translations
478 if ($template->param('parentlinks')
479 && istranslation($page)
480 && $masterpage eq "index") {
481 $template->param('parentlinks' => []);
488 my $updated_po_files=0;
490 # Refresh/create POT and PO files as needed.
491 foreach my $page (map pagename($_), @rendered) {
492 next unless istranslatable($page);
493 my $file=srcfile($pagesources{$page});
494 my $updated_pot_file=0;
495 if ((grep { $_ eq $pagesources{$page} } @origneedsbuild)
496 || ! -e potfile($file)) {
501 foreach my $lang (keys %{$config{po_slave_languages}}) {
502 my $pofile=pofile($file, $lang);
503 if ($updated_pot_file || ! -e $pofile) {
504 push @pofiles, $pofile;
508 refreshpofiles($file, @pofiles);
509 map { IkiWiki::rcs_add($_); } @pofiles if ($config{rcs});
514 if ($updated_po_files) {
515 # Check staged changes in.
517 IkiWiki::disable_commit_hook();
518 IkiWiki::rcs_commit_staged(gettext("updated PO files"),
519 "IkiWiki::Plugin::po::change", "127.0.0.1");
520 IkiWiki::enable_commit_hook();
521 IkiWiki::rcs_update();
523 # Reinitialize module's private variables.
526 # Trigger a wiki refresh.
527 require IkiWiki::Render;
529 IkiWiki::saveindex();
533 sub editcontent () { #{{{
535 # as we're previewing or saving a page, the content may have
536 # changed, so tell the next filter() invocation it must not be lazy
537 if (exists $filtered{$params{page}}{$params{page}}) {
538 delete $filtered{$params{page}}{$params{page}};
540 return $params{content};
543 sub istranslatable ($) { #{{{
546 my $file=$pagesources{$page};
549 || (defined pagetype($file) && pagetype($file) eq 'po')
550 || $file =~ /\.pot$/) {
553 return pagespec_match($page, $config{po_translatable_pages});
556 sub _istranslation ($) { #{{{
559 my $file=$pagesources{$page};
560 if (! defined $file) {
561 return IkiWiki::FailReason->new("no file specified");
565 || ! defined pagetype($file)
566 || ! pagetype($file) eq 'po'
567 || $file =~ /\.pot$/) {
571 my ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
572 if (! defined $masterpage || ! defined $lang
573 || ! (length($masterpage) > 0) || ! (length($lang) > 0)
574 || ! defined $pagesources{$masterpage}
575 || ! defined $config{po_slave_languages}{$lang}) {
579 return istranslatable($masterpage);
582 sub istranslation ($) { #{{{
585 if (_istranslation($page)) {
586 my ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
587 $translations{$masterpage}{$lang}=$page unless exists $translations{$masterpage}{$lang};
593 package IkiWiki::PageSpec;
598 sub match_istranslation ($;@) { #{{{
601 if (IkiWiki::Plugin::po::istranslation($page)) {
602 return IkiWiki::SuccessReason->new("is a translation page");
605 return IkiWiki::FailReason->new("is not a translation page");
609 sub match_istranslatable ($;@) { #{{{
612 if (IkiWiki::Plugin::po::istranslatable($page)) {
613 return IkiWiki::SuccessReason->new("is set as translatable in po_translatable_pages");
616 return IkiWiki::FailReason->new("is not set as translatable in po_translatable_pages");
620 sub match_lang ($$;@) { #{{{
624 my $regexp=IkiWiki::glob2re($wanted);
628 if (IkiWiki::Plugin::po::istranslation($page)) {
629 ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
632 $lang = $config{po_master_language}{code};
635 if ($lang!~/^$regexp$/i) {
636 return IkiWiki::FailReason->new("file language is $lang, not $wanted");
639 return IkiWiki::SuccessReason->new("file language is $wanted");
643 sub match_currentlang ($$;@) { #{{{
648 my ($currentmasterpage, $currentlang, $masterpage, $lang);
650 return IkiWiki::FailReason->new("no location provided") unless exists $params{location};
652 if (IkiWiki::Plugin::po::istranslation($params{location})) {
653 ($currentmasterpage, $currentlang) = ($params{location} =~ /(.*)[.]([a-z]{2})$/);
656 $currentlang = $config{po_master_language}{code};
659 if (IkiWiki::Plugin::po::istranslation($page)) {
660 ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
663 $lang = $config{po_master_language}{code};
666 if ($lang eq $currentlang) {
667 return IkiWiki::SuccessReason->new("file language is the same as current one, i.e. $currentlang");
670 return IkiWiki::FailReason->new("file language is $lang, whereas current language is $currentlang");