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 return unless UNIVERSAL::can("IkiWiki::Plugin::link", "import");
183 if (istranslation($page)) {
184 foreach my $destpage (@{$links{$page}}) {
185 if (istranslatable($destpage)) {
186 # replace one occurence of $destpage in $links{$page}
187 # (we only want to replace the one that was added by
188 # IkiWiki::Plugin::link::scan, other occurences may be
189 # there for other reasons)
190 for (my $i=0; $i<@{$links{$page}}; $i++) {
191 if (@{$links{$page}}[$i] eq $destpage) {
192 @{$links{$page}}[$i] = $destpage . '.' . lang($page);
199 elsif (! istranslatable($page) && ! istranslation($page)) {
200 foreach my $destpage (@{$links{$page}}) {
201 if (istranslatable($destpage)) {
202 # make sure any destpage's translations has
203 # $page in its backlinks
204 push @{$links{$page}},
205 values %{otherlanguages($destpage)};
211 # We use filter to convert PO to the master page's format,
212 # since the rest of ikiwiki should not work on PO files.
216 my $page = $params{page};
217 my $destpage = $params{destpage};
218 my $content = $params{content};
219 if (istranslation($page) && ! alreadyfiltered($page, $destpage)) {
220 $content = po_to_markup($page, $content);
221 setalreadyfiltered($page, $destpage);
229 my $page = $params{page};
230 my $content = $params{content};
232 # ignore PO files this plugin did not create
233 return $content unless istranslation($page);
235 # force content to be htmlize'd as if it was the same type as the master page
236 return IkiWiki::htmlize($page, $page,
237 pagetype(srcfile($pagesources{masterpage($page)})),
241 sub pagetemplate (@) {
243 my $page=$params{page};
244 my $destpage=$params{destpage};
245 my $template=$params{template};
247 my ($masterpage, $lang) = istranslation($page);
249 if (istranslation($page) && $template->query(name => "percenttranslated")) {
250 $template->param(percenttranslated => percenttranslated($page));
252 if ($template->query(name => "istranslation")) {
253 $template->param(istranslation => scalar istranslation($page));
255 if ($template->query(name => "istranslatable")) {
256 $template->param(istranslatable => istranslatable($page));
258 if ($template->query(name => "HOMEPAGEURL")) {
259 $template->param(homepageurl => homepageurl($page));
261 if ($template->query(name => "otherlanguages")) {
262 $template->param(otherlanguages => [otherlanguagesloop($page)]);
263 map add_depends($page, $_), (values %{otherlanguages($page)});
265 # Rely on IkiWiki::Render's genpage() to decide wether
266 # a discussion link should appear on $page; this is not
267 # totally accurate, though: some broken links may be generated
268 # when cgiurl is disabled.
269 # This compromise avoids some code duplication, and will probably
270 # prevent future breakage when ikiwiki internals change.
271 # Known limitations are preferred to future random bugs.
272 if ($template->param('discussionlink') && istranslation($page)) {
273 $template->param('discussionlink' => htmllink(
276 $masterpage . '/' . gettext("Discussion"),
279 linktext => gettext("Discussion"),
282 # Remove broken parentlink to ./index.html on home page's translations.
283 # It works because this hook has the "last" parameter set, to ensure it
284 # runs after parentlinks' own pagetemplate hook.
285 if ($template->param('parentlinks')
286 && istranslation($page)
287 && $masterpage eq "index") {
288 $template->param('parentlinks' => []);
292 # Add the renamed page translations to the list of to-be-renamed pages.
296 my %torename = %{$params{torename}};
297 my $session = $params{session};
299 # Save the page(s) the user asked to rename, so that our
300 # canrename hook can tell the difference between:
301 # - a translation being renamed as a consequence of its master page
303 # - a user trying to directly rename a translation
304 # This is why this hook has to be run first, before the list of pages
305 # to rename is modified by other plugins.
307 @orig_torename=@{$session->param("po_orig_torename")}
308 if defined $session->param("po_orig_torename");
309 push @orig_torename, $torename{src};
310 $session->param(po_orig_torename => \@orig_torename);
311 IkiWiki::cgi_savesession($session);
313 return () unless istranslatable($torename{src});
316 my %otherpages=%{otherlanguages($torename{src})};
317 while (my ($lang, $otherpage) = each %otherpages) {
320 srcfile => $pagesources{$otherpage},
321 dest => otherlanguage($torename{dest}, $lang),
322 destfile => $torename{dest}.".".$lang.".po",
332 map { deletetranslations($_) } grep istranslatablefile($_), @deleted;
338 # All meta titles are first extracted at scan time, i.e. before we turn
339 # PO files back into translated markdown; escaping of double-quotes in
340 # PO files breaks the meta plugin's parsing enough to save ugly titles
341 # to %pagestate at this time.
343 # Then, at render time, every page's passes on row through the Great
344 # Rendering Chain (filter->preprocess->linkify->htmlize), and the meta
345 # plugin's preprocess hook is this time in a position to correctly
346 # extract the titles from slave pages.
348 # This is, unfortunately, too late: if the page A, linking to the page B,
349 # is rendered before B, it will display the wrongly-extracted meta title
350 # as the link text to B.
352 # On the one hand, such a corner case only happens on rebuild: on
353 # refresh, every rendered page is fixed to contain correct meta titles.
354 # On the other hand, it can take some time to get every page fixed.
355 # We therefore re-render every rendered page after a rebuild to fix them
356 # at once. As this more or less doubles the time needed to rebuild the
357 # wiki, we do so only when really needed.
360 && exists $config{rebuild} && defined $config{rebuild} && $config{rebuild}
361 && UNIVERSAL::can("IkiWiki::Plugin::meta", "getsetup")
362 && exists $config{meta_overrides_page_title}
363 && defined $config{meta_overrides_page_title}
364 && $config{meta_overrides_page_title}) {
365 debug(sprintf(gettext("re-rendering all pages to fix meta titles")));
366 resetalreadyfiltered();
367 require IkiWiki::Render;
368 foreach my $file (@rendered) {
369 debug(sprintf(gettext("rendering %s"), $file));
370 IkiWiki::render($file);
374 my $updated_po_files=0;
376 # Refresh/create POT and PO files as needed.
377 foreach my $file (grep {istranslatablefile($_)} @rendered) {
378 my $page=pagename($file);
379 my $masterfile=srcfile($file);
380 my $updated_pot_file=0;
381 # Only refresh Pot file if it does not exist, or if
382 # $pagesources{$page} was changed: don't if only the HTML was
383 # refreshed, e.g. because of a dependency.
384 if ((grep { $_ eq $pagesources{$page} } @origneedsbuild)
385 || ! -e potfile($masterfile)) {
386 refreshpot($masterfile);
391 push @pofiles, $_ if ($updated_pot_file || ! -e $_);
392 } (pofiles($masterfile));
394 refreshpofiles($masterfile, @pofiles);
395 map { IkiWiki::rcs_add($_) } @pofiles if $config{rcs};
400 if ($updated_po_files) {
402 gettext("updated PO files"),
403 "IkiWiki::Plugin::po::change");
407 sub checkcontent (@) {
410 if (istranslation($params{page})) {
411 my $res = isvalidpo($params{content});
425 if (istranslation($params{page})) {
426 return gettext("Can not remove a translation. Removing the master page, ".
427 "though, removes its translations as well.");
434 my $session = $params{session};
436 if (istranslation($params{src})) {
437 my $masterpage = masterpage($params{src});
438 # Tell the difference between:
439 # - a translation being renamed as a consequence of its master page
440 # being renamed, which is allowed
441 # - a user trying to directly rename a translation, which is forbidden
442 # by looking for the master page in the list of to-be-renamed pages we
443 # saved early in the renaming process.
444 my $orig_torename = $session->param("po_orig_torename");
445 unless (grep { $_ eq $masterpage } @{$orig_torename}) {
446 return gettext("Can not rename a translation. Renaming the master page, ".
447 "though, renames its translations as well.");
453 # As we're previewing or saving a page, the content may have
454 # changed, so tell the next filter() invocation it must not be lazy.
458 unsetalreadyfiltered($params{page}, $params{page});
459 return $params{content};
462 sub formbuilder_setup (@) {
464 my $form=$params{form};
467 return unless defined $form->field("do");
469 if ($form->field("do") eq "create") {
470 # Warn the user: new pages must be written in master language.
471 my $template=template("pocreatepage.tmpl");
472 $template->param(LANG => $config{po_master_language}{name});
473 $form->tmpl_param(message => $template->output);
475 elsif ($form->field("do") eq "edit") {
476 # Remove the rename/remove buttons on slave pages.
477 # This has to be done after the rename/remove plugins have added
478 # their buttons, which is why this hook must be run last.
479 # The canrename/canremove hooks already ensure this is forbidden
480 # at the backend level, so this is only UI sugar.
481 if (istranslation($form->field("page"))) {
483 for (my $i = 0; $i < @{$params{buttons}}; $i++) {
484 if (@{$params{buttons}}[$i] eq $_) {
485 delete @{$params{buttons}}[$i];
494 sub formbuilder (@) {
496 my $form=$params{form};
499 return unless defined $form->field("do");
501 # Do not allow to create pages of type po: they are automatically created.
502 # The main reason to do so is to bypass the "favor the type of linking page
503 # on page creation" logic, which is unsuitable when a broken link is clicked
504 # on a slave (PO) page.
505 # This cannot be done in the formbuilder_setup hook as the list of types is
507 if ($form->field("do") eq "create") {
508 foreach my $field ($form->field) {
509 next unless "$field" eq "type";
510 if ($field->type eq 'select') {
511 # remove po from the list of types
512 my @types = grep { $_ ne 'po' } $field->options;
513 $field->options(\@types) if @types;
520 # | Injected functions
523 # Implement po_link_to 'current' and 'negotiated' settings.
524 sub mybestlink ($$) {
528 my $res=$origsubs{'bestlink'}->(masterpage($page), $link);
530 && ($config{po_link_to} eq "current" || $config{po_link_to} eq "negotiated")
531 && istranslatable($res)
532 && istranslation($page)) {
533 return $res . "." . lang($page);
538 sub mybeautify_urlpath ($) {
541 my $res=$origsubs{'beautify_urlpath'}->($url);
542 if ($config{po_link_to} eq "negotiated") {
543 $res =~ s!/\Qindex.$config{po_master_language}{code}.$config{htmlext}\E$!/!;
544 $res =~ s!/\Qindex.$config{htmlext}\E$!/!;
546 $res =~ s!/\Qindex.$_.$config{htmlext}\E$!/!;
547 } (keys %{$config{po_slave_languages}});
552 sub mytargetpage ($$) {
556 if (istranslation($page) || istranslatable($page)) {
557 my ($masterpage, $lang) = (masterpage($page), lang($page));
558 if (! $config{usedirs} || $masterpage eq 'index') {
559 return $masterpage . "." . $lang . "." . $ext;
562 return $masterpage . "/index." . $lang . "." . $ext;
565 return $origsubs{'targetpage'}->($page, $ext);
573 # workaround hard-coded /index.$config{htmlext} in IkiWiki::urlto()
575 && $config{po_link_to} eq "current"
576 && istranslatable('index')) {
577 return IkiWiki::beautify_urlpath(IkiWiki::baseurl($from) . "index." . lang($from) . ".$config{htmlext}");
579 # avoid using our injected beautify_urlpath if run by cgi_editpage,
580 # so that one is redirected to the just-edited page rather than to the
581 # negociated translation; to prevent unnecessary fiddling with caller/inject,
582 # we only do so when our beautify_urlpath would actually do what we want to
583 # avoid, i.e. when po_link_to = negotiated
584 if ($config{po_link_to} eq "negotiated") {
585 my @caller = caller(1);
586 my $run_by_editpage = 0;
587 $run_by_editpage = 1 if (exists $caller[3] && defined $caller[3]
588 && $caller[3] eq "IkiWiki::cgi_editpage");
589 inject(name => "IkiWiki::beautify_urlpath", call => $origsubs{'beautify_urlpath'})
591 my $res = $origsubs{'urlto'}->($to,$from,$absolute);
592 inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath)
597 return $origsubs{'urlto'}->($to,$from,$absolute)
604 # slave pages have no subpages
605 if (istranslation($params{'from'})) {
606 $params{'from'} = masterpage($params{'from'});
608 return $origsubs{'cgiurl'}->(%params);
612 # | Blackboxes for private data
618 sub alreadyfiltered($$) {
622 return exists $filtered{$page}{$destpage}
623 && $filtered{$page}{$destpage} eq 1;
626 sub setalreadyfiltered($$) {
630 $filtered{$page}{$destpage}=1;
633 sub unsetalreadyfiltered($$) {
637 if (exists $filtered{$page}{$destpage}) {
638 delete $filtered{$page}{$destpage};
642 sub resetalreadyfiltered() {
651 sub maybe_add_leading_slash ($;$) {
654 $add=1 unless defined $add;
655 return '/' . $str if $add;
659 sub istranslatablefile ($) {
662 return 0 unless defined $file;
663 return 0 if defined pagetype($file) && pagetype($file) eq 'po';
664 return 0 if $file =~ /\.pot$/;
665 return 0 unless -e "$config{srcdir}/$file"; # underlay dirs may be read-only
666 return 1 if pagespec_match(pagename($file), $config{po_translatable_pages});
670 sub istranslatable ($) {
674 return 1 if istranslatablefile($pagesources{$page});
678 sub _istranslation ($) {
681 $page='' unless defined $page && length $page;
682 my $hasleadingslash = ($page=~s#^/##);
683 my $file=$pagesources{$page};
684 return 0 unless defined $file
685 && defined pagetype($file)
686 && pagetype($file) eq 'po';
687 return 0 if $file =~ /\.pot$/;
689 my ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
690 return 0 unless defined $masterpage && defined $lang
691 && length $masterpage && length $lang
692 && defined $pagesources{$masterpage}
693 && defined $config{po_slave_languages}{$lang};
695 return (maybe_add_leading_slash($masterpage, $hasleadingslash), $lang)
696 if istranslatable($masterpage);
699 sub istranslation ($) {
702 if (1 < (my ($masterpage, $lang) = _istranslation($page))) {
703 my $hasleadingslash = ($masterpage=~s#^/##);
704 $translations{$masterpage}{$lang}=$page unless exists $translations{$masterpage}{$lang};
705 return (maybe_add_leading_slash($masterpage, $hasleadingslash), $lang);
713 if ( 1 < (my ($masterpage, $lang) = _istranslation($page))) {
722 if (1 < (my ($masterpage, $lang) = _istranslation($page))) {
725 return $config{po_master_language}{code};
728 sub islanguagecode ($) {
731 return $code =~ /^[a-z]{2}$/;
734 sub otherlanguage ($$) {
738 return masterpage($page) if $code eq $config{po_master_language}{code};
739 return masterpage($page) . '.' . $code;
742 sub otherlanguages ($) {
746 return \%ret unless istranslation($page) || istranslatable($page);
747 my $curlang=lang($page);
749 ($config{po_master_language}{code}, keys %{$config{po_slave_languages}}) {
750 next if $lang eq $curlang;
751 $ret{$lang}=otherlanguage($page, $lang);
757 my $masterfile=shift;
759 (my $name, my $dir, my $suffix) = fileparse($masterfile, qr/\.[^.]*/);
760 $dir='' if $dir eq './';
761 return File::Spec->catpath('', $dir, $name . ".pot");
765 my $masterfile=shift;
768 (my $name, my $dir, my $suffix) = fileparse($masterfile, qr/\.[^.]*/);
769 $dir='' if $dir eq './';
770 return File::Spec->catpath('', $dir, $name . "." . $lang . ".po");
774 my $masterfile=shift;
776 return map pofile($masterfile, $_), (keys %{$config{po_slave_languages}});
780 my $masterfile=shift;
782 my $potfile=potfile($masterfile);
783 my %options = ("markdown" => (pagetype($masterfile) eq 'mdwn') ? 1 : 0);
784 my $doc=Locale::Po4a::Chooser::new('text',%options);
785 $doc->{TT}{utf_mode} = 1;
786 $doc->{TT}{file_in_charset} = 'utf-8';
787 $doc->{TT}{file_out_charset} = 'utf-8';
788 $doc->read($masterfile);
789 # let's cheat a bit to force porefs option to be passed to Locale::Po4a::Po;
790 # this is undocument use of internal Locale::Po4a::TransTractor's data,
791 # compulsory since this module prevents us from using the porefs option.
792 $doc->{TT}{po_out}=Locale::Po4a::Po->new({ 'porefs' => 'none' });
793 $doc->{TT}{po_out}->set_charset('utf-8');
796 IkiWiki::prep_writefile(basename($potfile),dirname($potfile));
797 $doc->writepo($potfile);
800 sub refreshpofiles ($@) {
801 my $masterfile=shift;
804 my $potfile=potfile($masterfile);
806 error("po(refreshpofiles) ".sprintf(gettext("POT file (%s) does not exist"), $potfile));
809 foreach my $pofile (@pofiles) {
810 IkiWiki::prep_writefile(basename($pofile),dirname($pofile));
812 system("msgmerge", "-U", "--backup=none", $pofile, $potfile) == 0
813 or error("po(refreshpofiles) ".
814 sprintf(gettext("failed to update %s"),
818 File::Copy::syscopy($potfile,$pofile)
819 or error("po(refreshpofiles) ".
820 sprintf(gettext("failed to copy the POT file to %s"),
826 sub buildtranslationscache() {
827 # use istranslation's side-effect
828 map istranslation($_), (keys %pagesources);
831 sub resettranslationscache() {
835 sub flushmemoizecache() {
836 Memoize::flush_cache("istranslatable");
837 Memoize::flush_cache("_istranslation");
838 Memoize::flush_cache("percenttranslated");
841 sub urlto_with_orig_beautiful_urlpath($$) {
845 inject(name => "IkiWiki::beautify_urlpath", call => $origsubs{'beautify_urlpath'});
846 my $res=urlto($to, $from);
847 inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath);
852 sub percenttranslated ($) {
856 return gettext("N/A") unless istranslation($page);
857 my $file=srcfile($pagesources{$page});
858 my $masterfile = srcfile($pagesources{masterpage($page)});
860 "markdown" => (pagetype($masterfile) eq 'mdwn') ? 1 : 0,
862 my $doc=Locale::Po4a::Chooser::new('text',%options);
864 'po_in_name' => [ $file ],
865 'file_in_name' => [ $masterfile ],
866 'file_in_charset' => 'utf-8',
867 'file_out_charset' => 'utf-8',
868 ) or error("po(percenttranslated) ".
869 sprintf(gettext("failed to translate %s"), $page));
870 my ($percent,$hit,$queries) = $doc->stats();
871 $percent =~ s/\.[0-9]+$//;
875 sub languagename ($) {
878 return $config{po_master_language}{name}
879 if $code eq $config{po_master_language}{code};
880 return $config{po_slave_languages}{$code}
881 if defined $config{po_slave_languages}{$code};
885 sub otherlanguagesloop ($) {
889 my %otherpages=%{otherlanguages($page)};
890 while (my ($lang, $otherpage) = each %otherpages) {
891 if (istranslation($page) && masterpage($page) eq $otherpage) {
893 url => urlto_with_orig_beautiful_urlpath($otherpage, $page),
895 language => languagename($lang),
901 url => urlto_with_orig_beautiful_urlpath($otherpage, $page),
903 language => languagename($lang),
904 percent => percenttranslated($otherpage),
909 return -1 if $a->{code} eq $config{po_master_language}{code};
910 return 1 if $b->{code} eq $config{po_master_language}{code};
911 return $a->{language} cmp $b->{language};
915 sub homepageurl (;$) {
918 return urlto('', $page);
921 sub deletetranslations ($) {
922 my $deletedmasterfile=shift;
924 my $deletedmasterpage=pagename($deletedmasterfile);
927 my $file = newpagefile($deletedmasterpage.'.'.$_, 'po');
928 my $absfile = "$config{srcdir}/$file";
929 if (-e $absfile && ! -l $absfile && ! -d $absfile) {
930 push @todelete, $file;
932 } keys %{$config{po_slave_languages}};
936 IkiWiki::rcs_remove($_);
939 IkiWiki::prune("$config{srcdir}/$_");
945 gettext("removed obsolete PO files"),
946 "IkiWiki::Plugin::po::deletetranslations");
950 sub commit_and_refresh ($$) {
951 my ($msg, $author) = (shift, shift);
954 IkiWiki::disable_commit_hook();
955 IkiWiki::rcs_commit_staged($msg, $author, "127.0.0.1");
956 IkiWiki::enable_commit_hook();
957 IkiWiki::rcs_update();
959 # Reinitialize module's private variables.
960 resetalreadyfiltered();
961 resettranslationscache();
963 # Trigger a wiki refresh.
964 require IkiWiki::Render;
965 # without preliminary saveindex/loadindex, refresh()
966 # complains about a lot of uninitialized variables
967 IkiWiki::saveindex();
968 IkiWiki::loadindex();
970 IkiWiki::saveindex();
973 # on success, returns the filtered content.
974 # on error, if $nonfatal, warn and return undef; else, error out.
975 sub po_to_markup ($$;$) {
976 my ($page, $content) = (shift, shift);
977 my $nonfatal = shift;
979 $content = '' unless defined $content;
980 $content = decode_utf8(encode_utf8($content));
981 # CRLF line terminators make poor Locale::Po4a feel bad
982 $content=~s/\r\n/\n/g;
984 # There are incompatibilities between some File::Temp versions
985 # (including 0.18, bundled with Lenny's perl-modules package)
986 # and others (e.g. 0.20, previously present in the archive as
987 # a standalone package): under certain circumstances, some
988 # return a relative filename, whereas others return an absolute one;
989 # we here use this module in a way that is at least compatible
990 # with 0.18 and 0.20. Beware, hit'n'run refactorers!
991 my $infile = new File::Temp(TEMPLATE => "ikiwiki-po-filter-in.XXXXXXXXXX",
992 DIR => File::Spec->tmpdir,
993 UNLINK => 1)->filename;
994 my $outfile = new File::Temp(TEMPLATE => "ikiwiki-po-filter-out.XXXXXXXXXX",
995 DIR => File::Spec->tmpdir,
996 UNLINK => 1)->filename;
999 my $msg = "po(po_to_markup) - $page : " . shift;
1004 error($msg, sub { unlink $infile, $outfile});
1007 writefile(basename($infile), File::Spec->tmpdir, $content)
1008 or return $fail->(sprintf(gettext("failed to write %s"), $infile));
1010 my $masterfile = srcfile($pagesources{masterpage($page)});
1012 "markdown" => (pagetype($masterfile) eq 'mdwn') ? 1 : 0,
1014 my $doc=Locale::Po4a::Chooser::new('text',%options);
1016 'po_in_name' => [ $infile ],
1017 'file_in_name' => [ $masterfile ],
1018 'file_in_charset' => 'utf-8',
1019 'file_out_charset' => 'utf-8',
1020 ) or return $fail->(gettext("failed to translate"));
1021 $doc->write($outfile)
1022 or return $fail->(sprintf(gettext("failed to write %s"), $outfile));
1024 $content = readfile($outfile)
1025 or return $fail->(sprintf(gettext("failed to read %s"), $outfile));
1027 # Unlinking should happen automatically, thanks to File::Temp,
1028 # but it does not work here, probably because of the way writefile()
1029 # and Locale::Po4a::write() work.
1030 unlink $infile, $outfile;
1035 # returns a SuccessReason or FailReason object
1037 my $content = shift;
1039 # NB: we don't use po_to_markup here, since Po4a parser does
1040 # not mind invalid PO content
1041 $content = '' unless defined $content;
1042 $content = decode_utf8(encode_utf8($content));
1044 # There are incompatibilities between some File::Temp versions
1045 # (including 0.18, bundled with Lenny's perl-modules package)
1046 # and others (e.g. 0.20, previously present in the archive as
1047 # a standalone package): under certain circumstances, some
1048 # return a relative filename, whereas others return an absolute one;
1049 # we here use this module in a way that is at least compatible
1050 # with 0.18 and 0.20. Beware, hit'n'run refactorers!
1051 my $infile = new File::Temp(TEMPLATE => "ikiwiki-po-isvalidpo.XXXXXXXXXX",
1052 DIR => File::Spec->tmpdir,
1053 UNLINK => 1)->filename;
1055 my $fail = sub ($) {
1056 my $msg = '[po/isvalidpo] ' . shift;
1058 return IkiWiki::FailReason->new("$msg");
1061 writefile(basename($infile), File::Spec->tmpdir, $content)
1062 or return $fail->(sprintf(gettext("failed to write %s"), $infile));
1064 my $res = (system("msgfmt", "--check", $infile, "-o", "/dev/null") == 0);
1066 # Unlinking should happen automatically, thanks to File::Temp,
1067 # but it does not work here, probably because of the way writefile()
1068 # and Locale::Po4a::write() work.
1072 return IkiWiki::SuccessReason->new("valid gettext data");
1074 return IkiWiki::FailReason->new("invalid gettext data, go back ".
1075 "to previous page to go on with edit");
1082 package IkiWiki::PageSpec;
1084 sub match_istranslation ($;@) {
1087 if (IkiWiki::Plugin::po::istranslation($page)) {
1088 return IkiWiki::SuccessReason->new("is a translation page");
1091 return IkiWiki::FailReason->new("is not a translation page");
1095 sub match_istranslatable ($;@) {
1098 if (IkiWiki::Plugin::po::istranslatable($page)) {
1099 return IkiWiki::SuccessReason->new("is set as translatable in po_translatable_pages");
1102 return IkiWiki::FailReason->new("is not set as translatable in po_translatable_pages");
1106 sub match_lang ($$;@) {
1110 my $regexp=IkiWiki::glob2re($wanted);
1111 my $lang=IkiWiki::Plugin::po::lang($page);
1112 if ($lang !~ /^$regexp$/i) {
1113 return IkiWiki::FailReason->new("file language is $lang, not $wanted");
1116 return IkiWiki::SuccessReason->new("file language is $wanted");
1120 sub match_currentlang ($$;@) {
1125 return IkiWiki::FailReason->new("no location provided") unless exists $params{location};
1127 my $currentlang=IkiWiki::Plugin::po::lang($params{location});
1128 my $lang=IkiWiki::Plugin::po::lang($page);
1130 if ($lang eq $currentlang) {
1131 return IkiWiki::SuccessReason->new("file language is the same as current one, i.e. $currentlang");
1134 return IkiWiki::FailReason->new("file language is $lang, whereas current language is $currentlang");