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 => "postscan", id => "po", call => \&postscan);
39 hook(type => "rename", id => "po", call => \&renamepages);
40 hook(type => "delete", id => "po", call => \&mydelete);
41 hook(type => "change", id => "po", call => \&change);
42 hook(type => "editcontent", id => "po", call => \&editcontent);
44 $origsubs{'bestlink'}=\&IkiWiki::bestlink;
45 inject(name => "IkiWiki::bestlink", call => \&mybestlink);
46 $origsubs{'beautify_urlpath'}=\&IkiWiki::beautify_urlpath;
47 inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath);
48 $origsubs{'targetpage'}=\&IkiWiki::targetpage;
49 inject(name => "IkiWiki::targetpage", call => \&mytargetpage);
50 $origsubs{'urlto'}=\&IkiWiki::urlto;
51 inject(name => "IkiWiki::urlto", call => \&myurlto);
52 $origsubs{'nicepagetitle'}=\&IkiWiki::nicepagetitle;
53 inject(name => "IkiWiki::nicepagetitle", call => \&mynicepagetitle);
62 # 2. Injected functions
63 # 3. Blackboxes for private data
78 po_master_language => {
84 description => "master language (non-PO files)",
88 po_slave_languages => {
95 description => "slave languages (PO files)",
99 po_translatable_pages => {
101 example => "!*/Discussion",
102 description => "PageSpec controlling which pages are translatable",
103 link => "ikiwiki/PageSpec",
109 example => "current",
110 description => "internal linking behavior (default/current/negotiated)",
114 po_translation_status_in_links => {
117 description => "display translation status in links to translations",
124 foreach my $field (qw{po_master_language po_slave_languages}) {
125 if (! exists $config{$field} || ! defined $config{$field}) {
126 error(sprintf(gettext("Must specify %s"), $field));
129 if (! (keys %{$config{po_slave_languages}})) {
130 error(gettext("At least one slave language must be defined in po_slave_languages"));
134 or error(sprintf(gettext("%s is not a valid language code"), $_));
135 } ($config{po_master_language}{code}, keys %{$config{po_slave_languages}});
136 if (! exists $config{po_translatable_pages} ||
137 ! defined $config{po_translatable_pages}) {
138 $config{po_translatable_pages}="";
140 if (! exists $config{po_link_to} ||
141 ! defined $config{po_link_to}) {
142 $config{po_link_to}='default';
145 $config{po_link_to} eq $_
146 } ('default', 'current', 'negotiated')) {
147 warn(sprintf(gettext('po_link_to=%s is not a valid setting, falling back to po_link_to=default'),
148 $config{po_link_to}));
149 $config{po_link_to}='default';
151 elsif ($config{po_link_to} eq "negotiated" && ! $config{usedirs}) {
152 warn(gettext('po_link_to=negotiated requires usedirs to be enabled, falling back to po_link_to=default'));
153 $config{po_link_to}='default';
155 if (! exists $config{po_translation_status_in_links} ||
156 ! defined $config{po_translation_status_in_links}) {
157 $config{po_translation_status_in_links}=1;
159 push @{$config{wiki_file_prune_regexps}}, qr/\.pot$/;
163 my $needsbuild=shift;
165 # backup @needsbuild content so that change() can know whether
166 # a given master page was rendered because its source file was changed
167 @origneedsbuild=(@$needsbuild);
170 buildtranslationscache();
172 # make existing translations depend on the corresponding master page
173 foreach my $master (keys %translations) {
174 map add_depends($_, $master), values %{otherlanguages($master)};
178 # Massage the recorded state of internal links so that:
179 # - it matches the actually generated links, rather than the links as written
180 # in the pages' source
181 # - backlinks are consistent in all cases
184 my $page=$params{page};
185 my $content=$params{content};
187 return unless UNIVERSAL::can("IkiWiki::Plugin::link", "import");
189 if (istranslation($page)) {
190 foreach my $destpage (@{$links{$page}}) {
191 if (istranslatable($destpage)) {
192 # replace one occurence of $destpage in $links{$page}
193 # (we only want to replace the one that was added by
194 # IkiWiki::Plugin::link::scan, other occurences may be
195 # there for other reasons)
196 for (my $i=0; $i<@{$links{$page}}; $i++) {
197 if (@{$links{$page}}[$i] eq $destpage) {
198 @{$links{$page}}[$i] = $destpage . '.' . lang($page);
205 elsif (! istranslatable($page) && ! istranslation($page)) {
206 foreach my $destpage (@{$links{$page}}) {
207 if (istranslatable($destpage)) {
208 # make sure any destpage's translations has
209 # $page in its backlinks
210 push @{$links{$page}},
211 values %{otherlanguages($destpage)};
217 # We use filter to convert PO to the master page's format,
218 # since the rest of ikiwiki should not work on PO files.
222 my $page = $params{page};
223 my $destpage = $params{destpage};
224 my $content = decode_utf8(encode_utf8($params{content}));
226 return $content if ( ! istranslation($page)
227 || alreadyfiltered($page, $destpage) );
229 # CRLF line terminators make poor Locale::Po4a feel bad
230 $content=~s/\r\n/\n/g;
232 # There are incompatibilities between some File::Temp versions
233 # (including 0.18, bundled with Lenny's perl-modules package)
234 # and others (e.g. 0.20, previously present in the archive as
235 # a standalone package): under certain circumstances, some
236 # return a relative filename, whereas others return an absolute one;
237 # we here use this module in a way that is at least compatible
238 # with 0.18 and 0.20. Beware, hit'n'run refactorers!
239 my $infile = new File::Temp(TEMPLATE => "ikiwiki-po-filter-in.XXXXXXXXXX",
240 DIR => File::Spec->tmpdir,
241 UNLINK => 1)->filename;
242 my $outfile = new File::Temp(TEMPLATE => "ikiwiki-po-filter-out.XXXXXXXXXX",
243 DIR => File::Spec->tmpdir,
244 UNLINK => 1)->filename;
246 writefile(basename($infile), File::Spec->tmpdir, $content);
248 my $masterfile = srcfile($pagesources{masterpage($page)});
250 "markdown" => (pagetype($masterfile) eq 'mdwn') ? 1 : 0,
252 my $doc=Locale::Po4a::Chooser::new('text',%options);
254 'po_in_name' => [ $infile ],
255 'file_in_name' => [ $masterfile ],
256 'file_in_charset' => 'utf-8',
257 'file_out_charset' => 'utf-8',
258 ) or error("[po/filter:$page]: failed to translate");
259 $doc->write($outfile) or error("[po/filter:$page] could not write $outfile");
260 $content = readfile($outfile) or error("[po/filter:$page] could not read $outfile");
262 # Unlinking should happen automatically, thanks to File::Temp,
263 # but it does not work here, probably because of the way writefile()
264 # and Locale::Po4a::write() work.
265 unlink $infile, $outfile;
267 setalreadyfiltered($page, $destpage);
274 my $page = $params{page};
275 my $content = $params{content};
277 # ignore PO files this plugin did not create
278 return $content unless istranslation($page);
280 # force content to be htmlize'd as if it was the same type as the master page
281 return IkiWiki::htmlize($page, $page,
282 pagetype(srcfile($pagesources{masterpage($page)})),
286 sub pagetemplate (@) {
288 my $page=$params{page};
289 my $destpage=$params{destpage};
290 my $template=$params{template};
292 my ($masterpage, $lang) = istranslation($page);
294 if (istranslation($page) && $template->query(name => "percenttranslated")) {
295 $template->param(percenttranslated => percenttranslated($page));
297 if ($template->query(name => "istranslation")) {
298 $template->param(istranslation => scalar istranslation($page));
300 if ($template->query(name => "istranslatable")) {
301 $template->param(istranslatable => istranslatable($page));
303 if ($template->query(name => "HOMEPAGEURL")) {
304 $template->param(homepageurl => homepageurl($page));
306 if ($template->query(name => "otherlanguages")) {
307 $template->param(otherlanguages => [otherlanguagesloop($page)]);
308 map add_depends($page, $_), (values %{otherlanguages($page)});
310 # Rely on IkiWiki::Render's genpage() to decide wether
311 # a discussion link should appear on $page; this is not
312 # totally accurate, though: some broken links may be generated
313 # when cgiurl is disabled.
314 # This compromise avoids some code duplication, and will probably
315 # prevent future breakage when ikiwiki internals change.
316 # Known limitations are preferred to future random bugs.
317 if ($template->param('discussionlink') && istranslation($page)) {
318 $template->param('discussionlink' => htmllink(
321 $masterpage . '/' . gettext("Discussion"),
324 linktext => gettext("Discussion"),
327 # Remove broken parentlink to ./index.html on home page's translations.
328 # It works because this hook has the "last" parameter set, to ensure it
329 # runs after parentlinks' own pagetemplate hook.
330 if ($template->param('parentlinks')
331 && istranslation($page)
332 && $masterpage eq "index") {
333 $template->param('parentlinks' => []);
339 my $page = $params{page};
341 # backlinks involve back-dependencies, so that nicepagetitle effects,
342 # such as translation status displayed in links, are updated
344 map add_depends($page, $_), keys %{$IkiWiki::backlinks{$page}};
347 # Add the renamed page translations to the list of to-be-renamed pages.
350 my @torename=@{$torename};
352 foreach my $rename (@torename) {
353 next unless istranslatable($rename->{src});
354 my %otherpages=%{otherlanguages($rename->{src})};
355 while (my ($lang, $otherpage) = each %otherpages) {
358 srcfile => $pagesources{$otherpage},
359 dest => otherlanguage($rename->{dest}, $lang),
360 destfile => $rename->{dest}.".".$lang.".po",
370 map { deletetranslations($_) } grep istranslatablefile($_), @deleted;
376 my $updated_po_files=0;
378 # Refresh/create POT and PO files as needed.
379 foreach my $file (grep {istranslatablefile($_)} @rendered) {
380 my $page=pagename($file);
381 my $masterfile=srcfile($file);
382 my $updated_pot_file=0;
383 # Only refresh Pot file if it does not exist, or if
384 # $pagesources{$page} was changed: don't if only the HTML was
385 # refreshed, e.g. because of a dependency.
386 if ((grep { $_ eq $pagesources{$page} } @origneedsbuild)
387 || ! -e potfile($masterfile)) {
388 refreshpot($masterfile);
393 push @pofiles, $_ if ($updated_pot_file || ! -e $_);
394 } (pofiles($masterfile));
396 refreshpofiles($masterfile, @pofiles);
397 map { IkiWiki::rcs_add($_) } @pofiles if $config{rcs};
402 if ($updated_po_files) {
404 gettext("updated PO files"),
405 "IkiWiki::Plugin::po::change");
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.
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);
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 # avoid using our injected beautify_urlpath if run by cgi_editpage,
480 # so that one is redirected to the just-edited page rather than to the
481 # negociated translation; to prevent unnecessary fiddling with caller/inject,
482 # we only do so when our beautify_urlpath would actually do what we want to
483 # avoid, i.e. when po_link_to = negotiated
484 if ($config{po_link_to} eq "negotiated") {
485 my @caller = caller(1);
486 my $run_by_editpage = ($caller[3] eq "IkiWiki::cgi_editpage");
487 inject(name => "IkiWiki::beautify_urlpath", call => $origsubs{'beautify_urlpath'})
489 my $res = $origsubs{'urlto'}->($to,$from,$absolute);
490 inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath)
495 return $origsubs{'urlto'}->($to,$from,$absolute)
499 sub mynicepagetitle ($;$) {
500 my ($page, $unescaped) = (shift, shift);
502 my $res = $origsubs{'nicepagetitle'}->($page, $unescaped);
503 return $res unless istranslation($page);
504 return $res unless $config{po_translation_status_in_links};
505 return $res.' ('.percenttranslated($page).' %)';
509 # | Blackboxes for private data
515 sub alreadyfiltered($$) {
519 return ( exists $filtered{$page}{$destpage}
520 && $filtered{$page}{$destpage} eq 1 );
523 sub setalreadyfiltered($$) {
527 $filtered{$page}{$destpage}=1;
530 sub unsetalreadyfiltered($$) {
534 if (exists $filtered{$page}{$destpage}) {
535 delete $filtered{$page}{$destpage};
539 sub resetalreadyfiltered() {
548 sub maybe_add_leading_slash ($;$) {
551 $add=1 unless defined $add;
552 return '/' . $str if $add;
556 sub istranslatablefile ($) {
559 return 0 unless defined $file;
560 return 0 if (defined pagetype($file) && pagetype($file) eq 'po');
561 return 0 if $file =~ /\.pot$/;
562 return 1 if pagespec_match(pagename($file), $config{po_translatable_pages});
566 sub istranslatable ($) {
570 return 1 if istranslatablefile($pagesources{$page});
574 sub _istranslation ($) {
577 my $hasleadingslash = ($page=~s#^/##);
578 my $file=$pagesources{$page};
579 return 0 unless (defined $file
580 && defined pagetype($file)
581 && pagetype($file) eq 'po');
582 return 0 if $file =~ /\.pot$/;
584 my ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
585 return 0 unless (defined $masterpage && defined $lang
586 && length $masterpage && length $lang
587 && defined $pagesources{$masterpage}
588 && defined $config{po_slave_languages}{$lang});
590 return (maybe_add_leading_slash($masterpage, $hasleadingslash), $lang)
591 if istranslatable($masterpage);
594 sub istranslation ($) {
597 if (1 < (my ($masterpage, $lang) = _istranslation($page))) {
598 my $hasleadingslash = ($masterpage=~s#^/##);
599 $translations{$masterpage}{$lang}=$page unless exists $translations{$masterpage}{$lang};
600 return (maybe_add_leading_slash($masterpage, $hasleadingslash), $lang);
608 if ( 1 < (my ($masterpage, $lang) = _istranslation($page))) {
617 if (1 < (my ($masterpage, $lang) = _istranslation($page))) {
620 return $config{po_master_language}{code};
623 sub islanguagecode ($) {
626 return ($code =~ /^[a-z]{2}$/);
629 sub otherlanguage ($$) {
633 return masterpage($page) if $code eq $config{po_master_language}{code};
634 return masterpage($page) . '.' . $code;
637 sub otherlanguages ($) {
641 return \%ret unless (istranslation($page) || istranslatable($page));
642 my $curlang=lang($page);
644 ($config{po_master_language}{code}, keys %{$config{po_slave_languages}}) {
645 next if $lang eq $curlang;
646 $ret{$lang}=otherlanguage($page, $lang);
652 my $masterfile=shift;
654 (my $name, my $dir, my $suffix) = fileparse($masterfile, qr/\.[^.]*/);
655 $dir='' if $dir eq './';
656 return File::Spec->catpath('', $dir, $name . ".pot");
660 my $masterfile=shift;
663 (my $name, my $dir, my $suffix) = fileparse($masterfile, qr/\.[^.]*/);
664 $dir='' if $dir eq './';
665 return File::Spec->catpath('', $dir, $name . "." . $lang . ".po");
669 my $masterfile=shift;
671 return map pofile($masterfile, $_), (keys %{$config{po_slave_languages}});
675 my $masterfile=shift;
677 my $potfile=potfile($masterfile);
678 my %options = ("markdown" => (pagetype($masterfile) eq 'mdwn') ? 1 : 0);
679 my $doc=Locale::Po4a::Chooser::new('text',%options);
680 $doc->{TT}{utf_mode} = 1;
681 $doc->{TT}{file_in_charset} = 'utf-8';
682 $doc->{TT}{file_out_charset} = 'utf-8';
683 $doc->read($masterfile);
684 # let's cheat a bit to force porefs option to be passed to Locale::Po4a::Po;
685 # this is undocument use of internal Locale::Po4a::TransTractor's data,
686 # compulsory since this module prevents us from using the porefs option.
687 $doc->{TT}{po_out}=Locale::Po4a::Po->new({ 'porefs' => 'none' });
688 $doc->{TT}{po_out}->set_charset('utf-8');
691 IkiWiki::prep_writefile(basename($potfile),dirname($potfile));
692 $doc->writepo($potfile);
695 sub refreshpofiles ($@) {
696 my $masterfile=shift;
699 my $potfile=potfile($masterfile);
700 error("[po/refreshpofiles] POT file ($potfile) does not exist") unless (-e $potfile);
702 foreach my $pofile (@pofiles) {
703 IkiWiki::prep_writefile(basename($pofile),dirname($pofile));
705 system("msgmerge", "-U", "--backup=none", $pofile, $potfile) == 0
706 or error("[po/refreshpofiles:$pofile] failed to update");
709 File::Copy::syscopy($potfile,$pofile)
710 or error("[po/refreshpofiles:$pofile] failed to copy the POT file");
715 sub buildtranslationscache() {
716 # use istranslation's side-effect
717 map istranslation($_), (keys %pagesources);
720 sub resettranslationscache() {
724 sub flushmemoizecache() {
725 Memoize::flush_cache("istranslatable");
726 Memoize::flush_cache("_istranslation");
727 Memoize::flush_cache("percenttranslated");
730 sub urlto_with_orig_beautiful_urlpath($$) {
734 inject(name => "IkiWiki::beautify_urlpath", call => $origsubs{'beautify_urlpath'});
735 my $res=urlto($to, $from);
736 inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath);
741 sub percenttranslated ($) {
745 return gettext("N/A") unless istranslation($page);
746 my $file=srcfile($pagesources{$page});
747 my $masterfile = srcfile($pagesources{masterpage($page)});
749 "markdown" => (pagetype($masterfile) eq 'mdwn') ? 1 : 0,
751 my $doc=Locale::Po4a::Chooser::new('text',%options);
753 'po_in_name' => [ $file ],
754 'file_in_name' => [ $masterfile ],
755 'file_in_charset' => 'utf-8',
756 'file_out_charset' => 'utf-8',
757 ) or error("[po/percenttranslated:$page]: failed to translate");
758 my ($percent,$hit,$queries) = $doc->stats();
762 sub languagename ($) {
765 return $config{po_master_language}{name}
766 if $code eq $config{po_master_language}{code};
767 return $config{po_slave_languages}{$code}
768 if defined $config{po_slave_languages}{$code};
772 sub otherlanguagesloop ($) {
776 my %otherpages=%{otherlanguages($page)};
777 while (my ($lang, $otherpage) = each %otherpages) {
778 if (istranslation($page) && masterpage($page) eq $otherpage) {
780 url => urlto_with_orig_beautiful_urlpath($otherpage, $page),
782 language => languagename($lang),
788 url => urlto_with_orig_beautiful_urlpath($otherpage, $page),
790 language => languagename($lang),
791 percent => percenttranslated($otherpage),
796 return -1 if $a->{code} eq $config{po_master_language}{code};
797 return 1 if $b->{code} eq $config{po_master_language}{code};
798 return $a->{language} cmp $b->{language};
802 sub homepageurl (;$) {
805 return urlto('', $page);
808 sub deletetranslations ($) {
809 my $deletedmasterfile=shift;
811 my $deletedmasterpage=pagename($deletedmasterfile);
814 my $file = newpagefile($deletedmasterpage.'.'.$_, 'po');
815 my $absfile = "$config{srcdir}/$file";
816 if (-e $absfile && ! -l $absfile && ! -d $absfile) {
817 push @todelete, $file;
819 } keys %{$config{po_slave_languages}};
823 IkiWiki::rcs_remove($_);
826 IkiWiki::prune("$config{srcdir}/$_");
830 if (scalar @todelete) {
832 gettext("removed obsolete PO files"),
833 "IkiWiki::Plugin::po::deletetranslations");
837 sub commit_and_refresh ($$) {
838 my ($msg, $author) = (shift, shift);
841 IkiWiki::disable_commit_hook();
842 IkiWiki::rcs_commit_staged($msg, $author, "127.0.0.1");
843 IkiWiki::enable_commit_hook();
844 IkiWiki::rcs_update();
846 # Reinitialize module's private variables.
847 resetalreadyfiltered();
848 resettranslationscache();
850 # Trigger a wiki refresh.
851 require IkiWiki::Render;
852 # without preliminary saveindex/loadindex, refresh()
853 # complains about a lot of uninitialized variables
854 IkiWiki::saveindex();
855 IkiWiki::loadindex();
857 IkiWiki::saveindex();
864 package IkiWiki::PageSpec;
869 sub match_istranslation ($;@) {
872 if (IkiWiki::Plugin::po::istranslation($page)) {
873 return IkiWiki::SuccessReason->new("is a translation page");
876 return IkiWiki::FailReason->new("is not a translation page");
880 sub match_istranslatable ($;@) {
883 if (IkiWiki::Plugin::po::istranslatable($page)) {
884 return IkiWiki::SuccessReason->new("is set as translatable in po_translatable_pages");
887 return IkiWiki::FailReason->new("is not set as translatable in po_translatable_pages");
891 sub match_lang ($$;@) {
895 my $regexp=IkiWiki::glob2re($wanted);
896 my $lang=IkiWiki::Plugin::po::lang($page);
897 if ($lang!~/^$regexp$/i) {
898 return IkiWiki::FailReason->new("file language is $lang, not $wanted");
901 return IkiWiki::SuccessReason->new("file language is $wanted");
905 sub match_currentlang ($$;@) {
910 return IkiWiki::FailReason->new("no location provided") unless exists $params{location};
912 my $currentlang=IkiWiki::Plugin::po::lang($params{location});
913 my $lang=IkiWiki::Plugin::po::lang($page);
915 if ($lang eq $currentlang) {
916 return IkiWiki::SuccessReason->new("file language is the same as current one, i.e. $currentlang");
919 return IkiWiki::FailReason->new("file language is $lang, whereas current language is $currentlang");