2 # .po as a wiki page type
3 # Licensed under GPL v2 or greater
4 # Copyright (C) 2008-2009 intrigeri <intrigeri@boum.org>
5 # inspired by the GPL'd po4a-translate,
6 # which is Copyright 2002, 2003, 2004 by Martin Quinson (mquinson#debian.org)
7 package IkiWiki::Plugin::po;
13 eval q{use Locale::Po4a::Common qw(nowrapi18n !/.*/)};
15 print STDERR gettext("warning: Old po4a detected! Recommend upgrade to 0.35.")."\n";
16 eval q{use Locale::Po4a::Common qw(!/.*/)};
19 use Locale::Po4a::Chooser;
27 my ($master_language_code, $master_language_name);
31 my @slavelanguages; # language codes ordered as in config po_slave_languages
32 my %slavelanguages; # language code to name lookup
33 my $language_code_pattern = '[a-zA-Z]+(?:_[a-zA-Z]+)?';
35 memoize("istranslatable");
36 memoize("_istranslation");
37 memoize("percenttranslated");
40 hook(type => "getsetup", id => "po", call => \&getsetup);
41 hook(type => "checkconfig", id => "po", call => \&checkconfig,
43 hook(type => "needsbuild", id => "po", call => \&needsbuild);
44 hook(type => "scan", id => "po", call => \&scan, last => 1);
45 hook(type => "filter", id => "po", call => \&filter);
46 hook(type => "htmlize", id => "po", call => \&htmlize);
47 hook(type => "pagetemplate", id => "po", call => \&pagetemplate, last => 1);
48 hook(type => "rename", id => "po", call => \&renamepages, first => 1);
49 hook(type => "delete", id => "po", call => \&mydelete);
50 hook(type => "rendered", id => "po", call => \&rendered);
51 hook(type => "checkcontent", id => "po", call => \&checkcontent);
52 hook(type => "canremove", id => "po", call => \&canremove);
53 hook(type => "canrename", id => "po", call => \&canrename);
54 hook(type => "editcontent", id => "po", call => \&editcontent);
55 hook(type => "formbuilder_setup", id => "po", call => \&formbuilder_setup, last => 1);
56 hook(type => "formbuilder", id => "po", call => \&formbuilder);
59 $origsubs{'bestlink'}=\&IkiWiki::bestlink;
60 inject(name => "IkiWiki::bestlink", call => \&mybestlink);
61 $origsubs{'beautify_urlpath'}=\&IkiWiki::beautify_urlpath;
62 inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath);
63 $origsubs{'targetpage'}=\&IkiWiki::targetpage;
64 inject(name => "IkiWiki::targetpage", call => \&mytargetpage);
65 $origsubs{'urlto'}=\&IkiWiki::urlto;
66 inject(name => "IkiWiki::urlto", call => \&myurlto);
67 $origsubs{'cgiurl'}=\&IkiWiki::cgiurl;
68 inject(name => "IkiWiki::cgiurl", call => \&mycgiurl);
69 if (IkiWiki->can('rootpage')) {
70 $origsubs{'rootpage'}=\&IkiWiki::rootpage;
71 inject(name => "IkiWiki::rootpage", call => \&myrootpage)
72 if defined $origsubs{'rootpage'};
74 $origsubs{'isselflink'}=\&IkiWiki::isselflink;
75 inject(name => "IkiWiki::isselflink", call => \&myisselflink);
85 # 2. Injected functions
86 # 3. Blackboxes for private data
99 rebuild => 1, # format plugin
102 po_master_language => {
104 example => "en|English",
105 description => "master language (non-PO files)",
109 po_slave_languages => {
116 description => "slave languages (translated via PO files) format: ll|Langname",
120 po_translatable_pages => {
122 example => "* and !*/Discussion",
123 description => "PageSpec controlling which pages are translatable",
124 link => "ikiwiki/PageSpec",
130 example => "current",
131 description => "internal linking behavior (default/current/negotiated)",
138 if (exists $config{po_master_language}) {
139 if (! ref $config{po_master_language}) {
140 ($master_language_code, $master_language_name)=
141 splitlangpair($config{po_master_language});
144 $master_language_code=$config{po_master_language}{code};
145 $master_language_name=$config{po_master_language}{name};
146 $config{po_master_language}=joinlangpair($master_language_code, $master_language_name);
149 if (! defined $master_language_code) {
150 $master_language_code='en';
152 if (! defined $master_language_name) {
153 $master_language_name='English';
156 if (ref $config{po_slave_languages} eq 'ARRAY') {
157 foreach my $pair (@{$config{po_slave_languages}}) {
158 my ($code, $name)=splitlangpair($pair);
159 if (defined $code && ! exists $slavelanguages{$code}) {
160 push @slavelanguages, $code;
161 $slavelanguages{$code} = $name;
165 elsif (ref $config{po_slave_languages} eq 'HASH') {
166 %slavelanguages=%{$config{po_slave_languages}};
167 @slavelanguages = sort {
168 $config{po_slave_languages}->{$a} cmp $config{po_slave_languages}->{$b};
169 } keys %slavelanguages;
170 $config{po_slave_languages}=[
171 map { joinlangpair($_, $slavelanguages{$_}) } @slavelanguages
175 delete $slavelanguages{$master_language_code};
179 or error(sprintf(gettext("%s is not a valid language code"), $_));
180 } ($master_language_code, @slavelanguages);
182 if (! exists $config{po_translatable_pages} ||
183 ! defined $config{po_translatable_pages}) {
184 $config{po_translatable_pages}="";
186 if (! exists $config{po_link_to} ||
187 ! defined $config{po_link_to}) {
188 $config{po_link_to}='default';
190 elsif ($config{po_link_to} !~ /^(default|current|negotiated)$/) {
191 warn(sprintf(gettext('%s is not a valid value for po_link_to, falling back to po_link_to=default'),
192 $config{po_link_to}));
193 $config{po_link_to}='default';
195 elsif ($config{po_link_to} eq "negotiated" && ! $config{usedirs}) {
196 warn(gettext('po_link_to=negotiated requires usedirs to be enabled, falling back to po_link_to=default'));
197 $config{po_link_to}='default';
200 push @{$config{wiki_file_prune_regexps}}, qr/\.pot$/;
202 # Translated versions of the underlays are added if available.
203 foreach my $underlay ("basewiki",
204 map { m/^\Q$config{underlaydirbase}\E\/*(.*)/ }
205 reverse @{$config{underlaydirs}}) {
206 next if $underlay=~/^locale\//;
208 # Underlays containing the po files for slave languages.
209 foreach my $ll (@slavelanguages) {
210 add_underlay("po/$ll/$underlay")
211 if -d "$config{underlaydirbase}/po/$ll/$underlay";
214 if ($master_language_code ne 'en') {
215 # Add underlay containing translated source files
216 # for the master language.
217 add_underlay("locale/$master_language_code/$underlay")
218 if -d "$config{underlaydirbase}/locale/$master_language_code/$underlay";
224 my $needsbuild=shift;
226 # backup @needsbuild content so that change() can know whether
227 # a given master page was rendered because its source file was changed
228 @origneedsbuild=(@$needsbuild);
231 buildtranslationscache();
233 # make existing translations depend on the corresponding master page
234 foreach my $master (keys %translations) {
235 map add_depends($_, $master), values %{otherlanguages_pages($master)};
243 my $page=$params{page};
244 my $content=$params{content};
245 my $run_by_po=$params{run_by_po};
247 # Massage the recorded state of internal links so that:
248 # - it matches the actually generated links, rather than the links as
249 # written in the pages' source
250 # - backlinks are consistent in all cases
252 # A second scan pass is made over translation pages, so as an
253 # optimization, we only do so on the second pass in this case,
254 # i.e. when this hook is called by itself.
255 if ($run_by_po && istranslation($page)) {
256 # replace the occurence of $destpage in $links{$page}
257 my @orig_links = @{$links{$page}};
259 foreach my $destpage (@orig_links) {
260 if (istranslatedto($destpage, lang($page))) {
261 add_link($page, $destpage . '.' . lang($page));
264 add_link($page, $destpage);
268 # No second scan pass is done for a non-translation page, so
269 # links massaging must happen on first pass in this case.
270 elsif (! $run_by_po && ! istranslatable($page) && ! istranslation($page)) {
271 foreach my $destpage (@{$links{$page}}) {
272 if (istranslatable($destpage)) {
273 # make sure any destpage's translations has
274 # $page in its backlinks
275 foreach my $link (values %{otherlanguages_pages($destpage)}) {
276 add_link($page, $link);
282 # Re-run the preprocess hooks in scan mode, then the scan hooks,
283 # over the po-to-markup converted content
284 return if $run_by_po; # avoid looping endlessly
285 return unless istranslation($page);
286 $content = po_to_markup($page, $content);
288 IkiWiki::preprocess($page, $page, $content, 1);
289 IkiWiki::run_hooks(scan => sub {
298 # We use filter to convert PO to the master page's format,
299 # since the rest of ikiwiki should not work on PO files.
303 my $page = $params{page};
304 my $destpage = $params{destpage};
305 my $content = $params{content};
306 if (istranslation($page) && ! alreadyfiltered($page, $destpage)) {
307 $content = po_to_markup($page, $content);
308 setalreadyfiltered($page, $destpage);
316 my $page = $params{page};
317 my $content = $params{content};
319 # ignore PO files this plugin did not create
320 return $content unless istranslation($page);
322 # force content to be htmlize'd as if it was the same type as the master page
323 return IkiWiki::htmlize($page, $page,
324 pagetype(srcfile($pagesources{masterpage($page)})),
328 sub pagetemplate (@) {
330 my $page=$params{page};
331 my $destpage=$params{destpage};
332 my $template=$params{template};
334 my ($masterpage, $lang) = istranslation($page);
336 if (istranslation($page) && $template->query(name => "percenttranslated")) {
337 $template->param(percenttranslated => percenttranslated($page));
339 if ($template->query(name => "istranslation")) {
340 $template->param(istranslation => scalar istranslation($page));
342 if ($template->query(name => "istranslatable")) {
343 $template->param(istranslatable => istranslatable($page));
345 my $lang_code = istranslation($page) ? lang($page) : $master_language_code;
346 if ($template->query(name => "lang_code")) {
347 $template->param(lang_code => $lang_code);
349 if ($template->query(name => "lang_name")) {
350 $template->param(lang_name => languagename($lang_code));
352 if ($template->query(name => "HOMEPAGEURL")) {
353 $template->param(homepageurl => homepageurl($page));
355 if ($template->query(name => "otherlanguages")) {
356 $template->param(otherlanguages => [otherlanguagesloop($page)]);
357 map add_depends($page, $_), (values %{otherlanguages_pages($page)});
359 if ($config{discussion} && istranslation($page)) {
360 if ($page !~ /.*\/\Q$config{discussionpage}\E$/i &&
361 (length $config{cgiurl} ||
362 exists $links{$masterpage."/".lc($config{discussionpage})})) {
363 $template->param('discussionlink' => htmllink(
366 $masterpage . '/' . $config{discussionpage},
369 linktext => $config{discussionpage},
373 # Remove broken parentlink to ./index.html on home page's translations.
374 # It works because this hook has the "last" parameter set, to ensure it
375 # runs after parentlinks' own pagetemplate hook.
376 if ($template->param('parentlinks')
377 && istranslation($page)
378 && $masterpage eq "index") {
379 $template->param('parentlinks' => []);
381 if (ishomepage($page) && $template->query(name => "title")
382 && !$template->param("title_overridden")) {
383 $template->param(title => $config{wikiname});
387 # Add the renamed page translations to the list of to-be-renamed pages.
388 sub renamepages (@) {
391 my %torename = %{$params{torename}};
392 my $session = $params{session};
394 # Save the page(s) the user asked to rename, so that our
395 # canrename hook can tell the difference between:
396 # - a translation being renamed as a consequence of its master page
398 # - a user trying to directly rename a translation
399 # This is why this hook has to be run first, before the list of pages
400 # to rename is modified by other plugins.
402 @orig_torename=@{$session->param("po_orig_torename")}
403 if defined $session->param("po_orig_torename");
404 push @orig_torename, $torename{src};
405 $session->param(po_orig_torename => \@orig_torename);
406 IkiWiki::cgi_savesession($session);
408 return () unless istranslatable($torename{src});
411 my %otherpages=%{otherlanguages_pages($torename{src})};
412 while (my ($lang, $otherpage) = each %otherpages) {
415 srcfile => $pagesources{$otherpage},
416 dest => otherlanguage_page($torename{dest}, $lang),
417 destfile => $torename{dest}.".".$lang.".po",
427 map { deletetranslations($_) } grep istranslatablefile($_), @deleted;
433 my $updated_po_files=0;
435 # Refresh/create POT and PO files as needed.
436 foreach my $file (grep {istranslatablefile($_)} @rendered) {
437 my $masterfile=srcfile($file);
438 my $page=pagename($file);
439 my $updated_pot_file=0;
441 # Avoid touching underlay files.
442 next if $masterfile ne "$config{srcdir}/$file";
444 # Only refresh POT file if it does not exist, or if
445 # the source was changed: don't if only the HTML was
446 # refreshed, e.g. because of a dependency.
447 if ((grep { $_ eq $pagesources{$page} } @origneedsbuild) ||
448 ! -e potfile($masterfile)) {
449 refreshpot($masterfile);
453 foreach my $po (pofiles($masterfile)) {
454 next if ! $updated_pot_file && -e $po;
455 next if grep { $po=~/\Q$_\E/ } @{$config{underlaydirs}};
459 refreshpofiles($masterfile, @pofiles);
460 map { s/^\Q$config{srcdir}\E\/*//; IkiWiki::rcs_add($_) } @pofiles if $config{rcs};
465 if ($updated_po_files) {
467 gettext("updated PO files"));
471 sub checkcontent (@) {
474 if (istranslation($params{page})) {
475 my $res = isvalidpo($params{content});
489 if (istranslation($params{page})) {
490 return gettext("Can not remove a translation. If the master page is removed, ".
491 "however, its translations will be removed as well.");
498 my $session = $params{session};
500 if (istranslation($params{src})) {
501 my $masterpage = masterpage($params{src});
502 # Tell the difference between:
503 # - a translation being renamed as a consequence of its master page
504 # being renamed, which is allowed
505 # - a user trying to directly rename a translation, which is forbidden
506 # by looking for the master page in the list of to-be-renamed pages we
507 # saved early in the renaming process.
508 my $orig_torename = $session->param("po_orig_torename");
509 unless (grep { $_ eq $masterpage } @{$orig_torename}) {
510 return gettext("Can not rename a translation. If the master page is renamed, ".
511 "however, its translations will be renamed as well.");
517 # As we're previewing or saving a page, the content may have
518 # changed, so tell the next filter() invocation it must not be lazy.
522 unsetalreadyfiltered($params{page}, $params{page});
523 return $params{content};
526 sub formbuilder_setup (@) {
528 my $form=$params{form};
531 return unless defined $form->field("do");
533 if ($form->field("do") eq "create") {
534 # Warn the user: new pages must be written in master language.
535 my $template=template("pocreatepage.tmpl");
536 $template->param(LANG => $master_language_name);
537 $form->tmpl_param(message => $template->output);
539 elsif ($form->field("do") eq "edit") {
540 # Remove the rename/remove buttons on slave pages.
541 # This has to be done after the rename/remove plugins have added
542 # their buttons, which is why this hook must be run last.
543 # The canrename/canremove hooks already ensure this is forbidden
544 # at the backend level, so this is only UI sugar.
545 if (istranslation($form->field("page"))) {
547 for (my $i = 0; $i < @{$params{buttons}}; $i++) {
548 if (@{$params{buttons}}[$i] eq $_) {
549 delete @{$params{buttons}}[$i];
558 sub formbuilder (@) {
560 my $form=$params{form};
563 return unless defined $form->field("do");
565 # Do not allow to create pages of type po: they are automatically created.
566 # The main reason to do so is to bypass the "favor the type of linking page
567 # on page creation" logic, which is unsuitable when a broken link is clicked
568 # on a slave (PO) page.
569 # This cannot be done in the formbuilder_setup hook as the list of types is
571 if ($form->field("do") eq "create") {
572 foreach my $field ($form->field) {
573 next unless "$field" eq "type";
574 next unless $field->type eq 'select';
575 my $orig_value = $field->value;
576 # remove po from the list of types
577 my @types = grep { $_->[0] ne 'po' } $field->options;
578 $field->options(\@types) if @types;
579 # favor the type of linking page's masterpage
580 if ($orig_value eq 'po') {
582 if (defined $form->field('from')) {
583 ($from)=$form->field('from')=~/$config{wiki_file_regexp}/;
584 $from = masterpage($from);
586 if (defined $from && exists $pagesources{$from}) {
587 $type=pagetype($pagesources{$from});
589 $type=$config{default_pageext} unless defined $type;
590 $field->value($type) ;
597 # | Injected functions
600 # Implement po_link_to 'current' and 'negotiated' settings.
601 sub mybestlink ($$) {
605 return $origsubs{'bestlink'}->($page, $link)
606 if defined $config{po_link_to} && $config{po_link_to} eq "default";
608 my $res=$origsubs{'bestlink'}->(masterpage($page), $link);
609 my @caller = caller(1);
611 && istranslatedto($res, lang($page))
612 && istranslation($page)
613 && !(exists $caller[3] && defined $caller[3]
614 && ($caller[3] eq "IkiWiki::PageSpec::match_link"))) {
615 return $res . "." . lang($page);
620 sub mybeautify_urlpath ($) {
623 my $res=$origsubs{'beautify_urlpath'}->($url);
624 if (defined $config{po_link_to} && $config{po_link_to} eq "negotiated") {
625 $res =~ s!/\Qindex.$master_language_code.$config{htmlext}\E$!/!;
626 $res =~ s!/\Qindex.$config{htmlext}\E$!/!;
628 $res =~ s!/\Qindex.$_.$config{htmlext}\E$!/!;
634 sub mytargetpage ($$;$) {
639 if (istranslation($page) || istranslatable($page)) {
640 my ($masterpage, $lang) = (masterpage($page), lang($page));
641 if (defined $filename) {
642 return $masterpage . "/" . $filename . "." . $lang . "." . $ext;
644 elsif (! $config{usedirs} || $masterpage eq 'index') {
645 return $masterpage . "." . $lang . "." . $ext;
648 return $masterpage . "/index." . $lang . "." . $ext;
651 return $origsubs{'targetpage'}->($page, $ext, $filename);
659 # workaround hard-coded /index.$config{htmlext} in IkiWiki::urlto()
661 && $config{po_link_to} eq "current"
662 && istranslatable('index')) {
664 return IkiWiki::beautify_urlpath(IkiWiki::baseurl($from) . "index." . lang($from) . ".$config{htmlext}");
667 return $origsubs{'urlto'}->($to,$from,$absolute);
670 # avoid using our injected beautify_urlpath if run by cgi_editpage,
671 # so that one is redirected to the just-edited page rather than to the
672 # negociated translation; to prevent unnecessary fiddling with caller/inject,
673 # we only do so when our beautify_urlpath would actually do what we want to
674 # avoid, i.e. when po_link_to = negotiated.
675 # also avoid doing so when run by cgi_goto, so that the links on recentchanges
676 # page actually lead to the exact page they pretend to.
677 if ($config{po_link_to} eq "negotiated") {
678 my @caller = caller(1);
680 $use_orig = 1 if (exists $caller[3] && defined $caller[3]
681 && ($caller[3] eq "IkiWiki::cgi_editpage" ||
682 $caller[3] eq "IkiWiki::Plugin::goto::cgi_goto")
684 inject(name => "IkiWiki::beautify_urlpath", call => $origsubs{'beautify_urlpath'})
686 my $res = $origsubs{'urlto'}->($to,$from,$absolute);
687 inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath)
692 return $origsubs{'urlto'}->($to,$from,$absolute)
699 # slave pages have no subpages
700 if (istranslation($params{'from'})) {
701 $params{'from'} = masterpage($params{'from'});
703 return $origsubs{'cgiurl'}->(%params);
710 if (exists $params{rootpage}) {
711 $rootpage=$origsubs{'bestlink'}->($params{page}, $params{rootpage});
712 if (!length $rootpage) {
713 $rootpage=$params{rootpage};
717 $rootpage=masterpage($params{page});
722 sub myisselflink ($$) {
726 return 1 if $origsubs{'isselflink'}->($page, $link);
727 if (istranslation($page)) {
728 return $origsubs{'isselflink'}->(masterpage($page), $link);
734 # | Blackboxes for private data
740 sub alreadyfiltered($$) {
744 return exists $filtered{$page}{$destpage}
745 && $filtered{$page}{$destpage} eq 1;
748 sub setalreadyfiltered($$) {
752 $filtered{$page}{$destpage}=1;
755 sub unsetalreadyfiltered($$) {
759 if (exists $filtered{$page}{$destpage}) {
760 delete $filtered{$page}{$destpage};
764 sub resetalreadyfiltered() {
773 sub maybe_add_leading_slash ($;$) {
776 $add=1 unless defined $add;
777 return '/' . $str if $add;
781 sub istranslatablefile ($) {
784 return 0 unless defined $file;
785 my $type=pagetype($file);
786 return 0 if ! defined $type || $type eq 'po';
787 return 0 if $file =~ /\.pot$/;
788 return 0 if ! defined $config{po_translatable_pages};
789 return 1 if pagespec_match(pagename($file), $config{po_translatable_pages});
793 sub istranslatable ($) {
797 return 1 if istranslatablefile($pagesources{$page});
801 sub istranslatedto ($$) {
803 my $destlang = shift;
806 return 0 unless istranslatable($page);
807 exists $pagesources{otherlanguage_page($page, $destlang)};
810 sub _istranslation ($) {
813 $page='' unless defined $page && length $page;
814 my $hasleadingslash = ($page=~s#^/##);
815 my $file=$pagesources{$page};
816 return 0 unless defined $file
817 && defined pagetype($file)
818 && pagetype($file) eq 'po';
819 return 0 if $file =~ /\.pot$/;
821 my ($masterpage, $lang) = ($page =~ /(.*)[.]($language_code_pattern)$/);
822 return 0 unless defined $masterpage && defined $lang
823 && length $masterpage && length $lang
824 && defined $pagesources{$masterpage}
825 && defined $slavelanguages{$lang};
827 return (maybe_add_leading_slash($masterpage, $hasleadingslash), $lang)
828 if istranslatable($masterpage);
831 sub istranslation ($) {
834 if (1 < (my ($masterpage, $lang) = _istranslation($page))) {
835 my $hasleadingslash = ($masterpage=~s#^/##);
836 $translations{$masterpage}{$lang}=$page unless exists $translations{$masterpage}{$lang};
837 return (maybe_add_leading_slash($masterpage, $hasleadingslash), $lang);
845 if ( 1 < (my ($masterpage, $lang) = _istranslation($page))) {
854 if (1 < (my ($masterpage, $lang) = _istranslation($page))) {
857 return $master_language_code;
860 sub islanguagecode ($) {
863 return $code =~ /^$language_code_pattern$/;
866 sub otherlanguage_page ($$) {
870 return masterpage($page) if $code eq $master_language_code;
871 return masterpage($page) . '.' . $code;
874 # Returns the list of other languages codes: the master language comes first,
875 # then the codes are ordered the same way as in po_slave_languages, if it is
876 # an array, or in the language name lexical order, if it is a hash.
877 sub otherlanguages_codes ($) {
881 return \@ret unless istranslation($page) || istranslatable($page);
882 my $curlang=lang($page);
884 ($master_language_code, @slavelanguages) {
885 next if $lang eq $curlang;
886 if ($lang eq $master_language_code ||
887 istranslatedto(masterpage($page), $lang)) {
894 sub otherlanguages_pages ($) {
899 $ret{$_} = otherlanguage_page($page, $_)
900 } @{otherlanguages_codes($page)};
906 my $masterfile=shift;
908 (my $name, my $dir, my $suffix) = fileparse($masterfile, qr/\.[^.]*/);
909 $dir='' if $dir eq './';
910 return File::Spec->catpath('', $dir, $name . ".pot");
914 my $masterfile=shift;
917 (my $name, my $dir, my $suffix) = fileparse($masterfile, qr/\.[^.]*/);
918 $dir='' if $dir eq './';
919 return File::Spec->catpath('', $dir, $name . "." . $lang . ".po");
923 my $masterfile=shift;
925 return map pofile($masterfile, $_), @slavelanguages;
929 my $masterfile=shift;
931 my $potfile=potfile($masterfile);
932 my $doc=Locale::Po4a::Chooser::new(po4a_type($masterfile),
933 po4a_options($masterfile));
934 $doc->{TT}{utf_mode} = 1;
935 $doc->{TT}{file_in_charset} = 'UTF-8';
936 $doc->{TT}{file_out_charset} = 'UTF-8';
937 $doc->read($masterfile);
938 # let's cheat a bit to force porefs option to be passed to
939 # Locale::Po4a::Po; this is undocument use of internal
940 # Locale::Po4a::TransTractor's data, compulsory since this module
941 # prevents us from using the porefs option.
942 $doc->{TT}{po_out}=Locale::Po4a::Po->new({ 'porefs' => 'none' });
943 $doc->{TT}{po_out}->set_charset('UTF-8');
946 IkiWiki::prep_writefile(basename($potfile),dirname($potfile));
947 $doc->writepo($potfile);
950 sub refreshpofiles ($@) {
951 my $masterfile=shift;
954 my $potfile=potfile($masterfile);
956 error("po(refreshpofiles) ".sprintf(gettext("POT file (%s) does not exist"), $potfile));
959 foreach my $pofile (@pofiles) {
960 IkiWiki::prep_writefile(basename($pofile),dirname($pofile));
963 # If the po file exists in an underlay, copy it
965 my ($pobase)=$pofile=~/^\Q$config{srcdir}\E\/?(.*)$/;
966 foreach my $dir (@{$config{underlaydirs}}) {
967 if (-e "$dir/$pobase") {
968 File::Copy::syscopy("$dir/$pobase",$pofile)
969 or error("po(refreshpofiles) ".
970 sprintf(gettext("failed to copy underlay PO file to %s"),
977 system("msgmerge", "--previous", "-q", "-U", "--backup=none", $pofile, $potfile) == 0
978 or error("po(refreshpofiles) ".
979 sprintf(gettext("failed to update %s"),
983 File::Copy::syscopy($potfile,$pofile)
984 or error("po(refreshpofiles) ".
985 sprintf(gettext("failed to copy the POT file to %s"),
991 sub buildtranslationscache() {
992 # use istranslation's side-effect
993 map istranslation($_), (keys %pagesources);
996 sub resettranslationscache() {
1000 sub flushmemoizecache() {
1001 Memoize::flush_cache("istranslatable");
1002 Memoize::flush_cache("_istranslation");
1003 Memoize::flush_cache("percenttranslated");
1006 sub urlto_with_orig_beautiful_urlpath($$) {
1010 inject(name => "IkiWiki::beautify_urlpath", call => $origsubs{'beautify_urlpath'});
1011 my $res=urlto($to, $from);
1012 inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath);
1017 sub percenttranslated ($) {
1021 return gettext("N/A") unless istranslation($page);
1022 my $file=srcfile($pagesources{$page});
1023 my $masterfile = srcfile($pagesources{masterpage($page)});
1024 my $doc=Locale::Po4a::Chooser::new(po4a_type($masterfile),
1025 po4a_options($masterfile));
1027 'po_in_name' => [ $file ],
1028 'file_in_name' => [ $masterfile ],
1029 'file_in_charset' => 'UTF-8',
1030 'file_out_charset' => 'UTF-8',
1031 ) or error("po(percenttranslated) ".
1032 sprintf(gettext("failed to translate %s"), $page));
1033 my ($percent,$hit,$queries) = $doc->stats();
1034 $percent =~ s/\.[0-9]+$//;
1038 sub languagename ($) {
1041 return $master_language_name
1042 if $code eq $master_language_code;
1043 return $slavelanguages{$code}
1044 if defined $slavelanguages{$code};
1048 sub otherlanguagesloop ($) {
1052 if (istranslation($page)) {
1054 url => urlto_with_orig_beautiful_urlpath(masterpage($page), $page),
1055 code => $master_language_code,
1056 language => $master_language_name,
1060 foreach my $lang (@{otherlanguages_codes($page)}) {
1061 next if $lang eq $master_language_code;
1062 my $otherpage = otherlanguage_page($page, $lang);
1064 url => urlto_with_orig_beautiful_urlpath($otherpage, $page),
1066 language => languagename($lang),
1067 percent => percenttranslated($otherpage),
1073 sub homepageurl (;$) {
1076 return urlto('', $page);
1079 sub ishomepage ($) {
1082 return 1 if $page eq 'index';
1083 map { return 1 if $page eq 'index.'.$_ } @slavelanguages;
1087 sub deletetranslations ($) {
1088 my $deletedmasterfile=shift;
1090 my $deletedmasterpage=pagename($deletedmasterfile);
1093 my $file = newpagefile($deletedmasterpage.'.'.$_, 'po');
1094 my $absfile = "$config{srcdir}/$file";
1095 if (-e $absfile && ! -l $absfile && ! -d $absfile) {
1096 push @todelete, $file;
1102 IkiWiki::rcs_remove($_);
1105 IkiWiki::prune("$config{srcdir}/$_", $config{srcdir});
1111 gettext("removed obsolete PO files"));
1115 sub commit_and_refresh ($) {
1119 IkiWiki::disable_commit_hook();
1120 IkiWiki::rcs_commit_staged(
1123 IkiWiki::enable_commit_hook();
1124 IkiWiki::rcs_update();
1126 # Reinitialize module's private variables.
1127 resetalreadyfiltered();
1128 resettranslationscache();
1129 flushmemoizecache();
1130 # Trigger a wiki refresh.
1131 require IkiWiki::Render;
1132 # without preliminary saveindex/loadindex, refresh()
1133 # complains about a lot of uninitialized variables
1134 IkiWiki::saveindex();
1135 IkiWiki::loadindex();
1137 IkiWiki::saveindex();
1140 sub po_to_markup ($$) {
1141 my ($page, $content) = (shift, shift);
1143 $content = '' unless defined $content;
1144 $content = decode_utf8(encode_utf8($content));
1145 # CRLF line terminators make poor Locale::Po4a feel bad
1146 $content=~s/\r\n/\n/g;
1148 # There are incompatibilities between some File::Temp versions
1149 # (including 0.18, bundled with Lenny's perl-modules package)
1150 # and others (e.g. 0.20, previously present in the archive as
1151 # a standalone package): under certain circumstances, some
1152 # return a relative filename, whereas others return an absolute one;
1153 # we here use this module in a way that is at least compatible
1154 # with 0.18 and 0.20. Beware, hit'n'run refactorers!
1155 my $infile = new File::Temp(TEMPLATE => "ikiwiki-po-filter-in.XXXXXXXXXX",
1156 DIR => File::Spec->tmpdir,
1157 UNLINK => 1)->filename;
1158 my $outfile = new File::Temp(TEMPLATE => "ikiwiki-po-filter-out.XXXXXXXXXX",
1159 DIR => File::Spec->tmpdir,
1160 UNLINK => 1)->filename;
1162 my $fail = sub ($) {
1163 my $msg = "po(po_to_markup) - $page : " . shift;
1164 error($msg, sub { unlink $infile, $outfile});
1167 writefile(basename($infile), File::Spec->tmpdir, $content)
1168 or return $fail->(sprintf(gettext("failed to write %s"), $infile));
1170 my $masterfile = srcfile($pagesources{masterpage($page)});
1171 my $doc=Locale::Po4a::Chooser::new(po4a_type($masterfile),
1172 po4a_options($masterfile));
1174 'po_in_name' => [ $infile ],
1175 'file_in_name' => [ $masterfile ],
1176 'file_in_charset' => 'UTF-8',
1177 'file_out_charset' => 'UTF-8',
1178 ) or return $fail->(gettext("failed to translate"));
1179 $doc->write($outfile)
1180 or return $fail->(sprintf(gettext("failed to write %s"), $outfile));
1182 $content = readfile($outfile);
1184 # Unlinking should happen automatically, thanks to File::Temp,
1185 # but it does not work here, probably because of the way writefile()
1186 # and Locale::Po4a::write() work.
1187 unlink $infile, $outfile;
1192 # returns a SuccessReason or FailReason object
1194 my $content = shift;
1196 # NB: we don't use po_to_markup here, since Po4a parser does
1197 # not mind invalid PO content
1198 $content = '' unless defined $content;
1199 $content = decode_utf8(encode_utf8($content));
1201 # There are incompatibilities between some File::Temp versions
1202 # (including 0.18, bundled with Lenny's perl-modules package)
1203 # and others (e.g. 0.20, previously present in the archive as
1204 # a standalone package): under certain circumstances, some
1205 # return a relative filename, whereas others return an absolute one;
1206 # we here use this module in a way that is at least compatible
1207 # with 0.18 and 0.20. Beware, hit'n'run refactorers!
1208 my $infile = new File::Temp(TEMPLATE => "ikiwiki-po-isvalidpo.XXXXXXXXXX",
1209 DIR => File::Spec->tmpdir,
1210 UNLINK => 1)->filename;
1212 my $fail = sub ($) {
1213 my $msg = '[po/isvalidpo] ' . shift;
1215 return IkiWiki::FailReason->new("$msg");
1218 writefile(basename($infile), File::Spec->tmpdir, $content)
1219 or return $fail->(sprintf(gettext("failed to write %s"), $infile));
1221 my $res = (system("msgfmt", "--check", $infile, "-o", "/dev/null") == 0);
1223 # Unlinking should happen automatically, thanks to File::Temp,
1224 # but it does not work here, probably because of the way writefile()
1225 # and Locale::Po4a::write() work.
1229 return IkiWiki::SuccessReason->new("valid gettext data");
1231 return IkiWiki::FailReason->new(gettext("invalid gettext data, go back ".
1232 "to previous page to continue edit"));
1238 my $pagetype = pagetype($file);
1239 if ($pagetype eq 'html') {
1245 sub po4a_options($) {
1249 my $pagetype = pagetype($file);
1251 if ($pagetype eq 'html') {
1252 # how to disable options is not consistent across po4a modules
1253 $options{includessi} = '';
1254 $options{includeexternal} = 0;
1255 $options{ontagerror} = 'warn';
1257 elsif ($pagetype eq 'mdwn') {
1258 $options{markdown} = 1;
1261 $options{markdown} = 0;
1267 sub splitlangpair ($) {
1270 my ($code, $name) = ( $pair =~ /^($language_code_pattern)\|(.+)$/ );
1271 if (! defined $code || ! defined $name ||
1272 ! length $code || ! length $name) {
1273 # not a fatal error to avoid breaking if used with web setup
1274 warn sprintf(gettext("%s has invalid syntax: must use CODE|NAME"),
1278 return $code, $name;
1281 sub joinlangpair ($$) {
1285 return "$code|$name";
1292 package IkiWiki::PageSpec;
1294 sub match_istranslation ($;@) {
1297 if (IkiWiki::Plugin::po::istranslation($page)) {
1298 return IkiWiki::SuccessReason->new("is a translation page");
1301 return IkiWiki::FailReason->new("is not a translation page");
1305 sub match_istranslatable ($;@) {
1308 if (IkiWiki::Plugin::po::istranslatable($page)) {
1309 return IkiWiki::SuccessReason->new("is set as translatable in po_translatable_pages");
1312 return IkiWiki::FailReason->new("is not set as translatable in po_translatable_pages");
1316 sub match_lang ($$;@) {
1320 my $regexp=IkiWiki::glob2re($wanted);
1321 my $lang=IkiWiki::Plugin::po::lang($page);
1322 if ($lang !~ $regexp) {
1323 return IkiWiki::FailReason->new("file language is $lang, not $wanted");
1326 return IkiWiki::SuccessReason->new("file language is $wanted");
1330 sub match_currentlang ($$;@) {
1335 return IkiWiki::FailReason->new("no location provided") unless exists $params{location};
1337 my $currentlang=IkiWiki::Plugin::po::lang($params{location});
1338 my $lang=IkiWiki::Plugin::po::lang($page);
1340 if ($lang eq $currentlang) {
1341 return IkiWiki::SuccessReason->new("file language is the same as current one, i.e. $currentlang");
1344 return IkiWiki::FailReason->new("file language is $lang, whereas current language is $currentlang");
1348 sub match_needstranslation ($$;@) {
1352 if (defined $wanted && $wanted ne "") {
1353 if ($wanted !~ /^\d+$/) {
1354 return IkiWiki::FailReason->new("parameter is not an integer");
1356 elsif ($wanted > 100) {
1357 return IkiWiki::FailReason->new("parameter is greater than 100");
1364 my $percenttranslated=IkiWiki::Plugin::po::percenttranslated($page);
1365 if ($percenttranslated eq 'N/A') {
1366 return IkiWiki::FailReason->new("file is not a translatable page");
1368 elsif ($percenttranslated < $wanted) {
1369 return IkiWiki::SuccessReason->new("file has $percenttranslated translated");
1372 return IkiWiki::FailReason->new("file is translated enough");