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}) {
123 if (! exists $config{$field} || ! defined $config{$field}) {
124 error(sprintf(gettext("Must specify %s when using the %s plugin"),
131 or error(sprintf(gettext("%s is not a valid language code"), $_));
132 } ($config{po_master_language}{code}, keys %{$config{po_slave_languages}});
134 if (! exists $config{po_translatable_pages} ||
135 ! defined $config{po_translatable_pages}) {
136 $config{po_translatable_pages}="";
138 if (! exists $config{po_link_to} ||
139 ! defined $config{po_link_to}) {
140 $config{po_link_to}='default';
142 elsif ($config{po_link_to} !~ /^(default|current|negotiated)$/) {
143 warn(sprintf(gettext('%s is not a valid value for po_link_to, falling back to po_link_to=default'),
144 $config{po_link_to}));
145 $config{po_link_to}='default';
147 elsif ($config{po_link_to} eq "negotiated" && ! $config{usedirs}) {
148 warn(gettext('po_link_to=negotiated requires usedirs to be enabled, falling back to po_link_to=default'));
149 $config{po_link_to}='default';
152 push @{$config{wiki_file_prune_regexps}}, qr/\.pot$/;
154 if ($config{po_master_language}{code} ne 'en') {
155 # use translated underlay directories in preference
156 # to the untranslated ones
157 foreach my $underlay ('basewiki', reverse @{$config{underlaydirs}}) {
158 add_underlay("locale/".$config{po_master_language}{code}."/".$underlay);
164 my $needsbuild=shift;
166 # backup @needsbuild content so that change() can know whether
167 # a given master page was rendered because its source file was changed
168 @origneedsbuild=(@$needsbuild);
171 buildtranslationscache();
173 # make existing translations depend on the corresponding master page
174 foreach my $master (keys %translations) {
175 map add_depends($_, $master), values %{otherlanguages($master)};
179 # Massage the recorded state of internal links so that:
180 # - it matches the actually generated links, rather than the links as written
181 # in the pages' source
182 # - backlinks are consistent in all cases
185 my $page=$params{page};
186 my $content=$params{content};
188 if (istranslation($page)) {
189 foreach my $destpage (@{$links{$page}}) {
190 if (istranslatable($destpage)) {
191 # replace one occurence of $destpage in $links{$page}
192 # (we only want to replace the one that was added by
193 # IkiWiki::Plugin::link::scan, other occurences may be
194 # there for other reasons)
195 for (my $i=0; $i<@{$links{$page}}; $i++) {
196 if (@{$links{$page}}[$i] eq $destpage) {
197 @{$links{$page}}[$i] = $destpage . '.' . lang($page);
204 elsif (! istranslatable($page) && ! istranslation($page)) {
205 foreach my $destpage (@{$links{$page}}) {
206 if (istranslatable($destpage)) {
207 # make sure any destpage's translations has
208 # $page in its backlinks
209 push @{$links{$page}},
210 values %{otherlanguages($destpage)};
216 # We use filter to convert PO to the master page's format,
217 # since the rest of ikiwiki should not work on PO files.
221 my $page = $params{page};
222 my $destpage = $params{destpage};
223 my $content = $params{content};
224 if (istranslation($page) && ! alreadyfiltered($page, $destpage)) {
225 $content = po_to_markup($page, $content);
226 setalreadyfiltered($page, $destpage);
234 my $page = $params{page};
235 my $content = $params{content};
237 # ignore PO files this plugin did not create
238 return $content unless istranslation($page);
240 # force content to be htmlize'd as if it was the same type as the master page
241 return IkiWiki::htmlize($page, $page,
242 pagetype(srcfile($pagesources{masterpage($page)})),
246 sub pagetemplate (@) {
248 my $page=$params{page};
249 my $destpage=$params{destpage};
250 my $template=$params{template};
252 my ($masterpage, $lang) = istranslation($page);
254 if (istranslation($page) && $template->query(name => "percenttranslated")) {
255 $template->param(percenttranslated => percenttranslated($page));
257 if ($template->query(name => "istranslation")) {
258 $template->param(istranslation => scalar istranslation($page));
260 if ($template->query(name => "istranslatable")) {
261 $template->param(istranslatable => istranslatable($page));
263 if ($template->query(name => "HOMEPAGEURL")) {
264 $template->param(homepageurl => homepageurl($page));
266 if ($template->query(name => "otherlanguages")) {
267 $template->param(otherlanguages => [otherlanguagesloop($page)]);
268 map add_depends($page, $_), (values %{otherlanguages($page)});
270 if ($config{discussion} && istranslation($page)) {
271 my $discussionlink=gettext("discussion");
272 if ($page !~ /.*\/\Q$discussionlink\E$/i &&
273 (length $config{cgiurl} ||
274 exists $links{$masterpage."/".$discussionlink})) {
275 $template->param('discussionlink' => htmllink(
278 $masterpage . '/' . gettext("Discussion"),
281 linktext => gettext("Discussion"),
285 # Remove broken parentlink to ./index.html on home page's translations.
286 # It works because this hook has the "last" parameter set, to ensure it
287 # runs after parentlinks' own pagetemplate hook.
288 if ($template->param('parentlinks')
289 && istranslation($page)
290 && $masterpage eq "index") {
291 $template->param('parentlinks' => []);
295 # Add the renamed page translations to the list of to-be-renamed pages.
296 sub renamepages (@) {
299 my %torename = %{$params{torename}};
300 my $session = $params{session};
302 # Save the page(s) the user asked to rename, so that our
303 # canrename hook can tell the difference between:
304 # - a translation being renamed as a consequence of its master page
306 # - a user trying to directly rename a translation
307 # This is why this hook has to be run first, before the list of pages
308 # to rename is modified by other plugins.
310 @orig_torename=@{$session->param("po_orig_torename")}
311 if defined $session->param("po_orig_torename");
312 push @orig_torename, $torename{src};
313 $session->param(po_orig_torename => \@orig_torename);
314 IkiWiki::cgi_savesession($session);
316 return () unless istranslatable($torename{src});
319 my %otherpages=%{otherlanguages($torename{src})};
320 while (my ($lang, $otherpage) = each %otherpages) {
323 srcfile => $pagesources{$otherpage},
324 dest => otherlanguage($torename{dest}, $lang),
325 destfile => $torename{dest}.".".$lang.".po",
335 map { deletetranslations($_) } grep istranslatablefile($_), @deleted;
341 # All meta titles are first extracted at scan time, i.e. before we turn
342 # PO files back into translated markdown; escaping of double-quotes in
343 # PO files breaks the meta plugin's parsing enough to save ugly titles
344 # to %pagestate at this time.
346 # Then, at render time, every page passes in turn through the Great
347 # Rendering Chain (filter->preprocess->linkify->htmlize), and the meta
348 # plugin's preprocess hook is this time in a position to correctly
349 # extract the titles from slave pages.
351 # This is, unfortunately, too late: if the page A, linking to the page
352 # B, is rendered before B, it will display the wrongly-extracted meta
353 # title as the link text to B.
355 # On the one hand, such a corner case only happens on rebuild: on
356 # refresh, every rendered page is fixed to contain correct meta titles.
357 # On the other hand, it can take some time to get every page fixed.
358 # We therefore re-render every rendered page after a rebuild to fix them
359 # at once. As this more or less doubles the time needed to rebuild the
360 # wiki, we do so only when really needed.
363 && exists $config{rebuild} && defined $config{rebuild} && $config{rebuild}
364 && UNIVERSAL::can("IkiWiki::Plugin::meta", "getsetup")
365 && exists $config{meta_overrides_page_title}
366 && defined $config{meta_overrides_page_title}
367 && $config{meta_overrides_page_title}) {
368 debug(sprintf(gettext("re-rendering all pages to fix meta titles")));
369 resetalreadyfiltered();
370 require IkiWiki::Render;
371 foreach my $file (@rendered) {
372 debug(sprintf(gettext("rendering %s"), $file));
373 IkiWiki::render($file);
377 my $updated_po_files=0;
379 # Refresh/create POT and PO files as needed.
380 foreach my $file (grep {istranslatablefile($_)} @rendered) {
381 my $page=pagename($file);
382 my $masterfile=srcfile($file);
383 my $updated_pot_file=0;
384 # Only refresh Pot file if it does not exist, or if
385 # $pagesources{$page} was changed: don't if only the HTML was
386 # refreshed, e.g. because of a dependency.
387 if ((grep { $_ eq $pagesources{$page} } @origneedsbuild)
388 || ! -e potfile($masterfile)) {
389 refreshpot($masterfile);
394 push @pofiles, $_ if ($updated_pot_file || ! -e $_);
395 } (pofiles($masterfile));
397 refreshpofiles($masterfile, @pofiles);
398 map { IkiWiki::rcs_add($_) } @pofiles if $config{rcs};
403 if ($updated_po_files) {
405 gettext("updated PO files"),
406 "IkiWiki::Plugin::po::change");
410 sub checkcontent (@) {
413 if (istranslation($params{page})) {
414 my $res = isvalidpo($params{content});
428 if (istranslation($params{page})) {
429 return gettext("Can not remove a translation. Removing the master page, ".
430 "though, removes its translations as well.");
437 my $session = $params{session};
439 if (istranslation($params{src})) {
440 my $masterpage = masterpage($params{src});
441 # Tell the difference between:
442 # - a translation being renamed as a consequence of its master page
443 # being renamed, which is allowed
444 # - a user trying to directly rename a translation, which is forbidden
445 # by looking for the master page in the list of to-be-renamed pages we
446 # saved early in the renaming process.
447 my $orig_torename = $session->param("po_orig_torename");
448 unless (grep { $_ eq $masterpage } @{$orig_torename}) {
449 return gettext("Can not rename a translation. Renaming the master page, ".
450 "though, renames its translations as well.");
456 # As we're previewing or saving a page, the content may have
457 # changed, so tell the next filter() invocation it must not be lazy.
461 unsetalreadyfiltered($params{page}, $params{page});
462 return $params{content};
465 sub formbuilder_setup (@) {
467 my $form=$params{form};
470 return unless defined $form->field("do");
472 if ($form->field("do") eq "create") {
473 # Warn the user: new pages must be written in master language.
474 my $template=template("pocreatepage.tmpl");
475 $template->param(LANG => $config{po_master_language}{name});
476 $form->tmpl_param(message => $template->output);
478 elsif ($form->field("do") eq "edit") {
479 # Remove the rename/remove buttons on slave pages.
480 # This has to be done after the rename/remove plugins have added
481 # their buttons, which is why this hook must be run last.
482 # The canrename/canremove hooks already ensure this is forbidden
483 # at the backend level, so this is only UI sugar.
484 if (istranslation($form->field("page"))) {
486 for (my $i = 0; $i < @{$params{buttons}}; $i++) {
487 if (@{$params{buttons}}[$i] eq $_) {
488 delete @{$params{buttons}}[$i];
497 sub formbuilder (@) {
499 my $form=$params{form};
502 return unless defined $form->field("do");
504 # Do not allow to create pages of type po: they are automatically created.
505 # The main reason to do so is to bypass the "favor the type of linking page
506 # on page creation" logic, which is unsuitable when a broken link is clicked
507 # on a slave (PO) page.
508 # This cannot be done in the formbuilder_setup hook as the list of types is
510 if ($form->field("do") eq "create") {
511 foreach my $field ($form->field) {
512 next unless "$field" eq "type";
513 if ($field->type eq 'select') {
514 # remove po from the list of types
515 my @types = grep { $_ ne 'po' } $field->options;
516 $field->options(\@types) if @types;
523 # | Injected functions
526 # Implement po_link_to 'current' and 'negotiated' settings.
527 sub mybestlink ($$) {
531 my $res=$origsubs{'bestlink'}->(masterpage($page), $link);
533 && ($config{po_link_to} eq "current" || $config{po_link_to} eq "negotiated")
534 && istranslatable($res)
535 && istranslation($page)) {
536 return $res . "." . lang($page);
541 sub mybeautify_urlpath ($) {
544 my $res=$origsubs{'beautify_urlpath'}->($url);
545 if ($config{po_link_to} eq "negotiated") {
546 $res =~ s!/\Qindex.$config{po_master_language}{code}.$config{htmlext}\E$!/!;
547 $res =~ s!/\Qindex.$config{htmlext}\E$!/!;
549 $res =~ s!/\Qindex.$_.$config{htmlext}\E$!/!;
550 } (keys %{$config{po_slave_languages}});
555 sub mytargetpage ($$) {
559 if (istranslation($page) || istranslatable($page)) {
560 my ($masterpage, $lang) = (masterpage($page), lang($page));
561 if (! $config{usedirs} || $masterpage eq 'index') {
562 return $masterpage . "." . $lang . "." . $ext;
565 return $masterpage . "/index." . $lang . "." . $ext;
568 return $origsubs{'targetpage'}->($page, $ext);
576 # workaround hard-coded /index.$config{htmlext} in IkiWiki::urlto()
578 && $config{po_link_to} eq "current"
579 && istranslatable('index')) {
580 return IkiWiki::beautify_urlpath(IkiWiki::baseurl($from) . "index." . lang($from) . ".$config{htmlext}");
582 # avoid using our injected beautify_urlpath if run by cgi_editpage,
583 # so that one is redirected to the just-edited page rather than to the
584 # negociated translation; to prevent unnecessary fiddling with caller/inject,
585 # we only do so when our beautify_urlpath would actually do what we want to
586 # avoid, i.e. when po_link_to = negotiated
587 if ($config{po_link_to} eq "negotiated") {
588 my @caller = caller(1);
589 my $run_by_editpage = 0;
590 $run_by_editpage = 1 if (exists $caller[3] && defined $caller[3]
591 && $caller[3] eq "IkiWiki::cgi_editpage");
592 inject(name => "IkiWiki::beautify_urlpath", call => $origsubs{'beautify_urlpath'})
594 my $res = $origsubs{'urlto'}->($to,$from,$absolute);
595 inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath)
600 return $origsubs{'urlto'}->($to,$from,$absolute)
607 # slave pages have no subpages
608 if (istranslation($params{'from'})) {
609 $params{'from'} = masterpage($params{'from'});
611 return $origsubs{'cgiurl'}->(%params);
615 # | Blackboxes for private data
621 sub alreadyfiltered($$) {
625 return exists $filtered{$page}{$destpage}
626 && $filtered{$page}{$destpage} eq 1;
629 sub setalreadyfiltered($$) {
633 $filtered{$page}{$destpage}=1;
636 sub unsetalreadyfiltered($$) {
640 if (exists $filtered{$page}{$destpage}) {
641 delete $filtered{$page}{$destpage};
645 sub resetalreadyfiltered() {
654 sub maybe_add_leading_slash ($;$) {
657 $add=1 unless defined $add;
658 return '/' . $str if $add;
662 sub istranslatablefile ($) {
665 return 0 unless defined $file;
666 my $type=pagetype($file);
667 return 0 if ! defined $type || $type eq 'po';
668 return 0 if $file =~ /\.pot$/;
669 return 0 unless -e "$config{srcdir}/$file"; # underlay dirs may be read-only
670 return 1 if pagespec_match(pagename($file), $config{po_translatable_pages});
674 sub istranslatable ($) {
678 return 1 if istranslatablefile($pagesources{$page});
682 sub _istranslation ($) {
685 $page='' unless defined $page && length $page;
686 my $hasleadingslash = ($page=~s#^/##);
687 my $file=$pagesources{$page};
688 return 0 unless defined $file
689 && defined pagetype($file)
690 && pagetype($file) eq 'po';
691 return 0 if $file =~ /\.pot$/;
693 my ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
694 return 0 unless defined $masterpage && defined $lang
695 && length $masterpage && length $lang
696 && defined $pagesources{$masterpage}
697 && defined $config{po_slave_languages}{$lang};
699 return (maybe_add_leading_slash($masterpage, $hasleadingslash), $lang)
700 if istranslatable($masterpage);
703 sub istranslation ($) {
706 if (1 < (my ($masterpage, $lang) = _istranslation($page))) {
707 my $hasleadingslash = ($masterpage=~s#^/##);
708 $translations{$masterpage}{$lang}=$page unless exists $translations{$masterpage}{$lang};
709 return (maybe_add_leading_slash($masterpage, $hasleadingslash), $lang);
717 if ( 1 < (my ($masterpage, $lang) = _istranslation($page))) {
726 if (1 < (my ($masterpage, $lang) = _istranslation($page))) {
729 return $config{po_master_language}{code};
732 sub islanguagecode ($) {
735 return $code =~ /^[a-z]{2}$/;
738 sub otherlanguage ($$) {
742 return masterpage($page) if $code eq $config{po_master_language}{code};
743 return masterpage($page) . '.' . $code;
746 sub otherlanguages ($) {
750 return \%ret unless istranslation($page) || istranslatable($page);
751 my $curlang=lang($page);
753 ($config{po_master_language}{code}, keys %{$config{po_slave_languages}}) {
754 next if $lang eq $curlang;
755 $ret{$lang}=otherlanguage($page, $lang);
761 my $masterfile=shift;
763 (my $name, my $dir, my $suffix) = fileparse($masterfile, qr/\.[^.]*/);
764 $dir='' if $dir eq './';
765 return File::Spec->catpath('', $dir, $name . ".pot");
769 my $masterfile=shift;
772 (my $name, my $dir, my $suffix) = fileparse($masterfile, qr/\.[^.]*/);
773 $dir='' if $dir eq './';
774 return File::Spec->catpath('', $dir, $name . "." . $lang . ".po");
778 my $masterfile=shift;
780 return map pofile($masterfile, $_), (keys %{$config{po_slave_languages}});
784 my $masterfile=shift;
786 my $potfile=potfile($masterfile);
787 my %options = ("markdown" => (pagetype($masterfile) eq 'mdwn') ? 1 : 0);
788 my $doc=Locale::Po4a::Chooser::new('text',%options);
789 $doc->{TT}{utf_mode} = 1;
790 $doc->{TT}{file_in_charset} = 'utf-8';
791 $doc->{TT}{file_out_charset} = 'utf-8';
792 $doc->read($masterfile);
793 # let's cheat a bit to force porefs option to be passed to
794 # Locale::Po4a::Po; this is undocument use of internal
795 # Locale::Po4a::TransTractor's data, compulsory since this module
796 # prevents us from using the porefs option.
797 $doc->{TT}{po_out}=Locale::Po4a::Po->new({ 'porefs' => 'none' });
798 $doc->{TT}{po_out}->set_charset('utf-8');
801 IkiWiki::prep_writefile(basename($potfile),dirname($potfile));
802 $doc->writepo($potfile);
805 sub refreshpofiles ($@) {
806 my $masterfile=shift;
809 my $potfile=potfile($masterfile);
811 error("po(refreshpofiles) ".sprintf(gettext("POT file (%s) does not exist"), $potfile));
814 foreach my $pofile (@pofiles) {
815 IkiWiki::prep_writefile(basename($pofile),dirname($pofile));
817 system("msgmerge", "-q", "-U", "--backup=none", $pofile, $potfile) == 0
818 or error("po(refreshpofiles) ".
819 sprintf(gettext("failed to update %s"),
823 File::Copy::syscopy($potfile,$pofile)
824 or error("po(refreshpofiles) ".
825 sprintf(gettext("failed to copy the POT file to %s"),
831 sub buildtranslationscache() {
832 # use istranslation's side-effect
833 map istranslation($_), (keys %pagesources);
836 sub resettranslationscache() {
840 sub flushmemoizecache() {
841 Memoize::flush_cache("istranslatable");
842 Memoize::flush_cache("_istranslation");
843 Memoize::flush_cache("percenttranslated");
846 sub urlto_with_orig_beautiful_urlpath($$) {
850 inject(name => "IkiWiki::beautify_urlpath", call => $origsubs{'beautify_urlpath'});
851 my $res=urlto($to, $from);
852 inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath);
857 sub percenttranslated ($) {
861 return gettext("N/A") unless istranslation($page);
862 my $file=srcfile($pagesources{$page});
863 my $masterfile = srcfile($pagesources{masterpage($page)});
865 "markdown" => (pagetype($masterfile) eq 'mdwn') ? 1 : 0,
867 my $doc=Locale::Po4a::Chooser::new('text',%options);
869 'po_in_name' => [ $file ],
870 'file_in_name' => [ $masterfile ],
871 'file_in_charset' => 'utf-8',
872 'file_out_charset' => 'utf-8',
873 ) or error("po(percenttranslated) ".
874 sprintf(gettext("failed to translate %s"), $page));
875 my ($percent,$hit,$queries) = $doc->stats();
876 $percent =~ s/\.[0-9]+$//;
880 sub languagename ($) {
883 return $config{po_master_language}{name}
884 if $code eq $config{po_master_language}{code};
885 return $config{po_slave_languages}{$code}
886 if defined $config{po_slave_languages}{$code};
890 sub otherlanguagesloop ($) {
894 my %otherpages=%{otherlanguages($page)};
895 while (my ($lang, $otherpage) = each %otherpages) {
896 if (istranslation($page) && masterpage($page) eq $otherpage) {
898 url => urlto_with_orig_beautiful_urlpath($otherpage, $page),
900 language => languagename($lang),
906 url => urlto_with_orig_beautiful_urlpath($otherpage, $page),
908 language => languagename($lang),
909 percent => percenttranslated($otherpage),
914 return -1 if $a->{code} eq $config{po_master_language}{code};
915 return 1 if $b->{code} eq $config{po_master_language}{code};
916 return $a->{language} cmp $b->{language};
920 sub homepageurl (;$) {
923 return urlto('', $page);
926 sub deletetranslations ($) {
927 my $deletedmasterfile=shift;
929 my $deletedmasterpage=pagename($deletedmasterfile);
932 my $file = newpagefile($deletedmasterpage.'.'.$_, 'po');
933 my $absfile = "$config{srcdir}/$file";
934 if (-e $absfile && ! -l $absfile && ! -d $absfile) {
935 push @todelete, $file;
937 } keys %{$config{po_slave_languages}};
941 IkiWiki::rcs_remove($_);
944 IkiWiki::prune("$config{srcdir}/$_");
950 gettext("removed obsolete PO files"),
951 "IkiWiki::Plugin::po::deletetranslations");
955 sub commit_and_refresh ($$) {
956 my ($msg, $author) = (shift, shift);
959 IkiWiki::disable_commit_hook();
960 IkiWiki::rcs_commit_staged($msg, $author, "127.0.0.1");
961 IkiWiki::enable_commit_hook();
962 IkiWiki::rcs_update();
964 # Reinitialize module's private variables.
965 resetalreadyfiltered();
966 resettranslationscache();
968 # Trigger a wiki refresh.
969 require IkiWiki::Render;
970 # without preliminary saveindex/loadindex, refresh()
971 # complains about a lot of uninitialized variables
972 IkiWiki::saveindex();
973 IkiWiki::loadindex();
975 IkiWiki::saveindex();
978 # on success, returns the filtered content.
979 # on error, if $nonfatal, warn and return undef; else, error out.
980 sub po_to_markup ($$;$) {
981 my ($page, $content) = (shift, shift);
982 my $nonfatal = shift;
984 $content = '' unless defined $content;
985 $content = decode_utf8(encode_utf8($content));
986 # CRLF line terminators make poor Locale::Po4a feel bad
987 $content=~s/\r\n/\n/g;
989 # There are incompatibilities between some File::Temp versions
990 # (including 0.18, bundled with Lenny's perl-modules package)
991 # and others (e.g. 0.20, previously present in the archive as
992 # a standalone package): under certain circumstances, some
993 # return a relative filename, whereas others return an absolute one;
994 # we here use this module in a way that is at least compatible
995 # with 0.18 and 0.20. Beware, hit'n'run refactorers!
996 my $infile = new File::Temp(TEMPLATE => "ikiwiki-po-filter-in.XXXXXXXXXX",
997 DIR => File::Spec->tmpdir,
998 UNLINK => 1)->filename;
999 my $outfile = new File::Temp(TEMPLATE => "ikiwiki-po-filter-out.XXXXXXXXXX",
1000 DIR => File::Spec->tmpdir,
1001 UNLINK => 1)->filename;
1003 my $fail = sub ($) {
1004 my $msg = "po(po_to_markup) - $page : " . shift;
1009 error($msg, sub { unlink $infile, $outfile});
1012 writefile(basename($infile), File::Spec->tmpdir, $content)
1013 or return $fail->(sprintf(gettext("failed to write %s"), $infile));
1015 my $masterfile = srcfile($pagesources{masterpage($page)});
1017 "markdown" => (pagetype($masterfile) eq 'mdwn') ? 1 : 0,
1019 my $doc=Locale::Po4a::Chooser::new('text',%options);
1021 'po_in_name' => [ $infile ],
1022 'file_in_name' => [ $masterfile ],
1023 'file_in_charset' => 'utf-8',
1024 'file_out_charset' => 'utf-8',
1025 ) or return $fail->(gettext("failed to translate"));
1026 $doc->write($outfile)
1027 or return $fail->(sprintf(gettext("failed to write %s"), $outfile));
1029 $content = readfile($outfile)
1030 or return $fail->(sprintf(gettext("failed to read %s"), $outfile));
1032 # Unlinking should happen automatically, thanks to File::Temp,
1033 # but it does not work here, probably because of the way writefile()
1034 # and Locale::Po4a::write() work.
1035 unlink $infile, $outfile;
1040 # returns a SuccessReason or FailReason object
1042 my $content = shift;
1044 # NB: we don't use po_to_markup here, since Po4a parser does
1045 # not mind invalid PO content
1046 $content = '' unless defined $content;
1047 $content = decode_utf8(encode_utf8($content));
1049 # There are incompatibilities between some File::Temp versions
1050 # (including 0.18, bundled with Lenny's perl-modules package)
1051 # and others (e.g. 0.20, previously present in the archive as
1052 # a standalone package): under certain circumstances, some
1053 # return a relative filename, whereas others return an absolute one;
1054 # we here use this module in a way that is at least compatible
1055 # with 0.18 and 0.20. Beware, hit'n'run refactorers!
1056 my $infile = new File::Temp(TEMPLATE => "ikiwiki-po-isvalidpo.XXXXXXXXXX",
1057 DIR => File::Spec->tmpdir,
1058 UNLINK => 1)->filename;
1060 my $fail = sub ($) {
1061 my $msg = '[po/isvalidpo] ' . shift;
1063 return IkiWiki::FailReason->new("$msg");
1066 writefile(basename($infile), File::Spec->tmpdir, $content)
1067 or return $fail->(sprintf(gettext("failed to write %s"), $infile));
1069 my $res = (system("msgfmt", "--check", $infile, "-o", "/dev/null") == 0);
1071 # Unlinking should happen automatically, thanks to File::Temp,
1072 # but it does not work here, probably because of the way writefile()
1073 # and Locale::Po4a::write() work.
1077 return IkiWiki::SuccessReason->new("valid gettext data");
1079 return IkiWiki::FailReason->new("invalid gettext data, go back ".
1080 "to previous page to go on with edit");
1087 package IkiWiki::PageSpec;
1089 sub match_istranslation ($;@) {
1092 if (IkiWiki::Plugin::po::istranslation($page)) {
1093 return IkiWiki::SuccessReason->new("is a translation page");
1096 return IkiWiki::FailReason->new("is not a translation page");
1100 sub match_istranslatable ($;@) {
1103 if (IkiWiki::Plugin::po::istranslatable($page)) {
1104 return IkiWiki::SuccessReason->new("is set as translatable in po_translatable_pages");
1107 return IkiWiki::FailReason->new("is not set as translatable in po_translatable_pages");
1111 sub match_lang ($$;@) {
1115 my $regexp=IkiWiki::glob2re($wanted);
1116 my $lang=IkiWiki::Plugin::po::lang($page);
1117 if ($lang !~ /^$regexp$/i) {
1118 return IkiWiki::FailReason->new("file language is $lang, not $wanted");
1121 return IkiWiki::SuccessReason->new("file language is $wanted");
1125 sub match_currentlang ($$;@) {
1130 return IkiWiki::FailReason->new("no location provided") unless exists $params{location};
1132 my $currentlang=IkiWiki::Plugin::po::lang($params{location});
1133 my $lang=IkiWiki::Plugin::po::lang($page);
1135 if ($lang eq $currentlang) {
1136 return IkiWiki::SuccessReason->new("file language is the same as current one, i.e. $currentlang");
1139 return IkiWiki::FailReason->new("file language is $lang, whereas current language is $currentlang");