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 use Locale::Po4a::Common qw(nowrapi18n);
14 use Locale::Po4a::Chooser;
27 memoize("istranslatable");
28 memoize("_istranslation");
29 memoize("percenttranslated");
32 hook(type => "getsetup", id => "po", call => \&getsetup);
33 hook(type => "checkconfig", id => "po", call => \&checkconfig);
34 hook(type => "needsbuild", id => "po", call => \&needsbuild);
35 hook(type => "scan", id => "po", call => \&scan, last =>1);
36 hook(type => "filter", id => "po", call => \&filter);
37 hook(type => "htmlize", id => "po", call => \&htmlize);
38 hook(type => "pagetemplate", id => "po", call => \&pagetemplate, last => 1);
39 hook(type => "postscan", id => "po", call => \&postscan);
40 hook(type => "rename", id => "po", call => \&renamepages, first => 1);
41 hook(type => "delete", id => "po", call => \&mydelete);
42 hook(type => "change", id => "po", call => \&change);
43 hook(type => "checkcontent", id => "po", call => \&checkcontent);
44 hook(type => "canremove", id => "po", call => \&canremove);
45 hook(type => "canrename", id => "po", call => \&canrename);
46 hook(type => "editcontent", id => "po", call => \&editcontent);
47 hook(type => "formbuilder_setup", id => "po", call => \&formbuilder_setup, last => 1);
48 hook(type => "formbuilder", id => "po", call => \&formbuilder);
50 $origsubs{'bestlink'}=\&IkiWiki::bestlink;
51 inject(name => "IkiWiki::bestlink", call => \&mybestlink);
52 $origsubs{'beautify_urlpath'}=\&IkiWiki::beautify_urlpath;
53 inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath);
54 $origsubs{'targetpage'}=\&IkiWiki::targetpage;
55 inject(name => "IkiWiki::targetpage", call => \&mytargetpage);
56 $origsubs{'urlto'}=\&IkiWiki::urlto;
57 inject(name => "IkiWiki::urlto", call => \&myurlto);
58 $origsubs{'nicepagetitle'}=\&IkiWiki::nicepagetitle;
59 inject(name => "IkiWiki::nicepagetitle", call => \&mynicepagetitle);
60 $origsubs{'cgiurl'}=\&IkiWiki::cgiurl;
61 inject(name => "IkiWiki::cgiurl", call => \&mycgiurl);
70 # 2. Injected functions
71 # 3. Blackboxes for private data
86 po_master_language => {
92 description => "master language (non-PO files)",
96 po_slave_languages => {
100 'es' => 'Castellano',
103 description => "slave languages (PO files)",
107 po_translatable_pages => {
109 example => "!*/Discussion",
110 description => "PageSpec controlling which pages are translatable",
111 link => "ikiwiki/PageSpec",
117 example => "current",
118 description => "internal linking behavior (default/current/negotiated)",
122 po_translation_status_in_links => {
125 description => "display translation status in links to translations",
129 po_strictly_refresh_backlinks => {
132 description => "refresh a page when a backlinked page is changed (can hit performance)",
139 foreach my $field (qw{po_master_language po_slave_languages}) {
140 if (! exists $config{$field} || ! defined $config{$field}) {
141 error(sprintf(gettext("Must specify %s when using the %s plugin"),
145 if (! (keys %{$config{po_slave_languages}})) {
146 error(gettext("At least one slave language must be defined ".
147 "in po_slave_languages when using the po plugin"));
151 or error(sprintf(gettext("%s is not a valid language code"), $_));
152 } ($config{po_master_language}{code}, keys %{$config{po_slave_languages}});
153 if (! exists $config{po_translatable_pages} ||
154 ! defined $config{po_translatable_pages}) {
155 $config{po_translatable_pages}="";
157 if (! exists $config{po_link_to} ||
158 ! defined $config{po_link_to}) {
159 $config{po_link_to}='default';
162 $config{po_link_to} eq $_
163 } ('default', 'current', 'negotiated')) {
164 warn(sprintf(gettext('%s is not a valid value for po_link_to, falling back to po_link_to=default'),
165 $config{po_link_to}));
166 $config{po_link_to}='default';
168 elsif ($config{po_link_to} eq "negotiated" && ! $config{usedirs}) {
169 warn(gettext('po_link_to=negotiated requires usedirs to be enabled, falling back to po_link_to=default'));
170 $config{po_link_to}='default';
172 if (! exists $config{po_translation_status_in_links} ||
173 ! defined $config{po_translation_status_in_links}) {
174 $config{po_translation_status_in_links}=1;
176 if (! exists $config{po_strictly_refresh_backlinks} ||
177 ! defined $config{po_strictly_refresh_backlinks}) {
178 $config{po_strictly_refresh_backlinks}=1;
180 push @{$config{wiki_file_prune_regexps}}, qr/\.pot$/;
184 my $needsbuild=shift;
186 # backup @needsbuild content so that change() can know whether
187 # a given master page was rendered because its source file was changed
188 @origneedsbuild=(@$needsbuild);
191 buildtranslationscache();
193 # make existing translations depend on the corresponding master page
194 foreach my $master (keys %translations) {
195 map add_depends($_, $master), values %{otherlanguages($master)};
199 # Massage the recorded state of internal links so that:
200 # - it matches the actually generated links, rather than the links as written
201 # in the pages' source
202 # - backlinks are consistent in all cases
205 my $page=$params{page};
206 my $content=$params{content};
208 return unless UNIVERSAL::can("IkiWiki::Plugin::link", "import");
210 if (istranslation($page)) {
211 foreach my $destpage (@{$links{$page}}) {
212 if (istranslatable($destpage)) {
213 # replace one occurence of $destpage in $links{$page}
214 # (we only want to replace the one that was added by
215 # IkiWiki::Plugin::link::scan, other occurences may be
216 # there for other reasons)
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};
246 if (istranslation($page) && ! alreadyfiltered($page, $destpage)) {
247 $content = po_to_markup($page, $content);
248 setalreadyfiltered($page, $destpage);
256 my $page = $params{page};
257 my $content = $params{content};
259 # ignore PO files this plugin did not create
260 return $content unless istranslation($page);
262 # force content to be htmlize'd as if it was the same type as the master page
263 return IkiWiki::htmlize($page, $page,
264 pagetype(srcfile($pagesources{masterpage($page)})),
268 sub pagetemplate (@) {
270 my $page=$params{page};
271 my $destpage=$params{destpage};
272 my $template=$params{template};
274 my ($masterpage, $lang) = istranslation($page);
276 if (istranslation($page) && $template->query(name => "percenttranslated")) {
277 $template->param(percenttranslated => percenttranslated($page));
279 if ($template->query(name => "istranslation")) {
280 $template->param(istranslation => scalar istranslation($page));
282 if ($template->query(name => "istranslatable")) {
283 $template->param(istranslatable => istranslatable($page));
285 if ($template->query(name => "HOMEPAGEURL")) {
286 $template->param(homepageurl => homepageurl($page));
288 if ($template->query(name => "otherlanguages")) {
289 $template->param(otherlanguages => [otherlanguagesloop($page)]);
290 map add_depends($page, $_), (values %{otherlanguages($page)});
292 # Rely on IkiWiki::Render's genpage() to decide wether
293 # a discussion link should appear on $page; this is not
294 # totally accurate, though: some broken links may be generated
295 # when cgiurl is disabled.
296 # This compromise avoids some code duplication, and will probably
297 # prevent future breakage when ikiwiki internals change.
298 # Known limitations are preferred to future random bugs.
299 if ($template->param('discussionlink') && istranslation($page)) {
300 $template->param('discussionlink' => htmllink(
303 $masterpage . '/' . gettext("Discussion"),
306 linktext => gettext("Discussion"),
309 # Remove broken parentlink to ./index.html on home page's translations.
310 # It works because this hook has the "last" parameter set, to ensure it
311 # runs after parentlinks' own pagetemplate hook.
312 if ($template->param('parentlinks')
313 && istranslation($page)
314 && $masterpage eq "index") {
315 $template->param('parentlinks' => []);
322 return unless $config{po_strictly_refresh_backlinks};
324 my $page = $params{page};
325 # backlinks involve back-dependencies, so that nicepagetitle effects,
326 # such as translation status displayed in links, are updated
328 map add_depends($page, $_), keys %{$IkiWiki::backlinks{$page}};
331 # Add the renamed page translations to the list of to-be-renamed pages.
335 my @torename = @{$params{torename}};
336 my $session = $params{session};
338 # Save the page(s) the user asked to rename, so that our
339 # canrename hook can tell the difference between:
340 # - a translation being renamed as a consequence of its master page
342 # - a user trying to directly rename a translation
343 # This is why this hook has to be run first, before the list of pages
344 # to rename is modified by other plugins.
345 $session->param(po_orig_torename => \@torename);
346 IkiWiki::cgi_savesession($session);
349 # iterate on @torename and push onto @ret, so that we don't iterate
350 # on the items we added ourselves
351 foreach my $rename (@torename) {
352 next unless istranslatable($rename->{src});
353 my %otherpages=%{otherlanguages($rename->{src})};
354 while (my ($lang, $otherpage) = each %otherpages) {
357 srcfile => $pagesources{$otherpage},
358 dest => otherlanguage($rename->{dest}, $lang),
359 destfile => $rename->{dest}.".".$lang.".po",
370 map { deletetranslations($_) } grep istranslatablefile($_), @deleted;
376 # All meta titles are first extracted at scan time, i.e. before we turn
377 # PO files back into translated markdown; escaping of double-quotes in
378 # PO files breaks the meta plugin's parsing enough to save ugly titles
379 # to %pagestate at this time.
381 # Then, at render time, every page's passes on row through the Great
382 # Rendering Chain (filter->preprocess->linkify->htmlize), and the meta
383 # plugin's preprocess hook is this time in a position to correctly
384 # extract the titles from slave pages.
386 # This is, unfortunately, too late: if the page A, linking to the page B,
387 # is rendered before B, it will display the wrongly-extracted meta title
388 # as the link text to B.
390 # On the one hand, such a corner case only happens on rebuild: on
391 # refresh, every rendered page is fixed to contain correct meta titles.
392 # On the other hand, it can take some time to get every page fixed.
393 # We therefore re-render every rendered page after a rebuild to fix them
394 # at once. As this more or less doubles the time needed to rebuild the
395 # wiki, we do so only when really needed.
398 && exists $config{rebuild} && defined $config{rebuild} && $config{rebuild}
399 && UNIVERSAL::can("IkiWiki::Plugin::meta", "getsetup")
400 && exists $config{meta_overrides_page_title}
401 && defined $config{meta_overrides_page_title}
402 && $config{meta_overrides_page_title}) {
403 debug(sprintf(gettext("re-rendering all pages to fix meta titles")));
404 resetalreadyfiltered();
405 require IkiWiki::Render;
406 foreach my $file (@rendered) {
407 debug(sprintf(gettext("rendering %s"), $file));
408 IkiWiki::render($file);
412 my $updated_po_files=0;
414 # Refresh/create POT and PO files as needed.
415 foreach my $file (grep {istranslatablefile($_)} @rendered) {
416 my $page=pagename($file);
417 my $masterfile=srcfile($file);
418 my $updated_pot_file=0;
419 # Only refresh Pot file if it does not exist, or if
420 # $pagesources{$page} was changed: don't if only the HTML was
421 # refreshed, e.g. because of a dependency.
422 if ((grep { $_ eq $pagesources{$page} } @origneedsbuild)
423 || ! -e potfile($masterfile)) {
424 refreshpot($masterfile);
429 push @pofiles, $_ if ($updated_pot_file || ! -e $_);
430 } (pofiles($masterfile));
432 refreshpofiles($masterfile, @pofiles);
433 map { IkiWiki::rcs_add($_) } @pofiles if $config{rcs};
438 if ($updated_po_files) {
440 gettext("updated PO files"),
441 "IkiWiki::Plugin::po::change");
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. Removing the master page, ".
465 "though, removes its translations 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 { $_->{src} eq $masterpage } @{$orig_torename}) {
484 return gettext("Can not rename a translation. Renaming the master page, ".
485 "though, renames its translations 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 if ($field->type eq 'select') {
549 # remove po from the list of types
550 my @types = grep { $_ ne 'po' } $field->options;
551 $field->options(\@types) if @types;
558 # | Injected functions
561 # Implement po_link_to 'current' and 'negotiated' settings.
562 sub mybestlink ($$) {
566 my $res=$origsubs{'bestlink'}->(masterpage($page), $link);
568 && ($config{po_link_to} eq "current" || $config{po_link_to} eq "negotiated")
569 && istranslatable($res)
570 && istranslation($page)) {
571 return $res . "." . lang($page);
576 sub mybeautify_urlpath ($) {
579 my $res=$origsubs{'beautify_urlpath'}->($url);
580 if ($config{po_link_to} eq "negotiated") {
581 $res =~ s!/\Qindex.$config{po_master_language}{code}.$config{htmlext}\E$!/!;
582 $res =~ s!/\Qindex.$config{htmlext}\E$!/!;
584 $res =~ s!/\Qindex.$_.$config{htmlext}\E$!/!;
585 } (keys %{$config{po_slave_languages}});
590 sub mytargetpage ($$) {
594 if (istranslation($page) || istranslatable($page)) {
595 my ($masterpage, $lang) = (masterpage($page), lang($page));
596 if (! $config{usedirs} || $masterpage eq 'index') {
597 return $masterpage . "." . $lang . "." . $ext;
600 return $masterpage . "/index." . $lang . "." . $ext;
603 return $origsubs{'targetpage'}->($page, $ext);
611 # workaround hard-coded /index.$config{htmlext} in IkiWiki::urlto()
613 && $config{po_link_to} eq "current"
614 && istranslatable('index')) {
615 return IkiWiki::beautify_urlpath(IkiWiki::baseurl($from) . "index." . lang($from) . ".$config{htmlext}");
617 # avoid using our injected beautify_urlpath if run by cgi_editpage,
618 # so that one is redirected to the just-edited page rather than to the
619 # negociated translation; to prevent unnecessary fiddling with caller/inject,
620 # we only do so when our beautify_urlpath would actually do what we want to
621 # avoid, i.e. when po_link_to = negotiated
622 if ($config{po_link_to} eq "negotiated") {
623 my @caller = caller(1);
624 my $run_by_editpage = 0;
625 $run_by_editpage = 1 if (exists $caller[3] && defined $caller[3]
626 && $caller[3] eq "IkiWiki::cgi_editpage");
627 inject(name => "IkiWiki::beautify_urlpath", call => $origsubs{'beautify_urlpath'})
629 my $res = $origsubs{'urlto'}->($to,$from,$absolute);
630 inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath)
635 return $origsubs{'urlto'}->($to,$from,$absolute)
639 sub mynicepagetitle ($;$) {
640 my ($page, $unescaped) = (shift, shift);
642 my $res = $origsubs{'nicepagetitle'}->($page, $unescaped);
643 return $res unless istranslation($page);
644 return $res unless $config{po_translation_status_in_links};
645 my @caller = caller(1);
646 return $res if (exists $caller[3] && defined $caller[3]
647 && $caller[3] eq "IkiWiki::Plugin::parentlinks::parentlinks");
648 return $res.' ('.percenttranslated($page).' %)';
654 # slave pages have no subpages
655 if (istranslation($params{'from'})) {
656 $params{'from'} = masterpage($params{'from'});
658 return $origsubs{'cgiurl'}->(%params);
662 # | Blackboxes for private data
668 sub alreadyfiltered($$) {
672 return exists $filtered{$page}{$destpage}
673 && $filtered{$page}{$destpage} eq 1;
676 sub setalreadyfiltered($$) {
680 $filtered{$page}{$destpage}=1;
683 sub unsetalreadyfiltered($$) {
687 if (exists $filtered{$page}{$destpage}) {
688 delete $filtered{$page}{$destpage};
692 sub resetalreadyfiltered() {
701 sub maybe_add_leading_slash ($;$) {
704 $add=1 unless defined $add;
705 return '/' . $str if $add;
709 sub istranslatablefile ($) {
712 return 0 unless defined $file;
713 return 0 if defined pagetype($file) && pagetype($file) eq 'po';
714 return 0 if $file =~ /\.pot$/;
715 return 0 unless -e "$config{srcdir}/$file"; # underlay dirs may be read-only
716 return 1 if pagespec_match(pagename($file), $config{po_translatable_pages});
720 sub istranslatable ($) {
724 return 1 if istranslatablefile($pagesources{$page});
728 sub _istranslation ($) {
731 $page='' unless defined $page && length $page;
732 my $hasleadingslash = ($page=~s#^/##);
733 my $file=$pagesources{$page};
734 return 0 unless defined $file
735 && defined pagetype($file)
736 && pagetype($file) eq 'po';
737 return 0 if $file =~ /\.pot$/;
739 my ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
740 return 0 unless defined $masterpage && defined $lang
741 && length $masterpage && length $lang
742 && defined $pagesources{$masterpage}
743 && defined $config{po_slave_languages}{$lang};
745 return (maybe_add_leading_slash($masterpage, $hasleadingslash), $lang)
746 if istranslatable($masterpage);
749 sub istranslation ($) {
752 if (1 < (my ($masterpage, $lang) = _istranslation($page))) {
753 my $hasleadingslash = ($masterpage=~s#^/##);
754 $translations{$masterpage}{$lang}=$page unless exists $translations{$masterpage}{$lang};
755 return (maybe_add_leading_slash($masterpage, $hasleadingslash), $lang);
763 if ( 1 < (my ($masterpage, $lang) = _istranslation($page))) {
772 if (1 < (my ($masterpage, $lang) = _istranslation($page))) {
775 return $config{po_master_language}{code};
778 sub islanguagecode ($) {
781 return $code =~ /^[a-z]{2}$/;
784 sub otherlanguage ($$) {
788 return masterpage($page) if $code eq $config{po_master_language}{code};
789 return masterpage($page) . '.' . $code;
792 sub otherlanguages ($) {
796 return \%ret unless istranslation($page) || istranslatable($page);
797 my $curlang=lang($page);
799 ($config{po_master_language}{code}, keys %{$config{po_slave_languages}}) {
800 next if $lang eq $curlang;
801 $ret{$lang}=otherlanguage($page, $lang);
807 my $masterfile=shift;
809 (my $name, my $dir, my $suffix) = fileparse($masterfile, qr/\.[^.]*/);
810 $dir='' if $dir eq './';
811 return File::Spec->catpath('', $dir, $name . ".pot");
815 my $masterfile=shift;
818 (my $name, my $dir, my $suffix) = fileparse($masterfile, qr/\.[^.]*/);
819 $dir='' if $dir eq './';
820 return File::Spec->catpath('', $dir, $name . "." . $lang . ".po");
824 my $masterfile=shift;
826 return map pofile($masterfile, $_), (keys %{$config{po_slave_languages}});
830 my $masterfile=shift;
832 my $potfile=potfile($masterfile);
833 my %options = ("markdown" => (pagetype($masterfile) eq 'mdwn') ? 1 : 0);
834 my $doc=Locale::Po4a::Chooser::new('text',%options);
835 $doc->{TT}{utf_mode} = 1;
836 $doc->{TT}{file_in_charset} = 'utf-8';
837 $doc->{TT}{file_out_charset} = 'utf-8';
838 $doc->read($masterfile);
839 # let's cheat a bit to force porefs option to be passed to Locale::Po4a::Po;
840 # this is undocument use of internal Locale::Po4a::TransTractor's data,
841 # compulsory since this module prevents us from using the porefs option.
842 $doc->{TT}{po_out}=Locale::Po4a::Po->new({ 'porefs' => 'none' });
843 $doc->{TT}{po_out}->set_charset('utf-8');
846 IkiWiki::prep_writefile(basename($potfile),dirname($potfile));
847 $doc->writepo($potfile);
850 sub refreshpofiles ($@) {
851 my $masterfile=shift;
854 my $potfile=potfile($masterfile);
856 error("po(refreshpofiles) ".sprintf(gettext("POT file (%s) does not exist"), $potfile));
859 foreach my $pofile (@pofiles) {
860 IkiWiki::prep_writefile(basename($pofile),dirname($pofile));
862 system("msgmerge", "-U", "--backup=none", $pofile, $potfile) == 0
863 or error("po(refreshpofiles) ".
864 sprintf(gettext("failed to update %s"),
868 File::Copy::syscopy($potfile,$pofile)
869 or error("po(refreshpofiles) ".
870 sprintf(gettext("failed to copy the POT file to %s"),
876 sub buildtranslationscache() {
877 # use istranslation's side-effect
878 map istranslation($_), (keys %pagesources);
881 sub resettranslationscache() {
885 sub flushmemoizecache() {
886 Memoize::flush_cache("istranslatable");
887 Memoize::flush_cache("_istranslation");
888 Memoize::flush_cache("percenttranslated");
891 sub urlto_with_orig_beautiful_urlpath($$) {
895 inject(name => "IkiWiki::beautify_urlpath", call => $origsubs{'beautify_urlpath'});
896 my $res=urlto($to, $from);
897 inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath);
902 sub percenttranslated ($) {
906 return gettext("N/A") unless istranslation($page);
907 my $file=srcfile($pagesources{$page});
908 my $masterfile = srcfile($pagesources{masterpage($page)});
910 "markdown" => (pagetype($masterfile) eq 'mdwn') ? 1 : 0,
912 my $doc=Locale::Po4a::Chooser::new('text',%options);
914 'po_in_name' => [ $file ],
915 'file_in_name' => [ $masterfile ],
916 'file_in_charset' => 'utf-8',
917 'file_out_charset' => 'utf-8',
918 ) or error("po(percenttranslated) ".
919 sprintf(gettext("failed to translate %s"), $page));
920 my ($percent,$hit,$queries) = $doc->stats();
921 $percent =~ s/\.[0-9]+$//;
925 sub languagename ($) {
928 return $config{po_master_language}{name}
929 if $code eq $config{po_master_language}{code};
930 return $config{po_slave_languages}{$code}
931 if defined $config{po_slave_languages}{$code};
935 sub otherlanguagesloop ($) {
939 my %otherpages=%{otherlanguages($page)};
940 while (my ($lang, $otherpage) = each %otherpages) {
941 if (istranslation($page) && masterpage($page) eq $otherpage) {
943 url => urlto_with_orig_beautiful_urlpath($otherpage, $page),
945 language => languagename($lang),
951 url => urlto_with_orig_beautiful_urlpath($otherpage, $page),
953 language => languagename($lang),
954 percent => percenttranslated($otherpage),
959 return -1 if $a->{code} eq $config{po_master_language}{code};
960 return 1 if $b->{code} eq $config{po_master_language}{code};
961 return $a->{language} cmp $b->{language};
965 sub homepageurl (;$) {
968 return urlto('', $page);
971 sub deletetranslations ($) {
972 my $deletedmasterfile=shift;
974 my $deletedmasterpage=pagename($deletedmasterfile);
977 my $file = newpagefile($deletedmasterpage.'.'.$_, 'po');
978 my $absfile = "$config{srcdir}/$file";
979 if (-e $absfile && ! -l $absfile && ! -d $absfile) {
980 push @todelete, $file;
982 } keys %{$config{po_slave_languages}};
986 IkiWiki::rcs_remove($_);
989 IkiWiki::prune("$config{srcdir}/$_");
995 gettext("removed obsolete PO files"),
996 "IkiWiki::Plugin::po::deletetranslations");
1000 sub commit_and_refresh ($$) {
1001 my ($msg, $author) = (shift, shift);
1004 IkiWiki::disable_commit_hook();
1005 IkiWiki::rcs_commit_staged($msg, $author, "127.0.0.1");
1006 IkiWiki::enable_commit_hook();
1007 IkiWiki::rcs_update();
1009 # Reinitialize module's private variables.
1010 resetalreadyfiltered();
1011 resettranslationscache();
1012 flushmemoizecache();
1013 # Trigger a wiki refresh.
1014 require IkiWiki::Render;
1015 # without preliminary saveindex/loadindex, refresh()
1016 # complains about a lot of uninitialized variables
1017 IkiWiki::saveindex();
1018 IkiWiki::loadindex();
1020 IkiWiki::saveindex();
1023 # on success, returns the filtered content.
1024 # on error, if $nonfatal, warn and return undef; else, error out.
1025 sub po_to_markup ($$;$) {
1026 my ($page, $content) = (shift, shift);
1027 my $nonfatal = shift;
1029 $content = '' unless defined $content;
1030 $content = decode_utf8(encode_utf8($content));
1031 # CRLF line terminators make poor Locale::Po4a feel bad
1032 $content=~s/\r\n/\n/g;
1034 # There are incompatibilities between some File::Temp versions
1035 # (including 0.18, bundled with Lenny's perl-modules package)
1036 # and others (e.g. 0.20, previously present in the archive as
1037 # a standalone package): under certain circumstances, some
1038 # return a relative filename, whereas others return an absolute one;
1039 # we here use this module in a way that is at least compatible
1040 # with 0.18 and 0.20. Beware, hit'n'run refactorers!
1041 my $infile = new File::Temp(TEMPLATE => "ikiwiki-po-filter-in.XXXXXXXXXX",
1042 DIR => File::Spec->tmpdir,
1043 UNLINK => 1)->filename;
1044 my $outfile = new File::Temp(TEMPLATE => "ikiwiki-po-filter-out.XXXXXXXXXX",
1045 DIR => File::Spec->tmpdir,
1046 UNLINK => 1)->filename;
1048 my $fail = sub ($) {
1049 my $msg = "po(po_to_markup) - $page : " . shift;
1054 error($msg, sub { unlink $infile, $outfile});
1057 writefile(basename($infile), File::Spec->tmpdir, $content)
1058 or return $fail->(sprintf(gettext("failed to write %s"), $infile));
1060 my $masterfile = srcfile($pagesources{masterpage($page)});
1062 "markdown" => (pagetype($masterfile) eq 'mdwn') ? 1 : 0,
1064 my $doc=Locale::Po4a::Chooser::new('text',%options);
1066 'po_in_name' => [ $infile ],
1067 'file_in_name' => [ $masterfile ],
1068 'file_in_charset' => 'utf-8',
1069 'file_out_charset' => 'utf-8',
1070 ) or return $fail->(gettext("failed to translate"));
1071 $doc->write($outfile)
1072 or return $fail->(sprintf(gettext("failed to write %s"), $outfile));
1074 $content = readfile($outfile)
1075 or return $fail->(sprintf(gettext("failed to read %s"), $outfile));
1077 # Unlinking should happen automatically, thanks to File::Temp,
1078 # but it does not work here, probably because of the way writefile()
1079 # and Locale::Po4a::write() work.
1080 unlink $infile, $outfile;
1085 # returns a SuccessReason or FailReason object
1087 my $content = shift;
1089 # NB: we don't use po_to_markup here, since Po4a parser does
1090 # not mind invalid PO content
1091 $content = '' unless defined $content;
1092 $content = decode_utf8(encode_utf8($content));
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-isvalidpo.XXXXXXXXXX",
1102 DIR => File::Spec->tmpdir,
1103 UNLINK => 1)->filename;
1105 my $fail = sub ($) {
1106 my $msg = '[po/isvalidpo] ' . shift;
1108 return IkiWiki::FailReason->new("$msg");
1111 writefile(basename($infile), File::Spec->tmpdir, $content)
1112 or return $fail->(sprintf(gettext("failed to write %s"), $infile));
1114 my $res = (system("msgfmt", "--check", $infile, "-o", "/dev/null") == 0);
1116 # Unlinking should happen automatically, thanks to File::Temp,
1117 # but it does not work here, probably because of the way writefile()
1118 # and Locale::Po4a::write() work.
1122 return IkiWiki::SuccessReason->new("valid gettext data");
1124 return IkiWiki::FailReason->new("invalid gettext data, go back ".
1125 "to previous page to go on with edit");
1132 package IkiWiki::PageSpec;
1134 sub match_istranslation ($;@) {
1137 if (IkiWiki::Plugin::po::istranslation($page)) {
1138 return IkiWiki::SuccessReason->new("is a translation page");
1141 return IkiWiki::FailReason->new("is not a translation page");
1145 sub match_istranslatable ($;@) {
1148 if (IkiWiki::Plugin::po::istranslatable($page)) {
1149 return IkiWiki::SuccessReason->new("is set as translatable in po_translatable_pages");
1152 return IkiWiki::FailReason->new("is not set as translatable in po_translatable_pages");
1156 sub match_lang ($$;@) {
1160 my $regexp=IkiWiki::glob2re($wanted);
1161 my $lang=IkiWiki::Plugin::po::lang($page);
1162 if ($lang !~ /^$regexp$/i) {
1163 return IkiWiki::FailReason->new("file language is $lang, not $wanted");
1166 return IkiWiki::SuccessReason->new("file language is $wanted");
1170 sub match_currentlang ($$;@) {
1175 return IkiWiki::FailReason->new("no location provided") unless exists $params{location};
1177 my $currentlang=IkiWiki::Plugin::po::lang($params{location});
1178 my $lang=IkiWiki::Plugin::po::lang($page);
1180 if ($lang eq $currentlang) {
1181 return IkiWiki::SuccessReason->new("file language is the same as current one, i.e. $currentlang");
1184 return IkiWiki::FailReason->new("file language is $lang, whereas current language is $currentlang");