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 => \&renamepage);
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 # Save information about master page rename, so that:
331 # - our delete hook can ignore the translations not renamed already
332 # - our change hook can rename the translations accordingly.
333 sub renamepage(@) { #{{{
335 my $oldpage=$params{oldpage};
336 my $newpage=$params{newpage};
338 setrenamed($oldpage, $newpage) if istranslatable($oldpage);
341 sub mydelete(@) { #{{{
345 deletetranslations($_);
346 } grep { istranslatablefile($_) && ! renamed(pagename($_))} @deleted;
352 my $eachrenamed=eachrenamed();
353 while (my ($oldpage, $newpage) = $eachrenamed->()) {
354 renametranslations($oldpage, $newpage);
358 my $updated_po_files=0;
360 # Refresh/create POT and PO files as needed.
361 foreach my $file (@rendered) {
362 next unless istranslatablefile($file);
363 my $page=pagename($file);
364 my $masterfile=srcfile($file);
365 my $updated_pot_file=0;
366 # Only refresh Pot file if it does not exist, or if
367 # $pagesources{$page} was changed: don't if only the HTML was
368 # refreshed, e.g. because of a dependency.
369 if ((grep { $_ eq $pagesources{$page} } @origneedsbuild)
370 || ! -e potfile($masterfile)) {
371 refreshpot($masterfile);
376 push @pofiles, $_ if ($updated_pot_file || ! -e $_);
377 } (pofiles($masterfile));
379 refreshpofiles($masterfile, @pofiles);
380 map { IkiWiki::rcs_add($_); } @pofiles if ($config{rcs});
385 if ($updated_po_files) {
386 # Check staged changes in.
388 IkiWiki::disable_commit_hook();
389 IkiWiki::rcs_commit_staged(gettext("updated PO files"),
390 "IkiWiki::Plugin::po::change", "127.0.0.1");
391 IkiWiki::enable_commit_hook();
392 IkiWiki::rcs_update();
394 # Reinitialize module's private variables.
395 resetalreadyfiltered();
396 resettranslationscache();
398 # Trigger a wiki refresh.
399 require IkiWiki::Render;
400 # without preliminary saveindex/loadindex, refresh()
401 # complains about a lot of uninitialized variables
402 IkiWiki::saveindex();
403 IkiWiki::loadindex();
405 IkiWiki::saveindex();
409 # As we're previewing or saving a page, the content may have
410 # changed, so tell the next filter() invocation it must not be lazy.
411 sub editcontent () { #{{{
414 unsetalreadyfiltered($params{page}, $params{page});
415 return $params{content};
420 # | Injected functions
423 # Implement po_link_to 'current' and 'negotiated' settings.
424 sub mybestlink ($$) { #{{{
428 my $res=$origsubs{'bestlink'}->(masterpage($page), $link);
430 && ($config{po_link_to} eq "current" || $config{po_link_to} eq "negotiated")
431 && istranslatable($res)
432 && istranslation($page)) {
433 return $res . "." . lang($page);
438 sub mybeautify_urlpath ($) { #{{{
441 my $res=$origsubs{'beautify_urlpath'}->($url);
442 if ($config{po_link_to} eq "negotiated") {
443 $res =~ s!/\Qindex.$config{po_master_language}{code}.$config{htmlext}\E$!/!;
444 $res =~ s!/\Qindex.$config{htmlext}\E$!/!;
446 $res =~ s!/\Qindex.$_.$config{htmlext}\E$!/!;
447 } (keys %{$config{po_slave_languages}});
452 sub mytargetpage ($$) { #{{{
456 if (istranslation($page) || istranslatable($page)) {
457 my ($masterpage, $lang) = (masterpage($page), lang($page));
458 if (! $config{usedirs} || $masterpage eq 'index') {
459 return $masterpage . "." . $lang . "." . $ext;
462 return $masterpage . "/index." . $lang . "." . $ext;
465 return $origsubs{'targetpage'}->($page, $ext);
468 sub myurlto ($$;$) { #{{{
473 # workaround hard-coded /index.$config{htmlext} in IkiWiki::urlto()
475 && $config{po_link_to} eq "current"
476 && istranslatable('index')) {
477 return IkiWiki::beautify_urlpath(IkiWiki::baseurl($from) . "index." . lang($from) . ".$config{htmlext}");
479 return $origsubs{'urlto'}->($to,$from,$absolute);
484 # | Blackboxes for private data
490 sub alreadyfiltered($$) { #{{{
494 return ( exists $filtered{$page}{$destpage}
495 && $filtered{$page}{$destpage} eq 1 );
498 sub setalreadyfiltered($$) { #{{{
502 $filtered{$page}{$destpage}=1;
505 sub unsetalreadyfiltered($$) { #{{{
509 if (exists $filtered{$page}{$destpage}) {
510 delete $filtered{$page}{$destpage};
514 sub resetalreadyfiltered() { #{{{
522 sub renamed ($) { #{{{
525 if (exists $renamed{$page} &&
526 defined $renamed{$page}) {
527 return $renamed{$page};
532 sub setrenamed ($$) { #{{{
536 $renamed{$oldpage}=$newpage;
539 sub resetrenamed () { #{{{
543 sub eachrenamed () { #{{{
544 return sub { each %renamed };
552 sub maybe_add_leading_slash ($;$) { #{{{
555 $add=1 unless defined $add;
556 return '/' . $str if $add;
560 sub istranslatablefile ($) { #{{{
563 return 0 unless defined $file;
564 return 0 if (defined pagetype($file) && pagetype($file) eq 'po');
565 return 0 if $file =~ /\.pot$/;
566 return 1 if pagespec_match(pagename($file), $config{po_translatable_pages});
570 sub istranslatable ($) { #{{{
574 return 1 if istranslatablefile($pagesources{$page});
578 sub _istranslation ($) { #{{{
581 my $hasleadingslash = ($page=~s#^/##);
582 my $file=$pagesources{$page};
583 return 0 unless (defined $file
584 && defined pagetype($file)
585 && pagetype($file) eq 'po');
586 return 0 if $file =~ /\.pot$/;
588 my ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
589 return 0 unless (defined $masterpage && defined $lang
590 && length $masterpage && length $lang
591 && defined $pagesources{$masterpage}
592 && defined $config{po_slave_languages}{$lang});
594 return (maybe_add_leading_slash($masterpage, $hasleadingslash), $lang)
595 if istranslatable($masterpage);
598 sub istranslation ($) { #{{{
601 if (1 < (my ($masterpage, $lang) = _istranslation($page))) {
602 my $hasleadingslash = ($masterpage=~s#^/##);
603 $translations{$masterpage}{$lang}=$page unless exists $translations{$masterpage}{$lang};
604 return (maybe_add_leading_slash($masterpage, $hasleadingslash), $lang);
609 sub masterpage ($) { #{{{
612 if ( 1 < (my ($masterpage, $lang) = _istranslation($page))) {
621 if (1 < (my ($masterpage, $lang) = _istranslation($page))) {
624 return $config{po_master_language}{code};
627 sub islanguagecode ($) { #{{{
630 return ($code =~ /^[a-z]{2}$/);
633 sub otherlanguage ($$) { #{{{
637 return masterpage($page) if $code eq $config{po_master_language}{code};
638 return masterpage($page) . '.' . $code;
641 sub otherlanguages ($) { #{{{
645 return \%ret unless (istranslation($page) || istranslatable($page));
646 my $curlang=lang($page);
648 ($config{po_master_language}{code}, keys %{$config{po_slave_languages}}) {
649 next if $lang eq $curlang;
650 $ret{$lang}=otherlanguage($page, $lang);
655 sub potfile ($) { #{{{
656 my $masterfile=shift;
658 (my $name, my $dir, my $suffix) = fileparse($masterfile, qr/\.[^.]*/);
659 $dir='' if $dir eq './';
660 return File::Spec->catpath('', $dir, $name . ".pot");
663 sub pofile ($$) { #{{{
664 my $masterfile=shift;
667 (my $name, my $dir, my $suffix) = fileparse($masterfile, qr/\.[^.]*/);
668 $dir='' if $dir eq './';
669 return File::Spec->catpath('', $dir, $name . "." . $lang . ".po");
672 sub pofiles ($) { #{{{
673 my $masterfile=shift;
675 return map pofile($masterfile, $_), (keys %{$config{po_slave_languages}});
678 sub refreshpot ($) { #{{{
679 my $masterfile=shift;
681 my $potfile=potfile($masterfile);
682 my %options = ("markdown" => (pagetype($masterfile) eq 'mdwn') ? 1 : 0);
683 my $doc=Locale::Po4a::Chooser::new('text',%options);
684 $doc->{TT}{utf_mode} = 1;
685 $doc->{TT}{file_in_charset} = 'utf-8';
686 $doc->{TT}{file_out_charset} = 'utf-8';
687 $doc->read($masterfile);
688 # let's cheat a bit to force porefs option to be passed to Locale::Po4a::Po;
689 # this is undocument use of internal Locale::Po4a::TransTractor's data,
690 # compulsory since this module prevents us from using the porefs option.
691 my %po_options = ('porefs' => 'none');
692 $doc->{TT}{po_out}=Locale::Po4a::Po->new(\%po_options);
693 $doc->{TT}{po_out}->set_charset('utf-8');
696 IkiWiki::prep_writefile(basename($potfile),dirname($potfile));
697 $doc->writepo($potfile);
700 sub refreshpofiles ($@) { #{{{
701 my $masterfile=shift;
704 my $potfile=potfile($masterfile);
705 error("[po/refreshpofiles] POT file ($potfile) does not exist") unless (-e $potfile);
707 foreach my $pofile (@pofiles) {
708 IkiWiki::prep_writefile(basename($pofile),dirname($pofile));
710 system("msgmerge", "-U", "--backup=none", $pofile, $potfile) == 0
711 or error("[po/refreshpofiles:$pofile] failed to update");
714 File::Copy::syscopy($potfile,$pofile)
715 or error("[po/refreshpofiles:$pofile] failed to copy the POT file");
720 sub buildtranslationscache() { #{{{
721 # use istranslation's side-effect
722 map istranslation($_), (keys %pagesources);
725 sub resettranslationscache() { #{{{
729 sub flushmemoizecache() { #{{{
730 Memoize::flush_cache("istranslatable");
731 Memoize::flush_cache("_istranslation");
732 Memoize::flush_cache("percenttranslated");
735 sub urlto_with_orig_beautiful_urlpath($$) { #{{{
739 inject(name => "IkiWiki::beautify_urlpath", call => $origsubs{'beautify_urlpath'});
740 my $res=urlto($to, $from);
741 inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath);
746 sub percenttranslated ($) { #{{{
749 return gettext("N/A") unless istranslation($page);
750 my $file=srcfile($pagesources{$page});
751 my $masterfile = srcfile($pagesources{masterpage($page)});
754 push @masters,$masterfile;
756 "markdown" => (pagetype($masterfile) eq 'mdwn') ? 1 : 0,
758 my $doc=Locale::Po4a::Chooser::new('text',%options);
760 'po_in_name' => \@pos,
761 'file_in_name' => \@masters,
762 'file_in_charset' => 'utf-8',
763 'file_out_charset' => 'utf-8',
764 ) or error("[po/percenttranslated:$page]: failed to translate");
765 my ($percent,$hit,$queries) = $doc->stats();
769 sub languagename ($) { #{{{
772 return $config{po_master_language}{name}
773 if $code eq $config{po_master_language}{code};
774 return $config{po_slave_languages}{$code}
775 if defined $config{po_slave_languages}{$code};
779 sub otherlanguagesloop ($) { #{{{
783 my %otherpages=%{otherlanguages($page)};
784 while (my ($lang, $otherpage) = each %otherpages) {
785 if (istranslation($page) && masterpage($page) eq $otherpage) {
787 url => urlto_with_orig_beautiful_urlpath($otherpage, $page),
789 language => languagename($lang),
795 url => urlto_with_orig_beautiful_urlpath($otherpage, $page),
797 language => languagename($lang),
798 percent => percenttranslated($otherpage),
803 return -1 if $a->{code} eq $config{po_master_language}{code};
804 return 1 if $b->{code} eq $config{po_master_language}{code};
805 return $a->{language} cmp $b->{language};
809 sub homepageurl (;$) { #{{{
812 return urlto('', $page);
815 sub deletetranslations ($) { #{{{
816 my $deletedmasterfile=shift;
818 debug "po(deletetranslations): TODO: delete translations of $deletedmasterfile";
821 sub renametranslations (@) { #{{{
822 my ($oldpage, $newpage)=(shift, shift);
824 debug "po(renametranslations): TODO: rename translations of $oldpage to $newpage";
832 package IkiWiki::PageSpec;
837 sub match_istranslation ($;@) { #{{{
840 if (IkiWiki::Plugin::po::istranslation($page)) {
841 return IkiWiki::SuccessReason->new("is a translation page");
844 return IkiWiki::FailReason->new("is not a translation page");
848 sub match_istranslatable ($;@) { #{{{
851 if (IkiWiki::Plugin::po::istranslatable($page)) {
852 return IkiWiki::SuccessReason->new("is set as translatable in po_translatable_pages");
855 return IkiWiki::FailReason->new("is not set as translatable in po_translatable_pages");
859 sub match_lang ($$;@) { #{{{
863 my $regexp=IkiWiki::glob2re($wanted);
864 my $lang=IkiWiki::Plugin::po::lang($page);
865 if ($lang!~/^$regexp$/i) {
866 return IkiWiki::FailReason->new("file language is $lang, not $wanted");
869 return IkiWiki::SuccessReason->new("file language is $wanted");
873 sub match_currentlang ($$;@) { #{{{
878 return IkiWiki::FailReason->new("no location provided") unless exists $params{location};
880 my $currentlang=IkiWiki::Plugin::po::lang($params{location});
881 my $lang=IkiWiki::Plugin::po::lang($page);
883 if ($lang eq $currentlang) {
884 return IkiWiki::SuccessReason->new("file language is the same as current one, i.e. $currentlang");
887 return IkiWiki::FailReason->new("file language is $lang, whereas current language is $currentlang");