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",
132 foreach my $field (qw{po_master_language po_slave_languages}) {
133 if (! exists $config{$field} || ! defined $config{$field}) {
134 error(sprintf(gettext("Must specify %s when using the %s plugin"),
138 if (! (keys %{$config{po_slave_languages}})) {
139 error(gettext("At least one slave language must be defined ".
140 "in po_slave_languages when using the po plugin"));
144 or error(sprintf(gettext("%s is not a valid language code"), $_));
145 } ($config{po_master_language}{code}, keys %{$config{po_slave_languages}});
146 if (! exists $config{po_translatable_pages} ||
147 ! defined $config{po_translatable_pages}) {
148 $config{po_translatable_pages}="";
150 if (! exists $config{po_link_to} ||
151 ! defined $config{po_link_to}) {
152 $config{po_link_to}='default';
155 $config{po_link_to} eq $_
156 } ('default', 'current', 'negotiated')) {
157 warn(sprintf(gettext('%s is not a valid value for po_link_to, falling back to po_link_to=default'),
158 $config{po_link_to}));
159 $config{po_link_to}='default';
161 elsif ($config{po_link_to} eq "negotiated" && ! $config{usedirs}) {
162 warn(gettext('po_link_to=negotiated requires usedirs to be enabled, falling back to po_link_to=default'));
163 $config{po_link_to}='default';
165 if (! exists $config{po_translation_status_in_links} ||
166 ! defined $config{po_translation_status_in_links}) {
167 $config{po_translation_status_in_links}=1;
169 push @{$config{wiki_file_prune_regexps}}, qr/\.pot$/;
173 my $needsbuild=shift;
175 # backup @needsbuild content so that change() can know whether
176 # a given master page was rendered because its source file was changed
177 @origneedsbuild=(@$needsbuild);
180 buildtranslationscache();
182 # make existing translations depend on the corresponding master page
183 foreach my $master (keys %translations) {
184 map add_depends($_, $master), values %{otherlanguages($master)};
188 # Massage the recorded state of internal links so that:
189 # - it matches the actually generated links, rather than the links as written
190 # in the pages' source
191 # - backlinks are consistent in all cases
194 my $page=$params{page};
195 my $content=$params{content};
197 return unless UNIVERSAL::can("IkiWiki::Plugin::link", "import");
199 if (istranslation($page)) {
200 foreach my $destpage (@{$links{$page}}) {
201 if (istranslatable($destpage)) {
202 # replace one occurence of $destpage in $links{$page}
203 # (we only want to replace the one that was added by
204 # IkiWiki::Plugin::link::scan, other occurences may be
205 # there for other reasons)
206 for (my $i=0; $i<@{$links{$page}}; $i++) {
207 if (@{$links{$page}}[$i] eq $destpage) {
208 @{$links{$page}}[$i] = $destpage . '.' . lang($page);
215 elsif (! istranslatable($page) && ! istranslation($page)) {
216 foreach my $destpage (@{$links{$page}}) {
217 if (istranslatable($destpage)) {
218 # make sure any destpage's translations has
219 # $page in its backlinks
220 push @{$links{$page}},
221 values %{otherlanguages($destpage)};
227 # We use filter to convert PO to the master page's format,
228 # since the rest of ikiwiki should not work on PO files.
232 my $page = $params{page};
233 my $destpage = $params{destpage};
234 my $content = $params{content};
235 if (istranslation($page) && ! alreadyfiltered($page, $destpage)) {
236 $content = po_to_markup($page, $content);
237 setalreadyfiltered($page, $destpage);
245 my $page = $params{page};
246 my $content = $params{content};
248 # ignore PO files this plugin did not create
249 return $content unless istranslation($page);
251 # force content to be htmlize'd as if it was the same type as the master page
252 return IkiWiki::htmlize($page, $page,
253 pagetype(srcfile($pagesources{masterpage($page)})),
257 sub pagetemplate (@) {
259 my $page=$params{page};
260 my $destpage=$params{destpage};
261 my $template=$params{template};
263 my ($masterpage, $lang) = istranslation($page);
265 if (istranslation($page) && $template->query(name => "percenttranslated")) {
266 $template->param(percenttranslated => percenttranslated($page));
268 if ($template->query(name => "istranslation")) {
269 $template->param(istranslation => istranslation($page));
271 if ($template->query(name => "istranslatable")) {
272 $template->param(istranslatable => istranslatable($page));
274 if ($template->query(name => "HOMEPAGEURL")) {
275 $template->param(homepageurl => homepageurl($page));
277 if ($template->query(name => "otherlanguages")) {
278 $template->param(otherlanguages => [otherlanguagesloop($page)]);
279 map add_depends($page, $_), (values %{otherlanguages($page)});
281 # Rely on IkiWiki::Render's genpage() to decide wether
282 # a discussion link should appear on $page; this is not
283 # totally accurate, though: some broken links may be generated
284 # when cgiurl is disabled.
285 # This compromise avoids some code duplication, and will probably
286 # prevent future breakage when ikiwiki internals change.
287 # Known limitations are preferred to future random bugs.
288 if ($template->param('discussionlink') && istranslation($page)) {
289 $template->param('discussionlink' => htmllink(
292 $masterpage . '/' . gettext("Discussion"),
295 linktext => gettext("Discussion"),
298 # Remove broken parentlink to ./index.html on home page's translations.
299 # It works because this hook has the "last" parameter set, to ensure it
300 # runs after parentlinks' own pagetemplate hook.
301 if ($template->param('parentlinks')
302 && istranslation($page)
303 && $masterpage eq "index") {
304 $template->param('parentlinks' => []);
310 my $page = $params{page};
312 # backlinks involve back-dependencies, so that nicepagetitle effects,
313 # such as translation status displayed in links, are updated
315 map add_depends($page, $_), keys %{$IkiWiki::backlinks{$page}};
318 # Add the renamed page translations to the list of to-be-renamed pages.
319 sub renamepages($$$) {
320 my ($torename, $cgi, $session) = (shift, shift, shift);
322 # copy the initial array, so that we can iterate on it AND
323 # modify it at the same time, without iterating on the items we
324 # pushed on it ourselves
325 my @torename=@{$torename};
327 # Save the page(s) the user asked to rename, so that our
328 # canrename hook can tell the difference between:
329 # - a translation being renamed as a consequence of its master page
331 # - a user trying to directly rename a translation
332 # This is why this hook has to be run first, before @torename is modified
334 $session->param(po_orig_torename => [ @torename ]);
335 IkiWiki::cgi_savesession($session);
337 foreach my $rename (@torename) {
338 next unless istranslatable($rename->{src});
339 my %otherpages=%{otherlanguages($rename->{src})};
340 while (my ($lang, $otherpage) = each %otherpages) {
343 srcfile => $pagesources{$otherpage},
344 dest => otherlanguage($rename->{dest}, $lang),
345 destfile => $rename->{dest}.".".$lang.".po",
355 map { deletetranslations($_) } grep istranslatablefile($_), @deleted;
361 # All meta titles are first extracted at scan time, i.e. before we turn
362 # PO files back into translated markdown; escaping of double-quotes in
363 # PO files breaks the meta plugin's parsing enough to save ugly titles
364 # to %pagestate at this time.
366 # Then, at render time, every page's passes on row through the Great
367 # Rendering Chain (filter->preprocess->linkify->htmlize), and the meta
368 # plugin's preprocess hook is this time in a position to correctly
369 # extract the titles from slave pages.
371 # This is, unfortunately, too late: if the page A, linking to the page B,
372 # is rendered before B, it will display the wrongly-extracted meta title
373 # as the link text to B.
375 # On the one hand, such a corner case only happens on rebuild: on
376 # refresh, every rendered page is fixed to contain correct meta titles.
377 # On the other hand, it can take some time to get every page fixed.
378 # We therefore re-render every rendered page after a rebuild to fix them
379 # at once. As this more or less doubles the time needed to rebuild the
380 # wiki, we do so only when really needed.
383 && exists $config{rebuild} && defined $config{rebuild} && $config{rebuild}
384 && UNIVERSAL::can("IkiWiki::Plugin::meta", "getsetup")
385 && exists $config{meta_overrides_page_title}
386 && defined $config{meta_overrides_page_title}
387 && $config{meta_overrides_page_title}) {
388 debug(sprintf(gettext("re-rendering all pages to fix meta titles")));
389 resetalreadyfiltered();
390 require IkiWiki::Render;
391 foreach my $file (@rendered) {
392 debug(sprintf(gettext("rendering %s"), $file));
393 IkiWiki::render($file);
397 my $updated_po_files=0;
399 # Refresh/create POT and PO files as needed.
400 foreach my $file (grep {istranslatablefile($_)} @rendered) {
401 my $page=pagename($file);
402 my $masterfile=srcfile($file);
403 my $updated_pot_file=0;
404 # Only refresh Pot file if it does not exist, or if
405 # $pagesources{$page} was changed: don't if only the HTML was
406 # refreshed, e.g. because of a dependency.
407 if ((grep { $_ eq $pagesources{$page} } @origneedsbuild)
408 || ! -e potfile($masterfile)) {
409 refreshpot($masterfile);
414 push @pofiles, $_ if ($updated_pot_file || ! -e $_);
415 } (pofiles($masterfile));
417 refreshpofiles($masterfile, @pofiles);
418 map { IkiWiki::rcs_add($_) } @pofiles if $config{rcs};
423 if ($updated_po_files) {
425 gettext("updated PO files"),
426 "IkiWiki::Plugin::po::change");
430 sub checkcontent (@) {
433 if (istranslation($params{page})) {
434 my $res = isvalidpo($params{content});
445 sub canremove ($$$) {
446 my ($page, $cgi, $session) = (shift, shift, shift);
448 if (istranslation($page)) {
449 return gettext("Can not remove a translation. Removing the master page, ".
450 "though, removes its translations as well.");
455 sub canrename ($$@) {
456 my ($cgi, $session) = (shift, shift);
459 if (istranslation($params{src})) {
460 my $masterpage = masterpage($params{src});
461 # Tell the difference between:
462 # - a translation being renamed as a consequence of its master page
463 # being renamed, which is allowed
464 # - a user trying to directly rename a translation, which is forbidden
465 # by looking for the master page in the list of to-be-renamed pages we
466 # saved early in the renaming process.
467 my $orig_torename = $session->param("po_orig_torename");
468 unless (grep { $_->{src} eq $masterpage } @{$orig_torename}) {
469 return gettext("Can not rename a translation. Renaming the master page, ".
470 "though, renames its translations as well.");
476 # As we're previewing or saving a page, the content may have
477 # changed, so tell the next filter() invocation it must not be lazy.
481 unsetalreadyfiltered($params{page}, $params{page});
482 return $params{content};
485 sub formbuilder_setup (@) {
487 my $form=$params{form};
490 return unless defined $form->field("do");
492 if ($form->field("do") eq "create") {
493 # Warn the user: new pages must be written in master language.
494 my $template=template("pocreatepage.tmpl");
495 $template->param(LANG => $config{po_master_language}{name});
496 $form->tmpl_param(message => $template->output);
498 elsif ($form->field("do") eq "edit") {
499 # Remove the rename/remove buttons on slave pages.
500 # This has to be done after the rename/remove plugins have added
501 # their buttons, which is why this hook must be run last.
502 # The canrename/canremove hooks already ensure this is forbidden
503 # at the backend level, so this is only UI sugar.
504 if (istranslation($form->field("page"))) {
506 for (my $i = 0; $i < @{$params{buttons}}; $i++) {
507 if (@{$params{buttons}}[$i] eq $_) {
508 delete @{$params{buttons}}[$i];
517 sub formbuilder (@) {
519 my $form=$params{form};
522 return unless defined $form->field("do");
524 # Do not allow to create pages of type po: they are automatically created.
525 # The main reason to do so is to bypass the "favor the type of linking page
526 # on page creation" logic, which is unsuitable when a broken link is clicked
527 # on a slave (PO) page.
528 # This cannot be done in the formbuilder_setup hook as the list of types is
530 if ($form->field("do") eq "create") {
531 foreach my $field ($form->field) {
532 next unless "$field" eq "type";
533 if ($field->type eq 'select') {
534 # remove po from the list of types
535 my @types = grep { $_ ne 'po' } $field->options;
536 $field->options(\@types) if @types;
539 # make sure the default value is not po;
540 # does this case actually happen?
541 debug "po(formbuilder) ".gettext("type field is not selected - not implemented yet");
548 # | Injected functions
551 # Implement po_link_to 'current' and 'negotiated' settings.
552 sub mybestlink ($$) {
556 my $res=$origsubs{'bestlink'}->(masterpage($page), $link);
558 && ($config{po_link_to} eq "current" || $config{po_link_to} eq "negotiated")
559 && istranslatable($res)
560 && istranslation($page)) {
561 return $res . "." . lang($page);
566 sub mybeautify_urlpath ($) {
569 my $res=$origsubs{'beautify_urlpath'}->($url);
570 if ($config{po_link_to} eq "negotiated") {
571 $res =~ s!/\Qindex.$config{po_master_language}{code}.$config{htmlext}\E$!/!;
572 $res =~ s!/\Qindex.$config{htmlext}\E$!/!;
574 $res =~ s!/\Qindex.$_.$config{htmlext}\E$!/!;
575 } (keys %{$config{po_slave_languages}});
580 sub mytargetpage ($$) {
584 if (istranslation($page) || istranslatable($page)) {
585 my ($masterpage, $lang) = (masterpage($page), lang($page));
586 if (! $config{usedirs} || $masterpage eq 'index') {
587 return $masterpage . "." . $lang . "." . $ext;
590 return $masterpage . "/index." . $lang . "." . $ext;
593 return $origsubs{'targetpage'}->($page, $ext);
601 # workaround hard-coded /index.$config{htmlext} in IkiWiki::urlto()
603 && $config{po_link_to} eq "current"
604 && istranslatable('index')) {
605 return IkiWiki::beautify_urlpath(IkiWiki::baseurl($from) . "index." . lang($from) . ".$config{htmlext}");
607 # avoid using our injected beautify_urlpath if run by cgi_editpage,
608 # so that one is redirected to the just-edited page rather than to the
609 # negociated translation; to prevent unnecessary fiddling with caller/inject,
610 # we only do so when our beautify_urlpath would actually do what we want to
611 # avoid, i.e. when po_link_to = negotiated
612 if ($config{po_link_to} eq "negotiated") {
613 my @caller = caller(1);
614 my $run_by_editpage = 0;
615 $run_by_editpage = 1 if (exists $caller[3] && defined $caller[3]
616 && $caller[3] eq "IkiWiki::cgi_editpage");
617 inject(name => "IkiWiki::beautify_urlpath", call => $origsubs{'beautify_urlpath'})
619 my $res = $origsubs{'urlto'}->($to,$from,$absolute);
620 inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath)
625 return $origsubs{'urlto'}->($to,$from,$absolute)
629 sub mynicepagetitle ($;$) {
630 my ($page, $unescaped) = (shift, shift);
632 my $res = $origsubs{'nicepagetitle'}->($page, $unescaped);
633 return $res unless istranslation($page);
634 return $res unless $config{po_translation_status_in_links};
635 my @caller = caller(1);
636 return $res if (exists $caller[3] && defined $caller[3]
637 && $caller[3] eq "IkiWiki::Plugin::parentlinks::parentlinks");
638 return $res.' ('.percenttranslated($page).' %)';
644 # slave pages have no subpages
645 if (istranslation($params{'from'})) {
646 $params{'from'} = masterpage($params{'from'});
648 return $origsubs{'cgiurl'}->(%params);
652 # | Blackboxes for private data
658 sub alreadyfiltered($$) {
662 return exists $filtered{$page}{$destpage}
663 && $filtered{$page}{$destpage} eq 1;
666 sub setalreadyfiltered($$) {
670 $filtered{$page}{$destpage}=1;
673 sub unsetalreadyfiltered($$) {
677 if (exists $filtered{$page}{$destpage}) {
678 delete $filtered{$page}{$destpage};
682 sub resetalreadyfiltered() {
691 sub maybe_add_leading_slash ($;$) {
694 $add=1 unless defined $add;
695 return '/' . $str if $add;
699 sub istranslatablefile ($) {
702 return 0 unless defined $file;
703 return 0 if defined pagetype($file) && pagetype($file) eq 'po';
704 return 0 if $file =~ /\.pot$/;
705 return 0 unless -e "$config{srcdir}/$file"; # underlay dirs may be read-only
706 return 1 if pagespec_match(pagename($file), $config{po_translatable_pages});
710 sub istranslatable ($) {
714 return 1 if istranslatablefile($pagesources{$page});
718 sub _istranslation ($) {
721 $page='' unless defined $page && length $page;
722 my $hasleadingslash = ($page=~s#^/##);
723 my $file=$pagesources{$page};
724 return 0 unless defined $file
725 && defined pagetype($file)
726 && pagetype($file) eq 'po';
727 return 0 if $file =~ /\.pot$/;
729 my ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
730 return 0 unless defined $masterpage && defined $lang
731 && length $masterpage && length $lang
732 && defined $pagesources{$masterpage}
733 && defined $config{po_slave_languages}{$lang};
735 return (maybe_add_leading_slash($masterpage, $hasleadingslash), $lang)
736 if istranslatable($masterpage);
739 sub istranslation ($) {
742 if (1 < (my ($masterpage, $lang) = _istranslation($page))) {
743 my $hasleadingslash = ($masterpage=~s#^/##);
744 $translations{$masterpage}{$lang}=$page unless exists $translations{$masterpage}{$lang};
745 return (maybe_add_leading_slash($masterpage, $hasleadingslash), $lang);
753 if ( 1 < (my ($masterpage, $lang) = _istranslation($page))) {
762 if (1 < (my ($masterpage, $lang) = _istranslation($page))) {
765 return $config{po_master_language}{code};
768 sub islanguagecode ($) {
771 return $code =~ /^[a-z]{2}$/;
774 sub otherlanguage ($$) {
778 return masterpage($page) if $code eq $config{po_master_language}{code};
779 return masterpage($page) . '.' . $code;
782 sub otherlanguages ($) {
786 return \%ret unless istranslation($page) || istranslatable($page);
787 my $curlang=lang($page);
789 ($config{po_master_language}{code}, keys %{$config{po_slave_languages}}) {
790 next if $lang eq $curlang;
791 $ret{$lang}=otherlanguage($page, $lang);
797 my $masterfile=shift;
799 (my $name, my $dir, my $suffix) = fileparse($masterfile, qr/\.[^.]*/);
800 $dir='' if $dir eq './';
801 return File::Spec->catpath('', $dir, $name . ".pot");
805 my $masterfile=shift;
808 (my $name, my $dir, my $suffix) = fileparse($masterfile, qr/\.[^.]*/);
809 $dir='' if $dir eq './';
810 return File::Spec->catpath('', $dir, $name . "." . $lang . ".po");
814 my $masterfile=shift;
816 return map pofile($masterfile, $_), (keys %{$config{po_slave_languages}});
820 my $masterfile=shift;
822 my $potfile=potfile($masterfile);
823 my %options = ("markdown" => (pagetype($masterfile) eq 'mdwn') ? 1 : 0);
824 my $doc=Locale::Po4a::Chooser::new('text',%options);
825 $doc->{TT}{utf_mode} = 1;
826 $doc->{TT}{file_in_charset} = 'utf-8';
827 $doc->{TT}{file_out_charset} = 'utf-8';
828 $doc->read($masterfile);
829 # let's cheat a bit to force porefs option to be passed to Locale::Po4a::Po;
830 # this is undocument use of internal Locale::Po4a::TransTractor's data,
831 # compulsory since this module prevents us from using the porefs option.
832 $doc->{TT}{po_out}=Locale::Po4a::Po->new({ 'porefs' => 'none' });
833 $doc->{TT}{po_out}->set_charset('utf-8');
836 IkiWiki::prep_writefile(basename($potfile),dirname($potfile));
837 $doc->writepo($potfile);
840 sub refreshpofiles ($@) {
841 my $masterfile=shift;
844 my $potfile=potfile($masterfile);
846 error("po(refreshpofiles) ".sprintf(gettext("POT file (%s) does not exist"), $potfile));
849 foreach my $pofile (@pofiles) {
850 IkiWiki::prep_writefile(basename($pofile),dirname($pofile));
852 system("msgmerge", "-U", "--backup=none", $pofile, $potfile) == 0
853 or error("po(refreshpofiles) ".
854 sprintf(gettext("failed to update %s"),
858 File::Copy::syscopy($potfile,$pofile)
859 or error("po(refreshpofiles) ".
860 sprintf(gettext("failed to copy the POT file to %s"),
866 sub buildtranslationscache() {
867 # use istranslation's side-effect
868 map istranslation($_), (keys %pagesources);
871 sub resettranslationscache() {
875 sub flushmemoizecache() {
876 Memoize::flush_cache("istranslatable");
877 Memoize::flush_cache("_istranslation");
878 Memoize::flush_cache("percenttranslated");
881 sub urlto_with_orig_beautiful_urlpath($$) {
885 inject(name => "IkiWiki::beautify_urlpath", call => $origsubs{'beautify_urlpath'});
886 my $res=urlto($to, $from);
887 inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath);
892 sub percenttranslated ($) {
896 return gettext("N/A") unless istranslation($page);
897 my $file=srcfile($pagesources{$page});
898 my $masterfile = srcfile($pagesources{masterpage($page)});
900 "markdown" => (pagetype($masterfile) eq 'mdwn') ? 1 : 0,
902 my $doc=Locale::Po4a::Chooser::new('text',%options);
904 'po_in_name' => [ $file ],
905 'file_in_name' => [ $masterfile ],
906 'file_in_charset' => 'utf-8',
907 'file_out_charset' => 'utf-8',
908 ) or error("po(percenttranslated) ".
909 sprintf(gettext("failed to translate %s"), $page));
910 my ($percent,$hit,$queries) = $doc->stats();
911 $percent =~ s/\.[0-9]+$//;
915 sub languagename ($) {
918 return $config{po_master_language}{name}
919 if $code eq $config{po_master_language}{code};
920 return $config{po_slave_languages}{$code}
921 if defined $config{po_slave_languages}{$code};
925 sub otherlanguagesloop ($) {
929 my %otherpages=%{otherlanguages($page)};
930 while (my ($lang, $otherpage) = each %otherpages) {
931 if (istranslation($page) && masterpage($page) eq $otherpage) {
933 url => urlto_with_orig_beautiful_urlpath($otherpage, $page),
935 language => languagename($lang),
941 url => urlto_with_orig_beautiful_urlpath($otherpage, $page),
943 language => languagename($lang),
944 percent => percenttranslated($otherpage),
949 return -1 if $a->{code} eq $config{po_master_language}{code};
950 return 1 if $b->{code} eq $config{po_master_language}{code};
951 return $a->{language} cmp $b->{language};
955 sub homepageurl (;$) {
958 return urlto('', $page);
961 sub deletetranslations ($) {
962 my $deletedmasterfile=shift;
964 my $deletedmasterpage=pagename($deletedmasterfile);
967 my $file = newpagefile($deletedmasterpage.'.'.$_, 'po');
968 my $absfile = "$config{srcdir}/$file";
969 if (-e $absfile && ! -l $absfile && ! -d $absfile) {
970 push @todelete, $file;
972 } keys %{$config{po_slave_languages}};
976 IkiWiki::rcs_remove($_);
979 IkiWiki::prune("$config{srcdir}/$_");
985 gettext("removed obsolete PO files"),
986 "IkiWiki::Plugin::po::deletetranslations");
990 sub commit_and_refresh ($$) {
991 my ($msg, $author) = (shift, shift);
994 IkiWiki::disable_commit_hook();
995 IkiWiki::rcs_commit_staged($msg, $author, "127.0.0.1");
996 IkiWiki::enable_commit_hook();
997 IkiWiki::rcs_update();
999 # Reinitialize module's private variables.
1000 resetalreadyfiltered();
1001 resettranslationscache();
1002 flushmemoizecache();
1003 # Trigger a wiki refresh.
1004 require IkiWiki::Render;
1005 # without preliminary saveindex/loadindex, refresh()
1006 # complains about a lot of uninitialized variables
1007 IkiWiki::saveindex();
1008 IkiWiki::loadindex();
1010 IkiWiki::saveindex();
1013 # on success, returns the filtered content.
1014 # on error, if $nonfatal, warn and return undef; else, error out.
1015 sub po_to_markup ($$;$) {
1016 my ($page, $content) = (shift, shift);
1017 my $nonfatal = shift;
1019 $content = '' unless defined $content;
1020 $content = decode_utf8(encode_utf8($content));
1021 # CRLF line terminators make poor Locale::Po4a feel bad
1022 $content=~s/\r\n/\n/g;
1024 # There are incompatibilities between some File::Temp versions
1025 # (including 0.18, bundled with Lenny's perl-modules package)
1026 # and others (e.g. 0.20, previously present in the archive as
1027 # a standalone package): under certain circumstances, some
1028 # return a relative filename, whereas others return an absolute one;
1029 # we here use this module in a way that is at least compatible
1030 # with 0.18 and 0.20. Beware, hit'n'run refactorers!
1031 my $infile = new File::Temp(TEMPLATE => "ikiwiki-po-filter-in.XXXXXXXXXX",
1032 DIR => File::Spec->tmpdir,
1033 UNLINK => 1)->filename;
1034 my $outfile = new File::Temp(TEMPLATE => "ikiwiki-po-filter-out.XXXXXXXXXX",
1035 DIR => File::Spec->tmpdir,
1036 UNLINK => 1)->filename;
1038 my $fail = sub ($) {
1039 my $msg = "po(po_to_markup) - $page : " . shift;
1044 error($msg, sub { unlink $infile, $outfile});
1047 writefile(basename($infile), File::Spec->tmpdir, $content)
1048 or return $fail->(sprintf(gettext("failed to write %s"), $infile));
1050 my $masterfile = srcfile($pagesources{masterpage($page)});
1052 "markdown" => (pagetype($masterfile) eq 'mdwn') ? 1 : 0,
1054 my $doc=Locale::Po4a::Chooser::new('text',%options);
1056 'po_in_name' => [ $infile ],
1057 'file_in_name' => [ $masterfile ],
1058 'file_in_charset' => 'utf-8',
1059 'file_out_charset' => 'utf-8',
1060 ) or return $fail->(gettext("failed to translate"));
1061 $doc->write($outfile)
1062 or return $fail->(sprintf(gettext("failed to write %s"), $outfile));
1064 $content = readfile($outfile)
1065 or return $fail->(sprintf(gettext("failed to read %s"), $outfile));
1067 # Unlinking should happen automatically, thanks to File::Temp,
1068 # but it does not work here, probably because of the way writefile()
1069 # and Locale::Po4a::write() work.
1070 unlink $infile, $outfile;
1075 # returns a SuccessReason or FailReason object
1077 my $content = shift;
1079 # NB: we don't use po_to_markup here, since Po4a parser does
1080 # not mind invalid PO content
1081 $content = '' unless defined $content;
1082 $content = decode_utf8(encode_utf8($content));
1084 # There are incompatibilities between some File::Temp versions
1085 # (including 0.18, bundled with Lenny's perl-modules package)
1086 # and others (e.g. 0.20, previously present in the archive as
1087 # a standalone package): under certain circumstances, some
1088 # return a relative filename, whereas others return an absolute one;
1089 # we here use this module in a way that is at least compatible
1090 # with 0.18 and 0.20. Beware, hit'n'run refactorers!
1091 my $infile = new File::Temp(TEMPLATE => "ikiwiki-po-isvalidpo.XXXXXXXXXX",
1092 DIR => File::Spec->tmpdir,
1093 UNLINK => 1)->filename;
1095 my $fail = sub ($) {
1096 my $msg = '[po/isvalidpo] ' . shift;
1098 return IkiWiki::FailReason->new("$msg");
1101 writefile(basename($infile), File::Spec->tmpdir, $content)
1102 or return $fail->(sprintf(gettext("failed to write %s"), $infile));
1104 my $res = (system("msgfmt", "--check", $infile, "-o", "/dev/null") == 0);
1106 # Unlinking should happen automatically, thanks to File::Temp,
1107 # but it does not work here, probably because of the way writefile()
1108 # and Locale::Po4a::write() work.
1112 return IkiWiki::SuccessReason->new("valid gettext data");
1114 return IkiWiki::FailReason->new("invalid gettext data, go back ".
1115 "to previous page to go on with edit");
1122 package IkiWiki::PageSpec;
1124 sub match_istranslation ($;@) {
1127 if (IkiWiki::Plugin::po::istranslation($page)) {
1128 return IkiWiki::SuccessReason->new("is a translation page");
1131 return IkiWiki::FailReason->new("is not a translation page");
1135 sub match_istranslatable ($;@) {
1138 if (IkiWiki::Plugin::po::istranslatable($page)) {
1139 return IkiWiki::SuccessReason->new("is set as translatable in po_translatable_pages");
1142 return IkiWiki::FailReason->new("is not set as translatable in po_translatable_pages");
1146 sub match_lang ($$;@) {
1150 my $regexp=IkiWiki::glob2re($wanted);
1151 my $lang=IkiWiki::Plugin::po::lang($page);
1152 if ($lang !~ /^$regexp$/i) {
1153 return IkiWiki::FailReason->new("file language is $lang, not $wanted");
1156 return IkiWiki::SuccessReason->new("file language is $wanted");
1160 sub match_currentlang ($$;@) {
1165 return IkiWiki::FailReason->new("no location provided") unless exists $params{location};
1167 my $currentlang=IkiWiki::Plugin::po::lang($params{location});
1168 my $lang=IkiWiki::Plugin::po::lang($page);
1170 if ($lang eq $currentlang) {
1171 return IkiWiki::SuccessReason->new("file language is the same as current one, i.e. $currentlang");
1174 return IkiWiki::FailReason->new("file language is $lang, whereas current language is $currentlang");