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;
14 eval 'use Locale::Po4a::Common qw(nowrapi18n)';
16 warning(sprintf(gettext('%s is too old, can not disable %s; '.
17 'a denial of service can thus be '.
18 'triggered by malicious content'),
19 'Locale::Po4a', 'Text::WrapI18N'));
20 eval 'use Locale::Po4a::Common';
23 use Locale::Po4a::Chooser;
36 memoize("istranslatable");
37 memoize("_istranslation");
38 memoize("percenttranslated");
41 hook(type => "getsetup", id => "po", call => \&getsetup);
42 hook(type => "checkconfig", id => "po", call => \&checkconfig);
43 hook(type => "needsbuild", id => "po", call => \&needsbuild);
44 hook(type => "scan", id => "po", call => \&scan, last =>1);
45 hook(type => "filter", id => "po", call => \&filter);
46 hook(type => "htmlize", id => "po", call => \&htmlize);
47 hook(type => "pagetemplate", id => "po", call => \&pagetemplate, last => 1);
48 hook(type => "postscan", id => "po", call => \&postscan);
49 hook(type => "rename", id => "po", call => \&renamepages, first => 1);
50 hook(type => "delete", id => "po", call => \&mydelete);
51 hook(type => "change", id => "po", call => \&change);
52 hook(type => "checkcontent", id => "po", call => \&checkcontent);
53 hook(type => "canremove", id => "po", call => \&canremove);
54 hook(type => "canrename", id => "po", call => \&canrename);
55 hook(type => "editcontent", id => "po", call => \&editcontent);
56 hook(type => "formbuilder_setup", id => "po", call => \&formbuilder_setup, last => 1);
57 hook(type => "formbuilder", id => "po", call => \&formbuilder);
59 $origsubs{'bestlink'}=\&IkiWiki::bestlink;
60 inject(name => "IkiWiki::bestlink", call => \&mybestlink);
61 $origsubs{'beautify_urlpath'}=\&IkiWiki::beautify_urlpath;
62 inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath);
63 $origsubs{'targetpage'}=\&IkiWiki::targetpage;
64 inject(name => "IkiWiki::targetpage", call => \&mytargetpage);
65 $origsubs{'urlto'}=\&IkiWiki::urlto;
66 inject(name => "IkiWiki::urlto", call => \&myurlto);
67 $origsubs{'nicepagetitle'}=\&IkiWiki::nicepagetitle;
68 inject(name => "IkiWiki::nicepagetitle", call => \&mynicepagetitle);
69 $origsubs{'cgiurl'}=\&IkiWiki::cgiurl;
70 inject(name => "IkiWiki::cgiurl", call => \&mycgiurl);
79 # 2. Injected functions
80 # 3. Blackboxes for private data
95 po_master_language => {
101 description => "master language (non-PO files)",
105 po_slave_languages => {
109 'es' => 'Castellano',
112 description => "slave languages (PO files)",
116 po_translatable_pages => {
118 example => "!*/Discussion",
119 description => "PageSpec controlling which pages are translatable",
120 link => "ikiwiki/PageSpec",
126 example => "current",
127 description => "internal linking behavior (default/current/negotiated)",
131 po_translation_status_in_links => {
134 description => "display translation status in links to translations",
141 foreach my $field (qw{po_master_language po_slave_languages}) {
142 if (! exists $config{$field} || ! defined $config{$field}) {
143 error(sprintf(gettext("Must specify %s when using the %s plugin"),
147 if (! (keys %{$config{po_slave_languages}})) {
148 error(gettext("At least one slave language must be defined ".
149 "in po_slave_languages when using the po plugin"));
153 or error(sprintf(gettext("%s is not a valid language code"), $_));
154 } ($config{po_master_language}{code}, keys %{$config{po_slave_languages}});
155 if (! exists $config{po_translatable_pages} ||
156 ! defined $config{po_translatable_pages}) {
157 $config{po_translatable_pages}="";
159 if (! exists $config{po_link_to} ||
160 ! defined $config{po_link_to}) {
161 $config{po_link_to}='default';
164 $config{po_link_to} eq $_
165 } ('default', 'current', 'negotiated')) {
166 warn(sprintf(gettext('%s is not a valid value for po_link_to, falling back to po_link_to=default'),
167 $config{po_link_to}));
168 $config{po_link_to}='default';
170 elsif ($config{po_link_to} eq "negotiated" && ! $config{usedirs}) {
171 warn(gettext('po_link_to=negotiated requires usedirs to be enabled, falling back to po_link_to=default'));
172 $config{po_link_to}='default';
174 if (! exists $config{po_translation_status_in_links} ||
175 ! defined $config{po_translation_status_in_links}) {
176 $config{po_translation_status_in_links}=1;
178 push @{$config{wiki_file_prune_regexps}}, qr/\.pot$/;
182 my $needsbuild=shift;
184 # backup @needsbuild content so that change() can know whether
185 # a given master page was rendered because its source file was changed
186 @origneedsbuild=(@$needsbuild);
189 buildtranslationscache();
191 # make existing translations depend on the corresponding master page
192 foreach my $master (keys %translations) {
193 map add_depends($_, $master), values %{otherlanguages($master)};
197 # Massage the recorded state of internal links so that:
198 # - it matches the actually generated links, rather than the links as written
199 # in the pages' source
200 # - backlinks are consistent in all cases
203 my $page=$params{page};
204 my $content=$params{content};
206 return unless UNIVERSAL::can("IkiWiki::Plugin::link", "import");
208 if (istranslation($page)) {
209 foreach my $destpage (@{$links{$page}}) {
210 if (istranslatable($destpage)) {
211 # replace one occurence of $destpage in $links{$page}
212 # (we only want to replace the one that was added by
213 # IkiWiki::Plugin::link::scan, other occurences may be
214 # there for other reasons)
215 for (my $i=0; $i<@{$links{$page}}; $i++) {
216 if (@{$links{$page}}[$i] eq $destpage) {
217 @{$links{$page}}[$i] = $destpage . '.' . lang($page);
224 elsif (! istranslatable($page) && ! istranslation($page)) {
225 foreach my $destpage (@{$links{$page}}) {
226 if (istranslatable($destpage)) {
227 # make sure any destpage's translations has
228 # $page in its backlinks
229 push @{$links{$page}},
230 values %{otherlanguages($destpage)};
236 # We use filter to convert PO to the master page's format,
237 # since the rest of ikiwiki should not work on PO files.
241 my $page = $params{page};
242 my $destpage = $params{destpage};
243 my $content = $params{content};
244 if (istranslation($page) && ! alreadyfiltered($page, $destpage)) {
245 $content = po_to_markup($page, $content);
246 setalreadyfiltered($page, $destpage);
254 my $page = $params{page};
255 my $content = $params{content};
257 # ignore PO files this plugin did not create
258 return $content unless istranslation($page);
260 # force content to be htmlize'd as if it was the same type as the master page
261 return IkiWiki::htmlize($page, $page,
262 pagetype(srcfile($pagesources{masterpage($page)})),
266 sub pagetemplate (@) {
268 my $page=$params{page};
269 my $destpage=$params{destpage};
270 my $template=$params{template};
272 my ($masterpage, $lang) = istranslation($page);
274 if (istranslation($page) && $template->query(name => "percenttranslated")) {
275 $template->param(percenttranslated => percenttranslated($page));
277 if ($template->query(name => "istranslation")) {
278 $template->param(istranslation => istranslation($page));
280 if ($template->query(name => "istranslatable")) {
281 $template->param(istranslatable => istranslatable($page));
283 if ($template->query(name => "HOMEPAGEURL")) {
284 $template->param(homepageurl => homepageurl($page));
286 if ($template->query(name => "otherlanguages")) {
287 $template->param(otherlanguages => [otherlanguagesloop($page)]);
288 map add_depends($page, $_), (values %{otherlanguages($page)});
290 # Rely on IkiWiki::Render's genpage() to decide wether
291 # a discussion link should appear on $page; this is not
292 # totally accurate, though: some broken links may be generated
293 # when cgiurl is disabled.
294 # This compromise avoids some code duplication, and will probably
295 # prevent future breakage when ikiwiki internals change.
296 # Known limitations are preferred to future random bugs.
297 if ($template->param('discussionlink') && istranslation($page)) {
298 $template->param('discussionlink' => htmllink(
301 $masterpage . '/' . gettext("Discussion"),
304 linktext => gettext("Discussion"),
307 # Remove broken parentlink to ./index.html on home page's translations.
308 # It works because this hook has the "last" parameter set, to ensure it
309 # runs after parentlinks' own pagetemplate hook.
310 if ($template->param('parentlinks')
311 && istranslation($page)
312 && $masterpage eq "index") {
313 $template->param('parentlinks' => []);
319 my $page = $params{page};
321 # backlinks involve back-dependencies, so that nicepagetitle effects,
322 # such as translation status displayed in links, are updated
324 map add_depends($page, $_), keys %{$IkiWiki::backlinks{$page}};
327 # Add the renamed page translations to the list of to-be-renamed pages.
328 sub renamepages($$$) {
329 my ($torename, $cgi, $session) = (shift, shift, shift);
331 # copy the initial array, so that we can iterate on it AND
332 # modify it at the same time, without iterating on the items we
333 # pushed on it ourselves
334 my @torename=@{$torename};
336 # Save the page(s) the user asked to rename, so that our
337 # canrename hook can tell the difference between:
338 # - a translation being renamed as a consequence of its master page
340 # - a user trying to directly rename a translation
341 # This is why this hook has to be run first, before @torename is modified
343 $session->param(po_orig_torename => [ @torename ]);
344 IkiWiki::cgi_savesession($session);
346 foreach my $rename (@torename) {
347 next unless istranslatable($rename->{src});
348 my %otherpages=%{otherlanguages($rename->{src})};
349 while (my ($lang, $otherpage) = each %otherpages) {
352 srcfile => $pagesources{$otherpage},
353 dest => otherlanguage($rename->{dest}, $lang),
354 destfile => $rename->{dest}.".".$lang.".po",
364 map { deletetranslations($_) } grep istranslatablefile($_), @deleted;
370 # All meta titles are first extracted at scan time, i.e. before we turn
371 # PO files back into translated markdown; escaping of double-quotes in
372 # PO files breaks the meta plugin's parsing enough to save ugly titles
373 # to %pagestate at this time.
375 # Then, at render time, every page's passes on row through the Great
376 # Rendering Chain (filter->preprocess->linkify->htmlize), and the meta
377 # plugin's preprocess hook is this time in a position to correctly
378 # extract the titles from slave pages.
380 # This is, unfortunately, too late: if the page A, linking to the page B,
381 # is rendered before B, it will display the wrongly-extracted meta title
382 # as the link text to B.
384 # On the one hand, such a corner case only happens on rebuild: on
385 # refresh, every rendered page is fixed to contain correct meta titles.
386 # On the other hand, it can take some time to get every page fixed.
387 # We therefore re-render every rendered page after a rebuild to fix them
388 # at once. As this more or less doubles the time needed to rebuild the
389 # wiki, we do so only when really needed.
392 && exists $config{rebuild} && defined $config{rebuild} && $config{rebuild}
393 && UNIVERSAL::can("IkiWiki::Plugin::meta", "getsetup")
394 && exists $config{meta_overrides_page_title}
395 && defined $config{meta_overrides_page_title}
396 && $config{meta_overrides_page_title}) {
397 debug(sprintf(gettext("re-rendering all pages to fix meta titles")));
398 resetalreadyfiltered();
399 require IkiWiki::Render;
400 foreach my $file (@rendered) {
401 debug(sprintf(gettext("rendering %s"), $file));
402 IkiWiki::render($file);
406 my $updated_po_files=0;
408 # Refresh/create POT and PO files as needed.
409 foreach my $file (grep {istranslatablefile($_)} @rendered) {
410 my $page=pagename($file);
411 my $masterfile=srcfile($file);
412 my $updated_pot_file=0;
413 # Only refresh Pot file if it does not exist, or if
414 # $pagesources{$page} was changed: don't if only the HTML was
415 # refreshed, e.g. because of a dependency.
416 if ((grep { $_ eq $pagesources{$page} } @origneedsbuild)
417 || ! -e potfile($masterfile)) {
418 refreshpot($masterfile);
423 push @pofiles, $_ if ($updated_pot_file || ! -e $_);
424 } (pofiles($masterfile));
426 refreshpofiles($masterfile, @pofiles);
427 map { IkiWiki::rcs_add($_) } @pofiles if $config{rcs};
432 if ($updated_po_files) {
434 gettext("updated PO files"),
435 "IkiWiki::Plugin::po::change");
439 sub checkcontent (@) {
442 if (istranslation($params{page})) {
443 my $res = isvalidpo($params{content});
454 sub canremove ($$$) {
455 my ($page, $cgi, $session) = (shift, shift, shift);
457 if (istranslation($page)) {
458 return gettext("Can not remove a translation. Removing the master page, ".
459 "though, removes its translations as well.");
464 sub canrename ($$@) {
465 my ($cgi, $session) = (shift, shift);
468 if (istranslation($params{src})) {
469 my $masterpage = masterpage($params{src});
470 # Tell the difference between:
471 # - a translation being renamed as a consequence of its master page
472 # being renamed, which is allowed
473 # - a user trying to directly rename a translation, which is forbidden
474 # by looking for the master page in the list of to-be-renamed pages we
475 # saved early in the renaming process.
476 my $orig_torename = $session->param("po_orig_torename");
477 unless (grep { $_->{src} eq $masterpage } @{$orig_torename}) {
478 return gettext("Can not rename a translation. Renaming the master page, ".
479 "though, renames its translations as well.");
485 # As we're previewing or saving a page, the content may have
486 # changed, so tell the next filter() invocation it must not be lazy.
490 unsetalreadyfiltered($params{page}, $params{page});
491 return $params{content};
494 sub formbuilder_setup (@) {
496 my $form=$params{form};
499 return unless defined $form->field("do");
501 if ($form->field("do") eq "create") {
502 # Warn the user: new pages must be written in master language.
503 my $template=template("pocreatepage.tmpl");
504 $template->param(LANG => $config{po_master_language}{name});
505 $form->tmpl_param(message => $template->output);
507 elsif ($form->field("do") eq "edit") {
508 # Remove the rename/remove buttons on slave pages.
509 # This has to be done after the rename/remove plugins have added
510 # their buttons, which is why this hook must be run last.
511 # The canrename/canremove hooks already ensure this is forbidden
512 # at the backend level, so this is only UI sugar.
513 if (istranslation($form->field("page"))) {
515 for (my $i = 0; $i < @{$params{buttons}}; $i++) {
516 if (@{$params{buttons}}[$i] eq $_) {
517 delete @{$params{buttons}}[$i];
526 sub formbuilder (@) {
528 my $form=$params{form};
531 return unless defined $form->field("do");
533 # Do not allow to create pages of type po: they are automatically created.
534 # The main reason to do so is to bypass the "favor the type of linking page
535 # on page creation" logic, which is unsuitable when a broken link is clicked
536 # on a slave (PO) page.
537 # This cannot be done in the formbuilder_setup hook as the list of types is
539 if ($form->field("do") eq "create") {
540 foreach my $field ($form->field) {
541 next unless "$field" eq "type";
542 if ($field->type eq 'select') {
543 # remove po from the list of types
544 my @types = grep { $_ ne 'po' } $field->options;
545 $field->options(\@types) if @types;
548 # make sure the default value is not po;
549 # does this case actually happen?
550 debug "po(formbuilder) ".gettext("type field is not selected - not implemented yet");
557 # | Injected functions
560 # Implement po_link_to 'current' and 'negotiated' settings.
561 sub mybestlink ($$) {
565 my $res=$origsubs{'bestlink'}->(masterpage($page), $link);
567 && ($config{po_link_to} eq "current" || $config{po_link_to} eq "negotiated")
568 && istranslatable($res)
569 && istranslation($page)) {
570 return $res . "." . lang($page);
575 sub mybeautify_urlpath ($) {
578 my $res=$origsubs{'beautify_urlpath'}->($url);
579 if ($config{po_link_to} eq "negotiated") {
580 $res =~ s!/\Qindex.$config{po_master_language}{code}.$config{htmlext}\E$!/!;
581 $res =~ s!/\Qindex.$config{htmlext}\E$!/!;
583 $res =~ s!/\Qindex.$_.$config{htmlext}\E$!/!;
584 } (keys %{$config{po_slave_languages}});
589 sub mytargetpage ($$) {
593 if (istranslation($page) || istranslatable($page)) {
594 my ($masterpage, $lang) = (masterpage($page), lang($page));
595 if (! $config{usedirs} || $masterpage eq 'index') {
596 return $masterpage . "." . $lang . "." . $ext;
599 return $masterpage . "/index." . $lang . "." . $ext;
602 return $origsubs{'targetpage'}->($page, $ext);
610 # workaround hard-coded /index.$config{htmlext} in IkiWiki::urlto()
612 && $config{po_link_to} eq "current"
613 && istranslatable('index')) {
614 return IkiWiki::beautify_urlpath(IkiWiki::baseurl($from) . "index." . lang($from) . ".$config{htmlext}");
616 # avoid using our injected beautify_urlpath if run by cgi_editpage,
617 # so that one is redirected to the just-edited page rather than to the
618 # negociated translation; to prevent unnecessary fiddling with caller/inject,
619 # we only do so when our beautify_urlpath would actually do what we want to
620 # avoid, i.e. when po_link_to = negotiated
621 if ($config{po_link_to} eq "negotiated") {
622 my @caller = caller(1);
623 my $run_by_editpage = 0;
624 $run_by_editpage = 1 if (exists $caller[3] && defined $caller[3]
625 && $caller[3] eq "IkiWiki::cgi_editpage");
626 inject(name => "IkiWiki::beautify_urlpath", call => $origsubs{'beautify_urlpath'})
628 my $res = $origsubs{'urlto'}->($to,$from,$absolute);
629 inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath)
634 return $origsubs{'urlto'}->($to,$from,$absolute)
638 sub mynicepagetitle ($;$) {
639 my ($page, $unescaped) = (shift, shift);
641 my $res = $origsubs{'nicepagetitle'}->($page, $unescaped);
642 return $res unless istranslation($page);
643 return $res unless $config{po_translation_status_in_links};
644 my @caller = caller(1);
645 return $res if (exists $caller[3] && defined $caller[3]
646 && $caller[3] eq "IkiWiki::Plugin::parentlinks::parentlinks");
647 return $res.' ('.percenttranslated($page).' %)';
653 # slave pages have no subpages
654 if (istranslation($params{'from'})) {
655 $params{'from'} = masterpage($params{'from'});
657 return $origsubs{'cgiurl'}->(%params);
661 # | Blackboxes for private data
667 sub alreadyfiltered($$) {
671 return ( exists $filtered{$page}{$destpage}
672 && $filtered{$page}{$destpage} eq 1 );
675 sub setalreadyfiltered($$) {
679 $filtered{$page}{$destpage}=1;
682 sub unsetalreadyfiltered($$) {
686 if (exists $filtered{$page}{$destpage}) {
687 delete $filtered{$page}{$destpage};
691 sub resetalreadyfiltered() {
700 sub maybe_add_leading_slash ($;$) {
703 $add=1 unless defined $add;
704 return '/' . $str if $add;
708 sub istranslatablefile ($) {
711 return 0 unless defined $file;
712 return 0 if defined pagetype($file) && pagetype($file) eq 'po';
713 return 0 if $file =~ /\.pot$/;
714 return 0 unless -e "$config{srcdir}/$file"; # underlay dirs may be read-only
715 return 1 if pagespec_match(pagename($file), $config{po_translatable_pages});
719 sub istranslatable ($) {
723 return 1 if istranslatablefile($pagesources{$page});
727 sub _istranslation ($) {
730 $page='' unless defined $page && length $page;
731 my $hasleadingslash = ($page=~s#^/##);
732 my $file=$pagesources{$page};
733 return 0 unless defined $file
734 && defined pagetype($file)
735 && pagetype($file) eq 'po';
736 return 0 if $file =~ /\.pot$/;
738 my ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
739 return 0 unless defined $masterpage && defined $lang
740 && length $masterpage && length $lang
741 && defined $pagesources{$masterpage}
742 && defined $config{po_slave_languages}{$lang};
744 return (maybe_add_leading_slash($masterpage, $hasleadingslash), $lang)
745 if istranslatable($masterpage);
748 sub istranslation ($) {
751 if (1 < (my ($masterpage, $lang) = _istranslation($page))) {
752 my $hasleadingslash = ($masterpage=~s#^/##);
753 $translations{$masterpage}{$lang}=$page unless exists $translations{$masterpage}{$lang};
754 return (maybe_add_leading_slash($masterpage, $hasleadingslash), $lang);
762 if ( 1 < (my ($masterpage, $lang) = _istranslation($page))) {
771 if (1 < (my ($masterpage, $lang) = _istranslation($page))) {
774 return $config{po_master_language}{code};
777 sub islanguagecode ($) {
780 return ($code =~ /^[a-z]{2}$/);
783 sub otherlanguage ($$) {
787 return masterpage($page) if $code eq $config{po_master_language}{code};
788 return masterpage($page) . '.' . $code;
791 sub otherlanguages ($) {
795 return \%ret unless istranslation($page) || istranslatable($page);
796 my $curlang=lang($page);
798 ($config{po_master_language}{code}, keys %{$config{po_slave_languages}}) {
799 next if $lang eq $curlang;
800 $ret{$lang}=otherlanguage($page, $lang);
806 my $masterfile=shift;
808 (my $name, my $dir, my $suffix) = fileparse($masterfile, qr/\.[^.]*/);
809 $dir='' if $dir eq './';
810 return File::Spec->catpath('', $dir, $name . ".pot");
814 my $masterfile=shift;
817 (my $name, my $dir, my $suffix) = fileparse($masterfile, qr/\.[^.]*/);
818 $dir='' if $dir eq './';
819 return File::Spec->catpath('', $dir, $name . "." . $lang . ".po");
823 my $masterfile=shift;
825 return map pofile($masterfile, $_), (keys %{$config{po_slave_languages}});
829 my $masterfile=shift;
831 my $potfile=potfile($masterfile);
832 my %options = ("markdown" => (pagetype($masterfile) eq 'mdwn') ? 1 : 0);
833 my $doc=Locale::Po4a::Chooser::new('text',%options);
834 $doc->{TT}{utf_mode} = 1;
835 $doc->{TT}{file_in_charset} = 'utf-8';
836 $doc->{TT}{file_out_charset} = 'utf-8';
837 $doc->read($masterfile);
838 # let's cheat a bit to force porefs option to be passed to Locale::Po4a::Po;
839 # this is undocument use of internal Locale::Po4a::TransTractor's data,
840 # compulsory since this module prevents us from using the porefs option.
841 $doc->{TT}{po_out}=Locale::Po4a::Po->new({ 'porefs' => 'none' });
842 $doc->{TT}{po_out}->set_charset('utf-8');
845 IkiWiki::prep_writefile(basename($potfile),dirname($potfile));
846 $doc->writepo($potfile);
849 sub refreshpofiles ($@) {
850 my $masterfile=shift;
853 my $potfile=potfile($masterfile);
855 error("po(refreshpofiles) ".sprintf(gettext("POT file (%s) does not exist"), $potfile));
858 foreach my $pofile (@pofiles) {
859 IkiWiki::prep_writefile(basename($pofile),dirname($pofile));
861 system("msgmerge", "-U", "--backup=none", $pofile, $potfile) == 0
862 or error("po(refreshpofiles) ".
863 sprintf(gettext("failed to update %s"),
867 File::Copy::syscopy($potfile,$pofile)
868 or error("po(refreshpofiles) ".
869 sprintf(gettext("failed to copy the POT file to %s"),
875 sub buildtranslationscache() {
876 # use istranslation's side-effect
877 map istranslation($_), (keys %pagesources);
880 sub resettranslationscache() {
884 sub flushmemoizecache() {
885 Memoize::flush_cache("istranslatable");
886 Memoize::flush_cache("_istranslation");
887 Memoize::flush_cache("percenttranslated");
890 sub urlto_with_orig_beautiful_urlpath($$) {
894 inject(name => "IkiWiki::beautify_urlpath", call => $origsubs{'beautify_urlpath'});
895 my $res=urlto($to, $from);
896 inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath);
901 sub percenttranslated ($) {
905 return gettext("N/A") unless istranslation($page);
906 my $file=srcfile($pagesources{$page});
907 my $masterfile = srcfile($pagesources{masterpage($page)});
909 "markdown" => (pagetype($masterfile) eq 'mdwn') ? 1 : 0,
911 my $doc=Locale::Po4a::Chooser::new('text',%options);
913 'po_in_name' => [ $file ],
914 'file_in_name' => [ $masterfile ],
915 'file_in_charset' => 'utf-8',
916 'file_out_charset' => 'utf-8',
917 ) or error("po(percenttranslated) ".
918 sprintf(gettext("failed to translate %s"), $page));
919 my ($percent,$hit,$queries) = $doc->stats();
920 $percent =~ s/\.[0-9]+$//;
924 sub languagename ($) {
927 return $config{po_master_language}{name}
928 if $code eq $config{po_master_language}{code};
929 return $config{po_slave_languages}{$code}
930 if defined $config{po_slave_languages}{$code};
934 sub otherlanguagesloop ($) {
938 my %otherpages=%{otherlanguages($page)};
939 while (my ($lang, $otherpage) = each %otherpages) {
940 if (istranslation($page) && masterpage($page) eq $otherpage) {
942 url => urlto_with_orig_beautiful_urlpath($otherpage, $page),
944 language => languagename($lang),
950 url => urlto_with_orig_beautiful_urlpath($otherpage, $page),
952 language => languagename($lang),
953 percent => percenttranslated($otherpage),
958 return -1 if $a->{code} eq $config{po_master_language}{code};
959 return 1 if $b->{code} eq $config{po_master_language}{code};
960 return $a->{language} cmp $b->{language};
964 sub homepageurl (;$) {
967 return urlto('', $page);
970 sub deletetranslations ($) {
971 my $deletedmasterfile=shift;
973 my $deletedmasterpage=pagename($deletedmasterfile);
976 my $file = newpagefile($deletedmasterpage.'.'.$_, 'po');
977 my $absfile = "$config{srcdir}/$file";
978 if (-e $absfile && ! -l $absfile && ! -d $absfile) {
979 push @todelete, $file;
981 } keys %{$config{po_slave_languages}};
985 IkiWiki::rcs_remove($_);
988 IkiWiki::prune("$config{srcdir}/$_");
994 gettext("removed obsolete PO files"),
995 "IkiWiki::Plugin::po::deletetranslations");
999 sub commit_and_refresh ($$) {
1000 my ($msg, $author) = (shift, shift);
1003 IkiWiki::disable_commit_hook();
1004 IkiWiki::rcs_commit_staged($msg, $author, "127.0.0.1");
1005 IkiWiki::enable_commit_hook();
1006 IkiWiki::rcs_update();
1008 # Reinitialize module's private variables.
1009 resetalreadyfiltered();
1010 resettranslationscache();
1011 flushmemoizecache();
1012 # Trigger a wiki refresh.
1013 require IkiWiki::Render;
1014 # without preliminary saveindex/loadindex, refresh()
1015 # complains about a lot of uninitialized variables
1016 IkiWiki::saveindex();
1017 IkiWiki::loadindex();
1019 IkiWiki::saveindex();
1022 # on success, returns the filtered content.
1023 # on error, if $nonfatal, warn and return undef; else, error out.
1024 sub po_to_markup ($$;$) {
1025 my ($page, $content) = (shift, shift);
1026 my $nonfatal = shift;
1028 $content = '' unless defined $content;
1029 $content = decode_utf8(encode_utf8($content));
1030 # CRLF line terminators make poor Locale::Po4a feel bad
1031 $content=~s/\r\n/\n/g;
1033 # There are incompatibilities between some File::Temp versions
1034 # (including 0.18, bundled with Lenny's perl-modules package)
1035 # and others (e.g. 0.20, previously present in the archive as
1036 # a standalone package): under certain circumstances, some
1037 # return a relative filename, whereas others return an absolute one;
1038 # we here use this module in a way that is at least compatible
1039 # with 0.18 and 0.20. Beware, hit'n'run refactorers!
1040 my $infile = new File::Temp(TEMPLATE => "ikiwiki-po-filter-in.XXXXXXXXXX",
1041 DIR => File::Spec->tmpdir,
1042 UNLINK => 1)->filename;
1043 my $outfile = new File::Temp(TEMPLATE => "ikiwiki-po-filter-out.XXXXXXXXXX",
1044 DIR => File::Spec->tmpdir,
1045 UNLINK => 1)->filename;
1047 my $fail = sub ($) {
1048 my $msg = "po(po_to_markup) - $page : " . shift;
1053 error($msg, sub { unlink $infile, $outfile});
1056 writefile(basename($infile), File::Spec->tmpdir, $content)
1057 or return $fail->(sprintf(gettext("failed to write %s"), $infile));
1059 my $masterfile = srcfile($pagesources{masterpage($page)});
1061 "markdown" => (pagetype($masterfile) eq 'mdwn') ? 1 : 0,
1063 my $doc=Locale::Po4a::Chooser::new('text',%options);
1065 'po_in_name' => [ $infile ],
1066 'file_in_name' => [ $masterfile ],
1067 'file_in_charset' => 'utf-8',
1068 'file_out_charset' => 'utf-8',
1069 ) or return $fail->(gettext("failed to translate"));
1070 $doc->write($outfile)
1071 or return $fail->(sprintf(gettext("failed to write %s"), $outfile));
1073 $content = readfile($outfile)
1074 or return $fail->(sprintf(gettext("failed to read %s"), $outfile));
1076 # Unlinking should happen automatically, thanks to File::Temp,
1077 # but it does not work here, probably because of the way writefile()
1078 # and Locale::Po4a::write() work.
1079 unlink $infile, $outfile;
1084 # returns a SuccessReason or FailReason object
1086 my $content = shift;
1088 # NB: we don't use po_to_markup here, since Po4a parser does
1089 # not mind invalid PO content
1090 $content = '' unless defined $content;
1091 $content = decode_utf8(encode_utf8($content));
1093 # There are incompatibilities between some File::Temp versions
1094 # (including 0.18, bundled with Lenny's perl-modules package)
1095 # and others (e.g. 0.20, previously present in the archive as
1096 # a standalone package): under certain circumstances, some
1097 # return a relative filename, whereas others return an absolute one;
1098 # we here use this module in a way that is at least compatible
1099 # with 0.18 and 0.20. Beware, hit'n'run refactorers!
1100 my $infile = new File::Temp(TEMPLATE => "ikiwiki-po-isvalidpo.XXXXXXXXXX",
1101 DIR => File::Spec->tmpdir,
1102 UNLINK => 1)->filename;
1104 my $fail = sub ($) {
1105 my $msg = '[po/isvalidpo] ' . shift;
1107 return IkiWiki::FailReason->new("$msg");
1110 writefile(basename($infile), File::Spec->tmpdir, $content)
1111 or return $fail->(sprintf(gettext("failed to write %s"), $infile));
1113 my $res = (system("msgfmt", "--check", $infile, "-o", "/dev/null") == 0);
1115 # Unlinking should happen automatically, thanks to File::Temp,
1116 # but it does not work here, probably because of the way writefile()
1117 # and Locale::Po4a::write() work.
1121 return IkiWiki::SuccessReason->new("valid gettext data");
1123 return IkiWiki::FailReason->new("invalid gettext data, go back ".
1124 "to previous page to go on with edit");
1131 package IkiWiki::PageSpec;
1136 sub match_istranslation ($;@) {
1139 if (IkiWiki::Plugin::po::istranslation($page)) {
1140 return IkiWiki::SuccessReason->new("is a translation page");
1143 return IkiWiki::FailReason->new("is not a translation page");
1147 sub match_istranslatable ($;@) {
1150 if (IkiWiki::Plugin::po::istranslatable($page)) {
1151 return IkiWiki::SuccessReason->new("is set as translatable in po_translatable_pages");
1154 return IkiWiki::FailReason->new("is not set as translatable in po_translatable_pages");
1158 sub match_lang ($$;@) {
1162 my $regexp=IkiWiki::glob2re($wanted);
1163 my $lang=IkiWiki::Plugin::po::lang($page);
1164 if ($lang !~ /^$regexp$/i) {
1165 return IkiWiki::FailReason->new("file language is $lang, not $wanted");
1168 return IkiWiki::SuccessReason->new("file language is $wanted");
1172 sub match_currentlang ($$;@) {
1177 return IkiWiki::FailReason->new("no location provided") unless exists $params{location};
1179 my $currentlang=IkiWiki::Plugin::po::lang($params{location});
1180 my $lang=IkiWiki::Plugin::po::lang($page);
1182 if ($lang eq $currentlang) {
1183 return IkiWiki::SuccessReason->new("file language is the same as current one, i.e. $currentlang");
1186 return IkiWiki::FailReason->new("file language is $lang, whereas current language is $currentlang");