2 # .po as a wiki page type
3 # Licensed under GPL v2 or greater
4 # Copyright (C) 2008-2009 intrigeri <intrigeri@boum.org>
5 # inspired by the GPL'd po4a-translate,
6 # which is Copyright 2002, 2003, 2004 by Martin Quinson (mquinson#debian.org)
7 package IkiWiki::Plugin::po;
13 eval q{use Locale::Po4a::Common qw(nowrapi18n !/.*/)};
15 print STDERR gettext("warning: Old po4a detected! Recommend upgrade to 0.35.")."\n";
16 eval q{use Locale::Po4a::Common qw(!/.*/)};
19 use Locale::Po4a::Chooser;
31 my @slavelanguages; # language codes ordered as in config po_slave_languages
33 memoize("istranslatable");
34 memoize("_istranslation");
35 memoize("percenttranslated");
38 hook(type => "getsetup", id => "po", call => \&getsetup);
39 hook(type => "checkconfig", id => "po", call => \&checkconfig);
40 hook(type => "needsbuild", id => "po", call => \&needsbuild);
41 hook(type => "scan", id => "po", call => \&scan, last => 1);
42 hook(type => "filter", id => "po", call => \&filter);
43 hook(type => "htmlize", id => "po", call => \&htmlize);
44 hook(type => "pagetemplate", id => "po", call => \&pagetemplate, last => 1);
45 hook(type => "rename", id => "po", call => \&renamepages, first => 1);
46 hook(type => "delete", id => "po", call => \&mydelete);
47 hook(type => "change", id => "po", call => \&change);
48 hook(type => "checkcontent", id => "po", call => \&checkcontent);
49 hook(type => "canremove", id => "po", call => \&canremove);
50 hook(type => "canrename", id => "po", call => \&canrename);
51 hook(type => "editcontent", id => "po", call => \&editcontent);
52 hook(type => "formbuilder_setup", id => "po", call => \&formbuilder_setup, last => 1);
53 hook(type => "formbuilder", id => "po", call => \&formbuilder);
56 $origsubs{'bestlink'}=\&IkiWiki::bestlink;
57 inject(name => "IkiWiki::bestlink", call => \&mybestlink);
58 $origsubs{'beautify_urlpath'}=\&IkiWiki::beautify_urlpath;
59 inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath);
60 $origsubs{'targetpage'}=\&IkiWiki::targetpage;
61 inject(name => "IkiWiki::targetpage", call => \&mytargetpage);
62 $origsubs{'urlto'}=\&IkiWiki::urlto;
63 inject(name => "IkiWiki::urlto", call => \&myurlto);
64 $origsubs{'cgiurl'}=\&IkiWiki::cgiurl;
65 inject(name => "IkiWiki::cgiurl", call => \&mycgiurl);
66 $origsubs{'rootpage'}=\&IkiWiki::rootpage;
67 inject(name => "IkiWiki::rootpage", call => \&myrootpage);
68 $origsubs{'isselflink'}=\&IkiWiki::isselflink;
69 inject(name => "IkiWiki::isselflink", call => \&myisselflink);
79 # 2. Injected functions
80 # 3. Blackboxes for private data
93 rebuild => 1, # format plugin
96 po_master_language => {
102 description => "master language (non-PO files)",
106 po_slave_languages => {
113 description => "slave languages (PO files)",
117 po_translatable_pages => {
119 example => "* and !*/Discussion",
120 description => "PageSpec controlling which pages are translatable",
121 link => "ikiwiki/PageSpec",
127 example => "current",
128 description => "internal linking behavior (default/current/negotiated)",
135 foreach my $field (qw{po_master_language}) {
136 if (! exists $config{$field} || ! defined $config{$field}) {
137 error(sprintf(gettext("Must specify %s when using the %s plugin"),
142 if (ref $config{po_slave_languages} eq 'ARRAY') {
144 foreach my $pair (@{$config{po_slave_languages}}) {
145 my ($code, $name) = ( $pair =~ /^([a-z]{2})\|(.+)$/ );
146 if (!defined $code || !defined $name) {
147 error(sprintf(gettext("%s has invalid syntax: must use CODE|NAME"),
150 $slaves{$code} = $name;
151 push @slavelanguages, $code;
154 $config{po_slave_languages} = \%slaves;
156 elsif (ref $config{po_slave_languages} eq 'HASH') {
157 @slavelanguages = sort {
158 $config{po_slave_languages}->{$a} cmp $config{po_slave_languages}->{$b};
159 } keys %{$config{po_slave_languages}};
162 delete $config{po_slave_languages}{$config{po_master_language}{code}};;
166 or error(sprintf(gettext("%s is not a valid language code"), $_));
167 } ($config{po_master_language}{code}, @slavelanguages);
169 if (! exists $config{po_translatable_pages} ||
170 ! defined $config{po_translatable_pages}) {
171 $config{po_translatable_pages}="";
173 if (! exists $config{po_link_to} ||
174 ! defined $config{po_link_to}) {
175 $config{po_link_to}='default';
177 elsif ($config{po_link_to} !~ /^(default|current|negotiated)$/) {
178 warn(sprintf(gettext('%s is not a valid value for po_link_to, falling back to po_link_to=default'),
179 $config{po_link_to}));
180 $config{po_link_to}='default';
182 elsif ($config{po_link_to} eq "negotiated" && ! $config{usedirs}) {
183 warn(gettext('po_link_to=negotiated requires usedirs to be enabled, falling back to po_link_to=default'));
184 $config{po_link_to}='default';
187 push @{$config{wiki_file_prune_regexps}}, qr/\.pot$/;
189 # Translated versions of the underlays are added if available.
190 foreach my $underlay ("basewiki",
191 map { m/^\Q$config{underlaydirbase}\E\/*(.*)/ }
192 reverse @{$config{underlaydirs}}) {
193 next if $underlay=~/^locale\//;
195 # Underlays containing the po files for slave languages.
196 foreach my $ll (@slavelanguages) {
197 add_underlay("po/$ll/$underlay")
198 if -d "$config{underlaydirbase}/po/$ll/$underlay";
201 if ($config{po_master_language}{code} ne 'en') {
202 # Add underlay containing translated source files
203 # for the master language.
204 add_underlay("locale/$config{po_master_language}{code}/$underlay")
205 if -d "$config{underlaydirbase}/locale/$config{po_master_language}{code}/$underlay";
211 my $needsbuild=shift;
213 # backup @needsbuild content so that change() can know whether
214 # a given master page was rendered because its source file was changed
215 @origneedsbuild=(@$needsbuild);
218 buildtranslationscache();
220 # make existing translations depend on the corresponding master page
221 foreach my $master (keys %translations) {
222 map add_depends($_, $master), values %{otherlanguages_pages($master)};
228 my $page=$params{page};
229 my $content=$params{content};
230 my $run_by_po=$params{run_by_po};
232 # Massage the recorded state of internal links so that:
233 # - it matches the actually generated links, rather than the links as
234 # written in the pages' source
235 # - backlinks are consistent in all cases
237 # A second scan pass is made over translation pages, so as an
238 # optimization, we only do so on the second pass in this case,
239 # i.e. when this hook is called by itself.
240 if ($run_by_po && istranslation($page)) {
241 # replace the occurence of $destpage in $links{$page}
242 my @orig_links = @{$links{$page}};
244 foreach my $destpage (@orig_links) {
245 if (istranslatedto($destpage, lang($page))) {
246 add_link($page, $destpage . '.' . lang($page));
249 add_link($page, $destpage);
253 # No second scan pass is done for a non-translation page, so
254 # links massaging must happen on first pass in this case.
255 elsif (! $run_by_po && ! istranslatable($page) && ! istranslation($page)) {
256 foreach my $destpage (@{$links{$page}}) {
257 if (istranslatable($destpage)) {
258 # make sure any destpage's translations has
259 # $page in its backlinks
260 foreach my $link (values %{otherlanguages_pages($destpage)}) {
261 add_link($page, $link);
267 # Re-run the preprocess hooks in scan mode, then the scan hooks,
268 # over the po-to-markup converted content
269 return if $run_by_po; # avoid looping endlessly
270 return unless istranslation($page);
271 $content = po_to_markup($page, $content);
273 IkiWiki::preprocess($page, $page, $content, 1);
274 IkiWiki::run_hooks(scan => sub {
283 # We use filter to convert PO to the master page's format,
284 # since the rest of ikiwiki should not work on PO files.
288 my $page = $params{page};
289 my $destpage = $params{destpage};
290 my $content = $params{content};
291 if (istranslation($page) && ! alreadyfiltered($page, $destpage)) {
292 $content = po_to_markup($page, $content);
293 setalreadyfiltered($page, $destpage);
301 my $page = $params{page};
302 my $content = $params{content};
304 # ignore PO files this plugin did not create
305 return $content unless istranslation($page);
307 # force content to be htmlize'd as if it was the same type as the master page
308 return IkiWiki::htmlize($page, $page,
309 pagetype(srcfile($pagesources{masterpage($page)})),
313 sub pagetemplate (@) {
315 my $page=$params{page};
316 my $destpage=$params{destpage};
317 my $template=$params{template};
319 my ($masterpage, $lang) = istranslation($page);
321 if (istranslation($page) && $template->query(name => "percenttranslated")) {
322 $template->param(percenttranslated => percenttranslated($page));
324 if ($template->query(name => "istranslation")) {
325 $template->param(istranslation => scalar istranslation($page));
327 if ($template->query(name => "istranslatable")) {
328 $template->param(istranslatable => istranslatable($page));
330 if ($template->query(name => "HOMEPAGEURL")) {
331 $template->param(homepageurl => homepageurl($page));
333 if ($template->query(name => "otherlanguages")) {
334 $template->param(otherlanguages => [otherlanguagesloop($page)]);
335 map add_depends($page, $_), (values %{otherlanguages_pages($page)});
337 if ($config{discussion} && istranslation($page)) {
338 if ($page !~ /.*\/\Q$config{discussionpage}\E$/i &&
339 (length $config{cgiurl} ||
340 exists $links{$masterpage."/".lc($config{discussionpage})})) {
341 $template->param('discussionlink' => htmllink(
344 $masterpage . '/' . $config{discussionpage},
347 linktext => $config{discussionpage},
351 # Remove broken parentlink to ./index.html on home page's translations.
352 # It works because this hook has the "last" parameter set, to ensure it
353 # runs after parentlinks' own pagetemplate hook.
354 if ($template->param('parentlinks')
355 && istranslation($page)
356 && $masterpage eq "index") {
357 $template->param('parentlinks' => []);
359 if (ishomepage($page) && $template->query(name => "title")) {
360 $template->param(title => $config{wikiname});
364 # Add the renamed page translations to the list of to-be-renamed pages.
365 sub renamepages (@) {
368 my %torename = %{$params{torename}};
369 my $session = $params{session};
371 # Save the page(s) the user asked to rename, so that our
372 # canrename hook can tell the difference between:
373 # - a translation being renamed as a consequence of its master page
375 # - a user trying to directly rename a translation
376 # This is why this hook has to be run first, before the list of pages
377 # to rename is modified by other plugins.
379 @orig_torename=@{$session->param("po_orig_torename")}
380 if defined $session->param("po_orig_torename");
381 push @orig_torename, $torename{src};
382 $session->param(po_orig_torename => \@orig_torename);
383 IkiWiki::cgi_savesession($session);
385 return () unless istranslatable($torename{src});
388 my %otherpages=%{otherlanguages_pages($torename{src})};
389 while (my ($lang, $otherpage) = each %otherpages) {
392 srcfile => $pagesources{$otherpage},
393 dest => otherlanguage_page($torename{dest}, $lang),
394 destfile => $torename{dest}.".".$lang.".po",
404 map { deletetranslations($_) } grep istranslatablefile($_), @deleted;
410 my $updated_po_files=0;
412 # Refresh/create POT and PO files as needed.
413 foreach my $file (grep {istranslatablefile($_)} @rendered) {
414 my $masterfile=srcfile($file);
415 my $page=pagename($file);
416 my $updated_pot_file=0;
418 # Avoid touching underlay files.
419 next if $masterfile ne "$config{srcdir}/$file";
421 # Only refresh POT file if it does not exist, or if
422 # the source was changed: don't if only the HTML was
423 # refreshed, e.g. because of a dependency.
424 if ((grep { $_ eq $pagesources{$page} } @origneedsbuild) ||
425 ! -e potfile($masterfile)) {
426 refreshpot($masterfile);
430 foreach my $po (pofiles($masterfile)) {
431 next if ! $updated_pot_file && -e $po;
432 next if grep { $po=~/\Q$_\E/ } @{$config{underlaydirs}};
436 refreshpofiles($masterfile, @pofiles);
437 map { s/^\Q$config{srcdir}\E\/*//; IkiWiki::rcs_add($_) } @pofiles if $config{rcs};
442 if ($updated_po_files) {
444 gettext("updated PO files"));
448 sub checkcontent (@) {
451 if (istranslation($params{page})) {
452 my $res = isvalidpo($params{content});
466 if (istranslation($params{page})) {
467 return gettext("Can not remove a translation. If the master page is removed, ".
468 "however, its translations will be removed as well.");
475 my $session = $params{session};
477 if (istranslation($params{src})) {
478 my $masterpage = masterpage($params{src});
479 # Tell the difference between:
480 # - a translation being renamed as a consequence of its master page
481 # being renamed, which is allowed
482 # - a user trying to directly rename a translation, which is forbidden
483 # by looking for the master page in the list of to-be-renamed pages we
484 # saved early in the renaming process.
485 my $orig_torename = $session->param("po_orig_torename");
486 unless (grep { $_ eq $masterpage } @{$orig_torename}) {
487 return gettext("Can not rename a translation. If the master page is renamed, ".
488 "however, its translations will be renamed as well.");
494 # As we're previewing or saving a page, the content may have
495 # changed, so tell the next filter() invocation it must not be lazy.
499 unsetalreadyfiltered($params{page}, $params{page});
500 return $params{content};
503 sub formbuilder_setup (@) {
505 my $form=$params{form};
508 return unless defined $form->field("do");
510 if ($form->field("do") eq "create") {
511 # Warn the user: new pages must be written in master language.
512 my $template=template("pocreatepage.tmpl");
513 $template->param(LANG => $config{po_master_language}{name});
514 $form->tmpl_param(message => $template->output);
516 elsif ($form->field("do") eq "edit") {
517 # Remove the rename/remove buttons on slave pages.
518 # This has to be done after the rename/remove plugins have added
519 # their buttons, which is why this hook must be run last.
520 # The canrename/canremove hooks already ensure this is forbidden
521 # at the backend level, so this is only UI sugar.
522 if (istranslation($form->field("page"))) {
524 for (my $i = 0; $i < @{$params{buttons}}; $i++) {
525 if (@{$params{buttons}}[$i] eq $_) {
526 delete @{$params{buttons}}[$i];
535 sub formbuilder (@) {
537 my $form=$params{form};
540 return unless defined $form->field("do");
542 # Do not allow to create pages of type po: they are automatically created.
543 # The main reason to do so is to bypass the "favor the type of linking page
544 # on page creation" logic, which is unsuitable when a broken link is clicked
545 # on a slave (PO) page.
546 # This cannot be done in the formbuilder_setup hook as the list of types is
548 if ($form->field("do") eq "create") {
549 foreach my $field ($form->field) {
550 next unless "$field" eq "type";
551 next unless $field->type eq 'select';
552 my $orig_value = $field->value;
553 # remove po from the list of types
554 my @types = grep { $_->[0] ne 'po' } $field->options;
555 $field->options(\@types) if @types;
556 # favor the type of linking page's masterpage
557 if ($orig_value eq 'po') {
559 if (defined $form->field('from')) {
560 ($from)=$form->field('from')=~/$config{wiki_file_regexp}/;
561 $from = masterpage($from);
563 if (defined $from && exists $pagesources{$from}) {
564 $type=pagetype($pagesources{$from});
566 $type=$config{default_pageext} unless defined $type;
567 $field->value($type) ;
574 # | Injected functions
577 # Implement po_link_to 'current' and 'negotiated' settings.
578 sub mybestlink ($$) {
582 return $origsubs{'bestlink'}->($page, $link)
583 if defined $config{po_link_to} && $config{po_link_to} eq "default";
585 my $res=$origsubs{'bestlink'}->(masterpage($page), $link);
586 my @caller = caller(1);
588 && istranslatedto($res, lang($page))
589 && istranslation($page)
590 && !(exists $caller[3] && defined $caller[3]
591 && ($caller[3] eq "IkiWiki::PageSpec::match_link"))) {
592 return $res . "." . lang($page);
597 sub mybeautify_urlpath ($) {
600 my $res=$origsubs{'beautify_urlpath'}->($url);
601 if (defined $config{po_link_to} && $config{po_link_to} eq "negotiated") {
602 $res =~ s!/\Qindex.$config{po_master_language}{code}.$config{htmlext}\E$!/!;
603 $res =~ s!/\Qindex.$config{htmlext}\E$!/!;
605 $res =~ s!/\Qindex.$_.$config{htmlext}\E$!/!;
611 sub mytargetpage ($$) {
615 if (istranslation($page) || istranslatable($page)) {
616 my ($masterpage, $lang) = (masterpage($page), lang($page));
617 if (! $config{usedirs} || $masterpage eq 'index') {
618 return $masterpage . "." . $lang . "." . $ext;
621 return $masterpage . "/index." . $lang . "." . $ext;
624 return $origsubs{'targetpage'}->($page, $ext);
632 # workaround hard-coded /index.$config{htmlext} in IkiWiki::urlto()
634 && $config{po_link_to} eq "current"
635 && istranslatable('index')) {
636 return IkiWiki::beautify_urlpath(IkiWiki::baseurl($from) . "index." . lang($from) . ".$config{htmlext}");
638 # avoid using our injected beautify_urlpath if run by cgi_editpage,
639 # so that one is redirected to the just-edited page rather than to the
640 # negociated translation; to prevent unnecessary fiddling with caller/inject,
641 # we only do so when our beautify_urlpath would actually do what we want to
642 # avoid, i.e. when po_link_to = negotiated.
643 # also avoid doing so when run by cgi_goto, so that the links on recentchanges
644 # page actually lead to the exact page they pretend to.
645 if ($config{po_link_to} eq "negotiated") {
646 my @caller = caller(1);
648 $use_orig = 1 if (exists $caller[3] && defined $caller[3]
649 && ($caller[3] eq "IkiWiki::cgi_editpage" ||
650 $caller[3] eq "IkiWiki::Plugin::goto::cgi_goto")
652 inject(name => "IkiWiki::beautify_urlpath", call => $origsubs{'beautify_urlpath'})
654 my $res = $origsubs{'urlto'}->($to,$from,$absolute);
655 inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath)
660 return $origsubs{'urlto'}->($to,$from,$absolute)
667 # slave pages have no subpages
668 if (istranslation($params{'from'})) {
669 $params{'from'} = masterpage($params{'from'});
671 return $origsubs{'cgiurl'}->(%params);
678 if (exists $params{rootpage}) {
679 $rootpage=$origsubs{'bestlink'}->($params{page}, $params{rootpage});
680 if (!length $rootpage) {
681 $rootpage=$params{rootpage};
685 $rootpage=masterpage($params{page});
690 sub myisselflink ($$) {
694 return 1 if $origsubs{'isselflink'}->($page, $link);
695 if (istranslation($page)) {
696 return $origsubs{'isselflink'}->(masterpage($page), $link);
702 # | Blackboxes for private data
708 sub alreadyfiltered($$) {
712 return exists $filtered{$page}{$destpage}
713 && $filtered{$page}{$destpage} eq 1;
716 sub setalreadyfiltered($$) {
720 $filtered{$page}{$destpage}=1;
723 sub unsetalreadyfiltered($$) {
727 if (exists $filtered{$page}{$destpage}) {
728 delete $filtered{$page}{$destpage};
732 sub resetalreadyfiltered() {
741 sub maybe_add_leading_slash ($;$) {
744 $add=1 unless defined $add;
745 return '/' . $str if $add;
749 sub istranslatablefile ($) {
752 return 0 unless defined $file;
753 my $type=pagetype($file);
754 return 0 if ! defined $type || $type eq 'po';
755 return 0 if $file =~ /\.pot$/;
756 return 0 if ! defined $config{po_translatable_pages};
757 return 1 if pagespec_match(pagename($file), $config{po_translatable_pages});
761 sub istranslatable ($) {
765 return 1 if istranslatablefile($pagesources{$page});
769 sub istranslatedto ($$) {
771 my $destlang = shift;
774 return 0 unless istranslatable($page);
775 exists $pagesources{otherlanguage_page($page, $destlang)};
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;
854 if ($lang eq $config{po_master_language}{code} ||
855 istranslatedto(masterpage($page), $lang)) {
862 sub otherlanguages_pages ($) {
867 $ret{$_} = otherlanguage_page($page, $_)
868 } @{otherlanguages_codes($page)};
874 my $masterfile=shift;
876 (my $name, my $dir, my $suffix) = fileparse($masterfile, qr/\.[^.]*/);
877 $dir='' if $dir eq './';
878 return File::Spec->catpath('', $dir, $name . ".pot");
882 my $masterfile=shift;
885 (my $name, my $dir, my $suffix) = fileparse($masterfile, qr/\.[^.]*/);
886 $dir='' if $dir eq './';
887 return File::Spec->catpath('', $dir, $name . "." . $lang . ".po");
891 my $masterfile=shift;
893 return map pofile($masterfile, $_), @slavelanguages;
897 my $masterfile=shift;
899 my $potfile=potfile($masterfile);
900 my $doc=Locale::Po4a::Chooser::new(po4a_type($masterfile),
901 po4a_options($masterfile));
902 $doc->{TT}{utf_mode} = 1;
903 $doc->{TT}{file_in_charset} = 'UTF-8';
904 $doc->{TT}{file_out_charset} = 'UTF-8';
905 $doc->read($masterfile);
906 # let's cheat a bit to force porefs option to be passed to
907 # Locale::Po4a::Po; this is undocument use of internal
908 # Locale::Po4a::TransTractor's data, compulsory since this module
909 # prevents us from using the porefs option.
910 $doc->{TT}{po_out}=Locale::Po4a::Po->new({ 'porefs' => 'none' });
911 $doc->{TT}{po_out}->set_charset('UTF-8');
914 IkiWiki::prep_writefile(basename($potfile),dirname($potfile));
915 $doc->writepo($potfile);
918 sub refreshpofiles ($@) {
919 my $masterfile=shift;
922 my $potfile=potfile($masterfile);
924 error("po(refreshpofiles) ".sprintf(gettext("POT file (%s) does not exist"), $potfile));
927 foreach my $pofile (@pofiles) {
928 IkiWiki::prep_writefile(basename($pofile),dirname($pofile));
931 # If the po file exists in an underlay, copy it
933 my ($pobase)=$pofile=~/^\Q$config{srcdir}\E\/?(.*)$/;
934 foreach my $dir (@{$config{underlaydirs}}) {
935 if (-e "$dir/$pobase") {
936 File::Copy::syscopy("$dir/$pobase",$pofile)
937 or error("po(refreshpofiles) ".
938 sprintf(gettext("failed to copy underlay PO file to %s"),
945 system("msgmerge", "--previous", "-q", "-U", "--backup=none", $pofile, $potfile) == 0
946 or error("po(refreshpofiles) ".
947 sprintf(gettext("failed to update %s"),
951 File::Copy::syscopy($potfile,$pofile)
952 or error("po(refreshpofiles) ".
953 sprintf(gettext("failed to copy the POT file to %s"),
959 sub buildtranslationscache() {
960 # use istranslation's side-effect
961 map istranslation($_), (keys %pagesources);
964 sub resettranslationscache() {
968 sub flushmemoizecache() {
969 Memoize::flush_cache("istranslatable");
970 Memoize::flush_cache("_istranslation");
971 Memoize::flush_cache("percenttranslated");
974 sub urlto_with_orig_beautiful_urlpath($$) {
978 inject(name => "IkiWiki::beautify_urlpath", call => $origsubs{'beautify_urlpath'});
979 my $res=urlto($to, $from);
980 inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath);
985 sub percenttranslated ($) {
989 return gettext("N/A") unless istranslation($page);
990 my $file=srcfile($pagesources{$page});
991 my $masterfile = srcfile($pagesources{masterpage($page)});
992 my $doc=Locale::Po4a::Chooser::new(po4a_type($masterfile),
993 po4a_options($masterfile));
995 'po_in_name' => [ $file ],
996 'file_in_name' => [ $masterfile ],
997 'file_in_charset' => 'UTF-8',
998 'file_out_charset' => 'UTF-8',
999 ) or error("po(percenttranslated) ".
1000 sprintf(gettext("failed to translate %s"), $page));
1001 my ($percent,$hit,$queries) = $doc->stats();
1002 $percent =~ s/\.[0-9]+$//;
1006 sub languagename ($) {
1009 return $config{po_master_language}{name}
1010 if $code eq $config{po_master_language}{code};
1011 return $config{po_slave_languages}{$code}
1012 if defined $config{po_slave_languages}{$code};
1016 sub otherlanguagesloop ($) {
1020 if (istranslation($page)) {
1022 url => urlto_with_orig_beautiful_urlpath(masterpage($page), $page),
1023 code => $config{po_master_language}{code},
1024 language => $config{po_master_language}{name},
1028 foreach my $lang (@{otherlanguages_codes($page)}) {
1029 next if $lang eq $config{po_master_language}{code};
1030 my $otherpage = otherlanguage_page($page, $lang);
1032 url => urlto_with_orig_beautiful_urlpath($otherpage, $page),
1034 language => languagename($lang),
1035 percent => percenttranslated($otherpage),
1041 sub homepageurl (;$) {
1044 return urlto('', $page);
1047 sub ishomepage ($) {
1050 return 1 if $page eq 'index';
1051 map { return 1 if $page eq 'index.'.$_ } @slavelanguages;
1055 sub deletetranslations ($) {
1056 my $deletedmasterfile=shift;
1058 my $deletedmasterpage=pagename($deletedmasterfile);
1061 my $file = newpagefile($deletedmasterpage.'.'.$_, 'po');
1062 my $absfile = "$config{srcdir}/$file";
1063 if (-e $absfile && ! -l $absfile && ! -d $absfile) {
1064 push @todelete, $file;
1070 IkiWiki::rcs_remove($_);
1073 IkiWiki::prune("$config{srcdir}/$_");
1079 gettext("removed obsolete PO files"));
1083 sub commit_and_refresh ($) {
1087 IkiWiki::disable_commit_hook();
1088 IkiWiki::rcs_commit_staged(
1091 IkiWiki::enable_commit_hook();
1092 IkiWiki::rcs_update();
1094 # Reinitialize module's private variables.
1095 resetalreadyfiltered();
1096 resettranslationscache();
1097 flushmemoizecache();
1098 # Trigger a wiki refresh.
1099 require IkiWiki::Render;
1100 # without preliminary saveindex/loadindex, refresh()
1101 # complains about a lot of uninitialized variables
1102 IkiWiki::saveindex();
1103 IkiWiki::loadindex();
1105 IkiWiki::saveindex();
1108 sub po_to_markup ($$) {
1109 my ($page, $content) = (shift, shift);
1111 $content = '' unless defined $content;
1112 $content = decode_utf8(encode_utf8($content));
1113 # CRLF line terminators make poor Locale::Po4a feel bad
1114 $content=~s/\r\n/\n/g;
1116 # There are incompatibilities between some File::Temp versions
1117 # (including 0.18, bundled with Lenny's perl-modules package)
1118 # and others (e.g. 0.20, previously present in the archive as
1119 # a standalone package): under certain circumstances, some
1120 # return a relative filename, whereas others return an absolute one;
1121 # we here use this module in a way that is at least compatible
1122 # with 0.18 and 0.20. Beware, hit'n'run refactorers!
1123 my $infile = new File::Temp(TEMPLATE => "ikiwiki-po-filter-in.XXXXXXXXXX",
1124 DIR => File::Spec->tmpdir,
1125 UNLINK => 1)->filename;
1126 my $outfile = new File::Temp(TEMPLATE => "ikiwiki-po-filter-out.XXXXXXXXXX",
1127 DIR => File::Spec->tmpdir,
1128 UNLINK => 1)->filename;
1130 my $fail = sub ($) {
1131 my $msg = "po(po_to_markup) - $page : " . shift;
1132 error($msg, sub { unlink $infile, $outfile});
1135 writefile(basename($infile), File::Spec->tmpdir, $content)
1136 or return $fail->(sprintf(gettext("failed to write %s"), $infile));
1138 my $masterfile = srcfile($pagesources{masterpage($page)});
1139 my $doc=Locale::Po4a::Chooser::new(po4a_type($masterfile),
1140 po4a_options($masterfile));
1142 'po_in_name' => [ $infile ],
1143 'file_in_name' => [ $masterfile ],
1144 'file_in_charset' => 'UTF-8',
1145 'file_out_charset' => 'UTF-8',
1146 ) or return $fail->(gettext("failed to translate"));
1147 $doc->write($outfile)
1148 or return $fail->(sprintf(gettext("failed to write %s"), $outfile));
1150 $content = readfile($outfile);
1152 # Unlinking should happen automatically, thanks to File::Temp,
1153 # but it does not work here, probably because of the way writefile()
1154 # and Locale::Po4a::write() work.
1155 unlink $infile, $outfile;
1160 # returns a SuccessReason or FailReason object
1162 my $content = shift;
1164 # NB: we don't use po_to_markup here, since Po4a parser does
1165 # not mind invalid PO content
1166 $content = '' unless defined $content;
1167 $content = decode_utf8(encode_utf8($content));
1169 # There are incompatibilities between some File::Temp versions
1170 # (including 0.18, bundled with Lenny's perl-modules package)
1171 # and others (e.g. 0.20, previously present in the archive as
1172 # a standalone package): under certain circumstances, some
1173 # return a relative filename, whereas others return an absolute one;
1174 # we here use this module in a way that is at least compatible
1175 # with 0.18 and 0.20. Beware, hit'n'run refactorers!
1176 my $infile = new File::Temp(TEMPLATE => "ikiwiki-po-isvalidpo.XXXXXXXXXX",
1177 DIR => File::Spec->tmpdir,
1178 UNLINK => 1)->filename;
1180 my $fail = sub ($) {
1181 my $msg = '[po/isvalidpo] ' . shift;
1183 return IkiWiki::FailReason->new("$msg");
1186 writefile(basename($infile), File::Spec->tmpdir, $content)
1187 or return $fail->(sprintf(gettext("failed to write %s"), $infile));
1189 my $res = (system("msgfmt", "--check", $infile, "-o", "/dev/null") == 0);
1191 # Unlinking should happen automatically, thanks to File::Temp,
1192 # but it does not work here, probably because of the way writefile()
1193 # and Locale::Po4a::write() work.
1197 return IkiWiki::SuccessReason->new("valid gettext data");
1199 return IkiWiki::FailReason->new(gettext("invalid gettext data, go back ".
1200 "to previous page to continue edit"));
1206 my $pagetype = pagetype($file);
1207 if ($pagetype eq 'html') {
1213 sub po4a_options($) {
1217 my $pagetype = pagetype($file);
1219 if ($pagetype eq 'html') {
1220 # how to disable options is not consistent across po4a modules
1221 $options{includessi} = '';
1222 $options{includeexternal} = 0;
1224 elsif ($pagetype eq 'mdwn') {
1225 $options{markdown} = 1;
1228 $options{markdown} = 0;
1238 package IkiWiki::PageSpec;
1240 sub match_istranslation ($;@) {
1243 if (IkiWiki::Plugin::po::istranslation($page)) {
1244 return IkiWiki::SuccessReason->new("is a translation page");
1247 return IkiWiki::FailReason->new("is not a translation page");
1251 sub match_istranslatable ($;@) {
1254 if (IkiWiki::Plugin::po::istranslatable($page)) {
1255 return IkiWiki::SuccessReason->new("is set as translatable in po_translatable_pages");
1258 return IkiWiki::FailReason->new("is not set as translatable in po_translatable_pages");
1262 sub match_lang ($$;@) {
1266 my $regexp=IkiWiki::glob2re($wanted);
1267 my $lang=IkiWiki::Plugin::po::lang($page);
1268 if ($lang !~ /^$regexp$/i) {
1269 return IkiWiki::FailReason->new("file language is $lang, not $wanted");
1272 return IkiWiki::SuccessReason->new("file language is $wanted");
1276 sub match_currentlang ($$;@) {
1281 return IkiWiki::FailReason->new("no location provided") unless exists $params{location};
1283 my $currentlang=IkiWiki::Plugin::po::lang($params{location});
1284 my $lang=IkiWiki::Plugin::po::lang($page);
1286 if ($lang eq $currentlang) {
1287 return IkiWiki::SuccessReason->new("file language is the same as current one, i.e. $currentlang");
1290 return IkiWiki::FailReason->new("file language is $lang, whereas current language is $currentlang");
1294 sub match_needstranslation ($$;@) {
1298 if (defined $wanted && $wanted ne "") {
1299 if ($wanted !~ /^\d+$/) {
1300 return IkiWiki::FailReason->new("parameter is not an integer");
1302 elsif ($wanted > 100) {
1303 return IkiWiki::FailReason->new("parameter is greater than 100");
1310 my $percenttranslated=IkiWiki::Plugin::po::percenttranslated($page);
1311 if ($percenttranslated eq 'N/A') {
1312 return IkiWiki::FailReason->new("file is not a translatable page");
1314 elsif ($percenttranslated < $wanted) {
1315 return IkiWiki::SuccessReason->new("file has $percenttranslated translated");
1318 return IkiWiki::FailReason->new("file is translated enough");