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"),
433 "IkiWiki::Plugin::po::change");
437 sub checkcontent (@) {
440 if (istranslation($params{page})) {
441 my $res = isvalidpo($params{content});
455 if (istranslation($params{page})) {
456 return gettext("Can not remove a translation. If the master page is removed, ".
457 "however, its translations will be removed as well.");
464 my $session = $params{session};
466 if (istranslation($params{src})) {
467 my $masterpage = masterpage($params{src});
468 # Tell the difference between:
469 # - a translation being renamed as a consequence of its master page
470 # being renamed, which is allowed
471 # - a user trying to directly rename a translation, which is forbidden
472 # by looking for the master page in the list of to-be-renamed pages we
473 # saved early in the renaming process.
474 my $orig_torename = $session->param("po_orig_torename");
475 unless (grep { $_ eq $masterpage } @{$orig_torename}) {
476 return gettext("Can not rename a translation. If the master page is renamed, ".
477 "however, its translations will be renamed as well.");
483 # As we're previewing or saving a page, the content may have
484 # changed, so tell the next filter() invocation it must not be lazy.
488 unsetalreadyfiltered($params{page}, $params{page});
489 return $params{content};
492 sub formbuilder_setup (@) {
494 my $form=$params{form};
497 return unless defined $form->field("do");
499 if ($form->field("do") eq "create") {
500 # Warn the user: new pages must be written in master language.
501 my $template=template("pocreatepage.tmpl");
502 $template->param(LANG => $config{po_master_language}{name});
503 $form->tmpl_param(message => $template->output);
505 elsif ($form->field("do") eq "edit") {
506 # Remove the rename/remove buttons on slave pages.
507 # This has to be done after the rename/remove plugins have added
508 # their buttons, which is why this hook must be run last.
509 # The canrename/canremove hooks already ensure this is forbidden
510 # at the backend level, so this is only UI sugar.
511 if (istranslation($form->field("page"))) {
513 for (my $i = 0; $i < @{$params{buttons}}; $i++) {
514 if (@{$params{buttons}}[$i] eq $_) {
515 delete @{$params{buttons}}[$i];
524 sub formbuilder (@) {
526 my $form=$params{form};
529 return unless defined $form->field("do");
531 # Do not allow to create pages of type po: they are automatically created.
532 # The main reason to do so is to bypass the "favor the type of linking page
533 # on page creation" logic, which is unsuitable when a broken link is clicked
534 # on a slave (PO) page.
535 # This cannot be done in the formbuilder_setup hook as the list of types is
537 if ($form->field("do") eq "create") {
538 foreach my $field ($form->field) {
539 next unless "$field" eq "type";
540 next unless $field->type eq 'select';
541 my $orig_value = $field->value;
542 # remove po from the list of types
543 my @types = grep { $_->[0] ne 'po' } $field->options;
544 $field->options(\@types) if @types;
545 # favor the type of linking page's masterpage
546 if ($orig_value eq 'po') {
548 if (defined $form->field('from')) {
549 ($from)=$form->field('from')=~/$config{wiki_file_regexp}/;
550 $from = masterpage($from);
552 if (defined $from && exists $pagesources{$from}) {
553 $type=pagetype($pagesources{$from});
555 $type=$config{default_pageext} unless defined $type;
556 $field->value($type) ;
563 # | Injected functions
566 # Implement po_link_to 'current' and 'negotiated' settings.
567 sub mybestlink ($$) {
571 return $origsubs{'bestlink'}->($page, $link)
572 if defined $config{po_link_to} && $config{po_link_to} eq "default";
574 my $res=$origsubs{'bestlink'}->(masterpage($page), $link);
575 my @caller = caller(1);
577 && istranslatable($res)
578 && istranslation($page)
579 && !(exists $caller[3] && defined $caller[3]
580 && ($caller[3] eq "IkiWiki::PageSpec::match_link"))) {
581 return $res . "." . lang($page);
586 sub mybeautify_urlpath ($) {
589 my $res=$origsubs{'beautify_urlpath'}->($url);
590 if (defined $config{po_link_to} && $config{po_link_to} eq "negotiated") {
591 $res =~ s!/\Qindex.$config{po_master_language}{code}.$config{htmlext}\E$!/!;
592 $res =~ s!/\Qindex.$config{htmlext}\E$!/!;
594 $res =~ s!/\Qindex.$_.$config{htmlext}\E$!/!;
595 } (keys %{$config{po_slave_languages}});
600 sub mytargetpage ($$) {
604 if (istranslation($page) || istranslatable($page)) {
605 my ($masterpage, $lang) = (masterpage($page), lang($page));
606 if (! $config{usedirs} || $masterpage eq 'index') {
607 return $masterpage . "." . $lang . "." . $ext;
610 return $masterpage . "/index." . $lang . "." . $ext;
613 return $origsubs{'targetpage'}->($page, $ext);
621 # workaround hard-coded /index.$config{htmlext} in IkiWiki::urlto()
623 && $config{po_link_to} eq "current"
624 && istranslatable('index')) {
625 return IkiWiki::beautify_urlpath(IkiWiki::baseurl($from) . "index." . lang($from) . ".$config{htmlext}");
627 # avoid using our injected beautify_urlpath if run by cgi_editpage,
628 # so that one is redirected to the just-edited page rather than to the
629 # negociated translation; to prevent unnecessary fiddling with caller/inject,
630 # we only do so when our beautify_urlpath would actually do what we want to
631 # avoid, i.e. when po_link_to = negotiated.
632 # also avoid doing so when run by cgi_goto, so that the links on recentchanges
633 # page actually lead to the exact page they pretend to.
634 if ($config{po_link_to} eq "negotiated") {
635 my @caller = caller(1);
637 $use_orig = 1 if (exists $caller[3] && defined $caller[3]
638 && ($caller[3] eq "IkiWiki::cgi_editpage" ||
639 $caller[3] eq "IkiWiki::Plugin::goto::cgi_goto")
641 inject(name => "IkiWiki::beautify_urlpath", call => $origsubs{'beautify_urlpath'})
643 my $res = $origsubs{'urlto'}->($to,$from,$absolute);
644 inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath)
649 return $origsubs{'urlto'}->($to,$from,$absolute)
656 # slave pages have no subpages
657 if (istranslation($params{'from'})) {
658 $params{'from'} = masterpage($params{'from'});
660 return $origsubs{'cgiurl'}->(%params);
667 if (exists $params{rootpage}) {
668 $rootpage=$origsubs{'bestlink'}->($params{page}, $params{rootpage});
669 if (!length $rootpage) {
670 $rootpage=$params{rootpage};
674 $rootpage=masterpage($params{page});
680 # | Blackboxes for private data
686 sub alreadyfiltered($$) {
690 return exists $filtered{$page}{$destpage}
691 && $filtered{$page}{$destpage} eq 1;
694 sub setalreadyfiltered($$) {
698 $filtered{$page}{$destpage}=1;
701 sub unsetalreadyfiltered($$) {
705 if (exists $filtered{$page}{$destpage}) {
706 delete $filtered{$page}{$destpage};
710 sub resetalreadyfiltered() {
719 sub maybe_add_leading_slash ($;$) {
722 $add=1 unless defined $add;
723 return '/' . $str if $add;
727 sub istranslatablefile ($) {
730 return 0 unless defined $file;
731 my $type=pagetype($file);
732 return 0 if ! defined $type || $type eq 'po';
733 return 0 if $file =~ /\.pot$/;
734 return 0 if ! defined $config{po_translatable_pages};
735 return 1 if pagespec_match(pagename($file), $config{po_translatable_pages});
739 sub istranslatable ($) {
743 return 1 if istranslatablefile($pagesources{$page});
747 sub _istranslation ($) {
750 $page='' unless defined $page && length $page;
751 my $hasleadingslash = ($page=~s#^/##);
752 my $file=$pagesources{$page};
753 return 0 unless defined $file
754 && defined pagetype($file)
755 && pagetype($file) eq 'po';
756 return 0 if $file =~ /\.pot$/;
758 my ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
759 return 0 unless defined $masterpage && defined $lang
760 && length $masterpage && length $lang
761 && defined $pagesources{$masterpage}
762 && defined $config{po_slave_languages}{$lang};
764 return (maybe_add_leading_slash($masterpage, $hasleadingslash), $lang)
765 if istranslatable($masterpage);
768 sub istranslation ($) {
771 if (1 < (my ($masterpage, $lang) = _istranslation($page))) {
772 my $hasleadingslash = ($masterpage=~s#^/##);
773 $translations{$masterpage}{$lang}=$page unless exists $translations{$masterpage}{$lang};
774 return (maybe_add_leading_slash($masterpage, $hasleadingslash), $lang);
782 if ( 1 < (my ($masterpage, $lang) = _istranslation($page))) {
791 if (1 < (my ($masterpage, $lang) = _istranslation($page))) {
794 return $config{po_master_language}{code};
797 sub islanguagecode ($) {
800 return $code =~ /^[a-z]{2}$/;
803 sub otherlanguage ($$) {
807 return masterpage($page) if $code eq $config{po_master_language}{code};
808 return masterpage($page) . '.' . $code;
811 sub otherlanguages ($) {
815 return \%ret unless istranslation($page) || istranslatable($page);
816 my $curlang=lang($page);
818 ($config{po_master_language}{code}, keys %{$config{po_slave_languages}}) {
819 next if $lang eq $curlang;
820 $ret{$lang}=otherlanguage($page, $lang);
826 my $masterfile=shift;
828 (my $name, my $dir, my $suffix) = fileparse($masterfile, qr/\.[^.]*/);
829 $dir='' if $dir eq './';
830 return File::Spec->catpath('', $dir, $name . ".pot");
834 my $masterfile=shift;
837 (my $name, my $dir, my $suffix) = fileparse($masterfile, qr/\.[^.]*/);
838 $dir='' if $dir eq './';
839 return File::Spec->catpath('', $dir, $name . "." . $lang . ".po");
843 my $masterfile=shift;
845 return map pofile($masterfile, $_), (keys %{$config{po_slave_languages}});
849 my $masterfile=shift;
851 my $potfile=potfile($masterfile);
852 my %options = ("markdown" => (pagetype($masterfile) eq 'mdwn') ? 1 : 0);
853 my $doc=Locale::Po4a::Chooser::new('text',%options);
854 $doc->{TT}{utf_mode} = 1;
855 $doc->{TT}{file_in_charset} = 'utf-8';
856 $doc->{TT}{file_out_charset} = 'utf-8';
857 $doc->read($masterfile);
858 # let's cheat a bit to force porefs option to be passed to
859 # Locale::Po4a::Po; this is undocument use of internal
860 # Locale::Po4a::TransTractor's data, compulsory since this module
861 # prevents us from using the porefs option.
862 $doc->{TT}{po_out}=Locale::Po4a::Po->new({ 'porefs' => 'none' });
863 $doc->{TT}{po_out}->set_charset('utf-8');
866 IkiWiki::prep_writefile(basename($potfile),dirname($potfile));
867 $doc->writepo($potfile);
870 sub refreshpofiles ($@) {
871 my $masterfile=shift;
874 my $potfile=potfile($masterfile);
876 error("po(refreshpofiles) ".sprintf(gettext("POT file (%s) does not exist"), $potfile));
879 foreach my $pofile (@pofiles) {
880 IkiWiki::prep_writefile(basename($pofile),dirname($pofile));
883 # If the po file exists in an underlay, copy it
885 my ($pobase)=$pofile=~/^\Q$config{srcdir}\E\/?(.*)$/;
886 foreach my $dir (@{$config{underlaydirs}}) {
887 if (-e "$dir/$pobase") {
888 File::Copy::syscopy("$dir/$pobase",$pofile)
889 or error("po(refreshpofiles) ".
890 sprintf(gettext("failed to copy underlay PO file to %s"),
897 system("msgmerge", "--previous", "-q", "-U", "--backup=none", $pofile, $potfile) == 0
898 or error("po(refreshpofiles) ".
899 sprintf(gettext("failed to update %s"),
903 File::Copy::syscopy($potfile,$pofile)
904 or error("po(refreshpofiles) ".
905 sprintf(gettext("failed to copy the POT file to %s"),
911 sub buildtranslationscache() {
912 # use istranslation's side-effect
913 map istranslation($_), (keys %pagesources);
916 sub resettranslationscache() {
920 sub flushmemoizecache() {
921 Memoize::flush_cache("istranslatable");
922 Memoize::flush_cache("_istranslation");
923 Memoize::flush_cache("percenttranslated");
926 sub urlto_with_orig_beautiful_urlpath($$) {
930 inject(name => "IkiWiki::beautify_urlpath", call => $origsubs{'beautify_urlpath'});
931 my $res=urlto($to, $from);
932 inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath);
937 sub percenttranslated ($) {
941 return gettext("N/A") unless istranslation($page);
942 my $file=srcfile($pagesources{$page});
943 my $masterfile = srcfile($pagesources{masterpage($page)});
945 "markdown" => (pagetype($masterfile) eq 'mdwn') ? 1 : 0,
947 my $doc=Locale::Po4a::Chooser::new('text',%options);
949 'po_in_name' => [ $file ],
950 'file_in_name' => [ $masterfile ],
951 'file_in_charset' => 'utf-8',
952 'file_out_charset' => 'utf-8',
953 ) or error("po(percenttranslated) ".
954 sprintf(gettext("failed to translate %s"), $page));
955 my ($percent,$hit,$queries) = $doc->stats();
956 $percent =~ s/\.[0-9]+$//;
960 sub languagename ($) {
963 return $config{po_master_language}{name}
964 if $code eq $config{po_master_language}{code};
965 return $config{po_slave_languages}{$code}
966 if defined $config{po_slave_languages}{$code};
970 sub otherlanguagesloop ($) {
974 my %otherpages=%{otherlanguages($page)};
975 while (my ($lang, $otherpage) = each %otherpages) {
976 if (istranslation($page) && masterpage($page) eq $otherpage) {
978 url => urlto_with_orig_beautiful_urlpath($otherpage, $page),
980 language => languagename($lang),
984 elsif (istranslation($otherpage)) {
986 url => urlto_with_orig_beautiful_urlpath($otherpage, $page),
988 language => languagename($lang),
989 percent => percenttranslated($otherpage),
994 return -1 if $a->{code} eq $config{po_master_language}{code};
995 return 1 if $b->{code} eq $config{po_master_language}{code};
996 return $a->{language} cmp $b->{language};
1000 sub homepageurl (;$) {
1003 return urlto('', $page);
1006 sub ishomepage ($) {
1009 return 1 if $page eq 'index';
1010 map { return 1 if $page eq 'index.'.$_ } keys %{$config{po_slave_languages}};
1014 sub deletetranslations ($) {
1015 my $deletedmasterfile=shift;
1017 my $deletedmasterpage=pagename($deletedmasterfile);
1020 my $file = newpagefile($deletedmasterpage.'.'.$_, 'po');
1021 my $absfile = "$config{srcdir}/$file";
1022 if (-e $absfile && ! -l $absfile && ! -d $absfile) {
1023 push @todelete, $file;
1025 } keys %{$config{po_slave_languages}};
1029 IkiWiki::rcs_remove($_);
1032 IkiWiki::prune("$config{srcdir}/$_");
1038 gettext("removed obsolete PO files"),
1039 "IkiWiki::Plugin::po::deletetranslations");
1043 sub commit_and_refresh ($$) {
1044 my ($msg, $author) = (shift, shift);
1047 IkiWiki::disable_commit_hook();
1048 IkiWiki::rcs_commit_staged($msg, $author, "127.0.0.1");
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");