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 eval q{use Locale::Po4a::Common qw(nowrapi18n !/.*/)};
15 print STDERR gettext("warning: Old po4a detected! Recommend upgrade to 0.35.")."\n";
16 eval q{use Locale::Po4a::Common qw(!/.*/)};
19 use Locale::Po4a::Chooser;
32 memoize("istranslatable");
33 memoize("_istranslation");
34 memoize("percenttranslated");
37 hook(type => "getsetup", id => "po", call => \&getsetup);
38 hook(type => "checkconfig", id => "po", call => \&checkconfig);
39 hook(type => "needsbuild", id => "po", call => \&needsbuild);
40 hook(type => "scan", id => "po", call => \&scan, last => 1);
41 hook(type => "filter", id => "po", call => \&filter);
42 hook(type => "htmlize", id => "po", call => \&htmlize);
43 hook(type => "pagetemplate", id => "po", call => \&pagetemplate, last => 1);
44 hook(type => "rename", id => "po", call => \&renamepages, first => 1);
45 hook(type => "delete", id => "po", call => \&mydelete);
46 hook(type => "change", id => "po", call => \&change);
47 hook(type => "checkcontent", id => "po", call => \&checkcontent);
48 hook(type => "canremove", id => "po", call => \&canremove);
49 hook(type => "canrename", id => "po", call => \&canrename);
50 hook(type => "editcontent", id => "po", call => \&editcontent);
51 hook(type => "formbuilder_setup", id => "po", call => \&formbuilder_setup, last => 1);
52 hook(type => "formbuilder", id => "po", call => \&formbuilder);
55 $origsubs{'bestlink'}=\&IkiWiki::bestlink;
56 inject(name => "IkiWiki::bestlink", call => \&mybestlink);
57 $origsubs{'beautify_urlpath'}=\&IkiWiki::beautify_urlpath;
58 inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath);
59 $origsubs{'targetpage'}=\&IkiWiki::targetpage;
60 inject(name => "IkiWiki::targetpage", call => \&mytargetpage);
61 $origsubs{'urlto'}=\&IkiWiki::urlto;
62 inject(name => "IkiWiki::urlto", call => \&myurlto);
63 $origsubs{'cgiurl'}=\&IkiWiki::cgiurl;
64 inject(name => "IkiWiki::cgiurl", call => \&mycgiurl);
65 $origsubs{'rootpage'}=\&IkiWiki::rootpage;
66 inject(name => "IkiWiki::rootpage", call => \&myrootpage);
76 # 2. Injected functions
77 # 3. Blackboxes for private data
90 rebuild => 1, # format plugin
93 po_master_language => {
99 description => "master language (non-PO files)",
103 po_slave_languages => {
110 description => "slave languages (PO files)",
114 po_translatable_pages => {
116 example => "* and !*/Discussion",
117 description => "PageSpec controlling which pages are translatable",
118 link => "ikiwiki/PageSpec",
124 example => "current",
125 description => "internal linking behavior (default/current/negotiated)",
132 foreach my $field (qw{po_master_language}) {
133 if (! exists $config{$field} || ! defined $config{$field}) {
134 error(sprintf(gettext("Must specify %s when using the %s plugin"),
138 delete $config{po_slave_languages}{$config{po_master_language}{code}};;
142 or error(sprintf(gettext("%s is not a valid language code"), $_));
143 } ($config{po_master_language}{code}, keys %{$config{po_slave_languages}});
145 if (! exists $config{po_translatable_pages} ||
146 ! defined $config{po_translatable_pages}) {
147 $config{po_translatable_pages}="";
149 if (! exists $config{po_link_to} ||
150 ! defined $config{po_link_to}) {
151 $config{po_link_to}='default';
153 elsif ($config{po_link_to} !~ /^(default|current|negotiated)$/) {
154 warn(sprintf(gettext('%s is not a valid value for po_link_to, falling back to po_link_to=default'),
155 $config{po_link_to}));
156 $config{po_link_to}='default';
158 elsif ($config{po_link_to} eq "negotiated" && ! $config{usedirs}) {
159 warn(gettext('po_link_to=negotiated requires usedirs to be enabled, falling back to po_link_to=default'));
160 $config{po_link_to}='default';
163 push @{$config{wiki_file_prune_regexps}}, qr/\.pot$/;
165 # Translated versions of the underlays are added if available.
166 foreach my $underlay ("basewiki",
167 map { m/^\Q$config{underlaydirbase}\E\/*(.*)/ }
168 reverse @{$config{underlaydirs}}) {
169 next if $underlay=~/^locale\//;
171 # Underlays containing the po files for slave languages.
172 foreach my $ll (keys %{$config{po_slave_languages}}) {
173 add_underlay("po/$ll/$underlay")
174 if -d "$config{underlaydirbase}/po/$ll/$underlay";
177 if ($config{po_master_language}{code} ne 'en') {
178 # Add underlay containing translated source files
179 # for the master language.
180 add_underlay("locale/$config{po_master_language}{code}/$underlay")
181 if -d "$config{underlaydirbase}/locale/$config{po_master_language}{code}/$underlay";
187 my $needsbuild=shift;
189 # backup @needsbuild content so that change() can know whether
190 # a given master page was rendered because its source file was changed
191 @origneedsbuild=(@$needsbuild);
194 buildtranslationscache();
196 # make existing translations depend on the corresponding master page
197 foreach my $master (keys %translations) {
198 map add_depends($_, $master), values %{otherlanguages($master)};
202 # Massage the recorded state of internal links so that:
203 # - it matches the actually generated links, rather than the links as written
204 # in the pages' source
205 # - backlinks are consistent in all cases
208 my $page=$params{page};
209 my $content=$params{content};
211 if (istranslation($page)) {
212 foreach my $destpage (@{$links{$page}}) {
213 if (istranslatable($destpage)) {
214 # replace the occurence of $destpage in $links{$page}
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 => scalar 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 if ($config{discussion} && istranslation($page)) {
291 if ($page !~ /.*\/\Q$config{discussionpage}\E$/i &&
292 (length $config{cgiurl} ||
293 exists $links{$masterpage."/".lc($config{discussionpage})})) {
294 $template->param('discussionlink' => htmllink(
297 $masterpage . '/' . $config{discussionpage},
300 linktext => $config{discussionpage},
304 # Remove broken parentlink to ./index.html on home page's translations.
305 # It works because this hook has the "last" parameter set, to ensure it
306 # runs after parentlinks' own pagetemplate hook.
307 if ($template->param('parentlinks')
308 && istranslation($page)
309 && $masterpage eq "index") {
310 $template->param('parentlinks' => []);
312 if (ishomepage($page) && $template->query(name => "title")) {
313 $template->param(title => $config{wikiname});
317 # Add the renamed page translations to the list of to-be-renamed pages.
318 sub renamepages (@) {
321 my %torename = %{$params{torename}};
322 my $session = $params{session};
324 # Save the page(s) the user asked to rename, so that our
325 # canrename hook can tell the difference between:
326 # - a translation being renamed as a consequence of its master page
328 # - a user trying to directly rename a translation
329 # This is why this hook has to be run first, before the list of pages
330 # to rename is modified by other plugins.
332 @orig_torename=@{$session->param("po_orig_torename")}
333 if defined $session->param("po_orig_torename");
334 push @orig_torename, $torename{src};
335 $session->param(po_orig_torename => \@orig_torename);
336 IkiWiki::cgi_savesession($session);
338 return () unless istranslatable($torename{src});
341 my %otherpages=%{otherlanguages($torename{src})};
342 while (my ($lang, $otherpage) = each %otherpages) {
345 srcfile => $pagesources{$otherpage},
346 dest => otherlanguage($torename{dest}, $lang),
347 destfile => $torename{dest}.".".$lang.".po",
357 map { deletetranslations($_) } grep istranslatablefile($_), @deleted;
363 # All meta titles are first extracted at scan time, i.e. before we turn
364 # PO files back into translated markdown; escaping of double-quotes in
365 # PO files breaks the meta plugin's parsing enough to save ugly titles
366 # to %pagestate at this time.
368 # Then, at render time, every page passes in turn through the Great
369 # Rendering Chain (filter->preprocess->linkify->htmlize), and the meta
370 # plugin's preprocess hook is this time in a position to correctly
371 # extract the titles from slave pages.
373 # This is, unfortunately, too late: if the page A, linking to the page
374 # B, is rendered before B, it will display the wrongly-extracted meta
375 # title as the link text to B.
377 # On the one hand, such a corner case only happens on rebuild: on
378 # refresh, every rendered page is fixed to contain correct meta titles.
379 # On the other hand, it can take some time to get every page fixed.
380 # We therefore re-render every rendered page after a rebuild to fix them
381 # at once. As this more or less doubles the time needed to rebuild the
382 # wiki, we do so only when really needed.
385 && exists $config{rebuild} && defined $config{rebuild} && $config{rebuild}
386 && UNIVERSAL::can("IkiWiki::Plugin::meta", "getsetup")
387 && exists $config{meta_overrides_page_title}
388 && defined $config{meta_overrides_page_title}
389 && $config{meta_overrides_page_title}) {
390 debug(sprintf(gettext("rebuilding all pages to fix meta titles")));
391 resetalreadyfiltered();
392 require IkiWiki::Render;
393 foreach my $file (@rendered) {
394 IkiWiki::render($file, sprintf(gettext("building %s"), $file));
398 my $updated_po_files=0;
400 # Refresh/create POT and PO files as needed.
401 foreach my $file (grep {istranslatablefile($_)} @rendered) {
402 my $masterfile=srcfile($file);
403 my $page=pagename($file);
404 my $updated_pot_file=0;
406 # Avoid touching underlay files.
407 next if $masterfile ne "$config{srcdir}/$file";
409 # Only refresh POT file if it does not exist, or if
410 # the source was changed: don't if only the HTML was
411 # refreshed, e.g. because of a dependency.
412 if ((grep { $_ eq $pagesources{$page} } @origneedsbuild) ||
413 ! -e potfile($masterfile)) {
414 refreshpot($masterfile);
418 foreach my $po (pofiles($masterfile)) {
419 next if ! $updated_pot_file && -e $po;
420 next if grep { $po=~/\Q$_\E/ } @{$config{underlaydirs}};
424 refreshpofiles($masterfile, @pofiles);
425 map { s/^\Q$config{srcdir}\E\/*//; IkiWiki::rcs_add($_) } @pofiles if $config{rcs};
430 if ($updated_po_files) {
432 gettext("updated PO files"));
436 sub checkcontent (@) {
439 if (istranslation($params{page})) {
440 my $res = isvalidpo($params{content});
454 if (istranslation($params{page})) {
455 return gettext("Can not remove a translation. If the master page is removed, ".
456 "however, its translations will be removed as well.");
463 my $session = $params{session};
465 if (istranslation($params{src})) {
466 my $masterpage = masterpage($params{src});
467 # Tell the difference between:
468 # - a translation being renamed as a consequence of its master page
469 # being renamed, which is allowed
470 # - a user trying to directly rename a translation, which is forbidden
471 # by looking for the master page in the list of to-be-renamed pages we
472 # saved early in the renaming process.
473 my $orig_torename = $session->param("po_orig_torename");
474 unless (grep { $_ eq $masterpage } @{$orig_torename}) {
475 return gettext("Can not rename a translation. If the master page is renamed, ".
476 "however, its translations will be renamed as well.");
482 # As we're previewing or saving a page, the content may have
483 # changed, so tell the next filter() invocation it must not be lazy.
487 unsetalreadyfiltered($params{page}, $params{page});
488 return $params{content};
491 sub formbuilder_setup (@) {
493 my $form=$params{form};
496 return unless defined $form->field("do");
498 if ($form->field("do") eq "create") {
499 # Warn the user: new pages must be written in master language.
500 my $template=template("pocreatepage.tmpl");
501 $template->param(LANG => $config{po_master_language}{name});
502 $form->tmpl_param(message => $template->output);
504 elsif ($form->field("do") eq "edit") {
505 # Remove the rename/remove buttons on slave pages.
506 # This has to be done after the rename/remove plugins have added
507 # their buttons, which is why this hook must be run last.
508 # The canrename/canremove hooks already ensure this is forbidden
509 # at the backend level, so this is only UI sugar.
510 if (istranslation($form->field("page"))) {
512 for (my $i = 0; $i < @{$params{buttons}}; $i++) {
513 if (@{$params{buttons}}[$i] eq $_) {
514 delete @{$params{buttons}}[$i];
523 sub formbuilder (@) {
525 my $form=$params{form};
528 return unless defined $form->field("do");
530 # Do not allow to create pages of type po: they are automatically created.
531 # The main reason to do so is to bypass the "favor the type of linking page
532 # on page creation" logic, which is unsuitable when a broken link is clicked
533 # on a slave (PO) page.
534 # This cannot be done in the formbuilder_setup hook as the list of types is
536 if ($form->field("do") eq "create") {
537 foreach my $field ($form->field) {
538 next unless "$field" eq "type";
539 next unless $field->type eq 'select';
540 my $orig_value = $field->value;
541 # remove po from the list of types
542 my @types = grep { $_->[0] ne 'po' } $field->options;
543 $field->options(\@types) if @types;
544 # favor the type of linking page's masterpage
545 if ($orig_value eq 'po') {
547 if (defined $form->field('from')) {
548 ($from)=$form->field('from')=~/$config{wiki_file_regexp}/;
549 $from = masterpage($from);
551 if (defined $from && exists $pagesources{$from}) {
552 $type=pagetype($pagesources{$from});
554 $type=$config{default_pageext} unless defined $type;
555 $field->value($type) ;
562 # | Injected functions
565 # Implement po_link_to 'current' and 'negotiated' settings.
566 sub mybestlink ($$) {
570 return $origsubs{'bestlink'}->($page, $link)
571 if defined $config{po_link_to} && $config{po_link_to} eq "default";
573 my $res=$origsubs{'bestlink'}->(masterpage($page), $link);
574 my @caller = caller(1);
576 && istranslatable($res)
577 && istranslation($page)
578 && !(exists $caller[3] && defined $caller[3]
579 && ($caller[3] eq "IkiWiki::PageSpec::match_link"))) {
580 return $res . "." . lang($page);
585 sub mybeautify_urlpath ($) {
588 my $res=$origsubs{'beautify_urlpath'}->($url);
589 if (defined $config{po_link_to} && $config{po_link_to} eq "negotiated") {
590 $res =~ s!/\Qindex.$config{po_master_language}{code}.$config{htmlext}\E$!/!;
591 $res =~ s!/\Qindex.$config{htmlext}\E$!/!;
593 $res =~ s!/\Qindex.$_.$config{htmlext}\E$!/!;
594 } (keys %{$config{po_slave_languages}});
599 sub mytargetpage ($$) {
603 if (istranslation($page) || istranslatable($page)) {
604 my ($masterpage, $lang) = (masterpage($page), lang($page));
605 if (! $config{usedirs} || $masterpage eq 'index') {
606 return $masterpage . "." . $lang . "." . $ext;
609 return $masterpage . "/index." . $lang . "." . $ext;
612 return $origsubs{'targetpage'}->($page, $ext);
620 # workaround hard-coded /index.$config{htmlext} in IkiWiki::urlto()
622 && $config{po_link_to} eq "current"
623 && istranslatable('index')) {
624 return IkiWiki::beautify_urlpath(IkiWiki::baseurl($from) . "index." . lang($from) . ".$config{htmlext}");
626 # avoid using our injected beautify_urlpath if run by cgi_editpage,
627 # so that one is redirected to the just-edited page rather than to the
628 # negociated translation; to prevent unnecessary fiddling with caller/inject,
629 # we only do so when our beautify_urlpath would actually do what we want to
630 # avoid, i.e. when po_link_to = negotiated.
631 # also avoid doing so when run by cgi_goto, so that the links on recentchanges
632 # page actually lead to the exact page they pretend to.
633 if ($config{po_link_to} eq "negotiated") {
634 my @caller = caller(1);
636 $use_orig = 1 if (exists $caller[3] && defined $caller[3]
637 && ($caller[3] eq "IkiWiki::cgi_editpage" ||
638 $caller[3] eq "IkiWiki::Plugin::goto::cgi_goto")
640 inject(name => "IkiWiki::beautify_urlpath", call => $origsubs{'beautify_urlpath'})
642 my $res = $origsubs{'urlto'}->($to,$from,$absolute);
643 inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath)
648 return $origsubs{'urlto'}->($to,$from,$absolute)
655 # slave pages have no subpages
656 if (istranslation($params{'from'})) {
657 $params{'from'} = masterpage($params{'from'});
659 return $origsubs{'cgiurl'}->(%params);
666 if (exists $params{rootpage}) {
667 $rootpage=$origsubs{'bestlink'}->($params{page}, $params{rootpage});
668 if (!length $rootpage) {
669 $rootpage=$params{rootpage};
673 $rootpage=masterpage($params{page});
679 # | Blackboxes for private data
685 sub alreadyfiltered($$) {
689 return exists $filtered{$page}{$destpage}
690 && $filtered{$page}{$destpage} eq 1;
693 sub setalreadyfiltered($$) {
697 $filtered{$page}{$destpage}=1;
700 sub unsetalreadyfiltered($$) {
704 if (exists $filtered{$page}{$destpage}) {
705 delete $filtered{$page}{$destpage};
709 sub resetalreadyfiltered() {
718 sub maybe_add_leading_slash ($;$) {
721 $add=1 unless defined $add;
722 return '/' . $str if $add;
726 sub istranslatablefile ($) {
729 return 0 unless defined $file;
730 my $type=pagetype($file);
731 return 0 if ! defined $type || $type eq 'po';
732 return 0 if $file =~ /\.pot$/;
733 return 0 if ! defined $config{po_translatable_pages};
734 return 1 if pagespec_match(pagename($file), $config{po_translatable_pages});
738 sub istranslatable ($) {
742 return 1 if istranslatablefile($pagesources{$page});
746 sub _istranslation ($) {
749 $page='' unless defined $page && length $page;
750 my $hasleadingslash = ($page=~s#^/##);
751 my $file=$pagesources{$page};
752 return 0 unless defined $file
753 && defined pagetype($file)
754 && pagetype($file) eq 'po';
755 return 0 if $file =~ /\.pot$/;
757 my ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
758 return 0 unless defined $masterpage && defined $lang
759 && length $masterpage && length $lang
760 && defined $pagesources{$masterpage}
761 && defined $config{po_slave_languages}{$lang};
763 return (maybe_add_leading_slash($masterpage, $hasleadingslash), $lang)
764 if istranslatable($masterpage);
767 sub istranslation ($) {
770 if (1 < (my ($masterpage, $lang) = _istranslation($page))) {
771 my $hasleadingslash = ($masterpage=~s#^/##);
772 $translations{$masterpage}{$lang}=$page unless exists $translations{$masterpage}{$lang};
773 return (maybe_add_leading_slash($masterpage, $hasleadingslash), $lang);
781 if ( 1 < (my ($masterpage, $lang) = _istranslation($page))) {
790 if (1 < (my ($masterpage, $lang) = _istranslation($page))) {
793 return $config{po_master_language}{code};
796 sub islanguagecode ($) {
799 return $code =~ /^[a-z]{2}$/;
802 sub otherlanguage ($$) {
806 return masterpage($page) if $code eq $config{po_master_language}{code};
807 return masterpage($page) . '.' . $code;
810 sub otherlanguages ($) {
814 return \%ret unless istranslation($page) || istranslatable($page);
815 my $curlang=lang($page);
817 ($config{po_master_language}{code}, keys %{$config{po_slave_languages}}) {
818 next if $lang eq $curlang;
819 $ret{$lang}=otherlanguage($page, $lang);
825 my $masterfile=shift;
827 (my $name, my $dir, my $suffix) = fileparse($masterfile, qr/\.[^.]*/);
828 $dir='' if $dir eq './';
829 return File::Spec->catpath('', $dir, $name . ".pot");
833 my $masterfile=shift;
836 (my $name, my $dir, my $suffix) = fileparse($masterfile, qr/\.[^.]*/);
837 $dir='' if $dir eq './';
838 return File::Spec->catpath('', $dir, $name . "." . $lang . ".po");
842 my $masterfile=shift;
844 return map pofile($masterfile, $_), (keys %{$config{po_slave_languages}});
848 my $masterfile=shift;
850 my $potfile=potfile($masterfile);
851 my %options = ("markdown" => (pagetype($masterfile) eq 'mdwn') ? 1 : 0);
852 my $doc=Locale::Po4a::Chooser::new('text',%options);
853 $doc->{TT}{utf_mode} = 1;
854 $doc->{TT}{file_in_charset} = 'utf-8';
855 $doc->{TT}{file_out_charset} = 'utf-8';
856 $doc->read($masterfile);
857 # let's cheat a bit to force porefs option to be passed to
858 # Locale::Po4a::Po; this is undocument use of internal
859 # Locale::Po4a::TransTractor's data, compulsory since this module
860 # prevents us from using the porefs option.
861 $doc->{TT}{po_out}=Locale::Po4a::Po->new({ 'porefs' => 'none' });
862 $doc->{TT}{po_out}->set_charset('utf-8');
865 IkiWiki::prep_writefile(basename($potfile),dirname($potfile));
866 $doc->writepo($potfile);
869 sub refreshpofiles ($@) {
870 my $masterfile=shift;
873 my $potfile=potfile($masterfile);
875 error("po(refreshpofiles) ".sprintf(gettext("POT file (%s) does not exist"), $potfile));
878 foreach my $pofile (@pofiles) {
879 IkiWiki::prep_writefile(basename($pofile),dirname($pofile));
882 # If the po file exists in an underlay, copy it
884 my ($pobase)=$pofile=~/^\Q$config{srcdir}\E\/?(.*)$/;
885 foreach my $dir (@{$config{underlaydirs}}) {
886 if (-e "$dir/$pobase") {
887 File::Copy::syscopy("$dir/$pobase",$pofile)
888 or error("po(refreshpofiles) ".
889 sprintf(gettext("failed to copy underlay PO file to %s"),
896 system("msgmerge", "--previous", "-q", "-U", "--backup=none", $pofile, $potfile) == 0
897 or error("po(refreshpofiles) ".
898 sprintf(gettext("failed to update %s"),
902 File::Copy::syscopy($potfile,$pofile)
903 or error("po(refreshpofiles) ".
904 sprintf(gettext("failed to copy the POT file to %s"),
910 sub buildtranslationscache() {
911 # use istranslation's side-effect
912 map istranslation($_), (keys %pagesources);
915 sub resettranslationscache() {
919 sub flushmemoizecache() {
920 Memoize::flush_cache("istranslatable");
921 Memoize::flush_cache("_istranslation");
922 Memoize::flush_cache("percenttranslated");
925 sub urlto_with_orig_beautiful_urlpath($$) {
929 inject(name => "IkiWiki::beautify_urlpath", call => $origsubs{'beautify_urlpath'});
930 my $res=urlto($to, $from);
931 inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath);
936 sub percenttranslated ($) {
940 return gettext("N/A") unless istranslation($page);
941 my $file=srcfile($pagesources{$page});
942 my $masterfile = srcfile($pagesources{masterpage($page)});
944 "markdown" => (pagetype($masterfile) eq 'mdwn') ? 1 : 0,
946 my $doc=Locale::Po4a::Chooser::new('text',%options);
948 'po_in_name' => [ $file ],
949 'file_in_name' => [ $masterfile ],
950 'file_in_charset' => 'utf-8',
951 'file_out_charset' => 'utf-8',
952 ) or error("po(percenttranslated) ".
953 sprintf(gettext("failed to translate %s"), $page));
954 my ($percent,$hit,$queries) = $doc->stats();
955 $percent =~ s/\.[0-9]+$//;
959 sub languagename ($) {
962 return $config{po_master_language}{name}
963 if $code eq $config{po_master_language}{code};
964 return $config{po_slave_languages}{$code}
965 if defined $config{po_slave_languages}{$code};
969 sub otherlanguagesloop ($) {
973 my %otherpages=%{otherlanguages($page)};
974 while (my ($lang, $otherpage) = each %otherpages) {
975 if (istranslation($page) && masterpage($page) eq $otherpage) {
977 url => urlto_with_orig_beautiful_urlpath($otherpage, $page),
979 language => languagename($lang),
983 elsif (istranslation($otherpage)) {
985 url => urlto_with_orig_beautiful_urlpath($otherpage, $page),
987 language => languagename($lang),
988 percent => percenttranslated($otherpage),
993 return -1 if $a->{code} eq $config{po_master_language}{code};
994 return 1 if $b->{code} eq $config{po_master_language}{code};
995 return $a->{language} cmp $b->{language};
999 sub homepageurl (;$) {
1002 return urlto('', $page);
1005 sub ishomepage ($) {
1008 return 1 if $page eq 'index';
1009 map { return 1 if $page eq 'index.'.$_ } keys %{$config{po_slave_languages}};
1013 sub deletetranslations ($) {
1014 my $deletedmasterfile=shift;
1016 my $deletedmasterpage=pagename($deletedmasterfile);
1019 my $file = newpagefile($deletedmasterpage.'.'.$_, 'po');
1020 my $absfile = "$config{srcdir}/$file";
1021 if (-e $absfile && ! -l $absfile && ! -d $absfile) {
1022 push @todelete, $file;
1024 } keys %{$config{po_slave_languages}};
1028 IkiWiki::rcs_remove($_);
1031 IkiWiki::prune("$config{srcdir}/$_");
1037 gettext("removed obsolete PO files"));
1041 sub commit_and_refresh ($) {
1045 IkiWiki::disable_commit_hook();
1046 IkiWiki::rcs_commit_staged(
1049 IkiWiki::enable_commit_hook();
1050 IkiWiki::rcs_update();
1052 # Reinitialize module's private variables.
1053 resetalreadyfiltered();
1054 resettranslationscache();
1055 flushmemoizecache();
1056 # Trigger a wiki refresh.
1057 require IkiWiki::Render;
1058 # without preliminary saveindex/loadindex, refresh()
1059 # complains about a lot of uninitialized variables
1060 IkiWiki::saveindex();
1061 IkiWiki::loadindex();
1063 IkiWiki::saveindex();
1066 sub po_to_markup ($$) {
1067 my ($page, $content) = (shift, shift);
1069 $content = '' unless defined $content;
1070 $content = decode_utf8(encode_utf8($content));
1071 # CRLF line terminators make poor Locale::Po4a feel bad
1072 $content=~s/\r\n/\n/g;
1074 # There are incompatibilities between some File::Temp versions
1075 # (including 0.18, bundled with Lenny's perl-modules package)
1076 # and others (e.g. 0.20, previously present in the archive as
1077 # a standalone package): under certain circumstances, some
1078 # return a relative filename, whereas others return an absolute one;
1079 # we here use this module in a way that is at least compatible
1080 # with 0.18 and 0.20. Beware, hit'n'run refactorers!
1081 my $infile = new File::Temp(TEMPLATE => "ikiwiki-po-filter-in.XXXXXXXXXX",
1082 DIR => File::Spec->tmpdir,
1083 UNLINK => 1)->filename;
1084 my $outfile = new File::Temp(TEMPLATE => "ikiwiki-po-filter-out.XXXXXXXXXX",
1085 DIR => File::Spec->tmpdir,
1086 UNLINK => 1)->filename;
1088 my $fail = sub ($) {
1089 my $msg = "po(po_to_markup) - $page : " . shift;
1090 error($msg, sub { unlink $infile, $outfile});
1093 writefile(basename($infile), File::Spec->tmpdir, $content)
1094 or return $fail->(sprintf(gettext("failed to write %s"), $infile));
1096 my $masterfile = srcfile($pagesources{masterpage($page)});
1098 "markdown" => (pagetype($masterfile) eq 'mdwn') ? 1 : 0,
1100 my $doc=Locale::Po4a::Chooser::new('text',%options);
1102 'po_in_name' => [ $infile ],
1103 'file_in_name' => [ $masterfile ],
1104 'file_in_charset' => 'utf-8',
1105 'file_out_charset' => 'utf-8',
1106 ) or return $fail->(gettext("failed to translate"));
1107 $doc->write($outfile)
1108 or return $fail->(sprintf(gettext("failed to write %s"), $outfile));
1110 $content = readfile($outfile);
1112 # Unlinking should happen automatically, thanks to File::Temp,
1113 # but it does not work here, probably because of the way writefile()
1114 # and Locale::Po4a::write() work.
1115 unlink $infile, $outfile;
1120 # returns a SuccessReason or FailReason object
1122 my $content = shift;
1124 # NB: we don't use po_to_markup here, since Po4a parser does
1125 # not mind invalid PO content
1126 $content = '' unless defined $content;
1127 $content = decode_utf8(encode_utf8($content));
1129 # There are incompatibilities between some File::Temp versions
1130 # (including 0.18, bundled with Lenny's perl-modules package)
1131 # and others (e.g. 0.20, previously present in the archive as
1132 # a standalone package): under certain circumstances, some
1133 # return a relative filename, whereas others return an absolute one;
1134 # we here use this module in a way that is at least compatible
1135 # with 0.18 and 0.20. Beware, hit'n'run refactorers!
1136 my $infile = new File::Temp(TEMPLATE => "ikiwiki-po-isvalidpo.XXXXXXXXXX",
1137 DIR => File::Spec->tmpdir,
1138 UNLINK => 1)->filename;
1140 my $fail = sub ($) {
1141 my $msg = '[po/isvalidpo] ' . shift;
1143 return IkiWiki::FailReason->new("$msg");
1146 writefile(basename($infile), File::Spec->tmpdir, $content)
1147 or return $fail->(sprintf(gettext("failed to write %s"), $infile));
1149 my $res = (system("msgfmt", "--check", $infile, "-o", "/dev/null") == 0);
1151 # Unlinking should happen automatically, thanks to File::Temp,
1152 # but it does not work here, probably because of the way writefile()
1153 # and Locale::Po4a::write() work.
1157 return IkiWiki::SuccessReason->new("valid gettext data");
1159 return IkiWiki::FailReason->new(gettext("invalid gettext data, go back ".
1160 "to previous page to continue edit"));
1167 package IkiWiki::PageSpec;
1169 sub match_istranslation ($;@) {
1172 if (IkiWiki::Plugin::po::istranslation($page)) {
1173 return IkiWiki::SuccessReason->new("is a translation page");
1176 return IkiWiki::FailReason->new("is not a translation page");
1180 sub match_istranslatable ($;@) {
1183 if (IkiWiki::Plugin::po::istranslatable($page)) {
1184 return IkiWiki::SuccessReason->new("is set as translatable in po_translatable_pages");
1187 return IkiWiki::FailReason->new("is not set as translatable in po_translatable_pages");
1191 sub match_lang ($$;@) {
1195 my $regexp=IkiWiki::glob2re($wanted);
1196 my $lang=IkiWiki::Plugin::po::lang($page);
1197 if ($lang !~ /^$regexp$/i) {
1198 return IkiWiki::FailReason->new("file language is $lang, not $wanted");
1201 return IkiWiki::SuccessReason->new("file language is $wanted");
1205 sub match_currentlang ($$;@) {
1210 return IkiWiki::FailReason->new("no location provided") unless exists $params{location};
1212 my $currentlang=IkiWiki::Plugin::po::lang($params{location});
1213 my $lang=IkiWiki::Plugin::po::lang($page);
1215 if ($lang eq $currentlang) {
1216 return IkiWiki::SuccessReason->new("file language is the same as current one, i.e. $currentlang");
1219 return IkiWiki::FailReason->new("file language is $lang, whereas current language is $currentlang");
1223 sub match_needstranslation ($$;@) {
1226 my $percenttranslated=IkiWiki::Plugin::po::percenttranslated($page);
1227 if ($percenttranslated eq 'N/A') {
1228 return IkiWiki::FailReason->new("file is not a translation page");
1230 elsif ($percenttranslated < 100) {
1231 return IkiWiki::SuccessReason->new("file has $percenttranslated translated");
1234 return IkiWiki::FailReason->new("file is fully translated");