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;
32 memoize("istranslatable");
33 memoize("_istranslation");
34 memoize("percenttranslated");
37 hook(type => "getsetup", id => "po", call => \&getsetup);
38 hook(type => "checkconfig", id => "po", call => \&checkconfig);
39 hook(type => "needsbuild", id => "po", call => \&needsbuild);
40 hook(type => "scan", id => "po", call => \&scan, last => 1);
41 hook(type => "filter", id => "po", call => \&filter);
42 hook(type => "htmlize", id => "po", call => \&htmlize);
43 hook(type => "pagetemplate", id => "po", call => \&pagetemplate, last => 1);
44 hook(type => "rename", id => "po", call => \&renamepages, first => 1);
45 hook(type => "delete", id => "po", call => \&mydelete);
46 hook(type => "change", id => "po", call => \&change);
47 hook(type => "checkcontent", id => "po", call => \&checkcontent);
48 hook(type => "canremove", id => "po", call => \&canremove);
49 hook(type => "canrename", id => "po", call => \&canrename);
50 hook(type => "editcontent", id => "po", call => \&editcontent);
51 hook(type => "formbuilder_setup", id => "po", call => \&formbuilder_setup, last => 1);
52 hook(type => "formbuilder", id => "po", call => \&formbuilder);
55 $origsubs{'bestlink'}=\&IkiWiki::bestlink;
56 inject(name => "IkiWiki::bestlink", call => \&mybestlink);
57 $origsubs{'beautify_urlpath'}=\&IkiWiki::beautify_urlpath;
58 inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath);
59 $origsubs{'targetpage'}=\&IkiWiki::targetpage;
60 inject(name => "IkiWiki::targetpage", call => \&mytargetpage);
61 $origsubs{'urlto'}=\&IkiWiki::urlto;
62 inject(name => "IkiWiki::urlto", call => \&myurlto);
63 $origsubs{'cgiurl'}=\&IkiWiki::cgiurl;
64 inject(name => "IkiWiki::cgiurl", call => \&mycgiurl);
65 $origsubs{'rootpage'}=\&IkiWiki::rootpage;
66 inject(name => "IkiWiki::rootpage", call => \&myrootpage);
67 $origsubs{'isselflink'}=\&IkiWiki::isselflink;
68 inject(name => "IkiWiki::isselflink", call => \&myisselflink);
78 # 2. Injected functions
79 # 3. Blackboxes for private data
92 rebuild => 1, # format plugin
95 po_master_language => {
101 description => "master language (non-PO files)",
105 po_slave_languages => {
112 description => "slave languages (PO files)",
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 foreach my $field (qw{po_master_language}) {
135 if (! exists $config{$field} || ! defined $config{$field}) {
136 error(sprintf(gettext("Must specify %s when using the %s plugin"),
140 delete $config{po_slave_languages}{$config{po_master_language}{code}};;
144 or error(sprintf(gettext("%s is not a valid language code"), $_));
145 } ($config{po_master_language}{code}, keys %{$config{po_slave_languages}});
147 if (! exists $config{po_translatable_pages} ||
148 ! defined $config{po_translatable_pages}) {
149 $config{po_translatable_pages}="";
151 if (! exists $config{po_link_to} ||
152 ! defined $config{po_link_to}) {
153 $config{po_link_to}='default';
155 elsif ($config{po_link_to} !~ /^(default|current|negotiated)$/) {
156 warn(sprintf(gettext('%s is not a valid value for po_link_to, falling back to po_link_to=default'),
157 $config{po_link_to}));
158 $config{po_link_to}='default';
160 elsif ($config{po_link_to} eq "negotiated" && ! $config{usedirs}) {
161 warn(gettext('po_link_to=negotiated requires usedirs to be enabled, falling back to po_link_to=default'));
162 $config{po_link_to}='default';
165 push @{$config{wiki_file_prune_regexps}}, qr/\.pot$/;
167 # Translated versions of the underlays are added if available.
168 foreach my $underlay ("basewiki",
169 map { m/^\Q$config{underlaydirbase}\E\/*(.*)/ }
170 reverse @{$config{underlaydirs}}) {
171 next if $underlay=~/^locale\//;
173 # Underlays containing the po files for slave languages.
174 foreach my $ll (keys %{$config{po_slave_languages}}) {
175 add_underlay("po/$ll/$underlay")
176 if -d "$config{underlaydirbase}/po/$ll/$underlay";
179 if ($config{po_master_language}{code} ne 'en') {
180 # Add underlay containing translated source files
181 # for the master language.
182 add_underlay("locale/$config{po_master_language}{code}/$underlay")
183 if -d "$config{underlaydirbase}/locale/$config{po_master_language}{code}/$underlay";
189 my $needsbuild=shift;
191 # backup @needsbuild content so that change() can know whether
192 # a given master page was rendered because its source file was changed
193 @origneedsbuild=(@$needsbuild);
196 buildtranslationscache();
198 # make existing translations depend on the corresponding master page
199 foreach my $master (keys %translations) {
200 map add_depends($_, $master), values %{otherlanguages($master)};
204 # Massage the recorded state of internal links so that:
205 # - it matches the actually generated links, rather than the links as written
206 # in the pages' source
207 # - backlinks are consistent in all cases
210 my $page=$params{page};
211 my $content=$params{content};
213 if (istranslation($page)) {
214 foreach my $destpage (@{$links{$page}}) {
215 if (istranslatable($destpage)) {
216 # replace the occurence of $destpage in $links{$page}
217 for (my $i=0; $i<@{$links{$page}}; $i++) {
218 if (@{$links{$page}}[$i] eq $destpage) {
219 @{$links{$page}}[$i] = $destpage . '.' . lang($page);
226 elsif (! istranslatable($page) && ! istranslation($page)) {
227 foreach my $destpage (@{$links{$page}}) {
228 if (istranslatable($destpage)) {
229 # make sure any destpage's translations has
230 # $page in its backlinks
231 push @{$links{$page}},
232 values %{otherlanguages($destpage)};
238 # We use filter to convert PO to the master page's format,
239 # since the rest of ikiwiki should not work on PO files.
243 my $page = $params{page};
244 my $destpage = $params{destpage};
245 my $content = $params{content};
247 my @caller = caller(4);
248 unless ($caller[3] eq "IkiWiki::render" ||
249 $caller[3] eq 'IkiWiki::Plugin::sidebar::sidebar_content') {
253 if (istranslation($page) && ! alreadyfiltered($page, $destpage)) {
254 $content = po_to_markup($page, $content);
255 setalreadyfiltered($page, $destpage);
263 my $page = $params{page};
264 my $content = $params{content};
266 # ignore PO files this plugin did not create
267 return $content unless istranslation($page);
269 # force content to be htmlize'd as if it was the same type as the master page
270 return IkiWiki::htmlize($page, $page,
271 pagetype(srcfile($pagesources{masterpage($page)})),
275 sub pagetemplate (@) {
277 my $page=$params{page};
278 my $destpage=$params{destpage};
279 my $template=$params{template};
281 my ($masterpage, $lang) = istranslation($page);
283 if (istranslation($page) && $template->query(name => "percenttranslated")) {
284 $template->param(percenttranslated => percenttranslated($page));
286 if ($template->query(name => "istranslation")) {
287 $template->param(istranslation => scalar istranslation($page));
289 if ($template->query(name => "istranslatable")) {
290 $template->param(istranslatable => istranslatable($page));
292 if ($template->query(name => "HOMEPAGEURL")) {
293 $template->param(homepageurl => homepageurl($page));
295 if ($template->query(name => "otherlanguages")) {
296 $template->param(otherlanguages => [otherlanguagesloop($page)]);
297 map add_depends($page, $_), (values %{otherlanguages($page)});
299 if ($config{discussion} && istranslation($page)) {
300 if ($page !~ /.*\/\Q$config{discussionpage}\E$/i &&
301 (length $config{cgiurl} ||
302 exists $links{$masterpage."/".lc($config{discussionpage})})) {
303 $template->param('discussionlink' => htmllink(
306 $masterpage . '/' . $config{discussionpage},
309 linktext => $config{discussionpage},
313 # Remove broken parentlink to ./index.html on home page's translations.
314 # It works because this hook has the "last" parameter set, to ensure it
315 # runs after parentlinks' own pagetemplate hook.
316 if ($template->param('parentlinks')
317 && istranslation($page)
318 && $masterpage eq "index") {
319 $template->param('parentlinks' => []);
321 if (ishomepage($page) && $template->query(name => "title")) {
322 $template->param(title => $config{wikiname});
326 # Add the renamed page translations to the list of to-be-renamed pages.
327 sub renamepages (@) {
330 my %torename = %{$params{torename}};
331 my $session = $params{session};
333 # Save the page(s) the user asked to rename, so that our
334 # canrename hook can tell the difference between:
335 # - a translation being renamed as a consequence of its master page
337 # - a user trying to directly rename a translation
338 # This is why this hook has to be run first, before the list of pages
339 # to rename is modified by other plugins.
341 @orig_torename=@{$session->param("po_orig_torename")}
342 if defined $session->param("po_orig_torename");
343 push @orig_torename, $torename{src};
344 $session->param(po_orig_torename => \@orig_torename);
345 IkiWiki::cgi_savesession($session);
347 return () unless istranslatable($torename{src});
350 my %otherpages=%{otherlanguages($torename{src})};
351 while (my ($lang, $otherpage) = each %otherpages) {
354 srcfile => $pagesources{$otherpage},
355 dest => otherlanguage($torename{dest}, $lang),
356 destfile => $torename{dest}.".".$lang.".po",
366 map { deletetranslations($_) } grep istranslatablefile($_), @deleted;
372 # All meta titles are first extracted at scan time, i.e. before we turn
373 # PO files back into translated markdown; escaping of double-quotes in
374 # PO files breaks the meta plugin's parsing enough to save ugly titles
375 # to %pagestate at this time.
377 # Then, at render time, every page passes in turn through the Great
378 # Rendering Chain (filter->preprocess->linkify->htmlize), and the meta
379 # plugin's preprocess hook is this time in a position to correctly
380 # extract the titles from slave pages.
382 # This is, unfortunately, too late: if the page A, linking to the page
383 # B, is rendered before B, it will display the wrongly-extracted meta
384 # title as the link text to B.
386 # On the one hand, such a corner case only happens on rebuild: on
387 # refresh, every rendered page is fixed to contain correct meta titles.
388 # On the other hand, it can take some time to get every page fixed.
389 # We therefore re-render every rendered page after a rebuild to fix them
390 # at once. As this more or less doubles the time needed to rebuild the
391 # wiki, we do so only when really needed.
394 && exists $config{rebuild} && defined $config{rebuild} && $config{rebuild}
395 && UNIVERSAL::can("IkiWiki::Plugin::meta", "getsetup")
396 && exists $config{meta_overrides_page_title}
397 && defined $config{meta_overrides_page_title}
398 && $config{meta_overrides_page_title}) {
399 debug(sprintf(gettext("rebuilding all pages to fix meta titles")));
400 resetalreadyfiltered();
401 require IkiWiki::Render;
402 foreach my $file (@rendered) {
403 IkiWiki::render($file, sprintf(gettext("building %s"), $file));
407 my $updated_po_files=0;
409 # Refresh/create POT and PO files as needed.
410 foreach my $file (grep {istranslatablefile($_)} @rendered) {
411 my $masterfile=srcfile($file);
412 my $page=pagename($file);
413 my $updated_pot_file=0;
415 # Avoid touching underlay files.
416 next if $masterfile ne "$config{srcdir}/$file";
418 # Only refresh POT file if it does not exist, or if
419 # the source was changed: don't if only the HTML was
420 # refreshed, e.g. because of a dependency.
421 if ((grep { $_ eq $pagesources{$page} } @origneedsbuild) ||
422 ! -e potfile($masterfile)) {
423 refreshpot($masterfile);
427 foreach my $po (pofiles($masterfile)) {
428 next if ! $updated_pot_file && -e $po;
429 next if grep { $po=~/\Q$_\E/ } @{$config{underlaydirs}};
433 refreshpofiles($masterfile, @pofiles);
434 map { s/^\Q$config{srcdir}\E\/*//; IkiWiki::rcs_add($_) } @pofiles if $config{rcs};
439 if ($updated_po_files) {
441 gettext("updated PO files"));
445 sub checkcontent (@) {
448 if (istranslation($params{page})) {
449 my $res = isvalidpo($params{content});
463 if (istranslation($params{page})) {
464 return gettext("Can not remove a translation. If the master page is removed, ".
465 "however, its translations will be removed as well.");
472 my $session = $params{session};
474 if (istranslation($params{src})) {
475 my $masterpage = masterpage($params{src});
476 # Tell the difference between:
477 # - a translation being renamed as a consequence of its master page
478 # being renamed, which is allowed
479 # - a user trying to directly rename a translation, which is forbidden
480 # by looking for the master page in the list of to-be-renamed pages we
481 # saved early in the renaming process.
482 my $orig_torename = $session->param("po_orig_torename");
483 unless (grep { $_ eq $masterpage } @{$orig_torename}) {
484 return gettext("Can not rename a translation. If the master page is renamed, ".
485 "however, its translations will be renamed as well.");
491 # As we're previewing or saving a page, the content may have
492 # changed, so tell the next filter() invocation it must not be lazy.
496 unsetalreadyfiltered($params{page}, $params{page});
497 return $params{content};
500 sub formbuilder_setup (@) {
502 my $form=$params{form};
505 return unless defined $form->field("do");
507 if ($form->field("do") eq "create") {
508 # Warn the user: new pages must be written in master language.
509 my $template=template("pocreatepage.tmpl");
510 $template->param(LANG => $config{po_master_language}{name});
511 $form->tmpl_param(message => $template->output);
513 elsif ($form->field("do") eq "edit") {
514 # Remove the rename/remove buttons on slave pages.
515 # This has to be done after the rename/remove plugins have added
516 # their buttons, which is why this hook must be run last.
517 # The canrename/canremove hooks already ensure this is forbidden
518 # at the backend level, so this is only UI sugar.
519 if (istranslation($form->field("page"))) {
521 for (my $i = 0; $i < @{$params{buttons}}; $i++) {
522 if (@{$params{buttons}}[$i] eq $_) {
523 delete @{$params{buttons}}[$i];
532 sub formbuilder (@) {
534 my $form=$params{form};
537 return unless defined $form->field("do");
539 # Do not allow to create pages of type po: they are automatically created.
540 # The main reason to do so is to bypass the "favor the type of linking page
541 # on page creation" logic, which is unsuitable when a broken link is clicked
542 # on a slave (PO) page.
543 # This cannot be done in the formbuilder_setup hook as the list of types is
545 if ($form->field("do") eq "create") {
546 foreach my $field ($form->field) {
547 next unless "$field" eq "type";
548 next unless $field->type eq 'select';
549 my $orig_value = $field->value;
550 # remove po from the list of types
551 my @types = grep { $_->[0] ne 'po' } $field->options;
552 $field->options(\@types) if @types;
553 # favor the type of linking page's masterpage
554 if ($orig_value eq 'po') {
556 if (defined $form->field('from')) {
557 ($from)=$form->field('from')=~/$config{wiki_file_regexp}/;
558 $from = masterpage($from);
560 if (defined $from && exists $pagesources{$from}) {
561 $type=pagetype($pagesources{$from});
563 $type=$config{default_pageext} unless defined $type;
564 $field->value($type) ;
571 # | Injected functions
574 # Implement po_link_to 'current' and 'negotiated' settings.
575 sub mybestlink ($$) {
579 return $origsubs{'bestlink'}->($page, $link)
580 if defined $config{po_link_to} && $config{po_link_to} eq "default";
582 my $res=$origsubs{'bestlink'}->(masterpage($page), $link);
583 my @caller = caller(1);
585 && istranslatable($res)
586 && istranslation($page)
587 && !(exists $caller[3] && defined $caller[3]
588 && ($caller[3] eq "IkiWiki::PageSpec::match_link"))) {
589 return $res . "." . lang($page);
594 sub mybeautify_urlpath ($) {
597 my $res=$origsubs{'beautify_urlpath'}->($url);
598 if (defined $config{po_link_to} && $config{po_link_to} eq "negotiated") {
599 $res =~ s!/\Qindex.$config{po_master_language}{code}.$config{htmlext}\E$!/!;
600 $res =~ s!/\Qindex.$config{htmlext}\E$!/!;
602 $res =~ s!/\Qindex.$_.$config{htmlext}\E$!/!;
603 } (keys %{$config{po_slave_languages}});
608 sub mytargetpage ($$) {
612 if (istranslation($page) || istranslatable($page)) {
613 my ($masterpage, $lang) = (masterpage($page), lang($page));
614 if (! $config{usedirs} || $masterpage eq 'index') {
615 return $masterpage . "." . $lang . "." . $ext;
618 return $masterpage . "/index." . $lang . "." . $ext;
621 return $origsubs{'targetpage'}->($page, $ext);
629 # workaround hard-coded /index.$config{htmlext} in IkiWiki::urlto()
631 && $config{po_link_to} eq "current"
632 && istranslatable('index')) {
633 return IkiWiki::beautify_urlpath(IkiWiki::baseurl($from) . "index." . lang($from) . ".$config{htmlext}");
635 # avoid using our injected beautify_urlpath if run by cgi_editpage,
636 # so that one is redirected to the just-edited page rather than to the
637 # negociated translation; to prevent unnecessary fiddling with caller/inject,
638 # we only do so when our beautify_urlpath would actually do what we want to
639 # avoid, i.e. when po_link_to = negotiated.
640 # also avoid doing so when run by cgi_goto, so that the links on recentchanges
641 # page actually lead to the exact page they pretend to.
642 if ($config{po_link_to} eq "negotiated") {
643 my @caller = caller(1);
645 $use_orig = 1 if (exists $caller[3] && defined $caller[3]
646 && ($caller[3] eq "IkiWiki::cgi_editpage" ||
647 $caller[3] eq "IkiWiki::Plugin::goto::cgi_goto")
649 inject(name => "IkiWiki::beautify_urlpath", call => $origsubs{'beautify_urlpath'})
651 my $res = $origsubs{'urlto'}->($to,$from,$absolute);
652 inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath)
657 return $origsubs{'urlto'}->($to,$from,$absolute)
664 # slave pages have no subpages
665 if (istranslation($params{'from'})) {
666 $params{'from'} = masterpage($params{'from'});
668 return $origsubs{'cgiurl'}->(%params);
675 if (exists $params{rootpage}) {
676 $rootpage=$origsubs{'bestlink'}->($params{page}, $params{rootpage});
677 if (!length $rootpage) {
678 $rootpage=$params{rootpage};
682 $rootpage=masterpage($params{page});
687 sub myisselflink ($$) {
691 return 1 if $origsubs{'isselflink'}->($page, $link);
692 if (istranslation($page)) {
693 return $origsubs{'isselflink'}->(masterpage($page), $link);
699 # | Blackboxes for private data
705 sub alreadyfiltered($$) {
709 return exists $filtered{$page}{$destpage}
710 && $filtered{$page}{$destpage} eq 1;
713 sub setalreadyfiltered($$) {
717 $filtered{$page}{$destpage}=1;
720 sub unsetalreadyfiltered($$) {
724 if (exists $filtered{$page}{$destpage}) {
725 delete $filtered{$page}{$destpage};
729 sub resetalreadyfiltered() {
738 sub maybe_add_leading_slash ($;$) {
741 $add=1 unless defined $add;
742 return '/' . $str if $add;
746 sub istranslatablefile ($) {
749 return 0 unless defined $file;
750 my $type=pagetype($file);
751 return 0 if ! defined $type || $type eq 'po';
752 return 0 if $file =~ /\.pot$/;
753 return 0 if ! defined $config{po_translatable_pages};
754 return 1 if pagespec_match(pagename($file), $config{po_translatable_pages});
758 sub istranslatable ($) {
762 return 1 if istranslatablefile($pagesources{$page});
766 sub _istranslation ($) {
769 $page='' unless defined $page && length $page;
770 my $hasleadingslash = ($page=~s#^/##);
771 my $file=$pagesources{$page};
772 return 0 unless defined $file
773 && defined pagetype($file)
774 && pagetype($file) eq 'po';
775 return 0 if $file =~ /\.pot$/;
777 my ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
778 return 0 unless defined $masterpage && defined $lang
779 && length $masterpage && length $lang
780 && defined $pagesources{$masterpage}
781 && defined $config{po_slave_languages}{$lang};
783 return (maybe_add_leading_slash($masterpage, $hasleadingslash), $lang)
784 if istranslatable($masterpage);
787 sub istranslation ($) {
790 if (1 < (my ($masterpage, $lang) = _istranslation($page))) {
791 my $hasleadingslash = ($masterpage=~s#^/##);
792 $translations{$masterpage}{$lang}=$page unless exists $translations{$masterpage}{$lang};
793 return (maybe_add_leading_slash($masterpage, $hasleadingslash), $lang);
801 if ( 1 < (my ($masterpage, $lang) = _istranslation($page))) {
810 if (1 < (my ($masterpage, $lang) = _istranslation($page))) {
813 return $config{po_master_language}{code};
816 sub islanguagecode ($) {
819 return $code =~ /^[a-z]{2}$/;
822 sub otherlanguage ($$) {
826 return masterpage($page) if $code eq $config{po_master_language}{code};
827 return masterpage($page) . '.' . $code;
830 sub otherlanguages ($) {
834 return \%ret unless istranslation($page) || istranslatable($page);
835 my $curlang=lang($page);
837 ($config{po_master_language}{code}, keys %{$config{po_slave_languages}}) {
838 next if $lang eq $curlang;
839 $ret{$lang}=otherlanguage($page, $lang);
845 my $masterfile=shift;
847 (my $name, my $dir, my $suffix) = fileparse($masterfile, qr/\.[^.]*/);
848 $dir='' if $dir eq './';
849 return File::Spec->catpath('', $dir, $name . ".pot");
853 my $masterfile=shift;
856 (my $name, my $dir, my $suffix) = fileparse($masterfile, qr/\.[^.]*/);
857 $dir='' if $dir eq './';
858 return File::Spec->catpath('', $dir, $name . "." . $lang . ".po");
862 my $masterfile=shift;
864 return map pofile($masterfile, $_), (keys %{$config{po_slave_languages}});
868 my $masterfile=shift;
870 my $potfile=potfile($masterfile);
871 my %options = ("markdown" => (pagetype($masterfile) eq 'mdwn') ? 1 : 0);
872 my $doc=Locale::Po4a::Chooser::new('text',%options);
873 $doc->{TT}{utf_mode} = 1;
874 $doc->{TT}{file_in_charset} = 'utf-8';
875 $doc->{TT}{file_out_charset} = 'utf-8';
876 $doc->read($masterfile);
877 # let's cheat a bit to force porefs option to be passed to
878 # Locale::Po4a::Po; this is undocument use of internal
879 # Locale::Po4a::TransTractor's data, compulsory since this module
880 # prevents us from using the porefs option.
881 $doc->{TT}{po_out}=Locale::Po4a::Po->new({ 'porefs' => 'none' });
882 $doc->{TT}{po_out}->set_charset('utf-8');
885 IkiWiki::prep_writefile(basename($potfile),dirname($potfile));
886 $doc->writepo($potfile);
889 sub refreshpofiles ($@) {
890 my $masterfile=shift;
893 my $potfile=potfile($masterfile);
895 error("po(refreshpofiles) ".sprintf(gettext("POT file (%s) does not exist"), $potfile));
898 foreach my $pofile (@pofiles) {
899 IkiWiki::prep_writefile(basename($pofile),dirname($pofile));
902 # If the po file exists in an underlay, copy it
904 my ($pobase)=$pofile=~/^\Q$config{srcdir}\E\/?(.*)$/;
905 foreach my $dir (@{$config{underlaydirs}}) {
906 if (-e "$dir/$pobase") {
907 File::Copy::syscopy("$dir/$pobase",$pofile)
908 or error("po(refreshpofiles) ".
909 sprintf(gettext("failed to copy underlay PO file to %s"),
916 system("msgmerge", "--previous", "-q", "-U", "--backup=none", $pofile, $potfile) == 0
917 or error("po(refreshpofiles) ".
918 sprintf(gettext("failed to update %s"),
922 File::Copy::syscopy($potfile,$pofile)
923 or error("po(refreshpofiles) ".
924 sprintf(gettext("failed to copy the POT file to %s"),
930 sub buildtranslationscache() {
931 # use istranslation's side-effect
932 map istranslation($_), (keys %pagesources);
935 sub resettranslationscache() {
939 sub flushmemoizecache() {
940 Memoize::flush_cache("istranslatable");
941 Memoize::flush_cache("_istranslation");
942 Memoize::flush_cache("percenttranslated");
945 sub urlto_with_orig_beautiful_urlpath($$) {
949 inject(name => "IkiWiki::beautify_urlpath", call => $origsubs{'beautify_urlpath'});
950 my $res=urlto($to, $from);
951 inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath);
956 sub percenttranslated ($) {
960 return gettext("N/A") unless istranslation($page);
961 my $file=srcfile($pagesources{$page});
962 my $masterfile = srcfile($pagesources{masterpage($page)});
964 "markdown" => (pagetype($masterfile) eq 'mdwn') ? 1 : 0,
966 my $doc=Locale::Po4a::Chooser::new('text',%options);
968 'po_in_name' => [ $file ],
969 'file_in_name' => [ $masterfile ],
970 'file_in_charset' => 'utf-8',
971 'file_out_charset' => 'utf-8',
972 ) or error("po(percenttranslated) ".
973 sprintf(gettext("failed to translate %s"), $page));
974 my ($percent,$hit,$queries) = $doc->stats();
975 $percent =~ s/\.[0-9]+$//;
979 sub languagename ($) {
982 return $config{po_master_language}{name}
983 if $code eq $config{po_master_language}{code};
984 return $config{po_slave_languages}{$code}
985 if defined $config{po_slave_languages}{$code};
989 sub otherlanguagesloop ($) {
993 my %otherpages=%{otherlanguages($page)};
994 while (my ($lang, $otherpage) = each %otherpages) {
995 if (istranslation($page) && masterpage($page) eq $otherpage) {
997 url => urlto_with_orig_beautiful_urlpath($otherpage, $page),
999 language => languagename($lang),
1003 elsif (istranslation($otherpage)) {
1005 url => urlto_with_orig_beautiful_urlpath($otherpage, $page),
1007 language => languagename($lang),
1008 percent => percenttranslated($otherpage),
1013 return -1 if $a->{code} eq $config{po_master_language}{code};
1014 return 1 if $b->{code} eq $config{po_master_language}{code};
1015 return $a->{language} cmp $b->{language};
1019 sub homepageurl (;$) {
1022 return urlto('', $page);
1025 sub ishomepage ($) {
1028 return 1 if $page eq 'index';
1029 map { return 1 if $page eq 'index.'.$_ } keys %{$config{po_slave_languages}};
1033 sub deletetranslations ($) {
1034 my $deletedmasterfile=shift;
1036 my $deletedmasterpage=pagename($deletedmasterfile);
1039 my $file = newpagefile($deletedmasterpage.'.'.$_, 'po');
1040 my $absfile = "$config{srcdir}/$file";
1041 if (-e $absfile && ! -l $absfile && ! -d $absfile) {
1042 push @todelete, $file;
1044 } keys %{$config{po_slave_languages}};
1048 IkiWiki::rcs_remove($_);
1051 IkiWiki::prune("$config{srcdir}/$_");
1057 gettext("removed obsolete PO files"));
1061 sub commit_and_refresh ($) {
1065 IkiWiki::disable_commit_hook();
1066 IkiWiki::rcs_commit_staged(
1069 IkiWiki::enable_commit_hook();
1070 IkiWiki::rcs_update();
1072 # Reinitialize module's private variables.
1073 resetalreadyfiltered();
1074 resettranslationscache();
1075 flushmemoizecache();
1076 # Trigger a wiki refresh.
1077 require IkiWiki::Render;
1078 # without preliminary saveindex/loadindex, refresh()
1079 # complains about a lot of uninitialized variables
1080 IkiWiki::saveindex();
1081 IkiWiki::loadindex();
1083 IkiWiki::saveindex();
1086 sub po_to_markup ($$) {
1087 my ($page, $content) = (shift, shift);
1089 $content = '' unless defined $content;
1090 $content = decode_utf8(encode_utf8($content));
1091 # CRLF line terminators make poor Locale::Po4a feel bad
1092 $content=~s/\r\n/\n/g;
1094 # There are incompatibilities between some File::Temp versions
1095 # (including 0.18, bundled with Lenny's perl-modules package)
1096 # and others (e.g. 0.20, previously present in the archive as
1097 # a standalone package): under certain circumstances, some
1098 # return a relative filename, whereas others return an absolute one;
1099 # we here use this module in a way that is at least compatible
1100 # with 0.18 and 0.20. Beware, hit'n'run refactorers!
1101 my $infile = new File::Temp(TEMPLATE => "ikiwiki-po-filter-in.XXXXXXXXXX",
1102 DIR => File::Spec->tmpdir,
1103 UNLINK => 1)->filename;
1104 my $outfile = new File::Temp(TEMPLATE => "ikiwiki-po-filter-out.XXXXXXXXXX",
1105 DIR => File::Spec->tmpdir,
1106 UNLINK => 1)->filename;
1108 my $fail = sub ($) {
1109 my $msg = "po(po_to_markup) - $page : " . shift;
1110 error($msg, sub { unlink $infile, $outfile});
1113 writefile(basename($infile), File::Spec->tmpdir, $content)
1114 or return $fail->(sprintf(gettext("failed to write %s"), $infile));
1116 my $masterfile = srcfile($pagesources{masterpage($page)});
1118 "markdown" => (pagetype($masterfile) eq 'mdwn') ? 1 : 0,
1120 my $doc=Locale::Po4a::Chooser::new('text',%options);
1122 'po_in_name' => [ $infile ],
1123 'file_in_name' => [ $masterfile ],
1124 'file_in_charset' => 'utf-8',
1125 'file_out_charset' => 'utf-8',
1126 ) or return $fail->(gettext("failed to translate"));
1127 $doc->write($outfile)
1128 or return $fail->(sprintf(gettext("failed to write %s"), $outfile));
1130 $content = readfile($outfile);
1132 # Unlinking should happen automatically, thanks to File::Temp,
1133 # but it does not work here, probably because of the way writefile()
1134 # and Locale::Po4a::write() work.
1135 unlink $infile, $outfile;
1140 # returns a SuccessReason or FailReason object
1142 my $content = shift;
1144 # NB: we don't use po_to_markup here, since Po4a parser does
1145 # not mind invalid PO content
1146 $content = '' unless defined $content;
1147 $content = decode_utf8(encode_utf8($content));
1149 # There are incompatibilities between some File::Temp versions
1150 # (including 0.18, bundled with Lenny's perl-modules package)
1151 # and others (e.g. 0.20, previously present in the archive as
1152 # a standalone package): under certain circumstances, some
1153 # return a relative filename, whereas others return an absolute one;
1154 # we here use this module in a way that is at least compatible
1155 # with 0.18 and 0.20. Beware, hit'n'run refactorers!
1156 my $infile = new File::Temp(TEMPLATE => "ikiwiki-po-isvalidpo.XXXXXXXXXX",
1157 DIR => File::Spec->tmpdir,
1158 UNLINK => 1)->filename;
1160 my $fail = sub ($) {
1161 my $msg = '[po/isvalidpo] ' . shift;
1163 return IkiWiki::FailReason->new("$msg");
1166 writefile(basename($infile), File::Spec->tmpdir, $content)
1167 or return $fail->(sprintf(gettext("failed to write %s"), $infile));
1169 my $res = (system("msgfmt", "--check", $infile, "-o", "/dev/null") == 0);
1171 # Unlinking should happen automatically, thanks to File::Temp,
1172 # but it does not work here, probably because of the way writefile()
1173 # and Locale::Po4a::write() work.
1177 return IkiWiki::SuccessReason->new("valid gettext data");
1179 return IkiWiki::FailReason->new(gettext("invalid gettext data, go back ".
1180 "to previous page to continue edit"));
1187 package IkiWiki::PageSpec;
1189 sub match_istranslation ($;@) {
1192 if (IkiWiki::Plugin::po::istranslation($page)) {
1193 return IkiWiki::SuccessReason->new("is a translation page");
1196 return IkiWiki::FailReason->new("is not a translation page");
1200 sub match_istranslatable ($;@) {
1203 if (IkiWiki::Plugin::po::istranslatable($page)) {
1204 return IkiWiki::SuccessReason->new("is set as translatable in po_translatable_pages");
1207 return IkiWiki::FailReason->new("is not set as translatable in po_translatable_pages");
1211 sub match_lang ($$;@) {
1215 my $regexp=IkiWiki::glob2re($wanted);
1216 my $lang=IkiWiki::Plugin::po::lang($page);
1217 if ($lang !~ /^$regexp$/i) {
1218 return IkiWiki::FailReason->new("file language is $lang, not $wanted");
1221 return IkiWiki::SuccessReason->new("file language is $wanted");
1225 sub match_currentlang ($$;@) {
1230 return IkiWiki::FailReason->new("no location provided") unless exists $params{location};
1232 my $currentlang=IkiWiki::Plugin::po::lang($params{location});
1233 my $lang=IkiWiki::Plugin::po::lang($page);
1235 if ($lang eq $currentlang) {
1236 return IkiWiki::SuccessReason->new("file language is the same as current one, i.e. $currentlang");
1239 return IkiWiki::FailReason->new("file language is $lang, whereas current language is $currentlang");