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);
54 $origsubs{'beautify_urlpath'}=\&IkiWiki::beautify_urlpath;
55 inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath);
56 $origsubs{'targetpage'}=\&IkiWiki::targetpage;
57 inject(name => "IkiWiki::targetpage", call => \&mytargetpage);
58 $origsubs{'urlto'}=\&IkiWiki::urlto;
59 inject(name => "IkiWiki::urlto", call => \&myurlto);
60 $origsubs{'cgiurl'}=\&IkiWiki::cgiurl;
61 inject(name => "IkiWiki::cgiurl", call => \&mycgiurl);
62 $origsubs{'rootpage'}=\&IkiWiki::rootpage;
63 inject(name => "IkiWiki::rootpage", call => \&myrootpage);
72 # 2. Injected functions
73 # 3. Blackboxes for private data
88 po_master_language => {
94 description => "master language (non-PO files)",
98 po_slave_languages => {
105 description => "slave languages (PO files)",
109 po_translatable_pages => {
111 example => "* and !*/Discussion",
112 description => "PageSpec controlling which pages are translatable",
113 link => "ikiwiki/PageSpec",
119 example => "current",
120 description => "internal linking behavior (default/current/negotiated)",
127 foreach my $field (qw{po_master_language}) {
128 if (! exists $config{$field} || ! defined $config{$field}) {
129 error(sprintf(gettext("Must specify %s when using the %s plugin"),
136 or error(sprintf(gettext("%s is not a valid language code"), $_));
137 } ($config{po_master_language}{code}, keys %{$config{po_slave_languages}});
139 if (! exists $config{po_translatable_pages} ||
140 ! defined $config{po_translatable_pages}) {
141 $config{po_translatable_pages}="";
143 if (! exists $config{po_link_to} ||
144 ! defined $config{po_link_to}) {
145 $config{po_link_to}='default';
147 elsif ($config{po_link_to} !~ /^(default|current|negotiated)$/) {
148 warn(sprintf(gettext('%s is not a valid value for po_link_to, falling back to po_link_to=default'),
149 $config{po_link_to}));
150 $config{po_link_to}='default';
152 elsif ($config{po_link_to} eq "negotiated" && ! $config{usedirs}) {
153 warn(gettext('po_link_to=negotiated requires usedirs to be enabled, falling back to po_link_to=default'));
154 $config{po_link_to}='default';
156 unless ($config{po_link_to} eq 'default') {
157 $origsubs{'bestlink'}=\&IkiWiki::bestlink;
158 inject(name => "IkiWiki::bestlink", call => \&mybestlink);
161 push @{$config{wiki_file_prune_regexps}}, qr/\.pot$/;
163 # Translated versions of the underlays are added if available.
164 foreach my $underlay ("basewiki",
165 map { m/^\Q$config{underlaydirbase}\E\/*(.*)/ }
166 reverse @{$config{underlaydirs}}) {
167 next if $underlay=~/^locale\//;
169 # Underlays containing the po files for slave languages.
170 foreach my $ll (keys %{$config{po_slave_languages}}) {
171 add_underlay("po/$ll/$underlay")
172 if -d "$config{underlaydirbase}/po/$ll/$underlay";
175 if ($config{po_master_language}{code} ne 'en') {
176 # Add underlay containing translated source files
177 # for the master language.
178 add_underlay("locale/$config{po_master_language}{code}/$underlay");
184 my $needsbuild=shift;
186 # backup @needsbuild content so that change() can know whether
187 # a given master page was rendered because its source file was changed
188 @origneedsbuild=(@$needsbuild);
191 buildtranslationscache();
193 # make existing translations depend on the corresponding master page
194 foreach my $master (keys %translations) {
195 map add_depends($_, $master), values %{otherlanguages($master)};
199 # Massage the recorded state of internal links so that:
200 # - it matches the actually generated links, rather than the links as written
201 # in the pages' source
202 # - backlinks are consistent in all cases
205 my $page=$params{page};
206 my $content=$params{content};
208 if (istranslation($page)) {
209 foreach my $destpage (@{$links{$page}}) {
210 if (istranslatable($destpage)) {
211 # replace the occurence of $destpage in $links{$page}
212 for (my $i=0; $i<@{$links{$page}}; $i++) {
213 if (@{$links{$page}}[$i] eq $destpage) {
214 @{$links{$page}}[$i] = $destpage . '.' . lang($page);
221 elsif (! istranslatable($page) && ! istranslation($page)) {
222 foreach my $destpage (@{$links{$page}}) {
223 if (istranslatable($destpage)) {
224 # make sure any destpage's translations has
225 # $page in its backlinks
226 push @{$links{$page}},
227 values %{otherlanguages($destpage)};
233 # We use filter to convert PO to the master page's format,
234 # since the rest of ikiwiki should not work on PO files.
238 my $page = $params{page};
239 my $destpage = $params{destpage};
240 my $content = $params{content};
241 if (istranslation($page) && ! alreadyfiltered($page, $destpage)) {
242 $content = po_to_markup($page, $content);
243 setalreadyfiltered($page, $destpage);
251 my $page = $params{page};
252 my $content = $params{content};
254 # ignore PO files this plugin did not create
255 return $content unless istranslation($page);
257 # force content to be htmlize'd as if it was the same type as the master page
258 return IkiWiki::htmlize($page, $page,
259 pagetype(srcfile($pagesources{masterpage($page)})),
263 sub pagetemplate (@) {
265 my $page=$params{page};
266 my $destpage=$params{destpage};
267 my $template=$params{template};
269 my ($masterpage, $lang) = istranslation($page);
271 if (istranslation($page) && $template->query(name => "percenttranslated")) {
272 $template->param(percenttranslated => percenttranslated($page));
274 if ($template->query(name => "istranslation")) {
275 $template->param(istranslation => scalar istranslation($page));
277 if ($template->query(name => "istranslatable")) {
278 $template->param(istranslatable => istranslatable($page));
280 if ($template->query(name => "HOMEPAGEURL")) {
281 $template->param(homepageurl => homepageurl($page));
283 if ($template->query(name => "otherlanguages")) {
284 $template->param(otherlanguages => [otherlanguagesloop($page)]);
285 map add_depends($page, $_), (values %{otherlanguages($page)});
287 if ($config{discussion} && istranslation($page)) {
288 if ($page !~ /.*\/\Q$config{discussionpage}\E$/i &&
289 (length $config{cgiurl} ||
290 exists $links{$masterpage."/".lc($config{discussionpage})})) {
291 $template->param('discussionlink' => htmllink(
294 $masterpage . '/' . $config{discussionpage},
297 linktext => $config{discussionpage},
301 # Remove broken parentlink to ./index.html on home page's translations.
302 # It works because this hook has the "last" parameter set, to ensure it
303 # runs after parentlinks' own pagetemplate hook.
304 if ($template->param('parentlinks')
305 && istranslation($page)
306 && $masterpage eq "index") {
307 $template->param('parentlinks' => []);
309 if (ishomepage($page) && $template->query(name => "title")) {
310 $template->param(title => $config{wikiname});
314 # Add the renamed page translations to the list of to-be-renamed pages.
315 sub renamepages (@) {
318 my %torename = %{$params{torename}};
319 my $session = $params{session};
321 # Save the page(s) the user asked to rename, so that our
322 # canrename hook can tell the difference between:
323 # - a translation being renamed as a consequence of its master page
325 # - a user trying to directly rename a translation
326 # This is why this hook has to be run first, before the list of pages
327 # to rename is modified by other plugins.
329 @orig_torename=@{$session->param("po_orig_torename")}
330 if defined $session->param("po_orig_torename");
331 push @orig_torename, $torename{src};
332 $session->param(po_orig_torename => \@orig_torename);
333 IkiWiki::cgi_savesession($session);
335 return () unless istranslatable($torename{src});
338 my %otherpages=%{otherlanguages($torename{src})};
339 while (my ($lang, $otherpage) = each %otherpages) {
342 srcfile => $pagesources{$otherpage},
343 dest => otherlanguage($torename{dest}, $lang),
344 destfile => $torename{dest}.".".$lang.".po",
354 map { deletetranslations($_) } grep istranslatablefile($_), @deleted;
360 # All meta titles are first extracted at scan time, i.e. before we turn
361 # PO files back into translated markdown; escaping of double-quotes in
362 # PO files breaks the meta plugin's parsing enough to save ugly titles
363 # to %pagestate at this time.
365 # Then, at render time, every page passes in turn through the Great
366 # Rendering Chain (filter->preprocess->linkify->htmlize), and the meta
367 # plugin's preprocess hook is this time in a position to correctly
368 # extract the titles from slave pages.
370 # This is, unfortunately, too late: if the page A, linking to the page
371 # B, is rendered before B, it will display the wrongly-extracted meta
372 # title as the link text to B.
374 # On the one hand, such a corner case only happens on rebuild: on
375 # refresh, every rendered page is fixed to contain correct meta titles.
376 # On the other hand, it can take some time to get every page fixed.
377 # We therefore re-render every rendered page after a rebuild to fix them
378 # at once. As this more or less doubles the time needed to rebuild the
379 # wiki, we do so only when really needed.
382 && exists $config{rebuild} && defined $config{rebuild} && $config{rebuild}
383 && UNIVERSAL::can("IkiWiki::Plugin::meta", "getsetup")
384 && exists $config{meta_overrides_page_title}
385 && defined $config{meta_overrides_page_title}
386 && $config{meta_overrides_page_title}) {
387 debug(sprintf(gettext("rebuilding all pages to fix meta titles")));
388 resetalreadyfiltered();
389 require IkiWiki::Render;
390 foreach my $file (@rendered) {
391 debug(sprintf(gettext("building %s"), $file));
392 IkiWiki::render($file);
396 my $updated_po_files=0;
398 # Refresh/create POT and PO files as needed.
399 # (But avoid doing so if they are in an underlay directory.)
400 foreach my $file (grep {istranslatablefile($_)} @rendered) {
401 my $masterfile=srcfile($file);
402 my $page=pagename($file);
403 my $updated_pot_file=0;
404 # Only refresh POT file if it does not exist, or if
405 # $pagesources{$page} was changed: don't if only the HTML was
406 # refreshed, e.g. because of a dependency.
407 if ($masterfile eq "$config{srcdir}/$file" &&
408 ((grep { $_ eq $pagesources{$page} } @origneedsbuild)
409 || ! -e potfile($masterfile))) {
410 refreshpot($masterfile);
414 foreach my $po (pofiles($masterfile)) {
415 next if ! $updated_pot_file && ! -e $po;
416 next if grep { $po=~/\Q$_\E/ } @{$config{underlaydirs}};
420 refreshpofiles($masterfile, @pofiles);
421 map { s/^\Q$config{srcdir}\E\/*//; IkiWiki::rcs_add($_) } @pofiles if $config{rcs};
426 if ($updated_po_files) {
428 gettext("updated PO files"),
429 "IkiWiki::Plugin::po::change");
433 sub checkcontent (@) {
436 if (istranslation($params{page})) {
437 my $res = isvalidpo($params{content});
451 if (istranslation($params{page})) {
452 return gettext("Can not remove a translation. If the master page is removed, ".
453 "however, its translations will be removed as well.");
460 my $session = $params{session};
462 if (istranslation($params{src})) {
463 my $masterpage = masterpage($params{src});
464 # Tell the difference between:
465 # - a translation being renamed as a consequence of its master page
466 # being renamed, which is allowed
467 # - a user trying to directly rename a translation, which is forbidden
468 # by looking for the master page in the list of to-be-renamed pages we
469 # saved early in the renaming process.
470 my $orig_torename = $session->param("po_orig_torename");
471 unless (grep { $_ eq $masterpage } @{$orig_torename}) {
472 return gettext("Can not rename a translation. If the master page is renamed, ".
473 "however, its translations will be renamed as well.");
479 # As we're previewing or saving a page, the content may have
480 # changed, so tell the next filter() invocation it must not be lazy.
484 unsetalreadyfiltered($params{page}, $params{page});
485 return $params{content};
488 sub formbuilder_setup (@) {
490 my $form=$params{form};
493 return unless defined $form->field("do");
495 if ($form->field("do") eq "create") {
496 # Warn the user: new pages must be written in master language.
497 my $template=template("pocreatepage.tmpl");
498 $template->param(LANG => $config{po_master_language}{name});
499 $form->tmpl_param(message => $template->output);
501 elsif ($form->field("do") eq "edit") {
502 # Remove the rename/remove buttons on slave pages.
503 # This has to be done after the rename/remove plugins have added
504 # their buttons, which is why this hook must be run last.
505 # The canrename/canremove hooks already ensure this is forbidden
506 # at the backend level, so this is only UI sugar.
507 if (istranslation($form->field("page"))) {
509 for (my $i = 0; $i < @{$params{buttons}}; $i++) {
510 if (@{$params{buttons}}[$i] eq $_) {
511 delete @{$params{buttons}}[$i];
520 sub formbuilder (@) {
522 my $form=$params{form};
525 return unless defined $form->field("do");
527 # Do not allow to create pages of type po: they are automatically created.
528 # The main reason to do so is to bypass the "favor the type of linking page
529 # on page creation" logic, which is unsuitable when a broken link is clicked
530 # on a slave (PO) page.
531 # This cannot be done in the formbuilder_setup hook as the list of types is
533 if ($form->field("do") eq "create") {
534 foreach my $field ($form->field) {
535 next unless "$field" eq "type";
536 next unless $field->type eq 'select';
537 my $orig_value = $field->value;
538 # remove po from the list of types
539 my @types = grep { $_->[0] ne 'po' } $field->options;
540 $field->options(\@types) if @types;
541 # favor the type of linking page's masterpage
542 if ($orig_value eq 'po') {
544 if (defined $form->field('from')) {
545 ($from)=$form->field('from')=~/$config{wiki_file_regexp}/;
546 $from = masterpage($from);
548 if (defined $from && exists $pagesources{$from}) {
549 $type=pagetype($pagesources{$from});
551 $type=$config{default_pageext} unless defined $type;
552 $field->value($type) ;
559 # | Injected functions
562 # Implement po_link_to 'current' and 'negotiated' settings.
563 # Not injected otherwise.
564 sub mybestlink ($$) {
568 my $res=$origsubs{'bestlink'}->(masterpage($page), $link);
570 && istranslatable($res)
571 && istranslation($page)) {
572 return $res . "." . lang($page);
577 sub mybeautify_urlpath ($) {
580 my $res=$origsubs{'beautify_urlpath'}->($url);
581 if ($config{po_link_to} eq "negotiated") {
582 $res =~ s!/\Qindex.$config{po_master_language}{code}.$config{htmlext}\E$!/!;
583 $res =~ s!/\Qindex.$config{htmlext}\E$!/!;
585 $res =~ s!/\Qindex.$_.$config{htmlext}\E$!/!;
586 } (keys %{$config{po_slave_languages}});
591 sub mytargetpage ($$) {
595 if (istranslation($page) || istranslatable($page)) {
596 my ($masterpage, $lang) = (masterpage($page), lang($page));
597 if (! $config{usedirs} || $masterpage eq 'index') {
598 return $masterpage . "." . $lang . "." . $ext;
601 return $masterpage . "/index." . $lang . "." . $ext;
604 return $origsubs{'targetpage'}->($page, $ext);
612 # workaround hard-coded /index.$config{htmlext} in IkiWiki::urlto()
614 && $config{po_link_to} eq "current"
615 && istranslatable('index')) {
616 return IkiWiki::beautify_urlpath(IkiWiki::baseurl($from) . "index." . lang($from) . ".$config{htmlext}");
618 # avoid using our injected beautify_urlpath if run by cgi_editpage,
619 # so that one is redirected to the just-edited page rather than to the
620 # negociated translation; to prevent unnecessary fiddling with caller/inject,
621 # we only do so when our beautify_urlpath would actually do what we want to
622 # avoid, i.e. when po_link_to = negotiated.
623 # also avoid doing so when run by cgi_goto, so that the links on recentchanges
624 # page actually lead to the exact page they pretend to.
625 if ($config{po_link_to} eq "negotiated") {
626 my @caller = caller(1);
628 $use_orig = 1 if (exists $caller[3] && defined $caller[3]
629 && ($caller[3] eq "IkiWiki::cgi_editpage" ||
630 $caller[3] eq "IkiWiki::Plugin::goto::cgi_goto")
632 inject(name => "IkiWiki::beautify_urlpath", call => $origsubs{'beautify_urlpath'})
634 my $res = $origsubs{'urlto'}->($to,$from,$absolute);
635 inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath)
640 return $origsubs{'urlto'}->($to,$from,$absolute)
647 # slave pages have no subpages
648 if (istranslation($params{'from'})) {
649 $params{'from'} = masterpage($params{'from'});
651 return $origsubs{'cgiurl'}->(%params);
658 if (exists $params{rootpage}) {
659 $rootpage=$origsubs{'bestlink'}->($params{page}, $params{rootpage});
660 if (!length $rootpage) {
661 $rootpage=$params{rootpage};
665 $rootpage=masterpage($params{page});
671 # | Blackboxes for private data
677 sub alreadyfiltered($$) {
681 return exists $filtered{$page}{$destpage}
682 && $filtered{$page}{$destpage} eq 1;
685 sub setalreadyfiltered($$) {
689 $filtered{$page}{$destpage}=1;
692 sub unsetalreadyfiltered($$) {
696 if (exists $filtered{$page}{$destpage}) {
697 delete $filtered{$page}{$destpage};
701 sub resetalreadyfiltered() {
710 sub maybe_add_leading_slash ($;$) {
713 $add=1 unless defined $add;
714 return '/' . $str if $add;
718 sub istranslatablefile ($) {
721 return 0 unless defined $file;
722 my $type=pagetype($file);
723 return 0 if ! defined $type || $type eq 'po';
724 return 0 if $file =~ /\.pot$/;
725 return 1 if pagespec_match(pagename($file), $config{po_translatable_pages});
729 sub istranslatable ($) {
733 return 1 if istranslatablefile($pagesources{$page});
737 sub _istranslation ($) {
740 $page='' unless defined $page && length $page;
741 my $hasleadingslash = ($page=~s#^/##);
742 my $file=$pagesources{$page};
743 return 0 unless defined $file
744 && defined pagetype($file)
745 && pagetype($file) eq 'po';
746 return 0 if $file =~ /\.pot$/;
748 my ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
749 return 0 unless defined $masterpage && defined $lang
750 && length $masterpage && length $lang
751 && defined $pagesources{$masterpage}
752 && defined $config{po_slave_languages}{$lang};
754 return (maybe_add_leading_slash($masterpage, $hasleadingslash), $lang)
755 if istranslatable($masterpage);
758 sub istranslation ($) {
761 if (1 < (my ($masterpage, $lang) = _istranslation($page))) {
762 my $hasleadingslash = ($masterpage=~s#^/##);
763 $translations{$masterpage}{$lang}=$page unless exists $translations{$masterpage}{$lang};
764 return (maybe_add_leading_slash($masterpage, $hasleadingslash), $lang);
772 if ( 1 < (my ($masterpage, $lang) = _istranslation($page))) {
781 if (1 < (my ($masterpage, $lang) = _istranslation($page))) {
784 return $config{po_master_language}{code};
787 sub islanguagecode ($) {
790 return $code =~ /^[a-z]{2}$/;
793 sub otherlanguage ($$) {
797 return masterpage($page) if $code eq $config{po_master_language}{code};
798 return masterpage($page) . '.' . $code;
801 sub otherlanguages ($) {
805 return \%ret unless istranslation($page) || istranslatable($page);
806 my $curlang=lang($page);
808 ($config{po_master_language}{code}, keys %{$config{po_slave_languages}}) {
809 next if $lang eq $curlang;
810 $ret{$lang}=otherlanguage($page, $lang);
816 my $masterfile=shift;
818 (my $name, my $dir, my $suffix) = fileparse($masterfile, qr/\.[^.]*/);
819 $dir='' if $dir eq './';
820 return File::Spec->catpath('', $dir, $name . ".pot");
824 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 . "." . $lang . ".po");
833 my $masterfile=shift;
835 return map pofile($masterfile, $_), (keys %{$config{po_slave_languages}});
839 my $masterfile=shift;
841 my $potfile=potfile($masterfile);
842 my %options = ("markdown" => (pagetype($masterfile) eq 'mdwn') ? 1 : 0);
843 my $doc=Locale::Po4a::Chooser::new('text',%options);
844 $doc->{TT}{utf_mode} = 1;
845 $doc->{TT}{file_in_charset} = 'utf-8';
846 $doc->{TT}{file_out_charset} = 'utf-8';
847 $doc->read($masterfile);
848 # let's cheat a bit to force porefs option to be passed to
849 # Locale::Po4a::Po; this is undocument use of internal
850 # Locale::Po4a::TransTractor's data, compulsory since this module
851 # prevents us from using the porefs option.
852 $doc->{TT}{po_out}=Locale::Po4a::Po->new({ 'porefs' => 'none' });
853 $doc->{TT}{po_out}->set_charset('utf-8');
856 IkiWiki::prep_writefile(basename($potfile),dirname($potfile));
857 $doc->writepo($potfile);
860 sub refreshpofiles ($@) {
861 my $masterfile=shift;
864 my $potfile=potfile($masterfile);
866 error("po(refreshpofiles) ".sprintf(gettext("POT file (%s) does not exist"), $potfile));
869 foreach my $pofile (@pofiles) {
870 IkiWiki::prep_writefile(basename($pofile),dirname($pofile));
873 # If the po file exists in an underlay, copy it
875 my ($pobase)=$pofile=~/^\Q$config{srcdir}\E\/?(.*)$/;
876 foreach my $dir (@{$config{underlaydirs}}) {
877 if (-e "$dir/$pobase") {
878 File::Copy::syscopy("$dir/$pobase",$pofile)
879 or error("po(refreshpofiles) ".
880 sprintf(gettext("failed to copy underlay PO file to %s"),
887 system("msgmerge", "--previous", "-q", "-U", "--backup=none", $pofile, $potfile) == 0
888 or error("po(refreshpofiles) ".
889 sprintf(gettext("failed to update %s"),
893 File::Copy::syscopy($potfile,$pofile)
894 or error("po(refreshpofiles) ".
895 sprintf(gettext("failed to copy the POT file to %s"),
901 sub buildtranslationscache() {
902 # use istranslation's side-effect
903 map istranslation($_), (keys %pagesources);
906 sub resettranslationscache() {
910 sub flushmemoizecache() {
911 Memoize::flush_cache("istranslatable");
912 Memoize::flush_cache("_istranslation");
913 Memoize::flush_cache("percenttranslated");
916 sub urlto_with_orig_beautiful_urlpath($$) {
920 inject(name => "IkiWiki::beautify_urlpath", call => $origsubs{'beautify_urlpath'});
921 my $res=urlto($to, $from);
922 inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath);
927 sub percenttranslated ($) {
931 return gettext("N/A") unless istranslation($page);
932 my $file=srcfile($pagesources{$page});
933 my $masterfile = srcfile($pagesources{masterpage($page)});
935 "markdown" => (pagetype($masterfile) eq 'mdwn') ? 1 : 0,
937 my $doc=Locale::Po4a::Chooser::new('text',%options);
939 'po_in_name' => [ $file ],
940 'file_in_name' => [ $masterfile ],
941 'file_in_charset' => 'utf-8',
942 'file_out_charset' => 'utf-8',
943 ) or error("po(percenttranslated) ".
944 sprintf(gettext("failed to translate %s"), $page));
945 my ($percent,$hit,$queries) = $doc->stats();
946 $percent =~ s/\.[0-9]+$//;
950 sub languagename ($) {
953 return $config{po_master_language}{name}
954 if $code eq $config{po_master_language}{code};
955 return $config{po_slave_languages}{$code}
956 if defined $config{po_slave_languages}{$code};
960 sub otherlanguagesloop ($) {
964 my %otherpages=%{otherlanguages($page)};
965 while (my ($lang, $otherpage) = each %otherpages) {
966 if (istranslation($page) && masterpage($page) eq $otherpage) {
968 url => urlto_with_orig_beautiful_urlpath($otherpage, $page),
970 language => languagename($lang),
974 elsif (istranslation($otherpage)) {
976 url => urlto_with_orig_beautiful_urlpath($otherpage, $page),
978 language => languagename($lang),
979 percent => percenttranslated($otherpage),
984 return -1 if $a->{code} eq $config{po_master_language}{code};
985 return 1 if $b->{code} eq $config{po_master_language}{code};
986 return $a->{language} cmp $b->{language};
990 sub homepageurl (;$) {
993 return urlto('', $page);
999 return 1 if $page eq 'index';
1000 map { return 1 if $page eq 'index.'.$_ } keys %{$config{po_slave_languages}};
1004 sub deletetranslations ($) {
1005 my $deletedmasterfile=shift;
1007 my $deletedmasterpage=pagename($deletedmasterfile);
1010 my $file = newpagefile($deletedmasterpage.'.'.$_, 'po');
1011 my $absfile = "$config{srcdir}/$file";
1012 if (-e $absfile && ! -l $absfile && ! -d $absfile) {
1013 push @todelete, $file;
1015 } keys %{$config{po_slave_languages}};
1019 IkiWiki::rcs_remove($_);
1022 IkiWiki::prune("$config{srcdir}/$_");
1028 gettext("removed obsolete PO files"),
1029 "IkiWiki::Plugin::po::deletetranslations");
1033 sub commit_and_refresh ($$) {
1034 my ($msg, $author) = (shift, shift);
1037 IkiWiki::disable_commit_hook();
1038 IkiWiki::rcs_commit_staged($msg, $author, "127.0.0.1");
1039 IkiWiki::enable_commit_hook();
1040 IkiWiki::rcs_update();
1042 # Reinitialize module's private variables.
1043 resetalreadyfiltered();
1044 resettranslationscache();
1045 flushmemoizecache();
1046 # Trigger a wiki refresh.
1047 require IkiWiki::Render;
1048 # without preliminary saveindex/loadindex, refresh()
1049 # complains about a lot of uninitialized variables
1050 IkiWiki::saveindex();
1051 IkiWiki::loadindex();
1053 IkiWiki::saveindex();
1056 # on success, returns the filtered content.
1057 # on error, if $nonfatal, warn and return undef; else, error out.
1058 sub po_to_markup ($$;$) {
1059 my ($page, $content) = (shift, shift);
1060 my $nonfatal = shift;
1062 $content = '' unless defined $content;
1063 $content = decode_utf8(encode_utf8($content));
1064 # CRLF line terminators make poor Locale::Po4a feel bad
1065 $content=~s/\r\n/\n/g;
1067 # There are incompatibilities between some File::Temp versions
1068 # (including 0.18, bundled with Lenny's perl-modules package)
1069 # and others (e.g. 0.20, previously present in the archive as
1070 # a standalone package): under certain circumstances, some
1071 # return a relative filename, whereas others return an absolute one;
1072 # we here use this module in a way that is at least compatible
1073 # with 0.18 and 0.20. Beware, hit'n'run refactorers!
1074 my $infile = new File::Temp(TEMPLATE => "ikiwiki-po-filter-in.XXXXXXXXXX",
1075 DIR => File::Spec->tmpdir,
1076 UNLINK => 1)->filename;
1077 my $outfile = new File::Temp(TEMPLATE => "ikiwiki-po-filter-out.XXXXXXXXXX",
1078 DIR => File::Spec->tmpdir,
1079 UNLINK => 1)->filename;
1081 my $fail = sub ($) {
1082 my $msg = "po(po_to_markup) - $page : " . shift;
1087 error($msg, sub { unlink $infile, $outfile});
1090 writefile(basename($infile), File::Spec->tmpdir, $content)
1091 or return $fail->(sprintf(gettext("failed to write %s"), $infile));
1093 my $masterfile = srcfile($pagesources{masterpage($page)});
1095 "markdown" => (pagetype($masterfile) eq 'mdwn') ? 1 : 0,
1097 my $doc=Locale::Po4a::Chooser::new('text',%options);
1099 'po_in_name' => [ $infile ],
1100 'file_in_name' => [ $masterfile ],
1101 'file_in_charset' => 'utf-8',
1102 'file_out_charset' => 'utf-8',
1103 ) or return $fail->(gettext("failed to translate"));
1104 $doc->write($outfile)
1105 or return $fail->(sprintf(gettext("failed to write %s"), $outfile));
1107 $content = readfile($outfile)
1108 or return $fail->(sprintf(gettext("failed to read %s"), $outfile));
1110 # Unlinking should happen automatically, thanks to File::Temp,
1111 # but it does not work here, probably because of the way writefile()
1112 # and Locale::Po4a::write() work.
1113 unlink $infile, $outfile;
1118 # returns a SuccessReason or FailReason object
1120 my $content = shift;
1122 # NB: we don't use po_to_markup here, since Po4a parser does
1123 # not mind invalid PO content
1124 $content = '' unless defined $content;
1125 $content = decode_utf8(encode_utf8($content));
1127 # There are incompatibilities between some File::Temp versions
1128 # (including 0.18, bundled with Lenny's perl-modules package)
1129 # and others (e.g. 0.20, previously present in the archive as
1130 # a standalone package): under certain circumstances, some
1131 # return a relative filename, whereas others return an absolute one;
1132 # we here use this module in a way that is at least compatible
1133 # with 0.18 and 0.20. Beware, hit'n'run refactorers!
1134 my $infile = new File::Temp(TEMPLATE => "ikiwiki-po-isvalidpo.XXXXXXXXXX",
1135 DIR => File::Spec->tmpdir,
1136 UNLINK => 1)->filename;
1138 my $fail = sub ($) {
1139 my $msg = '[po/isvalidpo] ' . shift;
1141 return IkiWiki::FailReason->new("$msg");
1144 writefile(basename($infile), File::Spec->tmpdir, $content)
1145 or return $fail->(sprintf(gettext("failed to write %s"), $infile));
1147 my $res = (system("msgfmt", "--check", $infile, "-o", "/dev/null") == 0);
1149 # Unlinking should happen automatically, thanks to File::Temp,
1150 # but it does not work here, probably because of the way writefile()
1151 # and Locale::Po4a::write() work.
1155 return IkiWiki::SuccessReason->new("valid gettext data");
1157 return IkiWiki::FailReason->new(gettext("invalid gettext data, go back ".
1158 "to previous page to continue edit"));
1165 package IkiWiki::PageSpec;
1167 sub match_istranslation ($;@) {
1170 if (IkiWiki::Plugin::po::istranslation($page)) {
1171 return IkiWiki::SuccessReason->new("is a translation page");
1174 return IkiWiki::FailReason->new("is not a translation page");
1178 sub match_istranslatable ($;@) {
1181 if (IkiWiki::Plugin::po::istranslatable($page)) {
1182 return IkiWiki::SuccessReason->new("is set as translatable in po_translatable_pages");
1185 return IkiWiki::FailReason->new("is not set as translatable in po_translatable_pages");
1189 sub match_lang ($$;@) {
1193 my $regexp=IkiWiki::glob2re($wanted);
1194 my $lang=IkiWiki::Plugin::po::lang($page);
1195 if ($lang !~ /^$regexp$/i) {
1196 return IkiWiki::FailReason->new("file language is $lang, not $wanted");
1199 return IkiWiki::SuccessReason->new("file language is $wanted");
1203 sub match_currentlang ($$;@) {
1208 return IkiWiki::FailReason->new("no location provided") unless exists $params{location};
1210 my $currentlang=IkiWiki::Plugin::po::lang($params{location});
1211 my $lang=IkiWiki::Plugin::po::lang($page);
1213 if ($lang eq $currentlang) {
1214 return IkiWiki::SuccessReason->new("file language is the same as current one, i.e. $currentlang");
1217 return IkiWiki::FailReason->new("file language is $lang, whereas current language is $currentlang");