Merge branch 'master' of git://git.ikiwiki.info
[ikiwiki.git] / IkiWiki / Plugin / po.pm
blob0ae4adcfccc8f94a4c21ecbbc003b768617c9a19
1 #!/usr/bin/perl
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;
9 use warnings;
10 use strict;
11 use IkiWiki 3.00;
12 use Encode;
13 use Locale::Po4a::Common qw(nowrapi18n !/.*/);
14 use Locale::Po4a::Chooser;
15 use Locale::Po4a::Po;
16 use File::Basename;
17 use File::Copy;
18 use File::Spec;
19 use File::Temp;
20 use Memoize;
21 use UNIVERSAL;
23 my %translations;
24 my @origneedsbuild;
25 my %origsubs;
27 memoize("istranslatable");
28 memoize("_istranslation");
29 memoize("percenttranslated");
31 sub import {
32 hook(type => "getsetup", id => "po", call => \&getsetup);
33 hook(type => "checkconfig", id => "po", call => \&checkconfig);
34 hook(type => "needsbuild", id => "po", call => \&needsbuild);
35 hook(type => "scan", id => "po", call => \&scan, last => 1);
36 hook(type => "filter", id => "po", call => \&filter);
37 hook(type => "htmlize", id => "po", call => \&htmlize);
38 hook(type => "pagetemplate", id => "po", call => \&pagetemplate, last => 1);
39 hook(type => "rename", id => "po", call => \&renamepages, first => 1);
40 hook(type => "delete", id => "po", call => \&mydelete);
41 hook(type => "change", id => "po", call => \&change);
42 hook(type => "checkcontent", id => "po", call => \&checkcontent);
43 hook(type => "canremove", id => "po", call => \&canremove);
44 hook(type => "canrename", id => "po", call => \&canrename);
45 hook(type => "editcontent", id => "po", call => \&editcontent);
46 hook(type => "formbuilder_setup", id => "po", call => \&formbuilder_setup, last => 1);
47 hook(type => "formbuilder", id => "po", call => \&formbuilder);
49 $origsubs{'bestlink'}=\&IkiWiki::bestlink;
50 inject(name => "IkiWiki::bestlink", call => \&mybestlink);
51 $origsubs{'beautify_urlpath'}=\&IkiWiki::beautify_urlpath;
52 inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath);
53 $origsubs{'targetpage'}=\&IkiWiki::targetpage;
54 inject(name => "IkiWiki::targetpage", call => \&mytargetpage);
55 $origsubs{'urlto'}=\&IkiWiki::urlto;
56 inject(name => "IkiWiki::urlto", call => \&myurlto);
57 $origsubs{'cgiurl'}=\&IkiWiki::cgiurl;
58 inject(name => "IkiWiki::cgiurl", call => \&mycgiurl);
62 # ,----
63 # | Table of contents
64 # `----
66 # 1. Hooks
67 # 2. Injected functions
68 # 3. Blackboxes for private data
69 # 4. Helper functions
70 # 5. PageSpecs
73 # ,----
74 # | Hooks
75 # `----
77 sub getsetup () {
78 return
79 plugin => {
80 safe => 0,
81 rebuild => 1,
83 po_master_language => {
84 type => "string",
85 example => {
86 'code' => 'en',
87 'name' => 'English'
89 description => "master language (non-PO files)",
90 safe => 1,
91 rebuild => 1,
93 po_slave_languages => {
94 type => "string",
95 example => {
96 'fr' => 'Français',
97 'es' => 'Castellano',
98 'de' => 'Deutsch'
100 description => "slave languages (PO files)",
101 safe => 1,
102 rebuild => 1,
104 po_translatable_pages => {
105 type => "pagespec",
106 example => "* and !*/Discussion",
107 description => "PageSpec controlling which pages are translatable",
108 link => "ikiwiki/PageSpec",
109 safe => 1,
110 rebuild => 1,
112 po_link_to => {
113 type => "string",
114 example => "current",
115 description => "internal linking behavior (default/current/negotiated)",
116 safe => 1,
117 rebuild => 1,
121 sub checkconfig () {
122 foreach my $field (qw{po_master_language}) {
123 if (! exists $config{$field} || ! defined $config{$field}) {
124 error(sprintf(gettext("Must specify %s when using the %s plugin"),
125 $field, 'po'));
129 map {
130 islanguagecode($_)
131 or error(sprintf(gettext("%s is not a valid language code"), $_));
132 } ($config{po_master_language}{code}, keys %{$config{po_slave_languages}});
134 if (! exists $config{po_translatable_pages} ||
135 ! defined $config{po_translatable_pages}) {
136 $config{po_translatable_pages}="";
138 if (! exists $config{po_link_to} ||
139 ! defined $config{po_link_to}) {
140 $config{po_link_to}='default';
142 elsif ($config{po_link_to} !~ /^(default|current|negotiated)$/) {
143 warn(sprintf(gettext('%s is not a valid value for po_link_to, falling back to po_link_to=default'),
144 $config{po_link_to}));
145 $config{po_link_to}='default';
147 elsif ($config{po_link_to} eq "negotiated" && ! $config{usedirs}) {
148 warn(gettext('po_link_to=negotiated requires usedirs to be enabled, falling back to po_link_to=default'));
149 $config{po_link_to}='default';
152 push @{$config{wiki_file_prune_regexps}}, qr/\.pot$/;
154 # Translated versions of the underlays are added if available.
155 foreach my $underlay ("basewiki",
156 map { m/^\Q$config{underlaydirbase}\E\/*(.*)/ }
157 reverse @{$config{underlaydirs}}) {
158 next if $underlay=~/^locale\//;
160 # Underlays containing the po files for slave languages.
161 foreach my $ll (keys %{$config{po_slave_languages}}) {
162 add_underlay("po/$ll/$underlay")
163 if -d "$config{underlaydirbase}/po/$ll/$underlay";
166 if ($config{po_master_language}{code} ne 'en') {
167 # Add underlay containing translated source files
168 # for the master language.
169 add_underlay("locale/$config{po_master_language}{code}/$underlay");
174 sub needsbuild () {
175 my $needsbuild=shift;
177 # backup @needsbuild content so that change() can know whether
178 # a given master page was rendered because its source file was changed
179 @origneedsbuild=(@$needsbuild);
181 flushmemoizecache();
182 buildtranslationscache();
184 # make existing translations depend on the corresponding master page
185 foreach my $master (keys %translations) {
186 map add_depends($_, $master), values %{otherlanguages($master)};
190 # Massage the recorded state of internal links so that:
191 # - it matches the actually generated links, rather than the links as written
192 # in the pages' source
193 # - backlinks are consistent in all cases
194 sub scan (@) {
195 my %params=@_;
196 my $page=$params{page};
197 my $content=$params{content};
199 if (istranslation($page)) {
200 foreach my $destpage (@{$links{$page}}) {
201 if (istranslatable($destpage)) {
202 # replace one occurence of $destpage in $links{$page}
203 # (we only want to replace the one that was added by
204 # IkiWiki::Plugin::link::scan, other occurences may be
205 # there for other reasons)
206 for (my $i=0; $i<@{$links{$page}}; $i++) {
207 if (@{$links{$page}}[$i] eq $destpage) {
208 @{$links{$page}}[$i] = $destpage . '.' . lang($page);
209 last;
215 elsif (! istranslatable($page) && ! istranslation($page)) {
216 foreach my $destpage (@{$links{$page}}) {
217 if (istranslatable($destpage)) {
218 # make sure any destpage's translations has
219 # $page in its backlinks
220 push @{$links{$page}},
221 values %{otherlanguages($destpage)};
227 # We use filter to convert PO to the master page's format,
228 # since the rest of ikiwiki should not work on PO files.
229 sub filter (@) {
230 my %params = @_;
232 my $page = $params{page};
233 my $destpage = $params{destpage};
234 my $content = $params{content};
235 if (istranslation($page) && ! alreadyfiltered($page, $destpage)) {
236 $content = po_to_markup($page, $content);
237 setalreadyfiltered($page, $destpage);
239 return $content;
242 sub htmlize (@) {
243 my %params=@_;
245 my $page = $params{page};
246 my $content = $params{content};
248 # ignore PO files this plugin did not create
249 return $content unless istranslation($page);
251 # force content to be htmlize'd as if it was the same type as the master page
252 return IkiWiki::htmlize($page, $page,
253 pagetype(srcfile($pagesources{masterpage($page)})),
254 $content);
257 sub pagetemplate (@) {
258 my %params=@_;
259 my $page=$params{page};
260 my $destpage=$params{destpage};
261 my $template=$params{template};
263 my ($masterpage, $lang) = istranslation($page);
265 if (istranslation($page) && $template->query(name => "percenttranslated")) {
266 $template->param(percenttranslated => percenttranslated($page));
268 if ($template->query(name => "istranslation")) {
269 $template->param(istranslation => scalar istranslation($page));
271 if ($template->query(name => "istranslatable")) {
272 $template->param(istranslatable => istranslatable($page));
274 if ($template->query(name => "HOMEPAGEURL")) {
275 $template->param(homepageurl => homepageurl($page));
277 if ($template->query(name => "otherlanguages")) {
278 $template->param(otherlanguages => [otherlanguagesloop($page)]);
279 map add_depends($page, $_), (values %{otherlanguages($page)});
281 if ($config{discussion} && istranslation($page)) {
282 my $discussionlink=gettext("discussion");
283 if ($page !~ /.*\/\Q$discussionlink\E$/i &&
284 (length $config{cgiurl} ||
285 exists $links{$masterpage."/".$discussionlink})) {
286 $template->param('discussionlink' => htmllink(
287 $page,
288 $destpage,
289 $masterpage . '/' . gettext("Discussion"),
290 noimageinline => 1,
291 forcesubpage => 0,
292 linktext => gettext("Discussion"),
296 # Remove broken parentlink to ./index.html on home page's translations.
297 # It works because this hook has the "last" parameter set, to ensure it
298 # runs after parentlinks' own pagetemplate hook.
299 if ($template->param('parentlinks')
300 && istranslation($page)
301 && $masterpage eq "index") {
302 $template->param('parentlinks' => []);
304 } # }}}
306 # Add the renamed page translations to the list of to-be-renamed pages.
307 sub renamepages (@) {
308 my %params = @_;
310 my %torename = %{$params{torename}};
311 my $session = $params{session};
313 # Save the page(s) the user asked to rename, so that our
314 # canrename hook can tell the difference between:
315 # - a translation being renamed as a consequence of its master page
316 # being renamed
317 # - a user trying to directly rename a translation
318 # This is why this hook has to be run first, before the list of pages
319 # to rename is modified by other plugins.
320 my @orig_torename;
321 @orig_torename=@{$session->param("po_orig_torename")}
322 if defined $session->param("po_orig_torename");
323 push @orig_torename, $torename{src};
324 $session->param(po_orig_torename => \@orig_torename);
325 IkiWiki::cgi_savesession($session);
327 return () unless istranslatable($torename{src});
329 my @ret;
330 my %otherpages=%{otherlanguages($torename{src})};
331 while (my ($lang, $otherpage) = each %otherpages) {
332 push @ret, {
333 src => $otherpage,
334 srcfile => $pagesources{$otherpage},
335 dest => otherlanguage($torename{dest}, $lang),
336 destfile => $torename{dest}.".".$lang.".po",
337 required => 0,
340 return @ret;
343 sub mydelete (@) {
344 my @deleted=@_;
346 map { deletetranslations($_) } grep istranslatablefile($_), @deleted;
349 sub change (@) {
350 my @rendered=@_;
352 # All meta titles are first extracted at scan time, i.e. before we turn
353 # PO files back into translated markdown; escaping of double-quotes in
354 # PO files breaks the meta plugin's parsing enough to save ugly titles
355 # to %pagestate at this time.
357 # Then, at render time, every page passes in turn through the Great
358 # Rendering Chain (filter->preprocess->linkify->htmlize), and the meta
359 # plugin's preprocess hook is this time in a position to correctly
360 # extract the titles from slave pages.
362 # This is, unfortunately, too late: if the page A, linking to the page
363 # B, is rendered before B, it will display the wrongly-extracted meta
364 # title as the link text to B.
366 # On the one hand, such a corner case only happens on rebuild: on
367 # refresh, every rendered page is fixed to contain correct meta titles.
368 # On the other hand, it can take some time to get every page fixed.
369 # We therefore re-render every rendered page after a rebuild to fix them
370 # at once. As this more or less doubles the time needed to rebuild the
371 # wiki, we do so only when really needed.
373 if (@rendered
374 && exists $config{rebuild} && defined $config{rebuild} && $config{rebuild}
375 && UNIVERSAL::can("IkiWiki::Plugin::meta", "getsetup")
376 && exists $config{meta_overrides_page_title}
377 && defined $config{meta_overrides_page_title}
378 && $config{meta_overrides_page_title}) {
379 debug(sprintf(gettext("rebuilding all pages to fix meta titles")));
380 resetalreadyfiltered();
381 require IkiWiki::Render;
382 foreach my $file (@rendered) {
383 debug(sprintf(gettext("building %s"), $file));
384 IkiWiki::render($file);
388 my $updated_po_files=0;
390 # Refresh/create POT and PO files as needed.
391 # (But avoid doing so if they are in an underlay directory.)
392 foreach my $file (grep {istranslatablefile($_)} @rendered) {
393 my $masterfile=srcfile($file);
394 my $page=pagename($file);
395 my $updated_pot_file=0;
396 # Only refresh POT file if it does not exist, or if
397 # $pagesources{$page} was changed: don't if only the HTML was
398 # refreshed, e.g. because of a dependency.
399 if ($masterfile eq "$config{srcdir}/$file" &&
400 ((grep { $_ eq $pagesources{$page} } @origneedsbuild)
401 || ! -e potfile($masterfile))) {
402 refreshpot($masterfile);
403 $updated_pot_file=1;
405 my @pofiles;
406 foreach my $po (pofiles($masterfile)) {
407 next if ! $updated_pot_file && ! -e $po;
408 next if grep { $po=~/\Q$_\E/ } @{$config{underlaydirs}};
409 push @pofiles, $po;
411 if (@pofiles) {
412 refreshpofiles($masterfile, @pofiles);
413 map { IkiWiki::rcs_add($_) } @pofiles if $config{rcs};
414 $updated_po_files=1;
418 if ($updated_po_files) {
419 commit_and_refresh(
420 gettext("updated PO files"),
421 "IkiWiki::Plugin::po::change");
425 sub checkcontent (@) {
426 my %params=@_;
428 if (istranslation($params{page})) {
429 my $res = isvalidpo($params{content});
430 if ($res) {
431 return undef;
433 else {
434 return "$res";
437 return undef;
440 sub canremove (@) {
441 my %params = @_;
443 if (istranslation($params{page})) {
444 return gettext("Can not remove a translation. If the master page is removed, ".
445 "however, its translations will be removed as well.");
447 return undef;
450 sub canrename (@) {
451 my %params = @_;
452 my $session = $params{session};
454 if (istranslation($params{src})) {
455 my $masterpage = masterpage($params{src});
456 # Tell the difference between:
457 # - a translation being renamed as a consequence of its master page
458 # being renamed, which is allowed
459 # - a user trying to directly rename a translation, which is forbidden
460 # by looking for the master page in the list of to-be-renamed pages we
461 # saved early in the renaming process.
462 my $orig_torename = $session->param("po_orig_torename");
463 unless (grep { $_ eq $masterpage } @{$orig_torename}) {
464 return gettext("Can not rename a translation. If the master page is renamed, ".
465 "however, its translations will be renamed as well.");
468 return undef;
471 # As we're previewing or saving a page, the content may have
472 # changed, so tell the next filter() invocation it must not be lazy.
473 sub editcontent () {
474 my %params=@_;
476 unsetalreadyfiltered($params{page}, $params{page});
477 return $params{content};
480 sub formbuilder_setup (@) {
481 my %params=@_;
482 my $form=$params{form};
483 my $q=$params{cgi};
485 return unless defined $form->field("do");
487 if ($form->field("do") eq "create") {
488 # Warn the user: new pages must be written in master language.
489 my $template=template("pocreatepage.tmpl");
490 $template->param(LANG => $config{po_master_language}{name});
491 $form->tmpl_param(message => $template->output);
493 elsif ($form->field("do") eq "edit") {
494 # Remove the rename/remove buttons on slave pages.
495 # This has to be done after the rename/remove plugins have added
496 # their buttons, which is why this hook must be run last.
497 # The canrename/canremove hooks already ensure this is forbidden
498 # at the backend level, so this is only UI sugar.
499 if (istranslation($form->field("page"))) {
500 map {
501 for (my $i = 0; $i < @{$params{buttons}}; $i++) {
502 if (@{$params{buttons}}[$i] eq $_) {
503 delete @{$params{buttons}}[$i];
504 last;
507 } qw(Rename Remove);
512 sub formbuilder (@) {
513 my %params=@_;
514 my $form=$params{form};
515 my $q=$params{cgi};
517 return unless defined $form->field("do");
519 # Do not allow to create pages of type po: they are automatically created.
520 # The main reason to do so is to bypass the "favor the type of linking page
521 # on page creation" logic, which is unsuitable when a broken link is clicked
522 # on a slave (PO) page.
523 # This cannot be done in the formbuilder_setup hook as the list of types is
524 # computed later.
525 if ($form->field("do") eq "create") {
526 foreach my $field ($form->field) {
527 next unless "$field" eq "type";
528 if ($field->type eq 'select') {
529 # remove po from the list of types
530 my @types = grep { $_ ne 'po' } $field->options;
531 $field->options(\@types) if @types;
537 # ,----
538 # | Injected functions
539 # `----
541 # Implement po_link_to 'current' and 'negotiated' settings.
542 sub mybestlink ($$) {
543 my $page=shift;
544 my $link=shift;
546 my $res=$origsubs{'bestlink'}->(masterpage($page), $link);
547 if (length $res
548 && ($config{po_link_to} eq "current" || $config{po_link_to} eq "negotiated")
549 && istranslatable($res)
550 && istranslation($page)) {
551 return $res . "." . lang($page);
553 return $res;
556 sub mybeautify_urlpath ($) {
557 my $url=shift;
559 my $res=$origsubs{'beautify_urlpath'}->($url);
560 if ($config{po_link_to} eq "negotiated") {
561 $res =~ s!/\Qindex.$config{po_master_language}{code}.$config{htmlext}\E$!/!;
562 $res =~ s!/\Qindex.$config{htmlext}\E$!/!;
563 map {
564 $res =~ s!/\Qindex.$_.$config{htmlext}\E$!/!;
565 } (keys %{$config{po_slave_languages}});
567 return $res;
570 sub mytargetpage ($$) {
571 my $page=shift;
572 my $ext=shift;
574 if (istranslation($page) || istranslatable($page)) {
575 my ($masterpage, $lang) = (masterpage($page), lang($page));
576 if (! $config{usedirs} || $masterpage eq 'index') {
577 return $masterpage . "." . $lang . "." . $ext;
579 else {
580 return $masterpage . "/index." . $lang . "." . $ext;
583 return $origsubs{'targetpage'}->($page, $ext);
586 sub myurlto ($$;$) {
587 my $to=shift;
588 my $from=shift;
589 my $absolute=shift;
591 # workaround hard-coded /index.$config{htmlext} in IkiWiki::urlto()
592 if (! length $to
593 && $config{po_link_to} eq "current"
594 && istranslatable('index')) {
595 return IkiWiki::beautify_urlpath(IkiWiki::baseurl($from) . "index." . lang($from) . ".$config{htmlext}");
597 # avoid using our injected beautify_urlpath if run by cgi_editpage,
598 # so that one is redirected to the just-edited page rather than to the
599 # negociated translation; to prevent unnecessary fiddling with caller/inject,
600 # we only do so when our beautify_urlpath would actually do what we want to
601 # avoid, i.e. when po_link_to = negotiated
602 if ($config{po_link_to} eq "negotiated") {
603 my @caller = caller(1);
604 my $run_by_editpage = 0;
605 $run_by_editpage = 1 if (exists $caller[3] && defined $caller[3]
606 && $caller[3] eq "IkiWiki::cgi_editpage");
607 inject(name => "IkiWiki::beautify_urlpath", call => $origsubs{'beautify_urlpath'})
608 if $run_by_editpage;
609 my $res = $origsubs{'urlto'}->($to,$from,$absolute);
610 inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath)
611 if $run_by_editpage;
612 return $res;
614 else {
615 return $origsubs{'urlto'}->($to,$from,$absolute)
619 sub mycgiurl (@) {
620 my %params=@_;
622 # slave pages have no subpages
623 if (istranslation($params{'from'})) {
624 $params{'from'} = masterpage($params{'from'});
626 return $origsubs{'cgiurl'}->(%params);
629 # ,----
630 # | Blackboxes for private data
631 # `----
634 my %filtered;
636 sub alreadyfiltered($$) {
637 my $page=shift;
638 my $destpage=shift;
640 return exists $filtered{$page}{$destpage}
641 && $filtered{$page}{$destpage} eq 1;
644 sub setalreadyfiltered($$) {
645 my $page=shift;
646 my $destpage=shift;
648 $filtered{$page}{$destpage}=1;
651 sub unsetalreadyfiltered($$) {
652 my $page=shift;
653 my $destpage=shift;
655 if (exists $filtered{$page}{$destpage}) {
656 delete $filtered{$page}{$destpage};
660 sub resetalreadyfiltered() {
661 undef %filtered;
665 # ,----
666 # | Helper functions
667 # `----
669 sub maybe_add_leading_slash ($;$) {
670 my $str=shift;
671 my $add=shift;
672 $add=1 unless defined $add;
673 return '/' . $str if $add;
674 return $str;
677 sub istranslatablefile ($) {
678 my $file=shift;
680 return 0 unless defined $file;
681 my $type=pagetype($file);
682 return 0 if ! defined $type || $type eq 'po';
683 return 0 if $file =~ /\.pot$/;
684 return 1 if pagespec_match(pagename($file), $config{po_translatable_pages});
685 return;
688 sub istranslatable ($) {
689 my $page=shift;
691 $page=~s#^/##;
692 return 1 if istranslatablefile($pagesources{$page});
693 return;
696 sub _istranslation ($) {
697 my $page=shift;
699 $page='' unless defined $page && length $page;
700 my $hasleadingslash = ($page=~s#^/##);
701 my $file=$pagesources{$page};
702 return 0 unless defined $file
703 && defined pagetype($file)
704 && pagetype($file) eq 'po';
705 return 0 if $file =~ /\.pot$/;
707 my ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
708 return 0 unless defined $masterpage && defined $lang
709 && length $masterpage && length $lang
710 && defined $pagesources{$masterpage}
711 && defined $config{po_slave_languages}{$lang};
713 return (maybe_add_leading_slash($masterpage, $hasleadingslash), $lang)
714 if istranslatable($masterpage);
717 sub istranslation ($) {
718 my $page=shift;
720 if (1 < (my ($masterpage, $lang) = _istranslation($page))) {
721 my $hasleadingslash = ($masterpage=~s#^/##);
722 $translations{$masterpage}{$lang}=$page unless exists $translations{$masterpage}{$lang};
723 return (maybe_add_leading_slash($masterpage, $hasleadingslash), $lang);
725 return "";
728 sub masterpage ($) {
729 my $page=shift;
731 if ( 1 < (my ($masterpage, $lang) = _istranslation($page))) {
732 return $masterpage;
734 return $page;
737 sub lang ($) {
738 my $page=shift;
740 if (1 < (my ($masterpage, $lang) = _istranslation($page))) {
741 return $lang;
743 return $config{po_master_language}{code};
746 sub islanguagecode ($) {
747 my $code=shift;
749 return $code =~ /^[a-z]{2}$/;
752 sub otherlanguage ($$) {
753 my $page=shift;
754 my $code=shift;
756 return masterpage($page) if $code eq $config{po_master_language}{code};
757 return masterpage($page) . '.' . $code;
760 sub otherlanguages ($) {
761 my $page=shift;
763 my %ret;
764 return \%ret unless istranslation($page) || istranslatable($page);
765 my $curlang=lang($page);
766 foreach my $lang
767 ($config{po_master_language}{code}, keys %{$config{po_slave_languages}}) {
768 next if $lang eq $curlang;
769 $ret{$lang}=otherlanguage($page, $lang);
771 return \%ret;
774 sub potfile ($) {
775 my $masterfile=shift;
777 (my $name, my $dir, my $suffix) = fileparse($masterfile, qr/\.[^.]*/);
778 $dir='' if $dir eq './';
779 return File::Spec->catpath('', $dir, $name . ".pot");
782 sub pofile ($$) {
783 my $masterfile=shift;
784 my $lang=shift;
786 (my $name, my $dir, my $suffix) = fileparse($masterfile, qr/\.[^.]*/);
787 $dir='' if $dir eq './';
788 return File::Spec->catpath('', $dir, $name . "." . $lang . ".po");
791 sub pofiles ($) {
792 my $masterfile=shift;
794 return map pofile($masterfile, $_), (keys %{$config{po_slave_languages}});
797 sub refreshpot ($) {
798 my $masterfile=shift;
800 my $potfile=potfile($masterfile);
801 my %options = ("markdown" => (pagetype($masterfile) eq 'mdwn') ? 1 : 0);
802 my $doc=Locale::Po4a::Chooser::new('text',%options);
803 $doc->{TT}{utf_mode} = 1;
804 $doc->{TT}{file_in_charset} = 'utf-8';
805 $doc->{TT}{file_out_charset} = 'utf-8';
806 $doc->read($masterfile);
807 # let's cheat a bit to force porefs option to be passed to
808 # Locale::Po4a::Po; this is undocument use of internal
809 # Locale::Po4a::TransTractor's data, compulsory since this module
810 # prevents us from using the porefs option.
811 $doc->{TT}{po_out}=Locale::Po4a::Po->new({ 'porefs' => 'none' });
812 $doc->{TT}{po_out}->set_charset('utf-8');
813 # do the actual work
814 $doc->parse;
815 IkiWiki::prep_writefile(basename($potfile),dirname($potfile));
816 $doc->writepo($potfile);
819 sub refreshpofiles ($@) {
820 my $masterfile=shift;
821 my @pofiles=@_;
823 my $potfile=potfile($masterfile);
824 if (! -e $potfile) {
825 error("po(refreshpofiles) ".sprintf(gettext("POT file (%s) does not exist"), $potfile));
828 foreach my $pofile (@pofiles) {
829 IkiWiki::prep_writefile(basename($pofile),dirname($pofile));
830 if (-e $pofile) {
831 system("msgmerge", "--previous", "-q", "-U", "--backup=none", $pofile, $potfile) == 0
832 or error("po(refreshpofiles) ".
833 sprintf(gettext("failed to update %s"),
834 $pofile));
836 else {
837 File::Copy::syscopy($potfile,$pofile)
838 or error("po(refreshpofiles) ".
839 sprintf(gettext("failed to copy the POT file to %s"),
840 $pofile));
845 sub buildtranslationscache() {
846 # use istranslation's side-effect
847 map istranslation($_), (keys %pagesources);
850 sub resettranslationscache() {
851 undef %translations;
854 sub flushmemoizecache() {
855 Memoize::flush_cache("istranslatable");
856 Memoize::flush_cache("_istranslation");
857 Memoize::flush_cache("percenttranslated");
860 sub urlto_with_orig_beautiful_urlpath($$) {
861 my $to=shift;
862 my $from=shift;
864 inject(name => "IkiWiki::beautify_urlpath", call => $origsubs{'beautify_urlpath'});
865 my $res=urlto($to, $from);
866 inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath);
868 return $res;
871 sub percenttranslated ($) {
872 my $page=shift;
874 $page=~s/^\///;
875 return gettext("N/A") unless istranslation($page);
876 my $file=srcfile($pagesources{$page});
877 my $masterfile = srcfile($pagesources{masterpage($page)});
878 my %options = (
879 "markdown" => (pagetype($masterfile) eq 'mdwn') ? 1 : 0,
881 my $doc=Locale::Po4a::Chooser::new('text',%options);
882 $doc->process(
883 'po_in_name' => [ $file ],
884 'file_in_name' => [ $masterfile ],
885 'file_in_charset' => 'utf-8',
886 'file_out_charset' => 'utf-8',
887 ) or error("po(percenttranslated) ".
888 sprintf(gettext("failed to translate %s"), $page));
889 my ($percent,$hit,$queries) = $doc->stats();
890 $percent =~ s/\.[0-9]+$//;
891 return $percent;
894 sub languagename ($) {
895 my $code=shift;
897 return $config{po_master_language}{name}
898 if $code eq $config{po_master_language}{code};
899 return $config{po_slave_languages}{$code}
900 if defined $config{po_slave_languages}{$code};
901 return;
904 sub otherlanguagesloop ($) {
905 my $page=shift;
907 my @ret;
908 my %otherpages=%{otherlanguages($page)};
909 while (my ($lang, $otherpage) = each %otherpages) {
910 if (istranslation($page) && masterpage($page) eq $otherpage) {
911 push @ret, {
912 url => urlto_with_orig_beautiful_urlpath($otherpage, $page),
913 code => $lang,
914 language => languagename($lang),
915 master => 1,
918 else {
919 push @ret, {
920 url => urlto_with_orig_beautiful_urlpath($otherpage, $page),
921 code => $lang,
922 language => languagename($lang),
923 percent => percenttranslated($otherpage),
927 return sort {
928 return -1 if $a->{code} eq $config{po_master_language}{code};
929 return 1 if $b->{code} eq $config{po_master_language}{code};
930 return $a->{language} cmp $b->{language};
931 } @ret;
934 sub homepageurl (;$) {
935 my $page=shift;
937 return urlto('', $page);
940 sub deletetranslations ($) {
941 my $deletedmasterfile=shift;
943 my $deletedmasterpage=pagename($deletedmasterfile);
944 my @todelete;
945 map {
946 my $file = newpagefile($deletedmasterpage.'.'.$_, 'po');
947 my $absfile = "$config{srcdir}/$file";
948 if (-e $absfile && ! -l $absfile && ! -d $absfile) {
949 push @todelete, $file;
951 } keys %{$config{po_slave_languages}};
953 map {
954 if ($config{rcs}) {
955 IkiWiki::rcs_remove($_);
957 else {
958 IkiWiki::prune("$config{srcdir}/$_");
960 } @todelete;
962 if (@todelete) {
963 commit_and_refresh(
964 gettext("removed obsolete PO files"),
965 "IkiWiki::Plugin::po::deletetranslations");
969 sub commit_and_refresh ($$) {
970 my ($msg, $author) = (shift, shift);
972 if ($config{rcs}) {
973 IkiWiki::disable_commit_hook();
974 IkiWiki::rcs_commit_staged($msg, $author, "127.0.0.1");
975 IkiWiki::enable_commit_hook();
976 IkiWiki::rcs_update();
978 # Reinitialize module's private variables.
979 resetalreadyfiltered();
980 resettranslationscache();
981 flushmemoizecache();
982 # Trigger a wiki refresh.
983 require IkiWiki::Render;
984 # without preliminary saveindex/loadindex, refresh()
985 # complains about a lot of uninitialized variables
986 IkiWiki::saveindex();
987 IkiWiki::loadindex();
988 IkiWiki::refresh();
989 IkiWiki::saveindex();
992 # on success, returns the filtered content.
993 # on error, if $nonfatal, warn and return undef; else, error out.
994 sub po_to_markup ($$;$) {
995 my ($page, $content) = (shift, shift);
996 my $nonfatal = shift;
998 $content = '' unless defined $content;
999 $content = decode_utf8(encode_utf8($content));
1000 # CRLF line terminators make poor Locale::Po4a feel bad
1001 $content=~s/\r\n/\n/g;
1003 # There are incompatibilities between some File::Temp versions
1004 # (including 0.18, bundled with Lenny's perl-modules package)
1005 # and others (e.g. 0.20, previously present in the archive as
1006 # a standalone package): under certain circumstances, some
1007 # return a relative filename, whereas others return an absolute one;
1008 # we here use this module in a way that is at least compatible
1009 # with 0.18 and 0.20. Beware, hit'n'run refactorers!
1010 my $infile = new File::Temp(TEMPLATE => "ikiwiki-po-filter-in.XXXXXXXXXX",
1011 DIR => File::Spec->tmpdir,
1012 UNLINK => 1)->filename;
1013 my $outfile = new File::Temp(TEMPLATE => "ikiwiki-po-filter-out.XXXXXXXXXX",
1014 DIR => File::Spec->tmpdir,
1015 UNLINK => 1)->filename;
1017 my $fail = sub ($) {
1018 my $msg = "po(po_to_markup) - $page : " . shift;
1019 if ($nonfatal) {
1020 warn $msg;
1021 return undef;
1023 error($msg, sub { unlink $infile, $outfile});
1026 writefile(basename($infile), File::Spec->tmpdir, $content)
1027 or return $fail->(sprintf(gettext("failed to write %s"), $infile));
1029 my $masterfile = srcfile($pagesources{masterpage($page)});
1030 my %options = (
1031 "markdown" => (pagetype($masterfile) eq 'mdwn') ? 1 : 0,
1033 my $doc=Locale::Po4a::Chooser::new('text',%options);
1034 $doc->process(
1035 'po_in_name' => [ $infile ],
1036 'file_in_name' => [ $masterfile ],
1037 'file_in_charset' => 'utf-8',
1038 'file_out_charset' => 'utf-8',
1039 ) or return $fail->(gettext("failed to translate"));
1040 $doc->write($outfile)
1041 or return $fail->(sprintf(gettext("failed to write %s"), $outfile));
1043 $content = readfile($outfile)
1044 or return $fail->(sprintf(gettext("failed to read %s"), $outfile));
1046 # Unlinking should happen automatically, thanks to File::Temp,
1047 # but it does not work here, probably because of the way writefile()
1048 # and Locale::Po4a::write() work.
1049 unlink $infile, $outfile;
1051 return $content;
1054 # returns a SuccessReason or FailReason object
1055 sub isvalidpo ($) {
1056 my $content = shift;
1058 # NB: we don't use po_to_markup here, since Po4a parser does
1059 # not mind invalid PO content
1060 $content = '' unless defined $content;
1061 $content = decode_utf8(encode_utf8($content));
1063 # There are incompatibilities between some File::Temp versions
1064 # (including 0.18, bundled with Lenny's perl-modules package)
1065 # and others (e.g. 0.20, previously present in the archive as
1066 # a standalone package): under certain circumstances, some
1067 # return a relative filename, whereas others return an absolute one;
1068 # we here use this module in a way that is at least compatible
1069 # with 0.18 and 0.20. Beware, hit'n'run refactorers!
1070 my $infile = new File::Temp(TEMPLATE => "ikiwiki-po-isvalidpo.XXXXXXXXXX",
1071 DIR => File::Spec->tmpdir,
1072 UNLINK => 1)->filename;
1074 my $fail = sub ($) {
1075 my $msg = '[po/isvalidpo] ' . shift;
1076 unlink $infile;
1077 return IkiWiki::FailReason->new("$msg");
1080 writefile(basename($infile), File::Spec->tmpdir, $content)
1081 or return $fail->(sprintf(gettext("failed to write %s"), $infile));
1083 my $res = (system("msgfmt", "--check", $infile, "-o", "/dev/null") == 0);
1085 # Unlinking should happen automatically, thanks to File::Temp,
1086 # but it does not work here, probably because of the way writefile()
1087 # and Locale::Po4a::write() work.
1088 unlink $infile;
1090 if ($res) {
1091 return IkiWiki::SuccessReason->new("valid gettext data");
1093 return IkiWiki::FailReason->new(gettext("invalid gettext data, go back ".
1094 "to previous page to continue edit"));
1097 # ,----
1098 # | PageSpecs
1099 # `----
1101 package IkiWiki::PageSpec;
1103 sub match_istranslation ($;@) {
1104 my $page=shift;
1106 if (IkiWiki::Plugin::po::istranslation($page)) {
1107 return IkiWiki::SuccessReason->new("is a translation page");
1109 else {
1110 return IkiWiki::FailReason->new("is not a translation page");
1114 sub match_istranslatable ($;@) {
1115 my $page=shift;
1117 if (IkiWiki::Plugin::po::istranslatable($page)) {
1118 return IkiWiki::SuccessReason->new("is set as translatable in po_translatable_pages");
1120 else {
1121 return IkiWiki::FailReason->new("is not set as translatable in po_translatable_pages");
1125 sub match_lang ($$;@) {
1126 my $page=shift;
1127 my $wanted=shift;
1129 my $regexp=IkiWiki::glob2re($wanted);
1130 my $lang=IkiWiki::Plugin::po::lang($page);
1131 if ($lang !~ /^$regexp$/i) {
1132 return IkiWiki::FailReason->new("file language is $lang, not $wanted");
1134 else {
1135 return IkiWiki::SuccessReason->new("file language is $wanted");
1139 sub match_currentlang ($$;@) {
1140 my $page=shift;
1141 shift;
1142 my %params=@_;
1144 return IkiWiki::FailReason->new("no location provided") unless exists $params{location};
1146 my $currentlang=IkiWiki::Plugin::po::lang($params{location});
1147 my $lang=IkiWiki::Plugin::po::lang($page);
1149 if ($lang eq $currentlang) {
1150 return IkiWiki::SuccessReason->new("file language is the same as current one, i.e. $currentlang");
1152 else {
1153 return IkiWiki::FailReason->new("file language is $lang, whereas current language is $currentlang");