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");
230 if (istranslation($page)) {
231 my ($masterpage, $curlang) = ($page =~ /(.*)[.]([a-z]{2})$/);
232 foreach my $destpage (@{$links{$page}}) {
233 if (istranslatable($destpage)) {
234 # replace one occurence of $destpage in $links{$page}
235 # (we only want to replace the one that was added by
236 # IkiWiki::Plugin::link::scan, other occurences may be
237 # there for other reasons)
238 for (my $i=0; $i<@{$links{$page}}; $i++) {
239 if (@{$links{$page}}[$i] eq $destpage) {
240 @{$links{$page}}[$i] = $destpage . '.' . $curlang;
247 elsif (! istranslatable($page) && ! istranslation($page)) {
248 foreach my $destpage (@{$links{$page}}) {
249 if (istranslatable($destpage)) {
251 push @{$links{$page}}, $destpage . '.' . $_;
252 } (keys %{$config{po_slave_languages}});
258 sub mytargetpage ($$) { #{{{
262 if (istranslation($page)) {
263 my ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
264 if (! $config{usedirs} || $masterpage eq 'index') {
265 return $masterpage . "." . $lang . "." . $ext;
268 return $masterpage . "/index." . $lang . "." . $ext;
271 elsif (istranslatable($page)) {
272 if (! $config{usedirs} || $page eq 'index') {
273 return $page . "." . $config{po_master_language}{code} . "." . $ext;
276 return $page . "/index." . $config{po_master_language}{code} . "." . $ext;
279 return $origsubs{'targetpage'}->($page, $ext);
282 sub mybeautify_urlpath ($) { #{{{
285 my $res=$origsubs{'beautify_urlpath'}->($url);
286 if ($config{po_link_to} eq "negotiated") {
287 $res =~ s!/\Qindex.$config{po_master_language}{code}.$config{htmlext}\E$!/!;
292 sub urlto_with_orig_beautiful_urlpath($$) { #{{{
296 inject(name => "IkiWiki::beautify_urlpath", call => $origsubs{'beautify_urlpath'});
297 my $res=urlto($to, $from);
298 inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath);
303 sub myurlto ($$;$) { #{{{
308 # workaround hard-coded /index.$config{htmlext} in IkiWiki::urlto()
310 && $config{po_link_to} eq "current"
311 && istranslation($from)
312 && istranslatable('index')) {
313 my ($masterpage, $curlang) = ($from =~ /(.*)[.]([a-z]{2})$/);
314 return IkiWiki::beautify_urlpath(IkiWiki::baseurl($from) . "index." . $curlang . ".$config{htmlext}");
316 return $origsubs{'urlto'}->($to,$from,$absolute);
319 sub mybestlink ($$) { #{{{
323 my $res=$origsubs{'bestlink'}->($page, $link);
325 if ($config{po_link_to} eq "current"
326 && istranslatable($res)
327 && istranslation($page)) {
328 my ($masterpage, $curlang) = ($page =~ /(.*)[.]([a-z]{2})$/);
329 return $res . "." . $curlang;
338 # We use filter to convert PO to the master page's format,
339 # since the rest of ikiwiki should not work on PO files.
340 sub filter (@) { #{{{
343 my $page = $params{page};
344 my $destpage = $params{destpage};
345 my $content = decode_utf8(encode_utf8($params{content}));
347 return $content if ( ! istranslation($page)
348 || ( exists $filtered{$page}{$destpage}
349 && $filtered{$page}{$destpage} eq 1 ));
351 # CRLF line terminators make poor Locale::Po4a feel bad
352 $content=~s/\r\n/\n/g;
354 # Implementation notes
356 # 1. Locale::Po4a reads/writes from/to files, and I'm too lazy
357 # to learn how to disguise a variable as a file.
358 # 2. There are incompatibilities between some File::Temp versions
359 # (including 0.18, bundled with Lenny's perl-modules package)
360 # and others (e.g. 0.20, previously present in the archive as
361 # a standalone package): under certain circumstances, some
362 # return a relative filename, whereas others return an absolute one;
363 # we here use this module in a way that is at least compatible
364 # with 0.18 and 0.20. Beware, hit'n'run refactorers!
365 my $infile = new File::Temp(TEMPLATE => "ikiwiki-po-filter-in.XXXXXXXXXX",
366 DIR => File::Spec->tmpdir,
367 UNLINK => 1)->filename;
368 my $outfile = new File::Temp(TEMPLATE => "ikiwiki-po-filter-out.XXXXXXXXXX",
369 DIR => File::Spec->tmpdir,
370 UNLINK => 1)->filename;
372 writefile(basename($infile), File::Spec->tmpdir, $content);
374 my ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
375 my $masterfile = srcfile($pagesources{$masterpage});
378 push @masters,$masterfile;
380 "markdown" => (pagetype($masterfile) eq 'mdwn') ? 1 : 0,
382 my $doc=Locale::Po4a::Chooser::new('text',%options);
384 'po_in_name' => \@pos,
385 'file_in_name' => \@masters,
386 'file_in_charset' => 'utf-8',
387 'file_out_charset' => 'utf-8',
388 ) or error("[po/filter:$infile]: failed to translate");
389 $doc->write($outfile) or error("[po/filter:$infile] could not write $outfile");
390 $content = readfile($outfile) or error("[po/filter:$infile] could not read $outfile");
392 # Unlinking should happen automatically, thanks to File::Temp,
393 # but it does not work here, probably because of the way writefile()
394 # and Locale::Po4a::write() work.
395 unlink $infile, $outfile;
397 $filtered{$page}{$destpage}=1;
401 sub htmlize (@) { #{{{
404 my $page = $params{page};
405 my $content = $params{content};
406 my ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
407 my $masterfile = srcfile($pagesources{$masterpage});
409 # force content to be htmlize'd as if it was the same type as the master page
410 return IkiWiki::htmlize($page, $page, pagetype($masterfile), $content);
413 sub percenttranslated ($) { #{{{
416 return gettext("N/A") unless (istranslation($page));
417 my ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
418 my $file=srcfile($pagesources{$page});
419 my $masterfile = srcfile($pagesources{$masterpage});
422 push @masters,$masterfile;
424 "markdown" => (pagetype($masterfile) eq 'mdwn') ? 1 : 0,
426 my $doc=Locale::Po4a::Chooser::new('text',%options);
428 'po_in_name' => \@pos,
429 'file_in_name' => \@masters,
430 'file_in_charset' => 'utf-8',
431 'file_out_charset' => 'utf-8',
432 ) or error("[po/percenttranslated:$file]: failed to translate");
433 my ($percent,$hit,$queries) = $doc->stats();
437 sub otherlanguages ($) { #{{{
441 if (istranslatable($page)) {
442 foreach my $lang (sort keys %{$translations{$page}}) {
443 my $translation = $translations{$page}{$lang};
445 url => urlto($translation, $page),
447 language => $config{po_slave_languages}{$lang},
448 percent => percenttranslated($translation),
452 elsif (istranslation($page)) {
453 my ($masterpage, $curlang) = ($page =~ /(.*)[.]([a-z]{2})$/);
455 url => urlto_with_orig_beautiful_urlpath($masterpage, $page),
456 code => $config{po_master_language}{code},
457 language => $config{po_master_language}{name},
460 foreach my $lang (sort keys %{$translations{$masterpage}}) {
462 url => urlto($translations{$masterpage}{$lang}, $page),
464 language => $config{po_slave_languages}{$lang},
465 percent => percenttranslated($translations{$masterpage}{$lang}),
466 } unless ($lang eq $curlang);
472 sub pagetemplate (@) { #{{{
474 my $page=$params{page};
475 my $destpage=$params{destpage};
476 my $template=$params{template};
478 my ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/) if istranslation($page);
480 if (istranslation($page) && $template->query(name => "percenttranslated")) {
481 $template->param(percenttranslated => percenttranslated($page));
483 if ($template->query(name => "istranslation")) {
484 $template->param(istranslation => istranslation($page));
486 if ($template->query(name => "istranslatable")) {
487 $template->param(istranslatable => istranslatable($page));
489 if ($template->query(name => "otherlanguages")) {
490 $template->param(otherlanguages => [otherlanguages($page)]);
491 if (istranslatable($page)) {
492 foreach my $translation (values %{$translations{$page}}) {
493 add_depends($page, $translation);
496 elsif (istranslation($page)) {
497 add_depends($page, $masterpage);
498 foreach my $translation (values %{$translations{$masterpage}}) {
499 add_depends($page, $translation);
503 # Rely on IkiWiki::Render's genpage() to decide wether
504 # a discussion link should appear on $page; this is not
505 # totally accurate, though: some broken links may be generated
506 # when cgiurl is disabled.
507 # This compromise avoids some code duplication, and will probably
508 # prevent future breakage when ikiwiki internals change.
509 # Known limitations are preferred to future random bugs.
510 if ($template->param('discussionlink') && istranslation($page)) {
511 $template->param('discussionlink' => htmllink(
514 $masterpage . '/' . gettext("Discussion"),
517 linktext => gettext("Discussion"),
520 # remove broken parentlink to ./index.html on home page's translations
521 if ($template->param('parentlinks')
522 && istranslation($page)
523 && $masterpage eq "index") {
524 $template->param('parentlinks' => []);
531 my $updated_po_files=0;
533 # Refresh/create POT and PO files as needed.
534 foreach my $page (map pagename($_), @rendered) {
535 next unless istranslatable($page);
536 my $file=srcfile($pagesources{$page});
537 my $updated_pot_file=0;
538 if ((grep { $_ eq $pagesources{$page} } @origneedsbuild)
539 || ! -e potfile($file)) {
544 foreach my $lang (keys %{$config{po_slave_languages}}) {
545 my $pofile=pofile($file, $lang);
546 if ($updated_pot_file || ! -e $pofile) {
547 push @pofiles, $pofile;
551 refreshpofiles($file, @pofiles);
552 map { IkiWiki::rcs_add($_); } @pofiles if ($config{rcs});
557 if ($updated_po_files) {
558 # Check staged changes in.
560 IkiWiki::disable_commit_hook();
561 IkiWiki::rcs_commit_staged(gettext("updated PO files"),
562 "IkiWiki::Plugin::po::change", "127.0.0.1");
563 IkiWiki::enable_commit_hook();
564 IkiWiki::rcs_update();
566 # Reinitialize module's private variables.
569 # Trigger a wiki refresh.
570 require IkiWiki::Render;
572 IkiWiki::saveindex();
576 sub editcontent () { #{{{
578 # as we're previewing or saving a page, the content may have
579 # changed, so tell the next filter() invocation it must not be lazy
580 if (exists $filtered{$params{page}}{$params{page}}) {
581 delete $filtered{$params{page}}{$params{page}};
583 return $params{content};
586 sub istranslatable ($) { #{{{
589 my $file=$pagesources{$page};
592 || (defined pagetype($file) && pagetype($file) eq 'po')
593 || $file =~ /\.pot$/) {
596 return pagespec_match($page, $config{po_translatable_pages});
599 sub _istranslation ($) { #{{{
602 my $file=$pagesources{$page};
603 if (! defined $file) {
604 return IkiWiki::FailReason->new("no file specified");
608 || ! defined pagetype($file)
609 || ! pagetype($file) eq 'po'
610 || $file =~ /\.pot$/) {
614 my ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
615 if (! defined $masterpage || ! defined $lang
616 || ! (length($masterpage) > 0) || ! (length($lang) > 0)
617 || ! defined $pagesources{$masterpage}
618 || ! defined $config{po_slave_languages}{$lang}) {
622 return istranslatable($masterpage);
625 sub istranslation ($) { #{{{
628 if (_istranslation($page)) {
629 my ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
630 $translations{$masterpage}{$lang}=$page unless exists $translations{$masterpage}{$lang};
636 package IkiWiki::PageSpec;
641 sub match_istranslation ($;@) { #{{{
644 if (IkiWiki::Plugin::po::istranslation($page)) {
645 return IkiWiki::SuccessReason->new("is a translation page");
648 return IkiWiki::FailReason->new("is not a translation page");
652 sub match_istranslatable ($;@) { #{{{
655 if (IkiWiki::Plugin::po::istranslatable($page)) {
656 return IkiWiki::SuccessReason->new("is set as translatable in po_translatable_pages");
659 return IkiWiki::FailReason->new("is not set as translatable in po_translatable_pages");
663 sub match_lang ($$;@) { #{{{
667 my $regexp=IkiWiki::glob2re($wanted);
671 if (IkiWiki::Plugin::po::istranslation($page)) {
672 ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
675 $lang = $config{po_master_language}{code};
678 if ($lang!~/^$regexp$/i) {
679 return IkiWiki::FailReason->new("file language is $lang, not $wanted");
682 return IkiWiki::SuccessReason->new("file language is $wanted");
686 sub match_currentlang ($$;@) { #{{{
691 my ($currentmasterpage, $currentlang, $masterpage, $lang);
693 return IkiWiki::FailReason->new("no location provided") unless exists $params{location};
695 if (IkiWiki::Plugin::po::istranslation($params{location})) {
696 ($currentmasterpage, $currentlang) = ($params{location} =~ /(.*)[.]([a-z]{2})$/);
699 $currentlang = $config{po_master_language}{code};
702 if (IkiWiki::Plugin::po::istranslation($page)) {
703 ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
706 $lang = $config{po_master_language}{code};
709 if ($lang eq $currentlang) {
710 return IkiWiki::SuccessReason->new("file language is the same as current one, i.e. $currentlang");
713 return IkiWiki::FailReason->new("file language is $lang, whereas current language is $currentlang");