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;
27 my ($master_language_code, $master_language_name);
31 my @slavelanguages; # language codes ordered as in config po_slave_languages
32 my %slavelanguages; # language code to name lookup
33 my $language_code_pattern = '[a-zA-Z]+(?:_[a-zA-Z]+)?';
35 memoize("istranslatable");
36 memoize("_istranslation");
37 memoize("percenttranslated");
40 hook(type => "getsetup", id => "po", call => \&getsetup);
41 hook(type => "checkconfig", id => "po", call => \&checkconfig,
43 hook(type => "needsbuild", id => "po", call => \&needsbuild);
44 hook(type => "scan", id => "po", call => \&scan, last => 1);
45 hook(type => "filter", id => "po", call => \&filter);
46 hook(type => "htmlize", id => "po", call => \&htmlize);
47 hook(type => "pagetemplate", id => "po", call => \&pagetemplate, last => 1);
48 hook(type => "rename", id => "po", call => \&renamepages, first => 1);
49 hook(type => "delete", id => "po", call => \&mydelete);
50 hook(type => "rendered", id => "po", call => \&rendered);
51 hook(type => "checkcontent", id => "po", call => \&checkcontent);
52 hook(type => "canremove", id => "po", call => \&canremove);
53 hook(type => "canrename", id => "po", call => \&canrename);
54 hook(type => "editcontent", id => "po", call => \&editcontent);
55 hook(type => "formbuilder_setup", id => "po", call => \&formbuilder_setup, last => 1);
56 hook(type => "formbuilder", id => "po", call => \&formbuilder);
59 $origsubs{'bestlink'}=\&IkiWiki::bestlink;
60 inject(name => "IkiWiki::bestlink", call => \&mybestlink);
61 $origsubs{'beautify_urlpath'}=\&IkiWiki::beautify_urlpath;
62 inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath);
63 $origsubs{'targetpage'}=\&IkiWiki::targetpage;
64 inject(name => "IkiWiki::targetpage", call => \&mytargetpage);
65 $origsubs{'urlto'}=\&IkiWiki::urlto;
66 inject(name => "IkiWiki::urlto", call => \&myurlto);
67 $origsubs{'cgiurl'}=\&IkiWiki::cgiurl;
68 inject(name => "IkiWiki::cgiurl", call => \&mycgiurl);
69 if (IkiWiki->can('rootpage')) {
70 $origsubs{'rootpage'}=\&IkiWiki::rootpage;
71 inject(name => "IkiWiki::rootpage", call => \&myrootpage)
72 if defined $origsubs{'rootpage'};
74 $origsubs{'isselflink'}=\&IkiWiki::isselflink;
75 inject(name => "IkiWiki::isselflink", call => \&myisselflink);
85 # 2. Injected functions
86 # 3. Blackboxes for private data
99 rebuild => 1, # format plugin
102 po_master_language => {
104 example => "en|English",
105 description => "master language (non-PO files)",
109 po_slave_languages => {
116 description => "slave languages (translated via PO files) format: ll|Langname",
120 po_translatable_pages => {
122 example => "* and !*/Discussion",
123 description => "PageSpec controlling which pages are translatable",
124 link => "ikiwiki/PageSpec",
130 example => "current",
131 description => "internal linking behavior (default/current/negotiated)",
138 if (exists $config{po_master_language}) {
139 if (! ref $config{po_master_language}) {
140 ($master_language_code, $master_language_name)=
141 splitlangpair($config{po_master_language});
144 $master_language_code=$config{po_master_language}{code};
145 $master_language_name=$config{po_master_language}{name};
146 $config{po_master_language}=joinlangpair($master_language_code, $master_language_name);
149 if (! defined $master_language_code) {
150 $master_language_code='en';
152 if (! defined $master_language_name) {
153 $master_language_name='English';
156 if (ref $config{po_slave_languages} eq 'ARRAY') {
157 foreach my $pair (@{$config{po_slave_languages}}) {
158 my ($code, $name)=splitlangpair($pair);
159 if (defined $code && ! exists $slavelanguages{$code}) {
160 push @slavelanguages, $code;
161 $slavelanguages{$code} = $name;
165 elsif (ref $config{po_slave_languages} eq 'HASH') {
166 %slavelanguages=%{$config{po_slave_languages}};
167 @slavelanguages = sort {
168 $config{po_slave_languages}->{$a} cmp $config{po_slave_languages}->{$b};
169 } keys %slavelanguages;
170 $config{po_slave_languages}=[
171 map { joinlangpair($_, $slavelanguages{$_}) } @slavelanguages
175 delete $slavelanguages{$master_language_code};
179 or error(sprintf(gettext("%s is not a valid language code"), $_));
180 } ($master_language_code, @slavelanguages);
182 if (! exists $config{po_translatable_pages} ||
183 ! defined $config{po_translatable_pages}) {
184 $config{po_translatable_pages}="";
186 if (! exists $config{po_link_to} ||
187 ! defined $config{po_link_to}) {
188 $config{po_link_to}='default';
190 elsif ($config{po_link_to} !~ /^(default|current|negotiated)$/) {
191 warn(sprintf(gettext('%s is not a valid value for po_link_to, falling back to po_link_to=default'),
192 $config{po_link_to}));
193 $config{po_link_to}='default';
195 elsif ($config{po_link_to} eq "negotiated" && ! $config{usedirs}) {
196 warn(gettext('po_link_to=negotiated requires usedirs to be enabled, falling back to po_link_to=default'));
197 $config{po_link_to}='default';
200 push @{$config{wiki_file_prune_regexps}}, qr/\.pot$/;
202 # Translated versions of the underlays are added if available.
203 foreach my $underlay ("basewiki",
204 map { m/^\Q$config{underlaydirbase}\E\/*(.*)/ }
205 reverse @{$config{underlaydirs}}) {
206 next if $underlay=~/^locale\//;
208 # Underlays containing the po files for slave languages.
209 foreach my $ll (@slavelanguages) {
210 add_underlay("po/$ll/$underlay")
211 if -d "$config{underlaydirbase}/po/$ll/$underlay";
214 if ($master_language_code ne 'en') {
215 # Add underlay containing translated source files
216 # for the master language.
217 add_underlay("locale/$master_language_code/$underlay")
218 if -d "$config{underlaydirbase}/locale/$master_language_code/$underlay";
224 my $needsbuild=shift;
226 # backup @needsbuild content so that change() can know whether
227 # a given master page was rendered because its source file was changed
228 @origneedsbuild=(@$needsbuild);
231 buildtranslationscache();
233 # make existing translations depend on the corresponding master page
234 foreach my $master (keys %translations) {
235 map add_depends($_, $master), values %{otherlanguages_pages($master)};
243 my $page=$params{page};
244 my $content=$params{content};
245 my $run_by_po=$params{run_by_po};
247 # Massage the recorded state of internal links so that:
248 # - it matches the actually generated links, rather than the links as
249 # written in the pages' source
250 # - backlinks are consistent in all cases
252 # A second scan pass is made over translation pages, so as an
253 # optimization, we only do so on the second pass in this case,
254 # i.e. when this hook is called by itself.
255 if ($run_by_po && istranslation($page)) {
256 # replace the occurence of $destpage in $links{$page}
257 my @orig_links = @{$links{$page}};
259 foreach my $destpage (@orig_links) {
260 if (istranslatedto($destpage, lang($page))) {
261 add_link($page, $destpage . '.' . lang($page));
264 add_link($page, $destpage);
268 # No second scan pass is done for a non-translation page, so
269 # links massaging must happen on first pass in this case.
270 elsif (! $run_by_po && ! istranslatable($page) && ! istranslation($page)) {
271 foreach my $destpage (@{$links{$page}}) {
272 if (istranslatable($destpage)) {
273 # make sure any destpage's translations has
274 # $page in its backlinks
275 foreach my $link (values %{otherlanguages_pages($destpage)}) {
276 add_link($page, $link);
282 # Re-run the preprocess hooks in scan mode, then the scan hooks,
283 # over the po-to-markup converted content
284 return if $run_by_po; # avoid looping endlessly
285 return unless istranslation($page);
286 $content = po_to_markup($page, $content);
288 IkiWiki::preprocess($page, $page, $content, 1);
289 IkiWiki::run_hooks(scan => sub {
298 # We use filter to convert PO to the master page's format,
299 # since the rest of ikiwiki should not work on PO files.
303 my $page = $params{page};
304 my $destpage = $params{destpage};
305 my $content = $params{content};
306 if (istranslation($page) && ! alreadyfiltered($page, $destpage)) {
307 $content = po_to_markup($page, $content);
308 setalreadyfiltered($page, $destpage);
316 my $page = $params{page};
317 my $content = $params{content};
319 # ignore PO files this plugin did not create
320 return $content unless istranslation($page);
322 # force content to be htmlize'd as if it was the same type as the master page
323 return IkiWiki::htmlize($page, $page,
324 pagetype(srcfile($pagesources{masterpage($page)})),
328 sub pagetemplate (@) {
330 my $page=$params{page};
331 my $destpage=$params{destpage};
332 my $template=$params{template};
334 my ($masterpage, $lang) = istranslation($page);
336 if (istranslation($page) && $template->query(name => "percenttranslated")) {
337 $template->param(percenttranslated => percenttranslated($page));
339 if ($template->query(name => "istranslation")) {
340 $template->param(istranslation => scalar istranslation($page));
342 if ($template->query(name => "istranslatable")) {
343 $template->param(istranslatable => istranslatable($page));
345 my $lang_code = istranslation($page) ? lang($page) : $master_language_code;
346 if ($template->query(name => "lang_code")) {
347 $template->param(lang_code => $lang_code);
349 if ($template->query(name => "html_lang_code")) {
350 $template->param(html_lang_code => htmllangcode($lang_code));
352 if ($template->query(name => "html_lang_dir")) {
353 $template->param(html_lang_dir => htmllangdir($lang_code));
355 if ($template->query(name => "lang_name")) {
356 $template->param(lang_name => languagename($lang_code));
358 if ($template->query(name => "HOMEPAGEURL")) {
359 $template->param(homepageurl => homepageurl($page));
361 if ($template->query(name => "otherlanguages")) {
362 $template->param(otherlanguages => [otherlanguagesloop($page)]);
363 map add_depends($page, $_), (values %{otherlanguages_pages($page)});
365 if ($config{discussion} && istranslation($page)) {
366 if ($page !~ /.*\/\Q$config{discussionpage}\E$/i &&
367 (length $config{cgiurl} ||
368 exists $links{$masterpage."/".lc($config{discussionpage})})) {
369 $template->param('discussionlink' => htmllink(
372 $masterpage . '/' . $config{discussionpage},
375 linktext => $config{discussionpage},
379 # Remove broken parentlink to ./index.html on home page's translations.
380 # It works because this hook has the "last" parameter set, to ensure it
381 # runs after parentlinks' own pagetemplate hook.
382 if ($template->param('parentlinks')
383 && istranslation($page)
384 && $masterpage eq "index") {
385 $template->param('parentlinks' => []);
387 if (ishomepage($page) && $template->query(name => "title")
388 && !$template->param("title_overridden")) {
389 $template->param(title => $config{wikiname});
393 # Add the renamed page translations to the list of to-be-renamed pages.
394 sub renamepages (@) {
397 my %torename = %{$params{torename}};
398 my $session = $params{session};
400 # Save the page(s) the user asked to rename, so that our
401 # canrename hook can tell the difference between:
402 # - a translation being renamed as a consequence of its master page
404 # - a user trying to directly rename a translation
405 # This is why this hook has to be run first, before the list of pages
406 # to rename is modified by other plugins.
408 @orig_torename=@{$session->param("po_orig_torename")}
409 if defined $session->param("po_orig_torename");
410 push @orig_torename, $torename{src};
411 $session->param(po_orig_torename => \@orig_torename);
412 IkiWiki::cgi_savesession($session);
414 return () unless istranslatable($torename{src});
417 my %otherpages=%{otherlanguages_pages($torename{src})};
418 while (my ($lang, $otherpage) = each %otherpages) {
421 srcfile => $pagesources{$otherpage},
422 dest => otherlanguage_page($torename{dest}, $lang),
423 destfile => $torename{dest}.".".$lang.".po",
433 map { deletetranslations($_) } grep istranslatablefile($_), @deleted;
439 my $updated_po_files=0;
441 # Refresh/create POT and PO files as needed.
442 foreach my $file (grep {istranslatablefile($_)} @rendered) {
443 my $masterfile=srcfile($file);
444 my $page=pagename($file);
445 my $updated_pot_file=0;
447 # Avoid touching underlay files.
448 next if $masterfile ne "$config{srcdir}/$file";
450 # Only refresh POT file if it does not exist, or if
451 # the source was changed: don't if only the HTML was
452 # refreshed, e.g. because of a dependency.
453 if ((grep { $_ eq $pagesources{$page} } @origneedsbuild) ||
454 ! -e potfile($masterfile)) {
455 refreshpot($masterfile);
459 foreach my $po (pofiles($masterfile)) {
460 next if ! $updated_pot_file && -e $po;
461 next if grep { $po=~/\Q$_\E/ } @{$config{underlaydirs}};
465 refreshpofiles($masterfile, @pofiles);
466 map { s/^\Q$config{srcdir}\E\/*//; IkiWiki::rcs_add($_) } @pofiles if $config{rcs};
471 if ($updated_po_files) {
473 gettext("updated PO files"));
477 sub checkcontent (@) {
480 if (istranslation($params{page})) {
481 my $res = isvalidpo($params{content});
495 if (istranslation($params{page})) {
496 return gettext("Can not remove a translation. If the master page is removed, ".
497 "however, its translations will be removed as well.");
504 my $session = $params{session};
506 if (istranslation($params{src})) {
507 my $masterpage = masterpage($params{src});
508 # Tell the difference between:
509 # - a translation being renamed as a consequence of its master page
510 # being renamed, which is allowed
511 # - a user trying to directly rename a translation, which is forbidden
512 # by looking for the master page in the list of to-be-renamed pages we
513 # saved early in the renaming process.
514 my $orig_torename = $session->param("po_orig_torename");
515 unless (grep { $_ eq $masterpage } @{$orig_torename}) {
516 return gettext("Can not rename a translation. If the master page is renamed, ".
517 "however, its translations will be renamed as well.");
523 # As we're previewing or saving a page, the content may have
524 # changed, so tell the next filter() invocation it must not be lazy.
528 unsetalreadyfiltered($params{page}, $params{page});
529 return $params{content};
532 sub formbuilder_setup (@) {
534 my $form=$params{form};
537 return unless defined $form->field("do");
539 if ($form->field("do") eq "create") {
540 # Warn the user: new pages must be written in master language.
541 my $template=template("pocreatepage.tmpl");
542 $template->param(LANG => $master_language_name);
543 $form->tmpl_param(message => $template->output);
545 elsif ($form->field("do") eq "edit") {
546 # Remove the rename/remove buttons on slave pages.
547 # This has to be done after the rename/remove plugins have added
548 # their buttons, which is why this hook must be run last.
549 # The canrename/canremove hooks already ensure this is forbidden
550 # at the backend level, so this is only UI sugar.
551 if (istranslation($form->field("page"))) {
553 for (my $i = 0; $i < @{$params{buttons}}; $i++) {
554 if (@{$params{buttons}}[$i] eq $_) {
555 delete @{$params{buttons}}[$i];
564 sub formbuilder (@) {
566 my $form=$params{form};
569 return unless defined $form->field("do");
571 # Do not allow to create pages of type po: they are automatically created.
572 # The main reason to do so is to bypass the "favor the type of linking page
573 # on page creation" logic, which is unsuitable when a broken link is clicked
574 # on a slave (PO) page.
575 # This cannot be done in the formbuilder_setup hook as the list of types is
577 if ($form->field("do") eq "create") {
578 foreach my $field ($form->field) {
579 next unless "$field" eq "type";
580 next unless $field->type eq 'select';
581 my $orig_value = $field->value;
582 # remove po from the list of types
583 my @types = grep { $_->[0] ne 'po' } $field->options;
584 $field->options(\@types) if @types;
585 # favor the type of linking page's masterpage
586 if ($orig_value eq 'po') {
588 if (defined $form->field('from')) {
589 ($from)=$form->field('from')=~/$config{wiki_file_regexp}/;
590 $from = masterpage($from);
592 if (defined $from && exists $pagesources{$from}) {
593 $type=pagetype($pagesources{$from});
595 $type=$config{default_pageext} unless defined $type;
596 $field->value($type) ;
603 # | Injected functions
606 # Implement po_link_to 'current' and 'negotiated' settings.
607 sub mybestlink ($$) {
611 return $origsubs{'bestlink'}->($page, $link)
612 if defined $config{po_link_to} && $config{po_link_to} eq "default";
614 my $res=$origsubs{'bestlink'}->(masterpage($page), $link);
615 my @caller = caller(1);
617 && istranslatedto($res, lang($page))
618 && istranslation($page)
619 && !(exists $caller[3] && defined $caller[3]
620 && ($caller[3] eq "IkiWiki::PageSpec::match_link"))) {
621 return $res . "." . lang($page);
626 sub mybeautify_urlpath ($) {
629 my $res=$origsubs{'beautify_urlpath'}->($url);
630 if (defined $config{po_link_to} && $config{po_link_to} eq "negotiated") {
631 $res =~ s!/\Qindex.$master_language_code.$config{htmlext}\E$!/!;
632 $res =~ s!/\Qindex.$config{htmlext}\E$!/!;
634 $res =~ s!/\Qindex.$_.$config{htmlext}\E$!/!;
640 sub mytargetpage ($$;$) {
645 if (istranslation($page) || istranslatable($page)) {
646 my ($masterpage, $lang) = (masterpage($page), lang($page));
647 if (defined $filename) {
648 return $masterpage . "/" . $filename . "." . $lang . "." . $ext;
650 elsif (! $config{usedirs} || $masterpage eq 'index') {
651 return $masterpage . "." . $lang . "." . $ext;
654 return $masterpage . "/index." . $lang . "." . $ext;
657 return $origsubs{'targetpage'}->($page, $ext, $filename);
665 # workaround hard-coded /index.$config{htmlext} in IkiWiki::urlto()
667 && $config{po_link_to} eq "current"
668 && istranslatable('index')) {
670 return IkiWiki::beautify_urlpath(IkiWiki::baseurl($from) . "index." . lang($from) . ".$config{htmlext}");
673 return $origsubs{'urlto'}->($to,$from,$absolute);
676 # avoid using our injected beautify_urlpath if run by cgi_editpage,
677 # so that one is redirected to the just-edited page rather than to the
678 # negociated translation; to prevent unnecessary fiddling with caller/inject,
679 # we only do so when our beautify_urlpath would actually do what we want to
680 # avoid, i.e. when po_link_to = negotiated.
681 # also avoid doing so when run by cgi_goto, so that the links on recentchanges
682 # page actually lead to the exact page they pretend to.
683 if ($config{po_link_to} eq "negotiated") {
684 my @caller = caller(1);
686 $use_orig = 1 if (exists $caller[3] && defined $caller[3]
687 && ($caller[3] eq "IkiWiki::cgi_editpage" ||
688 $caller[3] eq "IkiWiki::Plugin::goto::cgi_goto")
690 inject(name => "IkiWiki::beautify_urlpath", call => $origsubs{'beautify_urlpath'})
692 my $res = $origsubs{'urlto'}->($to,$from,$absolute);
693 inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath)
698 return $origsubs{'urlto'}->($to,$from,$absolute)
705 # slave pages have no subpages
706 if (istranslation($params{'from'})) {
707 $params{'from'} = masterpage($params{'from'});
709 return $origsubs{'cgiurl'}->(%params);
716 if (exists $params{rootpage}) {
717 $rootpage=$origsubs{'bestlink'}->($params{page}, $params{rootpage});
718 if (!length $rootpage) {
719 $rootpage=$params{rootpage};
723 $rootpage=masterpage($params{page});
728 sub myisselflink ($$) {
732 return 1 if $origsubs{'isselflink'}->($page, $link);
733 if (istranslation($page)) {
734 return $origsubs{'isselflink'}->(masterpage($page), $link);
740 # | Blackboxes for private data
746 sub alreadyfiltered($$) {
750 return exists $filtered{$page}{$destpage}
751 && $filtered{$page}{$destpage} eq 1;
754 sub setalreadyfiltered($$) {
758 $filtered{$page}{$destpage}=1;
761 sub unsetalreadyfiltered($$) {
765 if (exists $filtered{$page}{$destpage}) {
766 delete $filtered{$page}{$destpage};
770 sub resetalreadyfiltered() {
779 sub maybe_add_leading_slash ($;$) {
782 $add=1 unless defined $add;
783 return '/' . $str if $add;
787 sub istranslatablefile ($) {
790 return 0 unless defined $file;
791 my $type=pagetype($file);
792 return 0 if ! defined $type || $type eq 'po';
793 return 0 if $file =~ /\.pot$/;
794 return 0 if ! defined $config{po_translatable_pages};
795 return 1 if pagespec_match(pagename($file), $config{po_translatable_pages});
799 sub istranslatable ($) {
803 return 1 if istranslatablefile($pagesources{$page});
807 sub istranslatedto ($$) {
809 my $destlang = shift;
812 return 0 unless istranslatable($page);
813 exists $pagesources{otherlanguage_page($page, $destlang)};
816 sub _istranslation ($) {
819 $page='' unless defined $page && length $page;
820 my $hasleadingslash = ($page=~s#^/##);
821 my $file=$pagesources{$page};
822 return 0 unless defined $file
823 && defined pagetype($file)
824 && pagetype($file) eq 'po';
825 return 0 if $file =~ /\.pot$/;
827 my ($masterpage, $lang) = ($page =~ /(.*)[.]($language_code_pattern)$/);
828 return 0 unless defined $masterpage && defined $lang
829 && length $masterpage && length $lang
830 && defined $pagesources{$masterpage}
831 && defined $slavelanguages{$lang};
833 return (maybe_add_leading_slash($masterpage, $hasleadingslash), $lang)
834 if istranslatable($masterpage);
837 sub istranslation ($) {
840 if (1 < (my ($masterpage, $lang) = _istranslation($page))) {
841 my $hasleadingslash = ($masterpage=~s#^/##);
842 $translations{$masterpage}{$lang}=$page unless exists $translations{$masterpage}{$lang};
843 return (maybe_add_leading_slash($masterpage, $hasleadingslash), $lang);
851 if ( 1 < (my ($masterpage, $lang) = _istranslation($page))) {
860 if (1 < (my ($masterpage, $lang) = _istranslation($page))) {
863 return $master_language_code;
866 sub htmllangcode ($) {
867 (my $lang = shift) =~ tr/_/-/;
871 sub htmllangdir ($) {
873 if ($lang =~ /^(ar|fa|he)/) {
879 sub islanguagecode ($) {
882 return $code =~ /^$language_code_pattern$/;
885 sub otherlanguage_page ($$) {
889 return masterpage($page) if $code eq $master_language_code;
890 return masterpage($page) . '.' . $code;
893 # Returns the list of other languages codes: the master language comes first,
894 # then the codes are ordered the same way as in po_slave_languages, if it is
895 # an array, or in the language name lexical order, if it is a hash.
896 sub otherlanguages_codes ($) {
900 return \@ret unless istranslation($page) || istranslatable($page);
901 my $curlang=lang($page);
903 ($master_language_code, @slavelanguages) {
904 next if $lang eq $curlang;
905 if ($lang eq $master_language_code ||
906 istranslatedto(masterpage($page), $lang)) {
913 sub otherlanguages_pages ($) {
918 $ret{$_} = otherlanguage_page($page, $_)
919 } @{otherlanguages_codes($page)};
925 my $masterfile=shift;
927 (my $name, my $dir, my $suffix) = fileparse($masterfile, qr/\.[^.]*/);
928 $dir='' if $dir eq './';
929 return File::Spec->catpath('', $dir, $name . ".pot");
933 my $masterfile=shift;
936 (my $name, my $dir, my $suffix) = fileparse($masterfile, qr/\.[^.]*/);
937 $dir='' if $dir eq './';
938 return File::Spec->catpath('', $dir, $name . "." . $lang . ".po");
942 my $masterfile=shift;
944 return map pofile($masterfile, $_), @slavelanguages;
948 my $masterfile=shift;
950 my $potfile=potfile($masterfile);
951 my $doc=Locale::Po4a::Chooser::new(po4a_type($masterfile),
952 po4a_options($masterfile));
953 $doc->{TT}{utf_mode} = 1;
954 $doc->{TT}{file_in_charset} = 'UTF-8';
955 $doc->{TT}{file_out_charset} = 'UTF-8';
956 $doc->read($masterfile);
957 # let's cheat a bit to force porefs option to be passed to
958 # Locale::Po4a::Po; this is undocument use of internal
959 # Locale::Po4a::TransTractor's data, compulsory since this module
960 # prevents us from using the porefs option.
961 $doc->{TT}{po_out}=Locale::Po4a::Po->new({ 'porefs' => 'none' });
962 $doc->{TT}{po_out}->set_charset('UTF-8');
965 IkiWiki::prep_writefile(basename($potfile),dirname($potfile));
966 $doc->writepo($potfile);
969 sub refreshpofiles ($@) {
970 my $masterfile=shift;
973 my $potfile=potfile($masterfile);
975 error("po(refreshpofiles) ".sprintf(gettext("POT file (%s) does not exist"), $potfile));
978 foreach my $pofile (@pofiles) {
979 IkiWiki::prep_writefile(basename($pofile),dirname($pofile));
982 # If the po file exists in an underlay, copy it
984 my ($pobase)=$pofile=~/^\Q$config{srcdir}\E\/?(.*)$/;
985 foreach my $dir (@{$config{underlaydirs}}) {
986 if (-e "$dir/$pobase") {
987 File::Copy::syscopy("$dir/$pobase",$pofile)
988 or error("po(refreshpofiles) ".
989 sprintf(gettext("failed to copy underlay PO file to %s"),
996 system("msgmerge", "--previous", "-q", "-U", "--backup=none", $pofile, $potfile) == 0
997 or error("po(refreshpofiles) ".
998 sprintf(gettext("failed to update %s"),
1002 File::Copy::syscopy($potfile,$pofile)
1003 or error("po(refreshpofiles) ".
1004 sprintf(gettext("failed to copy the POT file to %s"),
1010 sub buildtranslationscache() {
1011 # use istranslation's side-effect
1012 map istranslation($_), (keys %pagesources);
1015 sub resettranslationscache() {
1016 undef %translations;
1019 sub flushmemoizecache() {
1020 Memoize::flush_cache("istranslatable");
1021 Memoize::flush_cache("_istranslation");
1022 Memoize::flush_cache("percenttranslated");
1025 sub urlto_with_orig_beautiful_urlpath($$) {
1029 inject(name => "IkiWiki::beautify_urlpath", call => $origsubs{'beautify_urlpath'});
1030 my $res=urlto($to, $from);
1031 inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath);
1036 sub percenttranslated ($) {
1040 return gettext("N/A") unless istranslation($page);
1041 my $file=srcfile($pagesources{$page});
1042 my $masterfile = srcfile($pagesources{masterpage($page)});
1043 my $doc=Locale::Po4a::Chooser::new(po4a_type($masterfile),
1044 po4a_options($masterfile));
1046 'po_in_name' => [ $file ],
1047 'file_in_name' => [ $masterfile ],
1048 'file_in_charset' => 'UTF-8',
1049 'file_out_charset' => 'UTF-8',
1050 ) or error("po(percenttranslated) ".
1051 sprintf(gettext("failed to translate %s"), $page));
1052 my ($percent,$hit,$queries) = $doc->stats();
1053 $percent =~ s/\.[0-9]+$//;
1057 sub languagename ($) {
1060 return $master_language_name
1061 if $code eq $master_language_code;
1062 return $slavelanguages{$code}
1063 if defined $slavelanguages{$code};
1067 sub otherlanguagesloop ($) {
1071 if (istranslation($page)) {
1073 url => urlto_with_orig_beautiful_urlpath(masterpage($page), $page),
1074 code => $master_language_code,
1075 html_code => htmllangcode($master_language_code),
1076 html_dir => htmllangdir($master_language_code),
1077 language => $master_language_name,
1081 foreach my $lang (@{otherlanguages_codes($page)}) {
1082 next if $lang eq $master_language_code;
1083 my $otherpage = otherlanguage_page($page, $lang);
1085 url => urlto_with_orig_beautiful_urlpath($otherpage, $page),
1087 html_code => htmllangcode($lang),
1088 html_dir => htmllangdir($lang),
1089 language => languagename($lang),
1090 percent => percenttranslated($otherpage),
1096 sub homepageurl (;$) {
1099 return urlto('', $page);
1102 sub ishomepage ($) {
1105 return 1 if $page eq 'index';
1106 map { return 1 if $page eq 'index.'.$_ } @slavelanguages;
1110 sub deletetranslations ($) {
1111 my $deletedmasterfile=shift;
1113 my $deletedmasterpage=pagename($deletedmasterfile);
1116 my $file = newpagefile($deletedmasterpage.'.'.$_, 'po');
1117 my $absfile = "$config{srcdir}/$file";
1118 if (-e $absfile && ! -l $absfile && ! -d $absfile) {
1119 push @todelete, $file;
1125 IkiWiki::rcs_remove($_);
1128 IkiWiki::prune("$config{srcdir}/$_", $config{srcdir});
1134 gettext("removed obsolete PO files"));
1138 sub commit_and_refresh ($) {
1142 IkiWiki::disable_commit_hook();
1143 IkiWiki::rcs_commit_staged(
1146 IkiWiki::enable_commit_hook();
1147 IkiWiki::rcs_update();
1149 # Reinitialize module's private variables.
1150 resetalreadyfiltered();
1151 resettranslationscache();
1152 flushmemoizecache();
1153 # Trigger a wiki refresh.
1154 require IkiWiki::Render;
1155 # without preliminary saveindex/loadindex, refresh()
1156 # complains about a lot of uninitialized variables
1157 IkiWiki::saveindex();
1158 IkiWiki::loadindex();
1160 IkiWiki::saveindex();
1163 sub po_to_markup ($$) {
1164 my ($page, $content) = (shift, shift);
1166 $content = '' unless defined $content;
1167 $content = decode_utf8(encode_utf8($content));
1168 # CRLF line terminators make poor Locale::Po4a feel bad
1169 $content=~s/\r\n/\n/g;
1171 # There are incompatibilities between some File::Temp versions
1172 # (including 0.18, bundled with Lenny's perl-modules package)
1173 # and others (e.g. 0.20, previously present in the archive as
1174 # a standalone package): under certain circumstances, some
1175 # return a relative filename, whereas others return an absolute one;
1176 # we here use this module in a way that is at least compatible
1177 # with 0.18 and 0.20. Beware, hit'n'run refactorers!
1178 my $infile = new File::Temp(TEMPLATE => "ikiwiki-po-filter-in.XXXXXXXXXX",
1179 DIR => File::Spec->tmpdir,
1180 UNLINK => 1)->filename;
1181 my $outfile = new File::Temp(TEMPLATE => "ikiwiki-po-filter-out.XXXXXXXXXX",
1182 DIR => File::Spec->tmpdir,
1183 UNLINK => 1)->filename;
1185 my $fail = sub ($) {
1186 my $msg = "po(po_to_markup) - $page : " . shift;
1187 error($msg, sub { unlink $infile, $outfile});
1190 writefile(basename($infile), File::Spec->tmpdir, $content)
1191 or return $fail->(sprintf(gettext("failed to write %s"), $infile));
1193 my $masterfile = srcfile($pagesources{masterpage($page)});
1194 my $doc=Locale::Po4a::Chooser::new(po4a_type($masterfile),
1195 po4a_options($masterfile));
1197 'po_in_name' => [ $infile ],
1198 'file_in_name' => [ $masterfile ],
1199 'file_in_charset' => 'UTF-8',
1200 'file_out_charset' => 'UTF-8',
1201 ) or return $fail->(gettext("failed to translate"));
1202 $doc->write($outfile)
1203 or return $fail->(sprintf(gettext("failed to write %s"), $outfile));
1205 $content = readfile($outfile);
1207 # Unlinking should happen automatically, thanks to File::Temp,
1208 # but it does not work here, probably because of the way writefile()
1209 # and Locale::Po4a::write() work.
1210 unlink $infile, $outfile;
1215 # returns a SuccessReason or FailReason object
1217 my $content = shift;
1219 # NB: we don't use po_to_markup here, since Po4a parser does
1220 # not mind invalid PO content
1221 $content = '' unless defined $content;
1222 $content = decode_utf8(encode_utf8($content));
1224 # There are incompatibilities between some File::Temp versions
1225 # (including 0.18, bundled with Lenny's perl-modules package)
1226 # and others (e.g. 0.20, previously present in the archive as
1227 # a standalone package): under certain circumstances, some
1228 # return a relative filename, whereas others return an absolute one;
1229 # we here use this module in a way that is at least compatible
1230 # with 0.18 and 0.20. Beware, hit'n'run refactorers!
1231 my $infile = new File::Temp(TEMPLATE => "ikiwiki-po-isvalidpo.XXXXXXXXXX",
1232 DIR => File::Spec->tmpdir,
1233 UNLINK => 1)->filename;
1235 my $fail = sub ($) {
1236 my $msg = '[po/isvalidpo] ' . shift;
1238 return IkiWiki::FailReason->new("$msg");
1241 writefile(basename($infile), File::Spec->tmpdir, $content)
1242 or return $fail->(sprintf(gettext("failed to write %s"), $infile));
1244 my $res = (system("msgfmt", "--check", $infile, "-o", "/dev/null") == 0);
1246 # Unlinking should happen automatically, thanks to File::Temp,
1247 # but it does not work here, probably because of the way writefile()
1248 # and Locale::Po4a::write() work.
1252 return IkiWiki::SuccessReason->new("valid gettext data");
1254 return IkiWiki::FailReason->new(gettext("invalid gettext data, go back ".
1255 "to previous page to continue edit"));
1261 my $pagetype = pagetype($file);
1262 if ($pagetype eq 'html') {
1268 sub po4a_options($) {
1272 my $pagetype = pagetype($file);
1274 if ($pagetype eq 'html') {
1275 # how to disable options is not consistent across po4a modules
1276 $options{includessi} = '';
1277 $options{includeexternal} = 0;
1278 $options{ontagerror} = 'warn';
1280 elsif ($pagetype eq 'mdwn') {
1281 $options{markdown} = 1;
1284 $options{markdown} = 0;
1290 sub splitlangpair ($) {
1293 my ($code, $name) = ( $pair =~ /^($language_code_pattern)\|(.+)$/ );
1294 if (! defined $code || ! defined $name ||
1295 ! length $code || ! length $name) {
1296 # not a fatal error to avoid breaking if used with web setup
1297 warn sprintf(gettext("%s has invalid syntax: must use CODE|NAME"),
1301 return $code, $name;
1304 sub joinlangpair ($$) {
1308 return "$code|$name";
1315 package IkiWiki::PageSpec;
1317 sub match_istranslation ($;@) {
1320 if (IkiWiki::Plugin::po::istranslation($page)) {
1321 return IkiWiki::SuccessReason->new("is a translation page");
1324 return IkiWiki::FailReason->new("is not a translation page");
1328 sub match_istranslatable ($;@) {
1331 if (IkiWiki::Plugin::po::istranslatable($page)) {
1332 return IkiWiki::SuccessReason->new("is set as translatable in po_translatable_pages");
1335 return IkiWiki::FailReason->new("is not set as translatable in po_translatable_pages");
1339 sub match_lang ($$;@) {
1343 my $regexp=IkiWiki::glob2re($wanted);
1344 my $lang=IkiWiki::Plugin::po::lang($page);
1345 if ($lang !~ $regexp) {
1346 return IkiWiki::FailReason->new("file language is $lang, not $wanted");
1349 return IkiWiki::SuccessReason->new("file language is $wanted");
1353 sub match_currentlang ($$;@) {
1358 return IkiWiki::FailReason->new("no location provided") unless exists $params{location};
1360 my $currentlang=IkiWiki::Plugin::po::lang($params{location});
1361 my $lang=IkiWiki::Plugin::po::lang($page);
1363 if ($lang eq $currentlang) {
1364 return IkiWiki::SuccessReason->new("file language is the same as current one, i.e. $currentlang");
1367 return IkiWiki::FailReason->new("file language is $lang, whereas current language is $currentlang");
1371 sub match_needstranslation ($$;@) {
1375 if (defined $wanted && $wanted ne "") {
1376 if ($wanted !~ /^\d+$/) {
1377 return IkiWiki::FailReason->new("parameter is not an integer");
1379 elsif ($wanted > 100) {
1380 return IkiWiki::FailReason->new("parameter is greater than 100");
1387 my $percenttranslated=IkiWiki::Plugin::po::percenttranslated($page);
1388 if ($percenttranslated eq 'N/A') {
1389 return IkiWiki::FailReason->new("file is not a translatable page");
1391 elsif ($percenttranslated < $wanted) {
1392 return IkiWiki::SuccessReason->new("file has $percenttranslated translated");
1395 return IkiWiki::FailReason->new("file is translated enough");