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};
262 if (istranslation($page) && ! alreadyfiltered($page, $destpage)) {
263 $content = po_to_markup($page, $content);
264 setalreadyfiltered($page, $destpage);
272 my $page = $params{page};
273 my $content = $params{content};
275 # ignore PO files this plugin did not create
276 return $content unless istranslation($page);
278 # force content to be htmlize'd as if it was the same type as the master page
279 return IkiWiki::htmlize($page, $page,
280 pagetype(srcfile($pagesources{masterpage($page)})),
284 sub pagetemplate (@) {
286 my $page=$params{page};
287 my $destpage=$params{destpage};
288 my $template=$params{template};
290 my ($masterpage, $lang) = istranslation($page);
292 if (istranslation($page) && $template->query(name => "percenttranslated")) {
293 $template->param(percenttranslated => percenttranslated($page));
295 if ($template->query(name => "istranslation")) {
296 $template->param(istranslation => scalar istranslation($page));
298 if ($template->query(name => "istranslatable")) {
299 $template->param(istranslatable => istranslatable($page));
301 if ($template->query(name => "HOMEPAGEURL")) {
302 $template->param(homepageurl => homepageurl($page));
304 if ($template->query(name => "otherlanguages")) {
305 $template->param(otherlanguages => [otherlanguagesloop($page)]);
306 map add_depends($page, $_), (values %{otherlanguages_pages($page)});
308 if ($config{discussion} && istranslation($page)) {
309 if ($page !~ /.*\/\Q$config{discussionpage}\E$/i &&
310 (length $config{cgiurl} ||
311 exists $links{$masterpage."/".lc($config{discussionpage})})) {
312 $template->param('discussionlink' => htmllink(
315 $masterpage . '/' . $config{discussionpage},
318 linktext => $config{discussionpage},
322 # Remove broken parentlink to ./index.html on home page's translations.
323 # It works because this hook has the "last" parameter set, to ensure it
324 # runs after parentlinks' own pagetemplate hook.
325 if ($template->param('parentlinks')
326 && istranslation($page)
327 && $masterpage eq "index") {
328 $template->param('parentlinks' => []);
330 if (ishomepage($page) && $template->query(name => "title")) {
331 $template->param(title => $config{wikiname});
335 # Add the renamed page translations to the list of to-be-renamed pages.
336 sub renamepages (@) {
339 my %torename = %{$params{torename}};
340 my $session = $params{session};
342 # Save the page(s) the user asked to rename, so that our
343 # canrename hook can tell the difference between:
344 # - a translation being renamed as a consequence of its master page
346 # - a user trying to directly rename a translation
347 # This is why this hook has to be run first, before the list of pages
348 # to rename is modified by other plugins.
350 @orig_torename=@{$session->param("po_orig_torename")}
351 if defined $session->param("po_orig_torename");
352 push @orig_torename, $torename{src};
353 $session->param(po_orig_torename => \@orig_torename);
354 IkiWiki::cgi_savesession($session);
356 return () unless istranslatable($torename{src});
359 my %otherpages=%{otherlanguages_pages($torename{src})};
360 while (my ($lang, $otherpage) = each %otherpages) {
363 srcfile => $pagesources{$otherpage},
364 dest => otherlanguage_page($torename{dest}, $lang),
365 destfile => $torename{dest}.".".$lang.".po",
375 map { deletetranslations($_) } grep istranslatablefile($_), @deleted;
381 # All meta titles are first extracted at scan time, i.e. before we turn
382 # PO files back into translated markdown; escaping of double-quotes in
383 # PO files breaks the meta plugin's parsing enough to save ugly titles
384 # to %pagestate at this time.
386 # Then, at render time, every page passes in turn through the Great
387 # Rendering Chain (filter->preprocess->linkify->htmlize), and the meta
388 # plugin's preprocess hook is this time in a position to correctly
389 # extract the titles from slave pages.
391 # This is, unfortunately, too late: if the page A, linking to the page
392 # B, is rendered before B, it will display the wrongly-extracted meta
393 # title as the link text to B.
395 # On the one hand, such a corner case only happens on rebuild: on
396 # refresh, every rendered page is fixed to contain correct meta titles.
397 # On the other hand, it can take some time to get every page fixed.
398 # We therefore re-render every rendered page after a rebuild to fix them
399 # at once. As this more or less doubles the time needed to rebuild the
400 # wiki, we do so only when really needed.
403 && exists $config{rebuild} && defined $config{rebuild} && $config{rebuild}
404 && UNIVERSAL::can("IkiWiki::Plugin::meta", "getsetup")
405 && exists $config{meta_overrides_page_title}
406 && defined $config{meta_overrides_page_title}
407 && $config{meta_overrides_page_title}) {
408 debug(sprintf(gettext("rebuilding all pages to fix meta titles")));
409 resetalreadyfiltered();
410 require IkiWiki::Render;
411 foreach my $file (@rendered) {
412 IkiWiki::render($file, sprintf(gettext("building %s"), $file));
416 my $updated_po_files=0;
418 # Refresh/create POT and PO files as needed.
419 foreach my $file (grep {istranslatablefile($_)} @rendered) {
420 my $masterfile=srcfile($file);
421 my $page=pagename($file);
422 my $updated_pot_file=0;
424 # Avoid touching underlay files.
425 next if $masterfile ne "$config{srcdir}/$file";
427 # Only refresh POT file if it does not exist, or if
428 # the source was changed: don't if only the HTML was
429 # refreshed, e.g. because of a dependency.
430 if ((grep { $_ eq $pagesources{$page} } @origneedsbuild) ||
431 ! -e potfile($masterfile)) {
432 refreshpot($masterfile);
436 foreach my $po (pofiles($masterfile)) {
437 next if ! $updated_pot_file && -e $po;
438 next if grep { $po=~/\Q$_\E/ } @{$config{underlaydirs}};
442 refreshpofiles($masterfile, @pofiles);
443 map { s/^\Q$config{srcdir}\E\/*//; IkiWiki::rcs_add($_) } @pofiles if $config{rcs};
448 if ($updated_po_files) {
450 gettext("updated PO files"));
454 sub checkcontent (@) {
457 if (istranslation($params{page})) {
458 my $res = isvalidpo($params{content});
472 if (istranslation($params{page})) {
473 return gettext("Can not remove a translation. If the master page is removed, ".
474 "however, its translations will be removed as well.");
481 my $session = $params{session};
483 if (istranslation($params{src})) {
484 my $masterpage = masterpage($params{src});
485 # Tell the difference between:
486 # - a translation being renamed as a consequence of its master page
487 # being renamed, which is allowed
488 # - a user trying to directly rename a translation, which is forbidden
489 # by looking for the master page in the list of to-be-renamed pages we
490 # saved early in the renaming process.
491 my $orig_torename = $session->param("po_orig_torename");
492 unless (grep { $_ eq $masterpage } @{$orig_torename}) {
493 return gettext("Can not rename a translation. If the master page is renamed, ".
494 "however, its translations will be renamed as well.");
500 # As we're previewing or saving a page, the content may have
501 # changed, so tell the next filter() invocation it must not be lazy.
505 unsetalreadyfiltered($params{page}, $params{page});
506 return $params{content};
509 sub formbuilder_setup (@) {
511 my $form=$params{form};
514 return unless defined $form->field("do");
516 if ($form->field("do") eq "create") {
517 # Warn the user: new pages must be written in master language.
518 my $template=template("pocreatepage.tmpl");
519 $template->param(LANG => $config{po_master_language}{name});
520 $form->tmpl_param(message => $template->output);
522 elsif ($form->field("do") eq "edit") {
523 # Remove the rename/remove buttons on slave pages.
524 # This has to be done after the rename/remove plugins have added
525 # their buttons, which is why this hook must be run last.
526 # The canrename/canremove hooks already ensure this is forbidden
527 # at the backend level, so this is only UI sugar.
528 if (istranslation($form->field("page"))) {
530 for (my $i = 0; $i < @{$params{buttons}}; $i++) {
531 if (@{$params{buttons}}[$i] eq $_) {
532 delete @{$params{buttons}}[$i];
541 sub formbuilder (@) {
543 my $form=$params{form};
546 return unless defined $form->field("do");
548 # Do not allow to create pages of type po: they are automatically created.
549 # The main reason to do so is to bypass the "favor the type of linking page
550 # on page creation" logic, which is unsuitable when a broken link is clicked
551 # on a slave (PO) page.
552 # This cannot be done in the formbuilder_setup hook as the list of types is
554 if ($form->field("do") eq "create") {
555 foreach my $field ($form->field) {
556 next unless "$field" eq "type";
557 next unless $field->type eq 'select';
558 my $orig_value = $field->value;
559 # remove po from the list of types
560 my @types = grep { $_->[0] ne 'po' } $field->options;
561 $field->options(\@types) if @types;
562 # favor the type of linking page's masterpage
563 if ($orig_value eq 'po') {
565 if (defined $form->field('from')) {
566 ($from)=$form->field('from')=~/$config{wiki_file_regexp}/;
567 $from = masterpage($from);
569 if (defined $from && exists $pagesources{$from}) {
570 $type=pagetype($pagesources{$from});
572 $type=$config{default_pageext} unless defined $type;
573 $field->value($type) ;
580 # | Injected functions
583 # Implement po_link_to 'current' and 'negotiated' settings.
584 sub mybestlink ($$) {
588 return $origsubs{'bestlink'}->($page, $link)
589 if defined $config{po_link_to} && $config{po_link_to} eq "default";
591 my $res=$origsubs{'bestlink'}->(masterpage($page), $link);
592 my @caller = caller(1);
594 && istranslatable($res)
595 && istranslation($page)
596 && !(exists $caller[3] && defined $caller[3]
597 && ($caller[3] eq "IkiWiki::PageSpec::match_link"))) {
598 return $res . "." . lang($page);
603 sub mybeautify_urlpath ($) {
606 my $res=$origsubs{'beautify_urlpath'}->($url);
607 if (defined $config{po_link_to} && $config{po_link_to} eq "negotiated") {
608 $res =~ s!/\Qindex.$config{po_master_language}{code}.$config{htmlext}\E$!/!;
609 $res =~ s!/\Qindex.$config{htmlext}\E$!/!;
611 $res =~ s!/\Qindex.$_.$config{htmlext}\E$!/!;
612 } (keys %{$config{po_slave_languages}});
617 sub mytargetpage ($$) {
621 if (istranslation($page) || istranslatable($page)) {
622 my ($masterpage, $lang) = (masterpage($page), lang($page));
623 if (! $config{usedirs} || $masterpage eq 'index') {
624 return $masterpage . "." . $lang . "." . $ext;
627 return $masterpage . "/index." . $lang . "." . $ext;
630 return $origsubs{'targetpage'}->($page, $ext);
638 # workaround hard-coded /index.$config{htmlext} in IkiWiki::urlto()
640 && $config{po_link_to} eq "current"
641 && istranslatable('index')) {
642 return IkiWiki::beautify_urlpath(IkiWiki::baseurl($from) . "index." . lang($from) . ".$config{htmlext}");
644 # avoid using our injected beautify_urlpath if run by cgi_editpage,
645 # so that one is redirected to the just-edited page rather than to the
646 # negociated translation; to prevent unnecessary fiddling with caller/inject,
647 # we only do so when our beautify_urlpath would actually do what we want to
648 # avoid, i.e. when po_link_to = negotiated.
649 # also avoid doing so when run by cgi_goto, so that the links on recentchanges
650 # page actually lead to the exact page they pretend to.
651 if ($config{po_link_to} eq "negotiated") {
652 my @caller = caller(1);
654 $use_orig = 1 if (exists $caller[3] && defined $caller[3]
655 && ($caller[3] eq "IkiWiki::cgi_editpage" ||
656 $caller[3] eq "IkiWiki::Plugin::goto::cgi_goto")
658 inject(name => "IkiWiki::beautify_urlpath", call => $origsubs{'beautify_urlpath'})
660 my $res = $origsubs{'urlto'}->($to,$from,$absolute);
661 inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath)
666 return $origsubs{'urlto'}->($to,$from,$absolute)
673 # slave pages have no subpages
674 if (istranslation($params{'from'})) {
675 $params{'from'} = masterpage($params{'from'});
677 return $origsubs{'cgiurl'}->(%params);
684 if (exists $params{rootpage}) {
685 $rootpage=$origsubs{'bestlink'}->($params{page}, $params{rootpage});
686 if (!length $rootpage) {
687 $rootpage=$params{rootpage};
691 $rootpage=masterpage($params{page});
696 sub myisselflink ($$) {
700 return 1 if $origsubs{'isselflink'}->($page, $link);
701 if (istranslation($page)) {
702 return $origsubs{'isselflink'}->(masterpage($page), $link);
708 # | Blackboxes for private data
714 sub alreadyfiltered($$) {
718 return exists $filtered{$page}{$destpage}
719 && $filtered{$page}{$destpage} eq 1;
722 sub setalreadyfiltered($$) {
726 $filtered{$page}{$destpage}=1;
729 sub unsetalreadyfiltered($$) {
733 if (exists $filtered{$page}{$destpage}) {
734 delete $filtered{$page}{$destpage};
738 sub resetalreadyfiltered() {
747 sub maybe_add_leading_slash ($;$) {
750 $add=1 unless defined $add;
751 return '/' . $str if $add;
755 sub istranslatablefile ($) {
758 return 0 unless defined $file;
759 my $type=pagetype($file);
760 return 0 if ! defined $type || $type eq 'po';
761 return 0 if $file =~ /\.pot$/;
762 return 0 if ! defined $config{po_translatable_pages};
763 return 1 if pagespec_match(pagename($file), $config{po_translatable_pages});
767 sub istranslatable ($) {
771 return 1 if istranslatablefile($pagesources{$page});
775 sub _istranslation ($) {
778 $page='' unless defined $page && length $page;
779 my $hasleadingslash = ($page=~s#^/##);
780 my $file=$pagesources{$page};
781 return 0 unless defined $file
782 && defined pagetype($file)
783 && pagetype($file) eq 'po';
784 return 0 if $file =~ /\.pot$/;
786 my ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
787 return 0 unless defined $masterpage && defined $lang
788 && length $masterpage && length $lang
789 && defined $pagesources{$masterpage}
790 && defined $config{po_slave_languages}{$lang};
792 return (maybe_add_leading_slash($masterpage, $hasleadingslash), $lang)
793 if istranslatable($masterpage);
796 sub istranslation ($) {
799 if (1 < (my ($masterpage, $lang) = _istranslation($page))) {
800 my $hasleadingslash = ($masterpage=~s#^/##);
801 $translations{$masterpage}{$lang}=$page unless exists $translations{$masterpage}{$lang};
802 return (maybe_add_leading_slash($masterpage, $hasleadingslash), $lang);
810 if ( 1 < (my ($masterpage, $lang) = _istranslation($page))) {
819 if (1 < (my ($masterpage, $lang) = _istranslation($page))) {
822 return $config{po_master_language}{code};
825 sub islanguagecode ($) {
828 return $code =~ /^[a-z]{2}$/;
831 sub otherlanguage_page ($$) {
835 return masterpage($page) if $code eq $config{po_master_language}{code};
836 return masterpage($page) . '.' . $code;
839 # Returns the list of other languages codes: the master language comes first,
840 # then the codes are ordered the same way as in po_slave_languages, if it is
841 # an array, or in the language name lexical order, if it is a hash.
842 sub otherlanguages_codes ($) {
846 return \@ret unless istranslation($page) || istranslatable($page);
847 my $curlang=lang($page);
849 ($config{po_master_language}{code}, @slavelanguages) {
850 next if $lang eq $curlang;
856 sub otherlanguages_pages ($) {
861 $ret{$_} = otherlanguage_page($page, $_)
862 } @{otherlanguages_codes($page)};
868 my $masterfile=shift;
870 (my $name, my $dir, my $suffix) = fileparse($masterfile, qr/\.[^.]*/);
871 $dir='' if $dir eq './';
872 return File::Spec->catpath('', $dir, $name . ".pot");
876 my $masterfile=shift;
879 (my $name, my $dir, my $suffix) = fileparse($masterfile, qr/\.[^.]*/);
880 $dir='' if $dir eq './';
881 return File::Spec->catpath('', $dir, $name . "." . $lang . ".po");
885 my $masterfile=shift;
887 return map pofile($masterfile, $_), (keys %{$config{po_slave_languages}});
891 my $masterfile=shift;
893 my $potfile=potfile($masterfile);
894 my $doc=Locale::Po4a::Chooser::new(po4a_type($masterfile),
895 po4a_options($masterfile));
896 $doc->{TT}{utf_mode} = 1;
897 $doc->{TT}{file_in_charset} = 'UTF-8';
898 $doc->{TT}{file_out_charset} = 'UTF-8';
899 $doc->read($masterfile);
900 # let's cheat a bit to force porefs option to be passed to
901 # Locale::Po4a::Po; this is undocument use of internal
902 # Locale::Po4a::TransTractor's data, compulsory since this module
903 # prevents us from using the porefs option.
904 $doc->{TT}{po_out}=Locale::Po4a::Po->new({ 'porefs' => 'none' });
905 $doc->{TT}{po_out}->set_charset('UTF-8');
908 IkiWiki::prep_writefile(basename($potfile),dirname($potfile));
909 $doc->writepo($potfile);
912 sub refreshpofiles ($@) {
913 my $masterfile=shift;
916 my $potfile=potfile($masterfile);
918 error("po(refreshpofiles) ".sprintf(gettext("POT file (%s) does not exist"), $potfile));
921 foreach my $pofile (@pofiles) {
922 IkiWiki::prep_writefile(basename($pofile),dirname($pofile));
925 # If the po file exists in an underlay, copy it
927 my ($pobase)=$pofile=~/^\Q$config{srcdir}\E\/?(.*)$/;
928 foreach my $dir (@{$config{underlaydirs}}) {
929 if (-e "$dir/$pobase") {
930 File::Copy::syscopy("$dir/$pobase",$pofile)
931 or error("po(refreshpofiles) ".
932 sprintf(gettext("failed to copy underlay PO file to %s"),
939 system("msgmerge", "--previous", "-q", "-U", "--backup=none", $pofile, $potfile) == 0
940 or error("po(refreshpofiles) ".
941 sprintf(gettext("failed to update %s"),
945 File::Copy::syscopy($potfile,$pofile)
946 or error("po(refreshpofiles) ".
947 sprintf(gettext("failed to copy the POT file to %s"),
953 sub buildtranslationscache() {
954 # use istranslation's side-effect
955 map istranslation($_), (keys %pagesources);
958 sub resettranslationscache() {
962 sub flushmemoizecache() {
963 Memoize::flush_cache("istranslatable");
964 Memoize::flush_cache("_istranslation");
965 Memoize::flush_cache("percenttranslated");
968 sub urlto_with_orig_beautiful_urlpath($$) {
972 inject(name => "IkiWiki::beautify_urlpath", call => $origsubs{'beautify_urlpath'});
973 my $res=urlto($to, $from);
974 inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath);
979 sub percenttranslated ($) {
983 return gettext("N/A") unless istranslation($page);
984 my $file=srcfile($pagesources{$page});
985 my $masterfile = srcfile($pagesources{masterpage($page)});
986 my $doc=Locale::Po4a::Chooser::new(po4a_type($masterfile),
987 po4a_options($masterfile));
989 'po_in_name' => [ $file ],
990 'file_in_name' => [ $masterfile ],
991 'file_in_charset' => 'UTF-8',
992 'file_out_charset' => 'UTF-8',
993 ) or error("po(percenttranslated) ".
994 sprintf(gettext("failed to translate %s"), $page));
995 my ($percent,$hit,$queries) = $doc->stats();
996 $percent =~ s/\.[0-9]+$//;
1000 sub languagename ($) {
1003 return $config{po_master_language}{name}
1004 if $code eq $config{po_master_language}{code};
1005 return $config{po_slave_languages}{$code}
1006 if defined $config{po_slave_languages}{$code};
1010 sub otherlanguagesloop ($) {
1014 if (istranslation($page)) {
1016 url => urlto_with_orig_beautiful_urlpath(masterpage($page), $page),
1017 code => $config{po_master_language}{code},
1018 language => $config{po_master_language}{name},
1022 foreach my $lang (@{otherlanguages_codes($page)}) {
1023 next if $lang eq $config{po_master_language}{code};
1024 my $otherpage = otherlanguage_page($page, $lang);
1026 url => urlto_with_orig_beautiful_urlpath($otherpage, $page),
1028 language => languagename($lang),
1029 percent => percenttranslated($otherpage),
1035 sub homepageurl (;$) {
1038 return urlto('', $page);
1041 sub ishomepage ($) {
1044 return 1 if $page eq 'index';
1045 map { return 1 if $page eq 'index.'.$_ } keys %{$config{po_slave_languages}};
1049 sub deletetranslations ($) {
1050 my $deletedmasterfile=shift;
1052 my $deletedmasterpage=pagename($deletedmasterfile);
1055 my $file = newpagefile($deletedmasterpage.'.'.$_, 'po');
1056 my $absfile = "$config{srcdir}/$file";
1057 if (-e $absfile && ! -l $absfile && ! -d $absfile) {
1058 push @todelete, $file;
1060 } keys %{$config{po_slave_languages}};
1064 IkiWiki::rcs_remove($_);
1067 IkiWiki::prune("$config{srcdir}/$_");
1073 gettext("removed obsolete PO files"));
1077 sub commit_and_refresh ($) {
1081 IkiWiki::disable_commit_hook();
1082 IkiWiki::rcs_commit_staged(
1085 IkiWiki::enable_commit_hook();
1086 IkiWiki::rcs_update();
1088 # Reinitialize module's private variables.
1089 resetalreadyfiltered();
1090 resettranslationscache();
1091 flushmemoizecache();
1092 # Trigger a wiki refresh.
1093 require IkiWiki::Render;
1094 # without preliminary saveindex/loadindex, refresh()
1095 # complains about a lot of uninitialized variables
1096 IkiWiki::saveindex();
1097 IkiWiki::loadindex();
1099 IkiWiki::saveindex();
1102 sub po_to_markup ($$) {
1103 my ($page, $content) = (shift, shift);
1105 $content = '' unless defined $content;
1106 $content = decode_utf8(encode_utf8($content));
1107 # CRLF line terminators make poor Locale::Po4a feel bad
1108 $content=~s/\r\n/\n/g;
1110 # There are incompatibilities between some File::Temp versions
1111 # (including 0.18, bundled with Lenny's perl-modules package)
1112 # and others (e.g. 0.20, previously present in the archive as
1113 # a standalone package): under certain circumstances, some
1114 # return a relative filename, whereas others return an absolute one;
1115 # we here use this module in a way that is at least compatible
1116 # with 0.18 and 0.20. Beware, hit'n'run refactorers!
1117 my $infile = new File::Temp(TEMPLATE => "ikiwiki-po-filter-in.XXXXXXXXXX",
1118 DIR => File::Spec->tmpdir,
1119 UNLINK => 1)->filename;
1120 my $outfile = new File::Temp(TEMPLATE => "ikiwiki-po-filter-out.XXXXXXXXXX",
1121 DIR => File::Spec->tmpdir,
1122 UNLINK => 1)->filename;
1124 my $fail = sub ($) {
1125 my $msg = "po(po_to_markup) - $page : " . shift;
1126 error($msg, sub { unlink $infile, $outfile});
1129 writefile(basename($infile), File::Spec->tmpdir, $content)
1130 or return $fail->(sprintf(gettext("failed to write %s"), $infile));
1132 my $masterfile = srcfile($pagesources{masterpage($page)});
1133 my $doc=Locale::Po4a::Chooser::new(po4a_type($masterfile),
1134 po4a_options($masterfile));
1136 'po_in_name' => [ $infile ],
1137 'file_in_name' => [ $masterfile ],
1138 'file_in_charset' => 'UTF-8',
1139 'file_out_charset' => 'UTF-8',
1140 ) or return $fail->(gettext("failed to translate"));
1141 $doc->write($outfile)
1142 or return $fail->(sprintf(gettext("failed to write %s"), $outfile));
1144 $content = readfile($outfile);
1146 # Unlinking should happen automatically, thanks to File::Temp,
1147 # but it does not work here, probably because of the way writefile()
1148 # and Locale::Po4a::write() work.
1149 unlink $infile, $outfile;
1154 # returns a SuccessReason or FailReason object
1156 my $content = shift;
1158 # NB: we don't use po_to_markup here, since Po4a parser does
1159 # not mind invalid PO content
1160 $content = '' unless defined $content;
1161 $content = decode_utf8(encode_utf8($content));
1163 # There are incompatibilities between some File::Temp versions
1164 # (including 0.18, bundled with Lenny's perl-modules package)
1165 # and others (e.g. 0.20, previously present in the archive as
1166 # a standalone package): under certain circumstances, some
1167 # return a relative filename, whereas others return an absolute one;
1168 # we here use this module in a way that is at least compatible
1169 # with 0.18 and 0.20. Beware, hit'n'run refactorers!
1170 my $infile = new File::Temp(TEMPLATE => "ikiwiki-po-isvalidpo.XXXXXXXXXX",
1171 DIR => File::Spec->tmpdir,
1172 UNLINK => 1)->filename;
1174 my $fail = sub ($) {
1175 my $msg = '[po/isvalidpo] ' . shift;
1177 return IkiWiki::FailReason->new("$msg");
1180 writefile(basename($infile), File::Spec->tmpdir, $content)
1181 or return $fail->(sprintf(gettext("failed to write %s"), $infile));
1183 my $res = (system("msgfmt", "--check", $infile, "-o", "/dev/null") == 0);
1185 # Unlinking should happen automatically, thanks to File::Temp,
1186 # but it does not work here, probably because of the way writefile()
1187 # and Locale::Po4a::write() work.
1191 return IkiWiki::SuccessReason->new("valid gettext data");
1193 return IkiWiki::FailReason->new(gettext("invalid gettext data, go back ".
1194 "to previous page to continue edit"));
1200 my $pagetype = pagetype($file);
1201 if ($pagetype eq 'html') {
1207 sub po4a_options($) {
1211 my $pagetype = pagetype($file);
1213 if ($pagetype eq 'html') {
1214 # how to disable options is not consistent across po4a modules
1215 $options{includessi} = '';
1216 $options{includeexternal} = 0;
1218 elsif ($pagetype eq 'mdwn') {
1219 $options{markdown} = 1;
1222 $options{markdown} = 0;
1232 package IkiWiki::PageSpec;
1234 sub match_istranslation ($;@) {
1237 if (IkiWiki::Plugin::po::istranslation($page)) {
1238 return IkiWiki::SuccessReason->new("is a translation page");
1241 return IkiWiki::FailReason->new("is not a translation page");
1245 sub match_istranslatable ($;@) {
1248 if (IkiWiki::Plugin::po::istranslatable($page)) {
1249 return IkiWiki::SuccessReason->new("is set as translatable in po_translatable_pages");
1252 return IkiWiki::FailReason->new("is not set as translatable in po_translatable_pages");
1256 sub match_lang ($$;@) {
1260 my $regexp=IkiWiki::glob2re($wanted);
1261 my $lang=IkiWiki::Plugin::po::lang($page);
1262 if ($lang !~ /^$regexp$/i) {
1263 return IkiWiki::FailReason->new("file language is $lang, not $wanted");
1266 return IkiWiki::SuccessReason->new("file language is $wanted");
1270 sub match_currentlang ($$;@) {
1275 return IkiWiki::FailReason->new("no location provided") unless exists $params{location};
1277 my $currentlang=IkiWiki::Plugin::po::lang($params{location});
1278 my $lang=IkiWiki::Plugin::po::lang($page);
1280 if ($lang eq $currentlang) {
1281 return IkiWiki::SuccessReason->new("file language is the same as current one, i.e. $currentlang");
1284 return IkiWiki::FailReason->new("file language is $lang, whereas current language is $currentlang");
1288 sub match_needstranslation ($$;@) {
1291 my $percenttranslated=IkiWiki::Plugin::po::percenttranslated($page);
1292 if ($percenttranslated eq 'N/A') {
1293 return IkiWiki::FailReason->new("file is not a translatable page");
1295 elsif ($percenttranslated < 100) {
1296 return IkiWiki::SuccessReason->new("file has $percenttranslated translated");
1299 return IkiWiki::FailReason->new("file is fully translated");