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;
31 my @slavelanguages; # language codes ordered as in config po_slave_languages
33 memoize("istranslatable");
34 memoize("_istranslation");
35 memoize("percenttranslated");
38 hook(type => "getsetup", id => "po", call => \&getsetup);
39 hook(type => "checkconfig", id => "po", call => \&checkconfig);
40 hook(type => "needsbuild", id => "po", call => \&needsbuild);
41 hook(type => "scan", id => "po", call => \&scan, last => 1);
42 hook(type => "filter", id => "po", call => \&filter);
43 hook(type => "htmlize", id => "po", call => \&htmlize);
44 hook(type => "pagetemplate", id => "po", call => \&pagetemplate, last => 1);
45 hook(type => "rename", id => "po", call => \&renamepages, first => 1);
46 hook(type => "delete", id => "po", call => \&mydelete);
47 hook(type => "change", id => "po", call => \&change);
48 hook(type => "checkcontent", id => "po", call => \&checkcontent);
49 hook(type => "canremove", id => "po", call => \&canremove);
50 hook(type => "canrename", id => "po", call => \&canrename);
51 hook(type => "editcontent", id => "po", call => \&editcontent);
52 hook(type => "formbuilder_setup", id => "po", call => \&formbuilder_setup, last => 1);
53 hook(type => "formbuilder", id => "po", call => \&formbuilder);
56 $origsubs{'bestlink'}=\&IkiWiki::bestlink;
57 inject(name => "IkiWiki::bestlink", call => \&mybestlink);
58 $origsubs{'beautify_urlpath'}=\&IkiWiki::beautify_urlpath;
59 inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath);
60 $origsubs{'targetpage'}=\&IkiWiki::targetpage;
61 inject(name => "IkiWiki::targetpage", call => \&mytargetpage);
62 $origsubs{'urlto'}=\&IkiWiki::urlto;
63 inject(name => "IkiWiki::urlto", call => \&myurlto);
64 $origsubs{'cgiurl'}=\&IkiWiki::cgiurl;
65 inject(name => "IkiWiki::cgiurl", call => \&mycgiurl);
66 $origsubs{'rootpage'}=\&IkiWiki::rootpage;
67 inject(name => "IkiWiki::rootpage", call => \&myrootpage);
68 $origsubs{'isselflink'}=\&IkiWiki::isselflink;
69 inject(name => "IkiWiki::isselflink", call => \&myisselflink);
79 # 2. Injected functions
80 # 3. Blackboxes for private data
93 rebuild => 1, # format plugin
96 po_master_language => {
102 description => "master language (non-PO files)",
106 po_slave_languages => {
113 description => "slave languages (translated via PO files) format: ll|Langname",
117 po_translatable_pages => {
119 example => "* and !*/Discussion",
120 description => "PageSpec controlling which pages are translatable",
121 link => "ikiwiki/PageSpec",
127 example => "current",
128 description => "internal linking behavior (default/current/negotiated)",
135 foreach my $field (qw{po_master_language}) {
136 if (! exists $config{$field} || ! defined $config{$field}) {
137 error(sprintf(gettext("Must specify %s when using the %s plugin"),
142 if (ref $config{po_slave_languages} eq 'ARRAY') {
144 foreach my $pair (@{$config{po_slave_languages}}) {
145 my ($code, $name) = ( $pair =~ /^([a-z]{2})\|(.+)$/ );
146 if (!defined $code || !defined $name) {
147 error(sprintf(gettext("%s has invalid syntax: must use CODE|NAME"),
150 $slaves{$code} = $name;
151 push @slavelanguages, $code;
154 $config{po_slave_languages} = \%slaves;
156 elsif (ref $config{po_slave_languages} eq 'HASH') {
157 @slavelanguages = sort {
158 $config{po_slave_languages}->{$a} cmp $config{po_slave_languages}->{$b};
159 } keys %{$config{po_slave_languages}};
162 delete $config{po_slave_languages}{$config{po_master_language}{code}};;
166 or error(sprintf(gettext("%s is not a valid language code"), $_));
167 } ($config{po_master_language}{code}, @slavelanguages);
169 if (! exists $config{po_translatable_pages} ||
170 ! defined $config{po_translatable_pages}) {
171 $config{po_translatable_pages}="";
173 if (! exists $config{po_link_to} ||
174 ! defined $config{po_link_to}) {
175 $config{po_link_to}='default';
177 elsif ($config{po_link_to} !~ /^(default|current|negotiated)$/) {
178 warn(sprintf(gettext('%s is not a valid value for po_link_to, falling back to po_link_to=default'),
179 $config{po_link_to}));
180 $config{po_link_to}='default';
182 elsif ($config{po_link_to} eq "negotiated" && ! $config{usedirs}) {
183 warn(gettext('po_link_to=negotiated requires usedirs to be enabled, falling back to po_link_to=default'));
184 $config{po_link_to}='default';
187 push @{$config{wiki_file_prune_regexps}}, qr/\.pot$/;
189 # Translated versions of the underlays are added if available.
190 foreach my $underlay ("basewiki",
191 map { m/^\Q$config{underlaydirbase}\E\/*(.*)/ }
192 reverse @{$config{underlaydirs}}) {
193 next if $underlay=~/^locale\//;
195 # Underlays containing the po files for slave languages.
196 foreach my $ll (@slavelanguages) {
197 add_underlay("po/$ll/$underlay")
198 if -d "$config{underlaydirbase}/po/$ll/$underlay";
201 if ($config{po_master_language}{code} ne 'en') {
202 # Add underlay containing translated source files
203 # for the master language.
204 add_underlay("locale/$config{po_master_language}{code}/$underlay")
205 if -d "$config{underlaydirbase}/locale/$config{po_master_language}{code}/$underlay";
211 my $needsbuild=shift;
213 # backup @needsbuild content so that change() can know whether
214 # a given master page was rendered because its source file was changed
215 @origneedsbuild=(@$needsbuild);
218 buildtranslationscache();
220 # make existing translations depend on the corresponding master page
221 foreach my $master (keys %translations) {
222 map add_depends($_, $master), values %{otherlanguages_pages($master)};
230 my $page=$params{page};
231 my $content=$params{content};
232 my $run_by_po=$params{run_by_po};
234 # Massage the recorded state of internal links so that:
235 # - it matches the actually generated links, rather than the links as
236 # written in the pages' source
237 # - backlinks are consistent in all cases
239 # A second scan pass is made over translation pages, so as an
240 # optimization, we only do so on the second pass in this case,
241 # i.e. when this hook is called by itself.
242 if ($run_by_po && istranslation($page)) {
243 # replace the occurence of $destpage in $links{$page}
244 my @orig_links = @{$links{$page}};
246 foreach my $destpage (@orig_links) {
247 if (istranslatedto($destpage, lang($page))) {
248 add_link($page, $destpage . '.' . lang($page));
251 add_link($page, $destpage);
255 # No second scan pass is done for a non-translation page, so
256 # links massaging must happen on first pass in this case.
257 elsif (! $run_by_po && ! istranslatable($page) && ! istranslation($page)) {
258 foreach my $destpage (@{$links{$page}}) {
259 if (istranslatable($destpage)) {
260 # make sure any destpage's translations has
261 # $page in its backlinks
262 foreach my $link (values %{otherlanguages_pages($destpage)}) {
263 add_link($page, $link);
269 # Re-run the preprocess hooks in scan mode, then the scan hooks,
270 # over the po-to-markup converted content
271 return if $run_by_po; # avoid looping endlessly
272 return unless istranslation($page);
273 $content = po_to_markup($page, $content);
275 IkiWiki::preprocess($page, $page, $content, 1);
276 IkiWiki::run_hooks(scan => sub {
285 # We use filter to convert PO to the master page's format,
286 # since the rest of ikiwiki should not work on PO files.
290 my $page = $params{page};
291 my $destpage = $params{destpage};
292 my $content = $params{content};
293 if (istranslation($page) && ! alreadyfiltered($page, $destpage)) {
294 $content = po_to_markup($page, $content);
295 setalreadyfiltered($page, $destpage);
303 my $page = $params{page};
304 my $content = $params{content};
306 # ignore PO files this plugin did not create
307 return $content unless istranslation($page);
309 # force content to be htmlize'd as if it was the same type as the master page
310 return IkiWiki::htmlize($page, $page,
311 pagetype(srcfile($pagesources{masterpage($page)})),
315 sub pagetemplate (@) {
317 my $page=$params{page};
318 my $destpage=$params{destpage};
319 my $template=$params{template};
321 my ($masterpage, $lang) = istranslation($page);
323 if (istranslation($page) && $template->query(name => "percenttranslated")) {
324 $template->param(percenttranslated => percenttranslated($page));
326 if ($template->query(name => "istranslation")) {
327 $template->param(istranslation => scalar istranslation($page));
329 if ($template->query(name => "istranslatable")) {
330 $template->param(istranslatable => istranslatable($page));
332 if ($template->query(name => "HOMEPAGEURL")) {
333 $template->param(homepageurl => homepageurl($page));
335 if ($template->query(name => "otherlanguages")) {
336 $template->param(otherlanguages => [otherlanguagesloop($page)]);
337 map add_depends($page, $_), (values %{otherlanguages_pages($page)});
339 if ($config{discussion} && istranslation($page)) {
340 if ($page !~ /.*\/\Q$config{discussionpage}\E$/i &&
341 (length $config{cgiurl} ||
342 exists $links{$masterpage."/".lc($config{discussionpage})})) {
343 $template->param('discussionlink' => htmllink(
346 $masterpage . '/' . $config{discussionpage},
349 linktext => $config{discussionpage},
353 # Remove broken parentlink to ./index.html on home page's translations.
354 # It works because this hook has the "last" parameter set, to ensure it
355 # runs after parentlinks' own pagetemplate hook.
356 if ($template->param('parentlinks')
357 && istranslation($page)
358 && $masterpage eq "index") {
359 $template->param('parentlinks' => []);
361 if (ishomepage($page) && $template->query(name => "title")) {
362 $template->param(title => $config{wikiname});
366 # Add the renamed page translations to the list of to-be-renamed pages.
367 sub renamepages (@) {
370 my %torename = %{$params{torename}};
371 my $session = $params{session};
373 # Save the page(s) the user asked to rename, so that our
374 # canrename hook can tell the difference between:
375 # - a translation being renamed as a consequence of its master page
377 # - a user trying to directly rename a translation
378 # This is why this hook has to be run first, before the list of pages
379 # to rename is modified by other plugins.
381 @orig_torename=@{$session->param("po_orig_torename")}
382 if defined $session->param("po_orig_torename");
383 push @orig_torename, $torename{src};
384 $session->param(po_orig_torename => \@orig_torename);
385 IkiWiki::cgi_savesession($session);
387 return () unless istranslatable($torename{src});
390 my %otherpages=%{otherlanguages_pages($torename{src})};
391 while (my ($lang, $otherpage) = each %otherpages) {
394 srcfile => $pagesources{$otherpage},
395 dest => otherlanguage_page($torename{dest}, $lang),
396 destfile => $torename{dest}.".".$lang.".po",
406 map { deletetranslations($_) } grep istranslatablefile($_), @deleted;
412 my $updated_po_files=0;
414 # Refresh/create POT and PO files as needed.
415 foreach my $file (grep {istranslatablefile($_)} @rendered) {
416 my $masterfile=srcfile($file);
417 my $page=pagename($file);
418 my $updated_pot_file=0;
420 # Avoid touching underlay files.
421 next if $masterfile ne "$config{srcdir}/$file";
423 # Only refresh POT file if it does not exist, or if
424 # the source was changed: don't if only the HTML was
425 # refreshed, e.g. because of a dependency.
426 if ((grep { $_ eq $pagesources{$page} } @origneedsbuild) ||
427 ! -e potfile($masterfile)) {
428 refreshpot($masterfile);
432 foreach my $po (pofiles($masterfile)) {
433 next if ! $updated_pot_file && -e $po;
434 next if grep { $po=~/\Q$_\E/ } @{$config{underlaydirs}};
438 refreshpofiles($masterfile, @pofiles);
439 map { s/^\Q$config{srcdir}\E\/*//; IkiWiki::rcs_add($_) } @pofiles if $config{rcs};
444 if ($updated_po_files) {
446 gettext("updated PO files"));
450 sub checkcontent (@) {
453 if (istranslation($params{page})) {
454 my $res = isvalidpo($params{content});
468 if (istranslation($params{page})) {
469 return gettext("Can not remove a translation. If the master page is removed, ".
470 "however, its translations will be removed as well.");
477 my $session = $params{session};
479 if (istranslation($params{src})) {
480 my $masterpage = masterpage($params{src});
481 # Tell the difference between:
482 # - a translation being renamed as a consequence of its master page
483 # being renamed, which is allowed
484 # - a user trying to directly rename a translation, which is forbidden
485 # by looking for the master page in the list of to-be-renamed pages we
486 # saved early in the renaming process.
487 my $orig_torename = $session->param("po_orig_torename");
488 unless (grep { $_ eq $masterpage } @{$orig_torename}) {
489 return gettext("Can not rename a translation. If the master page is renamed, ".
490 "however, its translations will be renamed as well.");
496 # As we're previewing or saving a page, the content may have
497 # changed, so tell the next filter() invocation it must not be lazy.
501 unsetalreadyfiltered($params{page}, $params{page});
502 return $params{content};
505 sub formbuilder_setup (@) {
507 my $form=$params{form};
510 return unless defined $form->field("do");
512 if ($form->field("do") eq "create") {
513 # Warn the user: new pages must be written in master language.
514 my $template=template("pocreatepage.tmpl");
515 $template->param(LANG => $config{po_master_language}{name});
516 $form->tmpl_param(message => $template->output);
518 elsif ($form->field("do") eq "edit") {
519 # Remove the rename/remove buttons on slave pages.
520 # This has to be done after the rename/remove plugins have added
521 # their buttons, which is why this hook must be run last.
522 # The canrename/canremove hooks already ensure this is forbidden
523 # at the backend level, so this is only UI sugar.
524 if (istranslation($form->field("page"))) {
526 for (my $i = 0; $i < @{$params{buttons}}; $i++) {
527 if (@{$params{buttons}}[$i] eq $_) {
528 delete @{$params{buttons}}[$i];
537 sub formbuilder (@) {
539 my $form=$params{form};
542 return unless defined $form->field("do");
544 # Do not allow to create pages of type po: they are automatically created.
545 # The main reason to do so is to bypass the "favor the type of linking page
546 # on page creation" logic, which is unsuitable when a broken link is clicked
547 # on a slave (PO) page.
548 # This cannot be done in the formbuilder_setup hook as the list of types is
550 if ($form->field("do") eq "create") {
551 foreach my $field ($form->field) {
552 next unless "$field" eq "type";
553 next unless $field->type eq 'select';
554 my $orig_value = $field->value;
555 # remove po from the list of types
556 my @types = grep { $_->[0] ne 'po' } $field->options;
557 $field->options(\@types) if @types;
558 # favor the type of linking page's masterpage
559 if ($orig_value eq 'po') {
561 if (defined $form->field('from')) {
562 ($from)=$form->field('from')=~/$config{wiki_file_regexp}/;
563 $from = masterpage($from);
565 if (defined $from && exists $pagesources{$from}) {
566 $type=pagetype($pagesources{$from});
568 $type=$config{default_pageext} unless defined $type;
569 $field->value($type) ;
576 # | Injected functions
579 # Implement po_link_to 'current' and 'negotiated' settings.
580 sub mybestlink ($$) {
584 return $origsubs{'bestlink'}->($page, $link)
585 if defined $config{po_link_to} && $config{po_link_to} eq "default";
587 my $res=$origsubs{'bestlink'}->(masterpage($page), $link);
588 my @caller = caller(1);
590 && istranslatedto($res, lang($page))
591 && istranslation($page)
592 && !(exists $caller[3] && defined $caller[3]
593 && ($caller[3] eq "IkiWiki::PageSpec::match_link"))) {
594 return $res . "." . lang($page);
599 sub mybeautify_urlpath ($) {
602 my $res=$origsubs{'beautify_urlpath'}->($url);
603 if (defined $config{po_link_to} && $config{po_link_to} eq "negotiated") {
604 $res =~ s!/\Qindex.$config{po_master_language}{code}.$config{htmlext}\E$!/!;
605 $res =~ s!/\Qindex.$config{htmlext}\E$!/!;
607 $res =~ s!/\Qindex.$_.$config{htmlext}\E$!/!;
613 sub mytargetpage ($$) {
617 if (istranslation($page) || istranslatable($page)) {
618 my ($masterpage, $lang) = (masterpage($page), lang($page));
619 if (! $config{usedirs} || $masterpage eq 'index') {
620 return $masterpage . "." . $lang . "." . $ext;
623 return $masterpage . "/index." . $lang . "." . $ext;
626 return $origsubs{'targetpage'}->($page, $ext);
634 # workaround hard-coded /index.$config{htmlext} in IkiWiki::urlto()
636 && $config{po_link_to} eq "current"
637 && istranslatable('index')) {
638 return IkiWiki::beautify_urlpath(IkiWiki::baseurl($from) . "index." . lang($from) . ".$config{htmlext}");
640 # avoid using our injected beautify_urlpath if run by cgi_editpage,
641 # so that one is redirected to the just-edited page rather than to the
642 # negociated translation; to prevent unnecessary fiddling with caller/inject,
643 # we only do so when our beautify_urlpath would actually do what we want to
644 # avoid, i.e. when po_link_to = negotiated.
645 # also avoid doing so when run by cgi_goto, so that the links on recentchanges
646 # page actually lead to the exact page they pretend to.
647 if ($config{po_link_to} eq "negotiated") {
648 my @caller = caller(1);
650 $use_orig = 1 if (exists $caller[3] && defined $caller[3]
651 && ($caller[3] eq "IkiWiki::cgi_editpage" ||
652 $caller[3] eq "IkiWiki::Plugin::goto::cgi_goto")
654 inject(name => "IkiWiki::beautify_urlpath", call => $origsubs{'beautify_urlpath'})
656 my $res = $origsubs{'urlto'}->($to,$from,$absolute);
657 inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath)
662 return $origsubs{'urlto'}->($to,$from,$absolute)
669 # slave pages have no subpages
670 if (istranslation($params{'from'})) {
671 $params{'from'} = masterpage($params{'from'});
673 return $origsubs{'cgiurl'}->(%params);
680 if (exists $params{rootpage}) {
681 $rootpage=$origsubs{'bestlink'}->($params{page}, $params{rootpage});
682 if (!length $rootpage) {
683 $rootpage=$params{rootpage};
687 $rootpage=masterpage($params{page});
692 sub myisselflink ($$) {
696 return 1 if $origsubs{'isselflink'}->($page, $link);
697 if (istranslation($page)) {
698 return $origsubs{'isselflink'}->(masterpage($page), $link);
704 # | Blackboxes for private data
710 sub alreadyfiltered($$) {
714 return exists $filtered{$page}{$destpage}
715 && $filtered{$page}{$destpage} eq 1;
718 sub setalreadyfiltered($$) {
722 $filtered{$page}{$destpage}=1;
725 sub unsetalreadyfiltered($$) {
729 if (exists $filtered{$page}{$destpage}) {
730 delete $filtered{$page}{$destpage};
734 sub resetalreadyfiltered() {
743 sub maybe_add_leading_slash ($;$) {
746 $add=1 unless defined $add;
747 return '/' . $str if $add;
751 sub istranslatablefile ($) {
754 return 0 unless defined $file;
755 my $type=pagetype($file);
756 return 0 if ! defined $type || $type eq 'po';
757 return 0 if $file =~ /\.pot$/;
758 return 0 if ! defined $config{po_translatable_pages};
759 return 1 if pagespec_match(pagename($file), $config{po_translatable_pages});
763 sub istranslatable ($) {
767 return 1 if istranslatablefile($pagesources{$page});
771 sub istranslatedto ($$) {
773 my $destlang = shift;
776 return 0 unless istranslatable($page);
777 exists $pagesources{otherlanguage_page($page, $destlang)};
780 sub _istranslation ($) {
783 $page='' unless defined $page && length $page;
784 my $hasleadingslash = ($page=~s#^/##);
785 my $file=$pagesources{$page};
786 return 0 unless defined $file
787 && defined pagetype($file)
788 && pagetype($file) eq 'po';
789 return 0 if $file =~ /\.pot$/;
791 my ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
792 return 0 unless defined $masterpage && defined $lang
793 && length $masterpage && length $lang
794 && defined $pagesources{$masterpage}
795 && defined $config{po_slave_languages}{$lang};
797 return (maybe_add_leading_slash($masterpage, $hasleadingslash), $lang)
798 if istranslatable($masterpage);
801 sub istranslation ($) {
804 if (1 < (my ($masterpage, $lang) = _istranslation($page))) {
805 my $hasleadingslash = ($masterpage=~s#^/##);
806 $translations{$masterpage}{$lang}=$page unless exists $translations{$masterpage}{$lang};
807 return (maybe_add_leading_slash($masterpage, $hasleadingslash), $lang);
815 if ( 1 < (my ($masterpage, $lang) = _istranslation($page))) {
824 if (1 < (my ($masterpage, $lang) = _istranslation($page))) {
827 return $config{po_master_language}{code};
830 sub islanguagecode ($) {
833 return $code =~ /^[a-z]{2}$/;
836 sub otherlanguage_page ($$) {
840 return masterpage($page) if $code eq $config{po_master_language}{code};
841 return masterpage($page) . '.' . $code;
844 # Returns the list of other languages codes: the master language comes first,
845 # then the codes are ordered the same way as in po_slave_languages, if it is
846 # an array, or in the language name lexical order, if it is a hash.
847 sub otherlanguages_codes ($) {
851 return \@ret unless istranslation($page) || istranslatable($page);
852 my $curlang=lang($page);
854 ($config{po_master_language}{code}, @slavelanguages) {
855 next if $lang eq $curlang;
856 if ($lang eq $config{po_master_language}{code} ||
857 istranslatedto(masterpage($page), $lang)) {
864 sub otherlanguages_pages ($) {
869 $ret{$_} = otherlanguage_page($page, $_)
870 } @{otherlanguages_codes($page)};
876 my $masterfile=shift;
878 (my $name, my $dir, my $suffix) = fileparse($masterfile, qr/\.[^.]*/);
879 $dir='' if $dir eq './';
880 return File::Spec->catpath('', $dir, $name . ".pot");
884 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 . "." . $lang . ".po");
893 my $masterfile=shift;
895 return map pofile($masterfile, $_), @slavelanguages;
899 my $masterfile=shift;
901 my $potfile=potfile($masterfile);
902 my $doc=Locale::Po4a::Chooser::new(po4a_type($masterfile),
903 po4a_options($masterfile));
904 $doc->{TT}{utf_mode} = 1;
905 $doc->{TT}{file_in_charset} = 'UTF-8';
906 $doc->{TT}{file_out_charset} = 'UTF-8';
907 $doc->read($masterfile);
908 # let's cheat a bit to force porefs option to be passed to
909 # Locale::Po4a::Po; this is undocument use of internal
910 # Locale::Po4a::TransTractor's data, compulsory since this module
911 # prevents us from using the porefs option.
912 $doc->{TT}{po_out}=Locale::Po4a::Po->new({ 'porefs' => 'none' });
913 $doc->{TT}{po_out}->set_charset('UTF-8');
916 IkiWiki::prep_writefile(basename($potfile),dirname($potfile));
917 $doc->writepo($potfile);
920 sub refreshpofiles ($@) {
921 my $masterfile=shift;
924 my $potfile=potfile($masterfile);
926 error("po(refreshpofiles) ".sprintf(gettext("POT file (%s) does not exist"), $potfile));
929 foreach my $pofile (@pofiles) {
930 IkiWiki::prep_writefile(basename($pofile),dirname($pofile));
933 # If the po file exists in an underlay, copy it
935 my ($pobase)=$pofile=~/^\Q$config{srcdir}\E\/?(.*)$/;
936 foreach my $dir (@{$config{underlaydirs}}) {
937 if (-e "$dir/$pobase") {
938 File::Copy::syscopy("$dir/$pobase",$pofile)
939 or error("po(refreshpofiles) ".
940 sprintf(gettext("failed to copy underlay PO file to %s"),
947 system("msgmerge", "--previous", "-q", "-U", "--backup=none", $pofile, $potfile) == 0
948 or error("po(refreshpofiles) ".
949 sprintf(gettext("failed to update %s"),
953 File::Copy::syscopy($potfile,$pofile)
954 or error("po(refreshpofiles) ".
955 sprintf(gettext("failed to copy the POT file to %s"),
961 sub buildtranslationscache() {
962 # use istranslation's side-effect
963 map istranslation($_), (keys %pagesources);
966 sub resettranslationscache() {
970 sub flushmemoizecache() {
971 Memoize::flush_cache("istranslatable");
972 Memoize::flush_cache("_istranslation");
973 Memoize::flush_cache("percenttranslated");
976 sub urlto_with_orig_beautiful_urlpath($$) {
980 inject(name => "IkiWiki::beautify_urlpath", call => $origsubs{'beautify_urlpath'});
981 my $res=urlto($to, $from);
982 inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath);
987 sub percenttranslated ($) {
991 return gettext("N/A") unless istranslation($page);
992 my $file=srcfile($pagesources{$page});
993 my $masterfile = srcfile($pagesources{masterpage($page)});
994 my $doc=Locale::Po4a::Chooser::new(po4a_type($masterfile),
995 po4a_options($masterfile));
997 'po_in_name' => [ $file ],
998 'file_in_name' => [ $masterfile ],
999 'file_in_charset' => 'UTF-8',
1000 'file_out_charset' => 'UTF-8',
1001 ) or error("po(percenttranslated) ".
1002 sprintf(gettext("failed to translate %s"), $page));
1003 my ($percent,$hit,$queries) = $doc->stats();
1004 $percent =~ s/\.[0-9]+$//;
1008 sub languagename ($) {
1011 return $config{po_master_language}{name}
1012 if $code eq $config{po_master_language}{code};
1013 return $config{po_slave_languages}{$code}
1014 if defined $config{po_slave_languages}{$code};
1018 sub otherlanguagesloop ($) {
1022 if (istranslation($page)) {
1024 url => urlto_with_orig_beautiful_urlpath(masterpage($page), $page),
1025 code => $config{po_master_language}{code},
1026 language => $config{po_master_language}{name},
1030 foreach my $lang (@{otherlanguages_codes($page)}) {
1031 next if $lang eq $config{po_master_language}{code};
1032 my $otherpage = otherlanguage_page($page, $lang);
1034 url => urlto_with_orig_beautiful_urlpath($otherpage, $page),
1036 language => languagename($lang),
1037 percent => percenttranslated($otherpage),
1043 sub homepageurl (;$) {
1046 return urlto('', $page);
1049 sub ishomepage ($) {
1052 return 1 if $page eq 'index';
1053 map { return 1 if $page eq 'index.'.$_ } @slavelanguages;
1057 sub deletetranslations ($) {
1058 my $deletedmasterfile=shift;
1060 my $deletedmasterpage=pagename($deletedmasterfile);
1063 my $file = newpagefile($deletedmasterpage.'.'.$_, 'po');
1064 my $absfile = "$config{srcdir}/$file";
1065 if (-e $absfile && ! -l $absfile && ! -d $absfile) {
1066 push @todelete, $file;
1072 IkiWiki::rcs_remove($_);
1075 IkiWiki::prune("$config{srcdir}/$_");
1081 gettext("removed obsolete PO files"));
1085 sub commit_and_refresh ($) {
1089 IkiWiki::disable_commit_hook();
1090 IkiWiki::rcs_commit_staged(
1093 IkiWiki::enable_commit_hook();
1094 IkiWiki::rcs_update();
1096 # Reinitialize module's private variables.
1097 resetalreadyfiltered();
1098 resettranslationscache();
1099 flushmemoizecache();
1100 # Trigger a wiki refresh.
1101 require IkiWiki::Render;
1102 # without preliminary saveindex/loadindex, refresh()
1103 # complains about a lot of uninitialized variables
1104 IkiWiki::saveindex();
1105 IkiWiki::loadindex();
1107 IkiWiki::saveindex();
1110 sub po_to_markup ($$) {
1111 my ($page, $content) = (shift, shift);
1113 $content = '' unless defined $content;
1114 $content = decode_utf8(encode_utf8($content));
1115 # CRLF line terminators make poor Locale::Po4a feel bad
1116 $content=~s/\r\n/\n/g;
1118 # There are incompatibilities between some File::Temp versions
1119 # (including 0.18, bundled with Lenny's perl-modules package)
1120 # and others (e.g. 0.20, previously present in the archive as
1121 # a standalone package): under certain circumstances, some
1122 # return a relative filename, whereas others return an absolute one;
1123 # we here use this module in a way that is at least compatible
1124 # with 0.18 and 0.20. Beware, hit'n'run refactorers!
1125 my $infile = new File::Temp(TEMPLATE => "ikiwiki-po-filter-in.XXXXXXXXXX",
1126 DIR => File::Spec->tmpdir,
1127 UNLINK => 1)->filename;
1128 my $outfile = new File::Temp(TEMPLATE => "ikiwiki-po-filter-out.XXXXXXXXXX",
1129 DIR => File::Spec->tmpdir,
1130 UNLINK => 1)->filename;
1132 my $fail = sub ($) {
1133 my $msg = "po(po_to_markup) - $page : " . shift;
1134 error($msg, sub { unlink $infile, $outfile});
1137 writefile(basename($infile), File::Spec->tmpdir, $content)
1138 or return $fail->(sprintf(gettext("failed to write %s"), $infile));
1140 my $masterfile = srcfile($pagesources{masterpage($page)});
1141 my $doc=Locale::Po4a::Chooser::new(po4a_type($masterfile),
1142 po4a_options($masterfile));
1144 'po_in_name' => [ $infile ],
1145 'file_in_name' => [ $masterfile ],
1146 'file_in_charset' => 'UTF-8',
1147 'file_out_charset' => 'UTF-8',
1148 ) or return $fail->(gettext("failed to translate"));
1149 $doc->write($outfile)
1150 or return $fail->(sprintf(gettext("failed to write %s"), $outfile));
1152 $content = readfile($outfile);
1154 # Unlinking should happen automatically, thanks to File::Temp,
1155 # but it does not work here, probably because of the way writefile()
1156 # and Locale::Po4a::write() work.
1157 unlink $infile, $outfile;
1162 # returns a SuccessReason or FailReason object
1164 my $content = shift;
1166 # NB: we don't use po_to_markup here, since Po4a parser does
1167 # not mind invalid PO content
1168 $content = '' unless defined $content;
1169 $content = decode_utf8(encode_utf8($content));
1171 # There are incompatibilities between some File::Temp versions
1172 # (including 0.18, bundled with Lenny's perl-modules package)
1173 # and others (e.g. 0.20, previously present in the archive as
1174 # a standalone package): under certain circumstances, some
1175 # return a relative filename, whereas others return an absolute one;
1176 # we here use this module in a way that is at least compatible
1177 # with 0.18 and 0.20. Beware, hit'n'run refactorers!
1178 my $infile = new File::Temp(TEMPLATE => "ikiwiki-po-isvalidpo.XXXXXXXXXX",
1179 DIR => File::Spec->tmpdir,
1180 UNLINK => 1)->filename;
1182 my $fail = sub ($) {
1183 my $msg = '[po/isvalidpo] ' . shift;
1185 return IkiWiki::FailReason->new("$msg");
1188 writefile(basename($infile), File::Spec->tmpdir, $content)
1189 or return $fail->(sprintf(gettext("failed to write %s"), $infile));
1191 my $res = (system("msgfmt", "--check", $infile, "-o", "/dev/null") == 0);
1193 # Unlinking should happen automatically, thanks to File::Temp,
1194 # but it does not work here, probably because of the way writefile()
1195 # and Locale::Po4a::write() work.
1199 return IkiWiki::SuccessReason->new("valid gettext data");
1201 return IkiWiki::FailReason->new(gettext("invalid gettext data, go back ".
1202 "to previous page to continue edit"));
1208 my $pagetype = pagetype($file);
1209 if ($pagetype eq 'html') {
1215 sub po4a_options($) {
1219 my $pagetype = pagetype($file);
1221 if ($pagetype eq 'html') {
1222 # how to disable options is not consistent across po4a modules
1223 $options{includessi} = '';
1224 $options{includeexternal} = 0;
1226 elsif ($pagetype eq 'mdwn') {
1227 $options{markdown} = 1;
1230 $options{markdown} = 0;
1240 package IkiWiki::PageSpec;
1242 sub match_istranslation ($;@) {
1245 if (IkiWiki::Plugin::po::istranslation($page)) {
1246 return IkiWiki::SuccessReason->new("is a translation page");
1249 return IkiWiki::FailReason->new("is not a translation page");
1253 sub match_istranslatable ($;@) {
1256 if (IkiWiki::Plugin::po::istranslatable($page)) {
1257 return IkiWiki::SuccessReason->new("is set as translatable in po_translatable_pages");
1260 return IkiWiki::FailReason->new("is not set as translatable in po_translatable_pages");
1264 sub match_lang ($$;@) {
1268 my $regexp=IkiWiki::glob2re($wanted);
1269 my $lang=IkiWiki::Plugin::po::lang($page);
1270 if ($lang !~ /^$regexp$/i) {
1271 return IkiWiki::FailReason->new("file language is $lang, not $wanted");
1274 return IkiWiki::SuccessReason->new("file language is $wanted");
1278 sub match_currentlang ($$;@) {
1283 return IkiWiki::FailReason->new("no location provided") unless exists $params{location};
1285 my $currentlang=IkiWiki::Plugin::po::lang($params{location});
1286 my $lang=IkiWiki::Plugin::po::lang($page);
1288 if ($lang eq $currentlang) {
1289 return IkiWiki::SuccessReason->new("file language is the same as current one, i.e. $currentlang");
1292 return IkiWiki::FailReason->new("file language is $lang, whereas current language is $currentlang");
1296 sub match_needstranslation ($$;@) {
1300 if (defined $wanted && $wanted ne "") {
1301 if ($wanted !~ /^\d+$/) {
1302 return IkiWiki::FailReason->new("parameter is not an integer");
1304 elsif ($wanted > 100) {
1305 return IkiWiki::FailReason->new("parameter is greater than 100");
1312 my $percenttranslated=IkiWiki::Plugin::po::percenttranslated($page);
1313 if ($percenttranslated eq 'N/A') {
1314 return IkiWiki::FailReason->new("file is not a translatable page");
1316 elsif ($percenttranslated < $wanted) {
1317 return IkiWiki::SuccessReason->new("file has $percenttranslated translated");
1320 return IkiWiki::FailReason->new("file is translated enough");