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});
448 if (istranslation($params{page})) {
449 return gettext("Can not remove a translation. Removing the master page, ".
450 "though, removes its translations as well.");
457 my $session = $params{session};
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;
543 # | Injected functions
546 # Implement po_link_to 'current' and 'negotiated' settings.
547 sub mybestlink ($$) {
551 my $res=$origsubs{'bestlink'}->(masterpage($page), $link);
553 && ($config{po_link_to} eq "current" || $config{po_link_to} eq "negotiated")
554 && istranslatable($res)
555 && istranslation($page)) {
556 return $res . "." . lang($page);
561 sub mybeautify_urlpath ($) {
564 my $res=$origsubs{'beautify_urlpath'}->($url);
565 if ($config{po_link_to} eq "negotiated") {
566 $res =~ s!/\Qindex.$config{po_master_language}{code}.$config{htmlext}\E$!/!;
567 $res =~ s!/\Qindex.$config{htmlext}\E$!/!;
569 $res =~ s!/\Qindex.$_.$config{htmlext}\E$!/!;
570 } (keys %{$config{po_slave_languages}});
575 sub mytargetpage ($$) {
579 if (istranslation($page) || istranslatable($page)) {
580 my ($masterpage, $lang) = (masterpage($page), lang($page));
581 if (! $config{usedirs} || $masterpage eq 'index') {
582 return $masterpage . "." . $lang . "." . $ext;
585 return $masterpage . "/index." . $lang . "." . $ext;
588 return $origsubs{'targetpage'}->($page, $ext);
596 # workaround hard-coded /index.$config{htmlext} in IkiWiki::urlto()
598 && $config{po_link_to} eq "current"
599 && istranslatable('index')) {
600 return IkiWiki::beautify_urlpath(IkiWiki::baseurl($from) . "index." . lang($from) . ".$config{htmlext}");
602 # avoid using our injected beautify_urlpath if run by cgi_editpage,
603 # so that one is redirected to the just-edited page rather than to the
604 # negociated translation; to prevent unnecessary fiddling with caller/inject,
605 # we only do so when our beautify_urlpath would actually do what we want to
606 # avoid, i.e. when po_link_to = negotiated
607 if ($config{po_link_to} eq "negotiated") {
608 my @caller = caller(1);
609 my $run_by_editpage = 0;
610 $run_by_editpage = 1 if (exists $caller[3] && defined $caller[3]
611 && $caller[3] eq "IkiWiki::cgi_editpage");
612 inject(name => "IkiWiki::beautify_urlpath", call => $origsubs{'beautify_urlpath'})
614 my $res = $origsubs{'urlto'}->($to,$from,$absolute);
615 inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath)
620 return $origsubs{'urlto'}->($to,$from,$absolute)
624 sub mynicepagetitle ($;$) {
625 my ($page, $unescaped) = (shift, shift);
627 my $res = $origsubs{'nicepagetitle'}->($page, $unescaped);
628 return $res unless istranslation($page);
629 return $res unless $config{po_translation_status_in_links};
630 my @caller = caller(1);
631 return $res if (exists $caller[3] && defined $caller[3]
632 && $caller[3] eq "IkiWiki::Plugin::parentlinks::parentlinks");
633 return $res.' ('.percenttranslated($page).' %)';
639 # slave pages have no subpages
640 if (istranslation($params{'from'})) {
641 $params{'from'} = masterpage($params{'from'});
643 return $origsubs{'cgiurl'}->(%params);
647 # | Blackboxes for private data
653 sub alreadyfiltered($$) {
657 return exists $filtered{$page}{$destpage}
658 && $filtered{$page}{$destpage} eq 1;
661 sub setalreadyfiltered($$) {
665 $filtered{$page}{$destpage}=1;
668 sub unsetalreadyfiltered($$) {
672 if (exists $filtered{$page}{$destpage}) {
673 delete $filtered{$page}{$destpage};
677 sub resetalreadyfiltered() {
686 sub maybe_add_leading_slash ($;$) {
689 $add=1 unless defined $add;
690 return '/' . $str if $add;
694 sub istranslatablefile ($) {
697 return 0 unless defined $file;
698 return 0 if defined pagetype($file) && pagetype($file) eq 'po';
699 return 0 if $file =~ /\.pot$/;
700 return 0 unless -e "$config{srcdir}/$file"; # underlay dirs may be read-only
701 return 1 if pagespec_match(pagename($file), $config{po_translatable_pages});
705 sub istranslatable ($) {
709 return 1 if istranslatablefile($pagesources{$page});
713 sub _istranslation ($) {
716 $page='' unless defined $page && length $page;
717 my $hasleadingslash = ($page=~s#^/##);
718 my $file=$pagesources{$page};
719 return 0 unless defined $file
720 && defined pagetype($file)
721 && pagetype($file) eq 'po';
722 return 0 if $file =~ /\.pot$/;
724 my ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
725 return 0 unless defined $masterpage && defined $lang
726 && length $masterpage && length $lang
727 && defined $pagesources{$masterpage}
728 && defined $config{po_slave_languages}{$lang};
730 return (maybe_add_leading_slash($masterpage, $hasleadingslash), $lang)
731 if istranslatable($masterpage);
734 sub istranslation ($) {
737 if (1 < (my ($masterpage, $lang) = _istranslation($page))) {
738 my $hasleadingslash = ($masterpage=~s#^/##);
739 $translations{$masterpage}{$lang}=$page unless exists $translations{$masterpage}{$lang};
740 return (maybe_add_leading_slash($masterpage, $hasleadingslash), $lang);
748 if ( 1 < (my ($masterpage, $lang) = _istranslation($page))) {
757 if (1 < (my ($masterpage, $lang) = _istranslation($page))) {
760 return $config{po_master_language}{code};
763 sub islanguagecode ($) {
766 return $code =~ /^[a-z]{2}$/;
769 sub otherlanguage ($$) {
773 return masterpage($page) if $code eq $config{po_master_language}{code};
774 return masterpage($page) . '.' . $code;
777 sub otherlanguages ($) {
781 return \%ret unless istranslation($page) || istranslatable($page);
782 my $curlang=lang($page);
784 ($config{po_master_language}{code}, keys %{$config{po_slave_languages}}) {
785 next if $lang eq $curlang;
786 $ret{$lang}=otherlanguage($page, $lang);
792 my $masterfile=shift;
794 (my $name, my $dir, my $suffix) = fileparse($masterfile, qr/\.[^.]*/);
795 $dir='' if $dir eq './';
796 return File::Spec->catpath('', $dir, $name . ".pot");
800 my $masterfile=shift;
803 (my $name, my $dir, my $suffix) = fileparse($masterfile, qr/\.[^.]*/);
804 $dir='' if $dir eq './';
805 return File::Spec->catpath('', $dir, $name . "." . $lang . ".po");
809 my $masterfile=shift;
811 return map pofile($masterfile, $_), (keys %{$config{po_slave_languages}});
815 my $masterfile=shift;
817 my $potfile=potfile($masterfile);
818 my %options = ("markdown" => (pagetype($masterfile) eq 'mdwn') ? 1 : 0);
819 my $doc=Locale::Po4a::Chooser::new('text',%options);
820 $doc->{TT}{utf_mode} = 1;
821 $doc->{TT}{file_in_charset} = 'utf-8';
822 $doc->{TT}{file_out_charset} = 'utf-8';
823 $doc->read($masterfile);
824 # let's cheat a bit to force porefs option to be passed to Locale::Po4a::Po;
825 # this is undocument use of internal Locale::Po4a::TransTractor's data,
826 # compulsory since this module prevents us from using the porefs option.
827 $doc->{TT}{po_out}=Locale::Po4a::Po->new({ 'porefs' => 'none' });
828 $doc->{TT}{po_out}->set_charset('utf-8');
831 IkiWiki::prep_writefile(basename($potfile),dirname($potfile));
832 $doc->writepo($potfile);
835 sub refreshpofiles ($@) {
836 my $masterfile=shift;
839 my $potfile=potfile($masterfile);
841 error("po(refreshpofiles) ".sprintf(gettext("POT file (%s) does not exist"), $potfile));
844 foreach my $pofile (@pofiles) {
845 IkiWiki::prep_writefile(basename($pofile),dirname($pofile));
847 system("msgmerge", "-U", "--backup=none", $pofile, $potfile) == 0
848 or error("po(refreshpofiles) ".
849 sprintf(gettext("failed to update %s"),
853 File::Copy::syscopy($potfile,$pofile)
854 or error("po(refreshpofiles) ".
855 sprintf(gettext("failed to copy the POT file to %s"),
861 sub buildtranslationscache() {
862 # use istranslation's side-effect
863 map istranslation($_), (keys %pagesources);
866 sub resettranslationscache() {
870 sub flushmemoizecache() {
871 Memoize::flush_cache("istranslatable");
872 Memoize::flush_cache("_istranslation");
873 Memoize::flush_cache("percenttranslated");
876 sub urlto_with_orig_beautiful_urlpath($$) {
880 inject(name => "IkiWiki::beautify_urlpath", call => $origsubs{'beautify_urlpath'});
881 my $res=urlto($to, $from);
882 inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath);
887 sub percenttranslated ($) {
891 return gettext("N/A") unless istranslation($page);
892 my $file=srcfile($pagesources{$page});
893 my $masterfile = srcfile($pagesources{masterpage($page)});
895 "markdown" => (pagetype($masterfile) eq 'mdwn') ? 1 : 0,
897 my $doc=Locale::Po4a::Chooser::new('text',%options);
899 'po_in_name' => [ $file ],
900 'file_in_name' => [ $masterfile ],
901 'file_in_charset' => 'utf-8',
902 'file_out_charset' => 'utf-8',
903 ) or error("po(percenttranslated) ".
904 sprintf(gettext("failed to translate %s"), $page));
905 my ($percent,$hit,$queries) = $doc->stats();
906 $percent =~ s/\.[0-9]+$//;
910 sub languagename ($) {
913 return $config{po_master_language}{name}
914 if $code eq $config{po_master_language}{code};
915 return $config{po_slave_languages}{$code}
916 if defined $config{po_slave_languages}{$code};
920 sub otherlanguagesloop ($) {
924 my %otherpages=%{otherlanguages($page)};
925 while (my ($lang, $otherpage) = each %otherpages) {
926 if (istranslation($page) && masterpage($page) eq $otherpage) {
928 url => urlto_with_orig_beautiful_urlpath($otherpage, $page),
930 language => languagename($lang),
936 url => urlto_with_orig_beautiful_urlpath($otherpage, $page),
938 language => languagename($lang),
939 percent => percenttranslated($otherpage),
944 return -1 if $a->{code} eq $config{po_master_language}{code};
945 return 1 if $b->{code} eq $config{po_master_language}{code};
946 return $a->{language} cmp $b->{language};
950 sub homepageurl (;$) {
953 return urlto('', $page);
956 sub deletetranslations ($) {
957 my $deletedmasterfile=shift;
959 my $deletedmasterpage=pagename($deletedmasterfile);
962 my $file = newpagefile($deletedmasterpage.'.'.$_, 'po');
963 my $absfile = "$config{srcdir}/$file";
964 if (-e $absfile && ! -l $absfile && ! -d $absfile) {
965 push @todelete, $file;
967 } keys %{$config{po_slave_languages}};
971 IkiWiki::rcs_remove($_);
974 IkiWiki::prune("$config{srcdir}/$_");
980 gettext("removed obsolete PO files"),
981 "IkiWiki::Plugin::po::deletetranslations");
985 sub commit_and_refresh ($$) {
986 my ($msg, $author) = (shift, shift);
989 IkiWiki::disable_commit_hook();
990 IkiWiki::rcs_commit_staged($msg, $author, "127.0.0.1");
991 IkiWiki::enable_commit_hook();
992 IkiWiki::rcs_update();
994 # Reinitialize module's private variables.
995 resetalreadyfiltered();
996 resettranslationscache();
998 # Trigger a wiki refresh.
999 require IkiWiki::Render;
1000 # without preliminary saveindex/loadindex, refresh()
1001 # complains about a lot of uninitialized variables
1002 IkiWiki::saveindex();
1003 IkiWiki::loadindex();
1005 IkiWiki::saveindex();
1008 # on success, returns the filtered content.
1009 # on error, if $nonfatal, warn and return undef; else, error out.
1010 sub po_to_markup ($$;$) {
1011 my ($page, $content) = (shift, shift);
1012 my $nonfatal = shift;
1014 $content = '' unless defined $content;
1015 $content = decode_utf8(encode_utf8($content));
1016 # CRLF line terminators make poor Locale::Po4a feel bad
1017 $content=~s/\r\n/\n/g;
1019 # There are incompatibilities between some File::Temp versions
1020 # (including 0.18, bundled with Lenny's perl-modules package)
1021 # and others (e.g. 0.20, previously present in the archive as
1022 # a standalone package): under certain circumstances, some
1023 # return a relative filename, whereas others return an absolute one;
1024 # we here use this module in a way that is at least compatible
1025 # with 0.18 and 0.20. Beware, hit'n'run refactorers!
1026 my $infile = new File::Temp(TEMPLATE => "ikiwiki-po-filter-in.XXXXXXXXXX",
1027 DIR => File::Spec->tmpdir,
1028 UNLINK => 1)->filename;
1029 my $outfile = new File::Temp(TEMPLATE => "ikiwiki-po-filter-out.XXXXXXXXXX",
1030 DIR => File::Spec->tmpdir,
1031 UNLINK => 1)->filename;
1033 my $fail = sub ($) {
1034 my $msg = "po(po_to_markup) - $page : " . shift;
1039 error($msg, sub { unlink $infile, $outfile});
1042 writefile(basename($infile), File::Spec->tmpdir, $content)
1043 or return $fail->(sprintf(gettext("failed to write %s"), $infile));
1045 my $masterfile = srcfile($pagesources{masterpage($page)});
1047 "markdown" => (pagetype($masterfile) eq 'mdwn') ? 1 : 0,
1049 my $doc=Locale::Po4a::Chooser::new('text',%options);
1051 'po_in_name' => [ $infile ],
1052 'file_in_name' => [ $masterfile ],
1053 'file_in_charset' => 'utf-8',
1054 'file_out_charset' => 'utf-8',
1055 ) or return $fail->(gettext("failed to translate"));
1056 $doc->write($outfile)
1057 or return $fail->(sprintf(gettext("failed to write %s"), $outfile));
1059 $content = readfile($outfile)
1060 or return $fail->(sprintf(gettext("failed to read %s"), $outfile));
1062 # Unlinking should happen automatically, thanks to File::Temp,
1063 # but it does not work here, probably because of the way writefile()
1064 # and Locale::Po4a::write() work.
1065 unlink $infile, $outfile;
1070 # returns a SuccessReason or FailReason object
1072 my $content = shift;
1074 # NB: we don't use po_to_markup here, since Po4a parser does
1075 # not mind invalid PO content
1076 $content = '' unless defined $content;
1077 $content = decode_utf8(encode_utf8($content));
1079 # There are incompatibilities between some File::Temp versions
1080 # (including 0.18, bundled with Lenny's perl-modules package)
1081 # and others (e.g. 0.20, previously present in the archive as
1082 # a standalone package): under certain circumstances, some
1083 # return a relative filename, whereas others return an absolute one;
1084 # we here use this module in a way that is at least compatible
1085 # with 0.18 and 0.20. Beware, hit'n'run refactorers!
1086 my $infile = new File::Temp(TEMPLATE => "ikiwiki-po-isvalidpo.XXXXXXXXXX",
1087 DIR => File::Spec->tmpdir,
1088 UNLINK => 1)->filename;
1090 my $fail = sub ($) {
1091 my $msg = '[po/isvalidpo] ' . shift;
1093 return IkiWiki::FailReason->new("$msg");
1096 writefile(basename($infile), File::Spec->tmpdir, $content)
1097 or return $fail->(sprintf(gettext("failed to write %s"), $infile));
1099 my $res = (system("msgfmt", "--check", $infile, "-o", "/dev/null") == 0);
1101 # Unlinking should happen automatically, thanks to File::Temp,
1102 # but it does not work here, probably because of the way writefile()
1103 # and Locale::Po4a::write() work.
1107 return IkiWiki::SuccessReason->new("valid gettext data");
1109 return IkiWiki::FailReason->new("invalid gettext data, go back ".
1110 "to previous page to go on with edit");
1117 package IkiWiki::PageSpec;
1119 sub match_istranslation ($;@) {
1122 if (IkiWiki::Plugin::po::istranslation($page)) {
1123 return IkiWiki::SuccessReason->new("is a translation page");
1126 return IkiWiki::FailReason->new("is not a translation page");
1130 sub match_istranslatable ($;@) {
1133 if (IkiWiki::Plugin::po::istranslatable($page)) {
1134 return IkiWiki::SuccessReason->new("is set as translatable in po_translatable_pages");
1137 return IkiWiki::FailReason->new("is not set as translatable in po_translatable_pages");
1141 sub match_lang ($$;@) {
1145 my $regexp=IkiWiki::glob2re($wanted);
1146 my $lang=IkiWiki::Plugin::po::lang($page);
1147 if ($lang !~ /^$regexp$/i) {
1148 return IkiWiki::FailReason->new("file language is $lang, not $wanted");
1151 return IkiWiki::SuccessReason->new("file language is $wanted");
1155 sub match_currentlang ($$;@) {
1160 return IkiWiki::FailReason->new("no location provided") unless exists $params{location};
1162 my $currentlang=IkiWiki::Plugin::po::lang($params{location});
1163 my $lang=IkiWiki::Plugin::po::lang($page);
1165 if ($lang eq $currentlang) {
1166 return IkiWiki::SuccessReason->new("file language is the same as current one, i.e. $currentlang");
1169 return IkiWiki::FailReason->new("file language is $lang, whereas current language is $currentlang");