2 # .po as a wiki page type
3 # Licensed under GPL v2 or greater
4 # Copyright (C) 2008-2009 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 eval q{use Locale::Po4a::Common qw(nowrapi18n !/.*/)};
15 print STDERR gettext("warning: Old po4a detected! Recommend upgrade to 0.35.")."\n";
16 eval q{use Locale::Po4a::Common qw(!/.*/)};
19 use Locale::Po4a::Chooser;
31 my @slavelanguages; # language codes ordered as in config po_slave_languages
33 memoize("istranslatable");
34 memoize("_istranslation");
35 memoize("percenttranslated");
38 hook(type => "getsetup", id => "po", call => \&getsetup);
39 hook(type => "checkconfig", id => "po", call => \&checkconfig);
40 hook(type => "needsbuild", id => "po", call => \&needsbuild);
41 hook(type => "scan", id => "po", call => \&scan, last => 1);
42 hook(type => "filter", id => "po", call => \&filter);
43 hook(type => "htmlize", id => "po", call => \&htmlize);
44 hook(type => "pagetemplate", id => "po", call => \&pagetemplate, last => 1);
45 hook(type => "rename", id => "po", call => \&renamepages, first => 1);
46 hook(type => "delete", id => "po", call => \&mydelete);
47 hook(type => "change", id => "po", call => \&change);
48 hook(type => "checkcontent", id => "po", call => \&checkcontent);
49 hook(type => "canremove", id => "po", call => \&canremove);
50 hook(type => "canrename", id => "po", call => \&canrename);
51 hook(type => "editcontent", id => "po", call => \&editcontent);
52 hook(type => "formbuilder_setup", id => "po", call => \&formbuilder_setup, last => 1);
53 hook(type => "formbuilder", id => "po", call => \&formbuilder);
56 $origsubs{'bestlink'}=\&IkiWiki::bestlink;
57 inject(name => "IkiWiki::bestlink", call => \&mybestlink);
58 $origsubs{'beautify_urlpath'}=\&IkiWiki::beautify_urlpath;
59 inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath);
60 $origsubs{'targetpage'}=\&IkiWiki::targetpage;
61 inject(name => "IkiWiki::targetpage", call => \&mytargetpage);
62 $origsubs{'urlto'}=\&IkiWiki::urlto;
63 inject(name => "IkiWiki::urlto", call => \&myurlto);
64 $origsubs{'cgiurl'}=\&IkiWiki::cgiurl;
65 inject(name => "IkiWiki::cgiurl", call => \&mycgiurl);
66 $origsubs{'rootpage'}=\&IkiWiki::rootpage;
67 inject(name => "IkiWiki::rootpage", call => \&myrootpage);
68 $origsubs{'isselflink'}=\&IkiWiki::isselflink;
69 inject(name => "IkiWiki::isselflink", call => \&myisselflink);
79 # 2. Injected functions
80 # 3. Blackboxes for private data
93 rebuild => 1, # format plugin
96 po_master_language => {
102 description => "master language (non-PO files)",
106 po_slave_languages => {
113 description => "slave languages (PO files)",
117 po_translatable_pages => {
119 example => "* and !*/Discussion",
120 description => "PageSpec controlling which pages are translatable",
121 link => "ikiwiki/PageSpec",
127 example => "current",
128 description => "internal linking behavior (default/current/negotiated)",
135 foreach my $field (qw{po_master_language}) {
136 if (! exists $config{$field} || ! defined $config{$field}) {
137 error(sprintf(gettext("Must specify %s when using the %s plugin"),
142 if (ref $config{po_slave_languages} eq 'ARRAY') {
144 foreach my $pair (@{$config{po_slave_languages}}) {
145 my ($code, $name) = ( $pair =~ /^([a-z]{2})\|(.+)$/ );
146 if (!defined $code || !defined $name) {
147 error(sprintf(gettext("%s has invalid syntax: must use CODE|NAME"),
150 $slaves{$code} = $name;
151 push @slavelanguages, $code;
154 $config{po_slave_languages} = \%slaves;
156 elsif (ref $config{po_slave_languages} eq 'HASH') {
157 @slavelanguages = sort {
158 $config{po_slave_languages}->{$a} cmp $config{po_slave_languages}->{$b};
159 } keys %{$config{po_slave_languages}};
162 delete $config{po_slave_languages}{$config{po_master_language}{code}};;
166 or error(sprintf(gettext("%s is not a valid language code"), $_));
167 } ($config{po_master_language}{code}, keys %{$config{po_slave_languages}});
169 if (! exists $config{po_translatable_pages} ||
170 ! defined $config{po_translatable_pages}) {
171 $config{po_translatable_pages}="";
173 if (! exists $config{po_link_to} ||
174 ! defined $config{po_link_to}) {
175 $config{po_link_to}='default';
177 elsif ($config{po_link_to} !~ /^(default|current|negotiated)$/) {
178 warn(sprintf(gettext('%s is not a valid value for po_link_to, falling back to po_link_to=default'),
179 $config{po_link_to}));
180 $config{po_link_to}='default';
182 elsif ($config{po_link_to} eq "negotiated" && ! $config{usedirs}) {
183 warn(gettext('po_link_to=negotiated requires usedirs to be enabled, falling back to po_link_to=default'));
184 $config{po_link_to}='default';
187 push @{$config{wiki_file_prune_regexps}}, qr/\.pot$/;
189 # Translated versions of the underlays are added if available.
190 foreach my $underlay ("basewiki",
191 map { m/^\Q$config{underlaydirbase}\E\/*(.*)/ }
192 reverse @{$config{underlaydirs}}) {
193 next if $underlay=~/^locale\//;
195 # Underlays containing the po files for slave languages.
196 foreach my $ll (keys %{$config{po_slave_languages}}) {
197 add_underlay("po/$ll/$underlay")
198 if -d "$config{underlaydirbase}/po/$ll/$underlay";
201 if ($config{po_master_language}{code} ne 'en') {
202 # Add underlay containing translated source files
203 # for the master language.
204 add_underlay("locale/$config{po_master_language}{code}/$underlay")
205 if -d "$config{underlaydirbase}/locale/$config{po_master_language}{code}/$underlay";
211 my $needsbuild=shift;
213 # backup @needsbuild content so that change() can know whether
214 # a given master page was rendered because its source file was changed
215 @origneedsbuild=(@$needsbuild);
218 buildtranslationscache();
220 # make existing translations depend on the corresponding master page
221 foreach my $master (keys %translations) {
222 map add_depends($_, $master), values %{otherlanguages_pages($master)};
226 # Massage the recorded state of internal links so that:
227 # - it matches the actually generated links, rather than the links as written
228 # in the pages' source
229 # - backlinks are consistent in all cases
232 my $page=$params{page};
233 my $content=$params{content};
235 if (istranslation($page)) {
236 foreach my $destpage (@{$links{$page}}) {
237 if (istranslatable($destpage)) {
238 # replace the occurence of $destpage in $links{$page}
239 for (my $i=0; $i<@{$links{$page}}; $i++) {
240 if (@{$links{$page}}[$i] eq $destpage) {
241 @{$links{$page}}[$i] = $destpage . '.' . lang($page);
248 elsif (! istranslatable($page) && ! istranslation($page)) {
249 foreach my $destpage (@{$links{$page}}) {
250 if (istranslatable($destpage)) {
251 # make sure any destpage's translations has
252 # $page in its backlinks
253 push @{$links{$page}},
254 values %{otherlanguages_pages($destpage)};
260 # We use filter to convert PO to the master page's format,
261 # since the rest of ikiwiki should not work on PO files.
265 my $page = $params{page};
266 my $destpage = $params{destpage};
267 my $content = $params{content};
268 if (istranslation($page) && ! alreadyfiltered($page, $destpage)) {
269 $content = po_to_markup($page, $content);
270 setalreadyfiltered($page, $destpage);
278 my $page = $params{page};
279 my $content = $params{content};
281 # ignore PO files this plugin did not create
282 return $content unless istranslation($page);
284 # force content to be htmlize'd as if it was the same type as the master page
285 return IkiWiki::htmlize($page, $page,
286 pagetype(srcfile($pagesources{masterpage($page)})),
290 sub pagetemplate (@) {
292 my $page=$params{page};
293 my $destpage=$params{destpage};
294 my $template=$params{template};
296 my ($masterpage, $lang) = istranslation($page);
298 if (istranslation($page) && $template->query(name => "percenttranslated")) {
299 $template->param(percenttranslated => percenttranslated($page));
301 if ($template->query(name => "istranslation")) {
302 $template->param(istranslation => scalar istranslation($page));
304 if ($template->query(name => "istranslatable")) {
305 $template->param(istranslatable => istranslatable($page));
307 if ($template->query(name => "HOMEPAGEURL")) {
308 $template->param(homepageurl => homepageurl($page));
310 if ($template->query(name => "otherlanguages")) {
311 $template->param(otherlanguages => [otherlanguagesloop($page)]);
312 map add_depends($page, $_), (values %{otherlanguages_pages($page)});
314 if ($config{discussion} && istranslation($page)) {
315 if ($page !~ /.*\/\Q$config{discussionpage}\E$/i &&
316 (length $config{cgiurl} ||
317 exists $links{$masterpage."/".lc($config{discussionpage})})) {
318 $template->param('discussionlink' => htmllink(
321 $masterpage . '/' . $config{discussionpage},
324 linktext => $config{discussionpage},
328 # Remove broken parentlink to ./index.html on home page's translations.
329 # It works because this hook has the "last" parameter set, to ensure it
330 # runs after parentlinks' own pagetemplate hook.
331 if ($template->param('parentlinks')
332 && istranslation($page)
333 && $masterpage eq "index") {
334 $template->param('parentlinks' => []);
336 if (ishomepage($page) && $template->query(name => "title")) {
337 $template->param(title => $config{wikiname});
341 # Add the renamed page translations to the list of to-be-renamed pages.
342 sub renamepages (@) {
345 my %torename = %{$params{torename}};
346 my $session = $params{session};
348 # Save the page(s) the user asked to rename, so that our
349 # canrename hook can tell the difference between:
350 # - a translation being renamed as a consequence of its master page
352 # - a user trying to directly rename a translation
353 # This is why this hook has to be run first, before the list of pages
354 # to rename is modified by other plugins.
356 @orig_torename=@{$session->param("po_orig_torename")}
357 if defined $session->param("po_orig_torename");
358 push @orig_torename, $torename{src};
359 $session->param(po_orig_torename => \@orig_torename);
360 IkiWiki::cgi_savesession($session);
362 return () unless istranslatable($torename{src});
365 my %otherpages=%{otherlanguages_pages($torename{src})};
366 while (my ($lang, $otherpage) = each %otherpages) {
369 srcfile => $pagesources{$otherpage},
370 dest => otherlanguage_page($torename{dest}, $lang),
371 destfile => $torename{dest}.".".$lang.".po",
381 map { deletetranslations($_) } grep istranslatablefile($_), @deleted;
387 # All meta titles are first extracted at scan time, i.e. before we turn
388 # PO files back into translated markdown; escaping of double-quotes in
389 # PO files breaks the meta plugin's parsing enough to save ugly titles
390 # to %pagestate at this time.
392 # Then, at render time, every page passes in turn through the Great
393 # Rendering Chain (filter->preprocess->linkify->htmlize), and the meta
394 # plugin's preprocess hook is this time in a position to correctly
395 # extract the titles from slave pages.
397 # This is, unfortunately, too late: if the page A, linking to the page
398 # B, is rendered before B, it will display the wrongly-extracted meta
399 # title as the link text to B.
401 # On the one hand, such a corner case only happens on rebuild: on
402 # refresh, every rendered page is fixed to contain correct meta titles.
403 # On the other hand, it can take some time to get every page fixed.
404 # We therefore re-render every rendered page after a rebuild to fix them
405 # at once. As this more or less doubles the time needed to rebuild the
406 # wiki, we do so only when really needed.
409 && exists $config{rebuild} && defined $config{rebuild} && $config{rebuild}
410 && UNIVERSAL::can("IkiWiki::Plugin::meta", "getsetup")
411 && exists $config{meta_overrides_page_title}
412 && defined $config{meta_overrides_page_title}
413 && $config{meta_overrides_page_title}) {
414 debug(sprintf(gettext("rebuilding all pages to fix meta titles")));
415 resetalreadyfiltered();
416 require IkiWiki::Render;
417 foreach my $file (@rendered) {
418 IkiWiki::render($file, sprintf(gettext("building %s"), $file));
422 my $updated_po_files=0;
424 # Refresh/create POT and PO files as needed.
425 foreach my $file (grep {istranslatablefile($_)} @rendered) {
426 my $masterfile=srcfile($file);
427 my $page=pagename($file);
428 my $updated_pot_file=0;
430 # Avoid touching underlay files.
431 next if $masterfile ne "$config{srcdir}/$file";
433 # Only refresh POT file if it does not exist, or if
434 # the source was changed: don't if only the HTML was
435 # refreshed, e.g. because of a dependency.
436 if ((grep { $_ eq $pagesources{$page} } @origneedsbuild) ||
437 ! -e potfile($masterfile)) {
438 refreshpot($masterfile);
442 foreach my $po (pofiles($masterfile)) {
443 next if ! $updated_pot_file && -e $po;
444 next if grep { $po=~/\Q$_\E/ } @{$config{underlaydirs}};
448 refreshpofiles($masterfile, @pofiles);
449 map { s/^\Q$config{srcdir}\E\/*//; IkiWiki::rcs_add($_) } @pofiles if $config{rcs};
454 if ($updated_po_files) {
456 gettext("updated PO files"));
460 sub checkcontent (@) {
463 if (istranslation($params{page})) {
464 my $res = isvalidpo($params{content});
478 if (istranslation($params{page})) {
479 return gettext("Can not remove a translation. If the master page is removed, ".
480 "however, its translations will be removed as well.");
487 my $session = $params{session};
489 if (istranslation($params{src})) {
490 my $masterpage = masterpage($params{src});
491 # Tell the difference between:
492 # - a translation being renamed as a consequence of its master page
493 # being renamed, which is allowed
494 # - a user trying to directly rename a translation, which is forbidden
495 # by looking for the master page in the list of to-be-renamed pages we
496 # saved early in the renaming process.
497 my $orig_torename = $session->param("po_orig_torename");
498 unless (grep { $_ eq $masterpage } @{$orig_torename}) {
499 return gettext("Can not rename a translation. If the master page is renamed, ".
500 "however, its translations will be renamed as well.");
506 # As we're previewing or saving a page, the content may have
507 # changed, so tell the next filter() invocation it must not be lazy.
511 unsetalreadyfiltered($params{page}, $params{page});
512 return $params{content};
515 sub formbuilder_setup (@) {
517 my $form=$params{form};
520 return unless defined $form->field("do");
522 if ($form->field("do") eq "create") {
523 # Warn the user: new pages must be written in master language.
524 my $template=template("pocreatepage.tmpl");
525 $template->param(LANG => $config{po_master_language}{name});
526 $form->tmpl_param(message => $template->output);
528 elsif ($form->field("do") eq "edit") {
529 # Remove the rename/remove buttons on slave pages.
530 # This has to be done after the rename/remove plugins have added
531 # their buttons, which is why this hook must be run last.
532 # The canrename/canremove hooks already ensure this is forbidden
533 # at the backend level, so this is only UI sugar.
534 if (istranslation($form->field("page"))) {
536 for (my $i = 0; $i < @{$params{buttons}}; $i++) {
537 if (@{$params{buttons}}[$i] eq $_) {
538 delete @{$params{buttons}}[$i];
547 sub formbuilder (@) {
549 my $form=$params{form};
552 return unless defined $form->field("do");
554 # Do not allow to create pages of type po: they are automatically created.
555 # The main reason to do so is to bypass the "favor the type of linking page
556 # on page creation" logic, which is unsuitable when a broken link is clicked
557 # on a slave (PO) page.
558 # This cannot be done in the formbuilder_setup hook as the list of types is
560 if ($form->field("do") eq "create") {
561 foreach my $field ($form->field) {
562 next unless "$field" eq "type";
563 next unless $field->type eq 'select';
564 my $orig_value = $field->value;
565 # remove po from the list of types
566 my @types = grep { $_->[0] ne 'po' } $field->options;
567 $field->options(\@types) if @types;
568 # favor the type of linking page's masterpage
569 if ($orig_value eq 'po') {
571 if (defined $form->field('from')) {
572 ($from)=$form->field('from')=~/$config{wiki_file_regexp}/;
573 $from = masterpage($from);
575 if (defined $from && exists $pagesources{$from}) {
576 $type=pagetype($pagesources{$from});
578 $type=$config{default_pageext} unless defined $type;
579 $field->value($type) ;
586 # | Injected functions
589 # Implement po_link_to 'current' and 'negotiated' settings.
590 sub mybestlink ($$) {
594 return $origsubs{'bestlink'}->($page, $link)
595 if defined $config{po_link_to} && $config{po_link_to} eq "default";
597 my $res=$origsubs{'bestlink'}->(masterpage($page), $link);
598 my @caller = caller(1);
600 && istranslatable($res)
601 && istranslation($page)
602 && !(exists $caller[3] && defined $caller[3]
603 && ($caller[3] eq "IkiWiki::PageSpec::match_link"))) {
604 return $res . "." . lang($page);
609 sub mybeautify_urlpath ($) {
612 my $res=$origsubs{'beautify_urlpath'}->($url);
613 if (defined $config{po_link_to} && $config{po_link_to} eq "negotiated") {
614 $res =~ s!/\Qindex.$config{po_master_language}{code}.$config{htmlext}\E$!/!;
615 $res =~ s!/\Qindex.$config{htmlext}\E$!/!;
617 $res =~ s!/\Qindex.$_.$config{htmlext}\E$!/!;
618 } (keys %{$config{po_slave_languages}});
623 sub mytargetpage ($$) {
627 if (istranslation($page) || istranslatable($page)) {
628 my ($masterpage, $lang) = (masterpage($page), lang($page));
629 if (! $config{usedirs} || $masterpage eq 'index') {
630 return $masterpage . "." . $lang . "." . $ext;
633 return $masterpage . "/index." . $lang . "." . $ext;
636 return $origsubs{'targetpage'}->($page, $ext);
644 # workaround hard-coded /index.$config{htmlext} in IkiWiki::urlto()
646 && $config{po_link_to} eq "current"
647 && istranslatable('index')) {
648 return IkiWiki::beautify_urlpath(IkiWiki::baseurl($from) . "index." . lang($from) . ".$config{htmlext}");
650 # avoid using our injected beautify_urlpath if run by cgi_editpage,
651 # so that one is redirected to the just-edited page rather than to the
652 # negociated translation; to prevent unnecessary fiddling with caller/inject,
653 # we only do so when our beautify_urlpath would actually do what we want to
654 # avoid, i.e. when po_link_to = negotiated.
655 # also avoid doing so when run by cgi_goto, so that the links on recentchanges
656 # page actually lead to the exact page they pretend to.
657 if ($config{po_link_to} eq "negotiated") {
658 my @caller = caller(1);
660 $use_orig = 1 if (exists $caller[3] && defined $caller[3]
661 && ($caller[3] eq "IkiWiki::cgi_editpage" ||
662 $caller[3] eq "IkiWiki::Plugin::goto::cgi_goto")
664 inject(name => "IkiWiki::beautify_urlpath", call => $origsubs{'beautify_urlpath'})
666 my $res = $origsubs{'urlto'}->($to,$from,$absolute);
667 inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath)
672 return $origsubs{'urlto'}->($to,$from,$absolute)
679 # slave pages have no subpages
680 if (istranslation($params{'from'})) {
681 $params{'from'} = masterpage($params{'from'});
683 return $origsubs{'cgiurl'}->(%params);
690 if (exists $params{rootpage}) {
691 $rootpage=$origsubs{'bestlink'}->($params{page}, $params{rootpage});
692 if (!length $rootpage) {
693 $rootpage=$params{rootpage};
697 $rootpage=masterpage($params{page});
702 sub myisselflink ($$) {
706 return 1 if $origsubs{'isselflink'}->($page, $link);
707 if (istranslation($page)) {
708 return $origsubs{'isselflink'}->(masterpage($page), $link);
714 # | Blackboxes for private data
720 sub alreadyfiltered($$) {
724 return exists $filtered{$page}{$destpage}
725 && $filtered{$page}{$destpage} eq 1;
728 sub setalreadyfiltered($$) {
732 $filtered{$page}{$destpage}=1;
735 sub unsetalreadyfiltered($$) {
739 if (exists $filtered{$page}{$destpage}) {
740 delete $filtered{$page}{$destpage};
744 sub resetalreadyfiltered() {
753 sub maybe_add_leading_slash ($;$) {
756 $add=1 unless defined $add;
757 return '/' . $str if $add;
761 sub istranslatablefile ($) {
764 return 0 unless defined $file;
765 my $type=pagetype($file);
766 return 0 if ! defined $type || $type eq 'po';
767 return 0 if $file =~ /\.pot$/;
768 return 0 if ! defined $config{po_translatable_pages};
769 return 1 if pagespec_match(pagename($file), $config{po_translatable_pages});
773 sub istranslatable ($) {
777 return 1 if istranslatablefile($pagesources{$page});
781 sub _istranslation ($) {
784 $page='' unless defined $page && length $page;
785 my $hasleadingslash = ($page=~s#^/##);
786 my $file=$pagesources{$page};
787 return 0 unless defined $file
788 && defined pagetype($file)
789 && pagetype($file) eq 'po';
790 return 0 if $file =~ /\.pot$/;
792 my ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
793 return 0 unless defined $masterpage && defined $lang
794 && length $masterpage && length $lang
795 && defined $pagesources{$masterpage}
796 && defined $config{po_slave_languages}{$lang};
798 return (maybe_add_leading_slash($masterpage, $hasleadingslash), $lang)
799 if istranslatable($masterpage);
802 sub istranslation ($) {
805 if (1 < (my ($masterpage, $lang) = _istranslation($page))) {
806 my $hasleadingslash = ($masterpage=~s#^/##);
807 $translations{$masterpage}{$lang}=$page unless exists $translations{$masterpage}{$lang};
808 return (maybe_add_leading_slash($masterpage, $hasleadingslash), $lang);
816 if ( 1 < (my ($masterpage, $lang) = _istranslation($page))) {
825 if (1 < (my ($masterpage, $lang) = _istranslation($page))) {
828 return $config{po_master_language}{code};
831 sub islanguagecode ($) {
834 return $code =~ /^[a-z]{2}$/;
837 sub otherlanguage_page ($$) {
841 return masterpage($page) if $code eq $config{po_master_language}{code};
842 return masterpage($page) . '.' . $code;
845 # Returns the list of other languages codes: the master language comes first,
846 # then the codes are ordered the same way as in po_slave_languages, if it is
847 # an array, or in the language name lexical order, if it is a hash.
848 sub otherlanguages_codes ($) {
852 return \@ret unless istranslation($page) || istranslatable($page);
853 my $curlang=lang($page);
855 ($config{po_master_language}{code}, keys %{$config{po_slave_languages}}) {
856 next if $lang eq $curlang;
862 sub otherlanguages_pages ($) {
867 $ret{$_} = otherlanguage_page($page, $_)
868 } @{otherlanguages_codes($page)};
874 my $masterfile=shift;
876 (my $name, my $dir, my $suffix) = fileparse($masterfile, qr/\.[^.]*/);
877 $dir='' if $dir eq './';
878 return File::Spec->catpath('', $dir, $name . ".pot");
882 my $masterfile=shift;
885 (my $name, my $dir, my $suffix) = fileparse($masterfile, qr/\.[^.]*/);
886 $dir='' if $dir eq './';
887 return File::Spec->catpath('', $dir, $name . "." . $lang . ".po");
891 my $masterfile=shift;
893 return map pofile($masterfile, $_), (keys %{$config{po_slave_languages}});
897 my $masterfile=shift;
899 my $potfile=potfile($masterfile);
900 my $doc=Locale::Po4a::Chooser::new(po4a_type($masterfile),
901 po4a_options($masterfile));
902 $doc->{TT}{utf_mode} = 1;
903 $doc->{TT}{file_in_charset} = 'UTF-8';
904 $doc->{TT}{file_out_charset} = 'UTF-8';
905 $doc->read($masterfile);
906 # let's cheat a bit to force porefs option to be passed to
907 # Locale::Po4a::Po; this is undocument use of internal
908 # Locale::Po4a::TransTractor's data, compulsory since this module
909 # prevents us from using the porefs option.
910 $doc->{TT}{po_out}=Locale::Po4a::Po->new({ 'porefs' => 'none' });
911 $doc->{TT}{po_out}->set_charset('UTF-8');
914 IkiWiki::prep_writefile(basename($potfile),dirname($potfile));
915 $doc->writepo($potfile);
918 sub refreshpofiles ($@) {
919 my $masterfile=shift;
922 my $potfile=potfile($masterfile);
924 error("po(refreshpofiles) ".sprintf(gettext("POT file (%s) does not exist"), $potfile));
927 foreach my $pofile (@pofiles) {
928 IkiWiki::prep_writefile(basename($pofile),dirname($pofile));
931 # If the po file exists in an underlay, copy it
933 my ($pobase)=$pofile=~/^\Q$config{srcdir}\E\/?(.*)$/;
934 foreach my $dir (@{$config{underlaydirs}}) {
935 if (-e "$dir/$pobase") {
936 File::Copy::syscopy("$dir/$pobase",$pofile)
937 or error("po(refreshpofiles) ".
938 sprintf(gettext("failed to copy underlay PO file to %s"),
945 system("msgmerge", "--previous", "-q", "-U", "--backup=none", $pofile, $potfile) == 0
946 or error("po(refreshpofiles) ".
947 sprintf(gettext("failed to update %s"),
951 File::Copy::syscopy($potfile,$pofile)
952 or error("po(refreshpofiles) ".
953 sprintf(gettext("failed to copy the POT file to %s"),
959 sub buildtranslationscache() {
960 # use istranslation's side-effect
961 map istranslation($_), (keys %pagesources);
964 sub resettranslationscache() {
968 sub flushmemoizecache() {
969 Memoize::flush_cache("istranslatable");
970 Memoize::flush_cache("_istranslation");
971 Memoize::flush_cache("percenttranslated");
974 sub urlto_with_orig_beautiful_urlpath($$) {
978 inject(name => "IkiWiki::beautify_urlpath", call => $origsubs{'beautify_urlpath'});
979 my $res=urlto($to, $from);
980 inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath);
985 sub percenttranslated ($) {
989 return gettext("N/A") unless istranslation($page);
990 my $file=srcfile($pagesources{$page});
991 my $masterfile = srcfile($pagesources{masterpage($page)});
992 my $doc=Locale::Po4a::Chooser::new(po4a_type($masterfile),
993 po4a_options($masterfile));
995 'po_in_name' => [ $file ],
996 'file_in_name' => [ $masterfile ],
997 'file_in_charset' => 'UTF-8',
998 'file_out_charset' => 'UTF-8',
999 ) or error("po(percenttranslated) ".
1000 sprintf(gettext("failed to translate %s"), $page));
1001 my ($percent,$hit,$queries) = $doc->stats();
1002 $percent =~ s/\.[0-9]+$//;
1006 sub languagename ($) {
1009 return $config{po_master_language}{name}
1010 if $code eq $config{po_master_language}{code};
1011 return $config{po_slave_languages}{$code}
1012 if defined $config{po_slave_languages}{$code};
1016 sub otherlanguagesloop ($) {
1020 if (istranslation($page)) {
1022 url => urlto_with_orig_beautiful_urlpath(masterpage($page), $page),
1023 code => $config{po_master_language}{code},
1024 language => $config{po_master_language}{name},
1028 foreach my $lang (@{otherlanguages_codes($page)}) {
1029 next if $lang eq $config{po_master_language}{code};
1030 my $otherpage = otherlanguage_page($page, $lang);
1032 url => urlto_with_orig_beautiful_urlpath($otherpage, $page),
1034 language => languagename($lang),
1035 percent => percenttranslated($otherpage),
1041 sub homepageurl (;$) {
1044 return urlto('', $page);
1047 sub ishomepage ($) {
1050 return 1 if $page eq 'index';
1051 map { return 1 if $page eq 'index.'.$_ } keys %{$config{po_slave_languages}};
1055 sub deletetranslations ($) {
1056 my $deletedmasterfile=shift;
1058 my $deletedmasterpage=pagename($deletedmasterfile);
1061 my $file = newpagefile($deletedmasterpage.'.'.$_, 'po');
1062 my $absfile = "$config{srcdir}/$file";
1063 if (-e $absfile && ! -l $absfile && ! -d $absfile) {
1064 push @todelete, $file;
1066 } keys %{$config{po_slave_languages}};
1070 IkiWiki::rcs_remove($_);
1073 IkiWiki::prune("$config{srcdir}/$_");
1079 gettext("removed obsolete PO files"));
1083 sub commit_and_refresh ($) {
1087 IkiWiki::disable_commit_hook();
1088 IkiWiki::rcs_commit_staged(
1091 IkiWiki::enable_commit_hook();
1092 IkiWiki::rcs_update();
1094 # Reinitialize module's private variables.
1095 resetalreadyfiltered();
1096 resettranslationscache();
1097 flushmemoizecache();
1098 # Trigger a wiki refresh.
1099 require IkiWiki::Render;
1100 # without preliminary saveindex/loadindex, refresh()
1101 # complains about a lot of uninitialized variables
1102 IkiWiki::saveindex();
1103 IkiWiki::loadindex();
1105 IkiWiki::saveindex();
1108 sub po_to_markup ($$) {
1109 my ($page, $content) = (shift, shift);
1111 $content = '' unless defined $content;
1112 $content = decode_utf8(encode_utf8($content));
1113 # CRLF line terminators make poor Locale::Po4a feel bad
1114 $content=~s/\r\n/\n/g;
1116 # There are incompatibilities between some File::Temp versions
1117 # (including 0.18, bundled with Lenny's perl-modules package)
1118 # and others (e.g. 0.20, previously present in the archive as
1119 # a standalone package): under certain circumstances, some
1120 # return a relative filename, whereas others return an absolute one;
1121 # we here use this module in a way that is at least compatible
1122 # with 0.18 and 0.20. Beware, hit'n'run refactorers!
1123 my $infile = new File::Temp(TEMPLATE => "ikiwiki-po-filter-in.XXXXXXXXXX",
1124 DIR => File::Spec->tmpdir,
1125 UNLINK => 1)->filename;
1126 my $outfile = new File::Temp(TEMPLATE => "ikiwiki-po-filter-out.XXXXXXXXXX",
1127 DIR => File::Spec->tmpdir,
1128 UNLINK => 1)->filename;
1130 my $fail = sub ($) {
1131 my $msg = "po(po_to_markup) - $page : " . shift;
1132 error($msg, sub { unlink $infile, $outfile});
1135 writefile(basename($infile), File::Spec->tmpdir, $content)
1136 or return $fail->(sprintf(gettext("failed to write %s"), $infile));
1138 my $masterfile = srcfile($pagesources{masterpage($page)});
1139 my $doc=Locale::Po4a::Chooser::new(po4a_type($masterfile),
1140 po4a_options($masterfile));
1142 'po_in_name' => [ $infile ],
1143 'file_in_name' => [ $masterfile ],
1144 'file_in_charset' => 'UTF-8',
1145 'file_out_charset' => 'UTF-8',
1146 ) or return $fail->(gettext("failed to translate"));
1147 $doc->write($outfile)
1148 or return $fail->(sprintf(gettext("failed to write %s"), $outfile));
1150 $content = readfile($outfile);
1152 # Unlinking should happen automatically, thanks to File::Temp,
1153 # but it does not work here, probably because of the way writefile()
1154 # and Locale::Po4a::write() work.
1155 unlink $infile, $outfile;
1160 # returns a SuccessReason or FailReason object
1162 my $content = shift;
1164 # NB: we don't use po_to_markup here, since Po4a parser does
1165 # not mind invalid PO content
1166 $content = '' unless defined $content;
1167 $content = decode_utf8(encode_utf8($content));
1169 # There are incompatibilities between some File::Temp versions
1170 # (including 0.18, bundled with Lenny's perl-modules package)
1171 # and others (e.g. 0.20, previously present in the archive as
1172 # a standalone package): under certain circumstances, some
1173 # return a relative filename, whereas others return an absolute one;
1174 # we here use this module in a way that is at least compatible
1175 # with 0.18 and 0.20. Beware, hit'n'run refactorers!
1176 my $infile = new File::Temp(TEMPLATE => "ikiwiki-po-isvalidpo.XXXXXXXXXX",
1177 DIR => File::Spec->tmpdir,
1178 UNLINK => 1)->filename;
1180 my $fail = sub ($) {
1181 my $msg = '[po/isvalidpo] ' . shift;
1183 return IkiWiki::FailReason->new("$msg");
1186 writefile(basename($infile), File::Spec->tmpdir, $content)
1187 or return $fail->(sprintf(gettext("failed to write %s"), $infile));
1189 my $res = (system("msgfmt", "--check", $infile, "-o", "/dev/null") == 0);
1191 # Unlinking should happen automatically, thanks to File::Temp,
1192 # but it does not work here, probably because of the way writefile()
1193 # and Locale::Po4a::write() work.
1197 return IkiWiki::SuccessReason->new("valid gettext data");
1199 return IkiWiki::FailReason->new(gettext("invalid gettext data, go back ".
1200 "to previous page to continue edit"));
1206 my $pagetype = pagetype($file);
1207 if ($pagetype eq 'html') {
1213 sub po4a_options($) {
1217 my $pagetype = pagetype($file);
1219 if ($pagetype eq 'html') {
1220 # how to disable options is not consistent across po4a modules
1221 $options{includessi} = '';
1222 $options{includeexternal} = 0;
1224 elsif ($pagetype eq 'mdwn') {
1225 $options{markdown} = 1;
1228 $options{markdown} = 0;
1238 package IkiWiki::PageSpec;
1240 sub match_istranslation ($;@) {
1243 if (IkiWiki::Plugin::po::istranslation($page)) {
1244 return IkiWiki::SuccessReason->new("is a translation page");
1247 return IkiWiki::FailReason->new("is not a translation page");
1251 sub match_istranslatable ($;@) {
1254 if (IkiWiki::Plugin::po::istranslatable($page)) {
1255 return IkiWiki::SuccessReason->new("is set as translatable in po_translatable_pages");
1258 return IkiWiki::FailReason->new("is not set as translatable in po_translatable_pages");
1262 sub match_lang ($$;@) {
1266 my $regexp=IkiWiki::glob2re($wanted);
1267 my $lang=IkiWiki::Plugin::po::lang($page);
1268 if ($lang !~ /^$regexp$/i) {
1269 return IkiWiki::FailReason->new("file language is $lang, not $wanted");
1272 return IkiWiki::SuccessReason->new("file language is $wanted");
1276 sub match_currentlang ($$;@) {
1281 return IkiWiki::FailReason->new("no location provided") unless exists $params{location};
1283 my $currentlang=IkiWiki::Plugin::po::lang($params{location});
1284 my $lang=IkiWiki::Plugin::po::lang($page);
1286 if ($lang eq $currentlang) {
1287 return IkiWiki::SuccessReason->new("file language is the same as current one, i.e. $currentlang");
1290 return IkiWiki::FailReason->new("file language is $lang, whereas current language is $currentlang");
1294 sub match_needstranslation ($$;@) {
1298 if (defined $wanted && $wanted ne "") {
1299 if ($wanted !~ /^\d+$/) {
1300 return IkiWiki::FailReason->new("parameter is not an integer");
1302 elsif ($wanted > 100) {
1303 return IkiWiki::FailReason->new("parameter is greater than 100");
1310 my $percenttranslated=IkiWiki::Plugin::po::percenttranslated($page);
1311 if ($percenttranslated eq 'N/A') {
1312 return IkiWiki::FailReason->new("file is not a translatable page");
1314 elsif ($percenttranslated < $wanted) {
1315 return IkiWiki::SuccessReason->new("file has $percenttranslated translated");
1318 return IkiWiki::FailReason->new("file is translated enough");