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 if ($template->query(name => "HOMEPAGEURL")) {
347 $template->param(homepageurl => homepageurl($page));
349 if ($template->query(name => "otherlanguages")) {
350 $template->param(otherlanguages => [otherlanguagesloop($page)]);
351 map add_depends($page, $_), (values %{otherlanguages_pages($page)});
353 if ($config{discussion} && istranslation($page)) {
354 if ($page !~ /.*\/\Q$config{discussionpage}\E$/i &&
355 (length $config{cgiurl} ||
356 exists $links{$masterpage."/".lc($config{discussionpage})})) {
357 $template->param('discussionlink' => htmllink(
360 $masterpage . '/' . $config{discussionpage},
363 linktext => $config{discussionpage},
367 # Remove broken parentlink to ./index.html on home page's translations.
368 # It works because this hook has the "last" parameter set, to ensure it
369 # runs after parentlinks' own pagetemplate hook.
370 if ($template->param('parentlinks')
371 && istranslation($page)
372 && $masterpage eq "index") {
373 $template->param('parentlinks' => []);
375 if (ishomepage($page) && $template->query(name => "title")
376 && !$template->param("title_overridden")) {
377 $template->param(title => $config{wikiname});
381 # Add the renamed page translations to the list of to-be-renamed pages.
382 sub renamepages (@) {
385 my %torename = %{$params{torename}};
386 my $session = $params{session};
388 # Save the page(s) the user asked to rename, so that our
389 # canrename hook can tell the difference between:
390 # - a translation being renamed as a consequence of its master page
392 # - a user trying to directly rename a translation
393 # This is why this hook has to be run first, before the list of pages
394 # to rename is modified by other plugins.
396 @orig_torename=@{$session->param("po_orig_torename")}
397 if defined $session->param("po_orig_torename");
398 push @orig_torename, $torename{src};
399 $session->param(po_orig_torename => \@orig_torename);
400 IkiWiki::cgi_savesession($session);
402 return () unless istranslatable($torename{src});
405 my %otherpages=%{otherlanguages_pages($torename{src})};
406 while (my ($lang, $otherpage) = each %otherpages) {
409 srcfile => $pagesources{$otherpage},
410 dest => otherlanguage_page($torename{dest}, $lang),
411 destfile => $torename{dest}.".".$lang.".po",
421 map { deletetranslations($_) } grep istranslatablefile($_), @deleted;
427 my $updated_po_files=0;
429 # Refresh/create POT and PO files as needed.
430 foreach my $file (grep {istranslatablefile($_)} @rendered) {
431 my $masterfile=srcfile($file);
432 my $page=pagename($file);
433 my $updated_pot_file=0;
435 # Avoid touching underlay files.
436 next if $masterfile ne "$config{srcdir}/$file";
438 # Only refresh POT file if it does not exist, or if
439 # the source was changed: don't if only the HTML was
440 # refreshed, e.g. because of a dependency.
441 if ((grep { $_ eq $pagesources{$page} } @origneedsbuild) ||
442 ! -e potfile($masterfile)) {
443 refreshpot($masterfile);
447 foreach my $po (pofiles($masterfile)) {
448 next if ! $updated_pot_file && -e $po;
449 next if grep { $po=~/\Q$_\E/ } @{$config{underlaydirs}};
453 refreshpofiles($masterfile, @pofiles);
454 map { s/^\Q$config{srcdir}\E\/*//; IkiWiki::rcs_add($_) } @pofiles if $config{rcs};
459 if ($updated_po_files) {
461 gettext("updated PO files"));
465 sub checkcontent (@) {
468 if (istranslation($params{page})) {
469 my $res = isvalidpo($params{content});
483 if (istranslation($params{page})) {
484 return gettext("Can not remove a translation. If the master page is removed, ".
485 "however, its translations will be removed as well.");
492 my $session = $params{session};
494 if (istranslation($params{src})) {
495 my $masterpage = masterpage($params{src});
496 # Tell the difference between:
497 # - a translation being renamed as a consequence of its master page
498 # being renamed, which is allowed
499 # - a user trying to directly rename a translation, which is forbidden
500 # by looking for the master page in the list of to-be-renamed pages we
501 # saved early in the renaming process.
502 my $orig_torename = $session->param("po_orig_torename");
503 unless (grep { $_ eq $masterpage } @{$orig_torename}) {
504 return gettext("Can not rename a translation. If the master page is renamed, ".
505 "however, its translations will be renamed as well.");
511 # As we're previewing or saving a page, the content may have
512 # changed, so tell the next filter() invocation it must not be lazy.
516 unsetalreadyfiltered($params{page}, $params{page});
517 return $params{content};
520 sub formbuilder_setup (@) {
522 my $form=$params{form};
525 return unless defined $form->field("do");
527 if ($form->field("do") eq "create") {
528 # Warn the user: new pages must be written in master language.
529 my $template=template("pocreatepage.tmpl");
530 $template->param(LANG => $master_language_name);
531 $form->tmpl_param(message => $template->output);
533 elsif ($form->field("do") eq "edit") {
534 # Remove the rename/remove buttons on slave pages.
535 # This has to be done after the rename/remove plugins have added
536 # their buttons, which is why this hook must be run last.
537 # The canrename/canremove hooks already ensure this is forbidden
538 # at the backend level, so this is only UI sugar.
539 if (istranslation($form->field("page"))) {
541 for (my $i = 0; $i < @{$params{buttons}}; $i++) {
542 if (@{$params{buttons}}[$i] eq $_) {
543 delete @{$params{buttons}}[$i];
552 sub formbuilder (@) {
554 my $form=$params{form};
557 return unless defined $form->field("do");
559 # Do not allow to create pages of type po: they are automatically created.
560 # The main reason to do so is to bypass the "favor the type of linking page
561 # on page creation" logic, which is unsuitable when a broken link is clicked
562 # on a slave (PO) page.
563 # This cannot be done in the formbuilder_setup hook as the list of types is
565 if ($form->field("do") eq "create") {
566 foreach my $field ($form->field) {
567 next unless "$field" eq "type";
568 next unless $field->type eq 'select';
569 my $orig_value = $field->value;
570 # remove po from the list of types
571 my @types = grep { $_->[0] ne 'po' } $field->options;
572 $field->options(\@types) if @types;
573 # favor the type of linking page's masterpage
574 if ($orig_value eq 'po') {
576 if (defined $form->field('from')) {
577 ($from)=$form->field('from')=~/$config{wiki_file_regexp}/;
578 $from = masterpage($from);
580 if (defined $from && exists $pagesources{$from}) {
581 $type=pagetype($pagesources{$from});
583 $type=$config{default_pageext} unless defined $type;
584 $field->value($type) ;
591 # | Injected functions
594 # Implement po_link_to 'current' and 'negotiated' settings.
595 sub mybestlink ($$) {
599 return $origsubs{'bestlink'}->($page, $link)
600 if defined $config{po_link_to} && $config{po_link_to} eq "default";
602 my $res=$origsubs{'bestlink'}->(masterpage($page), $link);
603 my @caller = caller(1);
605 && istranslatedto($res, lang($page))
606 && istranslation($page)
607 && !(exists $caller[3] && defined $caller[3]
608 && ($caller[3] eq "IkiWiki::PageSpec::match_link"))) {
609 return $res . "." . lang($page);
614 sub mybeautify_urlpath ($) {
617 my $res=$origsubs{'beautify_urlpath'}->($url);
618 if (defined $config{po_link_to} && $config{po_link_to} eq "negotiated") {
619 $res =~ s!/\Qindex.$master_language_code.$config{htmlext}\E$!/!;
620 $res =~ s!/\Qindex.$config{htmlext}\E$!/!;
622 $res =~ s!/\Qindex.$_.$config{htmlext}\E$!/!;
628 sub mytargetpage ($$;$) {
633 if (istranslation($page) || istranslatable($page)) {
634 my ($masterpage, $lang) = (masterpage($page), lang($page));
635 if (defined $filename) {
636 return $masterpage . "/" . $filename . "." . $lang . "." . $ext;
638 elsif (! $config{usedirs} || $masterpage eq 'index') {
639 return $masterpage . "." . $lang . "." . $ext;
642 return $masterpage . "/index." . $lang . "." . $ext;
645 return $origsubs{'targetpage'}->($page, $ext, $filename);
653 # workaround hard-coded /index.$config{htmlext} in IkiWiki::urlto()
655 && $config{po_link_to} eq "current"
656 && istranslatable('index')) {
658 return IkiWiki::beautify_urlpath(IkiWiki::baseurl($from) . "index." . lang($from) . ".$config{htmlext}");
661 return $origsubs{'urlto'}->($to,$from,$absolute);
664 # avoid using our injected beautify_urlpath if run by cgi_editpage,
665 # so that one is redirected to the just-edited page rather than to the
666 # negociated translation; to prevent unnecessary fiddling with caller/inject,
667 # we only do so when our beautify_urlpath would actually do what we want to
668 # avoid, i.e. when po_link_to = negotiated.
669 # also avoid doing so when run by cgi_goto, so that the links on recentchanges
670 # page actually lead to the exact page they pretend to.
671 if ($config{po_link_to} eq "negotiated") {
672 my @caller = caller(1);
674 $use_orig = 1 if (exists $caller[3] && defined $caller[3]
675 && ($caller[3] eq "IkiWiki::cgi_editpage" ||
676 $caller[3] eq "IkiWiki::Plugin::goto::cgi_goto")
678 inject(name => "IkiWiki::beautify_urlpath", call => $origsubs{'beautify_urlpath'})
680 my $res = $origsubs{'urlto'}->($to,$from,$absolute);
681 inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath)
686 return $origsubs{'urlto'}->($to,$from,$absolute)
693 # slave pages have no subpages
694 if (istranslation($params{'from'})) {
695 $params{'from'} = masterpage($params{'from'});
697 return $origsubs{'cgiurl'}->(%params);
704 if (exists $params{rootpage}) {
705 $rootpage=$origsubs{'bestlink'}->($params{page}, $params{rootpage});
706 if (!length $rootpage) {
707 $rootpage=$params{rootpage};
711 $rootpage=masterpage($params{page});
716 sub myisselflink ($$) {
720 return 1 if $origsubs{'isselflink'}->($page, $link);
721 if (istranslation($page)) {
722 return $origsubs{'isselflink'}->(masterpage($page), $link);
728 # | Blackboxes for private data
734 sub alreadyfiltered($$) {
738 return exists $filtered{$page}{$destpage}
739 && $filtered{$page}{$destpage} eq 1;
742 sub setalreadyfiltered($$) {
746 $filtered{$page}{$destpage}=1;
749 sub unsetalreadyfiltered($$) {
753 if (exists $filtered{$page}{$destpage}) {
754 delete $filtered{$page}{$destpage};
758 sub resetalreadyfiltered() {
767 sub maybe_add_leading_slash ($;$) {
770 $add=1 unless defined $add;
771 return '/' . $str if $add;
775 sub istranslatablefile ($) {
778 return 0 unless defined $file;
779 my $type=pagetype($file);
780 return 0 if ! defined $type || $type eq 'po';
781 return 0 if $file =~ /\.pot$/;
782 return 0 if ! defined $config{po_translatable_pages};
783 return 1 if pagespec_match(pagename($file), $config{po_translatable_pages});
787 sub istranslatable ($) {
791 return 1 if istranslatablefile($pagesources{$page});
795 sub istranslatedto ($$) {
797 my $destlang = shift;
800 return 0 unless istranslatable($page);
801 exists $pagesources{otherlanguage_page($page, $destlang)};
804 sub _istranslation ($) {
807 $page='' unless defined $page && length $page;
808 my $hasleadingslash = ($page=~s#^/##);
809 my $file=$pagesources{$page};
810 return 0 unless defined $file
811 && defined pagetype($file)
812 && pagetype($file) eq 'po';
813 return 0 if $file =~ /\.pot$/;
815 my ($masterpage, $lang) = ($page =~ /(.*)[.]($language_code_pattern)$/);
816 return 0 unless defined $masterpage && defined $lang
817 && length $masterpage && length $lang
818 && defined $pagesources{$masterpage}
819 && defined $slavelanguages{$lang};
821 return (maybe_add_leading_slash($masterpage, $hasleadingslash), $lang)
822 if istranslatable($masterpage);
825 sub istranslation ($) {
828 if (1 < (my ($masterpage, $lang) = _istranslation($page))) {
829 my $hasleadingslash = ($masterpage=~s#^/##);
830 $translations{$masterpage}{$lang}=$page unless exists $translations{$masterpage}{$lang};
831 return (maybe_add_leading_slash($masterpage, $hasleadingslash), $lang);
839 if ( 1 < (my ($masterpage, $lang) = _istranslation($page))) {
848 if (1 < (my ($masterpage, $lang) = _istranslation($page))) {
851 return $master_language_code;
854 sub islanguagecode ($) {
857 return $code =~ /^$language_code_pattern$/;
860 sub otherlanguage_page ($$) {
864 return masterpage($page) if $code eq $master_language_code;
865 return masterpage($page) . '.' . $code;
868 # Returns the list of other languages codes: the master language comes first,
869 # then the codes are ordered the same way as in po_slave_languages, if it is
870 # an array, or in the language name lexical order, if it is a hash.
871 sub otherlanguages_codes ($) {
875 return \@ret unless istranslation($page) || istranslatable($page);
876 my $curlang=lang($page);
878 ($master_language_code, @slavelanguages) {
879 next if $lang eq $curlang;
880 if ($lang eq $master_language_code ||
881 istranslatedto(masterpage($page), $lang)) {
888 sub otherlanguages_pages ($) {
893 $ret{$_} = otherlanguage_page($page, $_)
894 } @{otherlanguages_codes($page)};
900 my $masterfile=shift;
902 (my $name, my $dir, my $suffix) = fileparse($masterfile, qr/\.[^.]*/);
903 $dir='' if $dir eq './';
904 return File::Spec->catpath('', $dir, $name . ".pot");
908 my $masterfile=shift;
911 (my $name, my $dir, my $suffix) = fileparse($masterfile, qr/\.[^.]*/);
912 $dir='' if $dir eq './';
913 return File::Spec->catpath('', $dir, $name . "." . $lang . ".po");
917 my $masterfile=shift;
919 return map pofile($masterfile, $_), @slavelanguages;
923 my $masterfile=shift;
925 my $potfile=potfile($masterfile);
926 my $doc=Locale::Po4a::Chooser::new(po4a_type($masterfile),
927 po4a_options($masterfile));
928 $doc->{TT}{utf_mode} = 1;
929 $doc->{TT}{file_in_charset} = 'UTF-8';
930 $doc->{TT}{file_out_charset} = 'UTF-8';
931 $doc->read($masterfile);
932 # let's cheat a bit to force porefs option to be passed to
933 # Locale::Po4a::Po; this is undocument use of internal
934 # Locale::Po4a::TransTractor's data, compulsory since this module
935 # prevents us from using the porefs option.
936 $doc->{TT}{po_out}=Locale::Po4a::Po->new({ 'porefs' => 'none' });
937 $doc->{TT}{po_out}->set_charset('UTF-8');
940 IkiWiki::prep_writefile(basename($potfile),dirname($potfile));
941 $doc->writepo($potfile);
944 sub refreshpofiles ($@) {
945 my $masterfile=shift;
948 my $potfile=potfile($masterfile);
950 error("po(refreshpofiles) ".sprintf(gettext("POT file (%s) does not exist"), $potfile));
953 foreach my $pofile (@pofiles) {
954 IkiWiki::prep_writefile(basename($pofile),dirname($pofile));
957 # If the po file exists in an underlay, copy it
959 my ($pobase)=$pofile=~/^\Q$config{srcdir}\E\/?(.*)$/;
960 foreach my $dir (@{$config{underlaydirs}}) {
961 if (-e "$dir/$pobase") {
962 File::Copy::syscopy("$dir/$pobase",$pofile)
963 or error("po(refreshpofiles) ".
964 sprintf(gettext("failed to copy underlay PO file to %s"),
971 system("msgmerge", "--previous", "-q", "-U", "--backup=none", $pofile, $potfile) == 0
972 or error("po(refreshpofiles) ".
973 sprintf(gettext("failed to update %s"),
977 File::Copy::syscopy($potfile,$pofile)
978 or error("po(refreshpofiles) ".
979 sprintf(gettext("failed to copy the POT file to %s"),
985 sub buildtranslationscache() {
986 # use istranslation's side-effect
987 map istranslation($_), (keys %pagesources);
990 sub resettranslationscache() {
994 sub flushmemoizecache() {
995 Memoize::flush_cache("istranslatable");
996 Memoize::flush_cache("_istranslation");
997 Memoize::flush_cache("percenttranslated");
1000 sub urlto_with_orig_beautiful_urlpath($$) {
1004 inject(name => "IkiWiki::beautify_urlpath", call => $origsubs{'beautify_urlpath'});
1005 my $res=urlto($to, $from);
1006 inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath);
1011 sub percenttranslated ($) {
1015 return gettext("N/A") unless istranslation($page);
1016 my $file=srcfile($pagesources{$page});
1017 my $masterfile = srcfile($pagesources{masterpage($page)});
1018 my $doc=Locale::Po4a::Chooser::new(po4a_type($masterfile),
1019 po4a_options($masterfile));
1021 'po_in_name' => [ $file ],
1022 'file_in_name' => [ $masterfile ],
1023 'file_in_charset' => 'UTF-8',
1024 'file_out_charset' => 'UTF-8',
1025 ) or error("po(percenttranslated) ".
1026 sprintf(gettext("failed to translate %s"), $page));
1027 my ($percent,$hit,$queries) = $doc->stats();
1028 $percent =~ s/\.[0-9]+$//;
1032 sub languagename ($) {
1035 return $master_language_name
1036 if $code eq $master_language_code;
1037 return $slavelanguages{$code}
1038 if defined $slavelanguages{$code};
1042 sub otherlanguagesloop ($) {
1046 if (istranslation($page)) {
1048 url => urlto_with_orig_beautiful_urlpath(masterpage($page), $page),
1049 code => $master_language_code,
1050 language => $master_language_name,
1054 foreach my $lang (@{otherlanguages_codes($page)}) {
1055 next if $lang eq $master_language_code;
1056 my $otherpage = otherlanguage_page($page, $lang);
1058 url => urlto_with_orig_beautiful_urlpath($otherpage, $page),
1060 language => languagename($lang),
1061 percent => percenttranslated($otherpage),
1067 sub homepageurl (;$) {
1070 return urlto('', $page);
1073 sub ishomepage ($) {
1076 return 1 if $page eq 'index';
1077 map { return 1 if $page eq 'index.'.$_ } @slavelanguages;
1081 sub deletetranslations ($) {
1082 my $deletedmasterfile=shift;
1084 my $deletedmasterpage=pagename($deletedmasterfile);
1087 my $file = newpagefile($deletedmasterpage.'.'.$_, 'po');
1088 my $absfile = "$config{srcdir}/$file";
1089 if (-e $absfile && ! -l $absfile && ! -d $absfile) {
1090 push @todelete, $file;
1096 IkiWiki::rcs_remove($_);
1099 IkiWiki::prune("$config{srcdir}/$_");
1105 gettext("removed obsolete PO files"));
1109 sub commit_and_refresh ($) {
1113 IkiWiki::disable_commit_hook();
1114 IkiWiki::rcs_commit_staged(
1117 IkiWiki::enable_commit_hook();
1118 IkiWiki::rcs_update();
1120 # Reinitialize module's private variables.
1121 resetalreadyfiltered();
1122 resettranslationscache();
1123 flushmemoizecache();
1124 # Trigger a wiki refresh.
1125 require IkiWiki::Render;
1126 # without preliminary saveindex/loadindex, refresh()
1127 # complains about a lot of uninitialized variables
1128 IkiWiki::saveindex();
1129 IkiWiki::loadindex();
1131 IkiWiki::saveindex();
1134 sub po_to_markup ($$) {
1135 my ($page, $content) = (shift, shift);
1137 $content = '' unless defined $content;
1138 $content = decode_utf8(encode_utf8($content));
1139 # CRLF line terminators make poor Locale::Po4a feel bad
1140 $content=~s/\r\n/\n/g;
1142 # There are incompatibilities between some File::Temp versions
1143 # (including 0.18, bundled with Lenny's perl-modules package)
1144 # and others (e.g. 0.20, previously present in the archive as
1145 # a standalone package): under certain circumstances, some
1146 # return a relative filename, whereas others return an absolute one;
1147 # we here use this module in a way that is at least compatible
1148 # with 0.18 and 0.20. Beware, hit'n'run refactorers!
1149 my $infile = new File::Temp(TEMPLATE => "ikiwiki-po-filter-in.XXXXXXXXXX",
1150 DIR => File::Spec->tmpdir,
1151 UNLINK => 1)->filename;
1152 my $outfile = new File::Temp(TEMPLATE => "ikiwiki-po-filter-out.XXXXXXXXXX",
1153 DIR => File::Spec->tmpdir,
1154 UNLINK => 1)->filename;
1156 my $fail = sub ($) {
1157 my $msg = "po(po_to_markup) - $page : " . shift;
1158 error($msg, sub { unlink $infile, $outfile});
1161 writefile(basename($infile), File::Spec->tmpdir, $content)
1162 or return $fail->(sprintf(gettext("failed to write %s"), $infile));
1164 my $masterfile = srcfile($pagesources{masterpage($page)});
1165 my $doc=Locale::Po4a::Chooser::new(po4a_type($masterfile),
1166 po4a_options($masterfile));
1168 'po_in_name' => [ $infile ],
1169 'file_in_name' => [ $masterfile ],
1170 'file_in_charset' => 'UTF-8',
1171 'file_out_charset' => 'UTF-8',
1172 ) or return $fail->(gettext("failed to translate"));
1173 $doc->write($outfile)
1174 or return $fail->(sprintf(gettext("failed to write %s"), $outfile));
1176 $content = readfile($outfile);
1178 # Unlinking should happen automatically, thanks to File::Temp,
1179 # but it does not work here, probably because of the way writefile()
1180 # and Locale::Po4a::write() work.
1181 unlink $infile, $outfile;
1186 # returns a SuccessReason or FailReason object
1188 my $content = shift;
1190 # NB: we don't use po_to_markup here, since Po4a parser does
1191 # not mind invalid PO content
1192 $content = '' unless defined $content;
1193 $content = decode_utf8(encode_utf8($content));
1195 # There are incompatibilities between some File::Temp versions
1196 # (including 0.18, bundled with Lenny's perl-modules package)
1197 # and others (e.g. 0.20, previously present in the archive as
1198 # a standalone package): under certain circumstances, some
1199 # return a relative filename, whereas others return an absolute one;
1200 # we here use this module in a way that is at least compatible
1201 # with 0.18 and 0.20. Beware, hit'n'run refactorers!
1202 my $infile = new File::Temp(TEMPLATE => "ikiwiki-po-isvalidpo.XXXXXXXXXX",
1203 DIR => File::Spec->tmpdir,
1204 UNLINK => 1)->filename;
1206 my $fail = sub ($) {
1207 my $msg = '[po/isvalidpo] ' . shift;
1209 return IkiWiki::FailReason->new("$msg");
1212 writefile(basename($infile), File::Spec->tmpdir, $content)
1213 or return $fail->(sprintf(gettext("failed to write %s"), $infile));
1215 my $res = (system("msgfmt", "--check", $infile, "-o", "/dev/null") == 0);
1217 # Unlinking should happen automatically, thanks to File::Temp,
1218 # but it does not work here, probably because of the way writefile()
1219 # and Locale::Po4a::write() work.
1223 return IkiWiki::SuccessReason->new("valid gettext data");
1225 return IkiWiki::FailReason->new(gettext("invalid gettext data, go back ".
1226 "to previous page to continue edit"));
1232 my $pagetype = pagetype($file);
1233 if ($pagetype eq 'html') {
1239 sub po4a_options($) {
1243 my $pagetype = pagetype($file);
1245 if ($pagetype eq 'html') {
1246 # how to disable options is not consistent across po4a modules
1247 $options{includessi} = '';
1248 $options{includeexternal} = 0;
1250 elsif ($pagetype eq 'mdwn') {
1251 $options{markdown} = 1;
1254 $options{markdown} = 0;
1260 sub splitlangpair ($) {
1263 my ($code, $name) = ( $pair =~ /^($language_code_pattern)\|(.+)$/ );
1264 if (! defined $code || ! defined $name ||
1265 ! length $code || ! length $name) {
1266 # not a fatal error to avoid breaking if used with web setup
1267 warn sprintf(gettext("%s has invalid syntax: must use CODE|NAME"),
1271 return $code, $name;
1274 sub joinlangpair ($$) {
1278 return "$code|$name";
1285 package IkiWiki::PageSpec;
1287 sub match_istranslation ($;@) {
1290 if (IkiWiki::Plugin::po::istranslation($page)) {
1291 return IkiWiki::SuccessReason->new("is a translation page");
1294 return IkiWiki::FailReason->new("is not a translation page");
1298 sub match_istranslatable ($;@) {
1301 if (IkiWiki::Plugin::po::istranslatable($page)) {
1302 return IkiWiki::SuccessReason->new("is set as translatable in po_translatable_pages");
1305 return IkiWiki::FailReason->new("is not set as translatable in po_translatable_pages");
1309 sub match_lang ($$;@) {
1313 my $regexp=IkiWiki::glob2re($wanted);
1314 my $lang=IkiWiki::Plugin::po::lang($page);
1315 if ($lang !~ $regexp) {
1316 return IkiWiki::FailReason->new("file language is $lang, not $wanted");
1319 return IkiWiki::SuccessReason->new("file language is $wanted");
1323 sub match_currentlang ($$;@) {
1328 return IkiWiki::FailReason->new("no location provided") unless exists $params{location};
1330 my $currentlang=IkiWiki::Plugin::po::lang($params{location});
1331 my $lang=IkiWiki::Plugin::po::lang($page);
1333 if ($lang eq $currentlang) {
1334 return IkiWiki::SuccessReason->new("file language is the same as current one, i.e. $currentlang");
1337 return IkiWiki::FailReason->new("file language is $lang, whereas current language is $currentlang");
1341 sub match_needstranslation ($$;@) {
1345 if (defined $wanted && $wanted ne "") {
1346 if ($wanted !~ /^\d+$/) {
1347 return IkiWiki::FailReason->new("parameter is not an integer");
1349 elsif ($wanted > 100) {
1350 return IkiWiki::FailReason->new("parameter is greater than 100");
1357 my $percenttranslated=IkiWiki::Plugin::po::percenttranslated($page);
1358 if ($percenttranslated eq 'N/A') {
1359 return IkiWiki::FailReason->new("file is not a translatable page");
1361 elsif ($percenttranslated < $wanted) {
1362 return IkiWiki::SuccessReason->new("file has $percenttranslated translated");
1365 return IkiWiki::FailReason->new("file is translated enough");