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;
28 my ($master_language_code, $master_language_name);
32 my @slavelanguages; # language codes ordered as in config po_slave_languages
33 my %slavelanguages; # language code to name lookup
34 my $language_code_pattern = '[a-zA-Z]+(?:_[a-zA-Z]+)?';
36 memoize("istranslatable");
37 memoize("_istranslation");
38 memoize("percenttranslated");
41 hook(type => "getsetup", id => "po", call => \&getsetup);
42 hook(type => "checkconfig", id => "po", call => \&checkconfig,
44 hook(type => "needsbuild", id => "po", call => \&needsbuild);
45 hook(type => "scan", id => "po", call => \&scan, last => 1);
46 hook(type => "filter", id => "po", call => \&filter);
47 hook(type => "htmlize", id => "po", call => \&htmlize);
48 hook(type => "pagetemplate", id => "po", call => \&pagetemplate, last => 1);
49 hook(type => "rename", id => "po", call => \&renamepages, first => 1);
50 hook(type => "delete", id => "po", call => \&mydelete);
51 hook(type => "change", id => "po", call => \&change);
52 hook(type => "checkcontent", id => "po", call => \&checkcontent);
53 hook(type => "canremove", id => "po", call => \&canremove);
54 hook(type => "canrename", id => "po", call => \&canrename);
55 hook(type => "editcontent", id => "po", call => \&editcontent);
56 hook(type => "formbuilder_setup", id => "po", call => \&formbuilder_setup, last => 1);
57 hook(type => "formbuilder", id => "po", call => \&formbuilder);
60 $origsubs{'bestlink'}=\&IkiWiki::bestlink;
61 inject(name => "IkiWiki::bestlink", call => \&mybestlink);
62 $origsubs{'beautify_urlpath'}=\&IkiWiki::beautify_urlpath;
63 inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath);
64 $origsubs{'targetpage'}=\&IkiWiki::targetpage;
65 inject(name => "IkiWiki::targetpage", call => \&mytargetpage);
66 $origsubs{'urlto'}=\&IkiWiki::urlto;
67 inject(name => "IkiWiki::urlto", call => \&myurlto);
68 $origsubs{'cgiurl'}=\&IkiWiki::cgiurl;
69 inject(name => "IkiWiki::cgiurl", call => \&mycgiurl);
70 if (IkiWiki->can('rootpage')) {
71 $origsubs{'rootpage'}=\&IkiWiki::rootpage;
72 inject(name => "IkiWiki::rootpage", call => \&myrootpage)
73 if defined $origsubs{'rootpage'};
75 $origsubs{'isselflink'}=\&IkiWiki::isselflink;
76 inject(name => "IkiWiki::isselflink", call => \&myisselflink);
86 # 2. Injected functions
87 # 3. Blackboxes for private data
100 rebuild => 1, # format plugin
103 po_master_language => {
105 example => "en|English",
106 description => "master language (non-PO files)",
110 po_slave_languages => {
117 description => "slave languages (translated via PO files) format: ll|Langname",
121 po_translatable_pages => {
123 example => "* and !*/Discussion",
124 description => "PageSpec controlling which pages are translatable",
125 link => "ikiwiki/PageSpec",
131 example => "current",
132 description => "internal linking behavior (default/current/negotiated)",
139 if (exists $config{po_master_language}) {
140 if (! ref $config{po_master_language}) {
141 ($master_language_code, $master_language_name)=
142 splitlangpair($config{po_master_language});
145 $master_language_code=$config{po_master_language}{code};
146 $master_language_name=$config{po_master_language}{name};
147 $config{po_master_language}=joinlangpair($master_language_code, $master_language_name);
150 if (! defined $master_language_code) {
151 $master_language_code='en';
153 if (! defined $master_language_name) {
154 $master_language_name='English';
157 if (ref $config{po_slave_languages} eq 'ARRAY') {
158 foreach my $pair (@{$config{po_slave_languages}}) {
159 my ($code, $name)=splitlangpair($pair);
160 if (defined $code && ! exists $slavelanguages{$code}) {
161 push @slavelanguages, $code;
162 $slavelanguages{$code} = $name;
166 elsif (ref $config{po_slave_languages} eq 'HASH') {
167 %slavelanguages=%{$config{po_slave_languages}};
168 @slavelanguages = sort {
169 $config{po_slave_languages}->{$a} cmp $config{po_slave_languages}->{$b};
170 } keys %slavelanguages;
171 $config{po_slave_languages}=[
172 map { joinlangpair($_, $slavelanguages{$_}) } @slavelanguages
176 delete $slavelanguages{$master_language_code};
180 or error(sprintf(gettext("%s is not a valid language code"), $_));
181 } ($master_language_code, @slavelanguages);
183 if (! exists $config{po_translatable_pages} ||
184 ! defined $config{po_translatable_pages}) {
185 $config{po_translatable_pages}="";
187 if (! exists $config{po_link_to} ||
188 ! defined $config{po_link_to}) {
189 $config{po_link_to}='default';
191 elsif ($config{po_link_to} !~ /^(default|current|negotiated)$/) {
192 warn(sprintf(gettext('%s is not a valid value for po_link_to, falling back to po_link_to=default'),
193 $config{po_link_to}));
194 $config{po_link_to}='default';
196 elsif ($config{po_link_to} eq "negotiated" && ! $config{usedirs}) {
197 warn(gettext('po_link_to=negotiated requires usedirs to be enabled, falling back to po_link_to=default'));
198 $config{po_link_to}='default';
201 push @{$config{wiki_file_prune_regexps}}, qr/\.pot$/;
203 # Translated versions of the underlays are added if available.
204 foreach my $underlay ("basewiki",
205 map { m/^\Q$config{underlaydirbase}\E\/*(.*)/ }
206 reverse @{$config{underlaydirs}}) {
207 next if $underlay=~/^locale\//;
209 # Underlays containing the po files for slave languages.
210 foreach my $ll (@slavelanguages) {
211 add_underlay("po/$ll/$underlay")
212 if -d "$config{underlaydirbase}/po/$ll/$underlay";
215 if ($master_language_code ne 'en') {
216 # Add underlay containing translated source files
217 # for the master language.
218 add_underlay("locale/$master_language_code/$underlay")
219 if -d "$config{underlaydirbase}/locale/$master_language_code/$underlay";
225 my $needsbuild=shift;
227 # backup @needsbuild content so that change() can know whether
228 # a given master page was rendered because its source file was changed
229 @origneedsbuild=(@$needsbuild);
232 buildtranslationscache();
234 # make existing translations depend on the corresponding master page
235 foreach my $master (keys %translations) {
236 map add_depends($_, $master), values %{otherlanguages_pages($master)};
244 my $page=$params{page};
245 my $content=$params{content};
246 my $run_by_po=$params{run_by_po};
248 # Massage the recorded state of internal links so that:
249 # - it matches the actually generated links, rather than the links as
250 # written in the pages' source
251 # - backlinks are consistent in all cases
253 # A second scan pass is made over translation pages, so as an
254 # optimization, we only do so on the second pass in this case,
255 # i.e. when this hook is called by itself.
256 if ($run_by_po && istranslation($page)) {
257 # replace the occurence of $destpage in $links{$page}
258 my @orig_links = @{$links{$page}};
260 foreach my $destpage (@orig_links) {
261 if (istranslatedto($destpage, lang($page))) {
262 add_link($page, $destpage . '.' . lang($page));
265 add_link($page, $destpage);
269 # No second scan pass is done for a non-translation page, so
270 # links massaging must happen on first pass in this case.
271 elsif (! $run_by_po && ! istranslatable($page) && ! istranslation($page)) {
272 foreach my $destpage (@{$links{$page}}) {
273 if (istranslatable($destpage)) {
274 # make sure any destpage's translations has
275 # $page in its backlinks
276 foreach my $link (values %{otherlanguages_pages($destpage)}) {
277 add_link($page, $link);
283 # Re-run the preprocess hooks in scan mode, then the scan hooks,
284 # over the po-to-markup converted content
285 return if $run_by_po; # avoid looping endlessly
286 return unless istranslation($page);
287 $content = po_to_markup($page, $content);
289 IkiWiki::preprocess($page, $page, $content, 1);
290 IkiWiki::run_hooks(scan => sub {
299 # We use filter to convert PO to the master page's format,
300 # since the rest of ikiwiki should not work on PO files.
304 my $page = $params{page};
305 my $destpage = $params{destpage};
306 my $content = $params{content};
307 if (istranslation($page) && ! alreadyfiltered($page, $destpage)) {
308 $content = po_to_markup($page, $content);
309 setalreadyfiltered($page, $destpage);
317 my $page = $params{page};
318 my $content = $params{content};
320 # ignore PO files this plugin did not create
321 return $content unless istranslation($page);
323 # force content to be htmlize'd as if it was the same type as the master page
324 return IkiWiki::htmlize($page, $page,
325 pagetype(srcfile($pagesources{masterpage($page)})),
329 sub pagetemplate (@) {
331 my $page=$params{page};
332 my $destpage=$params{destpage};
333 my $template=$params{template};
335 my ($masterpage, $lang) = istranslation($page);
337 if (istranslation($page) && $template->query(name => "percenttranslated")) {
338 $template->param(percenttranslated => percenttranslated($page));
340 if ($template->query(name => "istranslation")) {
341 $template->param(istranslation => scalar istranslation($page));
343 if ($template->query(name => "istranslatable")) {
344 $template->param(istranslatable => istranslatable($page));
346 my $lang_code = istranslation($page) ? lang($page) : $master_language_code;
347 if ($template->query(name => "lang_code")) {
348 $template->param(lang_code => $lang_code);
350 if ($template->query(name => "lang_name")) {
351 $template->param(lang_name => languagename($lang_code));
353 if ($template->query(name => "HOMEPAGEURL")) {
354 $template->param(homepageurl => homepageurl($page));
356 if ($template->query(name => "otherlanguages")) {
357 $template->param(otherlanguages => [otherlanguagesloop($page)]);
358 map add_depends($page, $_), (values %{otherlanguages_pages($page)});
360 if ($config{discussion} && istranslation($page)) {
361 if ($page !~ /.*\/\Q$config{discussionpage}\E$/i &&
362 (length $config{cgiurl} ||
363 exists $links{$masterpage."/".lc($config{discussionpage})})) {
364 $template->param('discussionlink' => htmllink(
367 $masterpage . '/' . $config{discussionpage},
370 linktext => $config{discussionpage},
374 # Remove broken parentlink to ./index.html on home page's translations.
375 # It works because this hook has the "last" parameter set, to ensure it
376 # runs after parentlinks' own pagetemplate hook.
377 if ($template->param('parentlinks')
378 && istranslation($page)
379 && $masterpage eq "index") {
380 $template->param('parentlinks' => []);
382 if (ishomepage($page) && $template->query(name => "title")
383 && !$template->param("title_overridden")) {
384 $template->param(title => $config{wikiname});
388 # Add the renamed page translations to the list of to-be-renamed pages.
389 sub renamepages (@) {
392 my %torename = %{$params{torename}};
393 my $session = $params{session};
395 # Save the page(s) the user asked to rename, so that our
396 # canrename hook can tell the difference between:
397 # - a translation being renamed as a consequence of its master page
399 # - a user trying to directly rename a translation
400 # This is why this hook has to be run first, before the list of pages
401 # to rename is modified by other plugins.
403 @orig_torename=@{$session->param("po_orig_torename")}
404 if defined $session->param("po_orig_torename");
405 push @orig_torename, $torename{src};
406 $session->param(po_orig_torename => \@orig_torename);
407 IkiWiki::cgi_savesession($session);
409 return () unless istranslatable($torename{src});
412 my %otherpages=%{otherlanguages_pages($torename{src})};
413 while (my ($lang, $otherpage) = each %otherpages) {
416 srcfile => $pagesources{$otherpage},
417 dest => otherlanguage_page($torename{dest}, $lang),
418 destfile => $torename{dest}.".".$lang.".po",
428 map { deletetranslations($_) } grep istranslatablefile($_), @deleted;
434 my $updated_po_files=0;
436 # Refresh/create POT and PO files as needed.
437 foreach my $file (grep {istranslatablefile($_)} @rendered) {
438 my $masterfile=srcfile($file);
439 my $page=pagename($file);
440 my $updated_pot_file=0;
442 # Avoid touching underlay files.
443 next if $masterfile ne "$config{srcdir}/$file";
445 # Only refresh POT file if it does not exist, or if
446 # the source was changed: don't if only the HTML was
447 # refreshed, e.g. because of a dependency.
448 if ((grep { $_ eq $pagesources{$page} } @origneedsbuild) ||
449 ! -e potfile($masterfile)) {
450 refreshpot($masterfile);
454 foreach my $po (pofiles($masterfile)) {
455 next if ! $updated_pot_file && -e $po;
456 next if grep { $po=~/\Q$_\E/ } @{$config{underlaydirs}};
460 refreshpofiles($masterfile, @pofiles);
461 map { s/^\Q$config{srcdir}\E\/*//; IkiWiki::rcs_add($_) } @pofiles if $config{rcs};
466 if ($updated_po_files) {
468 gettext("updated PO files"));
472 sub checkcontent (@) {
475 if (istranslation($params{page})) {
476 my $res = isvalidpo($params{content});
490 if (istranslation($params{page})) {
491 return gettext("Can not remove a translation. If the master page is removed, ".
492 "however, its translations will be removed as well.");
499 my $session = $params{session};
501 if (istranslation($params{src})) {
502 my $masterpage = masterpage($params{src});
503 # Tell the difference between:
504 # - a translation being renamed as a consequence of its master page
505 # being renamed, which is allowed
506 # - a user trying to directly rename a translation, which is forbidden
507 # by looking for the master page in the list of to-be-renamed pages we
508 # saved early in the renaming process.
509 my $orig_torename = $session->param("po_orig_torename");
510 unless (grep { $_ eq $masterpage } @{$orig_torename}) {
511 return gettext("Can not rename a translation. If the master page is renamed, ".
512 "however, its translations will be renamed as well.");
518 # As we're previewing or saving a page, the content may have
519 # changed, so tell the next filter() invocation it must not be lazy.
523 unsetalreadyfiltered($params{page}, $params{page});
524 return $params{content};
527 sub formbuilder_setup (@) {
529 my $form=$params{form};
532 return unless defined $form->field("do");
534 if ($form->field("do") eq "create") {
535 # Warn the user: new pages must be written in master language.
536 my $template=template("pocreatepage.tmpl");
537 $template->param(LANG => $master_language_name);
538 $form->tmpl_param(message => $template->output);
540 elsif ($form->field("do") eq "edit") {
541 # Remove the rename/remove buttons on slave pages.
542 # This has to be done after the rename/remove plugins have added
543 # their buttons, which is why this hook must be run last.
544 # The canrename/canremove hooks already ensure this is forbidden
545 # at the backend level, so this is only UI sugar.
546 if (istranslation($form->field("page"))) {
548 for (my $i = 0; $i < @{$params{buttons}}; $i++) {
549 if (@{$params{buttons}}[$i] eq $_) {
550 delete @{$params{buttons}}[$i];
559 sub formbuilder (@) {
561 my $form=$params{form};
564 return unless defined $form->field("do");
566 # Do not allow to create pages of type po: they are automatically created.
567 # The main reason to do so is to bypass the "favor the type of linking page
568 # on page creation" logic, which is unsuitable when a broken link is clicked
569 # on a slave (PO) page.
570 # This cannot be done in the formbuilder_setup hook as the list of types is
572 if ($form->field("do") eq "create") {
573 foreach my $field ($form->field) {
574 next unless "$field" eq "type";
575 next unless $field->type eq 'select';
576 my $orig_value = $field->value;
577 # remove po from the list of types
578 my @types = grep { $_->[0] ne 'po' } $field->options;
579 $field->options(\@types) if @types;
580 # favor the type of linking page's masterpage
581 if ($orig_value eq 'po') {
583 if (defined $form->field('from')) {
584 ($from)=$form->field('from')=~/$config{wiki_file_regexp}/;
585 $from = masterpage($from);
587 if (defined $from && exists $pagesources{$from}) {
588 $type=pagetype($pagesources{$from});
590 $type=$config{default_pageext} unless defined $type;
591 $field->value($type) ;
598 # | Injected functions
601 # Implement po_link_to 'current' and 'negotiated' settings.
602 sub mybestlink ($$) {
606 return $origsubs{'bestlink'}->($page, $link)
607 if defined $config{po_link_to} && $config{po_link_to} eq "default";
609 my $res=$origsubs{'bestlink'}->(masterpage($page), $link);
610 my @caller = caller(1);
612 && istranslatedto($res, lang($page))
613 && istranslation($page)
614 && !(exists $caller[3] && defined $caller[3]
615 && ($caller[3] eq "IkiWiki::PageSpec::match_link"))) {
616 return $res . "." . lang($page);
621 sub mybeautify_urlpath ($) {
624 my $res=$origsubs{'beautify_urlpath'}->($url);
625 if (defined $config{po_link_to} && $config{po_link_to} eq "negotiated") {
626 $res =~ s!/\Qindex.$master_language_code.$config{htmlext}\E$!/!;
627 $res =~ s!/\Qindex.$config{htmlext}\E$!/!;
629 $res =~ s!/\Qindex.$_.$config{htmlext}\E$!/!;
635 sub mytargetpage ($$;$) {
640 if (istranslation($page) || istranslatable($page)) {
641 my ($masterpage, $lang) = (masterpage($page), lang($page));
642 if (defined $filename) {
643 return $masterpage . "/" . $filename . "." . $lang . "." . $ext;
645 elsif (! $config{usedirs} || $masterpage eq 'index') {
646 return $masterpage . "." . $lang . "." . $ext;
649 return $masterpage . "/index." . $lang . "." . $ext;
652 return $origsubs{'targetpage'}->($page, $ext, $filename);
660 # workaround hard-coded /index.$config{htmlext} in IkiWiki::urlto()
662 && $config{po_link_to} eq "current"
663 && istranslatable('index')) {
665 return IkiWiki::beautify_urlpath(IkiWiki::baseurl($from) . "index." . lang($from) . ".$config{htmlext}");
668 return $origsubs{'urlto'}->($to,$from,$absolute);
671 # avoid using our injected beautify_urlpath if run by cgi_editpage,
672 # so that one is redirected to the just-edited page rather than to the
673 # negociated translation; to prevent unnecessary fiddling with caller/inject,
674 # we only do so when our beautify_urlpath would actually do what we want to
675 # avoid, i.e. when po_link_to = negotiated.
676 # also avoid doing so when run by cgi_goto, so that the links on recentchanges
677 # page actually lead to the exact page they pretend to.
678 if ($config{po_link_to} eq "negotiated") {
679 my @caller = caller(1);
681 $use_orig = 1 if (exists $caller[3] && defined $caller[3]
682 && ($caller[3] eq "IkiWiki::cgi_editpage" ||
683 $caller[3] eq "IkiWiki::Plugin::goto::cgi_goto")
685 inject(name => "IkiWiki::beautify_urlpath", call => $origsubs{'beautify_urlpath'})
687 my $res = $origsubs{'urlto'}->($to,$from,$absolute);
688 inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath)
693 return $origsubs{'urlto'}->($to,$from,$absolute)
700 # slave pages have no subpages
701 if (istranslation($params{'from'})) {
702 $params{'from'} = masterpage($params{'from'});
704 return $origsubs{'cgiurl'}->(%params);
711 if (exists $params{rootpage}) {
712 $rootpage=$origsubs{'bestlink'}->($params{page}, $params{rootpage});
713 if (!length $rootpage) {
714 $rootpage=$params{rootpage};
718 $rootpage=masterpage($params{page});
723 sub myisselflink ($$) {
727 return 1 if $origsubs{'isselflink'}->($page, $link);
728 if (istranslation($page)) {
729 return $origsubs{'isselflink'}->(masterpage($page), $link);
735 # | Blackboxes for private data
741 sub alreadyfiltered($$) {
745 return exists $filtered{$page}{$destpage}
746 && $filtered{$page}{$destpage} eq 1;
749 sub setalreadyfiltered($$) {
753 $filtered{$page}{$destpage}=1;
756 sub unsetalreadyfiltered($$) {
760 if (exists $filtered{$page}{$destpage}) {
761 delete $filtered{$page}{$destpage};
765 sub resetalreadyfiltered() {
774 sub maybe_add_leading_slash ($;$) {
777 $add=1 unless defined $add;
778 return '/' . $str if $add;
782 sub istranslatablefile ($) {
785 return 0 unless defined $file;
786 my $type=pagetype($file);
787 return 0 if ! defined $type || $type eq 'po';
788 return 0 if $file =~ /\.pot$/;
789 return 0 if ! defined $config{po_translatable_pages};
790 return 1 if pagespec_match(pagename($file), $config{po_translatable_pages});
794 sub istranslatable ($) {
798 return 1 if istranslatablefile($pagesources{$page});
802 sub istranslatedto ($$) {
804 my $destlang = shift;
807 return 0 unless istranslatable($page);
808 exists $pagesources{otherlanguage_page($page, $destlang)};
811 sub _istranslation ($) {
814 $page='' unless defined $page && length $page;
815 my $hasleadingslash = ($page=~s#^/##);
816 my $file=$pagesources{$page};
817 return 0 unless defined $file
818 && defined pagetype($file)
819 && pagetype($file) eq 'po';
820 return 0 if $file =~ /\.pot$/;
822 my ($masterpage, $lang) = ($page =~ /(.*)[.]($language_code_pattern)$/);
823 return 0 unless defined $masterpage && defined $lang
824 && length $masterpage && length $lang
825 && defined $pagesources{$masterpage}
826 && defined $slavelanguages{$lang};
828 return (maybe_add_leading_slash($masterpage, $hasleadingslash), $lang)
829 if istranslatable($masterpage);
832 sub istranslation ($) {
835 if (1 < (my ($masterpage, $lang) = _istranslation($page))) {
836 my $hasleadingslash = ($masterpage=~s#^/##);
837 $translations{$masterpage}{$lang}=$page unless exists $translations{$masterpage}{$lang};
838 return (maybe_add_leading_slash($masterpage, $hasleadingslash), $lang);
846 if ( 1 < (my ($masterpage, $lang) = _istranslation($page))) {
855 if (1 < (my ($masterpage, $lang) = _istranslation($page))) {
858 return $master_language_code;
861 sub islanguagecode ($) {
864 return $code =~ /^$language_code_pattern$/;
867 sub otherlanguage_page ($$) {
871 return masterpage($page) if $code eq $master_language_code;
872 return masterpage($page) . '.' . $code;
875 # Returns the list of other languages codes: the master language comes first,
876 # then the codes are ordered the same way as in po_slave_languages, if it is
877 # an array, or in the language name lexical order, if it is a hash.
878 sub otherlanguages_codes ($) {
882 return \@ret unless istranslation($page) || istranslatable($page);
883 my $curlang=lang($page);
885 ($master_language_code, @slavelanguages) {
886 next if $lang eq $curlang;
887 if ($lang eq $master_language_code ||
888 istranslatedto(masterpage($page), $lang)) {
895 sub otherlanguages_pages ($) {
900 $ret{$_} = otherlanguage_page($page, $_)
901 } @{otherlanguages_codes($page)};
907 my $masterfile=shift;
909 (my $name, my $dir, my $suffix) = fileparse($masterfile, qr/\.[^.]*/);
910 $dir='' if $dir eq './';
911 return File::Spec->catpath('', $dir, $name . ".pot");
915 my $masterfile=shift;
918 (my $name, my $dir, my $suffix) = fileparse($masterfile, qr/\.[^.]*/);
919 $dir='' if $dir eq './';
920 return File::Spec->catpath('', $dir, $name . "." . $lang . ".po");
924 my $masterfile=shift;
926 return map pofile($masterfile, $_), @slavelanguages;
930 my $masterfile=shift;
932 my $potfile=potfile($masterfile);
933 my $doc=Locale::Po4a::Chooser::new(po4a_type($masterfile),
934 po4a_options($masterfile));
935 $doc->{TT}{utf_mode} = 1;
936 $doc->{TT}{file_in_charset} = 'UTF-8';
937 $doc->{TT}{file_out_charset} = 'UTF-8';
938 $doc->read($masterfile);
939 # let's cheat a bit to force porefs option to be passed to
940 # Locale::Po4a::Po; this is undocument use of internal
941 # Locale::Po4a::TransTractor's data, compulsory since this module
942 # prevents us from using the porefs option.
943 $doc->{TT}{po_out}=Locale::Po4a::Po->new({ 'porefs' => 'none' });
944 $doc->{TT}{po_out}->set_charset('UTF-8');
947 IkiWiki::prep_writefile(basename($potfile),dirname($potfile));
948 $doc->writepo($potfile);
951 sub refreshpofiles ($@) {
952 my $masterfile=shift;
955 my $potfile=potfile($masterfile);
957 error("po(refreshpofiles) ".sprintf(gettext("POT file (%s) does not exist"), $potfile));
960 foreach my $pofile (@pofiles) {
961 IkiWiki::prep_writefile(basename($pofile),dirname($pofile));
964 # If the po file exists in an underlay, copy it
966 my ($pobase)=$pofile=~/^\Q$config{srcdir}\E\/?(.*)$/;
967 foreach my $dir (@{$config{underlaydirs}}) {
968 if (-e "$dir/$pobase") {
969 File::Copy::syscopy("$dir/$pobase",$pofile)
970 or error("po(refreshpofiles) ".
971 sprintf(gettext("failed to copy underlay PO file to %s"),
978 system("msgmerge", "--previous", "-q", "-U", "--backup=none", $pofile, $potfile) == 0
979 or error("po(refreshpofiles) ".
980 sprintf(gettext("failed to update %s"),
984 File::Copy::syscopy($potfile,$pofile)
985 or error("po(refreshpofiles) ".
986 sprintf(gettext("failed to copy the POT file to %s"),
992 sub buildtranslationscache() {
993 # use istranslation's side-effect
994 map istranslation($_), (keys %pagesources);
997 sub resettranslationscache() {
1001 sub flushmemoizecache() {
1002 Memoize::flush_cache("istranslatable");
1003 Memoize::flush_cache("_istranslation");
1004 Memoize::flush_cache("percenttranslated");
1007 sub urlto_with_orig_beautiful_urlpath($$) {
1011 inject(name => "IkiWiki::beautify_urlpath", call => $origsubs{'beautify_urlpath'});
1012 my $res=urlto($to, $from);
1013 inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath);
1018 sub percenttranslated ($) {
1022 return gettext("N/A") unless istranslation($page);
1023 my $file=srcfile($pagesources{$page});
1024 my $masterfile = srcfile($pagesources{masterpage($page)});
1025 my $doc=Locale::Po4a::Chooser::new(po4a_type($masterfile),
1026 po4a_options($masterfile));
1028 'po_in_name' => [ $file ],
1029 'file_in_name' => [ $masterfile ],
1030 'file_in_charset' => 'UTF-8',
1031 'file_out_charset' => 'UTF-8',
1032 ) or error("po(percenttranslated) ".
1033 sprintf(gettext("failed to translate %s"), $page));
1034 my ($percent,$hit,$queries) = $doc->stats();
1035 $percent =~ s/\.[0-9]+$//;
1039 sub languagename ($) {
1042 return $master_language_name
1043 if $code eq $master_language_code;
1044 return $slavelanguages{$code}
1045 if defined $slavelanguages{$code};
1049 sub otherlanguagesloop ($) {
1053 if (istranslation($page)) {
1055 url => urlto_with_orig_beautiful_urlpath(masterpage($page), $page),
1056 code => $master_language_code,
1057 language => $master_language_name,
1061 foreach my $lang (@{otherlanguages_codes($page)}) {
1062 next if $lang eq $master_language_code;
1063 my $otherpage = otherlanguage_page($page, $lang);
1065 url => urlto_with_orig_beautiful_urlpath($otherpage, $page),
1067 language => languagename($lang),
1068 percent => percenttranslated($otherpage),
1074 sub homepageurl (;$) {
1077 return urlto('', $page);
1080 sub ishomepage ($) {
1083 return 1 if $page eq 'index';
1084 map { return 1 if $page eq 'index.'.$_ } @slavelanguages;
1088 sub deletetranslations ($) {
1089 my $deletedmasterfile=shift;
1091 my $deletedmasterpage=pagename($deletedmasterfile);
1094 my $file = newpagefile($deletedmasterpage.'.'.$_, 'po');
1095 my $absfile = "$config{srcdir}/$file";
1096 if (-e $absfile && ! -l $absfile && ! -d $absfile) {
1097 push @todelete, $file;
1103 IkiWiki::rcs_remove($_);
1106 IkiWiki::prune("$config{srcdir}/$_");
1112 gettext("removed obsolete PO files"));
1116 sub commit_and_refresh ($) {
1120 IkiWiki::disable_commit_hook();
1121 IkiWiki::rcs_commit_staged(
1124 IkiWiki::enable_commit_hook();
1125 IkiWiki::rcs_update();
1127 # Reinitialize module's private variables.
1128 resetalreadyfiltered();
1129 resettranslationscache();
1130 flushmemoizecache();
1131 # Trigger a wiki refresh.
1132 require IkiWiki::Render;
1133 # without preliminary saveindex/loadindex, refresh()
1134 # complains about a lot of uninitialized variables
1135 IkiWiki::saveindex();
1136 IkiWiki::loadindex();
1138 IkiWiki::saveindex();
1141 sub po_to_markup ($$) {
1142 my ($page, $content) = (shift, shift);
1144 $content = '' unless defined $content;
1145 $content = decode_utf8(encode_utf8($content));
1146 # CRLF line terminators make poor Locale::Po4a feel bad
1147 $content=~s/\r\n/\n/g;
1149 # There are incompatibilities between some File::Temp versions
1150 # (including 0.18, bundled with Lenny's perl-modules package)
1151 # and others (e.g. 0.20, previously present in the archive as
1152 # a standalone package): under certain circumstances, some
1153 # return a relative filename, whereas others return an absolute one;
1154 # we here use this module in a way that is at least compatible
1155 # with 0.18 and 0.20. Beware, hit'n'run refactorers!
1156 my $infile = new File::Temp(TEMPLATE => "ikiwiki-po-filter-in.XXXXXXXXXX",
1157 DIR => File::Spec->tmpdir,
1158 UNLINK => 1)->filename;
1159 my $outfile = new File::Temp(TEMPLATE => "ikiwiki-po-filter-out.XXXXXXXXXX",
1160 DIR => File::Spec->tmpdir,
1161 UNLINK => 1)->filename;
1163 my $fail = sub ($) {
1164 my $msg = "po(po_to_markup) - $page : " . shift;
1165 error($msg, sub { unlink $infile, $outfile});
1168 writefile(basename($infile), File::Spec->tmpdir, $content)
1169 or return $fail->(sprintf(gettext("failed to write %s"), $infile));
1171 my $masterfile = srcfile($pagesources{masterpage($page)});
1172 my $doc=Locale::Po4a::Chooser::new(po4a_type($masterfile),
1173 po4a_options($masterfile));
1175 'po_in_name' => [ $infile ],
1176 'file_in_name' => [ $masterfile ],
1177 'file_in_charset' => 'UTF-8',
1178 'file_out_charset' => 'UTF-8',
1179 ) or return $fail->(gettext("failed to translate"));
1180 $doc->write($outfile)
1181 or return $fail->(sprintf(gettext("failed to write %s"), $outfile));
1183 $content = readfile($outfile);
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.
1188 unlink $infile, $outfile;
1193 # returns a SuccessReason or FailReason object
1195 my $content = shift;
1197 # NB: we don't use po_to_markup here, since Po4a parser does
1198 # not mind invalid PO content
1199 $content = '' unless defined $content;
1200 $content = decode_utf8(encode_utf8($content));
1202 # There are incompatibilities between some File::Temp versions
1203 # (including 0.18, bundled with Lenny's perl-modules package)
1204 # and others (e.g. 0.20, previously present in the archive as
1205 # a standalone package): under certain circumstances, some
1206 # return a relative filename, whereas others return an absolute one;
1207 # we here use this module in a way that is at least compatible
1208 # with 0.18 and 0.20. Beware, hit'n'run refactorers!
1209 my $infile = new File::Temp(TEMPLATE => "ikiwiki-po-isvalidpo.XXXXXXXXXX",
1210 DIR => File::Spec->tmpdir,
1211 UNLINK => 1)->filename;
1213 my $fail = sub ($) {
1214 my $msg = '[po/isvalidpo] ' . shift;
1216 return IkiWiki::FailReason->new("$msg");
1219 writefile(basename($infile), File::Spec->tmpdir, $content)
1220 or return $fail->(sprintf(gettext("failed to write %s"), $infile));
1222 my $res = (system("msgfmt", "--check", $infile, "-o", "/dev/null") == 0);
1224 # Unlinking should happen automatically, thanks to File::Temp,
1225 # but it does not work here, probably because of the way writefile()
1226 # and Locale::Po4a::write() work.
1230 return IkiWiki::SuccessReason->new("valid gettext data");
1232 return IkiWiki::FailReason->new(gettext("invalid gettext data, go back ".
1233 "to previous page to continue edit"));
1239 my $pagetype = pagetype($file);
1240 if ($pagetype eq 'html') {
1246 sub po4a_options($) {
1250 my $pagetype = pagetype($file);
1252 if ($pagetype eq 'html') {
1253 # how to disable options is not consistent across po4a modules
1254 $options{includessi} = '';
1255 $options{includeexternal} = 0;
1256 $options{ontagerror} = 'warn';
1258 elsif ($pagetype eq 'mdwn') {
1259 $options{markdown} = 1;
1262 $options{markdown} = 0;
1268 sub splitlangpair ($) {
1271 my ($code, $name) = ( $pair =~ /^($language_code_pattern)\|(.+)$/ );
1272 if (! defined $code || ! defined $name ||
1273 ! length $code || ! length $name) {
1274 # not a fatal error to avoid breaking if used with web setup
1275 warn sprintf(gettext("%s has invalid syntax: must use CODE|NAME"),
1279 return $code, $name;
1282 sub joinlangpair ($$) {
1286 return "$code|$name";
1293 package IkiWiki::PageSpec;
1295 sub match_istranslation ($;@) {
1298 if (IkiWiki::Plugin::po::istranslation($page)) {
1299 return IkiWiki::SuccessReason->new("is a translation page");
1302 return IkiWiki::FailReason->new("is not a translation page");
1306 sub match_istranslatable ($;@) {
1309 if (IkiWiki::Plugin::po::istranslatable($page)) {
1310 return IkiWiki::SuccessReason->new("is set as translatable in po_translatable_pages");
1313 return IkiWiki::FailReason->new("is not set as translatable in po_translatable_pages");
1317 sub match_lang ($$;@) {
1321 my $regexp=IkiWiki::glob2re($wanted);
1322 my $lang=IkiWiki::Plugin::po::lang($page);
1323 if ($lang !~ $regexp) {
1324 return IkiWiki::FailReason->new("file language is $lang, not $wanted");
1327 return IkiWiki::SuccessReason->new("file language is $wanted");
1331 sub match_currentlang ($$;@) {
1336 return IkiWiki::FailReason->new("no location provided") unless exists $params{location};
1338 my $currentlang=IkiWiki::Plugin::po::lang($params{location});
1339 my $lang=IkiWiki::Plugin::po::lang($page);
1341 if ($lang eq $currentlang) {
1342 return IkiWiki::SuccessReason->new("file language is the same as current one, i.e. $currentlang");
1345 return IkiWiki::FailReason->new("file language is $lang, whereas current language is $currentlang");
1349 sub match_needstranslation ($$;@) {
1353 if (defined $wanted && $wanted ne "") {
1354 if ($wanted !~ /^\d+$/) {
1355 return IkiWiki::FailReason->new("parameter is not an integer");
1357 elsif ($wanted > 100) {
1358 return IkiWiki::FailReason->new("parameter is greater than 100");
1365 my $percenttranslated=IkiWiki::Plugin::po::percenttranslated($page);
1366 if ($percenttranslated eq 'N/A') {
1367 return IkiWiki::FailReason->new("file is not a translatable page");
1369 elsif ($percenttranslated < $wanted) {
1370 return IkiWiki::SuccessReason->new("file has $percenttranslated translated");
1373 return IkiWiki::FailReason->new("file is translated enough");