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 => "change", id => "po", call => \&change);
39 hook(type => "editcontent", id => "po", call => \&editcontent);
41 $origsubs{'bestlink'}=\&IkiWiki::bestlink;
42 inject(name => "IkiWiki::bestlink", call => \&mybestlink);
43 $origsubs{'beautify_urlpath'}=\&IkiWiki::beautify_urlpath;
44 inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath);
45 $origsubs{'targetpage'}=\&IkiWiki::targetpage;
46 inject(name => "IkiWiki::targetpage", call => \&mytargetpage);
47 $origsubs{'urlto'}=\&IkiWiki::urlto;
48 inject(name => "IkiWiki::urlto", call => \&myurlto);
57 # 2. Injected functions
58 # 3. Blackboxes for private data
67 sub getsetup () { #{{{
73 po_master_language => {
79 description => "master language (non-PO files)",
83 po_slave_languages => {
90 description => "slave languages (PO files)",
94 po_translatable_pages => {
96 example => "!*/Discussion",
97 description => "PageSpec controlling which pages are translatable",
98 link => "ikiwiki/PageSpec",
104 example => "current",
105 description => "internal linking behavior (default/current/negotiated)",
111 sub checkconfig () { #{{{
112 foreach my $field (qw{po_master_language po_slave_languages}) {
113 if (! exists $config{$field} || ! defined $config{$field}) {
114 error(sprintf(gettext("Must specify %s"), $field));
117 if (! (keys %{$config{po_slave_languages}})) {
118 error(gettext("At least one slave language must be defined in po_slave_languages"));
122 or error(sprintf(gettext("%s is not a valid language code"), $_));
123 } ($config{po_master_language}{code}, keys %{$config{po_slave_languages}});
124 if (! exists $config{po_translatable_pages} ||
125 ! defined $config{po_translatable_pages}) {
126 $config{po_translatable_pages}="";
128 if (! exists $config{po_link_to} ||
129 ! defined $config{po_link_to}) {
130 $config{po_link_to}='default';
133 $config{po_link_to} eq $_
134 } ('default', 'current', 'negotiated')) {
135 warn(sprintf(gettext('po_link_to=%s is not a valid setting, falling back to po_link_to=default'),
136 $config{po_link_to}));
137 $config{po_link_to}='default';
139 elsif ($config{po_link_to} eq "negotiated" && ! $config{usedirs}) {
140 warn(gettext('po_link_to=negotiated requires usedirs to be enabled, falling back to po_link_to=default'));
141 $config{po_link_to}='default';
143 push @{$config{wiki_file_prune_regexps}}, qr/\.pot$/;
146 sub needsbuild () { #{{{
147 my $needsbuild=shift;
149 # backup @needsbuild content so that change() can know whether
150 # a given master page was rendered because its source file was changed
151 @origneedsbuild=(@$needsbuild);
154 buildtranslationscache();
156 # make existing translations depend on the corresponding master page
157 foreach my $master (keys %translations) {
158 map add_depends($_, $master), values %{otherlanguages($master)};
162 # Massage the recorded state of internal links so that:
163 # - it matches the actually generated links, rather than the links as written
164 # in the pages' source
165 # - backlinks are consistent in all cases
168 my $page=$params{page};
169 my $content=$params{content};
171 return unless UNIVERSAL::can("IkiWiki::Plugin::link", "import");
173 if (istranslation($page)) {
174 foreach my $destpage (@{$links{$page}}) {
175 if (istranslatable($destpage)) {
176 # replace one occurence of $destpage in $links{$page}
177 # (we only want to replace the one that was added by
178 # IkiWiki::Plugin::link::scan, other occurences may be
179 # there for other reasons)
180 for (my $i=0; $i<@{$links{$page}}; $i++) {
181 if (@{$links{$page}}[$i] eq $destpage) {
182 @{$links{$page}}[$i] = $destpage . '.' . lang($page);
189 elsif (! istranslatable($page) && ! istranslation($page)) {
190 foreach my $destpage (@{$links{$page}}) {
191 if (istranslatable($destpage)) {
192 # make sure any destpage's translations has
193 # $page in its backlinks
194 push @{$links{$page}},
195 values %{otherlanguages($destpage)};
201 # We use filter to convert PO to the master page's format,
202 # since the rest of ikiwiki should not work on PO files.
203 sub filter (@) { #{{{
206 my $page = $params{page};
207 my $destpage = $params{destpage};
208 my $content = decode_utf8(encode_utf8($params{content}));
210 return $content if ( ! istranslation($page)
211 || alreadyfiltered($page, $destpage) );
213 # CRLF line terminators make poor Locale::Po4a feel bad
214 $content=~s/\r\n/\n/g;
216 # Implementation notes
218 # 1. Locale::Po4a reads/writes from/to files, and I'm too lazy
219 # to learn how to disguise a variable as a file.
220 # 2. There are incompatibilities between some File::Temp versions
221 # (including 0.18, bundled with Lenny's perl-modules package)
222 # and others (e.g. 0.20, previously present in the archive as
223 # a standalone package): under certain circumstances, some
224 # return a relative filename, whereas others return an absolute one;
225 # we here use this module in a way that is at least compatible
226 # with 0.18 and 0.20. Beware, hit'n'run refactorers!
227 my $infile = new File::Temp(TEMPLATE => "ikiwiki-po-filter-in.XXXXXXXXXX",
228 DIR => File::Spec->tmpdir,
229 UNLINK => 1)->filename;
230 my $outfile = new File::Temp(TEMPLATE => "ikiwiki-po-filter-out.XXXXXXXXXX",
231 DIR => File::Spec->tmpdir,
232 UNLINK => 1)->filename;
234 writefile(basename($infile), File::Spec->tmpdir, $content);
236 my $masterfile = srcfile($pagesources{masterpage($page)});
239 push @masters,$masterfile;
241 "markdown" => (pagetype($masterfile) eq 'mdwn') ? 1 : 0,
243 my $doc=Locale::Po4a::Chooser::new('text',%options);
245 'po_in_name' => \@pos,
246 'file_in_name' => \@masters,
247 'file_in_charset' => 'utf-8',
248 'file_out_charset' => 'utf-8',
249 ) or error("[po/filter:$page]: failed to translate");
250 $doc->write($outfile) or error("[po/filter:$page] could not write $outfile");
251 $content = readfile($outfile) or error("[po/filter:$page] could not read $outfile");
253 # Unlinking should happen automatically, thanks to File::Temp,
254 # but it does not work here, probably because of the way writefile()
255 # and Locale::Po4a::write() work.
256 unlink $infile, $outfile;
258 setalreadyfiltered($page, $destpage);
262 sub htmlize (@) { #{{{
265 my $page = $params{page};
266 my $content = $params{content};
268 # ignore PO files this plugin did not create
269 return $content unless istranslation($page);
271 # force content to be htmlize'd as if it was the same type as the master page
272 return IkiWiki::htmlize($page, $page,
273 pagetype(srcfile($pagesources{masterpage($page)})),
277 sub pagetemplate (@) { #{{{
279 my $page=$params{page};
280 my $destpage=$params{destpage};
281 my $template=$params{template};
283 my ($masterpage, $lang) = istranslation($page);
285 if (istranslation($page) && $template->query(name => "percenttranslated")) {
286 $template->param(percenttranslated => percenttranslated($page));
288 if ($template->query(name => "istranslation")) {
289 $template->param(istranslation => scalar istranslation($page));
291 if ($template->query(name => "istranslatable")) {
292 $template->param(istranslatable => istranslatable($page));
294 if ($template->query(name => "HOMEPAGEURL")) {
295 $template->param(homepageurl => homepageurl($page));
297 if ($template->query(name => "otherlanguages")) {
298 $template->param(otherlanguages => [otherlanguagesloop($page)]);
299 map add_depends($page, $_), (values %{otherlanguages($page)});
301 # Rely on IkiWiki::Render's genpage() to decide wether
302 # a discussion link should appear on $page; this is not
303 # totally accurate, though: some broken links may be generated
304 # when cgiurl is disabled.
305 # This compromise avoids some code duplication, and will probably
306 # prevent future breakage when ikiwiki internals change.
307 # Known limitations are preferred to future random bugs.
308 if ($template->param('discussionlink') && istranslation($page)) {
309 $template->param('discussionlink' => htmllink(
312 $masterpage . '/' . gettext("Discussion"),
315 linktext => gettext("Discussion"),
318 # Remove broken parentlink to ./index.html on home page's translations.
319 # It works because this hook has the "last" parameter set, to ensure it
320 # runs after parentlinks' own pagetemplate hook.
321 if ($template->param('parentlinks')
322 && istranslation($page)
323 && $masterpage eq "index") {
324 $template->param('parentlinks' => []);
331 my $updated_po_files=0;
333 # Refresh/create POT and PO files as needed.
334 foreach my $page (map pagename($_), @rendered) {
335 next unless istranslatable($page);
336 my $file=srcfile($pagesources{$page});
337 my $updated_pot_file=0;
338 # Only refresh Pot file if it does not exist, or if
339 # $pagesources{$page} was changed: don't if only the HTML was
340 # refreshed, e.g. because of a dependency.
341 if ((grep { $_ eq $pagesources{$page} } @origneedsbuild)
342 || ! -e potfile($file)) {
348 push @pofiles, $_ if ($updated_pot_file || ! -e $_);
351 refreshpofiles($file, @pofiles);
352 map { IkiWiki::rcs_add($_); } @pofiles if ($config{rcs});
357 if ($updated_po_files) {
358 # Check staged changes in.
360 IkiWiki::disable_commit_hook();
361 IkiWiki::rcs_commit_staged(gettext("updated PO files"),
362 "IkiWiki::Plugin::po::change", "127.0.0.1");
363 IkiWiki::enable_commit_hook();
364 IkiWiki::rcs_update();
366 # Reinitialize module's private variables.
367 resetalreadyfiltered();
368 resettranslationscache();
370 # Trigger a wiki refresh.
371 require IkiWiki::Render;
372 # without preliminary saveindex/loadindex, refresh()
373 # complains about a lot of uninitialized variables
374 IkiWiki::saveindex();
375 IkiWiki::loadindex();
377 IkiWiki::saveindex();
381 # As we're previewing or saving a page, the content may have
382 # changed, so tell the next filter() invocation it must not be lazy.
383 sub editcontent () { #{{{
386 unsetalreadyfiltered($params{page}, $params{page});
387 return $params{content};
392 # | Injected functions
395 # Implement po_link_to 'current' and 'negotiated' settings.
396 sub mybestlink ($$) { #{{{
400 my $res=$origsubs{'bestlink'}->(masterpage($page), $link);
402 && ($config{po_link_to} eq "current" || $config{po_link_to} eq "negotiated")
403 && istranslatable($res)
404 && istranslation($page)) {
405 return $res . "." . lang($page);
410 sub mybeautify_urlpath ($) { #{{{
413 my $res=$origsubs{'beautify_urlpath'}->($url);
414 if ($config{po_link_to} eq "negotiated") {
415 $res =~ s!/\Qindex.$config{po_master_language}{code}.$config{htmlext}\E$!/!;
416 $res =~ s!/\Qindex.$config{htmlext}\E$!/!;
418 $res =~ s!/\Qindex.$_.$config{htmlext}\E$!/!;
419 } (keys %{$config{po_slave_languages}});
424 sub mytargetpage ($$) { #{{{
428 if (istranslation($page) || istranslatable($page)) {
429 my ($masterpage, $lang) = (masterpage($page), lang($page));
430 if (! $config{usedirs} || $masterpage eq 'index') {
431 return $masterpage . "." . $lang . "." . $ext;
434 return $masterpage . "/index." . $lang . "." . $ext;
437 return $origsubs{'targetpage'}->($page, $ext);
440 sub myurlto ($$;$) { #{{{
445 # workaround hard-coded /index.$config{htmlext} in IkiWiki::urlto()
447 && $config{po_link_to} eq "current"
448 && istranslatable('index')) {
449 return IkiWiki::beautify_urlpath(IkiWiki::baseurl($from) . "index." . lang($from) . ".$config{htmlext}");
451 return $origsubs{'urlto'}->($to,$from,$absolute);
456 # | Blackboxes for private data
462 sub alreadyfiltered($$) { #{{{
466 return ( exists $filtered{$page}{$destpage}
467 && $filtered{$page}{$destpage} eq 1 );
470 sub setalreadyfiltered($$) { #{{{
474 $filtered{$page}{$destpage}=1;
477 sub unsetalreadyfiltered($$) { #{{{
481 if (exists $filtered{$page}{$destpage}) {
482 delete $filtered{$page}{$destpage};
486 sub resetalreadyfiltered() { #{{{
496 sub maybe_add_leading_slash ($;$) { #{{{
499 $add=1 unless defined $add;
500 return '/' . $str if $add;
504 sub istranslatablefile ($) { #{{{
507 return 0 unless defined $file;
508 return 0 if (defined pagetype($file) && pagetype($file) eq 'po');
509 return 0 if $file =~ /\.pot$/;
510 return 1 if pagespec_match(pagename($file), $config{po_translatable_pages});
514 sub istranslatable ($) { #{{{
518 return 1 if istranslatablefile($pagesources{$page});
522 sub _istranslation ($) { #{{{
525 my $hasleadingslash = ($page=~s#^/##);
526 my $file=$pagesources{$page};
527 return 0 unless (defined $file
528 && defined pagetype($file)
529 && pagetype($file) eq 'po');
530 return 0 if $file =~ /\.pot$/;
532 my ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
533 return 0 unless (defined $masterpage && defined $lang
534 && length $masterpage && length $lang
535 && defined $pagesources{$masterpage}
536 && defined $config{po_slave_languages}{$lang});
538 return (maybe_add_leading_slash($masterpage, $hasleadingslash), $lang)
539 if istranslatable($masterpage);
542 sub istranslation ($) { #{{{
545 if (1 < (my ($masterpage, $lang) = _istranslation($page))) {
546 my $hasleadingslash = ($masterpage=~s#^/##);
547 $translations{$masterpage}{$lang}=$page unless exists $translations{$masterpage}{$lang};
548 return (maybe_add_leading_slash($masterpage, $hasleadingslash), $lang);
553 sub masterpage ($) { #{{{
556 if ( 1 < (my ($masterpage, $lang) = _istranslation($page))) {
565 if (1 < (my ($masterpage, $lang) = _istranslation($page))) {
568 return $config{po_master_language}{code};
571 sub islanguagecode ($) { #{{{
574 return ($code =~ /^[a-z]{2}$/);
577 sub otherlanguage ($$) { #{{{
581 return masterpage($page) if $code eq $config{po_master_language}{code};
582 return masterpage($page) . '.' . $code;
585 sub otherlanguages ($) { #{{{
589 return \%ret unless (istranslation($page) || istranslatable($page));
590 my $curlang=lang($page);
592 ($config{po_master_language}{code}, keys %{$config{po_slave_languages}}) {
593 next if $lang eq $curlang;
594 $ret{$lang}=otherlanguage($page, $lang);
599 sub potfile ($) { #{{{
600 my $masterfile=shift;
602 (my $name, my $dir, my $suffix) = fileparse($masterfile, qr/\.[^.]*/);
603 $dir='' if $dir eq './';
604 return File::Spec->catpath('', $dir, $name . ".pot");
607 sub pofile ($$) { #{{{
608 my $masterfile=shift;
611 (my $name, my $dir, my $suffix) = fileparse($masterfile, qr/\.[^.]*/);
612 $dir='' if $dir eq './';
613 return File::Spec->catpath('', $dir, $name . "." . $lang . ".po");
616 sub pofiles ($) { #{{{
617 my $masterfile=shift;
619 return map pofile($masterfile, $_), (keys %{$config{po_slave_languages}});
622 sub refreshpot ($) { #{{{
623 my $masterfile=shift;
625 my $potfile=potfile($masterfile);
626 my %options = ("markdown" => (pagetype($masterfile) eq 'mdwn') ? 1 : 0);
627 my $doc=Locale::Po4a::Chooser::new('text',%options);
628 $doc->{TT}{utf_mode} = 1;
629 $doc->{TT}{file_in_charset} = 'utf-8';
630 $doc->{TT}{file_out_charset} = 'utf-8';
631 $doc->read($masterfile);
632 # let's cheat a bit to force porefs option to be passed to Locale::Po4a::Po;
633 # this is undocument use of internal Locale::Po4a::TransTractor's data,
634 # compulsory since this module prevents us from using the porefs option.
635 my %po_options = ('porefs' => 'none');
636 $doc->{TT}{po_out}=Locale::Po4a::Po->new(\%po_options);
637 $doc->{TT}{po_out}->set_charset('utf-8');
640 IkiWiki::prep_writefile(basename($potfile),dirname($potfile));
641 $doc->writepo($potfile);
644 sub refreshpofiles ($@) { #{{{
645 my $masterfile=shift;
648 my $potfile=potfile($masterfile);
649 error("[po/refreshpofiles] POT file ($potfile) does not exist") unless (-e $potfile);
651 foreach my $pofile (@pofiles) {
652 IkiWiki::prep_writefile(basename($pofile),dirname($pofile));
654 system("msgmerge", "-U", "--backup=none", $pofile, $potfile) == 0
655 or error("[po/refreshpofiles:$pofile] failed to update");
658 File::Copy::syscopy($potfile,$pofile)
659 or error("[po/refreshpofiles:$pofile] failed to copy the POT file");
664 sub buildtranslationscache() { #{{{
665 # use istranslation's side-effect
666 map istranslation($_), (keys %pagesources);
669 sub resettranslationscache() { #{{{
673 sub flushmemoizecache() { #{{{
674 Memoize::flush_cache("istranslatable");
675 Memoize::flush_cache("_istranslation");
676 Memoize::flush_cache("percenttranslated");
679 sub urlto_with_orig_beautiful_urlpath($$) { #{{{
683 inject(name => "IkiWiki::beautify_urlpath", call => $origsubs{'beautify_urlpath'});
684 my $res=urlto($to, $from);
685 inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath);
690 sub percenttranslated ($) { #{{{
693 return gettext("N/A") unless istranslation($page);
694 my $file=srcfile($pagesources{$page});
695 my $masterfile = srcfile($pagesources{masterpage($page)});
698 push @masters,$masterfile;
700 "markdown" => (pagetype($masterfile) eq 'mdwn') ? 1 : 0,
702 my $doc=Locale::Po4a::Chooser::new('text',%options);
704 'po_in_name' => \@pos,
705 'file_in_name' => \@masters,
706 'file_in_charset' => 'utf-8',
707 'file_out_charset' => 'utf-8',
708 ) or error("[po/percenttranslated:$page]: failed to translate");
709 my ($percent,$hit,$queries) = $doc->stats();
713 sub languagename ($) { #{{{
716 return $config{po_master_language}{name}
717 if $code eq $config{po_master_language}{code};
718 return $config{po_slave_languages}{$code}
719 if defined $config{po_slave_languages}{$code};
723 sub otherlanguagesloop ($) { #{{{
727 my %otherpages=%{otherlanguages($page)};
728 while (my ($lang, $otherpage) = each %otherpages) {
729 if (istranslation($page) && masterpage($page) eq $otherpage) {
731 url => urlto_with_orig_beautiful_urlpath($otherpage, $page),
733 language => languagename($lang),
739 url => urlto_with_orig_beautiful_urlpath($otherpage, $page),
741 language => languagename($lang),
742 percent => percenttranslated($otherpage),
747 return -1 if $a->{code} eq $config{po_master_language}{code};
748 return 1 if $b->{code} eq $config{po_master_language}{code};
749 return $a->{language} cmp $b->{language};
753 sub homepageurl (;$) { #{{{
756 return urlto('', $page);
763 package IkiWiki::PageSpec;
768 sub match_istranslation ($;@) { #{{{
771 if (IkiWiki::Plugin::po::istranslation($page)) {
772 return IkiWiki::SuccessReason->new("is a translation page");
775 return IkiWiki::FailReason->new("is not a translation page");
779 sub match_istranslatable ($;@) { #{{{
782 if (IkiWiki::Plugin::po::istranslatable($page)) {
783 return IkiWiki::SuccessReason->new("is set as translatable in po_translatable_pages");
786 return IkiWiki::FailReason->new("is not set as translatable in po_translatable_pages");
790 sub match_lang ($$;@) { #{{{
794 my $regexp=IkiWiki::glob2re($wanted);
795 my $lang=IkiWiki::Plugin::po::lang($page);
796 if ($lang!~/^$regexp$/i) {
797 return IkiWiki::FailReason->new("file language is $lang, not $wanted");
800 return IkiWiki::SuccessReason->new("file language is $wanted");
804 sub match_currentlang ($$;@) { #{{{
809 return IkiWiki::FailReason->new("no location provided") unless exists $params{location};
811 my $currentlang=IkiWiki::Plugin::po::lang($params{location});
812 my $lang=IkiWiki::Plugin::po::lang($page);
814 if ($lang eq $currentlang) {
815 return IkiWiki::SuccessReason->new("file language is the same as current one, i.e. $currentlang");
818 return IkiWiki::FailReason->new("file language is $lang, whereas current language is $currentlang");