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 istranslatable ($) { #{{{
508 my $file=$pagesources{$page};
510 return 0 unless defined $file;
511 return 0 if (defined pagetype($file) && pagetype($file) eq 'po');
512 return 0 if $file =~ /\.pot$/;
513 return 1 if pagespec_match($page, $config{po_translatable_pages});
517 sub _istranslation ($) { #{{{
520 my $hasleadingslash = ($page=~s#^/##);
521 my $file=$pagesources{$page};
522 return 0 unless (defined $file
523 && defined pagetype($file)
524 && pagetype($file) eq 'po');
525 return 0 if $file =~ /\.pot$/;
527 my ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
528 return 0 unless (defined $masterpage && defined $lang
529 && length $masterpage && length $lang
530 && defined $pagesources{$masterpage}
531 && defined $config{po_slave_languages}{$lang});
533 return (maybe_add_leading_slash($masterpage, $hasleadingslash), $lang)
534 if istranslatable($masterpage);
537 sub istranslation ($) { #{{{
540 if (1 < (my ($masterpage, $lang) = _istranslation($page))) {
541 my $hasleadingslash = ($masterpage=~s#^/##);
542 $translations{$masterpage}{$lang}=$page unless exists $translations{$masterpage}{$lang};
543 return (maybe_add_leading_slash($masterpage, $hasleadingslash), $lang);
548 sub masterpage ($) { #{{{
551 if ( 1 < (my ($masterpage, $lang) = _istranslation($page))) {
560 if (1 < (my ($masterpage, $lang) = _istranslation($page))) {
563 return $config{po_master_language}{code};
566 sub islanguagecode ($) { #{{{
569 return ($code =~ /^[a-z]{2}$/);
572 sub otherlanguage ($$) { #{{{
576 return masterpage($page) if $code eq $config{po_master_language}{code};
577 return masterpage($page) . '.' . $code;
580 sub otherlanguages ($) { #{{{
584 return \%ret unless (istranslation($page) || istranslatable($page));
585 my $curlang=lang($page);
587 ($config{po_master_language}{code}, keys %{$config{po_slave_languages}}) {
588 next if $lang eq $curlang;
589 $ret{$lang}=otherlanguage($page, $lang);
594 sub potfile ($) { #{{{
595 my $masterfile=shift;
597 (my $name, my $dir, my $suffix) = fileparse($masterfile, qr/\.[^.]*/);
598 $dir='' if $dir eq './';
599 return File::Spec->catpath('', $dir, $name . ".pot");
602 sub pofile ($$) { #{{{
603 my $masterfile=shift;
606 (my $name, my $dir, my $suffix) = fileparse($masterfile, qr/\.[^.]*/);
607 $dir='' if $dir eq './';
608 return File::Spec->catpath('', $dir, $name . "." . $lang . ".po");
611 sub pofiles ($) { #{{{
612 my $masterfile=shift;
614 return map pofile($masterfile, $_), (keys %{$config{po_slave_languages}});
617 sub refreshpot ($) { #{{{
618 my $masterfile=shift;
620 my $potfile=potfile($masterfile);
621 my %options = ("markdown" => (pagetype($masterfile) eq 'mdwn') ? 1 : 0);
622 my $doc=Locale::Po4a::Chooser::new('text',%options);
623 $doc->{TT}{utf_mode} = 1;
624 $doc->{TT}{file_in_charset} = 'utf-8';
625 $doc->{TT}{file_out_charset} = 'utf-8';
626 $doc->read($masterfile);
627 # let's cheat a bit to force porefs option to be passed to Locale::Po4a::Po;
628 # this is undocument use of internal Locale::Po4a::TransTractor's data,
629 # compulsory since this module prevents us from using the porefs option.
630 my %po_options = ('porefs' => 'none');
631 $doc->{TT}{po_out}=Locale::Po4a::Po->new(\%po_options);
632 $doc->{TT}{po_out}->set_charset('utf-8');
635 IkiWiki::prep_writefile(basename($potfile),dirname($potfile));
636 $doc->writepo($potfile);
639 sub refreshpofiles ($@) { #{{{
640 my $masterfile=shift;
643 my $potfile=potfile($masterfile);
644 error("[po/refreshpofiles] POT file ($potfile) does not exist") unless (-e $potfile);
646 foreach my $pofile (@pofiles) {
647 IkiWiki::prep_writefile(basename($pofile),dirname($pofile));
649 system("msgmerge", "-U", "--backup=none", $pofile, $potfile) == 0
650 or error("[po/refreshpofiles:$pofile] failed to update");
653 File::Copy::syscopy($potfile,$pofile)
654 or error("[po/refreshpofiles:$pofile] failed to copy the POT file");
659 sub buildtranslationscache() { #{{{
660 # use istranslation's side-effect
661 map istranslation($_), (keys %pagesources);
664 sub resettranslationscache() { #{{{
668 sub flushmemoizecache() { #{{{
669 Memoize::flush_cache("istranslatable");
670 Memoize::flush_cache("_istranslation");
671 Memoize::flush_cache("percenttranslated");
674 sub urlto_with_orig_beautiful_urlpath($$) { #{{{
678 inject(name => "IkiWiki::beautify_urlpath", call => $origsubs{'beautify_urlpath'});
679 my $res=urlto($to, $from);
680 inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath);
685 sub percenttranslated ($) { #{{{
688 return gettext("N/A") unless istranslation($page);
689 my $file=srcfile($pagesources{$page});
690 my $masterfile = srcfile($pagesources{masterpage($page)});
693 push @masters,$masterfile;
695 "markdown" => (pagetype($masterfile) eq 'mdwn') ? 1 : 0,
697 my $doc=Locale::Po4a::Chooser::new('text',%options);
699 'po_in_name' => \@pos,
700 'file_in_name' => \@masters,
701 'file_in_charset' => 'utf-8',
702 'file_out_charset' => 'utf-8',
703 ) or error("[po/percenttranslated:$page]: failed to translate");
704 my ($percent,$hit,$queries) = $doc->stats();
708 sub languagename ($) { #{{{
711 return $config{po_master_language}{name}
712 if $code eq $config{po_master_language}{code};
713 return $config{po_slave_languages}{$code}
714 if defined $config{po_slave_languages}{$code};
718 sub otherlanguagesloop ($) { #{{{
722 my %otherpages=%{otherlanguages($page)};
723 while (my ($lang, $otherpage) = each %otherpages) {
724 if (istranslation($page) && masterpage($page) eq $otherpage) {
726 url => urlto_with_orig_beautiful_urlpath($otherpage, $page),
728 language => languagename($lang),
734 url => urlto_with_orig_beautiful_urlpath($otherpage, $page),
736 language => languagename($lang),
737 percent => percenttranslated($otherpage),
742 return -1 if $a->{code} eq $config{po_master_language}{code};
743 return 1 if $b->{code} eq $config{po_master_language}{code};
744 return $a->{language} cmp $b->{language};
748 sub homepageurl (;$) { #{{{
751 return urlto('', $page);
758 package IkiWiki::PageSpec;
763 sub match_istranslation ($;@) { #{{{
766 if (IkiWiki::Plugin::po::istranslation($page)) {
767 return IkiWiki::SuccessReason->new("is a translation page");
770 return IkiWiki::FailReason->new("is not a translation page");
774 sub match_istranslatable ($;@) { #{{{
777 if (IkiWiki::Plugin::po::istranslatable($page)) {
778 return IkiWiki::SuccessReason->new("is set as translatable in po_translatable_pages");
781 return IkiWiki::FailReason->new("is not set as translatable in po_translatable_pages");
785 sub match_lang ($$;@) { #{{{
789 my $regexp=IkiWiki::glob2re($wanted);
790 my $lang=IkiWiki::Plugin::po::lang($page);
791 if ($lang!~/^$regexp$/i) {
792 return IkiWiki::FailReason->new("file language is $lang, not $wanted");
795 return IkiWiki::SuccessReason->new("file language is $wanted");
799 sub match_currentlang ($$;@) { #{{{
804 return IkiWiki::FailReason->new("no location provided") unless exists $params{location};
806 my $currentlang=IkiWiki::Plugin::po::lang($params{location});
807 my $lang=IkiWiki::Plugin::po::lang($page);
809 if ($lang eq $currentlang) {
810 return IkiWiki::SuccessReason->new("file language is the same as current one, i.e. $currentlang");
813 return IkiWiki::FailReason->new("file language is $lang, whereas current language is $currentlang");