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("istranslatable");
27 memoize("_istranslation");
28 memoize("percenttranslated");
31 hook(type => "getsetup", id => "po", call => \&getsetup);
32 hook(type => "checkconfig", id => "po", call => \&checkconfig);
33 hook(type => "needsbuild", id => "po", call => \&needsbuild);
34 hook(type => "scan", id => "po", call => \&scan, last =>1);
35 hook(type => "filter", id => "po", call => \&filter);
36 hook(type => "htmlize", id => "po", call => \&htmlize);
37 hook(type => "pagetemplate", id => "po", call => \&pagetemplate, last => 1);
38 hook(type => "rename", id => "po", call => \&renamepages);
39 hook(type => "delete", id => "po", call => \&mydelete);
40 hook(type => "change", id => "po", call => \&change);
41 hook(type => "editcontent", id => "po", call => \&editcontent);
43 $origsubs{'bestlink'}=\&IkiWiki::bestlink;
44 inject(name => "IkiWiki::bestlink", call => \&mybestlink);
45 $origsubs{'beautify_urlpath'}=\&IkiWiki::beautify_urlpath;
46 inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath);
47 $origsubs{'targetpage'}=\&IkiWiki::targetpage;
48 inject(name => "IkiWiki::targetpage", call => \&mytargetpage);
49 $origsubs{'urlto'}=\&IkiWiki::urlto;
50 inject(name => "IkiWiki::urlto", call => \&myurlto);
59 # 2. Injected functions
60 # 3. Blackboxes for private data
69 sub getsetup () { #{{{
75 po_master_language => {
81 description => "master language (non-PO files)",
85 po_slave_languages => {
92 description => "slave languages (PO files)",
96 po_translatable_pages => {
98 example => "!*/Discussion",
99 description => "PageSpec controlling which pages are translatable",
100 link => "ikiwiki/PageSpec",
106 example => "current",
107 description => "internal linking behavior (default/current/negotiated)",
113 sub checkconfig () { #{{{
114 foreach my $field (qw{po_master_language po_slave_languages}) {
115 if (! exists $config{$field} || ! defined $config{$field}) {
116 error(sprintf(gettext("Must specify %s"), $field));
119 if (! (keys %{$config{po_slave_languages}})) {
120 error(gettext("At least one slave language must be defined in po_slave_languages"));
124 or error(sprintf(gettext("%s is not a valid language code"), $_));
125 } ($config{po_master_language}{code}, keys %{$config{po_slave_languages}});
126 if (! exists $config{po_translatable_pages} ||
127 ! defined $config{po_translatable_pages}) {
128 $config{po_translatable_pages}="";
130 if (! exists $config{po_link_to} ||
131 ! defined $config{po_link_to}) {
132 $config{po_link_to}='default';
135 $config{po_link_to} eq $_
136 } ('default', 'current', 'negotiated')) {
137 warn(sprintf(gettext('po_link_to=%s is not a valid setting, falling back to po_link_to=default'),
138 $config{po_link_to}));
139 $config{po_link_to}='default';
141 elsif ($config{po_link_to} eq "negotiated" && ! $config{usedirs}) {
142 warn(gettext('po_link_to=negotiated requires usedirs to be enabled, falling back to po_link_to=default'));
143 $config{po_link_to}='default';
145 push @{$config{wiki_file_prune_regexps}}, qr/\.pot$/;
148 sub needsbuild () { #{{{
149 my $needsbuild=shift;
151 # backup @needsbuild content so that change() can know whether
152 # a given master page was rendered because its source file was changed
153 @origneedsbuild=(@$needsbuild);
156 buildtranslationscache();
158 # make existing translations depend on the corresponding master page
159 foreach my $master (keys %translations) {
160 map add_depends($_, $master), values %{otherlanguages($master)};
164 # Massage the recorded state of internal links so that:
165 # - it matches the actually generated links, rather than the links as written
166 # in the pages' source
167 # - backlinks are consistent in all cases
170 my $page=$params{page};
171 my $content=$params{content};
173 return unless UNIVERSAL::can("IkiWiki::Plugin::link", "import");
175 if (istranslation($page)) {
176 foreach my $destpage (@{$links{$page}}) {
177 if (istranslatable($destpage)) {
178 # replace one occurence of $destpage in $links{$page}
179 # (we only want to replace the one that was added by
180 # IkiWiki::Plugin::link::scan, other occurences may be
181 # there for other reasons)
182 for (my $i=0; $i<@{$links{$page}}; $i++) {
183 if (@{$links{$page}}[$i] eq $destpage) {
184 @{$links{$page}}[$i] = $destpage . '.' . lang($page);
191 elsif (! istranslatable($page) && ! istranslation($page)) {
192 foreach my $destpage (@{$links{$page}}) {
193 if (istranslatable($destpage)) {
194 # make sure any destpage's translations has
195 # $page in its backlinks
196 push @{$links{$page}},
197 values %{otherlanguages($destpage)};
203 # We use filter to convert PO to the master page's format,
204 # since the rest of ikiwiki should not work on PO files.
205 sub filter (@) { #{{{
208 my $page = $params{page};
209 my $destpage = $params{destpage};
210 my $content = decode_utf8(encode_utf8($params{content}));
212 return $content if ( ! istranslation($page)
213 || alreadyfiltered($page, $destpage) );
215 # CRLF line terminators make poor Locale::Po4a feel bad
216 $content=~s/\r\n/\n/g;
218 # Implementation notes
220 # 1. Locale::Po4a reads/writes from/to files, and I'm too lazy
221 # to learn how to disguise a variable as a file.
222 # 2. There are incompatibilities between some File::Temp versions
223 # (including 0.18, bundled with Lenny's perl-modules package)
224 # and others (e.g. 0.20, previously present in the archive as
225 # a standalone package): under certain circumstances, some
226 # return a relative filename, whereas others return an absolute one;
227 # we here use this module in a way that is at least compatible
228 # with 0.18 and 0.20. Beware, hit'n'run refactorers!
229 my $infile = new File::Temp(TEMPLATE => "ikiwiki-po-filter-in.XXXXXXXXXX",
230 DIR => File::Spec->tmpdir,
231 UNLINK => 1)->filename;
232 my $outfile = new File::Temp(TEMPLATE => "ikiwiki-po-filter-out.XXXXXXXXXX",
233 DIR => File::Spec->tmpdir,
234 UNLINK => 1)->filename;
236 writefile(basename($infile), File::Spec->tmpdir, $content);
238 my $masterfile = srcfile($pagesources{masterpage($page)});
241 push @masters,$masterfile;
243 "markdown" => (pagetype($masterfile) eq 'mdwn') ? 1 : 0,
245 my $doc=Locale::Po4a::Chooser::new('text',%options);
247 'po_in_name' => \@pos,
248 'file_in_name' => \@masters,
249 'file_in_charset' => 'utf-8',
250 'file_out_charset' => 'utf-8',
251 ) or error("[po/filter:$page]: failed to translate");
252 $doc->write($outfile) or error("[po/filter:$page] could not write $outfile");
253 $content = readfile($outfile) or error("[po/filter:$page] could not read $outfile");
255 # Unlinking should happen automatically, thanks to File::Temp,
256 # but it does not work here, probably because of the way writefile()
257 # and Locale::Po4a::write() work.
258 unlink $infile, $outfile;
260 setalreadyfiltered($page, $destpage);
264 sub htmlize (@) { #{{{
267 my $page = $params{page};
268 my $content = $params{content};
270 # ignore PO files this plugin did not create
271 return $content unless istranslation($page);
273 # force content to be htmlize'd as if it was the same type as the master page
274 return IkiWiki::htmlize($page, $page,
275 pagetype(srcfile($pagesources{masterpage($page)})),
279 sub pagetemplate (@) { #{{{
281 my $page=$params{page};
282 my $destpage=$params{destpage};
283 my $template=$params{template};
285 my ($masterpage, $lang) = istranslation($page);
287 if (istranslation($page) && $template->query(name => "percenttranslated")) {
288 $template->param(percenttranslated => percenttranslated($page));
290 if ($template->query(name => "istranslation")) {
291 $template->param(istranslation => scalar istranslation($page));
293 if ($template->query(name => "istranslatable")) {
294 $template->param(istranslatable => istranslatable($page));
296 if ($template->query(name => "HOMEPAGEURL")) {
297 $template->param(homepageurl => homepageurl($page));
299 if ($template->query(name => "otherlanguages")) {
300 $template->param(otherlanguages => [otherlanguagesloop($page)]);
301 map add_depends($page, $_), (values %{otherlanguages($page)});
303 # Rely on IkiWiki::Render's genpage() to decide wether
304 # a discussion link should appear on $page; this is not
305 # totally accurate, though: some broken links may be generated
306 # when cgiurl is disabled.
307 # This compromise avoids some code duplication, and will probably
308 # prevent future breakage when ikiwiki internals change.
309 # Known limitations are preferred to future random bugs.
310 if ($template->param('discussionlink') && istranslation($page)) {
311 $template->param('discussionlink' => htmllink(
314 $masterpage . '/' . gettext("Discussion"),
317 linktext => gettext("Discussion"),
320 # Remove broken parentlink to ./index.html on home page's translations.
321 # It works because this hook has the "last" parameter set, to ensure it
322 # runs after parentlinks' own pagetemplate hook.
323 if ($template->param('parentlinks')
324 && istranslation($page)
325 && $masterpage eq "index") {
326 $template->param('parentlinks' => []);
330 # Add the renamed page translations to the list of to-be-renamed pages.
331 # Save information about master page rename, so that:
332 # - our delete hook can ignore the translations not renamed already
333 # - our change hook can rename the translations accordingly.
334 sub renamepages() { #{{{
336 my @torename=@{$torename};
338 foreach my $rename (@torename) {
339 next unless istranslatable($rename->{src});
340 my %otherpages=%{otherlanguages($rename->{src})};
341 while (my ($lang, $otherpage) = each %otherpages) {
344 srcfile => $pagesources{$otherpage},
345 dest => otherlanguage($rename->{dest}, $lang),
346 destfile => $rename->{dest}.".".$lang.".po",
353 sub mydelete(@) { #{{{
357 deletetranslations($_);
358 } grep { istranslatablefile($_) } @deleted;
364 my $updated_po_files=0;
366 # Refresh/create POT and PO files as needed.
367 foreach my $file (@rendered) {
368 next unless istranslatablefile($file);
369 my $page=pagename($file);
370 my $masterfile=srcfile($file);
371 my $updated_pot_file=0;
372 # Only refresh Pot file if it does not exist, or if
373 # $pagesources{$page} was changed: don't if only the HTML was
374 # refreshed, e.g. because of a dependency.
375 if ((grep { $_ eq $pagesources{$page} } @origneedsbuild)
376 || ! -e potfile($masterfile)) {
377 refreshpot($masterfile);
382 push @pofiles, $_ if ($updated_pot_file || ! -e $_);
383 } (pofiles($masterfile));
385 refreshpofiles($masterfile, @pofiles);
386 map { IkiWiki::rcs_add($_); } @pofiles if ($config{rcs});
391 if ($updated_po_files) {
392 # Check staged changes in.
394 IkiWiki::disable_commit_hook();
395 IkiWiki::rcs_commit_staged(gettext("updated PO files"),
396 "IkiWiki::Plugin::po::change", "127.0.0.1");
397 IkiWiki::enable_commit_hook();
398 IkiWiki::rcs_update();
400 # Reinitialize module's private variables.
401 resetalreadyfiltered();
402 resettranslationscache();
404 # Trigger a wiki refresh.
405 require IkiWiki::Render;
406 # without preliminary saveindex/loadindex, refresh()
407 # complains about a lot of uninitialized variables
408 IkiWiki::saveindex();
409 IkiWiki::loadindex();
411 IkiWiki::saveindex();
415 # As we're previewing or saving a page, the content may have
416 # changed, so tell the next filter() invocation it must not be lazy.
417 sub editcontent () { #{{{
420 unsetalreadyfiltered($params{page}, $params{page});
421 return $params{content};
426 # | Injected functions
429 # Implement po_link_to 'current' and 'negotiated' settings.
430 sub mybestlink ($$) { #{{{
434 my $res=$origsubs{'bestlink'}->(masterpage($page), $link);
436 && ($config{po_link_to} eq "current" || $config{po_link_to} eq "negotiated")
437 && istranslatable($res)
438 && istranslation($page)) {
439 return $res . "." . lang($page);
444 sub mybeautify_urlpath ($) { #{{{
447 my $res=$origsubs{'beautify_urlpath'}->($url);
448 if ($config{po_link_to} eq "negotiated") {
449 $res =~ s!/\Qindex.$config{po_master_language}{code}.$config{htmlext}\E$!/!;
450 $res =~ s!/\Qindex.$config{htmlext}\E$!/!;
452 $res =~ s!/\Qindex.$_.$config{htmlext}\E$!/!;
453 } (keys %{$config{po_slave_languages}});
458 sub mytargetpage ($$) { #{{{
462 if (istranslation($page) || istranslatable($page)) {
463 my ($masterpage, $lang) = (masterpage($page), lang($page));
464 if (! $config{usedirs} || $masterpage eq 'index') {
465 return $masterpage . "." . $lang . "." . $ext;
468 return $masterpage . "/index." . $lang . "." . $ext;
471 return $origsubs{'targetpage'}->($page, $ext);
474 sub myurlto ($$;$) { #{{{
479 # workaround hard-coded /index.$config{htmlext} in IkiWiki::urlto()
481 && $config{po_link_to} eq "current"
482 && istranslatable('index')) {
483 return IkiWiki::beautify_urlpath(IkiWiki::baseurl($from) . "index." . lang($from) . ".$config{htmlext}");
485 return $origsubs{'urlto'}->($to,$from,$absolute);
490 # | Blackboxes for private data
496 sub alreadyfiltered($$) { #{{{
500 return ( exists $filtered{$page}{$destpage}
501 && $filtered{$page}{$destpage} eq 1 );
504 sub setalreadyfiltered($$) { #{{{
508 $filtered{$page}{$destpage}=1;
511 sub unsetalreadyfiltered($$) { #{{{
515 if (exists $filtered{$page}{$destpage}) {
516 delete $filtered{$page}{$destpage};
520 sub resetalreadyfiltered() { #{{{
529 sub maybe_add_leading_slash ($;$) { #{{{
532 $add=1 unless defined $add;
533 return '/' . $str if $add;
537 sub istranslatablefile ($) { #{{{
540 return 0 unless defined $file;
541 return 0 if (defined pagetype($file) && pagetype($file) eq 'po');
542 return 0 if $file =~ /\.pot$/;
543 return 1 if pagespec_match(pagename($file), $config{po_translatable_pages});
547 sub istranslatable ($) { #{{{
551 return 1 if istranslatablefile($pagesources{$page});
555 sub _istranslation ($) { #{{{
558 my $hasleadingslash = ($page=~s#^/##);
559 my $file=$pagesources{$page};
560 return 0 unless (defined $file
561 && defined pagetype($file)
562 && pagetype($file) eq 'po');
563 return 0 if $file =~ /\.pot$/;
565 my ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
566 return 0 unless (defined $masterpage && defined $lang
567 && length $masterpage && length $lang
568 && defined $pagesources{$masterpage}
569 && defined $config{po_slave_languages}{$lang});
571 return (maybe_add_leading_slash($masterpage, $hasleadingslash), $lang)
572 if istranslatable($masterpage);
575 sub istranslation ($) { #{{{
578 if (1 < (my ($masterpage, $lang) = _istranslation($page))) {
579 my $hasleadingslash = ($masterpage=~s#^/##);
580 $translations{$masterpage}{$lang}=$page unless exists $translations{$masterpage}{$lang};
581 return (maybe_add_leading_slash($masterpage, $hasleadingslash), $lang);
586 sub masterpage ($) { #{{{
589 if ( 1 < (my ($masterpage, $lang) = _istranslation($page))) {
598 if (1 < (my ($masterpage, $lang) = _istranslation($page))) {
601 return $config{po_master_language}{code};
604 sub islanguagecode ($) { #{{{
607 return ($code =~ /^[a-z]{2}$/);
610 sub otherlanguage ($$) { #{{{
614 return masterpage($page) if $code eq $config{po_master_language}{code};
615 return masterpage($page) . '.' . $code;
618 sub otherlanguages ($) { #{{{
622 return \%ret unless (istranslation($page) || istranslatable($page));
623 my $curlang=lang($page);
625 ($config{po_master_language}{code}, keys %{$config{po_slave_languages}}) {
626 next if $lang eq $curlang;
627 $ret{$lang}=otherlanguage($page, $lang);
632 sub potfile ($) { #{{{
633 my $masterfile=shift;
635 (my $name, my $dir, my $suffix) = fileparse($masterfile, qr/\.[^.]*/);
636 $dir='' if $dir eq './';
637 return File::Spec->catpath('', $dir, $name . ".pot");
640 sub pofile ($$) { #{{{
641 my $masterfile=shift;
644 (my $name, my $dir, my $suffix) = fileparse($masterfile, qr/\.[^.]*/);
645 $dir='' if $dir eq './';
646 return File::Spec->catpath('', $dir, $name . "." . $lang . ".po");
649 sub pofiles ($) { #{{{
650 my $masterfile=shift;
652 return map pofile($masterfile, $_), (keys %{$config{po_slave_languages}});
655 sub refreshpot ($) { #{{{
656 my $masterfile=shift;
658 my $potfile=potfile($masterfile);
659 my %options = ("markdown" => (pagetype($masterfile) eq 'mdwn') ? 1 : 0);
660 my $doc=Locale::Po4a::Chooser::new('text',%options);
661 $doc->{TT}{utf_mode} = 1;
662 $doc->{TT}{file_in_charset} = 'utf-8';
663 $doc->{TT}{file_out_charset} = 'utf-8';
664 $doc->read($masterfile);
665 # let's cheat a bit to force porefs option to be passed to Locale::Po4a::Po;
666 # this is undocument use of internal Locale::Po4a::TransTractor's data,
667 # compulsory since this module prevents us from using the porefs option.
668 my %po_options = ('porefs' => 'none');
669 $doc->{TT}{po_out}=Locale::Po4a::Po->new(\%po_options);
670 $doc->{TT}{po_out}->set_charset('utf-8');
673 IkiWiki::prep_writefile(basename($potfile),dirname($potfile));
674 $doc->writepo($potfile);
677 sub refreshpofiles ($@) { #{{{
678 my $masterfile=shift;
681 my $potfile=potfile($masterfile);
682 error("[po/refreshpofiles] POT file ($potfile) does not exist") unless (-e $potfile);
684 foreach my $pofile (@pofiles) {
685 IkiWiki::prep_writefile(basename($pofile),dirname($pofile));
687 system("msgmerge", "-U", "--backup=none", $pofile, $potfile) == 0
688 or error("[po/refreshpofiles:$pofile] failed to update");
691 File::Copy::syscopy($potfile,$pofile)
692 or error("[po/refreshpofiles:$pofile] failed to copy the POT file");
697 sub buildtranslationscache() { #{{{
698 # use istranslation's side-effect
699 map istranslation($_), (keys %pagesources);
702 sub resettranslationscache() { #{{{
706 sub flushmemoizecache() { #{{{
707 Memoize::flush_cache("istranslatable");
708 Memoize::flush_cache("_istranslation");
709 Memoize::flush_cache("percenttranslated");
712 sub urlto_with_orig_beautiful_urlpath($$) { #{{{
716 inject(name => "IkiWiki::beautify_urlpath", call => $origsubs{'beautify_urlpath'});
717 my $res=urlto($to, $from);
718 inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath);
723 sub percenttranslated ($) { #{{{
726 return gettext("N/A") unless istranslation($page);
727 my $file=srcfile($pagesources{$page});
728 my $masterfile = srcfile($pagesources{masterpage($page)});
731 push @masters,$masterfile;
733 "markdown" => (pagetype($masterfile) eq 'mdwn') ? 1 : 0,
735 my $doc=Locale::Po4a::Chooser::new('text',%options);
737 'po_in_name' => \@pos,
738 'file_in_name' => \@masters,
739 'file_in_charset' => 'utf-8',
740 'file_out_charset' => 'utf-8',
741 ) or error("[po/percenttranslated:$page]: failed to translate");
742 my ($percent,$hit,$queries) = $doc->stats();
746 sub languagename ($) { #{{{
749 return $config{po_master_language}{name}
750 if $code eq $config{po_master_language}{code};
751 return $config{po_slave_languages}{$code}
752 if defined $config{po_slave_languages}{$code};
756 sub otherlanguagesloop ($) { #{{{
760 my %otherpages=%{otherlanguages($page)};
761 while (my ($lang, $otherpage) = each %otherpages) {
762 if (istranslation($page) && masterpage($page) eq $otherpage) {
764 url => urlto_with_orig_beautiful_urlpath($otherpage, $page),
766 language => languagename($lang),
772 url => urlto_with_orig_beautiful_urlpath($otherpage, $page),
774 language => languagename($lang),
775 percent => percenttranslated($otherpage),
780 return -1 if $a->{code} eq $config{po_master_language}{code};
781 return 1 if $b->{code} eq $config{po_master_language}{code};
782 return $a->{language} cmp $b->{language};
786 sub homepageurl (;$) { #{{{
789 return urlto('', $page);
792 sub deletetranslations ($) { #{{{
793 my $deletedmasterfile=shift;
795 debug "po(deletetranslations): TODO: delete translations of $deletedmasterfile";
802 package IkiWiki::PageSpec;
807 sub match_istranslation ($;@) { #{{{
810 if (IkiWiki::Plugin::po::istranslation($page)) {
811 return IkiWiki::SuccessReason->new("is a translation page");
814 return IkiWiki::FailReason->new("is not a translation page");
818 sub match_istranslatable ($;@) { #{{{
821 if (IkiWiki::Plugin::po::istranslatable($page)) {
822 return IkiWiki::SuccessReason->new("is set as translatable in po_translatable_pages");
825 return IkiWiki::FailReason->new("is not set as translatable in po_translatable_pages");
829 sub match_lang ($$;@) { #{{{
833 my $regexp=IkiWiki::glob2re($wanted);
834 my $lang=IkiWiki::Plugin::po::lang($page);
835 if ($lang!~/^$regexp$/i) {
836 return IkiWiki::FailReason->new("file language is $lang, not $wanted");
839 return IkiWiki::SuccessReason->new("file language is $wanted");
843 sub match_currentlang ($$;@) { #{{{
848 return IkiWiki::FailReason->new("no location provided") unless exists $params{location};
850 my $currentlang=IkiWiki::Plugin::po::lang($params{location});
851 my $lang=IkiWiki::Plugin::po::lang($page);
853 if ($lang eq $currentlang) {
854 return IkiWiki::SuccessReason->new("file language is the same as current one, i.e. $currentlang");
857 return IkiWiki::FailReason->new("file language is $lang, whereas current language is $currentlang");