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");
30 hook(type => "getsetup", id => "po", call => \&getsetup);
31 hook(type => "checkconfig", id => "po", call => \&checkconfig);
32 hook(type => "needsbuild", id => "po", call => \&needsbuild);
33 hook(type => "scan", id => "po", call => \&scan, last =>1);
34 hook(type => "filter", id => "po", call => \&filter);
35 hook(type => "htmlize", id => "po", call => \&htmlize);
36 hook(type => "pagetemplate", id => "po", call => \&pagetemplate, last => 1);
37 hook(type => "change", id => "po", call => \&change);
38 hook(type => "editcontent", id => "po", call => \&editcontent);
40 $origsubs{'bestlink'}=\&IkiWiki::bestlink;
41 inject(name => "IkiWiki::bestlink", call => \&mybestlink);
42 $origsubs{'beautify_urlpath'}=\&IkiWiki::beautify_urlpath;
43 inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath);
44 $origsubs{'targetpage'}=\&IkiWiki::targetpage;
45 inject(name => "IkiWiki::targetpage", call => \&mytargetpage);
46 $origsubs{'urlto'}=\&IkiWiki::urlto;
47 inject(name => "IkiWiki::urlto", call => \&myurlto);
56 # 2. Injected functions
57 # 3. Blackboxes for private data
66 sub getsetup () { #{{{
72 po_master_language => {
78 description => "master language (non-PO files)",
82 po_slave_languages => {
89 description => "slave languages (PO files)",
93 po_translatable_pages => {
95 example => "!*/Discussion",
96 description => "PageSpec controlling which pages are translatable",
97 link => "ikiwiki/PageSpec",
103 example => "current",
104 description => "internal linking behavior (default/current/negotiated)",
110 sub checkconfig () { #{{{
111 foreach my $field (qw{po_master_language po_slave_languages}) {
112 if (! exists $config{$field} || ! defined $config{$field}) {
113 error(sprintf(gettext("Must specify %s"), $field));
116 if (! (keys %{$config{po_slave_languages}})) {
117 error(gettext("At least one slave language must be defined in po_slave_languages"));
121 or error(sprintf(gettext("%s is not a valid language code"), $_));
122 } ($config{po_master_language}{code}, keys %{$config{po_slave_languages}});
123 if (! exists $config{po_translatable_pages} ||
124 ! defined $config{po_translatable_pages}) {
125 $config{po_translatable_pages}="";
127 if (! exists $config{po_link_to} ||
128 ! defined $config{po_link_to}) {
129 $config{po_link_to}='default';
132 $config{po_link_to} eq $_
133 } ('default', 'current', 'negotiated')) {
134 warn(sprintf(gettext('po_link_to=%s is not a valid setting, falling back to po_link_to=default'),
135 $config{po_link_to}));
136 $config{po_link_to}='default';
138 elsif ($config{po_link_to} eq "negotiated" && ! $config{usedirs}) {
139 warn(gettext('po_link_to=negotiated requires usedirs to be enabled, falling back to po_link_to=default'));
140 $config{po_link_to}='default';
142 push @{$config{wiki_file_prune_regexps}}, qr/\.pot$/;
145 sub needsbuild () { #{{{
146 my $needsbuild=shift;
148 # backup @needsbuild content so that change() can know whether
149 # a given master page was rendered because its source file was changed
150 @origneedsbuild=(@$needsbuild);
152 buildtranslationscache();
154 # make existing translations depend on the corresponding master page
155 foreach my $master (keys %translations) {
156 map add_depends($_, $master), values %{otherlanguages($master)};
162 my $page=$params{page};
163 my $content=$params{content};
165 return unless UNIVERSAL::can("IkiWiki::Plugin::link", "import");
167 if (istranslation($page)) {
168 foreach my $destpage (@{$links{$page}}) {
169 if (istranslatable($destpage)) {
170 # replace one occurence of $destpage in $links{$page}
171 # (we only want to replace the one that was added by
172 # IkiWiki::Plugin::link::scan, other occurences may be
173 # there for other reasons)
174 for (my $i=0; $i<@{$links{$page}}; $i++) {
175 if (@{$links{$page}}[$i] eq $destpage) {
176 @{$links{$page}}[$i] = $destpage . '.' . lang($page);
183 elsif (! istranslatable($page) && ! istranslation($page)) {
184 foreach my $destpage (@{$links{$page}}) {
185 if (istranslatable($destpage)) {
187 push @{$links{$page}}, $destpage . '.' . $_;
188 } (keys %{$config{po_slave_languages}});
194 # We use filter to convert PO to the master page's format,
195 # since the rest of ikiwiki should not work on PO files.
196 sub filter (@) { #{{{
199 my $page = $params{page};
200 my $destpage = $params{destpage};
201 my $content = decode_utf8(encode_utf8($params{content}));
203 return $content if ( ! istranslation($page)
204 || alreadyfiltered($page, $destpage) );
206 # CRLF line terminators make poor Locale::Po4a feel bad
207 $content=~s/\r\n/\n/g;
209 # Implementation notes
211 # 1. Locale::Po4a reads/writes from/to files, and I'm too lazy
212 # to learn how to disguise a variable as a file.
213 # 2. There are incompatibilities between some File::Temp versions
214 # (including 0.18, bundled with Lenny's perl-modules package)
215 # and others (e.g. 0.20, previously present in the archive as
216 # a standalone package): under certain circumstances, some
217 # return a relative filename, whereas others return an absolute one;
218 # we here use this module in a way that is at least compatible
219 # with 0.18 and 0.20. Beware, hit'n'run refactorers!
220 my $infile = new File::Temp(TEMPLATE => "ikiwiki-po-filter-in.XXXXXXXXXX",
221 DIR => File::Spec->tmpdir,
222 UNLINK => 1)->filename;
223 my $outfile = new File::Temp(TEMPLATE => "ikiwiki-po-filter-out.XXXXXXXXXX",
224 DIR => File::Spec->tmpdir,
225 UNLINK => 1)->filename;
227 writefile(basename($infile), File::Spec->tmpdir, $content);
229 my $masterfile = srcfile($pagesources{masterpage($page)});
232 push @masters,$masterfile;
234 "markdown" => (pagetype($masterfile) eq 'mdwn') ? 1 : 0,
236 my $doc=Locale::Po4a::Chooser::new('text',%options);
238 'po_in_name' => \@pos,
239 'file_in_name' => \@masters,
240 'file_in_charset' => 'utf-8',
241 'file_out_charset' => 'utf-8',
242 ) or error("[po/filter:$page]: failed to translate");
243 $doc->write($outfile) or error("[po/filter:$page] could not write $outfile");
244 $content = readfile($outfile) or error("[po/filter:$page] could not read $outfile");
246 # Unlinking should happen automatically, thanks to File::Temp,
247 # but it does not work here, probably because of the way writefile()
248 # and Locale::Po4a::write() work.
249 unlink $infile, $outfile;
251 setalreadyfiltered($page, $destpage);
255 sub htmlize (@) { #{{{
258 my $page = $params{page};
259 my $content = $params{content};
260 my $masterfile = srcfile($pagesources{masterpage($page)});
262 # force content to be htmlize'd as if it was the same type as the master page
263 return IkiWiki::htmlize($page, $page, pagetype($masterfile), $content);
266 sub pagetemplate (@) { #{{{
268 my $page=$params{page};
269 my $destpage=$params{destpage};
270 my $template=$params{template};
272 my ($masterpage, $lang) = istranslation($page);
274 if (istranslation($page) && $template->query(name => "percenttranslated")) {
275 $template->param(percenttranslated => percenttranslated($page));
277 if ($template->query(name => "istranslation")) {
278 $template->param(istranslation => scalar istranslation($page));
280 if ($template->query(name => "istranslatable")) {
281 $template->param(istranslatable => istranslatable($page));
283 if ($template->query(name => "otherlanguages")) {
284 $template->param(otherlanguages => [otherlanguagesloop($page)]);
285 map add_depends($page, $_), (values %{otherlanguages($page)});
287 # Rely on IkiWiki::Render's genpage() to decide wether
288 # a discussion link should appear on $page; this is not
289 # totally accurate, though: some broken links may be generated
290 # when cgiurl is disabled.
291 # This compromise avoids some code duplication, and will probably
292 # prevent future breakage when ikiwiki internals change.
293 # Known limitations are preferred to future random bugs.
294 if ($template->param('discussionlink') && istranslation($page)) {
295 $template->param('discussionlink' => htmllink(
298 $masterpage . '/' . gettext("Discussion"),
301 linktext => gettext("Discussion"),
304 # Remove broken parentlink to ./index.html on home page's translations.
305 # It works because this hook has the "last" parameter set, to ensure it
306 # runs after parentlinks' own pagetemplate hook.
307 if ($template->param('parentlinks')
308 && istranslation($page)
309 && $masterpage eq "index") {
310 $template->param('parentlinks' => []);
317 my $updated_po_files=0;
319 # Refresh/create POT and PO files as needed.
320 foreach my $page (map pagename($_), @rendered) {
321 next unless istranslatable($page);
322 my $file=srcfile($pagesources{$page});
323 my $updated_pot_file=0;
324 # Only refresh Pot file if it does not exist, or if
325 # $pagesources{$page} was changed: don't if only the HTML was
326 # refreshed, e.g. because of a dependency.
327 if ((grep { $_ eq $pagesources{$page} } @origneedsbuild)
328 || ! -e potfile($file)) {
334 push @pofiles, $_ if ($updated_pot_file || ! -e $_);
337 refreshpofiles($file, @pofiles);
338 map { IkiWiki::rcs_add($_); } @pofiles if ($config{rcs});
343 if ($updated_po_files) {
344 # Check staged changes in.
346 IkiWiki::disable_commit_hook();
347 IkiWiki::rcs_commit_staged(gettext("updated PO files"),
348 "IkiWiki::Plugin::po::change", "127.0.0.1");
349 IkiWiki::enable_commit_hook();
350 IkiWiki::rcs_update();
352 # Reinitialize module's private variables.
353 resetalreadyfiltered();
354 resettranslationscache();
355 # Trigger a wiki refresh.
356 require IkiWiki::Render;
358 IkiWiki::saveindex();
362 sub editcontent () { #{{{
364 # as we're previewing or saving a page, the content may have
365 # changed, so tell the next filter() invocation it must not be lazy
366 unsetalreadyfiltered($params{page}, $params{page});
367 return $params{content};
372 # | Injected functions
375 sub mybestlink ($$) { #{{{
379 my $res=$origsubs{'bestlink'}->($page, $link);
381 if ($config{po_link_to} eq "current"
382 && istranslatable($res)
383 && istranslation($page)) {
384 return $res . "." . lang($page);
393 sub mybeautify_urlpath ($) { #{{{
396 my $res=$origsubs{'beautify_urlpath'}->($url);
397 if ($config{po_link_to} eq "negotiated") {
398 $res =~ s!/\Qindex.$config{po_master_language}{code}.$config{htmlext}\E$!/!;
403 sub mytargetpage ($$) { #{{{
407 if (istranslation($page)) {
408 my ($masterpage, $lang) = (masterpage($page), lang($page));
409 if (! $config{usedirs} || $masterpage eq 'index') {
410 return $masterpage . "." . $lang . "." . $ext;
413 return $masterpage . "/index." . $lang . "." . $ext;
416 elsif (istranslatable($page)) {
417 if (! $config{usedirs} || $page eq 'index') {
418 return $page . "." . $config{po_master_language}{code} . "." . $ext;
421 return $page . "/index." . $config{po_master_language}{code} . "." . $ext;
424 return $origsubs{'targetpage'}->($page, $ext);
427 sub myurlto ($$;$) { #{{{
432 # workaround hard-coded /index.$config{htmlext} in IkiWiki::urlto()
434 && $config{po_link_to} eq "current"
435 && istranslation($from)
436 && istranslatable('index')) {
437 return IkiWiki::beautify_urlpath(IkiWiki::baseurl($from) . "index." . lang($from) . ".$config{htmlext}");
439 return $origsubs{'urlto'}->($to,$from,$absolute);
444 # | Blackboxes for private data
450 sub alreadyfiltered($$) { #{{{
454 return ( exists $filtered{$page}{$destpage}
455 && $filtered{$page}{$destpage} eq 1 );
458 sub setalreadyfiltered($$) { #{{{
462 $filtered{$page}{$destpage}=1;
465 sub unsetalreadyfiltered($$) { #{{{
469 if (exists $filtered{$page}{$destpage}) {
470 delete $filtered{$page}{$destpage};
474 sub resetalreadyfiltered() { #{{{
484 sub istranslatable ($) { #{{{
487 my $file=$pagesources{$page};
490 || (defined pagetype($file) && pagetype($file) eq 'po')
491 || $file =~ /\.pot$/) {
494 return pagespec_match($page, $config{po_translatable_pages});
497 sub _istranslation ($) { #{{{
500 my $file=$pagesources{$page};
501 if (! defined $file) {
502 return IkiWiki::FailReason->new("no file specified");
506 || ! defined pagetype($file)
507 || ! pagetype($file) eq 'po'
508 || $file =~ /\.pot$/) {
512 my ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
513 if (! defined $masterpage || ! defined $lang
514 || ! (length($masterpage) > 0) || ! (length($lang) > 0)
515 || ! defined $pagesources{$masterpage}
516 || ! defined $config{po_slave_languages}{$lang}) {
520 return ($masterpage, $lang) if istranslatable($masterpage);
523 sub istranslation ($) { #{{{
526 if (1 < (my ($masterpage, $lang) = _istranslation($page))) {
527 $translations{$masterpage}{$lang}=$page unless exists $translations{$masterpage}{$lang};
528 return ($masterpage, $lang);
533 sub masterpage ($) { #{{{
536 if ( 1 < (my ($masterpage, $lang) = _istranslation($page))) {
545 if (1 < (my ($masterpage, $lang) = _istranslation($page))) {
548 return $config{po_master_language}{code};
551 sub islanguagecode ($) { #{{{
553 return ($code =~ /^[a-z]{2}$/);
556 sub otherlanguages($) { #{{{
560 if (istranslatable($page)) {
561 %ret = %{$translations{$page}};
563 elsif (istranslation($page)) {
564 my $masterpage = masterpage($page);
565 $ret{$config{po_master_language}{code}} = $masterpage;
566 foreach my $lang (sort keys %{$translations{$masterpage}}) {
567 next if $lang eq lang($page);
568 $ret{$lang} = $translations{$masterpage}{$lang};
574 sub potfile ($) { #{{{
575 my $masterfile=shift;
577 (my $name, my $dir, my $suffix) = fileparse($masterfile, qr/\.[^.]*/);
578 $dir='' if $dir eq './';
579 return File::Spec->catpath('', $dir, $name . ".pot");
582 sub pofile ($$) { #{{{
583 my $masterfile=shift;
586 (my $name, my $dir, my $suffix) = fileparse($masterfile, qr/\.[^.]*/);
587 $dir='' if $dir eq './';
588 return File::Spec->catpath('', $dir, $name . "." . $lang . ".po");
591 sub pofiles ($) { #{{{
592 my $masterfile=shift;
593 return map pofile($masterfile, $_), (keys %{$config{po_slave_languages}});
596 sub refreshpot ($) { #{{{
597 my $masterfile=shift;
599 my $potfile=potfile($masterfile);
600 my %options = ("markdown" => (pagetype($masterfile) eq 'mdwn') ? 1 : 0);
601 my $doc=Locale::Po4a::Chooser::new('text',%options);
602 $doc->{TT}{utf_mode} = 1;
603 $doc->{TT}{file_in_charset} = 'utf-8';
604 $doc->{TT}{file_out_charset} = 'utf-8';
605 $doc->read($masterfile);
606 # let's cheat a bit to force porefs option to be passed to Locale::Po4a::Po;
607 # this is undocument use of internal Locale::Po4a::TransTractor's data,
608 # compulsory since this module prevents us from using the porefs option.
609 my %po_options = ('porefs' => 'none');
610 $doc->{TT}{po_out}=Locale::Po4a::Po->new(\%po_options);
611 $doc->{TT}{po_out}->set_charset('utf-8');
614 IkiWiki::prep_writefile(basename($potfile),dirname($potfile));
615 $doc->writepo($potfile);
618 sub refreshpofiles ($@) { #{{{
619 my $masterfile=shift;
622 my $potfile=potfile($masterfile);
623 error("[po/refreshpofiles] POT file ($potfile) does not exist") unless (-e $potfile);
625 foreach my $pofile (@pofiles) {
626 IkiWiki::prep_writefile(basename($pofile),dirname($pofile));
628 system("msgmerge", "-U", "--backup=none", $pofile, $potfile) == 0
629 or error("[po/refreshpofiles:$pofile] failed to update");
632 File::Copy::syscopy($potfile,$pofile)
633 or error("[po/refreshpofiles:$pofile] failed to copy the POT file");
638 sub buildtranslationscache() { #{{{
639 # use istranslation's side-effect
640 map istranslation($_), (keys %pagesources);
643 sub resettranslationscache() { #{{{
647 sub urlto_with_orig_beautiful_urlpath($$) { #{{{
651 inject(name => "IkiWiki::beautify_urlpath", call => $origsubs{'beautify_urlpath'});
652 my $res=urlto($to, $from);
653 inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath);
658 sub percenttranslated ($) { #{{{
661 return gettext("N/A") unless istranslation($page);
662 my $file=srcfile($pagesources{$page});
663 my $masterfile = srcfile($pagesources{masterpage($page)});
666 push @masters,$masterfile;
668 "markdown" => (pagetype($masterfile) eq 'mdwn') ? 1 : 0,
670 my $doc=Locale::Po4a::Chooser::new('text',%options);
672 'po_in_name' => \@pos,
673 'file_in_name' => \@masters,
674 'file_in_charset' => 'utf-8',
675 'file_out_charset' => 'utf-8',
676 ) or error("[po/percenttranslated:$page]: failed to translate");
677 my ($percent,$hit,$queries) = $doc->stats();
681 sub languagename ($) { #{{{
684 return $config{po_master_language}{name}
685 if $code eq $config{po_master_language}{code};
686 return $config{po_slave_languages}{$code}
687 if defined $config{po_slave_languages}{$code};
691 sub otherlanguagesloop ($) { #{{{
695 my %otherpages=%{otherlanguages($page)};
696 while (my ($lang, $otherpage) = each %otherpages) {
697 if (istranslation($page) && masterpage($page) eq $otherpage) {
699 url => urlto_with_orig_beautiful_urlpath($otherpage, $page),
701 language => languagename($lang),
707 url => urlto($otherpage, $page),
709 language => languagename($lang),
710 percent => percenttranslated($otherpage),
715 return -1 if $a->{code} eq $config{po_master_language}{code};
716 return 1 if $b->{code} eq $config{po_master_language}{code};
717 return $a->{language} cmp $b->{language};
726 package IkiWiki::PageSpec;
731 sub match_istranslation ($;@) { #{{{
734 if (IkiWiki::Plugin::po::istranslation($page)) {
735 return IkiWiki::SuccessReason->new("is a translation page");
738 return IkiWiki::FailReason->new("is not a translation page");
742 sub match_istranslatable ($;@) { #{{{
745 if (IkiWiki::Plugin::po::istranslatable($page)) {
746 return IkiWiki::SuccessReason->new("is set as translatable in po_translatable_pages");
749 return IkiWiki::FailReason->new("is not set as translatable in po_translatable_pages");
753 sub match_lang ($$;@) { #{{{
757 my $regexp=IkiWiki::glob2re($wanted);
758 my $lang=IkiWiki::Plugin::po::lang($page);
759 if ($lang!~/^$regexp$/i) {
760 return IkiWiki::FailReason->new("file language is $lang, not $wanted");
763 return IkiWiki::SuccessReason->new("file language is $wanted");
767 sub match_currentlang ($$;@) { #{{{
772 return IkiWiki::FailReason->new("no location provided") unless exists $params{location};
774 my $currentlang=IkiWiki::Plugin::po::lang($params{location});
775 my $lang=IkiWiki::Plugin::po::lang($page);
777 if ($lang eq $currentlang) {
778 return IkiWiki::SuccessReason->new("file language is the same as current one, i.e. $currentlang");
781 return IkiWiki::FailReason->new("file language is $lang, whereas current language is $currentlang");