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 $file (@rendered) {
335 next unless istranslatablefile($file);
336 my $page=pagename($file);
337 my $masterfile=srcfile($file);
338 my $updated_pot_file=0;
339 # Only refresh Pot file if it does not exist, or if
340 # $pagesources{$page} was changed: don't if only the HTML was
341 # refreshed, e.g. because of a dependency.
342 if ((grep { $_ eq $pagesources{$page} } @origneedsbuild)
343 || ! -e potfile($masterfile)) {
344 refreshpot($masterfile);
349 push @pofiles, $_ if ($updated_pot_file || ! -e $_);
350 } (pofiles($masterfile));
352 refreshpofiles($masterfile, @pofiles);
353 map { IkiWiki::rcs_add($_); } @pofiles if ($config{rcs});
358 if ($updated_po_files) {
359 # Check staged changes in.
361 IkiWiki::disable_commit_hook();
362 IkiWiki::rcs_commit_staged(gettext("updated PO files"),
363 "IkiWiki::Plugin::po::change", "127.0.0.1");
364 IkiWiki::enable_commit_hook();
365 IkiWiki::rcs_update();
367 # Reinitialize module's private variables.
368 resetalreadyfiltered();
369 resettranslationscache();
371 # Trigger a wiki refresh.
372 require IkiWiki::Render;
373 # without preliminary saveindex/loadindex, refresh()
374 # complains about a lot of uninitialized variables
375 IkiWiki::saveindex();
376 IkiWiki::loadindex();
378 IkiWiki::saveindex();
382 # As we're previewing or saving a page, the content may have
383 # changed, so tell the next filter() invocation it must not be lazy.
384 sub editcontent () { #{{{
387 unsetalreadyfiltered($params{page}, $params{page});
388 return $params{content};
393 # | Injected functions
396 # Implement po_link_to 'current' and 'negotiated' settings.
397 sub mybestlink ($$) { #{{{
401 my $res=$origsubs{'bestlink'}->(masterpage($page), $link);
403 && ($config{po_link_to} eq "current" || $config{po_link_to} eq "negotiated")
404 && istranslatable($res)
405 && istranslation($page)) {
406 return $res . "." . lang($page);
411 sub mybeautify_urlpath ($) { #{{{
414 my $res=$origsubs{'beautify_urlpath'}->($url);
415 if ($config{po_link_to} eq "negotiated") {
416 $res =~ s!/\Qindex.$config{po_master_language}{code}.$config{htmlext}\E$!/!;
417 $res =~ s!/\Qindex.$config{htmlext}\E$!/!;
419 $res =~ s!/\Qindex.$_.$config{htmlext}\E$!/!;
420 } (keys %{$config{po_slave_languages}});
425 sub mytargetpage ($$) { #{{{
429 if (istranslation($page) || istranslatable($page)) {
430 my ($masterpage, $lang) = (masterpage($page), lang($page));
431 if (! $config{usedirs} || $masterpage eq 'index') {
432 return $masterpage . "." . $lang . "." . $ext;
435 return $masterpage . "/index." . $lang . "." . $ext;
438 return $origsubs{'targetpage'}->($page, $ext);
441 sub myurlto ($$;$) { #{{{
446 # workaround hard-coded /index.$config{htmlext} in IkiWiki::urlto()
448 && $config{po_link_to} eq "current"
449 && istranslatable('index')) {
450 return IkiWiki::beautify_urlpath(IkiWiki::baseurl($from) . "index." . lang($from) . ".$config{htmlext}");
452 return $origsubs{'urlto'}->($to,$from,$absolute);
457 # | Blackboxes for private data
463 sub alreadyfiltered($$) { #{{{
467 return ( exists $filtered{$page}{$destpage}
468 && $filtered{$page}{$destpage} eq 1 );
471 sub setalreadyfiltered($$) { #{{{
475 $filtered{$page}{$destpage}=1;
478 sub unsetalreadyfiltered($$) { #{{{
482 if (exists $filtered{$page}{$destpage}) {
483 delete $filtered{$page}{$destpage};
487 sub resetalreadyfiltered() { #{{{
497 sub maybe_add_leading_slash ($;$) { #{{{
500 $add=1 unless defined $add;
501 return '/' . $str if $add;
505 sub istranslatablefile ($) { #{{{
508 return 0 unless defined $file;
509 return 0 if (defined pagetype($file) && pagetype($file) eq 'po');
510 return 0 if $file =~ /\.pot$/;
511 return 1 if pagespec_match(pagename($file), $config{po_translatable_pages});
515 sub istranslatable ($) { #{{{
519 return 1 if istranslatablefile($pagesources{$page});
523 sub _istranslation ($) { #{{{
526 my $hasleadingslash = ($page=~s#^/##);
527 my $file=$pagesources{$page};
528 return 0 unless (defined $file
529 && defined pagetype($file)
530 && pagetype($file) eq 'po');
531 return 0 if $file =~ /\.pot$/;
533 my ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
534 return 0 unless (defined $masterpage && defined $lang
535 && length $masterpage && length $lang
536 && defined $pagesources{$masterpage}
537 && defined $config{po_slave_languages}{$lang});
539 return (maybe_add_leading_slash($masterpage, $hasleadingslash), $lang)
540 if istranslatable($masterpage);
543 sub istranslation ($) { #{{{
546 if (1 < (my ($masterpage, $lang) = _istranslation($page))) {
547 my $hasleadingslash = ($masterpage=~s#^/##);
548 $translations{$masterpage}{$lang}=$page unless exists $translations{$masterpage}{$lang};
549 return (maybe_add_leading_slash($masterpage, $hasleadingslash), $lang);
554 sub masterpage ($) { #{{{
557 if ( 1 < (my ($masterpage, $lang) = _istranslation($page))) {
566 if (1 < (my ($masterpage, $lang) = _istranslation($page))) {
569 return $config{po_master_language}{code};
572 sub islanguagecode ($) { #{{{
575 return ($code =~ /^[a-z]{2}$/);
578 sub otherlanguage ($$) { #{{{
582 return masterpage($page) if $code eq $config{po_master_language}{code};
583 return masterpage($page) . '.' . $code;
586 sub otherlanguages ($) { #{{{
590 return \%ret unless (istranslation($page) || istranslatable($page));
591 my $curlang=lang($page);
593 ($config{po_master_language}{code}, keys %{$config{po_slave_languages}}) {
594 next if $lang eq $curlang;
595 $ret{$lang}=otherlanguage($page, $lang);
600 sub potfile ($) { #{{{
601 my $masterfile=shift;
603 (my $name, my $dir, my $suffix) = fileparse($masterfile, qr/\.[^.]*/);
604 $dir='' if $dir eq './';
605 return File::Spec->catpath('', $dir, $name . ".pot");
608 sub pofile ($$) { #{{{
609 my $masterfile=shift;
612 (my $name, my $dir, my $suffix) = fileparse($masterfile, qr/\.[^.]*/);
613 $dir='' if $dir eq './';
614 return File::Spec->catpath('', $dir, $name . "." . $lang . ".po");
617 sub pofiles ($) { #{{{
618 my $masterfile=shift;
620 return map pofile($masterfile, $_), (keys %{$config{po_slave_languages}});
623 sub refreshpot ($) { #{{{
624 my $masterfile=shift;
626 my $potfile=potfile($masterfile);
627 my %options = ("markdown" => (pagetype($masterfile) eq 'mdwn') ? 1 : 0);
628 my $doc=Locale::Po4a::Chooser::new('text',%options);
629 $doc->{TT}{utf_mode} = 1;
630 $doc->{TT}{file_in_charset} = 'utf-8';
631 $doc->{TT}{file_out_charset} = 'utf-8';
632 $doc->read($masterfile);
633 # let's cheat a bit to force porefs option to be passed to Locale::Po4a::Po;
634 # this is undocument use of internal Locale::Po4a::TransTractor's data,
635 # compulsory since this module prevents us from using the porefs option.
636 my %po_options = ('porefs' => 'none');
637 $doc->{TT}{po_out}=Locale::Po4a::Po->new(\%po_options);
638 $doc->{TT}{po_out}->set_charset('utf-8');
641 IkiWiki::prep_writefile(basename($potfile),dirname($potfile));
642 $doc->writepo($potfile);
645 sub refreshpofiles ($@) { #{{{
646 my $masterfile=shift;
649 my $potfile=potfile($masterfile);
650 error("[po/refreshpofiles] POT file ($potfile) does not exist") unless (-e $potfile);
652 foreach my $pofile (@pofiles) {
653 IkiWiki::prep_writefile(basename($pofile),dirname($pofile));
655 system("msgmerge", "-U", "--backup=none", $pofile, $potfile) == 0
656 or error("[po/refreshpofiles:$pofile] failed to update");
659 File::Copy::syscopy($potfile,$pofile)
660 or error("[po/refreshpofiles:$pofile] failed to copy the POT file");
665 sub buildtranslationscache() { #{{{
666 # use istranslation's side-effect
667 map istranslation($_), (keys %pagesources);
670 sub resettranslationscache() { #{{{
674 sub flushmemoizecache() { #{{{
675 Memoize::flush_cache("istranslatable");
676 Memoize::flush_cache("_istranslation");
677 Memoize::flush_cache("percenttranslated");
680 sub urlto_with_orig_beautiful_urlpath($$) { #{{{
684 inject(name => "IkiWiki::beautify_urlpath", call => $origsubs{'beautify_urlpath'});
685 my $res=urlto($to, $from);
686 inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath);
691 sub percenttranslated ($) { #{{{
694 return gettext("N/A") unless istranslation($page);
695 my $file=srcfile($pagesources{$page});
696 my $masterfile = srcfile($pagesources{masterpage($page)});
699 push @masters,$masterfile;
701 "markdown" => (pagetype($masterfile) eq 'mdwn') ? 1 : 0,
703 my $doc=Locale::Po4a::Chooser::new('text',%options);
705 'po_in_name' => \@pos,
706 'file_in_name' => \@masters,
707 'file_in_charset' => 'utf-8',
708 'file_out_charset' => 'utf-8',
709 ) or error("[po/percenttranslated:$page]: failed to translate");
710 my ($percent,$hit,$queries) = $doc->stats();
714 sub languagename ($) { #{{{
717 return $config{po_master_language}{name}
718 if $code eq $config{po_master_language}{code};
719 return $config{po_slave_languages}{$code}
720 if defined $config{po_slave_languages}{$code};
724 sub otherlanguagesloop ($) { #{{{
728 my %otherpages=%{otherlanguages($page)};
729 while (my ($lang, $otherpage) = each %otherpages) {
730 if (istranslation($page) && masterpage($page) eq $otherpage) {
732 url => urlto_with_orig_beautiful_urlpath($otherpage, $page),
734 language => languagename($lang),
740 url => urlto_with_orig_beautiful_urlpath($otherpage, $page),
742 language => languagename($lang),
743 percent => percenttranslated($otherpage),
748 return -1 if $a->{code} eq $config{po_master_language}{code};
749 return 1 if $b->{code} eq $config{po_master_language}{code};
750 return $a->{language} cmp $b->{language};
754 sub homepageurl (;$) { #{{{
757 return urlto('', $page);
764 package IkiWiki::PageSpec;
769 sub match_istranslation ($;@) { #{{{
772 if (IkiWiki::Plugin::po::istranslation($page)) {
773 return IkiWiki::SuccessReason->new("is a translation page");
776 return IkiWiki::FailReason->new("is not a translation page");
780 sub match_istranslatable ($;@) { #{{{
783 if (IkiWiki::Plugin::po::istranslatable($page)) {
784 return IkiWiki::SuccessReason->new("is set as translatable in po_translatable_pages");
787 return IkiWiki::FailReason->new("is not set as translatable in po_translatable_pages");
791 sub match_lang ($$;@) { #{{{
795 my $regexp=IkiWiki::glob2re($wanted);
796 my $lang=IkiWiki::Plugin::po::lang($page);
797 if ($lang!~/^$regexp$/i) {
798 return IkiWiki::FailReason->new("file language is $lang, not $wanted");
801 return IkiWiki::SuccessReason->new("file language is $wanted");
805 sub match_currentlang ($$;@) { #{{{
810 return IkiWiki::FailReason->new("no location provided") unless exists $params{location};
812 my $currentlang=IkiWiki::Plugin::po::lang($params{location});
813 my $lang=IkiWiki::Plugin::po::lang($page);
815 if ($lang eq $currentlang) {
816 return IkiWiki::SuccessReason->new("file language is the same as current one, i.e. $currentlang");
819 return IkiWiki::FailReason->new("file language is $lang, whereas current language is $currentlang");