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 => "rename", id => "po", call => \&renamepages, first => 1);
40 hook(type => "delete", id => "po", call => \&mydelete);
41 hook(type => "change", id => "po", call => \&change);
42 hook(type => "checkcontent", id => "po", call => \&checkcontent);
43 hook(type => "canremove", id => "po", call => \&canremove);
44 hook(type => "canrename", id => "po", call => \&canrename);
45 hook(type => "editcontent", id => "po", call => \&editcontent);
46 hook(type => "formbuilder_setup", id => "po", call => \&formbuilder_setup, last => 1);
47 hook(type => "formbuilder", id => "po", call => \&formbuilder);
49 $origsubs{'bestlink'}=\&IkiWiki::bestlink;
50 inject(name => "IkiWiki::bestlink", call => \&mybestlink);
51 $origsubs{'beautify_urlpath'}=\&IkiWiki::beautify_urlpath;
52 inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath);
53 $origsubs{'targetpage'}=\&IkiWiki::targetpage;
54 inject(name => "IkiWiki::targetpage", call => \&mytargetpage);
55 $origsubs{'urlto'}=\&IkiWiki::urlto;
56 inject(name => "IkiWiki::urlto", call => \&myurlto);
57 $origsubs{'cgiurl'}=\&IkiWiki::cgiurl;
58 inject(name => "IkiWiki::cgiurl", call => \&mycgiurl);
67 # 2. Injected functions
68 # 3. Blackboxes for private data
83 po_master_language => {
89 description => "master language (non-PO files)",
93 po_slave_languages => {
100 description => "slave languages (PO files)",
104 po_translatable_pages => {
106 example => "!*/Discussion",
107 description => "PageSpec controlling which pages are translatable",
108 link => "ikiwiki/PageSpec",
114 example => "current",
115 description => "internal linking behavior (default/current/negotiated)",
122 foreach my $field (qw{po_master_language po_slave_languages}) {
123 if (! exists $config{$field} || ! defined $config{$field}) {
124 error(sprintf(gettext("Must specify %s when using the %s plugin"),
128 if (! (keys %{$config{po_slave_languages}})) {
129 error(gettext("At least one slave language must be defined ".
130 "in po_slave_languages when using the po plugin"));
134 or error(sprintf(gettext("%s is not a valid language code"), $_));
135 } ($config{po_master_language}{code}, keys %{$config{po_slave_languages}});
136 if (! exists $config{po_translatable_pages} ||
137 ! defined $config{po_translatable_pages}) {
138 $config{po_translatable_pages}="";
140 if (! exists $config{po_link_to} ||
141 ! defined $config{po_link_to}) {
142 $config{po_link_to}='default';
144 elsif ($config{po_link_to} !~ /^(default|current|negotiated)$/) {
145 warn(sprintf(gettext('%s is not a valid value for po_link_to, falling back to po_link_to=default'),
146 $config{po_link_to}));
147 $config{po_link_to}='default';
149 elsif ($config{po_link_to} eq "negotiated" && ! $config{usedirs}) {
150 warn(gettext('po_link_to=negotiated requires usedirs to be enabled, falling back to po_link_to=default'));
151 $config{po_link_to}='default';
153 push @{$config{wiki_file_prune_regexps}}, qr/\.pot$/;
157 my $needsbuild=shift;
159 # backup @needsbuild content so that change() can know whether
160 # a given master page was rendered because its source file was changed
161 @origneedsbuild=(@$needsbuild);
164 buildtranslationscache();
166 # make existing translations depend on the corresponding master page
167 foreach my $master (keys %translations) {
168 map add_depends($_, $master), values %{otherlanguages($master)};
172 # Massage the recorded state of internal links so that:
173 # - it matches the actually generated links, rather than the links as written
174 # in the pages' source
175 # - backlinks are consistent in all cases
178 my $page=$params{page};
179 my $content=$params{content};
181 if (istranslation($page)) {
182 foreach my $destpage (@{$links{$page}}) {
183 if (istranslatable($destpage)) {
184 # replace one occurence of $destpage in $links{$page}
185 # (we only want to replace the one that was added by
186 # IkiWiki::Plugin::link::scan, other occurences may be
187 # there for other reasons)
188 for (my $i=0; $i<@{$links{$page}}; $i++) {
189 if (@{$links{$page}}[$i] eq $destpage) {
190 @{$links{$page}}[$i] = $destpage . '.' . lang($page);
197 elsif (! istranslatable($page) && ! istranslation($page)) {
198 foreach my $destpage (@{$links{$page}}) {
199 if (istranslatable($destpage)) {
200 # make sure any destpage's translations has
201 # $page in its backlinks
202 push @{$links{$page}},
203 values %{otherlanguages($destpage)};
209 # We use filter to convert PO to the master page's format,
210 # since the rest of ikiwiki should not work on PO files.
214 my $page = $params{page};
215 my $destpage = $params{destpage};
216 my $content = $params{content};
217 if (istranslation($page) && ! alreadyfiltered($page, $destpage)) {
218 $content = po_to_markup($page, $content);
219 setalreadyfiltered($page, $destpage);
227 my $page = $params{page};
228 my $content = $params{content};
230 # ignore PO files this plugin did not create
231 return $content unless istranslation($page);
233 # force content to be htmlize'd as if it was the same type as the master page
234 return IkiWiki::htmlize($page, $page,
235 pagetype(srcfile($pagesources{masterpage($page)})),
239 sub pagetemplate (@) {
241 my $page=$params{page};
242 my $destpage=$params{destpage};
243 my $template=$params{template};
245 my ($masterpage, $lang) = istranslation($page);
247 if (istranslation($page) && $template->query(name => "percenttranslated")) {
248 $template->param(percenttranslated => percenttranslated($page));
250 if ($template->query(name => "istranslation")) {
251 $template->param(istranslation => scalar istranslation($page));
253 if ($template->query(name => "istranslatable")) {
254 $template->param(istranslatable => istranslatable($page));
256 if ($template->query(name => "HOMEPAGEURL")) {
257 $template->param(homepageurl => homepageurl($page));
259 if ($template->query(name => "otherlanguages")) {
260 $template->param(otherlanguages => [otherlanguagesloop($page)]);
261 map add_depends($page, $_), (values %{otherlanguages($page)});
263 if ($config{discussion} && istranslation($page)) {
264 my $discussionlink=gettext("discussion");
265 if ($page !~ /.*\/\Q$discussionlink\E$/i &&
266 (length $config{cgiurl} ||
267 exists $links{$masterpage."/".$discussionlink})) {
268 $template->param('discussionlink' => htmllink(
271 $masterpage . '/' . gettext("Discussion"),
274 linktext => gettext("Discussion"),
278 # Remove broken parentlink to ./index.html on home page's translations.
279 # It works because this hook has the "last" parameter set, to ensure it
280 # runs after parentlinks' own pagetemplate hook.
281 if ($template->param('parentlinks')
282 && istranslation($page)
283 && $masterpage eq "index") {
284 $template->param('parentlinks' => []);
288 # Add the renamed page translations to the list of to-be-renamed pages.
289 sub renamepages (@) {
292 my %torename = %{$params{torename}};
293 my $session = $params{session};
295 # Save the page(s) the user asked to rename, so that our
296 # canrename hook can tell the difference between:
297 # - a translation being renamed as a consequence of its master page
299 # - a user trying to directly rename a translation
300 # This is why this hook has to be run first, before the list of pages
301 # to rename is modified by other plugins.
303 @orig_torename=@{$session->param("po_orig_torename")}
304 if defined $session->param("po_orig_torename");
305 push @orig_torename, $torename{src};
306 $session->param(po_orig_torename => \@orig_torename);
307 IkiWiki::cgi_savesession($session);
309 return () unless istranslatable($torename{src});
312 my %otherpages=%{otherlanguages($torename{src})};
313 while (my ($lang, $otherpage) = each %otherpages) {
316 srcfile => $pagesources{$otherpage},
317 dest => otherlanguage($torename{dest}, $lang),
318 destfile => $torename{dest}.".".$lang.".po",
328 map { deletetranslations($_) } grep istranslatablefile($_), @deleted;
334 # All meta titles are first extracted at scan time, i.e. before we turn
335 # PO files back into translated markdown; escaping of double-quotes in
336 # PO files breaks the meta plugin's parsing enough to save ugly titles
337 # to %pagestate at this time.
339 # Then, at render time, every page passes in turn through the Great
340 # Rendering Chain (filter->preprocess->linkify->htmlize), and the meta
341 # plugin's preprocess hook is this time in a position to correctly
342 # extract the titles from slave pages.
344 # This is, unfortunately, too late: if the page A, linking to the page
345 # B, is rendered before B, it will display the wrongly-extracted meta
346 # title as the link text to B.
348 # On the one hand, such a corner case only happens on rebuild: on
349 # refresh, every rendered page is fixed to contain correct meta titles.
350 # On the other hand, it can take some time to get every page fixed.
351 # We therefore re-render every rendered page after a rebuild to fix them
352 # at once. As this more or less doubles the time needed to rebuild the
353 # wiki, we do so only when really needed.
356 && exists $config{rebuild} && defined $config{rebuild} && $config{rebuild}
357 && UNIVERSAL::can("IkiWiki::Plugin::meta", "getsetup")
358 && exists $config{meta_overrides_page_title}
359 && defined $config{meta_overrides_page_title}
360 && $config{meta_overrides_page_title}) {
361 debug(sprintf(gettext("re-rendering all pages to fix meta titles")));
362 resetalreadyfiltered();
363 require IkiWiki::Render;
364 foreach my $file (@rendered) {
365 debug(sprintf(gettext("rendering %s"), $file));
366 IkiWiki::render($file);
370 my $updated_po_files=0;
372 # Refresh/create POT and PO files as needed.
373 foreach my $file (grep {istranslatablefile($_)} @rendered) {
374 my $page=pagename($file);
375 my $masterfile=srcfile($file);
376 my $updated_pot_file=0;
377 # Only refresh Pot file if it does not exist, or if
378 # $pagesources{$page} was changed: don't if only the HTML was
379 # refreshed, e.g. because of a dependency.
380 if ((grep { $_ eq $pagesources{$page} } @origneedsbuild)
381 || ! -e potfile($masterfile)) {
382 refreshpot($masterfile);
387 push @pofiles, $_ if ($updated_pot_file || ! -e $_);
388 } (pofiles($masterfile));
390 refreshpofiles($masterfile, @pofiles);
391 map { IkiWiki::rcs_add($_) } @pofiles if $config{rcs};
396 if ($updated_po_files) {
398 gettext("updated PO files"),
399 "IkiWiki::Plugin::po::change");
403 sub checkcontent (@) {
406 if (istranslation($params{page})) {
407 my $res = isvalidpo($params{content});
421 if (istranslation($params{page})) {
422 return gettext("Can not remove a translation. Removing the master page, ".
423 "though, removes its translations as well.");
430 my $session = $params{session};
432 if (istranslation($params{src})) {
433 my $masterpage = masterpage($params{src});
434 # Tell the difference between:
435 # - a translation being renamed as a consequence of its master page
436 # being renamed, which is allowed
437 # - a user trying to directly rename a translation, which is forbidden
438 # by looking for the master page in the list of to-be-renamed pages we
439 # saved early in the renaming process.
440 my $orig_torename = $session->param("po_orig_torename");
441 unless (grep { $_ eq $masterpage } @{$orig_torename}) {
442 return gettext("Can not rename a translation. Renaming the master page, ".
443 "though, renames its translations as well.");
449 # As we're previewing or saving a page, the content may have
450 # changed, so tell the next filter() invocation it must not be lazy.
454 unsetalreadyfiltered($params{page}, $params{page});
455 return $params{content};
458 sub formbuilder_setup (@) {
460 my $form=$params{form};
463 return unless defined $form->field("do");
465 if ($form->field("do") eq "create") {
466 # Warn the user: new pages must be written in master language.
467 my $template=template("pocreatepage.tmpl");
468 $template->param(LANG => $config{po_master_language}{name});
469 $form->tmpl_param(message => $template->output);
471 elsif ($form->field("do") eq "edit") {
472 # Remove the rename/remove buttons on slave pages.
473 # This has to be done after the rename/remove plugins have added
474 # their buttons, which is why this hook must be run last.
475 # The canrename/canremove hooks already ensure this is forbidden
476 # at the backend level, so this is only UI sugar.
477 if (istranslation($form->field("page"))) {
479 for (my $i = 0; $i < @{$params{buttons}}; $i++) {
480 if (@{$params{buttons}}[$i] eq $_) {
481 delete @{$params{buttons}}[$i];
490 sub formbuilder (@) {
492 my $form=$params{form};
495 return unless defined $form->field("do");
497 # Do not allow to create pages of type po: they are automatically created.
498 # The main reason to do so is to bypass the "favor the type of linking page
499 # on page creation" logic, which is unsuitable when a broken link is clicked
500 # on a slave (PO) page.
501 # This cannot be done in the formbuilder_setup hook as the list of types is
503 if ($form->field("do") eq "create") {
504 foreach my $field ($form->field) {
505 next unless "$field" eq "type";
506 if ($field->type eq 'select') {
507 # remove po from the list of types
508 my @types = grep { $_ ne 'po' } $field->options;
509 $field->options(\@types) if @types;
516 # | Injected functions
519 # Implement po_link_to 'current' and 'negotiated' settings.
520 sub mybestlink ($$) {
524 my $res=$origsubs{'bestlink'}->(masterpage($page), $link);
526 && ($config{po_link_to} eq "current" || $config{po_link_to} eq "negotiated")
527 && istranslatable($res)
528 && istranslation($page)) {
529 return $res . "." . lang($page);
534 sub mybeautify_urlpath ($) {
537 my $res=$origsubs{'beautify_urlpath'}->($url);
538 if ($config{po_link_to} eq "negotiated") {
539 $res =~ s!/\Qindex.$config{po_master_language}{code}.$config{htmlext}\E$!/!;
540 $res =~ s!/\Qindex.$config{htmlext}\E$!/!;
542 $res =~ s!/\Qindex.$_.$config{htmlext}\E$!/!;
543 } (keys %{$config{po_slave_languages}});
548 sub mytargetpage ($$) {
552 if (istranslation($page) || istranslatable($page)) {
553 my ($masterpage, $lang) = (masterpage($page), lang($page));
554 if (! $config{usedirs} || $masterpage eq 'index') {
555 return $masterpage . "." . $lang . "." . $ext;
558 return $masterpage . "/index." . $lang . "." . $ext;
561 return $origsubs{'targetpage'}->($page, $ext);
569 # workaround hard-coded /index.$config{htmlext} in IkiWiki::urlto()
571 && $config{po_link_to} eq "current"
572 && istranslatable('index')) {
573 return IkiWiki::beautify_urlpath(IkiWiki::baseurl($from) . "index." . lang($from) . ".$config{htmlext}");
575 # avoid using our injected beautify_urlpath if run by cgi_editpage,
576 # so that one is redirected to the just-edited page rather than to the
577 # negociated translation; to prevent unnecessary fiddling with caller/inject,
578 # we only do so when our beautify_urlpath would actually do what we want to
579 # avoid, i.e. when po_link_to = negotiated
580 if ($config{po_link_to} eq "negotiated") {
581 my @caller = caller(1);
582 my $run_by_editpage = 0;
583 $run_by_editpage = 1 if (exists $caller[3] && defined $caller[3]
584 && $caller[3] eq "IkiWiki::cgi_editpage");
585 inject(name => "IkiWiki::beautify_urlpath", call => $origsubs{'beautify_urlpath'})
587 my $res = $origsubs{'urlto'}->($to,$from,$absolute);
588 inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath)
593 return $origsubs{'urlto'}->($to,$from,$absolute)
600 # slave pages have no subpages
601 if (istranslation($params{'from'})) {
602 $params{'from'} = masterpage($params{'from'});
604 return $origsubs{'cgiurl'}->(%params);
608 # | Blackboxes for private data
614 sub alreadyfiltered($$) {
618 return exists $filtered{$page}{$destpage}
619 && $filtered{$page}{$destpage} eq 1;
622 sub setalreadyfiltered($$) {
626 $filtered{$page}{$destpage}=1;
629 sub unsetalreadyfiltered($$) {
633 if (exists $filtered{$page}{$destpage}) {
634 delete $filtered{$page}{$destpage};
638 sub resetalreadyfiltered() {
647 sub maybe_add_leading_slash ($;$) {
650 $add=1 unless defined $add;
651 return '/' . $str if $add;
655 sub istranslatablefile ($) {
658 return 0 unless defined $file;
659 return 0 if defined pagetype($file) && pagetype($file) eq 'po';
660 return 0 if $file =~ /\.pot$/;
661 return 0 unless -e "$config{srcdir}/$file"; # underlay dirs may be read-only
662 return 1 if pagespec_match(pagename($file), $config{po_translatable_pages});
666 sub istranslatable ($) {
670 return 1 if istranslatablefile($pagesources{$page});
674 sub _istranslation ($) {
677 $page='' unless defined $page && length $page;
678 my $hasleadingslash = ($page=~s#^/##);
679 my $file=$pagesources{$page};
680 return 0 unless defined $file
681 && defined pagetype($file)
682 && pagetype($file) eq 'po';
683 return 0 if $file =~ /\.pot$/;
685 my ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
686 return 0 unless defined $masterpage && defined $lang
687 && length $masterpage && length $lang
688 && defined $pagesources{$masterpage}
689 && defined $config{po_slave_languages}{$lang};
691 return (maybe_add_leading_slash($masterpage, $hasleadingslash), $lang)
692 if istranslatable($masterpage);
695 sub istranslation ($) {
698 if (1 < (my ($masterpage, $lang) = _istranslation($page))) {
699 my $hasleadingslash = ($masterpage=~s#^/##);
700 $translations{$masterpage}{$lang}=$page unless exists $translations{$masterpage}{$lang};
701 return (maybe_add_leading_slash($masterpage, $hasleadingslash), $lang);
709 if ( 1 < (my ($masterpage, $lang) = _istranslation($page))) {
718 if (1 < (my ($masterpage, $lang) = _istranslation($page))) {
721 return $config{po_master_language}{code};
724 sub islanguagecode ($) {
727 return $code =~ /^[a-z]{2}$/;
730 sub otherlanguage ($$) {
734 return masterpage($page) if $code eq $config{po_master_language}{code};
735 return masterpage($page) . '.' . $code;
738 sub otherlanguages ($) {
742 return \%ret unless istranslation($page) || istranslatable($page);
743 my $curlang=lang($page);
745 ($config{po_master_language}{code}, keys %{$config{po_slave_languages}}) {
746 next if $lang eq $curlang;
747 $ret{$lang}=otherlanguage($page, $lang);
753 my $masterfile=shift;
755 (my $name, my $dir, my $suffix) = fileparse($masterfile, qr/\.[^.]*/);
756 $dir='' if $dir eq './';
757 return File::Spec->catpath('', $dir, $name . ".pot");
761 my $masterfile=shift;
764 (my $name, my $dir, my $suffix) = fileparse($masterfile, qr/\.[^.]*/);
765 $dir='' if $dir eq './';
766 return File::Spec->catpath('', $dir, $name . "." . $lang . ".po");
770 my $masterfile=shift;
772 return map pofile($masterfile, $_), (keys %{$config{po_slave_languages}});
776 my $masterfile=shift;
778 my $potfile=potfile($masterfile);
779 my %options = ("markdown" => (pagetype($masterfile) eq 'mdwn') ? 1 : 0);
780 my $doc=Locale::Po4a::Chooser::new('text',%options);
781 $doc->{TT}{utf_mode} = 1;
782 $doc->{TT}{file_in_charset} = 'utf-8';
783 $doc->{TT}{file_out_charset} = 'utf-8';
784 $doc->read($masterfile);
785 # let's cheat a bit to force porefs option to be passed to
786 # Locale::Po4a::Po; this is undocument use of internal
787 # Locale::Po4a::TransTractor's data, compulsory since this module
788 # prevents us from using the porefs option.
789 $doc->{TT}{po_out}=Locale::Po4a::Po->new({ 'porefs' => 'none' });
790 $doc->{TT}{po_out}->set_charset('utf-8');
793 IkiWiki::prep_writefile(basename($potfile),dirname($potfile));
794 $doc->writepo($potfile);
797 sub refreshpofiles ($@) {
798 my $masterfile=shift;
801 my $potfile=potfile($masterfile);
803 error("po(refreshpofiles) ".sprintf(gettext("POT file (%s) does not exist"), $potfile));
806 foreach my $pofile (@pofiles) {
807 IkiWiki::prep_writefile(basename($pofile),dirname($pofile));
809 system("msgmerge", "-U", "--backup=none", $pofile, $potfile) == 0
810 or error("po(refreshpofiles) ".
811 sprintf(gettext("failed to update %s"),
815 File::Copy::syscopy($potfile,$pofile)
816 or error("po(refreshpofiles) ".
817 sprintf(gettext("failed to copy the POT file to %s"),
823 sub buildtranslationscache() {
824 # use istranslation's side-effect
825 map istranslation($_), (keys %pagesources);
828 sub resettranslationscache() {
832 sub flushmemoizecache() {
833 Memoize::flush_cache("istranslatable");
834 Memoize::flush_cache("_istranslation");
835 Memoize::flush_cache("percenttranslated");
838 sub urlto_with_orig_beautiful_urlpath($$) {
842 inject(name => "IkiWiki::beautify_urlpath", call => $origsubs{'beautify_urlpath'});
843 my $res=urlto($to, $from);
844 inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath);
849 sub percenttranslated ($) {
853 return gettext("N/A") unless istranslation($page);
854 my $file=srcfile($pagesources{$page});
855 my $masterfile = srcfile($pagesources{masterpage($page)});
857 "markdown" => (pagetype($masterfile) eq 'mdwn') ? 1 : 0,
859 my $doc=Locale::Po4a::Chooser::new('text',%options);
861 'po_in_name' => [ $file ],
862 'file_in_name' => [ $masterfile ],
863 'file_in_charset' => 'utf-8',
864 'file_out_charset' => 'utf-8',
865 ) or error("po(percenttranslated) ".
866 sprintf(gettext("failed to translate %s"), $page));
867 my ($percent,$hit,$queries) = $doc->stats();
868 $percent =~ s/\.[0-9]+$//;
872 sub languagename ($) {
875 return $config{po_master_language}{name}
876 if $code eq $config{po_master_language}{code};
877 return $config{po_slave_languages}{$code}
878 if defined $config{po_slave_languages}{$code};
882 sub otherlanguagesloop ($) {
886 my %otherpages=%{otherlanguages($page)};
887 while (my ($lang, $otherpage) = each %otherpages) {
888 if (istranslation($page) && masterpage($page) eq $otherpage) {
890 url => urlto_with_orig_beautiful_urlpath($otherpage, $page),
892 language => languagename($lang),
898 url => urlto_with_orig_beautiful_urlpath($otherpage, $page),
900 language => languagename($lang),
901 percent => percenttranslated($otherpage),
906 return -1 if $a->{code} eq $config{po_master_language}{code};
907 return 1 if $b->{code} eq $config{po_master_language}{code};
908 return $a->{language} cmp $b->{language};
912 sub homepageurl (;$) {
915 return urlto('', $page);
918 sub deletetranslations ($) {
919 my $deletedmasterfile=shift;
921 my $deletedmasterpage=pagename($deletedmasterfile);
924 my $file = newpagefile($deletedmasterpage.'.'.$_, 'po');
925 my $absfile = "$config{srcdir}/$file";
926 if (-e $absfile && ! -l $absfile && ! -d $absfile) {
927 push @todelete, $file;
929 } keys %{$config{po_slave_languages}};
933 IkiWiki::rcs_remove($_);
936 IkiWiki::prune("$config{srcdir}/$_");
942 gettext("removed obsolete PO files"),
943 "IkiWiki::Plugin::po::deletetranslations");
947 sub commit_and_refresh ($$) {
948 my ($msg, $author) = (shift, shift);
951 IkiWiki::disable_commit_hook();
952 IkiWiki::rcs_commit_staged($msg, $author, "127.0.0.1");
953 IkiWiki::enable_commit_hook();
954 IkiWiki::rcs_update();
956 # Reinitialize module's private variables.
957 resetalreadyfiltered();
958 resettranslationscache();
960 # Trigger a wiki refresh.
961 require IkiWiki::Render;
962 # without preliminary saveindex/loadindex, refresh()
963 # complains about a lot of uninitialized variables
964 IkiWiki::saveindex();
965 IkiWiki::loadindex();
967 IkiWiki::saveindex();
970 # on success, returns the filtered content.
971 # on error, if $nonfatal, warn and return undef; else, error out.
972 sub po_to_markup ($$;$) {
973 my ($page, $content) = (shift, shift);
974 my $nonfatal = shift;
976 $content = '' unless defined $content;
977 $content = decode_utf8(encode_utf8($content));
978 # CRLF line terminators make poor Locale::Po4a feel bad
979 $content=~s/\r\n/\n/g;
981 # There are incompatibilities between some File::Temp versions
982 # (including 0.18, bundled with Lenny's perl-modules package)
983 # and others (e.g. 0.20, previously present in the archive as
984 # a standalone package): under certain circumstances, some
985 # return a relative filename, whereas others return an absolute one;
986 # we here use this module in a way that is at least compatible
987 # with 0.18 and 0.20. Beware, hit'n'run refactorers!
988 my $infile = new File::Temp(TEMPLATE => "ikiwiki-po-filter-in.XXXXXXXXXX",
989 DIR => File::Spec->tmpdir,
990 UNLINK => 1)->filename;
991 my $outfile = new File::Temp(TEMPLATE => "ikiwiki-po-filter-out.XXXXXXXXXX",
992 DIR => File::Spec->tmpdir,
993 UNLINK => 1)->filename;
996 my $msg = "po(po_to_markup) - $page : " . shift;
1001 error($msg, sub { unlink $infile, $outfile});
1004 writefile(basename($infile), File::Spec->tmpdir, $content)
1005 or return $fail->(sprintf(gettext("failed to write %s"), $infile));
1007 my $masterfile = srcfile($pagesources{masterpage($page)});
1009 "markdown" => (pagetype($masterfile) eq 'mdwn') ? 1 : 0,
1011 my $doc=Locale::Po4a::Chooser::new('text',%options);
1013 'po_in_name' => [ $infile ],
1014 'file_in_name' => [ $masterfile ],
1015 'file_in_charset' => 'utf-8',
1016 'file_out_charset' => 'utf-8',
1017 ) or return $fail->(gettext("failed to translate"));
1018 $doc->write($outfile)
1019 or return $fail->(sprintf(gettext("failed to write %s"), $outfile));
1021 $content = readfile($outfile)
1022 or return $fail->(sprintf(gettext("failed to read %s"), $outfile));
1024 # Unlinking should happen automatically, thanks to File::Temp,
1025 # but it does not work here, probably because of the way writefile()
1026 # and Locale::Po4a::write() work.
1027 unlink $infile, $outfile;
1032 # returns a SuccessReason or FailReason object
1034 my $content = shift;
1036 # NB: we don't use po_to_markup here, since Po4a parser does
1037 # not mind invalid PO content
1038 $content = '' unless defined $content;
1039 $content = decode_utf8(encode_utf8($content));
1041 # There are incompatibilities between some File::Temp versions
1042 # (including 0.18, bundled with Lenny's perl-modules package)
1043 # and others (e.g. 0.20, previously present in the archive as
1044 # a standalone package): under certain circumstances, some
1045 # return a relative filename, whereas others return an absolute one;
1046 # we here use this module in a way that is at least compatible
1047 # with 0.18 and 0.20. Beware, hit'n'run refactorers!
1048 my $infile = new File::Temp(TEMPLATE => "ikiwiki-po-isvalidpo.XXXXXXXXXX",
1049 DIR => File::Spec->tmpdir,
1050 UNLINK => 1)->filename;
1052 my $fail = sub ($) {
1053 my $msg = '[po/isvalidpo] ' . shift;
1055 return IkiWiki::FailReason->new("$msg");
1058 writefile(basename($infile), File::Spec->tmpdir, $content)
1059 or return $fail->(sprintf(gettext("failed to write %s"), $infile));
1061 my $res = (system("msgfmt", "--check", $infile, "-o", "/dev/null") == 0);
1063 # Unlinking should happen automatically, thanks to File::Temp,
1064 # but it does not work here, probably because of the way writefile()
1065 # and Locale::Po4a::write() work.
1069 return IkiWiki::SuccessReason->new("valid gettext data");
1071 return IkiWiki::FailReason->new("invalid gettext data, go back ".
1072 "to previous page to go on with edit");
1079 package IkiWiki::PageSpec;
1081 sub match_istranslation ($;@) {
1084 if (IkiWiki::Plugin::po::istranslation($page)) {
1085 return IkiWiki::SuccessReason->new("is a translation page");
1088 return IkiWiki::FailReason->new("is not a translation page");
1092 sub match_istranslatable ($;@) {
1095 if (IkiWiki::Plugin::po::istranslatable($page)) {
1096 return IkiWiki::SuccessReason->new("is set as translatable in po_translatable_pages");
1099 return IkiWiki::FailReason->new("is not set as translatable in po_translatable_pages");
1103 sub match_lang ($$;@) {
1107 my $regexp=IkiWiki::glob2re($wanted);
1108 my $lang=IkiWiki::Plugin::po::lang($page);
1109 if ($lang !~ /^$regexp$/i) {
1110 return IkiWiki::FailReason->new("file language is $lang, not $wanted");
1113 return IkiWiki::SuccessReason->new("file language is $wanted");
1117 sub match_currentlang ($$;@) {
1122 return IkiWiki::FailReason->new("no location provided") unless exists $params{location};
1124 my $currentlang=IkiWiki::Plugin::po::lang($params{location});
1125 my $lang=IkiWiki::Plugin::po::lang($page);
1127 if ($lang eq $currentlang) {
1128 return IkiWiki::SuccessReason->new("file language is the same as current one, i.e. $currentlang");
1131 return IkiWiki::FailReason->new("file language is $lang, whereas current language is $currentlang");