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
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);
42 hook(type => "needsbuild", id => "po", call => \&needsbuild);
43 hook(type => "scan", id => "po", call => \&scan, last => 1);
44 hook(type => "filter", id => "po", call => \&filter);
45 hook(type => "htmlize", id => "po", call => \&htmlize);
46 hook(type => "pagetemplate", id => "po", call => \&pagetemplate, last => 1);
47 hook(type => "rename", id => "po", call => \&renamepages, first => 1);
48 hook(type => "delete", id => "po", call => \&mydelete);
49 hook(type => "change", id => "po", call => \&change);
50 hook(type => "checkcontent", id => "po", call => \&checkcontent);
51 hook(type => "canremove", id => "po", call => \&canremove);
52 hook(type => "canrename", id => "po", call => \&canrename);
53 hook(type => "editcontent", id => "po", call => \&editcontent);
54 hook(type => "formbuilder_setup", id => "po", call => \&formbuilder_setup, last => 1);
55 hook(type => "formbuilder", id => "po", call => \&formbuilder);
58 $origsubs{'bestlink'}=\&IkiWiki::bestlink;
59 inject(name => "IkiWiki::bestlink", call => \&mybestlink);
60 $origsubs{'beautify_urlpath'}=\&IkiWiki::beautify_urlpath;
61 inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath);
62 $origsubs{'targetpage'}=\&IkiWiki::targetpage;
63 inject(name => "IkiWiki::targetpage", call => \&mytargetpage);
64 $origsubs{'urlto'}=\&IkiWiki::urlto;
65 inject(name => "IkiWiki::urlto", call => \&myurlto);
66 $origsubs{'cgiurl'}=\&IkiWiki::cgiurl;
67 inject(name => "IkiWiki::cgiurl", call => \&mycgiurl);
68 $origsubs{'rootpage'}=\&IkiWiki::rootpage;
69 inject(name => "IkiWiki::rootpage", call => \&myrootpage);
70 $origsubs{'isselflink'}=\&IkiWiki::isselflink;
71 inject(name => "IkiWiki::isselflink", call => \&myisselflink);
81 # 2. Injected functions
82 # 3. Blackboxes for private data
95 rebuild => 1, # format plugin
98 po_master_language => {
100 example => "en|English",
101 description => "master language (non-PO files)",
105 po_slave_languages => {
112 description => "slave languages (translated via PO files) format: ll|Langname",
116 po_translatable_pages => {
118 example => "* and !*/Discussion",
119 description => "PageSpec controlling which pages are translatable",
120 link => "ikiwiki/PageSpec",
126 example => "current",
127 description => "internal linking behavior (default/current/negotiated)",
134 if (exists $config{po_master_language}) {
135 if (! ref $config{po_master_language}) {
136 ($master_language_code, $master_language_name)=
137 splitlangpair($config{po_master_language});
140 $master_language_code=$config{po_master_language}{code};
141 $master_language_name=$config{po_master_language}{name};
142 $config{po_master_language}=joinlangpair($master_language_code, $master_language_name);
145 if (! defined $master_language_code) {
146 $master_language_code='en';
148 if (! defined $master_language_name) {
149 $master_language_name='English';
152 if (ref $config{po_slave_languages} eq 'ARRAY') {
153 foreach my $pair (@{$config{po_slave_languages}}) {
154 my ($code, $name)=splitlangpair($pair);
155 if (defined $code && ! exists $slavelanguages{$code}) {
156 push @slavelanguages, $code;
157 $slavelanguages{$code} = $name;
161 elsif (ref $config{po_slave_languages} eq 'HASH') {
162 %slavelanguages=%{$config{po_slave_languages}};
163 @slavelanguages = sort {
164 $config{po_slave_languages}->{$a} cmp $config{po_slave_languages}->{$b};
165 } keys %slavelanguages;
166 $config{po_slave_languages}=[
167 map { joinlangpair($_, $slavelanguages{$_}) } @slavelanguages
171 delete $slavelanguages{$master_language_code};
175 or error(sprintf(gettext("%s is not a valid language code"), $_));
176 } ($master_language_code, @slavelanguages);
178 if (! exists $config{po_translatable_pages} ||
179 ! defined $config{po_translatable_pages}) {
180 $config{po_translatable_pages}="";
182 if (! exists $config{po_link_to} ||
183 ! defined $config{po_link_to}) {
184 $config{po_link_to}='default';
186 elsif ($config{po_link_to} !~ /^(default|current|negotiated)$/) {
187 warn(sprintf(gettext('%s is not a valid value for po_link_to, falling back to po_link_to=default'),
188 $config{po_link_to}));
189 $config{po_link_to}='default';
191 elsif ($config{po_link_to} eq "negotiated" && ! $config{usedirs}) {
192 warn(gettext('po_link_to=negotiated requires usedirs to be enabled, falling back to po_link_to=default'));
193 $config{po_link_to}='default';
196 push @{$config{wiki_file_prune_regexps}}, qr/\.pot$/;
198 # Translated versions of the underlays are added if available.
199 foreach my $underlay ("basewiki",
200 map { m/^\Q$config{underlaydirbase}\E\/*(.*)/ }
201 reverse @{$config{underlaydirs}}) {
202 next if $underlay=~/^locale\//;
204 # Underlays containing the po files for slave languages.
205 foreach my $ll (@slavelanguages) {
206 add_underlay("po/$ll/$underlay")
207 if -d "$config{underlaydirbase}/po/$ll/$underlay";
210 if ($master_language_code ne 'en') {
211 # Add underlay containing translated source files
212 # for the master language.
213 add_underlay("locale/$master_language_code/$underlay")
214 if -d "$config{underlaydirbase}/locale/$master_language_code/$underlay";
220 my $needsbuild=shift;
222 # backup @needsbuild content so that change() can know whether
223 # a given master page was rendered because its source file was changed
224 @origneedsbuild=(@$needsbuild);
227 buildtranslationscache();
229 # make existing translations depend on the corresponding master page
230 foreach my $master (keys %translations) {
231 map add_depends($_, $master), values %{otherlanguages_pages($master)};
239 my $page=$params{page};
240 my $content=$params{content};
241 my $run_by_po=$params{run_by_po};
243 # Massage the recorded state of internal links so that:
244 # - it matches the actually generated links, rather than the links as
245 # written in the pages' source
246 # - backlinks are consistent in all cases
248 # A second scan pass is made over translation pages, so as an
249 # optimization, we only do so on the second pass in this case,
250 # i.e. when this hook is called by itself.
251 if ($run_by_po && istranslation($page)) {
252 # replace the occurence of $destpage in $links{$page}
253 my @orig_links = @{$links{$page}};
255 foreach my $destpage (@orig_links) {
256 if (istranslatedto($destpage, lang($page))) {
257 add_link($page, $destpage . '.' . lang($page));
260 add_link($page, $destpage);
264 # No second scan pass is done for a non-translation page, so
265 # links massaging must happen on first pass in this case.
266 elsif (! $run_by_po && ! istranslatable($page) && ! istranslation($page)) {
267 foreach my $destpage (@{$links{$page}}) {
268 if (istranslatable($destpage)) {
269 # make sure any destpage's translations has
270 # $page in its backlinks
271 foreach my $link (values %{otherlanguages_pages($destpage)}) {
272 add_link($page, $link);
278 # Re-run the preprocess hooks in scan mode, then the scan hooks,
279 # over the po-to-markup converted content
280 return if $run_by_po; # avoid looping endlessly
281 return unless istranslation($page);
282 $content = po_to_markup($page, $content);
284 IkiWiki::preprocess($page, $page, $content, 1);
285 IkiWiki::run_hooks(scan => sub {
294 # We use filter to convert PO to the master page's format,
295 # since the rest of ikiwiki should not work on PO files.
299 my $page = $params{page};
300 my $destpage = $params{destpage};
301 my $content = $params{content};
302 if (istranslation($page) && ! alreadyfiltered($page, $destpage)) {
303 $content = po_to_markup($page, $content);
304 setalreadyfiltered($page, $destpage);
312 my $page = $params{page};
313 my $content = $params{content};
315 # ignore PO files this plugin did not create
316 return $content unless istranslation($page);
318 # force content to be htmlize'd as if it was the same type as the master page
319 return IkiWiki::htmlize($page, $page,
320 pagetype(srcfile($pagesources{masterpage($page)})),
324 sub pagetemplate (@) {
326 my $page=$params{page};
327 my $destpage=$params{destpage};
328 my $template=$params{template};
330 my ($masterpage, $lang) = istranslation($page);
332 if (istranslation($page) && $template->query(name => "percenttranslated")) {
333 $template->param(percenttranslated => percenttranslated($page));
335 if ($template->query(name => "istranslation")) {
336 $template->param(istranslation => scalar istranslation($page));
338 if ($template->query(name => "istranslatable")) {
339 $template->param(istranslatable => istranslatable($page));
341 if ($template->query(name => "HOMEPAGEURL")) {
342 $template->param(homepageurl => homepageurl($page));
344 if ($template->query(name => "otherlanguages")) {
345 $template->param(otherlanguages => [otherlanguagesloop($page)]);
346 map add_depends($page, $_), (values %{otherlanguages_pages($page)});
348 if ($config{discussion} && istranslation($page)) {
349 if ($page !~ /.*\/\Q$config{discussionpage}\E$/i &&
350 (length $config{cgiurl} ||
351 exists $links{$masterpage."/".lc($config{discussionpage})})) {
352 $template->param('discussionlink' => htmllink(
355 $masterpage . '/' . $config{discussionpage},
358 linktext => $config{discussionpage},
362 # Remove broken parentlink to ./index.html on home page's translations.
363 # It works because this hook has the "last" parameter set, to ensure it
364 # runs after parentlinks' own pagetemplate hook.
365 if ($template->param('parentlinks')
366 && istranslation($page)
367 && $masterpage eq "index") {
368 $template->param('parentlinks' => []);
370 if (ishomepage($page) && $template->query(name => "title")) {
371 $template->param(title => $config{wikiname});
375 # Add the renamed page translations to the list of to-be-renamed pages.
376 sub renamepages (@) {
379 my %torename = %{$params{torename}};
380 my $session = $params{session};
382 # Save the page(s) the user asked to rename, so that our
383 # canrename hook can tell the difference between:
384 # - a translation being renamed as a consequence of its master page
386 # - a user trying to directly rename a translation
387 # This is why this hook has to be run first, before the list of pages
388 # to rename is modified by other plugins.
390 @orig_torename=@{$session->param("po_orig_torename")}
391 if defined $session->param("po_orig_torename");
392 push @orig_torename, $torename{src};
393 $session->param(po_orig_torename => \@orig_torename);
394 IkiWiki::cgi_savesession($session);
396 return () unless istranslatable($torename{src});
399 my %otherpages=%{otherlanguages_pages($torename{src})};
400 while (my ($lang, $otherpage) = each %otherpages) {
403 srcfile => $pagesources{$otherpage},
404 dest => otherlanguage_page($torename{dest}, $lang),
405 destfile => $torename{dest}.".".$lang.".po",
415 map { deletetranslations($_) } grep istranslatablefile($_), @deleted;
421 my $updated_po_files=0;
423 # Refresh/create POT and PO files as needed.
424 foreach my $file (grep {istranslatablefile($_)} @rendered) {
425 my $masterfile=srcfile($file);
426 my $page=pagename($file);
427 my $updated_pot_file=0;
429 # Avoid touching underlay files.
430 next if $masterfile ne "$config{srcdir}/$file";
432 # Only refresh POT file if it does not exist, or if
433 # the source was changed: don't if only the HTML was
434 # refreshed, e.g. because of a dependency.
435 if ((grep { $_ eq $pagesources{$page} } @origneedsbuild) ||
436 ! -e potfile($masterfile)) {
437 refreshpot($masterfile);
441 foreach my $po (pofiles($masterfile)) {
442 next if ! $updated_pot_file && -e $po;
443 next if grep { $po=~/\Q$_\E/ } @{$config{underlaydirs}};
447 refreshpofiles($masterfile, @pofiles);
448 map { s/^\Q$config{srcdir}\E\/*//; IkiWiki::rcs_add($_) } @pofiles if $config{rcs};
453 if ($updated_po_files) {
455 gettext("updated PO files"));
459 sub checkcontent (@) {
462 if (istranslation($params{page})) {
463 my $res = isvalidpo($params{content});
477 if (istranslation($params{page})) {
478 return gettext("Can not remove a translation. If the master page is removed, ".
479 "however, its translations will be removed as well.");
486 my $session = $params{session};
488 if (istranslation($params{src})) {
489 my $masterpage = masterpage($params{src});
490 # Tell the difference between:
491 # - a translation being renamed as a consequence of its master page
492 # being renamed, which is allowed
493 # - a user trying to directly rename a translation, which is forbidden
494 # by looking for the master page in the list of to-be-renamed pages we
495 # saved early in the renaming process.
496 my $orig_torename = $session->param("po_orig_torename");
497 unless (grep { $_ eq $masterpage } @{$orig_torename}) {
498 return gettext("Can not rename a translation. If the master page is renamed, ".
499 "however, its translations will be renamed as well.");
505 # As we're previewing or saving a page, the content may have
506 # changed, so tell the next filter() invocation it must not be lazy.
510 unsetalreadyfiltered($params{page}, $params{page});
511 return $params{content};
514 sub formbuilder_setup (@) {
516 my $form=$params{form};
519 return unless defined $form->field("do");
521 if ($form->field("do") eq "create") {
522 # Warn the user: new pages must be written in master language.
523 my $template=template("pocreatepage.tmpl");
524 $template->param(LANG => $master_language_name);
525 $form->tmpl_param(message => $template->output);
527 elsif ($form->field("do") eq "edit") {
528 # Remove the rename/remove buttons on slave pages.
529 # This has to be done after the rename/remove plugins have added
530 # their buttons, which is why this hook must be run last.
531 # The canrename/canremove hooks already ensure this is forbidden
532 # at the backend level, so this is only UI sugar.
533 if (istranslation($form->field("page"))) {
535 for (my $i = 0; $i < @{$params{buttons}}; $i++) {
536 if (@{$params{buttons}}[$i] eq $_) {
537 delete @{$params{buttons}}[$i];
546 sub formbuilder (@) {
548 my $form=$params{form};
551 return unless defined $form->field("do");
553 # Do not allow to create pages of type po: they are automatically created.
554 # The main reason to do so is to bypass the "favor the type of linking page
555 # on page creation" logic, which is unsuitable when a broken link is clicked
556 # on a slave (PO) page.
557 # This cannot be done in the formbuilder_setup hook as the list of types is
559 if ($form->field("do") eq "create") {
560 foreach my $field ($form->field) {
561 next unless "$field" eq "type";
562 next unless $field->type eq 'select';
563 my $orig_value = $field->value;
564 # remove po from the list of types
565 my @types = grep { $_->[0] ne 'po' } $field->options;
566 $field->options(\@types) if @types;
567 # favor the type of linking page's masterpage
568 if ($orig_value eq 'po') {
570 if (defined $form->field('from')) {
571 ($from)=$form->field('from')=~/$config{wiki_file_regexp}/;
572 $from = masterpage($from);
574 if (defined $from && exists $pagesources{$from}) {
575 $type=pagetype($pagesources{$from});
577 $type=$config{default_pageext} unless defined $type;
578 $field->value($type) ;
585 # | Injected functions
588 # Implement po_link_to 'current' and 'negotiated' settings.
589 sub mybestlink ($$) {
593 return $origsubs{'bestlink'}->($page, $link)
594 if defined $config{po_link_to} && $config{po_link_to} eq "default";
596 my $res=$origsubs{'bestlink'}->(masterpage($page), $link);
597 my @caller = caller(1);
599 && istranslatedto($res, lang($page))
600 && istranslation($page)
601 && !(exists $caller[3] && defined $caller[3]
602 && ($caller[3] eq "IkiWiki::PageSpec::match_link"))) {
603 return $res . "." . lang($page);
608 sub mybeautify_urlpath ($) {
611 my $res=$origsubs{'beautify_urlpath'}->($url);
612 if (defined $config{po_link_to} && $config{po_link_to} eq "negotiated") {
613 $res =~ s!/\Qindex.$master_language_code.$config{htmlext}\E$!/!;
614 $res =~ s!/\Qindex.$config{htmlext}\E$!/!;
616 $res =~ s!/\Qindex.$_.$config{htmlext}\E$!/!;
622 sub mytargetpage ($$) {
626 if (istranslation($page) || istranslatable($page)) {
627 my ($masterpage, $lang) = (masterpage($page), lang($page));
628 if (! $config{usedirs} || $masterpage eq 'index') {
629 return $masterpage . "." . $lang . "." . $ext;
632 return $masterpage . "/index." . $lang . "." . $ext;
635 return $origsubs{'targetpage'}->($page, $ext);
643 # workaround hard-coded /index.$config{htmlext} in IkiWiki::urlto()
645 && $config{po_link_to} eq "current"
646 && istranslatable('index')) {
647 return IkiWiki::beautify_urlpath(IkiWiki::baseurl($from) . "index." . lang($from) . ".$config{htmlext}");
649 # avoid using our injected beautify_urlpath if run by cgi_editpage,
650 # so that one is redirected to the just-edited page rather than to the
651 # negociated translation; to prevent unnecessary fiddling with caller/inject,
652 # we only do so when our beautify_urlpath would actually do what we want to
653 # avoid, i.e. when po_link_to = negotiated.
654 # also avoid doing so when run by cgi_goto, so that the links on recentchanges
655 # page actually lead to the exact page they pretend to.
656 if ($config{po_link_to} eq "negotiated") {
657 my @caller = caller(1);
659 $use_orig = 1 if (exists $caller[3] && defined $caller[3]
660 && ($caller[3] eq "IkiWiki::cgi_editpage" ||
661 $caller[3] eq "IkiWiki::Plugin::goto::cgi_goto")
663 inject(name => "IkiWiki::beautify_urlpath", call => $origsubs{'beautify_urlpath'})
665 my $res = $origsubs{'urlto'}->($to,$from,$absolute);
666 inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath)
671 return $origsubs{'urlto'}->($to,$from,$absolute)
678 # slave pages have no subpages
679 if (istranslation($params{'from'})) {
680 $params{'from'} = masterpage($params{'from'});
682 return $origsubs{'cgiurl'}->(%params);
689 if (exists $params{rootpage}) {
690 $rootpage=$origsubs{'bestlink'}->($params{page}, $params{rootpage});
691 if (!length $rootpage) {
692 $rootpage=$params{rootpage};
696 $rootpage=masterpage($params{page});
701 sub myisselflink ($$) {
705 return 1 if $origsubs{'isselflink'}->($page, $link);
706 if (istranslation($page)) {
707 return $origsubs{'isselflink'}->(masterpage($page), $link);
713 # | Blackboxes for private data
719 sub alreadyfiltered($$) {
723 return exists $filtered{$page}{$destpage}
724 && $filtered{$page}{$destpage} eq 1;
727 sub setalreadyfiltered($$) {
731 $filtered{$page}{$destpage}=1;
734 sub unsetalreadyfiltered($$) {
738 if (exists $filtered{$page}{$destpage}) {
739 delete $filtered{$page}{$destpage};
743 sub resetalreadyfiltered() {
752 sub maybe_add_leading_slash ($;$) {
755 $add=1 unless defined $add;
756 return '/' . $str if $add;
760 sub istranslatablefile ($) {
763 return 0 unless defined $file;
764 my $type=pagetype($file);
765 return 0 if ! defined $type || $type eq 'po';
766 return 0 if $file =~ /\.pot$/;
767 return 0 if ! defined $config{po_translatable_pages};
768 return 1 if pagespec_match(pagename($file), $config{po_translatable_pages});
772 sub istranslatable ($) {
776 return 1 if istranslatablefile($pagesources{$page});
780 sub istranslatedto ($$) {
782 my $destlang = shift;
785 return 0 unless istranslatable($page);
786 exists $pagesources{otherlanguage_page($page, $destlang)};
789 sub _istranslation ($) {
792 $page='' unless defined $page && length $page;
793 my $hasleadingslash = ($page=~s#^/##);
794 my $file=$pagesources{$page};
795 return 0 unless defined $file
796 && defined pagetype($file)
797 && pagetype($file) eq 'po';
798 return 0 if $file =~ /\.pot$/;
800 my ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
801 return 0 unless defined $masterpage && defined $lang
802 && length $masterpage && length $lang
803 && defined $pagesources{$masterpage}
804 && defined $slavelanguages{$lang};
806 return (maybe_add_leading_slash($masterpage, $hasleadingslash), $lang)
807 if istranslatable($masterpage);
810 sub istranslation ($) {
813 if (1 < (my ($masterpage, $lang) = _istranslation($page))) {
814 my $hasleadingslash = ($masterpage=~s#^/##);
815 $translations{$masterpage}{$lang}=$page unless exists $translations{$masterpage}{$lang};
816 return (maybe_add_leading_slash($masterpage, $hasleadingslash), $lang);
824 if ( 1 < (my ($masterpage, $lang) = _istranslation($page))) {
833 if (1 < (my ($masterpage, $lang) = _istranslation($page))) {
836 return $master_language_code;
839 sub islanguagecode ($) {
842 return $code =~ /^[a-z]{2}$/;
845 sub otherlanguage_page ($$) {
849 return masterpage($page) if $code eq $master_language_code;
850 return masterpage($page) . '.' . $code;
853 # Returns the list of other languages codes: the master language comes first,
854 # then the codes are ordered the same way as in po_slave_languages, if it is
855 # an array, or in the language name lexical order, if it is a hash.
856 sub otherlanguages_codes ($) {
860 return \@ret unless istranslation($page) || istranslatable($page);
861 my $curlang=lang($page);
863 ($master_language_code, @slavelanguages) {
864 next if $lang eq $curlang;
865 if ($lang eq $master_language_code ||
866 istranslatedto(masterpage($page), $lang)) {
873 sub otherlanguages_pages ($) {
878 $ret{$_} = otherlanguage_page($page, $_)
879 } @{otherlanguages_codes($page)};
885 my $masterfile=shift;
887 (my $name, my $dir, my $suffix) = fileparse($masterfile, qr/\.[^.]*/);
888 $dir='' if $dir eq './';
889 return File::Spec->catpath('', $dir, $name . ".pot");
893 my $masterfile=shift;
896 (my $name, my $dir, my $suffix) = fileparse($masterfile, qr/\.[^.]*/);
897 $dir='' if $dir eq './';
898 return File::Spec->catpath('', $dir, $name . "." . $lang . ".po");
902 my $masterfile=shift;
904 return map pofile($masterfile, $_), @slavelanguages;
908 my $masterfile=shift;
910 my $potfile=potfile($masterfile);
911 my $doc=Locale::Po4a::Chooser::new(po4a_type($masterfile),
912 po4a_options($masterfile));
913 $doc->{TT}{utf_mode} = 1;
914 $doc->{TT}{file_in_charset} = 'UTF-8';
915 $doc->{TT}{file_out_charset} = 'UTF-8';
916 $doc->read($masterfile);
917 # let's cheat a bit to force porefs option to be passed to
918 # Locale::Po4a::Po; this is undocument use of internal
919 # Locale::Po4a::TransTractor's data, compulsory since this module
920 # prevents us from using the porefs option.
921 $doc->{TT}{po_out}=Locale::Po4a::Po->new({ 'porefs' => 'none' });
922 $doc->{TT}{po_out}->set_charset('UTF-8');
925 IkiWiki::prep_writefile(basename($potfile),dirname($potfile));
926 $doc->writepo($potfile);
929 sub refreshpofiles ($@) {
930 my $masterfile=shift;
933 my $potfile=potfile($masterfile);
935 error("po(refreshpofiles) ".sprintf(gettext("POT file (%s) does not exist"), $potfile));
938 foreach my $pofile (@pofiles) {
939 IkiWiki::prep_writefile(basename($pofile),dirname($pofile));
942 # If the po file exists in an underlay, copy it
944 my ($pobase)=$pofile=~/^\Q$config{srcdir}\E\/?(.*)$/;
945 foreach my $dir (@{$config{underlaydirs}}) {
946 if (-e "$dir/$pobase") {
947 File::Copy::syscopy("$dir/$pobase",$pofile)
948 or error("po(refreshpofiles) ".
949 sprintf(gettext("failed to copy underlay PO file to %s"),
956 system("msgmerge", "--previous", "-q", "-U", "--backup=none", $pofile, $potfile) == 0
957 or error("po(refreshpofiles) ".
958 sprintf(gettext("failed to update %s"),
962 File::Copy::syscopy($potfile,$pofile)
963 or error("po(refreshpofiles) ".
964 sprintf(gettext("failed to copy the POT file to %s"),
970 sub buildtranslationscache() {
971 # use istranslation's side-effect
972 map istranslation($_), (keys %pagesources);
975 sub resettranslationscache() {
979 sub flushmemoizecache() {
980 Memoize::flush_cache("istranslatable");
981 Memoize::flush_cache("_istranslation");
982 Memoize::flush_cache("percenttranslated");
985 sub urlto_with_orig_beautiful_urlpath($$) {
989 inject(name => "IkiWiki::beautify_urlpath", call => $origsubs{'beautify_urlpath'});
990 my $res=urlto($to, $from);
991 inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath);
996 sub percenttranslated ($) {
1000 return gettext("N/A") unless istranslation($page);
1001 my $file=srcfile($pagesources{$page});
1002 my $masterfile = srcfile($pagesources{masterpage($page)});
1003 my $doc=Locale::Po4a::Chooser::new(po4a_type($masterfile),
1004 po4a_options($masterfile));
1006 'po_in_name' => [ $file ],
1007 'file_in_name' => [ $masterfile ],
1008 'file_in_charset' => 'UTF-8',
1009 'file_out_charset' => 'UTF-8',
1010 ) or error("po(percenttranslated) ".
1011 sprintf(gettext("failed to translate %s"), $page));
1012 my ($percent,$hit,$queries) = $doc->stats();
1013 $percent =~ s/\.[0-9]+$//;
1017 sub languagename ($) {
1020 return $master_language_name
1021 if $code eq $master_language_code;
1022 return $slavelanguages{$code}
1023 if defined $slavelanguages{$code};
1027 sub otherlanguagesloop ($) {
1031 if (istranslation($page)) {
1033 url => urlto_with_orig_beautiful_urlpath(masterpage($page), $page),
1034 code => $master_language_code,
1035 language => $master_language_name,
1039 foreach my $lang (@{otherlanguages_codes($page)}) {
1040 next if $lang eq $master_language_code;
1041 my $otherpage = otherlanguage_page($page, $lang);
1043 url => urlto_with_orig_beautiful_urlpath($otherpage, $page),
1045 language => languagename($lang),
1046 percent => percenttranslated($otherpage),
1052 sub homepageurl (;$) {
1055 return urlto('', $page);
1058 sub ishomepage ($) {
1061 return 1 if $page eq 'index';
1062 map { return 1 if $page eq 'index.'.$_ } @slavelanguages;
1066 sub deletetranslations ($) {
1067 my $deletedmasterfile=shift;
1069 my $deletedmasterpage=pagename($deletedmasterfile);
1072 my $file = newpagefile($deletedmasterpage.'.'.$_, 'po');
1073 my $absfile = "$config{srcdir}/$file";
1074 if (-e $absfile && ! -l $absfile && ! -d $absfile) {
1075 push @todelete, $file;
1081 IkiWiki::rcs_remove($_);
1084 IkiWiki::prune("$config{srcdir}/$_");
1090 gettext("removed obsolete PO files"));
1094 sub commit_and_refresh ($) {
1098 IkiWiki::disable_commit_hook();
1099 IkiWiki::rcs_commit_staged(
1102 IkiWiki::enable_commit_hook();
1103 IkiWiki::rcs_update();
1105 # Reinitialize module's private variables.
1106 resetalreadyfiltered();
1107 resettranslationscache();
1108 flushmemoizecache();
1109 # Trigger a wiki refresh.
1110 require IkiWiki::Render;
1111 # without preliminary saveindex/loadindex, refresh()
1112 # complains about a lot of uninitialized variables
1113 IkiWiki::saveindex();
1114 IkiWiki::loadindex();
1116 IkiWiki::saveindex();
1119 sub po_to_markup ($$) {
1120 my ($page, $content) = (shift, shift);
1122 $content = '' unless defined $content;
1123 $content = decode_utf8(encode_utf8($content));
1124 # CRLF line terminators make poor Locale::Po4a feel bad
1125 $content=~s/\r\n/\n/g;
1127 # There are incompatibilities between some File::Temp versions
1128 # (including 0.18, bundled with Lenny's perl-modules package)
1129 # and others (e.g. 0.20, previously present in the archive as
1130 # a standalone package): under certain circumstances, some
1131 # return a relative filename, whereas others return an absolute one;
1132 # we here use this module in a way that is at least compatible
1133 # with 0.18 and 0.20. Beware, hit'n'run refactorers!
1134 my $infile = new File::Temp(TEMPLATE => "ikiwiki-po-filter-in.XXXXXXXXXX",
1135 DIR => File::Spec->tmpdir,
1136 UNLINK => 1)->filename;
1137 my $outfile = new File::Temp(TEMPLATE => "ikiwiki-po-filter-out.XXXXXXXXXX",
1138 DIR => File::Spec->tmpdir,
1139 UNLINK => 1)->filename;
1141 my $fail = sub ($) {
1142 my $msg = "po(po_to_markup) - $page : " . shift;
1143 error($msg, sub { unlink $infile, $outfile});
1146 writefile(basename($infile), File::Spec->tmpdir, $content)
1147 or return $fail->(sprintf(gettext("failed to write %s"), $infile));
1149 my $masterfile = srcfile($pagesources{masterpage($page)});
1150 my $doc=Locale::Po4a::Chooser::new(po4a_type($masterfile),
1151 po4a_options($masterfile));
1153 'po_in_name' => [ $infile ],
1154 'file_in_name' => [ $masterfile ],
1155 'file_in_charset' => 'UTF-8',
1156 'file_out_charset' => 'UTF-8',
1157 ) or return $fail->(gettext("failed to translate"));
1158 $doc->write($outfile)
1159 or return $fail->(sprintf(gettext("failed to write %s"), $outfile));
1161 $content = readfile($outfile);
1163 # Unlinking should happen automatically, thanks to File::Temp,
1164 # but it does not work here, probably because of the way writefile()
1165 # and Locale::Po4a::write() work.
1166 unlink $infile, $outfile;
1171 # returns a SuccessReason or FailReason object
1173 my $content = shift;
1175 # NB: we don't use po_to_markup here, since Po4a parser does
1176 # not mind invalid PO content
1177 $content = '' unless defined $content;
1178 $content = decode_utf8(encode_utf8($content));
1180 # There are incompatibilities between some File::Temp versions
1181 # (including 0.18, bundled with Lenny's perl-modules package)
1182 # and others (e.g. 0.20, previously present in the archive as
1183 # a standalone package): under certain circumstances, some
1184 # return a relative filename, whereas others return an absolute one;
1185 # we here use this module in a way that is at least compatible
1186 # with 0.18 and 0.20. Beware, hit'n'run refactorers!
1187 my $infile = new File::Temp(TEMPLATE => "ikiwiki-po-isvalidpo.XXXXXXXXXX",
1188 DIR => File::Spec->tmpdir,
1189 UNLINK => 1)->filename;
1191 my $fail = sub ($) {
1192 my $msg = '[po/isvalidpo] ' . shift;
1194 return IkiWiki::FailReason->new("$msg");
1197 writefile(basename($infile), File::Spec->tmpdir, $content)
1198 or return $fail->(sprintf(gettext("failed to write %s"), $infile));
1200 my $res = (system("msgfmt", "--check", $infile, "-o", "/dev/null") == 0);
1202 # Unlinking should happen automatically, thanks to File::Temp,
1203 # but it does not work here, probably because of the way writefile()
1204 # and Locale::Po4a::write() work.
1208 return IkiWiki::SuccessReason->new("valid gettext data");
1210 return IkiWiki::FailReason->new(gettext("invalid gettext data, go back ".
1211 "to previous page to continue edit"));
1217 my $pagetype = pagetype($file);
1218 if ($pagetype eq 'html') {
1224 sub po4a_options($) {
1228 my $pagetype = pagetype($file);
1230 if ($pagetype eq 'html') {
1231 # how to disable options is not consistent across po4a modules
1232 $options{includessi} = '';
1233 $options{includeexternal} = 0;
1235 elsif ($pagetype eq 'mdwn') {
1236 $options{markdown} = 1;
1239 $options{markdown} = 0;
1245 sub splitlangpair ($) {
1248 my ($code, $name) = ( $pair =~ /^([a-z]{2})\|(.+)$/ );
1249 if (! defined $code || ! defined $name ||
1250 ! length $code || ! length $name) {
1251 # not a fatal error to avoid breaking if used with web setup
1252 warn sprintf(gettext("%s has invalid syntax: must use CODE|NAME"),
1256 return $code, $name;
1259 sub joinlangpair ($$) {
1263 return "$code|$name";
1270 package IkiWiki::PageSpec;
1272 sub match_istranslation ($;@) {
1275 if (IkiWiki::Plugin::po::istranslation($page)) {
1276 return IkiWiki::SuccessReason->new("is a translation page");
1279 return IkiWiki::FailReason->new("is not a translation page");
1283 sub match_istranslatable ($;@) {
1286 if (IkiWiki::Plugin::po::istranslatable($page)) {
1287 return IkiWiki::SuccessReason->new("is set as translatable in po_translatable_pages");
1290 return IkiWiki::FailReason->new("is not set as translatable in po_translatable_pages");
1294 sub match_lang ($$;@) {
1298 my $regexp=IkiWiki::glob2re($wanted);
1299 my $lang=IkiWiki::Plugin::po::lang($page);
1300 if ($lang !~ /^$regexp$/i) {
1301 return IkiWiki::FailReason->new("file language is $lang, not $wanted");
1304 return IkiWiki::SuccessReason->new("file language is $wanted");
1308 sub match_currentlang ($$;@) {
1313 return IkiWiki::FailReason->new("no location provided") unless exists $params{location};
1315 my $currentlang=IkiWiki::Plugin::po::lang($params{location});
1316 my $lang=IkiWiki::Plugin::po::lang($page);
1318 if ($lang eq $currentlang) {
1319 return IkiWiki::SuccessReason->new("file language is the same as current one, i.e. $currentlang");
1322 return IkiWiki::FailReason->new("file language is $lang, whereas current language is $currentlang");
1326 sub match_needstranslation ($$;@) {
1330 if (defined $wanted && $wanted ne "") {
1331 if ($wanted !~ /^\d+$/) {
1332 return IkiWiki::FailReason->new("parameter is not an integer");
1334 elsif ($wanted > 100) {
1335 return IkiWiki::FailReason->new("parameter is greater than 100");
1342 my $percenttranslated=IkiWiki::Plugin::po::percenttranslated($page);
1343 if ($percenttranslated eq 'N/A') {
1344 return IkiWiki::FailReason->new("file is not a translatable page");
1346 elsif ($percenttranslated < $wanted) {
1347 return IkiWiki::SuccessReason->new("file has $percenttranslated translated");
1350 return IkiWiki::FailReason->new("file is translated enough");