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{'bestlink'}=\&IkiWiki::bestlink;
55 inject(name => "IkiWiki::bestlink", call => \&mybestlink);
56 $origsubs{'beautify_urlpath'}=\&IkiWiki::beautify_urlpath;
57 inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath);
58 $origsubs{'targetpage'}=\&IkiWiki::targetpage;
59 inject(name => "IkiWiki::targetpage", call => \&mytargetpage);
60 $origsubs{'urlto'}=\&IkiWiki::urlto;
61 inject(name => "IkiWiki::urlto", call => \&myurlto);
62 $origsubs{'cgiurl'}=\&IkiWiki::cgiurl;
63 inject(name => "IkiWiki::cgiurl", call => \&mycgiurl);
64 $origsubs{'rootpage'}=\&IkiWiki::rootpage;
65 inject(name => "IkiWiki::rootpage", call => \&myrootpage);
74 # 2. Injected functions
75 # 3. Blackboxes for private data
88 rebuild => 1, # format plugin
91 po_master_language => {
97 description => "master language (non-PO files)",
101 po_slave_languages => {
108 description => "slave languages (PO files)",
112 po_translatable_pages => {
114 example => "* and !*/Discussion",
115 description => "PageSpec controlling which pages are translatable",
116 link => "ikiwiki/PageSpec",
122 example => "current",
123 description => "internal linking behavior (default/current/negotiated)",
130 foreach my $field (qw{po_master_language}) {
131 if (! exists $config{$field} || ! defined $config{$field}) {
132 error(sprintf(gettext("Must specify %s when using the %s plugin"),
139 or error(sprintf(gettext("%s is not a valid language code"), $_));
140 } ($config{po_master_language}{code}, keys %{$config{po_slave_languages}});
142 if (! exists $config{po_translatable_pages} ||
143 ! defined $config{po_translatable_pages}) {
144 $config{po_translatable_pages}="";
146 if (! exists $config{po_link_to} ||
147 ! defined $config{po_link_to}) {
148 $config{po_link_to}='default';
150 elsif ($config{po_link_to} !~ /^(default|current|negotiated)$/) {
151 warn(sprintf(gettext('%s is not a valid value for po_link_to, falling back to po_link_to=default'),
152 $config{po_link_to}));
153 $config{po_link_to}='default';
155 elsif ($config{po_link_to} eq "negotiated" && ! $config{usedirs}) {
156 warn(gettext('po_link_to=negotiated requires usedirs to be enabled, falling back to po_link_to=default'));
157 $config{po_link_to}='default';
160 push @{$config{wiki_file_prune_regexps}}, qr/\.pot$/;
162 # Translated versions of the underlays are added if available.
163 foreach my $underlay ("basewiki",
164 map { m/^\Q$config{underlaydirbase}\E\/*(.*)/ }
165 reverse @{$config{underlaydirs}}) {
166 next if $underlay=~/^locale\//;
168 # Underlays containing the po files for slave languages.
169 foreach my $ll (keys %{$config{po_slave_languages}}) {
170 add_underlay("po/$ll/$underlay")
171 if -d "$config{underlaydirbase}/po/$ll/$underlay";
174 if ($config{po_master_language}{code} ne 'en') {
175 # Add underlay containing translated source files
176 # for the master language.
177 add_underlay("locale/$config{po_master_language}{code}/$underlay");
183 my $needsbuild=shift;
185 # backup @needsbuild content so that change() can know whether
186 # a given master page was rendered because its source file was changed
187 @origneedsbuild=(@$needsbuild);
190 buildtranslationscache();
192 # make existing translations depend on the corresponding master page
193 foreach my $master (keys %translations) {
194 map add_depends($_, $master), values %{otherlanguages($master)};
198 # Massage the recorded state of internal links so that:
199 # - it matches the actually generated links, rather than the links as written
200 # in the pages' source
201 # - backlinks are consistent in all cases
204 my $page=$params{page};
205 my $content=$params{content};
207 if (istranslation($page)) {
208 foreach my $destpage (@{$links{$page}}) {
209 if (istranslatable($destpage)) {
210 # replace the occurence of $destpage in $links{$page}
211 for (my $i=0; $i<@{$links{$page}}; $i++) {
212 if (@{$links{$page}}[$i] eq $destpage) {
213 @{$links{$page}}[$i] = $destpage . '.' . lang($page);
220 elsif (! istranslatable($page) && ! istranslation($page)) {
221 foreach my $destpage (@{$links{$page}}) {
222 if (istranslatable($destpage)) {
223 # make sure any destpage's translations has
224 # $page in its backlinks
225 push @{$links{$page}},
226 values %{otherlanguages($destpage)};
232 # We use filter to convert PO to the master page's format,
233 # since the rest of ikiwiki should not work on PO files.
237 my $page = $params{page};
238 my $destpage = $params{destpage};
239 my $content = $params{content};
240 if (istranslation($page) && ! alreadyfiltered($page, $destpage)) {
241 $content = po_to_markup($page, $content);
242 setalreadyfiltered($page, $destpage);
250 my $page = $params{page};
251 my $content = $params{content};
253 # ignore PO files this plugin did not create
254 return $content unless istranslation($page);
256 # force content to be htmlize'd as if it was the same type as the master page
257 return IkiWiki::htmlize($page, $page,
258 pagetype(srcfile($pagesources{masterpage($page)})),
262 sub pagetemplate (@) {
264 my $page=$params{page};
265 my $destpage=$params{destpage};
266 my $template=$params{template};
268 my ($masterpage, $lang) = istranslation($page);
270 if (istranslation($page) && $template->query(name => "percenttranslated")) {
271 $template->param(percenttranslated => percenttranslated($page));
273 if ($template->query(name => "istranslation")) {
274 $template->param(istranslation => scalar istranslation($page));
276 if ($template->query(name => "istranslatable")) {
277 $template->param(istranslatable => istranslatable($page));
279 if ($template->query(name => "HOMEPAGEURL")) {
280 $template->param(homepageurl => homepageurl($page));
282 if ($template->query(name => "otherlanguages")) {
283 $template->param(otherlanguages => [otherlanguagesloop($page)]);
284 map add_depends($page, $_), (values %{otherlanguages($page)});
286 if ($config{discussion} && istranslation($page)) {
287 if ($page !~ /.*\/\Q$config{discussionpage}\E$/i &&
288 (length $config{cgiurl} ||
289 exists $links{$masterpage."/".lc($config{discussionpage})})) {
290 $template->param('discussionlink' => htmllink(
293 $masterpage . '/' . $config{discussionpage},
296 linktext => $config{discussionpage},
300 # Remove broken parentlink to ./index.html on home page's translations.
301 # It works because this hook has the "last" parameter set, to ensure it
302 # runs after parentlinks' own pagetemplate hook.
303 if ($template->param('parentlinks')
304 && istranslation($page)
305 && $masterpage eq "index") {
306 $template->param('parentlinks' => []);
308 if (ishomepage($page) && $template->query(name => "title")) {
309 $template->param(title => $config{wikiname});
313 # Add the renamed page translations to the list of to-be-renamed pages.
314 sub renamepages (@) {
317 my %torename = %{$params{torename}};
318 my $session = $params{session};
320 # Save the page(s) the user asked to rename, so that our
321 # canrename hook can tell the difference between:
322 # - a translation being renamed as a consequence of its master page
324 # - a user trying to directly rename a translation
325 # This is why this hook has to be run first, before the list of pages
326 # to rename is modified by other plugins.
328 @orig_torename=@{$session->param("po_orig_torename")}
329 if defined $session->param("po_orig_torename");
330 push @orig_torename, $torename{src};
331 $session->param(po_orig_torename => \@orig_torename);
332 IkiWiki::cgi_savesession($session);
334 return () unless istranslatable($torename{src});
337 my %otherpages=%{otherlanguages($torename{src})};
338 while (my ($lang, $otherpage) = each %otherpages) {
341 srcfile => $pagesources{$otherpage},
342 dest => otherlanguage($torename{dest}, $lang),
343 destfile => $torename{dest}.".".$lang.".po",
353 map { deletetranslations($_) } grep istranslatablefile($_), @deleted;
359 # All meta titles are first extracted at scan time, i.e. before we turn
360 # PO files back into translated markdown; escaping of double-quotes in
361 # PO files breaks the meta plugin's parsing enough to save ugly titles
362 # to %pagestate at this time.
364 # Then, at render time, every page passes in turn through the Great
365 # Rendering Chain (filter->preprocess->linkify->htmlize), and the meta
366 # plugin's preprocess hook is this time in a position to correctly
367 # extract the titles from slave pages.
369 # This is, unfortunately, too late: if the page A, linking to the page
370 # B, is rendered before B, it will display the wrongly-extracted meta
371 # title as the link text to B.
373 # On the one hand, such a corner case only happens on rebuild: on
374 # refresh, every rendered page is fixed to contain correct meta titles.
375 # On the other hand, it can take some time to get every page fixed.
376 # We therefore re-render every rendered page after a rebuild to fix them
377 # at once. As this more or less doubles the time needed to rebuild the
378 # wiki, we do so only when really needed.
381 && exists $config{rebuild} && defined $config{rebuild} && $config{rebuild}
382 && UNIVERSAL::can("IkiWiki::Plugin::meta", "getsetup")
383 && exists $config{meta_overrides_page_title}
384 && defined $config{meta_overrides_page_title}
385 && $config{meta_overrides_page_title}) {
386 debug(sprintf(gettext("rebuilding all pages to fix meta titles")));
387 resetalreadyfiltered();
388 require IkiWiki::Render;
389 foreach my $file (@rendered) {
390 IkiWiki::render($file, sprintf(gettext("building %s"), $file));
394 my $updated_po_files=0;
396 # Refresh/create POT and PO files as needed.
397 foreach my $file (grep {istranslatablefile($_)} @rendered) {
398 my $masterfile=srcfile($file);
399 my $page=pagename($file);
400 my $updated_pot_file=0;
402 # Avoid touching underlay files.
403 next if $masterfile ne "$config{srcdir}/$file";
405 # Only refresh POT file if it does not exist, or if
406 # the source was changed: don't if only the HTML was
407 # refreshed, e.g. because of a dependency.
408 if ((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 sub mybestlink ($$) {
567 return $origsubs{'bestlink'}->($page, $link)
568 if $config{po_link_to} eq "default";
570 my $res=$origsubs{'bestlink'}->(masterpage($page), $link);
571 my @caller = caller(1);
573 && istranslatable($res)
574 && istranslation($page)
575 && !(exists $caller[3] && defined $caller[3]
576 && ($caller[3] eq "IkiWiki::PageSpec::match_link"))) {
577 return $res . "." . lang($page);
582 sub mybeautify_urlpath ($) {
585 my $res=$origsubs{'beautify_urlpath'}->($url);
586 if ($config{po_link_to} eq "negotiated") {
587 $res =~ s!/\Qindex.$config{po_master_language}{code}.$config{htmlext}\E$!/!;
588 $res =~ s!/\Qindex.$config{htmlext}\E$!/!;
590 $res =~ s!/\Qindex.$_.$config{htmlext}\E$!/!;
591 } (keys %{$config{po_slave_languages}});
596 sub mytargetpage ($$) {
600 if (istranslation($page) || istranslatable($page)) {
601 my ($masterpage, $lang) = (masterpage($page), lang($page));
602 if (! $config{usedirs} || $masterpage eq 'index') {
603 return $masterpage . "." . $lang . "." . $ext;
606 return $masterpage . "/index." . $lang . "." . $ext;
609 return $origsubs{'targetpage'}->($page, $ext);
617 # workaround hard-coded /index.$config{htmlext} in IkiWiki::urlto()
619 && $config{po_link_to} eq "current"
620 && istranslatable('index')) {
621 return IkiWiki::beautify_urlpath(IkiWiki::baseurl($from) . "index." . lang($from) . ".$config{htmlext}");
623 # avoid using our injected beautify_urlpath if run by cgi_editpage,
624 # so that one is redirected to the just-edited page rather than to the
625 # negociated translation; to prevent unnecessary fiddling with caller/inject,
626 # we only do so when our beautify_urlpath would actually do what we want to
627 # avoid, i.e. when po_link_to = negotiated.
628 # also avoid doing so when run by cgi_goto, so that the links on recentchanges
629 # page actually lead to the exact page they pretend to.
630 if ($config{po_link_to} eq "negotiated") {
631 my @caller = caller(1);
633 $use_orig = 1 if (exists $caller[3] && defined $caller[3]
634 && ($caller[3] eq "IkiWiki::cgi_editpage" ||
635 $caller[3] eq "IkiWiki::Plugin::goto::cgi_goto")
637 inject(name => "IkiWiki::beautify_urlpath", call => $origsubs{'beautify_urlpath'})
639 my $res = $origsubs{'urlto'}->($to,$from,$absolute);
640 inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath)
645 return $origsubs{'urlto'}->($to,$from,$absolute)
652 # slave pages have no subpages
653 if (istranslation($params{'from'})) {
654 $params{'from'} = masterpage($params{'from'});
656 return $origsubs{'cgiurl'}->(%params);
663 if (exists $params{rootpage}) {
664 $rootpage=$origsubs{'bestlink'}->($params{page}, $params{rootpage});
665 if (!length $rootpage) {
666 $rootpage=$params{rootpage};
670 $rootpage=masterpage($params{page});
676 # | Blackboxes for private data
682 sub alreadyfiltered($$) {
686 return exists $filtered{$page}{$destpage}
687 && $filtered{$page}{$destpage} eq 1;
690 sub setalreadyfiltered($$) {
694 $filtered{$page}{$destpage}=1;
697 sub unsetalreadyfiltered($$) {
701 if (exists $filtered{$page}{$destpage}) {
702 delete $filtered{$page}{$destpage};
706 sub resetalreadyfiltered() {
715 sub maybe_add_leading_slash ($;$) {
718 $add=1 unless defined $add;
719 return '/' . $str if $add;
723 sub istranslatablefile ($) {
726 return 0 unless defined $file;
727 my $type=pagetype($file);
728 return 0 if ! defined $type || $type eq 'po';
729 return 0 if $file =~ /\.pot$/;
730 return 1 if pagespec_match(pagename($file), $config{po_translatable_pages});
734 sub istranslatable ($) {
738 return 1 if istranslatablefile($pagesources{$page});
742 sub _istranslation ($) {
745 $page='' unless defined $page && length $page;
746 my $hasleadingslash = ($page=~s#^/##);
747 my $file=$pagesources{$page};
748 return 0 unless defined $file
749 && defined pagetype($file)
750 && pagetype($file) eq 'po';
751 return 0 if $file =~ /\.pot$/;
753 my ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
754 return 0 unless defined $masterpage && defined $lang
755 && length $masterpage && length $lang
756 && defined $pagesources{$masterpage}
757 && defined $config{po_slave_languages}{$lang};
759 return (maybe_add_leading_slash($masterpage, $hasleadingslash), $lang)
760 if istranslatable($masterpage);
763 sub istranslation ($) {
766 if (1 < (my ($masterpage, $lang) = _istranslation($page))) {
767 my $hasleadingslash = ($masterpage=~s#^/##);
768 $translations{$masterpage}{$lang}=$page unless exists $translations{$masterpage}{$lang};
769 return (maybe_add_leading_slash($masterpage, $hasleadingslash), $lang);
777 if ( 1 < (my ($masterpage, $lang) = _istranslation($page))) {
786 if (1 < (my ($masterpage, $lang) = _istranslation($page))) {
789 return $config{po_master_language}{code};
792 sub islanguagecode ($) {
795 return $code =~ /^[a-z]{2}$/;
798 sub otherlanguage ($$) {
802 return masterpage($page) if $code eq $config{po_master_language}{code};
803 return masterpage($page) . '.' . $code;
806 sub otherlanguages ($) {
810 return \%ret unless istranslation($page) || istranslatable($page);
811 my $curlang=lang($page);
813 ($config{po_master_language}{code}, keys %{$config{po_slave_languages}}) {
814 next if $lang eq $curlang;
815 $ret{$lang}=otherlanguage($page, $lang);
821 my $masterfile=shift;
823 (my $name, my $dir, my $suffix) = fileparse($masterfile, qr/\.[^.]*/);
824 $dir='' if $dir eq './';
825 return File::Spec->catpath('', $dir, $name . ".pot");
829 my $masterfile=shift;
832 (my $name, my $dir, my $suffix) = fileparse($masterfile, qr/\.[^.]*/);
833 $dir='' if $dir eq './';
834 return File::Spec->catpath('', $dir, $name . "." . $lang . ".po");
838 my $masterfile=shift;
840 return map pofile($masterfile, $_), (keys %{$config{po_slave_languages}});
844 my $masterfile=shift;
846 my $potfile=potfile($masterfile);
847 my %options = ("markdown" => (pagetype($masterfile) eq 'mdwn') ? 1 : 0);
848 my $doc=Locale::Po4a::Chooser::new('text',%options);
849 $doc->{TT}{utf_mode} = 1;
850 $doc->{TT}{file_in_charset} = 'utf-8';
851 $doc->{TT}{file_out_charset} = 'utf-8';
852 $doc->read($masterfile);
853 # let's cheat a bit to force porefs option to be passed to
854 # Locale::Po4a::Po; this is undocument use of internal
855 # Locale::Po4a::TransTractor's data, compulsory since this module
856 # prevents us from using the porefs option.
857 $doc->{TT}{po_out}=Locale::Po4a::Po->new({ 'porefs' => 'none' });
858 $doc->{TT}{po_out}->set_charset('utf-8');
861 IkiWiki::prep_writefile(basename($potfile),dirname($potfile));
862 $doc->writepo($potfile);
865 sub refreshpofiles ($@) {
866 my $masterfile=shift;
869 my $potfile=potfile($masterfile);
871 error("po(refreshpofiles) ".sprintf(gettext("POT file (%s) does not exist"), $potfile));
874 foreach my $pofile (@pofiles) {
875 IkiWiki::prep_writefile(basename($pofile),dirname($pofile));
878 # If the po file exists in an underlay, copy it
880 my ($pobase)=$pofile=~/^\Q$config{srcdir}\E\/?(.*)$/;
881 foreach my $dir (@{$config{underlaydirs}}) {
882 if (-e "$dir/$pobase") {
883 File::Copy::syscopy("$dir/$pobase",$pofile)
884 or error("po(refreshpofiles) ".
885 sprintf(gettext("failed to copy underlay PO file to %s"),
892 system("msgmerge", "--previous", "-q", "-U", "--backup=none", $pofile, $potfile) == 0
893 or error("po(refreshpofiles) ".
894 sprintf(gettext("failed to update %s"),
898 File::Copy::syscopy($potfile,$pofile)
899 or error("po(refreshpofiles) ".
900 sprintf(gettext("failed to copy the POT file to %s"),
906 sub buildtranslationscache() {
907 # use istranslation's side-effect
908 map istranslation($_), (keys %pagesources);
911 sub resettranslationscache() {
915 sub flushmemoizecache() {
916 Memoize::flush_cache("istranslatable");
917 Memoize::flush_cache("_istranslation");
918 Memoize::flush_cache("percenttranslated");
921 sub urlto_with_orig_beautiful_urlpath($$) {
925 inject(name => "IkiWiki::beautify_urlpath", call => $origsubs{'beautify_urlpath'});
926 my $res=urlto($to, $from);
927 inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath);
932 sub percenttranslated ($) {
936 return gettext("N/A") unless istranslation($page);
937 my $file=srcfile($pagesources{$page});
938 my $masterfile = srcfile($pagesources{masterpage($page)});
940 "markdown" => (pagetype($masterfile) eq 'mdwn') ? 1 : 0,
942 my $doc=Locale::Po4a::Chooser::new('text',%options);
944 'po_in_name' => [ $file ],
945 'file_in_name' => [ $masterfile ],
946 'file_in_charset' => 'utf-8',
947 'file_out_charset' => 'utf-8',
948 ) or error("po(percenttranslated) ".
949 sprintf(gettext("failed to translate %s"), $page));
950 my ($percent,$hit,$queries) = $doc->stats();
951 $percent =~ s/\.[0-9]+$//;
955 sub languagename ($) {
958 return $config{po_master_language}{name}
959 if $code eq $config{po_master_language}{code};
960 return $config{po_slave_languages}{$code}
961 if defined $config{po_slave_languages}{$code};
965 sub otherlanguagesloop ($) {
969 my %otherpages=%{otherlanguages($page)};
970 while (my ($lang, $otherpage) = each %otherpages) {
971 if (istranslation($page) && masterpage($page) eq $otherpage) {
973 url => urlto_with_orig_beautiful_urlpath($otherpage, $page),
975 language => languagename($lang),
979 elsif (istranslation($otherpage)) {
981 url => urlto_with_orig_beautiful_urlpath($otherpage, $page),
983 language => languagename($lang),
984 percent => percenttranslated($otherpage),
989 return -1 if $a->{code} eq $config{po_master_language}{code};
990 return 1 if $b->{code} eq $config{po_master_language}{code};
991 return $a->{language} cmp $b->{language};
995 sub homepageurl (;$) {
998 return urlto('', $page);
1001 sub ishomepage ($) {
1004 return 1 if $page eq 'index';
1005 map { return 1 if $page eq 'index.'.$_ } keys %{$config{po_slave_languages}};
1009 sub deletetranslations ($) {
1010 my $deletedmasterfile=shift;
1012 my $deletedmasterpage=pagename($deletedmasterfile);
1015 my $file = newpagefile($deletedmasterpage.'.'.$_, 'po');
1016 my $absfile = "$config{srcdir}/$file";
1017 if (-e $absfile && ! -l $absfile && ! -d $absfile) {
1018 push @todelete, $file;
1020 } keys %{$config{po_slave_languages}};
1024 IkiWiki::rcs_remove($_);
1027 IkiWiki::prune("$config{srcdir}/$_");
1033 gettext("removed obsolete PO files"),
1034 "IkiWiki::Plugin::po::deletetranslations");
1038 sub commit_and_refresh ($$) {
1039 my ($msg, $author) = (shift, shift);
1042 IkiWiki::disable_commit_hook();
1043 IkiWiki::rcs_commit_staged($msg, $author, "127.0.0.1");
1044 IkiWiki::enable_commit_hook();
1045 IkiWiki::rcs_update();
1047 # Reinitialize module's private variables.
1048 resetalreadyfiltered();
1049 resettranslationscache();
1050 flushmemoizecache();
1051 # Trigger a wiki refresh.
1052 require IkiWiki::Render;
1053 # without preliminary saveindex/loadindex, refresh()
1054 # complains about a lot of uninitialized variables
1055 IkiWiki::saveindex();
1056 IkiWiki::loadindex();
1058 IkiWiki::saveindex();
1061 sub po_to_markup ($$) {
1062 my ($page, $content) = (shift, shift);
1064 $content = '' unless defined $content;
1065 $content = decode_utf8(encode_utf8($content));
1066 # CRLF line terminators make poor Locale::Po4a feel bad
1067 $content=~s/\r\n/\n/g;
1069 # There are incompatibilities between some File::Temp versions
1070 # (including 0.18, bundled with Lenny's perl-modules package)
1071 # and others (e.g. 0.20, previously present in the archive as
1072 # a standalone package): under certain circumstances, some
1073 # return a relative filename, whereas others return an absolute one;
1074 # we here use this module in a way that is at least compatible
1075 # with 0.18 and 0.20. Beware, hit'n'run refactorers!
1076 my $infile = new File::Temp(TEMPLATE => "ikiwiki-po-filter-in.XXXXXXXXXX",
1077 DIR => File::Spec->tmpdir,
1078 UNLINK => 1)->filename;
1079 my $outfile = new File::Temp(TEMPLATE => "ikiwiki-po-filter-out.XXXXXXXXXX",
1080 DIR => File::Spec->tmpdir,
1081 UNLINK => 1)->filename;
1083 my $fail = sub ($) {
1084 my $msg = "po(po_to_markup) - $page : " . shift;
1085 error($msg, sub { unlink $infile, $outfile});
1088 writefile(basename($infile), File::Spec->tmpdir, $content)
1089 or return $fail->(sprintf(gettext("failed to write %s"), $infile));
1091 my $masterfile = srcfile($pagesources{masterpage($page)});
1093 "markdown" => (pagetype($masterfile) eq 'mdwn') ? 1 : 0,
1095 my $doc=Locale::Po4a::Chooser::new('text',%options);
1097 'po_in_name' => [ $infile ],
1098 'file_in_name' => [ $masterfile ],
1099 'file_in_charset' => 'utf-8',
1100 'file_out_charset' => 'utf-8',
1101 ) or return $fail->(gettext("failed to translate"));
1102 $doc->write($outfile)
1103 or return $fail->(sprintf(gettext("failed to write %s"), $outfile));
1105 $content = readfile($outfile);
1107 # Unlinking should happen automatically, thanks to File::Temp,
1108 # but it does not work here, probably because of the way writefile()
1109 # and Locale::Po4a::write() work.
1110 unlink $infile, $outfile;
1115 # returns a SuccessReason or FailReason object
1117 my $content = shift;
1119 # NB: we don't use po_to_markup here, since Po4a parser does
1120 # not mind invalid PO content
1121 $content = '' unless defined $content;
1122 $content = decode_utf8(encode_utf8($content));
1124 # There are incompatibilities between some File::Temp versions
1125 # (including 0.18, bundled with Lenny's perl-modules package)
1126 # and others (e.g. 0.20, previously present in the archive as
1127 # a standalone package): under certain circumstances, some
1128 # return a relative filename, whereas others return an absolute one;
1129 # we here use this module in a way that is at least compatible
1130 # with 0.18 and 0.20. Beware, hit'n'run refactorers!
1131 my $infile = new File::Temp(TEMPLATE => "ikiwiki-po-isvalidpo.XXXXXXXXXX",
1132 DIR => File::Spec->tmpdir,
1133 UNLINK => 1)->filename;
1135 my $fail = sub ($) {
1136 my $msg = '[po/isvalidpo] ' . shift;
1138 return IkiWiki::FailReason->new("$msg");
1141 writefile(basename($infile), File::Spec->tmpdir, $content)
1142 or return $fail->(sprintf(gettext("failed to write %s"), $infile));
1144 my $res = (system("msgfmt", "--check", $infile, "-o", "/dev/null") == 0);
1146 # Unlinking should happen automatically, thanks to File::Temp,
1147 # but it does not work here, probably because of the way writefile()
1148 # and Locale::Po4a::write() work.
1152 return IkiWiki::SuccessReason->new("valid gettext data");
1154 return IkiWiki::FailReason->new(gettext("invalid gettext data, go back ".
1155 "to previous page to continue edit"));
1162 package IkiWiki::PageSpec;
1164 sub match_istranslation ($;@) {
1167 if (IkiWiki::Plugin::po::istranslation($page)) {
1168 return IkiWiki::SuccessReason->new("is a translation page");
1171 return IkiWiki::FailReason->new("is not a translation page");
1175 sub match_istranslatable ($;@) {
1178 if (IkiWiki::Plugin::po::istranslatable($page)) {
1179 return IkiWiki::SuccessReason->new("is set as translatable in po_translatable_pages");
1182 return IkiWiki::FailReason->new("is not set as translatable in po_translatable_pages");
1186 sub match_lang ($$;@) {
1190 my $regexp=IkiWiki::glob2re($wanted);
1191 my $lang=IkiWiki::Plugin::po::lang($page);
1192 if ($lang !~ /^$regexp$/i) {
1193 return IkiWiki::FailReason->new("file language is $lang, not $wanted");
1196 return IkiWiki::SuccessReason->new("file language is $wanted");
1200 sub match_currentlang ($$;@) {
1205 return IkiWiki::FailReason->new("no location provided") unless exists $params{location};
1207 my $currentlang=IkiWiki::Plugin::po::lang($params{location});
1208 my $lang=IkiWiki::Plugin::po::lang($page);
1210 if ($lang eq $currentlang) {
1211 return IkiWiki::SuccessReason->new("file language is the same as current one, i.e. $currentlang");
1214 return IkiWiki::FailReason->new("file language is $lang, whereas current language is $currentlang");