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) {
393 gettext("updated PO files"),
394 "IkiWiki::Plugin::po::change");
398 # As we're previewing or saving a page, the content may have
399 # changed, so tell the next filter() invocation it must not be lazy.
400 sub editcontent () { #{{{
403 unsetalreadyfiltered($params{page}, $params{page});
404 return $params{content};
409 # | Injected functions
412 # Implement po_link_to 'current' and 'negotiated' settings.
413 sub mybestlink ($$) { #{{{
417 my $res=$origsubs{'bestlink'}->(masterpage($page), $link);
419 && ($config{po_link_to} eq "current" || $config{po_link_to} eq "negotiated")
420 && istranslatable($res)
421 && istranslation($page)) {
422 return $res . "." . lang($page);
427 sub mybeautify_urlpath ($) { #{{{
430 my $res=$origsubs{'beautify_urlpath'}->($url);
431 if ($config{po_link_to} eq "negotiated") {
432 $res =~ s!/\Qindex.$config{po_master_language}{code}.$config{htmlext}\E$!/!;
433 $res =~ s!/\Qindex.$config{htmlext}\E$!/!;
435 $res =~ s!/\Qindex.$_.$config{htmlext}\E$!/!;
436 } (keys %{$config{po_slave_languages}});
441 sub mytargetpage ($$) { #{{{
445 if (istranslation($page) || istranslatable($page)) {
446 my ($masterpage, $lang) = (masterpage($page), lang($page));
447 if (! $config{usedirs} || $masterpage eq 'index') {
448 return $masterpage . "." . $lang . "." . $ext;
451 return $masterpage . "/index." . $lang . "." . $ext;
454 return $origsubs{'targetpage'}->($page, $ext);
457 sub myurlto ($$;$) { #{{{
462 # workaround hard-coded /index.$config{htmlext} in IkiWiki::urlto()
464 && $config{po_link_to} eq "current"
465 && istranslatable('index')) {
466 return IkiWiki::beautify_urlpath(IkiWiki::baseurl($from) . "index." . lang($from) . ".$config{htmlext}");
468 return $origsubs{'urlto'}->($to,$from,$absolute);
473 # | Blackboxes for private data
479 sub alreadyfiltered($$) { #{{{
483 return ( exists $filtered{$page}{$destpage}
484 && $filtered{$page}{$destpage} eq 1 );
487 sub setalreadyfiltered($$) { #{{{
491 $filtered{$page}{$destpage}=1;
494 sub unsetalreadyfiltered($$) { #{{{
498 if (exists $filtered{$page}{$destpage}) {
499 delete $filtered{$page}{$destpage};
503 sub resetalreadyfiltered() { #{{{
512 sub maybe_add_leading_slash ($;$) { #{{{
515 $add=1 unless defined $add;
516 return '/' . $str if $add;
520 sub istranslatablefile ($) { #{{{
523 return 0 unless defined $file;
524 return 0 if (defined pagetype($file) && pagetype($file) eq 'po');
525 return 0 if $file =~ /\.pot$/;
526 return 1 if pagespec_match(pagename($file), $config{po_translatable_pages});
530 sub istranslatable ($) { #{{{
534 return 1 if istranslatablefile($pagesources{$page});
538 sub _istranslation ($) { #{{{
541 my $hasleadingslash = ($page=~s#^/##);
542 my $file=$pagesources{$page};
543 return 0 unless (defined $file
544 && defined pagetype($file)
545 && pagetype($file) eq 'po');
546 return 0 if $file =~ /\.pot$/;
548 my ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
549 return 0 unless (defined $masterpage && defined $lang
550 && length $masterpage && length $lang
551 && defined $pagesources{$masterpage}
552 && defined $config{po_slave_languages}{$lang});
554 return (maybe_add_leading_slash($masterpage, $hasleadingslash), $lang)
555 if istranslatable($masterpage);
558 sub istranslation ($) { #{{{
561 if (1 < (my ($masterpage, $lang) = _istranslation($page))) {
562 my $hasleadingslash = ($masterpage=~s#^/##);
563 $translations{$masterpage}{$lang}=$page unless exists $translations{$masterpage}{$lang};
564 return (maybe_add_leading_slash($masterpage, $hasleadingslash), $lang);
569 sub masterpage ($) { #{{{
572 if ( 1 < (my ($masterpage, $lang) = _istranslation($page))) {
581 if (1 < (my ($masterpage, $lang) = _istranslation($page))) {
584 return $config{po_master_language}{code};
587 sub islanguagecode ($) { #{{{
590 return ($code =~ /^[a-z]{2}$/);
593 sub otherlanguage ($$) { #{{{
597 return masterpage($page) if $code eq $config{po_master_language}{code};
598 return masterpage($page) . '.' . $code;
601 sub otherlanguages ($) { #{{{
605 return \%ret unless (istranslation($page) || istranslatable($page));
606 my $curlang=lang($page);
608 ($config{po_master_language}{code}, keys %{$config{po_slave_languages}}) {
609 next if $lang eq $curlang;
610 $ret{$lang}=otherlanguage($page, $lang);
615 sub potfile ($) { #{{{
616 my $masterfile=shift;
618 (my $name, my $dir, my $suffix) = fileparse($masterfile, qr/\.[^.]*/);
619 $dir='' if $dir eq './';
620 return File::Spec->catpath('', $dir, $name . ".pot");
623 sub pofile ($$) { #{{{
624 my $masterfile=shift;
627 (my $name, my $dir, my $suffix) = fileparse($masterfile, qr/\.[^.]*/);
628 $dir='' if $dir eq './';
629 return File::Spec->catpath('', $dir, $name . "." . $lang . ".po");
632 sub pofiles ($) { #{{{
633 my $masterfile=shift;
635 return map pofile($masterfile, $_), (keys %{$config{po_slave_languages}});
638 sub refreshpot ($) { #{{{
639 my $masterfile=shift;
641 my $potfile=potfile($masterfile);
642 my %options = ("markdown" => (pagetype($masterfile) eq 'mdwn') ? 1 : 0);
643 my $doc=Locale::Po4a::Chooser::new('text',%options);
644 $doc->{TT}{utf_mode} = 1;
645 $doc->{TT}{file_in_charset} = 'utf-8';
646 $doc->{TT}{file_out_charset} = 'utf-8';
647 $doc->read($masterfile);
648 # let's cheat a bit to force porefs option to be passed to Locale::Po4a::Po;
649 # this is undocument use of internal Locale::Po4a::TransTractor's data,
650 # compulsory since this module prevents us from using the porefs option.
651 my %po_options = ('porefs' => 'none');
652 $doc->{TT}{po_out}=Locale::Po4a::Po->new(\%po_options);
653 $doc->{TT}{po_out}->set_charset('utf-8');
656 IkiWiki::prep_writefile(basename($potfile),dirname($potfile));
657 $doc->writepo($potfile);
660 sub refreshpofiles ($@) { #{{{
661 my $masterfile=shift;
664 my $potfile=potfile($masterfile);
665 error("[po/refreshpofiles] POT file ($potfile) does not exist") unless (-e $potfile);
667 foreach my $pofile (@pofiles) {
668 IkiWiki::prep_writefile(basename($pofile),dirname($pofile));
670 system("msgmerge", "-U", "--backup=none", $pofile, $potfile) == 0
671 or error("[po/refreshpofiles:$pofile] failed to update");
674 File::Copy::syscopy($potfile,$pofile)
675 or error("[po/refreshpofiles:$pofile] failed to copy the POT file");
680 sub buildtranslationscache() { #{{{
681 # use istranslation's side-effect
682 map istranslation($_), (keys %pagesources);
685 sub resettranslationscache() { #{{{
689 sub flushmemoizecache() { #{{{
690 Memoize::flush_cache("istranslatable");
691 Memoize::flush_cache("_istranslation");
692 Memoize::flush_cache("percenttranslated");
695 sub urlto_with_orig_beautiful_urlpath($$) { #{{{
699 inject(name => "IkiWiki::beautify_urlpath", call => $origsubs{'beautify_urlpath'});
700 my $res=urlto($to, $from);
701 inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath);
706 sub percenttranslated ($) { #{{{
709 return gettext("N/A") unless istranslation($page);
710 my $file=srcfile($pagesources{$page});
711 my $masterfile = srcfile($pagesources{masterpage($page)});
714 push @masters,$masterfile;
716 "markdown" => (pagetype($masterfile) eq 'mdwn') ? 1 : 0,
718 my $doc=Locale::Po4a::Chooser::new('text',%options);
720 'po_in_name' => \@pos,
721 'file_in_name' => \@masters,
722 'file_in_charset' => 'utf-8',
723 'file_out_charset' => 'utf-8',
724 ) or error("[po/percenttranslated:$page]: failed to translate");
725 my ($percent,$hit,$queries) = $doc->stats();
729 sub languagename ($) { #{{{
732 return $config{po_master_language}{name}
733 if $code eq $config{po_master_language}{code};
734 return $config{po_slave_languages}{$code}
735 if defined $config{po_slave_languages}{$code};
739 sub otherlanguagesloop ($) { #{{{
743 my %otherpages=%{otherlanguages($page)};
744 while (my ($lang, $otherpage) = each %otherpages) {
745 if (istranslation($page) && masterpage($page) eq $otherpage) {
747 url => urlto_with_orig_beautiful_urlpath($otherpage, $page),
749 language => languagename($lang),
755 url => urlto_with_orig_beautiful_urlpath($otherpage, $page),
757 language => languagename($lang),
758 percent => percenttranslated($otherpage),
763 return -1 if $a->{code} eq $config{po_master_language}{code};
764 return 1 if $b->{code} eq $config{po_master_language}{code};
765 return $a->{language} cmp $b->{language};
769 sub homepageurl (;$) { #{{{
772 return urlto('', $page);
775 sub deletetranslations ($) { #{{{
776 my $deletedmasterfile=shift;
778 my $deletedmasterpage=pagename($deletedmasterfile);
781 my $file = newpagefile($deletedmasterpage.'.'.$_, 'po');
782 my $absfile = "$config{srcdir}/$file";
783 if (-e $absfile && ! -l $absfile && ! -d $absfile) {
784 push @todelete, $file;
786 } keys %{$config{po_slave_languages}};
790 IkiWiki::rcs_remove($_);
793 IkiWiki::prune("$config{srcdir}/$_");
797 if (scalar @todelete) {
799 gettext("removed obsolete PO files"),
800 "IkiWiki::Plugin::po::deletetranslations");
804 sub commit_and_refresh ($$) { #{{{
805 my ($msg, $author) = (shift, shift);
808 IkiWiki::disable_commit_hook();
809 IkiWiki::rcs_commit_staged($msg, $author, "127.0.0.1");
810 IkiWiki::enable_commit_hook();
811 IkiWiki::rcs_update();
813 # Reinitialize module's private variables.
814 resetalreadyfiltered();
815 resettranslationscache();
817 # Trigger a wiki refresh.
818 require IkiWiki::Render;
819 # without preliminary saveindex/loadindex, refresh()
820 # complains about a lot of uninitialized variables
821 IkiWiki::saveindex();
822 IkiWiki::loadindex();
824 IkiWiki::saveindex();
831 package IkiWiki::PageSpec;
836 sub match_istranslation ($;@) { #{{{
839 if (IkiWiki::Plugin::po::istranslation($page)) {
840 return IkiWiki::SuccessReason->new("is a translation page");
843 return IkiWiki::FailReason->new("is not a translation page");
847 sub match_istranslatable ($;@) { #{{{
850 if (IkiWiki::Plugin::po::istranslatable($page)) {
851 return IkiWiki::SuccessReason->new("is set as translatable in po_translatable_pages");
854 return IkiWiki::FailReason->new("is not set as translatable in po_translatable_pages");
858 sub match_lang ($$;@) { #{{{
862 my $regexp=IkiWiki::glob2re($wanted);
863 my $lang=IkiWiki::Plugin::po::lang($page);
864 if ($lang!~/^$regexp$/i) {
865 return IkiWiki::FailReason->new("file language is $lang, not $wanted");
868 return IkiWiki::SuccessReason->new("file language is $wanted");
872 sub match_currentlang ($$;@) { #{{{
877 return IkiWiki::FailReason->new("no location provided") unless exists $params{location};
879 my $currentlang=IkiWiki::Plugin::po::lang($params{location});
880 my $lang=IkiWiki::Plugin::po::lang($page);
882 if ($lang eq $currentlang) {
883 return IkiWiki::SuccessReason->new("file language is the same as current one, i.e. $currentlang");
886 return IkiWiki::FailReason->new("file language is $lang, whereas current language is $currentlang");