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.
332 sub renamepages($$$) {
333 my ($torename, $cgi, $session) = (shift, shift, shift);
335 # copy the initial array, so that we can iterate on it AND
336 # modify it at the same time, without iterating on the items we
337 # pushed on it ourselves
338 my @torename=@{$torename};
340 # Save the page(s) the user asked to rename, so that our
341 # canrename hook can tell the difference between:
342 # - a translation being renamed as a consequence of its master page
344 # - a user trying to directly rename a translation
345 # This is why this hook has to be run first, before @torename is modified
347 $session->param(po_orig_torename => [ @torename ]);
348 IkiWiki::cgi_savesession($session);
350 foreach my $rename (@torename) {
351 next unless istranslatable($rename->{src});
352 my %otherpages=%{otherlanguages($rename->{src})};
353 while (my ($lang, $otherpage) = each %otherpages) {
356 srcfile => $pagesources{$otherpage},
357 dest => otherlanguage($rename->{dest}, $lang),
358 destfile => $rename->{dest}.".".$lang.".po",
368 map { deletetranslations($_) } grep istranslatablefile($_), @deleted;
374 # All meta titles are first extracted at scan time, i.e. before we turn
375 # PO files back into translated markdown; escaping of double-quotes in
376 # PO files breaks the meta plugin's parsing enough to save ugly titles
377 # to %pagestate at this time.
379 # Then, at render time, every page's passes on row through the Great
380 # Rendering Chain (filter->preprocess->linkify->htmlize), and the meta
381 # plugin's preprocess hook is this time in a position to correctly
382 # extract the titles from slave pages.
384 # This is, unfortunately, too late: if the page A, linking to the page B,
385 # is rendered before B, it will display the wrongly-extracted meta title
386 # as the link text to B.
388 # On the one hand, such a corner case only happens on rebuild: on
389 # refresh, every rendered page is fixed to contain correct meta titles.
390 # On the other hand, it can take some time to get every page fixed.
391 # We therefore re-render every rendered page after a rebuild to fix them
392 # at once. As this more or less doubles the time needed to rebuild the
393 # wiki, we do so only when really needed.
396 && exists $config{rebuild} && defined $config{rebuild} && $config{rebuild}
397 && UNIVERSAL::can("IkiWiki::Plugin::meta", "getsetup")
398 && exists $config{meta_overrides_page_title}
399 && defined $config{meta_overrides_page_title}
400 && $config{meta_overrides_page_title}) {
401 debug(sprintf(gettext("re-rendering all pages to fix meta titles")));
402 resetalreadyfiltered();
403 require IkiWiki::Render;
404 foreach my $file (@rendered) {
405 debug(sprintf(gettext("rendering %s"), $file));
406 IkiWiki::render($file);
410 my $updated_po_files=0;
412 # Refresh/create POT and PO files as needed.
413 foreach my $file (grep {istranslatablefile($_)} @rendered) {
414 my $page=pagename($file);
415 my $masterfile=srcfile($file);
416 my $updated_pot_file=0;
417 # Only refresh Pot file if it does not exist, or if
418 # $pagesources{$page} was changed: don't if only the HTML was
419 # refreshed, e.g. because of a dependency.
420 if ((grep { $_ eq $pagesources{$page} } @origneedsbuild)
421 || ! -e potfile($masterfile)) {
422 refreshpot($masterfile);
427 push @pofiles, $_ if ($updated_pot_file || ! -e $_);
428 } (pofiles($masterfile));
430 refreshpofiles($masterfile, @pofiles);
431 map { IkiWiki::rcs_add($_) } @pofiles if $config{rcs};
436 if ($updated_po_files) {
438 gettext("updated PO files"),
439 "IkiWiki::Plugin::po::change");
443 sub checkcontent (@) {
446 if (istranslation($params{page})) {
447 my $res = isvalidpo($params{content});
461 if (istranslation($params{page})) {
462 return gettext("Can not remove a translation. Removing the master page, ".
463 "though, removes its translations as well.");
470 my $session = $params{session};
472 if (istranslation($params{src})) {
473 my $masterpage = masterpage($params{src});
474 # Tell the difference between:
475 # - a translation being renamed as a consequence of its master page
476 # being renamed, which is allowed
477 # - a user trying to directly rename a translation, which is forbidden
478 # by looking for the master page in the list of to-be-renamed pages we
479 # saved early in the renaming process.
480 my $orig_torename = $session->param("po_orig_torename");
481 unless (grep { $_->{src} eq $masterpage } @{$orig_torename}) {
482 return gettext("Can not rename a translation. Renaming the master page, ".
483 "though, renames its translations as well.");
489 # As we're previewing or saving a page, the content may have
490 # changed, so tell the next filter() invocation it must not be lazy.
494 unsetalreadyfiltered($params{page}, $params{page});
495 return $params{content};
498 sub formbuilder_setup (@) {
500 my $form=$params{form};
503 return unless defined $form->field("do");
505 if ($form->field("do") eq "create") {
506 # Warn the user: new pages must be written in master language.
507 my $template=template("pocreatepage.tmpl");
508 $template->param(LANG => $config{po_master_language}{name});
509 $form->tmpl_param(message => $template->output);
511 elsif ($form->field("do") eq "edit") {
512 # Remove the rename/remove buttons on slave pages.
513 # This has to be done after the rename/remove plugins have added
514 # their buttons, which is why this hook must be run last.
515 # The canrename/canremove hooks already ensure this is forbidden
516 # at the backend level, so this is only UI sugar.
517 if (istranslation($form->field("page"))) {
519 for (my $i = 0; $i < @{$params{buttons}}; $i++) {
520 if (@{$params{buttons}}[$i] eq $_) {
521 delete @{$params{buttons}}[$i];
530 sub formbuilder (@) {
532 my $form=$params{form};
535 return unless defined $form->field("do");
537 # Do not allow to create pages of type po: they are automatically created.
538 # The main reason to do so is to bypass the "favor the type of linking page
539 # on page creation" logic, which is unsuitable when a broken link is clicked
540 # on a slave (PO) page.
541 # This cannot be done in the formbuilder_setup hook as the list of types is
543 if ($form->field("do") eq "create") {
544 foreach my $field ($form->field) {
545 next unless "$field" eq "type";
546 if ($field->type eq 'select') {
547 # remove po from the list of types
548 my @types = grep { $_ ne 'po' } $field->options;
549 $field->options(\@types) if @types;
556 # | Injected functions
559 # Implement po_link_to 'current' and 'negotiated' settings.
560 sub mybestlink ($$) {
564 my $res=$origsubs{'bestlink'}->(masterpage($page), $link);
566 && ($config{po_link_to} eq "current" || $config{po_link_to} eq "negotiated")
567 && istranslatable($res)
568 && istranslation($page)) {
569 return $res . "." . lang($page);
574 sub mybeautify_urlpath ($) {
577 my $res=$origsubs{'beautify_urlpath'}->($url);
578 if ($config{po_link_to} eq "negotiated") {
579 $res =~ s!/\Qindex.$config{po_master_language}{code}.$config{htmlext}\E$!/!;
580 $res =~ s!/\Qindex.$config{htmlext}\E$!/!;
582 $res =~ s!/\Qindex.$_.$config{htmlext}\E$!/!;
583 } (keys %{$config{po_slave_languages}});
588 sub mytargetpage ($$) {
592 if (istranslation($page) || istranslatable($page)) {
593 my ($masterpage, $lang) = (masterpage($page), lang($page));
594 if (! $config{usedirs} || $masterpage eq 'index') {
595 return $masterpage . "." . $lang . "." . $ext;
598 return $masterpage . "/index." . $lang . "." . $ext;
601 return $origsubs{'targetpage'}->($page, $ext);
609 # workaround hard-coded /index.$config{htmlext} in IkiWiki::urlto()
611 && $config{po_link_to} eq "current"
612 && istranslatable('index')) {
613 return IkiWiki::beautify_urlpath(IkiWiki::baseurl($from) . "index." . lang($from) . ".$config{htmlext}");
615 # avoid using our injected beautify_urlpath if run by cgi_editpage,
616 # so that one is redirected to the just-edited page rather than to the
617 # negociated translation; to prevent unnecessary fiddling with caller/inject,
618 # we only do so when our beautify_urlpath would actually do what we want to
619 # avoid, i.e. when po_link_to = negotiated
620 if ($config{po_link_to} eq "negotiated") {
621 my @caller = caller(1);
622 my $run_by_editpage = 0;
623 $run_by_editpage = 1 if (exists $caller[3] && defined $caller[3]
624 && $caller[3] eq "IkiWiki::cgi_editpage");
625 inject(name => "IkiWiki::beautify_urlpath", call => $origsubs{'beautify_urlpath'})
627 my $res = $origsubs{'urlto'}->($to,$from,$absolute);
628 inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath)
633 return $origsubs{'urlto'}->($to,$from,$absolute)
637 sub mynicepagetitle ($;$) {
638 my ($page, $unescaped) = (shift, shift);
640 my $res = $origsubs{'nicepagetitle'}->($page, $unescaped);
641 return $res unless istranslation($page);
642 return $res unless $config{po_translation_status_in_links};
643 my @caller = caller(1);
644 return $res if (exists $caller[3] && defined $caller[3]
645 && $caller[3] eq "IkiWiki::Plugin::parentlinks::parentlinks");
646 return $res.' ('.percenttranslated($page).' %)';
652 # slave pages have no subpages
653 if (istranslation($params{'from'})) {
654 $params{'from'} = masterpage($params{'from'});
656 return $origsubs{'cgiurl'}->(%params);
660 # | Blackboxes for private data
666 sub alreadyfiltered($$) {
670 return exists $filtered{$page}{$destpage}
671 && $filtered{$page}{$destpage} eq 1;
674 sub setalreadyfiltered($$) {
678 $filtered{$page}{$destpage}=1;
681 sub unsetalreadyfiltered($$) {
685 if (exists $filtered{$page}{$destpage}) {
686 delete $filtered{$page}{$destpage};
690 sub resetalreadyfiltered() {
699 sub maybe_add_leading_slash ($;$) {
702 $add=1 unless defined $add;
703 return '/' . $str if $add;
707 sub istranslatablefile ($) {
710 return 0 unless defined $file;
711 return 0 if defined pagetype($file) && pagetype($file) eq 'po';
712 return 0 if $file =~ /\.pot$/;
713 return 0 unless -e "$config{srcdir}/$file"; # underlay dirs may be read-only
714 return 1 if pagespec_match(pagename($file), $config{po_translatable_pages});
718 sub istranslatable ($) {
722 return 1 if istranslatablefile($pagesources{$page});
726 sub _istranslation ($) {
729 $page='' unless defined $page && length $page;
730 my $hasleadingslash = ($page=~s#^/##);
731 my $file=$pagesources{$page};
732 return 0 unless defined $file
733 && defined pagetype($file)
734 && pagetype($file) eq 'po';
735 return 0 if $file =~ /\.pot$/;
737 my ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
738 return 0 unless defined $masterpage && defined $lang
739 && length $masterpage && length $lang
740 && defined $pagesources{$masterpage}
741 && defined $config{po_slave_languages}{$lang};
743 return (maybe_add_leading_slash($masterpage, $hasleadingslash), $lang)
744 if istranslatable($masterpage);
747 sub istranslation ($) {
750 if (1 < (my ($masterpage, $lang) = _istranslation($page))) {
751 my $hasleadingslash = ($masterpage=~s#^/##);
752 $translations{$masterpage}{$lang}=$page unless exists $translations{$masterpage}{$lang};
753 return (maybe_add_leading_slash($masterpage, $hasleadingslash), $lang);
761 if ( 1 < (my ($masterpage, $lang) = _istranslation($page))) {
770 if (1 < (my ($masterpage, $lang) = _istranslation($page))) {
773 return $config{po_master_language}{code};
776 sub islanguagecode ($) {
779 return $code =~ /^[a-z]{2}$/;
782 sub otherlanguage ($$) {
786 return masterpage($page) if $code eq $config{po_master_language}{code};
787 return masterpage($page) . '.' . $code;
790 sub otherlanguages ($) {
794 return \%ret unless istranslation($page) || istranslatable($page);
795 my $curlang=lang($page);
797 ($config{po_master_language}{code}, keys %{$config{po_slave_languages}}) {
798 next if $lang eq $curlang;
799 $ret{$lang}=otherlanguage($page, $lang);
805 my $masterfile=shift;
807 (my $name, my $dir, my $suffix) = fileparse($masterfile, qr/\.[^.]*/);
808 $dir='' if $dir eq './';
809 return File::Spec->catpath('', $dir, $name . ".pot");
813 my $masterfile=shift;
816 (my $name, my $dir, my $suffix) = fileparse($masterfile, qr/\.[^.]*/);
817 $dir='' if $dir eq './';
818 return File::Spec->catpath('', $dir, $name . "." . $lang . ".po");
822 my $masterfile=shift;
824 return map pofile($masterfile, $_), (keys %{$config{po_slave_languages}});
828 my $masterfile=shift;
830 my $potfile=potfile($masterfile);
831 my %options = ("markdown" => (pagetype($masterfile) eq 'mdwn') ? 1 : 0);
832 my $doc=Locale::Po4a::Chooser::new('text',%options);
833 $doc->{TT}{utf_mode} = 1;
834 $doc->{TT}{file_in_charset} = 'utf-8';
835 $doc->{TT}{file_out_charset} = 'utf-8';
836 $doc->read($masterfile);
837 # let's cheat a bit to force porefs option to be passed to Locale::Po4a::Po;
838 # this is undocument use of internal Locale::Po4a::TransTractor's data,
839 # compulsory since this module prevents us from using the porefs option.
840 $doc->{TT}{po_out}=Locale::Po4a::Po->new({ 'porefs' => 'none' });
841 $doc->{TT}{po_out}->set_charset('utf-8');
844 IkiWiki::prep_writefile(basename($potfile),dirname($potfile));
845 $doc->writepo($potfile);
848 sub refreshpofiles ($@) {
849 my $masterfile=shift;
852 my $potfile=potfile($masterfile);
854 error("po(refreshpofiles) ".sprintf(gettext("POT file (%s) does not exist"), $potfile));
857 foreach my $pofile (@pofiles) {
858 IkiWiki::prep_writefile(basename($pofile),dirname($pofile));
860 system("msgmerge", "-U", "--backup=none", $pofile, $potfile) == 0
861 or error("po(refreshpofiles) ".
862 sprintf(gettext("failed to update %s"),
866 File::Copy::syscopy($potfile,$pofile)
867 or error("po(refreshpofiles) ".
868 sprintf(gettext("failed to copy the POT file to %s"),
874 sub buildtranslationscache() {
875 # use istranslation's side-effect
876 map istranslation($_), (keys %pagesources);
879 sub resettranslationscache() {
883 sub flushmemoizecache() {
884 Memoize::flush_cache("istranslatable");
885 Memoize::flush_cache("_istranslation");
886 Memoize::flush_cache("percenttranslated");
889 sub urlto_with_orig_beautiful_urlpath($$) {
893 inject(name => "IkiWiki::beautify_urlpath", call => $origsubs{'beautify_urlpath'});
894 my $res=urlto($to, $from);
895 inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath);
900 sub percenttranslated ($) {
904 return gettext("N/A") unless istranslation($page);
905 my $file=srcfile($pagesources{$page});
906 my $masterfile = srcfile($pagesources{masterpage($page)});
908 "markdown" => (pagetype($masterfile) eq 'mdwn') ? 1 : 0,
910 my $doc=Locale::Po4a::Chooser::new('text',%options);
912 'po_in_name' => [ $file ],
913 'file_in_name' => [ $masterfile ],
914 'file_in_charset' => 'utf-8',
915 'file_out_charset' => 'utf-8',
916 ) or error("po(percenttranslated) ".
917 sprintf(gettext("failed to translate %s"), $page));
918 my ($percent,$hit,$queries) = $doc->stats();
919 $percent =~ s/\.[0-9]+$//;
923 sub languagename ($) {
926 return $config{po_master_language}{name}
927 if $code eq $config{po_master_language}{code};
928 return $config{po_slave_languages}{$code}
929 if defined $config{po_slave_languages}{$code};
933 sub otherlanguagesloop ($) {
937 my %otherpages=%{otherlanguages($page)};
938 while (my ($lang, $otherpage) = each %otherpages) {
939 if (istranslation($page) && masterpage($page) eq $otherpage) {
941 url => urlto_with_orig_beautiful_urlpath($otherpage, $page),
943 language => languagename($lang),
949 url => urlto_with_orig_beautiful_urlpath($otherpage, $page),
951 language => languagename($lang),
952 percent => percenttranslated($otherpage),
957 return -1 if $a->{code} eq $config{po_master_language}{code};
958 return 1 if $b->{code} eq $config{po_master_language}{code};
959 return $a->{language} cmp $b->{language};
963 sub homepageurl (;$) {
966 return urlto('', $page);
969 sub deletetranslations ($) {
970 my $deletedmasterfile=shift;
972 my $deletedmasterpage=pagename($deletedmasterfile);
975 my $file = newpagefile($deletedmasterpage.'.'.$_, 'po');
976 my $absfile = "$config{srcdir}/$file";
977 if (-e $absfile && ! -l $absfile && ! -d $absfile) {
978 push @todelete, $file;
980 } keys %{$config{po_slave_languages}};
984 IkiWiki::rcs_remove($_);
987 IkiWiki::prune("$config{srcdir}/$_");
993 gettext("removed obsolete PO files"),
994 "IkiWiki::Plugin::po::deletetranslations");
998 sub commit_and_refresh ($$) {
999 my ($msg, $author) = (shift, shift);
1002 IkiWiki::disable_commit_hook();
1003 IkiWiki::rcs_commit_staged($msg, $author, "127.0.0.1");
1004 IkiWiki::enable_commit_hook();
1005 IkiWiki::rcs_update();
1007 # Reinitialize module's private variables.
1008 resetalreadyfiltered();
1009 resettranslationscache();
1010 flushmemoizecache();
1011 # Trigger a wiki refresh.
1012 require IkiWiki::Render;
1013 # without preliminary saveindex/loadindex, refresh()
1014 # complains about a lot of uninitialized variables
1015 IkiWiki::saveindex();
1016 IkiWiki::loadindex();
1018 IkiWiki::saveindex();
1021 # on success, returns the filtered content.
1022 # on error, if $nonfatal, warn and return undef; else, error out.
1023 sub po_to_markup ($$;$) {
1024 my ($page, $content) = (shift, shift);
1025 my $nonfatal = shift;
1027 $content = '' unless defined $content;
1028 $content = decode_utf8(encode_utf8($content));
1029 # CRLF line terminators make poor Locale::Po4a feel bad
1030 $content=~s/\r\n/\n/g;
1032 # There are incompatibilities between some File::Temp versions
1033 # (including 0.18, bundled with Lenny's perl-modules package)
1034 # and others (e.g. 0.20, previously present in the archive as
1035 # a standalone package): under certain circumstances, some
1036 # return a relative filename, whereas others return an absolute one;
1037 # we here use this module in a way that is at least compatible
1038 # with 0.18 and 0.20. Beware, hit'n'run refactorers!
1039 my $infile = new File::Temp(TEMPLATE => "ikiwiki-po-filter-in.XXXXXXXXXX",
1040 DIR => File::Spec->tmpdir,
1041 UNLINK => 1)->filename;
1042 my $outfile = new File::Temp(TEMPLATE => "ikiwiki-po-filter-out.XXXXXXXXXX",
1043 DIR => File::Spec->tmpdir,
1044 UNLINK => 1)->filename;
1046 my $fail = sub ($) {
1047 my $msg = "po(po_to_markup) - $page : " . shift;
1052 error($msg, sub { unlink $infile, $outfile});
1055 writefile(basename($infile), File::Spec->tmpdir, $content)
1056 or return $fail->(sprintf(gettext("failed to write %s"), $infile));
1058 my $masterfile = srcfile($pagesources{masterpage($page)});
1060 "markdown" => (pagetype($masterfile) eq 'mdwn') ? 1 : 0,
1062 my $doc=Locale::Po4a::Chooser::new('text',%options);
1064 'po_in_name' => [ $infile ],
1065 'file_in_name' => [ $masterfile ],
1066 'file_in_charset' => 'utf-8',
1067 'file_out_charset' => 'utf-8',
1068 ) or return $fail->(gettext("failed to translate"));
1069 $doc->write($outfile)
1070 or return $fail->(sprintf(gettext("failed to write %s"), $outfile));
1072 $content = readfile($outfile)
1073 or return $fail->(sprintf(gettext("failed to read %s"), $outfile));
1075 # Unlinking should happen automatically, thanks to File::Temp,
1076 # but it does not work here, probably because of the way writefile()
1077 # and Locale::Po4a::write() work.
1078 unlink $infile, $outfile;
1083 # returns a SuccessReason or FailReason object
1085 my $content = shift;
1087 # NB: we don't use po_to_markup here, since Po4a parser does
1088 # not mind invalid PO content
1089 $content = '' unless defined $content;
1090 $content = decode_utf8(encode_utf8($content));
1092 # There are incompatibilities between some File::Temp versions
1093 # (including 0.18, bundled with Lenny's perl-modules package)
1094 # and others (e.g. 0.20, previously present in the archive as
1095 # a standalone package): under certain circumstances, some
1096 # return a relative filename, whereas others return an absolute one;
1097 # we here use this module in a way that is at least compatible
1098 # with 0.18 and 0.20. Beware, hit'n'run refactorers!
1099 my $infile = new File::Temp(TEMPLATE => "ikiwiki-po-isvalidpo.XXXXXXXXXX",
1100 DIR => File::Spec->tmpdir,
1101 UNLINK => 1)->filename;
1103 my $fail = sub ($) {
1104 my $msg = '[po/isvalidpo] ' . shift;
1106 return IkiWiki::FailReason->new("$msg");
1109 writefile(basename($infile), File::Spec->tmpdir, $content)
1110 or return $fail->(sprintf(gettext("failed to write %s"), $infile));
1112 my $res = (system("msgfmt", "--check", $infile, "-o", "/dev/null") == 0);
1114 # Unlinking should happen automatically, thanks to File::Temp,
1115 # but it does not work here, probably because of the way writefile()
1116 # and Locale::Po4a::write() work.
1120 return IkiWiki::SuccessReason->new("valid gettext data");
1122 return IkiWiki::FailReason->new("invalid gettext data, go back ".
1123 "to previous page to go on with edit");
1130 package IkiWiki::PageSpec;
1132 sub match_istranslation ($;@) {
1135 if (IkiWiki::Plugin::po::istranslation($page)) {
1136 return IkiWiki::SuccessReason->new("is a translation page");
1139 return IkiWiki::FailReason->new("is not a translation page");
1143 sub match_istranslatable ($;@) {
1146 if (IkiWiki::Plugin::po::istranslatable($page)) {
1147 return IkiWiki::SuccessReason->new("is set as translatable in po_translatable_pages");
1150 return IkiWiki::FailReason->new("is not set as translatable in po_translatable_pages");
1154 sub match_lang ($$;@) {
1158 my $regexp=IkiWiki::glob2re($wanted);
1159 my $lang=IkiWiki::Plugin::po::lang($page);
1160 if ($lang !~ /^$regexp$/i) {
1161 return IkiWiki::FailReason->new("file language is $lang, not $wanted");
1164 return IkiWiki::SuccessReason->new("file language is $wanted");
1168 sub match_currentlang ($$;@) {
1173 return IkiWiki::FailReason->new("no location provided") unless exists $params{location};
1175 my $currentlang=IkiWiki::Plugin::po::lang($params{location});
1176 my $lang=IkiWiki::Plugin::po::lang($page);
1178 if ($lang eq $currentlang) {
1179 return IkiWiki::SuccessReason->new("file language is the same as current one, i.e. $currentlang");
1182 return IkiWiki::FailReason->new("file language is $lang, whereas current language is $currentlang");