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(scalar $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 if (! (system("msgmerge", "--previous", "-q", "-U", "--backup=none", $pofile, $potfile) == 0)) {
997 print STDERR ("po(refreshpofiles) ". sprintf(gettext("failed to update %s"), $pofile));
1001 File::Copy::syscopy($potfile,$pofile)
1002 or error("po(refreshpofiles) ".
1003 sprintf(gettext("failed to copy the POT file to %s"),
1009 sub buildtranslationscache() {
1010 # use istranslation's side-effect
1011 map istranslation($_), (keys %pagesources);
1014 sub resettranslationscache() {
1015 undef %translations;
1018 sub flushmemoizecache() {
1019 Memoize::flush_cache("istranslatable");
1020 Memoize::flush_cache("_istranslation");
1021 Memoize::flush_cache("percenttranslated");
1024 sub urlto_with_orig_beautiful_urlpath($$) {
1028 inject(name => "IkiWiki::beautify_urlpath", call => $origsubs{'beautify_urlpath'});
1029 my $res=urlto($to, $from);
1030 inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath);
1035 sub percenttranslated ($) {
1039 return gettext("N/A") unless istranslation($page);
1040 my $file=srcfile($pagesources{$page});
1041 my $masterfile = srcfile($pagesources{masterpage($page)});
1042 my $doc=Locale::Po4a::Chooser::new(po4a_type($masterfile),
1043 po4a_options($masterfile));
1045 'po_in_name' => [ $file ],
1046 'file_in_name' => [ $masterfile ],
1047 'file_in_charset' => 'UTF-8',
1048 'file_out_charset' => 'UTF-8',
1049 ) or error("po(percenttranslated) ".
1050 sprintf(gettext("failed to translate %s"), $page));
1051 my ($percent,$hit,$queries) = $doc->stats();
1052 $percent =~ s/\.[0-9]+$//;
1056 sub languagename ($) {
1059 return $master_language_name
1060 if $code eq $master_language_code;
1061 return $slavelanguages{$code}
1062 if defined $slavelanguages{$code};
1066 sub otherlanguagesloop ($) {
1070 if (istranslation($page)) {
1072 url => urlto_with_orig_beautiful_urlpath(masterpage($page), $page),
1073 code => $master_language_code,
1074 html_code => htmllangcode($master_language_code),
1075 html_dir => htmllangdir($master_language_code),
1076 language => $master_language_name,
1080 foreach my $lang (@{otherlanguages_codes($page)}) {
1081 next if $lang eq $master_language_code;
1082 my $otherpage = otherlanguage_page($page, $lang);
1084 url => urlto_with_orig_beautiful_urlpath($otherpage, $page),
1086 html_code => htmllangcode($lang),
1087 html_dir => htmllangdir($lang),
1088 language => languagename($lang),
1089 percent => percenttranslated($otherpage),
1095 sub homepageurl (;$) {
1098 return urlto('', $page);
1101 sub ishomepage ($) {
1104 return 1 if $page eq 'index';
1105 map { return 1 if $page eq 'index.'.$_ } @slavelanguages;
1109 sub deletetranslations ($) {
1110 my $deletedmasterfile=shift;
1112 my $deletedmasterpage=pagename($deletedmasterfile);
1115 my $file = newpagefile($deletedmasterpage.'.'.$_, 'po');
1116 my $absfile = "$config{srcdir}/$file";
1117 if (-e $absfile && ! -l $absfile && ! -d $absfile) {
1118 push @todelete, $file;
1124 IkiWiki::rcs_remove($_);
1127 IkiWiki::prune("$config{srcdir}/$_", $config{srcdir});
1133 gettext("removed obsolete PO files"));
1137 sub commit_and_refresh ($) {
1141 IkiWiki::disable_commit_hook();
1142 IkiWiki::rcs_commit_staged(
1145 IkiWiki::enable_commit_hook();
1146 IkiWiki::rcs_update();
1148 # Reinitialize module's private variables.
1149 resetalreadyfiltered();
1150 resettranslationscache();
1151 flushmemoizecache();
1152 # Trigger a wiki refresh.
1153 require IkiWiki::Render;
1154 # without preliminary saveindex/loadindex, refresh()
1155 # complains about a lot of uninitialized variables
1156 IkiWiki::saveindex();
1157 IkiWiki::loadindex();
1159 IkiWiki::saveindex();
1162 sub po_to_markup ($$) {
1163 my ($page, $content) = (shift, shift);
1165 $content = '' unless defined $content;
1166 $content = decode_utf8(encode_utf8($content));
1167 # CRLF line terminators make poor Locale::Po4a feel bad
1168 $content=~s/\r\n/\n/g;
1170 # There are incompatibilities between some File::Temp versions
1171 # (including 0.18, bundled with Lenny's perl-modules package)
1172 # and others (e.g. 0.20, previously present in the archive as
1173 # a standalone package): under certain circumstances, some
1174 # return a relative filename, whereas others return an absolute one;
1175 # we here use this module in a way that is at least compatible
1176 # with 0.18 and 0.20. Beware, hit'n'run refactorers!
1177 my $infile = new File::Temp(TEMPLATE => "ikiwiki-po-filter-in.XXXXXXXXXX",
1178 DIR => File::Spec->tmpdir,
1179 UNLINK => 1)->filename;
1180 my $outfile = new File::Temp(TEMPLATE => "ikiwiki-po-filter-out.XXXXXXXXXX",
1181 DIR => File::Spec->tmpdir,
1182 UNLINK => 1)->filename;
1184 my $fail = sub ($) {
1185 my $msg = "po(po_to_markup) - $page : " . shift;
1186 error($msg, sub { unlink $infile, $outfile});
1189 writefile(basename($infile), File::Spec->tmpdir, $content)
1190 or return $fail->(sprintf(gettext("failed to write %s"), $infile));
1192 my $masterfile = srcfile($pagesources{masterpage($page)});
1193 my $doc=Locale::Po4a::Chooser::new(po4a_type($masterfile),
1194 po4a_options($masterfile));
1196 'po_in_name' => [ $infile ],
1197 'file_in_name' => [ $masterfile ],
1198 'file_in_charset' => 'UTF-8',
1199 'file_out_charset' => 'UTF-8',
1200 ) or return $fail->(gettext("failed to translate"));
1201 $doc->write($outfile)
1202 or return $fail->(sprintf(gettext("failed to write %s"), $outfile));
1204 $content = readfile($outfile);
1206 # Unlinking should happen automatically, thanks to File::Temp,
1207 # but it does not work here, probably because of the way writefile()
1208 # and Locale::Po4a::write() work.
1209 unlink $infile, $outfile;
1214 # returns a SuccessReason or FailReason object
1216 my $content = shift;
1218 # NB: we don't use po_to_markup here, since Po4a parser does
1219 # not mind invalid PO content
1220 $content = '' unless defined $content;
1221 $content = decode_utf8(encode_utf8($content));
1223 # There are incompatibilities between some File::Temp versions
1224 # (including 0.18, bundled with Lenny's perl-modules package)
1225 # and others (e.g. 0.20, previously present in the archive as
1226 # a standalone package): under certain circumstances, some
1227 # return a relative filename, whereas others return an absolute one;
1228 # we here use this module in a way that is at least compatible
1229 # with 0.18 and 0.20. Beware, hit'n'run refactorers!
1230 my $infile = new File::Temp(TEMPLATE => "ikiwiki-po-isvalidpo.XXXXXXXXXX",
1231 DIR => File::Spec->tmpdir,
1232 UNLINK => 1)->filename;
1234 my $fail = sub ($) {
1235 my $msg = '[po/isvalidpo] ' . shift;
1237 return IkiWiki::FailReason->new("$msg");
1240 writefile(basename($infile), File::Spec->tmpdir, $content)
1241 or return $fail->(sprintf(gettext("failed to write %s"), $infile));
1243 my $res = (system("msgfmt", "--check", $infile, "-o", "/dev/null") == 0);
1245 # Unlinking should happen automatically, thanks to File::Temp,
1246 # but it does not work here, probably because of the way writefile()
1247 # and Locale::Po4a::write() work.
1251 return IkiWiki::SuccessReason->new("valid gettext data");
1253 return IkiWiki::FailReason->new(gettext("invalid gettext data, go back ".
1254 "to previous page to continue edit"));
1260 my $pagetype = pagetype($file);
1261 if ($pagetype eq 'html') {
1267 sub po4a_options($) {
1271 my $pagetype = pagetype($file);
1273 if ($pagetype eq 'html') {
1274 # how to disable options is not consistent across po4a modules
1275 $options{includessi} = '';
1276 $options{includeexternal} = 0;
1277 $options{ontagerror} = 'warn';
1279 elsif ($pagetype eq 'mdwn') {
1280 $options{markdown} = 1;
1283 $options{markdown} = 0;
1289 sub splitlangpair ($) {
1292 my ($code, $name) = ( $pair =~ /^($language_code_pattern)\|(.+)$/ );
1293 if (! defined $code || ! defined $name ||
1294 ! length $code || ! length $name) {
1295 # not a fatal error to avoid breaking if used with web setup
1296 warn sprintf(gettext("%s has invalid syntax: must use CODE|NAME"),
1300 return $code, $name;
1303 sub joinlangpair ($$) {
1307 return "$code|$name";
1314 package IkiWiki::PageSpec;
1316 sub match_istranslation ($;@) {
1319 if (IkiWiki::Plugin::po::istranslation($page)) {
1320 return IkiWiki::SuccessReason->new("is a translation page");
1323 return IkiWiki::FailReason->new("is not a translation page");
1327 sub match_istranslatable ($;@) {
1330 if (IkiWiki::Plugin::po::istranslatable($page)) {
1331 return IkiWiki::SuccessReason->new("is set as translatable in po_translatable_pages");
1334 return IkiWiki::FailReason->new("is not set as translatable in po_translatable_pages");
1338 sub match_lang ($$;@) {
1342 my $regexp=IkiWiki::glob2re($wanted);
1343 my $lang=IkiWiki::Plugin::po::lang($page);
1344 if ($lang !~ $regexp) {
1345 return IkiWiki::FailReason->new("file language is $lang, not $wanted");
1348 return IkiWiki::SuccessReason->new("file language is $wanted");
1352 sub match_currentlang ($$;@) {
1357 return IkiWiki::FailReason->new("no location provided") unless exists $params{location};
1359 my $currentlang=IkiWiki::Plugin::po::lang($params{location});
1360 my $lang=IkiWiki::Plugin::po::lang($page);
1362 if ($lang eq $currentlang) {
1363 return IkiWiki::SuccessReason->new("file language is the same as current one, i.e. $currentlang");
1366 return IkiWiki::FailReason->new("file language is $lang, whereas current language is $currentlang");
1370 sub match_needstranslation ($$;@) {
1374 if (defined $wanted && $wanted ne "") {
1375 if ($wanted !~ /^\d+$/) {
1376 return IkiWiki::FailReason->new("parameter is not an integer");
1378 elsif ($wanted > 100) {
1379 return IkiWiki::FailReason->new("parameter is greater than 100");
1386 my $percenttranslated=IkiWiki::Plugin::po::percenttranslated($page);
1387 if ($percenttranslated eq 'N/A') {
1388 return IkiWiki::FailReason->new("file is not a translatable page");
1390 elsif ($percenttranslated < $wanted) {
1391 return IkiWiki::SuccessReason->new("file has $percenttranslated translated");
1394 return IkiWiki::FailReason->new("file is translated enough");