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; # orderer 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 for (my $i=0; $i<@{$config{po_slave_languages}}; $i = $i + 2) {
145 $slaves{$config{po_slave_languages}->[$i]} = $config{po_slave_languages}->[$i + 1];
146 push @slavelanguages, $config{po_slave_languages}->[$i];
148 $config{po_slave_languages} = \%slaves;
150 elsif (ref $config{po_slave_languages} eq 'HASH') {
151 @slavelanguages = sort {
152 $config{po_slave_languages}->{$a} cmp $config{po_slave_languages}->{$b};
153 } keys %{$config{po_slave_languages}};
156 delete $config{po_slave_languages}{$config{po_master_language}{code}};;
160 or error(sprintf(gettext("%s is not a valid language code"), $_));
161 } ($config{po_master_language}{code}, keys %{$config{po_slave_languages}});
163 if (! exists $config{po_translatable_pages} ||
164 ! defined $config{po_translatable_pages}) {
165 $config{po_translatable_pages}="";
167 if (! exists $config{po_link_to} ||
168 ! defined $config{po_link_to}) {
169 $config{po_link_to}='default';
171 elsif ($config{po_link_to} !~ /^(default|current|negotiated)$/) {
172 warn(sprintf(gettext('%s is not a valid value for po_link_to, falling back to po_link_to=default'),
173 $config{po_link_to}));
174 $config{po_link_to}='default';
176 elsif ($config{po_link_to} eq "negotiated" && ! $config{usedirs}) {
177 warn(gettext('po_link_to=negotiated requires usedirs to be enabled, falling back to po_link_to=default'));
178 $config{po_link_to}='default';
181 push @{$config{wiki_file_prune_regexps}}, qr/\.pot$/;
183 # Translated versions of the underlays are added if available.
184 foreach my $underlay ("basewiki",
185 map { m/^\Q$config{underlaydirbase}\E\/*(.*)/ }
186 reverse @{$config{underlaydirs}}) {
187 next if $underlay=~/^locale\//;
189 # Underlays containing the po files for slave languages.
190 foreach my $ll (keys %{$config{po_slave_languages}}) {
191 add_underlay("po/$ll/$underlay")
192 if -d "$config{underlaydirbase}/po/$ll/$underlay";
195 if ($config{po_master_language}{code} ne 'en') {
196 # Add underlay containing translated source files
197 # for the master language.
198 add_underlay("locale/$config{po_master_language}{code}/$underlay")
199 if -d "$config{underlaydirbase}/locale/$config{po_master_language}{code}/$underlay";
205 my $needsbuild=shift;
207 # backup @needsbuild content so that change() can know whether
208 # a given master page was rendered because its source file was changed
209 @origneedsbuild=(@$needsbuild);
212 buildtranslationscache();
214 # make existing translations depend on the corresponding master page
215 foreach my $master (keys %translations) {
216 map add_depends($_, $master), values %{otherlanguages_pages($master)};
220 # Massage the recorded state of internal links so that:
221 # - it matches the actually generated links, rather than the links as written
222 # in the pages' source
223 # - backlinks are consistent in all cases
226 my $page=$params{page};
227 my $content=$params{content};
229 if (istranslation($page)) {
230 foreach my $destpage (@{$links{$page}}) {
231 if (istranslatable($destpage)) {
232 # replace the occurence of $destpage in $links{$page}
233 for (my $i=0; $i<@{$links{$page}}; $i++) {
234 if (@{$links{$page}}[$i] eq $destpage) {
235 @{$links{$page}}[$i] = $destpage . '.' . lang($page);
242 elsif (! istranslatable($page) && ! istranslation($page)) {
243 foreach my $destpage (@{$links{$page}}) {
244 if (istranslatable($destpage)) {
245 # make sure any destpage's translations has
246 # $page in its backlinks
247 push @{$links{$page}},
248 values %{otherlanguages_pages($destpage)};
254 # We use filter to convert PO to the master page's format,
255 # since the rest of ikiwiki should not work on PO files.
259 my $page = $params{page};
260 my $destpage = $params{destpage};
261 my $content = $params{content};
263 my @caller = caller(4);
264 # FIXME: need to whitelist inline as well?
265 unless ($caller[3] eq "IkiWiki::render" ||
266 $caller[3] eq 'IkiWiki::Plugin::sidebar::sidebar_content') {
270 if (istranslation($page) && ! alreadyfiltered($page, $destpage)) {
271 $content = po_to_markup($page, $content);
272 setalreadyfiltered($page, $destpage);
280 my $page = $params{page};
281 my $content = $params{content};
283 # ignore PO files this plugin did not create
284 return $content unless istranslation($page);
286 # force content to be htmlize'd as if it was the same type as the master page
287 return IkiWiki::htmlize($page, $page,
288 pagetype(srcfile($pagesources{masterpage($page)})),
292 sub pagetemplate (@) {
294 my $page=$params{page};
295 my $destpage=$params{destpage};
296 my $template=$params{template};
298 my ($masterpage, $lang) = istranslation($page);
300 if (istranslation($page) && $template->query(name => "percenttranslated")) {
301 $template->param(percenttranslated => percenttranslated($page));
303 if ($template->query(name => "istranslation")) {
304 $template->param(istranslation => scalar istranslation($page));
306 if ($template->query(name => "istranslatable")) {
307 $template->param(istranslatable => istranslatable($page));
309 if ($template->query(name => "HOMEPAGEURL")) {
310 $template->param(homepageurl => homepageurl($page));
312 if ($template->query(name => "otherlanguages")) {
313 $template->param(otherlanguages => [otherlanguagesloop($page)]);
314 map add_depends($page, $_), (values %{otherlanguages_pages($page)});
316 if ($config{discussion} && istranslation($page)) {
317 if ($page !~ /.*\/\Q$config{discussionpage}\E$/i &&
318 (length $config{cgiurl} ||
319 exists $links{$masterpage."/".lc($config{discussionpage})})) {
320 $template->param('discussionlink' => htmllink(
323 $masterpage . '/' . $config{discussionpage},
326 linktext => $config{discussionpage},
330 # Remove broken parentlink to ./index.html on home page's translations.
331 # It works because this hook has the "last" parameter set, to ensure it
332 # runs after parentlinks' own pagetemplate hook.
333 if ($template->param('parentlinks')
334 && istranslation($page)
335 && $masterpage eq "index") {
336 $template->param('parentlinks' => []);
338 if (ishomepage($page) && $template->query(name => "title")) {
339 $template->param(title => $config{wikiname});
343 # Add the renamed page translations to the list of to-be-renamed pages.
344 sub renamepages (@) {
347 my %torename = %{$params{torename}};
348 my $session = $params{session};
350 # Save the page(s) the user asked to rename, so that our
351 # canrename hook can tell the difference between:
352 # - a translation being renamed as a consequence of its master page
354 # - a user trying to directly rename a translation
355 # This is why this hook has to be run first, before the list of pages
356 # to rename is modified by other plugins.
358 @orig_torename=@{$session->param("po_orig_torename")}
359 if defined $session->param("po_orig_torename");
360 push @orig_torename, $torename{src};
361 $session->param(po_orig_torename => \@orig_torename);
362 IkiWiki::cgi_savesession($session);
364 return () unless istranslatable($torename{src});
367 my %otherpages=%{otherlanguages_pages($torename{src})};
368 while (my ($lang, $otherpage) = each %otherpages) {
371 srcfile => $pagesources{$otherpage},
372 dest => otherlanguage_page($torename{dest}, $lang),
373 destfile => $torename{dest}.".".$lang.".po",
383 map { deletetranslations($_) } grep istranslatablefile($_), @deleted;
389 # All meta titles are first extracted at scan time, i.e. before we turn
390 # PO files back into translated markdown; escaping of double-quotes in
391 # PO files breaks the meta plugin's parsing enough to save ugly titles
392 # to %pagestate at this time.
394 # Then, at render time, every page passes in turn through the Great
395 # Rendering Chain (filter->preprocess->linkify->htmlize), and the meta
396 # plugin's preprocess hook is this time in a position to correctly
397 # extract the titles from slave pages.
399 # This is, unfortunately, too late: if the page A, linking to the page
400 # B, is rendered before B, it will display the wrongly-extracted meta
401 # title as the link text to B.
403 # On the one hand, such a corner case only happens on rebuild: on
404 # refresh, every rendered page is fixed to contain correct meta titles.
405 # On the other hand, it can take some time to get every page fixed.
406 # We therefore re-render every rendered page after a rebuild to fix them
407 # at once. As this more or less doubles the time needed to rebuild the
408 # wiki, we do so only when really needed.
411 && exists $config{rebuild} && defined $config{rebuild} && $config{rebuild}
412 && UNIVERSAL::can("IkiWiki::Plugin::meta", "getsetup")
413 && exists $config{meta_overrides_page_title}
414 && defined $config{meta_overrides_page_title}
415 && $config{meta_overrides_page_title}) {
416 debug(sprintf(gettext("rebuilding all pages to fix meta titles")));
417 resetalreadyfiltered();
418 require IkiWiki::Render;
419 foreach my $file (@rendered) {
420 IkiWiki::render($file, sprintf(gettext("building %s"), $file));
424 my $updated_po_files=0;
426 # Refresh/create POT and PO files as needed.
427 foreach my $file (grep {istranslatablefile($_)} @rendered) {
428 my $masterfile=srcfile($file);
429 my $page=pagename($file);
430 my $updated_pot_file=0;
432 # Avoid touching underlay files.
433 next if $masterfile ne "$config{srcdir}/$file";
435 # Only refresh POT file if it does not exist, or if
436 # the source was changed: don't if only the HTML was
437 # refreshed, e.g. because of a dependency.
438 if ((grep { $_ eq $pagesources{$page} } @origneedsbuild) ||
439 ! -e potfile($masterfile)) {
440 refreshpot($masterfile);
444 foreach my $po (pofiles($masterfile)) {
445 next if ! $updated_pot_file && -e $po;
446 next if grep { $po=~/\Q$_\E/ } @{$config{underlaydirs}};
450 refreshpofiles($masterfile, @pofiles);
451 map { s/^\Q$config{srcdir}\E\/*//; IkiWiki::rcs_add($_) } @pofiles if $config{rcs};
456 if ($updated_po_files) {
458 gettext("updated PO files"));
462 sub checkcontent (@) {
465 if (istranslation($params{page})) {
466 my $res = isvalidpo($params{content});
480 if (istranslation($params{page})) {
481 return gettext("Can not remove a translation. If the master page is removed, ".
482 "however, its translations will be removed as well.");
489 my $session = $params{session};
491 if (istranslation($params{src})) {
492 my $masterpage = masterpage($params{src});
493 # Tell the difference between:
494 # - a translation being renamed as a consequence of its master page
495 # being renamed, which is allowed
496 # - a user trying to directly rename a translation, which is forbidden
497 # by looking for the master page in the list of to-be-renamed pages we
498 # saved early in the renaming process.
499 my $orig_torename = $session->param("po_orig_torename");
500 unless (grep { $_ eq $masterpage } @{$orig_torename}) {
501 return gettext("Can not rename a translation. If the master page is renamed, ".
502 "however, its translations will be renamed as well.");
508 # As we're previewing or saving a page, the content may have
509 # changed, so tell the next filter() invocation it must not be lazy.
513 unsetalreadyfiltered($params{page}, $params{page});
514 return $params{content};
517 sub formbuilder_setup (@) {
519 my $form=$params{form};
522 return unless defined $form->field("do");
524 if ($form->field("do") eq "create") {
525 # Warn the user: new pages must be written in master language.
526 my $template=template("pocreatepage.tmpl");
527 $template->param(LANG => $config{po_master_language}{name});
528 $form->tmpl_param(message => $template->output);
530 elsif ($form->field("do") eq "edit") {
531 # Remove the rename/remove buttons on slave pages.
532 # This has to be done after the rename/remove plugins have added
533 # their buttons, which is why this hook must be run last.
534 # The canrename/canremove hooks already ensure this is forbidden
535 # at the backend level, so this is only UI sugar.
536 if (istranslation($form->field("page"))) {
538 for (my $i = 0; $i < @{$params{buttons}}; $i++) {
539 if (@{$params{buttons}}[$i] eq $_) {
540 delete @{$params{buttons}}[$i];
549 sub formbuilder (@) {
551 my $form=$params{form};
554 return unless defined $form->field("do");
556 # Do not allow to create pages of type po: they are automatically created.
557 # The main reason to do so is to bypass the "favor the type of linking page
558 # on page creation" logic, which is unsuitable when a broken link is clicked
559 # on a slave (PO) page.
560 # This cannot be done in the formbuilder_setup hook as the list of types is
562 if ($form->field("do") eq "create") {
563 foreach my $field ($form->field) {
564 next unless "$field" eq "type";
565 next unless $field->type eq 'select';
566 my $orig_value = $field->value;
567 # remove po from the list of types
568 my @types = grep { $_->[0] ne 'po' } $field->options;
569 $field->options(\@types) if @types;
570 # favor the type of linking page's masterpage
571 if ($orig_value eq 'po') {
573 if (defined $form->field('from')) {
574 ($from)=$form->field('from')=~/$config{wiki_file_regexp}/;
575 $from = masterpage($from);
577 if (defined $from && exists $pagesources{$from}) {
578 $type=pagetype($pagesources{$from});
580 $type=$config{default_pageext} unless defined $type;
581 $field->value($type) ;
588 # | Injected functions
591 # Implement po_link_to 'current' and 'negotiated' settings.
592 sub mybestlink ($$) {
596 return $origsubs{'bestlink'}->($page, $link)
597 if defined $config{po_link_to} && $config{po_link_to} eq "default";
599 my $res=$origsubs{'bestlink'}->(masterpage($page), $link);
600 my @caller = caller(1);
602 && istranslatable($res)
603 && istranslation($page)
604 && !(exists $caller[3] && defined $caller[3]
605 && ($caller[3] eq "IkiWiki::PageSpec::match_link"))) {
606 return $res . "." . lang($page);
611 sub mybeautify_urlpath ($) {
614 my $res=$origsubs{'beautify_urlpath'}->($url);
615 if (defined $config{po_link_to} && $config{po_link_to} eq "negotiated") {
616 $res =~ s!/\Qindex.$config{po_master_language}{code}.$config{htmlext}\E$!/!;
617 $res =~ s!/\Qindex.$config{htmlext}\E$!/!;
619 $res =~ s!/\Qindex.$_.$config{htmlext}\E$!/!;
620 } (keys %{$config{po_slave_languages}});
625 sub mytargetpage ($$) {
629 if (istranslation($page) || istranslatable($page)) {
630 my ($masterpage, $lang) = (masterpage($page), lang($page));
631 if (! $config{usedirs} || $masterpage eq 'index') {
632 return $masterpage . "." . $lang . "." . $ext;
635 return $masterpage . "/index." . $lang . "." . $ext;
638 return $origsubs{'targetpage'}->($page, $ext);
646 # workaround hard-coded /index.$config{htmlext} in IkiWiki::urlto()
648 && $config{po_link_to} eq "current"
649 && istranslatable('index')) {
650 return IkiWiki::beautify_urlpath(IkiWiki::baseurl($from) . "index." . lang($from) . ".$config{htmlext}");
652 # avoid using our injected beautify_urlpath if run by cgi_editpage,
653 # so that one is redirected to the just-edited page rather than to the
654 # negociated translation; to prevent unnecessary fiddling with caller/inject,
655 # we only do so when our beautify_urlpath would actually do what we want to
656 # avoid, i.e. when po_link_to = negotiated.
657 # also avoid doing so when run by cgi_goto, so that the links on recentchanges
658 # page actually lead to the exact page they pretend to.
659 if ($config{po_link_to} eq "negotiated") {
660 my @caller = caller(1);
662 $use_orig = 1 if (exists $caller[3] && defined $caller[3]
663 && ($caller[3] eq "IkiWiki::cgi_editpage" ||
664 $caller[3] eq "IkiWiki::Plugin::goto::cgi_goto")
666 inject(name => "IkiWiki::beautify_urlpath", call => $origsubs{'beautify_urlpath'})
668 my $res = $origsubs{'urlto'}->($to,$from,$absolute);
669 inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath)
674 return $origsubs{'urlto'}->($to,$from,$absolute)
681 # slave pages have no subpages
682 if (istranslation($params{'from'})) {
683 $params{'from'} = masterpage($params{'from'});
685 return $origsubs{'cgiurl'}->(%params);
692 if (exists $params{rootpage}) {
693 $rootpage=$origsubs{'bestlink'}->($params{page}, $params{rootpage});
694 if (!length $rootpage) {
695 $rootpage=$params{rootpage};
699 $rootpage=masterpage($params{page});
704 sub myisselflink ($$) {
708 return 1 if $origsubs{'isselflink'}->($page, $link);
709 if (istranslation($page)) {
710 return $origsubs{'isselflink'}->(masterpage($page), $link);
716 # | Blackboxes for private data
722 sub alreadyfiltered($$) {
726 return exists $filtered{$page}{$destpage}
727 && $filtered{$page}{$destpage} eq 1;
730 sub setalreadyfiltered($$) {
734 $filtered{$page}{$destpage}=1;
737 sub unsetalreadyfiltered($$) {
741 if (exists $filtered{$page}{$destpage}) {
742 delete $filtered{$page}{$destpage};
746 sub resetalreadyfiltered() {
755 sub maybe_add_leading_slash ($;$) {
758 $add=1 unless defined $add;
759 return '/' . $str if $add;
763 sub istranslatablefile ($) {
766 return 0 unless defined $file;
767 my $type=pagetype($file);
768 return 0 if ! defined $type || $type eq 'po';
769 return 0 if $file =~ /\.pot$/;
770 return 0 if ! defined $config{po_translatable_pages};
771 return 1 if pagespec_match(pagename($file), $config{po_translatable_pages});
775 sub istranslatable ($) {
779 return 1 if istranslatablefile($pagesources{$page});
783 sub _istranslation ($) {
786 $page='' unless defined $page && length $page;
787 my $hasleadingslash = ($page=~s#^/##);
788 my $file=$pagesources{$page};
789 return 0 unless defined $file
790 && defined pagetype($file)
791 && pagetype($file) eq 'po';
792 return 0 if $file =~ /\.pot$/;
794 my ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
795 return 0 unless defined $masterpage && defined $lang
796 && length $masterpage && length $lang
797 && defined $pagesources{$masterpage}
798 && defined $config{po_slave_languages}{$lang};
800 return (maybe_add_leading_slash($masterpage, $hasleadingslash), $lang)
801 if istranslatable($masterpage);
804 sub istranslation ($) {
807 if (1 < (my ($masterpage, $lang) = _istranslation($page))) {
808 my $hasleadingslash = ($masterpage=~s#^/##);
809 $translations{$masterpage}{$lang}=$page unless exists $translations{$masterpage}{$lang};
810 return (maybe_add_leading_slash($masterpage, $hasleadingslash), $lang);
818 if ( 1 < (my ($masterpage, $lang) = _istranslation($page))) {
827 if (1 < (my ($masterpage, $lang) = _istranslation($page))) {
830 return $config{po_master_language}{code};
833 sub islanguagecode ($) {
836 return $code =~ /^[a-z]{2}$/;
839 sub otherlanguage_page ($$) {
843 return masterpage($page) if $code eq $config{po_master_language}{code};
844 return masterpage($page) . '.' . $code;
847 # Returns the list of other languages codes: the master language comes first,
848 # then the codes are ordered the same way as in po_slave_languages, if it is
849 # an array, or in the language name lexical order, if it is a hash.
850 sub otherlanguages_codes ($) {
854 return \@ret unless istranslation($page) || istranslatable($page);
855 my $curlang=lang($page);
857 ($config{po_master_language}{code}, @slavelanguages) {
858 next if $lang eq $curlang;
864 sub otherlanguages_pages ($) {
869 $ret{$_} = otherlanguage_page($page, $_)
870 } otherlanguages_codes($page);
876 my $masterfile=shift;
878 (my $name, my $dir, my $suffix) = fileparse($masterfile, qr/\.[^.]*/);
879 $dir='' if $dir eq './';
880 return File::Spec->catpath('', $dir, $name . ".pot");
884 my $masterfile=shift;
887 (my $name, my $dir, my $suffix) = fileparse($masterfile, qr/\.[^.]*/);
888 $dir='' if $dir eq './';
889 return File::Spec->catpath('', $dir, $name . "." . $lang . ".po");
893 my $masterfile=shift;
895 return map pofile($masterfile, $_), (keys %{$config{po_slave_languages}});
899 my $masterfile=shift;
901 my $potfile=potfile($masterfile);
902 my $doc=Locale::Po4a::Chooser::new(po4a_type($masterfile),
903 po4a_options($masterfile));
904 $doc->{TT}{utf_mode} = 1;
905 $doc->{TT}{file_in_charset} = 'utf-8';
906 $doc->{TT}{file_out_charset} = 'utf-8';
907 $doc->read($masterfile);
908 # let's cheat a bit to force porefs option to be passed to
909 # Locale::Po4a::Po; this is undocument use of internal
910 # Locale::Po4a::TransTractor's data, compulsory since this module
911 # prevents us from using the porefs option.
912 $doc->{TT}{po_out}=Locale::Po4a::Po->new({ 'porefs' => 'none' });
913 $doc->{TT}{po_out}->set_charset('utf-8');
916 IkiWiki::prep_writefile(basename($potfile),dirname($potfile));
917 $doc->writepo($potfile);
920 sub refreshpofiles ($@) {
921 my $masterfile=shift;
924 my $potfile=potfile($masterfile);
926 error("po(refreshpofiles) ".sprintf(gettext("POT file (%s) does not exist"), $potfile));
929 foreach my $pofile (@pofiles) {
930 IkiWiki::prep_writefile(basename($pofile),dirname($pofile));
933 # If the po file exists in an underlay, copy it
935 my ($pobase)=$pofile=~/^\Q$config{srcdir}\E\/?(.*)$/;
936 foreach my $dir (@{$config{underlaydirs}}) {
937 if (-e "$dir/$pobase") {
938 File::Copy::syscopy("$dir/$pobase",$pofile)
939 or error("po(refreshpofiles) ".
940 sprintf(gettext("failed to copy underlay PO file to %s"),
947 system("msgmerge", "--previous", "-q", "-U", "--backup=none", $pofile, $potfile) == 0
948 or error("po(refreshpofiles) ".
949 sprintf(gettext("failed to update %s"),
953 File::Copy::syscopy($potfile,$pofile)
954 or error("po(refreshpofiles) ".
955 sprintf(gettext("failed to copy the POT file to %s"),
961 sub buildtranslationscache() {
962 # use istranslation's side-effect
963 map istranslation($_), (keys %pagesources);
966 sub resettranslationscache() {
970 sub flushmemoizecache() {
971 Memoize::flush_cache("istranslatable");
972 Memoize::flush_cache("_istranslation");
973 Memoize::flush_cache("percenttranslated");
976 sub urlto_with_orig_beautiful_urlpath($$) {
980 inject(name => "IkiWiki::beautify_urlpath", call => $origsubs{'beautify_urlpath'});
981 my $res=urlto($to, $from);
982 inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath);
987 sub percenttranslated ($) {
991 return gettext("N/A") unless istranslation($page);
992 my $file=srcfile($pagesources{$page});
993 my $masterfile = srcfile($pagesources{masterpage($page)});
994 my $doc=Locale::Po4a::Chooser::new(po4a_type($masterfile),
995 po4a_options($masterfile));
997 'po_in_name' => [ $file ],
998 'file_in_name' => [ $masterfile ],
999 'file_in_charset' => 'utf-8',
1000 'file_out_charset' => 'utf-8',
1001 ) or error("po(percenttranslated) ".
1002 sprintf(gettext("failed to translate %s"), $page));
1003 my ($percent,$hit,$queries) = $doc->stats();
1004 $percent =~ s/\.[0-9]+$//;
1008 sub languagename ($) {
1011 return $config{po_master_language}{name}
1012 if $code eq $config{po_master_language}{code};
1013 return $config{po_slave_languages}{$code}
1014 if defined $config{po_slave_languages}{$code};
1018 sub otherlanguagesloop ($) {
1022 if (istranslation($page)) {
1024 url => urlto_with_orig_beautiful_urlpath(masterpage($page), $page),
1025 code => $config{po_master_language}{code},
1026 language => $config{po_master_language}{name},
1030 foreach my $lang (@{otherlanguages_codes($page)}) {
1031 next if $lang eq $config{po_master_language}{code};
1032 my $otherpage = otherlanguage_page($page, $lang);
1034 url => urlto_with_orig_beautiful_urlpath($otherpage, $page),
1036 language => languagename($lang),
1037 percent => percenttranslated($otherpage),
1043 sub homepageurl (;$) {
1046 return urlto('', $page);
1049 sub ishomepage ($) {
1052 return 1 if $page eq 'index';
1053 map { return 1 if $page eq 'index.'.$_ } keys %{$config{po_slave_languages}};
1057 sub deletetranslations ($) {
1058 my $deletedmasterfile=shift;
1060 my $deletedmasterpage=pagename($deletedmasterfile);
1063 my $file = newpagefile($deletedmasterpage.'.'.$_, 'po');
1064 my $absfile = "$config{srcdir}/$file";
1065 if (-e $absfile && ! -l $absfile && ! -d $absfile) {
1066 push @todelete, $file;
1068 } keys %{$config{po_slave_languages}};
1072 IkiWiki::rcs_remove($_);
1075 IkiWiki::prune("$config{srcdir}/$_");
1081 gettext("removed obsolete PO files"));
1085 sub commit_and_refresh ($) {
1089 IkiWiki::disable_commit_hook();
1090 IkiWiki::rcs_commit_staged(
1093 IkiWiki::enable_commit_hook();
1094 IkiWiki::rcs_update();
1096 # Reinitialize module's private variables.
1097 resetalreadyfiltered();
1098 resettranslationscache();
1099 flushmemoizecache();
1100 # Trigger a wiki refresh.
1101 require IkiWiki::Render;
1102 # without preliminary saveindex/loadindex, refresh()
1103 # complains about a lot of uninitialized variables
1104 IkiWiki::saveindex();
1105 IkiWiki::loadindex();
1107 IkiWiki::saveindex();
1110 sub po_to_markup ($$) {
1111 my ($page, $content) = (shift, shift);
1113 $content = '' unless defined $content;
1114 $content = decode_utf8(encode_utf8($content));
1115 # CRLF line terminators make poor Locale::Po4a feel bad
1116 $content=~s/\r\n/\n/g;
1118 # There are incompatibilities between some File::Temp versions
1119 # (including 0.18, bundled with Lenny's perl-modules package)
1120 # and others (e.g. 0.20, previously present in the archive as
1121 # a standalone package): under certain circumstances, some
1122 # return a relative filename, whereas others return an absolute one;
1123 # we here use this module in a way that is at least compatible
1124 # with 0.18 and 0.20. Beware, hit'n'run refactorers!
1125 my $infile = new File::Temp(TEMPLATE => "ikiwiki-po-filter-in.XXXXXXXXXX",
1126 DIR => File::Spec->tmpdir,
1127 UNLINK => 1)->filename;
1128 my $outfile = new File::Temp(TEMPLATE => "ikiwiki-po-filter-out.XXXXXXXXXX",
1129 DIR => File::Spec->tmpdir,
1130 UNLINK => 1)->filename;
1132 my $fail = sub ($) {
1133 my $msg = "po(po_to_markup) - $page : " . shift;
1134 error($msg, sub { unlink $infile, $outfile});
1137 writefile(basename($infile), File::Spec->tmpdir, $content)
1138 or return $fail->(sprintf(gettext("failed to write %s"), $infile));
1140 my $masterfile = srcfile($pagesources{masterpage($page)});
1141 my $doc=Locale::Po4a::Chooser::new(po4a_type($masterfile),
1142 po4a_options($masterfile));
1144 'po_in_name' => [ $infile ],
1145 'file_in_name' => [ $masterfile ],
1146 'file_in_charset' => 'utf-8',
1147 'file_out_charset' => 'utf-8',
1148 ) or return $fail->(gettext("failed to translate"));
1149 $doc->write($outfile)
1150 or return $fail->(sprintf(gettext("failed to write %s"), $outfile));
1152 $content = readfile($outfile);
1154 # Unlinking should happen automatically, thanks to File::Temp,
1155 # but it does not work here, probably because of the way writefile()
1156 # and Locale::Po4a::write() work.
1157 unlink $infile, $outfile;
1162 # returns a SuccessReason or FailReason object
1164 my $content = shift;
1166 # NB: we don't use po_to_markup here, since Po4a parser does
1167 # not mind invalid PO content
1168 $content = '' unless defined $content;
1169 $content = decode_utf8(encode_utf8($content));
1171 # There are incompatibilities between some File::Temp versions
1172 # (including 0.18, bundled with Lenny's perl-modules package)
1173 # and others (e.g. 0.20, previously present in the archive as
1174 # a standalone package): under certain circumstances, some
1175 # return a relative filename, whereas others return an absolute one;
1176 # we here use this module in a way that is at least compatible
1177 # with 0.18 and 0.20. Beware, hit'n'run refactorers!
1178 my $infile = new File::Temp(TEMPLATE => "ikiwiki-po-isvalidpo.XXXXXXXXXX",
1179 DIR => File::Spec->tmpdir,
1180 UNLINK => 1)->filename;
1182 my $fail = sub ($) {
1183 my $msg = '[po/isvalidpo] ' . shift;
1185 return IkiWiki::FailReason->new("$msg");
1188 writefile(basename($infile), File::Spec->tmpdir, $content)
1189 or return $fail->(sprintf(gettext("failed to write %s"), $infile));
1191 my $res = (system("msgfmt", "--check", $infile, "-o", "/dev/null") == 0);
1193 # Unlinking should happen automatically, thanks to File::Temp,
1194 # but it does not work here, probably because of the way writefile()
1195 # and Locale::Po4a::write() work.
1199 return IkiWiki::SuccessReason->new("valid gettext data");
1201 return IkiWiki::FailReason->new(gettext("invalid gettext data, go back ".
1202 "to previous page to continue edit"));
1208 my $pagetype = pagetype($file);
1209 if ($pagetype eq 'html') {
1215 sub po4a_options($) {
1219 my $pagetype = pagetype($file);
1221 if ($pagetype eq 'html') {
1222 # how to disable options is not consistent across po4a modules
1223 $options{includessi} = '';
1224 $options{includeexternal} = 0;
1226 elsif ($pagetype eq 'mdwn') {
1227 $options{markdown} = 1;
1230 $options{markdown} = 0;
1240 package IkiWiki::PageSpec;
1242 sub match_istranslation ($;@) {
1245 if (IkiWiki::Plugin::po::istranslation($page)) {
1246 return IkiWiki::SuccessReason->new("is a translation page");
1249 return IkiWiki::FailReason->new("is not a translation page");
1253 sub match_istranslatable ($;@) {
1256 if (IkiWiki::Plugin::po::istranslatable($page)) {
1257 return IkiWiki::SuccessReason->new("is set as translatable in po_translatable_pages");
1260 return IkiWiki::FailReason->new("is not set as translatable in po_translatable_pages");
1264 sub match_lang ($$;@) {
1268 my $regexp=IkiWiki::glob2re($wanted);
1269 my $lang=IkiWiki::Plugin::po::lang($page);
1270 if ($lang !~ /^$regexp$/i) {
1271 return IkiWiki::FailReason->new("file language is $lang, not $wanted");
1274 return IkiWiki::SuccessReason->new("file language is $wanted");
1278 sub match_currentlang ($$;@) {
1283 return IkiWiki::FailReason->new("no location provided") unless exists $params{location};
1285 my $currentlang=IkiWiki::Plugin::po::lang($params{location});
1286 my $lang=IkiWiki::Plugin::po::lang($page);
1288 if ($lang eq $currentlang) {
1289 return IkiWiki::SuccessReason->new("file language is the same as current one, i.e. $currentlang");
1292 return IkiWiki::FailReason->new("file language is $lang, whereas current language is $currentlang");