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 if (@{$config{po_slave_languages}} % 2 != 0) {
145 error(sprintf(gettext("The %s field is invalid."), 'po_slave_languages'));
147 for (my $i=0; $i<@{$config{po_slave_languages}}; $i = $i + 2) {
148 $slaves{$config{po_slave_languages}->[$i]} = $config{po_slave_languages}->[$i + 1];
149 push @slavelanguages, $config{po_slave_languages}->[$i];
151 $config{po_slave_languages} = \%slaves;
153 elsif (ref $config{po_slave_languages} eq 'HASH') {
154 @slavelanguages = sort {
155 $config{po_slave_languages}->{$a} cmp $config{po_slave_languages}->{$b};
156 } keys %{$config{po_slave_languages}};
159 delete $config{po_slave_languages}{$config{po_master_language}{code}};;
163 or error(sprintf(gettext("%s is not a valid language code"), $_));
164 } ($config{po_master_language}{code}, keys %{$config{po_slave_languages}});
166 if (! exists $config{po_translatable_pages} ||
167 ! defined $config{po_translatable_pages}) {
168 $config{po_translatable_pages}="";
170 if (! exists $config{po_link_to} ||
171 ! defined $config{po_link_to}) {
172 $config{po_link_to}='default';
174 elsif ($config{po_link_to} !~ /^(default|current|negotiated)$/) {
175 warn(sprintf(gettext('%s is not a valid value for po_link_to, falling back to po_link_to=default'),
176 $config{po_link_to}));
177 $config{po_link_to}='default';
179 elsif ($config{po_link_to} eq "negotiated" && ! $config{usedirs}) {
180 warn(gettext('po_link_to=negotiated requires usedirs to be enabled, falling back to po_link_to=default'));
181 $config{po_link_to}='default';
184 push @{$config{wiki_file_prune_regexps}}, qr/\.pot$/;
186 # Translated versions of the underlays are added if available.
187 foreach my $underlay ("basewiki",
188 map { m/^\Q$config{underlaydirbase}\E\/*(.*)/ }
189 reverse @{$config{underlaydirs}}) {
190 next if $underlay=~/^locale\//;
192 # Underlays containing the po files for slave languages.
193 foreach my $ll (keys %{$config{po_slave_languages}}) {
194 add_underlay("po/$ll/$underlay")
195 if -d "$config{underlaydirbase}/po/$ll/$underlay";
198 if ($config{po_master_language}{code} ne 'en') {
199 # Add underlay containing translated source files
200 # for the master language.
201 add_underlay("locale/$config{po_master_language}{code}/$underlay")
202 if -d "$config{underlaydirbase}/locale/$config{po_master_language}{code}/$underlay";
208 my $needsbuild=shift;
210 # backup @needsbuild content so that change() can know whether
211 # a given master page was rendered because its source file was changed
212 @origneedsbuild=(@$needsbuild);
215 buildtranslationscache();
217 # make existing translations depend on the corresponding master page
218 foreach my $master (keys %translations) {
219 map add_depends($_, $master), values %{otherlanguages_pages($master)};
223 # Massage the recorded state of internal links so that:
224 # - it matches the actually generated links, rather than the links as written
225 # in the pages' source
226 # - backlinks are consistent in all cases
229 my $page=$params{page};
230 my $content=$params{content};
232 if (istranslation($page)) {
233 foreach my $destpage (@{$links{$page}}) {
234 if (istranslatable($destpage)) {
235 # replace the occurence of $destpage in $links{$page}
236 for (my $i=0; $i<@{$links{$page}}; $i++) {
237 if (@{$links{$page}}[$i] eq $destpage) {
238 @{$links{$page}}[$i] = $destpage . '.' . lang($page);
245 elsif (! istranslatable($page) && ! istranslation($page)) {
246 foreach my $destpage (@{$links{$page}}) {
247 if (istranslatable($destpage)) {
248 # make sure any destpage's translations has
249 # $page in its backlinks
250 push @{$links{$page}},
251 values %{otherlanguages_pages($destpage)};
257 # We use filter to convert PO to the master page's format,
258 # since the rest of ikiwiki should not work on PO files.
262 my $page = $params{page};
263 my $destpage = $params{destpage};
264 my $content = $params{content};
265 if (istranslation($page) && ! alreadyfiltered($page, $destpage)) {
266 $content = po_to_markup($page, $content);
267 setalreadyfiltered($page, $destpage);
275 my $page = $params{page};
276 my $content = $params{content};
278 # ignore PO files this plugin did not create
279 return $content unless istranslation($page);
281 # force content to be htmlize'd as if it was the same type as the master page
282 return IkiWiki::htmlize($page, $page,
283 pagetype(srcfile($pagesources{masterpage($page)})),
287 sub pagetemplate (@) {
289 my $page=$params{page};
290 my $destpage=$params{destpage};
291 my $template=$params{template};
293 my ($masterpage, $lang) = istranslation($page);
295 if (istranslation($page) && $template->query(name => "percenttranslated")) {
296 $template->param(percenttranslated => percenttranslated($page));
298 if ($template->query(name => "istranslation")) {
299 $template->param(istranslation => scalar istranslation($page));
301 if ($template->query(name => "istranslatable")) {
302 $template->param(istranslatable => istranslatable($page));
304 if ($template->query(name => "HOMEPAGEURL")) {
305 $template->param(homepageurl => homepageurl($page));
307 if ($template->query(name => "otherlanguages")) {
308 $template->param(otherlanguages => [otherlanguagesloop($page)]);
309 map add_depends($page, $_), (values %{otherlanguages_pages($page)});
311 if ($config{discussion} && istranslation($page)) {
312 if ($page !~ /.*\/\Q$config{discussionpage}\E$/i &&
313 (length $config{cgiurl} ||
314 exists $links{$masterpage."/".lc($config{discussionpage})})) {
315 $template->param('discussionlink' => htmllink(
318 $masterpage . '/' . $config{discussionpage},
321 linktext => $config{discussionpage},
325 # Remove broken parentlink to ./index.html on home page's translations.
326 # It works because this hook has the "last" parameter set, to ensure it
327 # runs after parentlinks' own pagetemplate hook.
328 if ($template->param('parentlinks')
329 && istranslation($page)
330 && $masterpage eq "index") {
331 $template->param('parentlinks' => []);
333 if (ishomepage($page) && $template->query(name => "title")) {
334 $template->param(title => $config{wikiname});
338 # Add the renamed page translations to the list of to-be-renamed pages.
339 sub renamepages (@) {
342 my %torename = %{$params{torename}};
343 my $session = $params{session};
345 # Save the page(s) the user asked to rename, so that our
346 # canrename hook can tell the difference between:
347 # - a translation being renamed as a consequence of its master page
349 # - a user trying to directly rename a translation
350 # This is why this hook has to be run first, before the list of pages
351 # to rename is modified by other plugins.
353 @orig_torename=@{$session->param("po_orig_torename")}
354 if defined $session->param("po_orig_torename");
355 push @orig_torename, $torename{src};
356 $session->param(po_orig_torename => \@orig_torename);
357 IkiWiki::cgi_savesession($session);
359 return () unless istranslatable($torename{src});
362 my %otherpages=%{otherlanguages_pages($torename{src})};
363 while (my ($lang, $otherpage) = each %otherpages) {
366 srcfile => $pagesources{$otherpage},
367 dest => otherlanguage_page($torename{dest}, $lang),
368 destfile => $torename{dest}.".".$lang.".po",
378 map { deletetranslations($_) } grep istranslatablefile($_), @deleted;
384 # All meta titles are first extracted at scan time, i.e. before we turn
385 # PO files back into translated markdown; escaping of double-quotes in
386 # PO files breaks the meta plugin's parsing enough to save ugly titles
387 # to %pagestate at this time.
389 # Then, at render time, every page passes in turn through the Great
390 # Rendering Chain (filter->preprocess->linkify->htmlize), and the meta
391 # plugin's preprocess hook is this time in a position to correctly
392 # extract the titles from slave pages.
394 # This is, unfortunately, too late: if the page A, linking to the page
395 # B, is rendered before B, it will display the wrongly-extracted meta
396 # title as the link text to B.
398 # On the one hand, such a corner case only happens on rebuild: on
399 # refresh, every rendered page is fixed to contain correct meta titles.
400 # On the other hand, it can take some time to get every page fixed.
401 # We therefore re-render every rendered page after a rebuild to fix them
402 # at once. As this more or less doubles the time needed to rebuild the
403 # wiki, we do so only when really needed.
406 && exists $config{rebuild} && defined $config{rebuild} && $config{rebuild}
407 && UNIVERSAL::can("IkiWiki::Plugin::meta", "getsetup")
408 && exists $config{meta_overrides_page_title}
409 && defined $config{meta_overrides_page_title}
410 && $config{meta_overrides_page_title}) {
411 debug(sprintf(gettext("rebuilding all pages to fix meta titles")));
412 resetalreadyfiltered();
413 require IkiWiki::Render;
414 foreach my $file (@rendered) {
415 IkiWiki::render($file, sprintf(gettext("building %s"), $file));
419 my $updated_po_files=0;
421 # Refresh/create POT and PO files as needed.
422 foreach my $file (grep {istranslatablefile($_)} @rendered) {
423 my $masterfile=srcfile($file);
424 my $page=pagename($file);
425 my $updated_pot_file=0;
427 # Avoid touching underlay files.
428 next if $masterfile ne "$config{srcdir}/$file";
430 # Only refresh POT file if it does not exist, or if
431 # the source was changed: don't if only the HTML was
432 # refreshed, e.g. because of a dependency.
433 if ((grep { $_ eq $pagesources{$page} } @origneedsbuild) ||
434 ! -e potfile($masterfile)) {
435 refreshpot($masterfile);
439 foreach my $po (pofiles($masterfile)) {
440 next if ! $updated_pot_file && -e $po;
441 next if grep { $po=~/\Q$_\E/ } @{$config{underlaydirs}};
445 refreshpofiles($masterfile, @pofiles);
446 map { s/^\Q$config{srcdir}\E\/*//; IkiWiki::rcs_add($_) } @pofiles if $config{rcs};
451 if ($updated_po_files) {
453 gettext("updated PO files"));
457 sub checkcontent (@) {
460 if (istranslation($params{page})) {
461 my $res = isvalidpo($params{content});
475 if (istranslation($params{page})) {
476 return gettext("Can not remove a translation. If the master page is removed, ".
477 "however, its translations will be removed as well.");
484 my $session = $params{session};
486 if (istranslation($params{src})) {
487 my $masterpage = masterpage($params{src});
488 # Tell the difference between:
489 # - a translation being renamed as a consequence of its master page
490 # being renamed, which is allowed
491 # - a user trying to directly rename a translation, which is forbidden
492 # by looking for the master page in the list of to-be-renamed pages we
493 # saved early in the renaming process.
494 my $orig_torename = $session->param("po_orig_torename");
495 unless (grep { $_ eq $masterpage } @{$orig_torename}) {
496 return gettext("Can not rename a translation. If the master page is renamed, ".
497 "however, its translations will be renamed as well.");
503 # As we're previewing or saving a page, the content may have
504 # changed, so tell the next filter() invocation it must not be lazy.
508 unsetalreadyfiltered($params{page}, $params{page});
509 return $params{content};
512 sub formbuilder_setup (@) {
514 my $form=$params{form};
517 return unless defined $form->field("do");
519 if ($form->field("do") eq "create") {
520 # Warn the user: new pages must be written in master language.
521 my $template=template("pocreatepage.tmpl");
522 $template->param(LANG => $config{po_master_language}{name});
523 $form->tmpl_param(message => $template->output);
525 elsif ($form->field("do") eq "edit") {
526 # Remove the rename/remove buttons on slave pages.
527 # This has to be done after the rename/remove plugins have added
528 # their buttons, which is why this hook must be run last.
529 # The canrename/canremove hooks already ensure this is forbidden
530 # at the backend level, so this is only UI sugar.
531 if (istranslation($form->field("page"))) {
533 for (my $i = 0; $i < @{$params{buttons}}; $i++) {
534 if (@{$params{buttons}}[$i] eq $_) {
535 delete @{$params{buttons}}[$i];
544 sub formbuilder (@) {
546 my $form=$params{form};
549 return unless defined $form->field("do");
551 # Do not allow to create pages of type po: they are automatically created.
552 # The main reason to do so is to bypass the "favor the type of linking page
553 # on page creation" logic, which is unsuitable when a broken link is clicked
554 # on a slave (PO) page.
555 # This cannot be done in the formbuilder_setup hook as the list of types is
557 if ($form->field("do") eq "create") {
558 foreach my $field ($form->field) {
559 next unless "$field" eq "type";
560 next unless $field->type eq 'select';
561 my $orig_value = $field->value;
562 # remove po from the list of types
563 my @types = grep { $_->[0] ne 'po' } $field->options;
564 $field->options(\@types) if @types;
565 # favor the type of linking page's masterpage
566 if ($orig_value eq 'po') {
568 if (defined $form->field('from')) {
569 ($from)=$form->field('from')=~/$config{wiki_file_regexp}/;
570 $from = masterpage($from);
572 if (defined $from && exists $pagesources{$from}) {
573 $type=pagetype($pagesources{$from});
575 $type=$config{default_pageext} unless defined $type;
576 $field->value($type) ;
583 # | Injected functions
586 # Implement po_link_to 'current' and 'negotiated' settings.
587 sub mybestlink ($$) {
591 return $origsubs{'bestlink'}->($page, $link)
592 if defined $config{po_link_to} && $config{po_link_to} eq "default";
594 my $res=$origsubs{'bestlink'}->(masterpage($page), $link);
595 my @caller = caller(1);
597 && istranslatable($res)
598 && istranslation($page)
599 && !(exists $caller[3] && defined $caller[3]
600 && ($caller[3] eq "IkiWiki::PageSpec::match_link"))) {
601 return $res . "." . lang($page);
606 sub mybeautify_urlpath ($) {
609 my $res=$origsubs{'beautify_urlpath'}->($url);
610 if (defined $config{po_link_to} && $config{po_link_to} eq "negotiated") {
611 $res =~ s!/\Qindex.$config{po_master_language}{code}.$config{htmlext}\E$!/!;
612 $res =~ s!/\Qindex.$config{htmlext}\E$!/!;
614 $res =~ s!/\Qindex.$_.$config{htmlext}\E$!/!;
615 } (keys %{$config{po_slave_languages}});
620 sub mytargetpage ($$) {
624 if (istranslation($page) || istranslatable($page)) {
625 my ($masterpage, $lang) = (masterpage($page), lang($page));
626 if (! $config{usedirs} || $masterpage eq 'index') {
627 return $masterpage . "." . $lang . "." . $ext;
630 return $masterpage . "/index." . $lang . "." . $ext;
633 return $origsubs{'targetpage'}->($page, $ext);
641 # workaround hard-coded /index.$config{htmlext} in IkiWiki::urlto()
643 && $config{po_link_to} eq "current"
644 && istranslatable('index')) {
645 return IkiWiki::beautify_urlpath(IkiWiki::baseurl($from) . "index." . lang($from) . ".$config{htmlext}");
647 # avoid using our injected beautify_urlpath if run by cgi_editpage,
648 # so that one is redirected to the just-edited page rather than to the
649 # negociated translation; to prevent unnecessary fiddling with caller/inject,
650 # we only do so when our beautify_urlpath would actually do what we want to
651 # avoid, i.e. when po_link_to = negotiated.
652 # also avoid doing so when run by cgi_goto, so that the links on recentchanges
653 # page actually lead to the exact page they pretend to.
654 if ($config{po_link_to} eq "negotiated") {
655 my @caller = caller(1);
657 $use_orig = 1 if (exists $caller[3] && defined $caller[3]
658 && ($caller[3] eq "IkiWiki::cgi_editpage" ||
659 $caller[3] eq "IkiWiki::Plugin::goto::cgi_goto")
661 inject(name => "IkiWiki::beautify_urlpath", call => $origsubs{'beautify_urlpath'})
663 my $res = $origsubs{'urlto'}->($to,$from,$absolute);
664 inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath)
669 return $origsubs{'urlto'}->($to,$from,$absolute)
676 # slave pages have no subpages
677 if (istranslation($params{'from'})) {
678 $params{'from'} = masterpage($params{'from'});
680 return $origsubs{'cgiurl'}->(%params);
687 if (exists $params{rootpage}) {
688 $rootpage=$origsubs{'bestlink'}->($params{page}, $params{rootpage});
689 if (!length $rootpage) {
690 $rootpage=$params{rootpage};
694 $rootpage=masterpage($params{page});
699 sub myisselflink ($$) {
703 return 1 if $origsubs{'isselflink'}->($page, $link);
704 if (istranslation($page)) {
705 return $origsubs{'isselflink'}->(masterpage($page), $link);
711 # | Blackboxes for private data
717 sub alreadyfiltered($$) {
721 return exists $filtered{$page}{$destpage}
722 && $filtered{$page}{$destpage} eq 1;
725 sub setalreadyfiltered($$) {
729 $filtered{$page}{$destpage}=1;
732 sub unsetalreadyfiltered($$) {
736 if (exists $filtered{$page}{$destpage}) {
737 delete $filtered{$page}{$destpage};
741 sub resetalreadyfiltered() {
750 sub maybe_add_leading_slash ($;$) {
753 $add=1 unless defined $add;
754 return '/' . $str if $add;
758 sub istranslatablefile ($) {
761 return 0 unless defined $file;
762 my $type=pagetype($file);
763 return 0 if ! defined $type || $type eq 'po';
764 return 0 if $file =~ /\.pot$/;
765 return 0 if ! defined $config{po_translatable_pages};
766 return 1 if pagespec_match(pagename($file), $config{po_translatable_pages});
770 sub istranslatable ($) {
774 return 1 if istranslatablefile($pagesources{$page});
778 sub _istranslation ($) {
781 $page='' unless defined $page && length $page;
782 my $hasleadingslash = ($page=~s#^/##);
783 my $file=$pagesources{$page};
784 return 0 unless defined $file
785 && defined pagetype($file)
786 && pagetype($file) eq 'po';
787 return 0 if $file =~ /\.pot$/;
789 my ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
790 return 0 unless defined $masterpage && defined $lang
791 && length $masterpage && length $lang
792 && defined $pagesources{$masterpage}
793 && defined $config{po_slave_languages}{$lang};
795 return (maybe_add_leading_slash($masterpage, $hasleadingslash), $lang)
796 if istranslatable($masterpage);
799 sub istranslation ($) {
802 if (1 < (my ($masterpage, $lang) = _istranslation($page))) {
803 my $hasleadingslash = ($masterpage=~s#^/##);
804 $translations{$masterpage}{$lang}=$page unless exists $translations{$masterpage}{$lang};
805 return (maybe_add_leading_slash($masterpage, $hasleadingslash), $lang);
813 if ( 1 < (my ($masterpage, $lang) = _istranslation($page))) {
822 if (1 < (my ($masterpage, $lang) = _istranslation($page))) {
825 return $config{po_master_language}{code};
828 sub islanguagecode ($) {
831 return $code =~ /^[a-z]{2}$/;
834 sub otherlanguage_page ($$) {
838 return masterpage($page) if $code eq $config{po_master_language}{code};
839 return masterpage($page) . '.' . $code;
842 # Returns the list of other languages codes: the master language comes first,
843 # then the codes are ordered the same way as in po_slave_languages, if it is
844 # an array, or in the language name lexical order, if it is a hash.
845 sub otherlanguages_codes ($) {
849 return \@ret unless istranslation($page) || istranslatable($page);
850 my $curlang=lang($page);
852 ($config{po_master_language}{code}, @slavelanguages) {
853 next if $lang eq $curlang;
859 sub otherlanguages_pages ($) {
864 $ret{$_} = otherlanguage_page($page, $_)
865 } @{otherlanguages_codes($page)};
871 my $masterfile=shift;
873 (my $name, my $dir, my $suffix) = fileparse($masterfile, qr/\.[^.]*/);
874 $dir='' if $dir eq './';
875 return File::Spec->catpath('', $dir, $name . ".pot");
879 my $masterfile=shift;
882 (my $name, my $dir, my $suffix) = fileparse($masterfile, qr/\.[^.]*/);
883 $dir='' if $dir eq './';
884 return File::Spec->catpath('', $dir, $name . "." . $lang . ".po");
888 my $masterfile=shift;
890 return map pofile($masterfile, $_), (keys %{$config{po_slave_languages}});
894 my $masterfile=shift;
896 my $potfile=potfile($masterfile);
897 my $doc=Locale::Po4a::Chooser::new(po4a_type($masterfile),
898 po4a_options($masterfile));
899 $doc->{TT}{utf_mode} = 1;
900 $doc->{TT}{file_in_charset} = 'UTF-8';
901 $doc->{TT}{file_out_charset} = 'UTF-8';
902 $doc->read($masterfile);
903 # let's cheat a bit to force porefs option to be passed to
904 # Locale::Po4a::Po; this is undocument use of internal
905 # Locale::Po4a::TransTractor's data, compulsory since this module
906 # prevents us from using the porefs option.
907 $doc->{TT}{po_out}=Locale::Po4a::Po->new({ 'porefs' => 'none' });
908 $doc->{TT}{po_out}->set_charset('UTF-8');
911 IkiWiki::prep_writefile(basename($potfile),dirname($potfile));
912 $doc->writepo($potfile);
915 sub refreshpofiles ($@) {
916 my $masterfile=shift;
919 my $potfile=potfile($masterfile);
921 error("po(refreshpofiles) ".sprintf(gettext("POT file (%s) does not exist"), $potfile));
924 foreach my $pofile (@pofiles) {
925 IkiWiki::prep_writefile(basename($pofile),dirname($pofile));
928 # If the po file exists in an underlay, copy it
930 my ($pobase)=$pofile=~/^\Q$config{srcdir}\E\/?(.*)$/;
931 foreach my $dir (@{$config{underlaydirs}}) {
932 if (-e "$dir/$pobase") {
933 File::Copy::syscopy("$dir/$pobase",$pofile)
934 or error("po(refreshpofiles) ".
935 sprintf(gettext("failed to copy underlay PO file to %s"),
942 system("msgmerge", "--previous", "-q", "-U", "--backup=none", $pofile, $potfile) == 0
943 or error("po(refreshpofiles) ".
944 sprintf(gettext("failed to update %s"),
948 File::Copy::syscopy($potfile,$pofile)
949 or error("po(refreshpofiles) ".
950 sprintf(gettext("failed to copy the POT file to %s"),
956 sub buildtranslationscache() {
957 # use istranslation's side-effect
958 map istranslation($_), (keys %pagesources);
961 sub resettranslationscache() {
965 sub flushmemoizecache() {
966 Memoize::flush_cache("istranslatable");
967 Memoize::flush_cache("_istranslation");
968 Memoize::flush_cache("percenttranslated");
971 sub urlto_with_orig_beautiful_urlpath($$) {
975 inject(name => "IkiWiki::beautify_urlpath", call => $origsubs{'beautify_urlpath'});
976 my $res=urlto($to, $from);
977 inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath);
982 sub percenttranslated ($) {
986 return gettext("N/A") unless istranslation($page);
987 my $file=srcfile($pagesources{$page});
988 my $masterfile = srcfile($pagesources{masterpage($page)});
989 my $doc=Locale::Po4a::Chooser::new(po4a_type($masterfile),
990 po4a_options($masterfile));
992 'po_in_name' => [ $file ],
993 'file_in_name' => [ $masterfile ],
994 'file_in_charset' => 'UTF-8',
995 'file_out_charset' => 'UTF-8',
996 ) or error("po(percenttranslated) ".
997 sprintf(gettext("failed to translate %s"), $page));
998 my ($percent,$hit,$queries) = $doc->stats();
999 $percent =~ s/\.[0-9]+$//;
1003 sub languagename ($) {
1006 return $config{po_master_language}{name}
1007 if $code eq $config{po_master_language}{code};
1008 return $config{po_slave_languages}{$code}
1009 if defined $config{po_slave_languages}{$code};
1013 sub otherlanguagesloop ($) {
1017 if (istranslation($page)) {
1019 url => urlto_with_orig_beautiful_urlpath(masterpage($page), $page),
1020 code => $config{po_master_language}{code},
1021 language => $config{po_master_language}{name},
1025 foreach my $lang (@{otherlanguages_codes($page)}) {
1026 next if $lang eq $config{po_master_language}{code};
1027 my $otherpage = otherlanguage_page($page, $lang);
1029 url => urlto_with_orig_beautiful_urlpath($otherpage, $page),
1031 language => languagename($lang),
1032 percent => percenttranslated($otherpage),
1038 sub homepageurl (;$) {
1041 return urlto('', $page);
1044 sub ishomepage ($) {
1047 return 1 if $page eq 'index';
1048 map { return 1 if $page eq 'index.'.$_ } keys %{$config{po_slave_languages}};
1052 sub deletetranslations ($) {
1053 my $deletedmasterfile=shift;
1055 my $deletedmasterpage=pagename($deletedmasterfile);
1058 my $file = newpagefile($deletedmasterpage.'.'.$_, 'po');
1059 my $absfile = "$config{srcdir}/$file";
1060 if (-e $absfile && ! -l $absfile && ! -d $absfile) {
1061 push @todelete, $file;
1063 } keys %{$config{po_slave_languages}};
1067 IkiWiki::rcs_remove($_);
1070 IkiWiki::prune("$config{srcdir}/$_");
1076 gettext("removed obsolete PO files"));
1080 sub commit_and_refresh ($) {
1084 IkiWiki::disable_commit_hook();
1085 IkiWiki::rcs_commit_staged(
1088 IkiWiki::enable_commit_hook();
1089 IkiWiki::rcs_update();
1091 # Reinitialize module's private variables.
1092 resetalreadyfiltered();
1093 resettranslationscache();
1094 flushmemoizecache();
1095 # Trigger a wiki refresh.
1096 require IkiWiki::Render;
1097 # without preliminary saveindex/loadindex, refresh()
1098 # complains about a lot of uninitialized variables
1099 IkiWiki::saveindex();
1100 IkiWiki::loadindex();
1102 IkiWiki::saveindex();
1105 sub po_to_markup ($$) {
1106 my ($page, $content) = (shift, shift);
1108 $content = '' unless defined $content;
1109 $content = decode_utf8(encode_utf8($content));
1110 # CRLF line terminators make poor Locale::Po4a feel bad
1111 $content=~s/\r\n/\n/g;
1113 # There are incompatibilities between some File::Temp versions
1114 # (including 0.18, bundled with Lenny's perl-modules package)
1115 # and others (e.g. 0.20, previously present in the archive as
1116 # a standalone package): under certain circumstances, some
1117 # return a relative filename, whereas others return an absolute one;
1118 # we here use this module in a way that is at least compatible
1119 # with 0.18 and 0.20. Beware, hit'n'run refactorers!
1120 my $infile = new File::Temp(TEMPLATE => "ikiwiki-po-filter-in.XXXXXXXXXX",
1121 DIR => File::Spec->tmpdir,
1122 UNLINK => 1)->filename;
1123 my $outfile = new File::Temp(TEMPLATE => "ikiwiki-po-filter-out.XXXXXXXXXX",
1124 DIR => File::Spec->tmpdir,
1125 UNLINK => 1)->filename;
1127 my $fail = sub ($) {
1128 my $msg = "po(po_to_markup) - $page : " . shift;
1129 error($msg, sub { unlink $infile, $outfile});
1132 writefile(basename($infile), File::Spec->tmpdir, $content)
1133 or return $fail->(sprintf(gettext("failed to write %s"), $infile));
1135 my $masterfile = srcfile($pagesources{masterpage($page)});
1136 my $doc=Locale::Po4a::Chooser::new(po4a_type($masterfile),
1137 po4a_options($masterfile));
1139 'po_in_name' => [ $infile ],
1140 'file_in_name' => [ $masterfile ],
1141 'file_in_charset' => 'UTF-8',
1142 'file_out_charset' => 'UTF-8',
1143 ) or return $fail->(gettext("failed to translate"));
1144 $doc->write($outfile)
1145 or return $fail->(sprintf(gettext("failed to write %s"), $outfile));
1147 $content = readfile($outfile);
1149 # Unlinking should happen automatically, thanks to File::Temp,
1150 # but it does not work here, probably because of the way writefile()
1151 # and Locale::Po4a::write() work.
1152 unlink $infile, $outfile;
1157 # returns a SuccessReason or FailReason object
1159 my $content = shift;
1161 # NB: we don't use po_to_markup here, since Po4a parser does
1162 # not mind invalid PO content
1163 $content = '' unless defined $content;
1164 $content = decode_utf8(encode_utf8($content));
1166 # There are incompatibilities between some File::Temp versions
1167 # (including 0.18, bundled with Lenny's perl-modules package)
1168 # and others (e.g. 0.20, previously present in the archive as
1169 # a standalone package): under certain circumstances, some
1170 # return a relative filename, whereas others return an absolute one;
1171 # we here use this module in a way that is at least compatible
1172 # with 0.18 and 0.20. Beware, hit'n'run refactorers!
1173 my $infile = new File::Temp(TEMPLATE => "ikiwiki-po-isvalidpo.XXXXXXXXXX",
1174 DIR => File::Spec->tmpdir,
1175 UNLINK => 1)->filename;
1177 my $fail = sub ($) {
1178 my $msg = '[po/isvalidpo] ' . shift;
1180 return IkiWiki::FailReason->new("$msg");
1183 writefile(basename($infile), File::Spec->tmpdir, $content)
1184 or return $fail->(sprintf(gettext("failed to write %s"), $infile));
1186 my $res = (system("msgfmt", "--check", $infile, "-o", "/dev/null") == 0);
1188 # Unlinking should happen automatically, thanks to File::Temp,
1189 # but it does not work here, probably because of the way writefile()
1190 # and Locale::Po4a::write() work.
1194 return IkiWiki::SuccessReason->new("valid gettext data");
1196 return IkiWiki::FailReason->new(gettext("invalid gettext data, go back ".
1197 "to previous page to continue edit"));
1203 my $pagetype = pagetype($file);
1204 if ($pagetype eq 'html') {
1210 sub po4a_options($) {
1214 my $pagetype = pagetype($file);
1216 if ($pagetype eq 'html') {
1217 # how to disable options is not consistent across po4a modules
1218 $options{includessi} = '';
1219 $options{includeexternal} = 0;
1221 elsif ($pagetype eq 'mdwn') {
1222 $options{markdown} = 1;
1225 $options{markdown} = 0;
1235 package IkiWiki::PageSpec;
1237 sub match_istranslation ($;@) {
1240 if (IkiWiki::Plugin::po::istranslation($page)) {
1241 return IkiWiki::SuccessReason->new("is a translation page");
1244 return IkiWiki::FailReason->new("is not a translation page");
1248 sub match_istranslatable ($;@) {
1251 if (IkiWiki::Plugin::po::istranslatable($page)) {
1252 return IkiWiki::SuccessReason->new("is set as translatable in po_translatable_pages");
1255 return IkiWiki::FailReason->new("is not set as translatable in po_translatable_pages");
1259 sub match_lang ($$;@) {
1263 my $regexp=IkiWiki::glob2re($wanted);
1264 my $lang=IkiWiki::Plugin::po::lang($page);
1265 if ($lang !~ /^$regexp$/i) {
1266 return IkiWiki::FailReason->new("file language is $lang, not $wanted");
1269 return IkiWiki::SuccessReason->new("file language is $wanted");
1273 sub match_currentlang ($$;@) {
1278 return IkiWiki::FailReason->new("no location provided") unless exists $params{location};
1280 my $currentlang=IkiWiki::Plugin::po::lang($params{location});
1281 my $lang=IkiWiki::Plugin::po::lang($page);
1283 if ($lang eq $currentlang) {
1284 return IkiWiki::SuccessReason->new("file language is the same as current one, i.e. $currentlang");
1287 return IkiWiki::FailReason->new("file language is $lang, whereas current language is $currentlang");
1291 sub match_needstranslation ($$;@) {
1295 if (defined $wanted && $wanted ne "") {
1296 if ($wanted !~ /^\d+$/) {
1297 return IkiWiki::FailReason->new("parameter is not an integer");
1299 elsif ($wanted > 100) {
1300 return IkiWiki::FailReason->new("parameter is greater than 100");
1307 my $percenttranslated=IkiWiki::Plugin::po::percenttranslated($page);
1308 if ($percenttranslated eq 'N/A') {
1309 return IkiWiki::FailReason->new("file is not a translatable page");
1311 elsif ($percenttranslated < $wanted) {
1312 return IkiWiki::SuccessReason->new("file has $percenttranslated translated");
1315 return IkiWiki::FailReason->new("file is translated enough");