add paths to plugin files in copyright
[ikiwiki.git] / IkiWiki / Plugin / po.pm
blob4f8d5036e198b4c0eac2f290156c411907190b87
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 eval q{use Locale::Po4a::Common qw(nowrapi18n !/.*/)};
14 if ($@) {
15 print STDERR gettext("warning: Old po4a detected! Recommend upgrade to 0.35.")."\n";
16 eval q{use Locale::Po4a::Common qw(!/.*/)};
17 die $@ if $@;
19 use Locale::Po4a::Chooser;
20 use Locale::Po4a::Po;
21 use File::Basename;
22 use File::Copy;
23 use File::Spec;
24 use File::Temp;
25 use Memoize;
26 use UNIVERSAL;
28 my ($master_language_code, $master_language_name);
29 my %translations;
30 my @origneedsbuild;
31 my %origsubs;
32 my @slavelanguages; # language codes ordered as in config po_slave_languages
33 my %slavelanguages; # language code to name lookup
35 memoize("istranslatable");
36 memoize("_istranslation");
37 memoize("percenttranslated");
39 sub import {
40 hook(type => "getsetup", id => "po", call => \&getsetup);
41 hook(type => "checkconfig", id => "po", call => \&checkconfig,
42 last => 1);
43 hook(type => "needsbuild", id => "po", call => \&needsbuild);
44 hook(type => "scan", id => "po", call => \&scan, last => 1);
45 hook(type => "filter", id => "po", call => \&filter);
46 hook(type => "htmlize", id => "po", call => \&htmlize);
47 hook(type => "pagetemplate", id => "po", call => \&pagetemplate, last => 1);
48 hook(type => "rename", id => "po", call => \&renamepages, first => 1);
49 hook(type => "delete", id => "po", call => \&mydelete);
50 hook(type => "change", id => "po", call => \&change);
51 hook(type => "checkcontent", id => "po", call => \&checkcontent);
52 hook(type => "canremove", id => "po", call => \&canremove);
53 hook(type => "canrename", id => "po", call => \&canrename);
54 hook(type => "editcontent", id => "po", call => \&editcontent);
55 hook(type => "formbuilder_setup", id => "po", call => \&formbuilder_setup, last => 1);
56 hook(type => "formbuilder", id => "po", call => \&formbuilder);
58 if (! %origsubs) {
59 $origsubs{'bestlink'}=\&IkiWiki::bestlink;
60 inject(name => "IkiWiki::bestlink", call => \&mybestlink);
61 $origsubs{'beautify_urlpath'}=\&IkiWiki::beautify_urlpath;
62 inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath);
63 $origsubs{'targetpage'}=\&IkiWiki::targetpage;
64 inject(name => "IkiWiki::targetpage", call => \&mytargetpage);
65 $origsubs{'urlto'}=\&IkiWiki::urlto;
66 inject(name => "IkiWiki::urlto", call => \&myurlto);
67 $origsubs{'cgiurl'}=\&IkiWiki::cgiurl;
68 inject(name => "IkiWiki::cgiurl", call => \&mycgiurl);
69 $origsubs{'rootpage'}=\&IkiWiki::rootpage;
70 inject(name => "IkiWiki::rootpage", call => \&myrootpage);
71 $origsubs{'isselflink'}=\&IkiWiki::isselflink;
72 inject(name => "IkiWiki::isselflink", call => \&myisselflink);
77 # ,----
78 # | Table of contents
79 # `----
81 # 1. Hooks
82 # 2. Injected functions
83 # 3. Blackboxes for private data
84 # 4. Helper functions
85 # 5. PageSpecs
88 # ,----
89 # | Hooks
90 # `----
92 sub getsetup () {
93 return
94 plugin => {
95 safe => 1,
96 rebuild => 1, # format plugin
97 section => "format",
99 po_master_language => {
100 type => "string",
101 example => "en|English",
102 description => "master language (non-PO files)",
103 safe => 1,
104 rebuild => 1,
106 po_slave_languages => {
107 type => "string",
108 example => [
109 'fr|Français',
110 'es|Español',
111 'de|Deutsch'
113 description => "slave languages (translated via PO files) format: ll|Langname",
114 safe => 1,
115 rebuild => 1,
117 po_translatable_pages => {
118 type => "pagespec",
119 example => "* and !*/Discussion",
120 description => "PageSpec controlling which pages are translatable",
121 link => "ikiwiki/PageSpec",
122 safe => 1,
123 rebuild => 1,
125 po_link_to => {
126 type => "string",
127 example => "current",
128 description => "internal linking behavior (default/current/negotiated)",
129 safe => 1,
130 rebuild => 1,
134 sub checkconfig () {
135 if (exists $config{po_master_language}) {
136 if (! ref $config{po_master_language}) {
137 ($master_language_code, $master_language_name)=
138 splitlangpair($config{po_master_language});
140 else {
141 $master_language_code=$config{po_master_language}{code};
142 $master_language_name=$config{po_master_language}{name};
143 $config{po_master_language}=joinlangpair($master_language_code, $master_language_name);
146 if (! defined $master_language_code) {
147 $master_language_code='en';
149 if (! defined $master_language_name) {
150 $master_language_name='English';
153 if (ref $config{po_slave_languages} eq 'ARRAY') {
154 foreach my $pair (@{$config{po_slave_languages}}) {
155 my ($code, $name)=splitlangpair($pair);
156 if (defined $code && ! exists $slavelanguages{$code}) {
157 push @slavelanguages, $code;
158 $slavelanguages{$code} = $name;
162 elsif (ref $config{po_slave_languages} eq 'HASH') {
163 %slavelanguages=%{$config{po_slave_languages}};
164 @slavelanguages = sort {
165 $config{po_slave_languages}->{$a} cmp $config{po_slave_languages}->{$b};
166 } keys %slavelanguages;
167 $config{po_slave_languages}=[
168 map { joinlangpair($_, $slavelanguages{$_}) } @slavelanguages
172 delete $slavelanguages{$master_language_code};
174 map {
175 islanguagecode($_)
176 or error(sprintf(gettext("%s is not a valid language code"), $_));
177 } ($master_language_code, @slavelanguages);
179 if (! exists $config{po_translatable_pages} ||
180 ! defined $config{po_translatable_pages}) {
181 $config{po_translatable_pages}="";
183 if (! exists $config{po_link_to} ||
184 ! defined $config{po_link_to}) {
185 $config{po_link_to}='default';
187 elsif ($config{po_link_to} !~ /^(default|current|negotiated)$/) {
188 warn(sprintf(gettext('%s is not a valid value for po_link_to, falling back to po_link_to=default'),
189 $config{po_link_to}));
190 $config{po_link_to}='default';
192 elsif ($config{po_link_to} eq "negotiated" && ! $config{usedirs}) {
193 warn(gettext('po_link_to=negotiated requires usedirs to be enabled, falling back to po_link_to=default'));
194 $config{po_link_to}='default';
197 push @{$config{wiki_file_prune_regexps}}, qr/\.pot$/;
199 # Translated versions of the underlays are added if available.
200 foreach my $underlay ("basewiki",
201 map { m/^\Q$config{underlaydirbase}\E\/*(.*)/ }
202 reverse @{$config{underlaydirs}}) {
203 next if $underlay=~/^locale\//;
205 # Underlays containing the po files for slave languages.
206 foreach my $ll (@slavelanguages) {
207 add_underlay("po/$ll/$underlay")
208 if -d "$config{underlaydirbase}/po/$ll/$underlay";
211 if ($master_language_code ne 'en') {
212 # Add underlay containing translated source files
213 # for the master language.
214 add_underlay("locale/$master_language_code/$underlay")
215 if -d "$config{underlaydirbase}/locale/$master_language_code/$underlay";
220 sub needsbuild () {
221 my $needsbuild=shift;
223 # backup @needsbuild content so that change() can know whether
224 # a given master page was rendered because its source file was changed
225 @origneedsbuild=(@$needsbuild);
227 flushmemoizecache();
228 buildtranslationscache();
230 # make existing translations depend on the corresponding master page
231 foreach my $master (keys %translations) {
232 map add_depends($_, $master), values %{otherlanguages_pages($master)};
235 return $needsbuild;
238 sub scan (@) {
239 my %params=@_;
240 my $page=$params{page};
241 my $content=$params{content};
242 my $run_by_po=$params{run_by_po};
244 # Massage the recorded state of internal links so that:
245 # - it matches the actually generated links, rather than the links as
246 # written in the pages' source
247 # - backlinks are consistent in all cases
249 # A second scan pass is made over translation pages, so as an
250 # optimization, we only do so on the second pass in this case,
251 # i.e. when this hook is called by itself.
252 if ($run_by_po && istranslation($page)) {
253 # replace the occurence of $destpage in $links{$page}
254 my @orig_links = @{$links{$page}};
255 $links{$page} = [];
256 foreach my $destpage (@orig_links) {
257 if (istranslatedto($destpage, lang($page))) {
258 add_link($page, $destpage . '.' . lang($page));
260 else {
261 add_link($page, $destpage);
265 # No second scan pass is done for a non-translation page, so
266 # links massaging must happen on first pass in this case.
267 elsif (! $run_by_po && ! istranslatable($page) && ! istranslation($page)) {
268 foreach my $destpage (@{$links{$page}}) {
269 if (istranslatable($destpage)) {
270 # make sure any destpage's translations has
271 # $page in its backlinks
272 foreach my $link (values %{otherlanguages_pages($destpage)}) {
273 add_link($page, $link);
279 # Re-run the preprocess hooks in scan mode, then the scan hooks,
280 # over the po-to-markup converted content
281 return if $run_by_po; # avoid looping endlessly
282 return unless istranslation($page);
283 $content = po_to_markup($page, $content);
284 require IkiWiki;
285 IkiWiki::preprocess($page, $page, $content, 1);
286 IkiWiki::run_hooks(scan => sub {
287 shift->(
288 page => $page,
289 content => $content,
290 run_by_po => 1,
295 # We use filter to convert PO to the master page's format,
296 # since the rest of ikiwiki should not work on PO files.
297 sub filter (@) {
298 my %params = @_;
300 my $page = $params{page};
301 my $destpage = $params{destpage};
302 my $content = $params{content};
303 if (istranslation($page) && ! alreadyfiltered($page, $destpage)) {
304 $content = po_to_markup($page, $content);
305 setalreadyfiltered($page, $destpage);
307 return $content;
310 sub htmlize (@) {
311 my %params=@_;
313 my $page = $params{page};
314 my $content = $params{content};
316 # ignore PO files this plugin did not create
317 return $content unless istranslation($page);
319 # force content to be htmlize'd as if it was the same type as the master page
320 return IkiWiki::htmlize($page, $page,
321 pagetype(srcfile($pagesources{masterpage($page)})),
322 $content);
325 sub pagetemplate (@) {
326 my %params=@_;
327 my $page=$params{page};
328 my $destpage=$params{destpage};
329 my $template=$params{template};
331 my ($masterpage, $lang) = istranslation($page);
333 if (istranslation($page) && $template->query(name => "percenttranslated")) {
334 $template->param(percenttranslated => percenttranslated($page));
336 if ($template->query(name => "istranslation")) {
337 $template->param(istranslation => scalar istranslation($page));
339 if ($template->query(name => "istranslatable")) {
340 $template->param(istranslatable => istranslatable($page));
342 if ($template->query(name => "HOMEPAGEURL")) {
343 $template->param(homepageurl => homepageurl($page));
345 if ($template->query(name => "otherlanguages")) {
346 $template->param(otherlanguages => [otherlanguagesloop($page)]);
347 map add_depends($page, $_), (values %{otherlanguages_pages($page)});
349 if ($config{discussion} && istranslation($page)) {
350 if ($page !~ /.*\/\Q$config{discussionpage}\E$/i &&
351 (length $config{cgiurl} ||
352 exists $links{$masterpage."/".lc($config{discussionpage})})) {
353 $template->param('discussionlink' => htmllink(
354 $page,
355 $destpage,
356 $masterpage . '/' . $config{discussionpage},
357 noimageinline => 1,
358 forcesubpage => 0,
359 linktext => $config{discussionpage},
363 # Remove broken parentlink to ./index.html on home page's translations.
364 # It works because this hook has the "last" parameter set, to ensure it
365 # runs after parentlinks' own pagetemplate hook.
366 if ($template->param('parentlinks')
367 && istranslation($page)
368 && $masterpage eq "index") {
369 $template->param('parentlinks' => []);
371 if (ishomepage($page) && $template->query(name => "title")
372 && !$template->param("title_overridden")) {
373 $template->param(title => $config{wikiname});
377 # Add the renamed page translations to the list of to-be-renamed pages.
378 sub renamepages (@) {
379 my %params = @_;
381 my %torename = %{$params{torename}};
382 my $session = $params{session};
384 # Save the page(s) the user asked to rename, so that our
385 # canrename hook can tell the difference between:
386 # - a translation being renamed as a consequence of its master page
387 # being renamed
388 # - a user trying to directly rename a translation
389 # This is why this hook has to be run first, before the list of pages
390 # to rename is modified by other plugins.
391 my @orig_torename;
392 @orig_torename=@{$session->param("po_orig_torename")}
393 if defined $session->param("po_orig_torename");
394 push @orig_torename, $torename{src};
395 $session->param(po_orig_torename => \@orig_torename);
396 IkiWiki::cgi_savesession($session);
398 return () unless istranslatable($torename{src});
400 my @ret;
401 my %otherpages=%{otherlanguages_pages($torename{src})};
402 while (my ($lang, $otherpage) = each %otherpages) {
403 push @ret, {
404 src => $otherpage,
405 srcfile => $pagesources{$otherpage},
406 dest => otherlanguage_page($torename{dest}, $lang),
407 destfile => $torename{dest}.".".$lang.".po",
408 required => 0,
411 return @ret;
414 sub mydelete (@) {
415 my @deleted=@_;
417 map { deletetranslations($_) } grep istranslatablefile($_), @deleted;
420 sub change (@) {
421 my @rendered=@_;
423 my $updated_po_files=0;
425 # Refresh/create POT and PO files as needed.
426 foreach my $file (grep {istranslatablefile($_)} @rendered) {
427 my $masterfile=srcfile($file);
428 my $page=pagename($file);
429 my $updated_pot_file=0;
431 # Avoid touching underlay files.
432 next if $masterfile ne "$config{srcdir}/$file";
434 # Only refresh POT file if it does not exist, or if
435 # the source was changed: don't if only the HTML was
436 # refreshed, e.g. because of a dependency.
437 if ((grep { $_ eq $pagesources{$page} } @origneedsbuild) ||
438 ! -e potfile($masterfile)) {
439 refreshpot($masterfile);
440 $updated_pot_file=1;
442 my @pofiles;
443 foreach my $po (pofiles($masterfile)) {
444 next if ! $updated_pot_file && -e $po;
445 next if grep { $po=~/\Q$_\E/ } @{$config{underlaydirs}};
446 push @pofiles, $po;
448 if (@pofiles) {
449 refreshpofiles($masterfile, @pofiles);
450 map { s/^\Q$config{srcdir}\E\/*//; IkiWiki::rcs_add($_) } @pofiles if $config{rcs};
451 $updated_po_files=1;
455 if ($updated_po_files) {
456 commit_and_refresh(
457 gettext("updated PO files"));
461 sub checkcontent (@) {
462 my %params=@_;
464 if (istranslation($params{page})) {
465 my $res = isvalidpo($params{content});
466 if ($res) {
467 return undef;
469 else {
470 return "$res";
473 return undef;
476 sub canremove (@) {
477 my %params = @_;
479 if (istranslation($params{page})) {
480 return gettext("Can not remove a translation. If the master page is removed, ".
481 "however, its translations will be removed as well.");
483 return undef;
486 sub canrename (@) {
487 my %params = @_;
488 my $session = $params{session};
490 if (istranslation($params{src})) {
491 my $masterpage = masterpage($params{src});
492 # Tell the difference between:
493 # - a translation being renamed as a consequence of its master page
494 # being renamed, which is allowed
495 # - a user trying to directly rename a translation, which is forbidden
496 # by looking for the master page in the list of to-be-renamed pages we
497 # saved early in the renaming process.
498 my $orig_torename = $session->param("po_orig_torename");
499 unless (grep { $_ eq $masterpage } @{$orig_torename}) {
500 return gettext("Can not rename a translation. If the master page is renamed, ".
501 "however, its translations will be renamed as well.");
504 return undef;
507 # As we're previewing or saving a page, the content may have
508 # changed, so tell the next filter() invocation it must not be lazy.
509 sub editcontent () {
510 my %params=@_;
512 unsetalreadyfiltered($params{page}, $params{page});
513 return $params{content};
516 sub formbuilder_setup (@) {
517 my %params=@_;
518 my $form=$params{form};
519 my $q=$params{cgi};
521 return unless defined $form->field("do");
523 if ($form->field("do") eq "create") {
524 # Warn the user: new pages must be written in master language.
525 my $template=template("pocreatepage.tmpl");
526 $template->param(LANG => $master_language_name);
527 $form->tmpl_param(message => $template->output);
529 elsif ($form->field("do") eq "edit") {
530 # Remove the rename/remove buttons on slave pages.
531 # This has to be done after the rename/remove plugins have added
532 # their buttons, which is why this hook must be run last.
533 # The canrename/canremove hooks already ensure this is forbidden
534 # at the backend level, so this is only UI sugar.
535 if (istranslation($form->field("page"))) {
536 map {
537 for (my $i = 0; $i < @{$params{buttons}}; $i++) {
538 if (@{$params{buttons}}[$i] eq $_) {
539 delete @{$params{buttons}}[$i];
540 last;
543 } qw(Rename Remove);
548 sub formbuilder (@) {
549 my %params=@_;
550 my $form=$params{form};
551 my $q=$params{cgi};
553 return unless defined $form->field("do");
555 # Do not allow to create pages of type po: they are automatically created.
556 # The main reason to do so is to bypass the "favor the type of linking page
557 # on page creation" logic, which is unsuitable when a broken link is clicked
558 # on a slave (PO) page.
559 # This cannot be done in the formbuilder_setup hook as the list of types is
560 # computed later.
561 if ($form->field("do") eq "create") {
562 foreach my $field ($form->field) {
563 next unless "$field" eq "type";
564 next unless $field->type eq 'select';
565 my $orig_value = $field->value;
566 # remove po from the list of types
567 my @types = grep { $_->[0] ne 'po' } $field->options;
568 $field->options(\@types) if @types;
569 # favor the type of linking page's masterpage
570 if ($orig_value eq 'po') {
571 my ($from, $type);
572 if (defined $form->field('from')) {
573 ($from)=$form->field('from')=~/$config{wiki_file_regexp}/;
574 $from = masterpage($from);
576 if (defined $from && exists $pagesources{$from}) {
577 $type=pagetype($pagesources{$from});
579 $type=$config{default_pageext} unless defined $type;
580 $field->value($type) ;
586 # ,----
587 # | Injected functions
588 # `----
590 # Implement po_link_to 'current' and 'negotiated' settings.
591 sub mybestlink ($$) {
592 my $page=shift;
593 my $link=shift;
595 return $origsubs{'bestlink'}->($page, $link)
596 if defined $config{po_link_to} && $config{po_link_to} eq "default";
598 my $res=$origsubs{'bestlink'}->(masterpage($page), $link);
599 my @caller = caller(1);
600 if (length $res
601 && istranslatedto($res, lang($page))
602 && istranslation($page)
603 && !(exists $caller[3] && defined $caller[3]
604 && ($caller[3] eq "IkiWiki::PageSpec::match_link"))) {
605 return $res . "." . lang($page);
607 return $res;
610 sub mybeautify_urlpath ($) {
611 my $url=shift;
613 my $res=$origsubs{'beautify_urlpath'}->($url);
614 if (defined $config{po_link_to} && $config{po_link_to} eq "negotiated") {
615 $res =~ s!/\Qindex.$master_language_code.$config{htmlext}\E$!/!;
616 $res =~ s!/\Qindex.$config{htmlext}\E$!/!;
617 map {
618 $res =~ s!/\Qindex.$_.$config{htmlext}\E$!/!;
619 } @slavelanguages;
621 return $res;
624 sub mytargetpage ($$) {
625 my $page=shift;
626 my $ext=shift;
628 if (istranslation($page) || istranslatable($page)) {
629 my ($masterpage, $lang) = (masterpage($page), lang($page));
630 if (! $config{usedirs} || $masterpage eq 'index') {
631 return $masterpage . "." . $lang . "." . $ext;
633 else {
634 return $masterpage . "/index." . $lang . "." . $ext;
637 return $origsubs{'targetpage'}->($page, $ext);
640 sub myurlto ($;$$) {
641 my $to=shift;
642 my $from=shift;
643 my $absolute=shift;
645 # workaround hard-coded /index.$config{htmlext} in IkiWiki::urlto()
646 if (! length $to
647 && $config{po_link_to} eq "current"
648 && istranslatable('index')) {
649 if (defined $from) {
650 return IkiWiki::beautify_urlpath(IkiWiki::baseurl($from) . "index." . lang($from) . ".$config{htmlext}");
652 else {
653 return $origsubs{'urlto'}->($to,$from,$absolute);
656 # avoid using our injected beautify_urlpath if run by cgi_editpage,
657 # so that one is redirected to the just-edited page rather than to the
658 # negociated translation; to prevent unnecessary fiddling with caller/inject,
659 # we only do so when our beautify_urlpath would actually do what we want to
660 # avoid, i.e. when po_link_to = negotiated.
661 # also avoid doing so when run by cgi_goto, so that the links on recentchanges
662 # page actually lead to the exact page they pretend to.
663 if ($config{po_link_to} eq "negotiated") {
664 my @caller = caller(1);
665 my $use_orig = 0;
666 $use_orig = 1 if (exists $caller[3] && defined $caller[3]
667 && ($caller[3] eq "IkiWiki::cgi_editpage" ||
668 $caller[3] eq "IkiWiki::Plugin::goto::cgi_goto")
670 inject(name => "IkiWiki::beautify_urlpath", call => $origsubs{'beautify_urlpath'})
671 if $use_orig;
672 my $res = $origsubs{'urlto'}->($to,$from,$absolute);
673 inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath)
674 if $use_orig;
675 return $res;
677 else {
678 return $origsubs{'urlto'}->($to,$from,$absolute)
682 sub mycgiurl (@) {
683 my %params=@_;
685 # slave pages have no subpages
686 if (istranslation($params{'from'})) {
687 $params{'from'} = masterpage($params{'from'});
689 return $origsubs{'cgiurl'}->(%params);
692 sub myrootpage (@) {
693 my %params=@_;
695 my $rootpage;
696 if (exists $params{rootpage}) {
697 $rootpage=$origsubs{'bestlink'}->($params{page}, $params{rootpage});
698 if (!length $rootpage) {
699 $rootpage=$params{rootpage};
702 else {
703 $rootpage=masterpage($params{page});
705 return $rootpage;
708 sub myisselflink ($$) {
709 my $page=shift;
710 my $link=shift;
712 return 1 if $origsubs{'isselflink'}->($page, $link);
713 if (istranslation($page)) {
714 return $origsubs{'isselflink'}->(masterpage($page), $link);
716 return;
719 # ,----
720 # | Blackboxes for private data
721 # `----
724 my %filtered;
726 sub alreadyfiltered($$) {
727 my $page=shift;
728 my $destpage=shift;
730 return exists $filtered{$page}{$destpage}
731 && $filtered{$page}{$destpage} eq 1;
734 sub setalreadyfiltered($$) {
735 my $page=shift;
736 my $destpage=shift;
738 $filtered{$page}{$destpage}=1;
741 sub unsetalreadyfiltered($$) {
742 my $page=shift;
743 my $destpage=shift;
745 if (exists $filtered{$page}{$destpage}) {
746 delete $filtered{$page}{$destpage};
750 sub resetalreadyfiltered() {
751 undef %filtered;
755 # ,----
756 # | Helper functions
757 # `----
759 sub maybe_add_leading_slash ($;$) {
760 my $str=shift;
761 my $add=shift;
762 $add=1 unless defined $add;
763 return '/' . $str if $add;
764 return $str;
767 sub istranslatablefile ($) {
768 my $file=shift;
770 return 0 unless defined $file;
771 my $type=pagetype($file);
772 return 0 if ! defined $type || $type eq 'po';
773 return 0 if $file =~ /\.pot$/;
774 return 0 if ! defined $config{po_translatable_pages};
775 return 1 if pagespec_match(pagename($file), $config{po_translatable_pages});
776 return;
779 sub istranslatable ($) {
780 my $page=shift;
782 $page=~s#^/##;
783 return 1 if istranslatablefile($pagesources{$page});
784 return;
787 sub istranslatedto ($$) {
788 my $page=shift;
789 my $destlang = shift;
791 $page=~s#^/##;
792 return 0 unless istranslatable($page);
793 exists $pagesources{otherlanguage_page($page, $destlang)};
796 sub _istranslation ($) {
797 my $page=shift;
799 $page='' unless defined $page && length $page;
800 my $hasleadingslash = ($page=~s#^/##);
801 my $file=$pagesources{$page};
802 return 0 unless defined $file
803 && defined pagetype($file)
804 && pagetype($file) eq 'po';
805 return 0 if $file =~ /\.pot$/;
807 my ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
808 return 0 unless defined $masterpage && defined $lang
809 && length $masterpage && length $lang
810 && defined $pagesources{$masterpage}
811 && defined $slavelanguages{$lang};
813 return (maybe_add_leading_slash($masterpage, $hasleadingslash), $lang)
814 if istranslatable($masterpage);
817 sub istranslation ($) {
818 my $page=shift;
820 if (1 < (my ($masterpage, $lang) = _istranslation($page))) {
821 my $hasleadingslash = ($masterpage=~s#^/##);
822 $translations{$masterpage}{$lang}=$page unless exists $translations{$masterpage}{$lang};
823 return (maybe_add_leading_slash($masterpage, $hasleadingslash), $lang);
825 return "";
828 sub masterpage ($) {
829 my $page=shift;
831 if ( 1 < (my ($masterpage, $lang) = _istranslation($page))) {
832 return $masterpage;
834 return $page;
837 sub lang ($) {
838 my $page=shift;
840 if (1 < (my ($masterpage, $lang) = _istranslation($page))) {
841 return $lang;
843 return $master_language_code;
846 sub islanguagecode ($) {
847 my $code=shift;
849 return $code =~ /^[a-z]{2}$/;
852 sub otherlanguage_page ($$) {
853 my $page=shift;
854 my $code=shift;
856 return masterpage($page) if $code eq $master_language_code;
857 return masterpage($page) . '.' . $code;
860 # Returns the list of other languages codes: the master language comes first,
861 # then the codes are ordered the same way as in po_slave_languages, if it is
862 # an array, or in the language name lexical order, if it is a hash.
863 sub otherlanguages_codes ($) {
864 my $page=shift;
866 my @ret;
867 return \@ret unless istranslation($page) || istranslatable($page);
868 my $curlang=lang($page);
869 foreach my $lang
870 ($master_language_code, @slavelanguages) {
871 next if $lang eq $curlang;
872 if ($lang eq $master_language_code ||
873 istranslatedto(masterpage($page), $lang)) {
874 push @ret, $lang;
877 return \@ret;
880 sub otherlanguages_pages ($) {
881 my $page=shift;
883 my %ret;
884 map {
885 $ret{$_} = otherlanguage_page($page, $_)
886 } @{otherlanguages_codes($page)};
888 return \%ret;
891 sub potfile ($) {
892 my $masterfile=shift;
894 (my $name, my $dir, my $suffix) = fileparse($masterfile, qr/\.[^.]*/);
895 $dir='' if $dir eq './';
896 return File::Spec->catpath('', $dir, $name . ".pot");
899 sub pofile ($$) {
900 my $masterfile=shift;
901 my $lang=shift;
903 (my $name, my $dir, my $suffix) = fileparse($masterfile, qr/\.[^.]*/);
904 $dir='' if $dir eq './';
905 return File::Spec->catpath('', $dir, $name . "." . $lang . ".po");
908 sub pofiles ($) {
909 my $masterfile=shift;
911 return map pofile($masterfile, $_), @slavelanguages;
914 sub refreshpot ($) {
915 my $masterfile=shift;
917 my $potfile=potfile($masterfile);
918 my $doc=Locale::Po4a::Chooser::new(po4a_type($masterfile),
919 po4a_options($masterfile));
920 $doc->{TT}{utf_mode} = 1;
921 $doc->{TT}{file_in_charset} = 'UTF-8';
922 $doc->{TT}{file_out_charset} = 'UTF-8';
923 $doc->read($masterfile);
924 # let's cheat a bit to force porefs option to be passed to
925 # Locale::Po4a::Po; this is undocument use of internal
926 # Locale::Po4a::TransTractor's data, compulsory since this module
927 # prevents us from using the porefs option.
928 $doc->{TT}{po_out}=Locale::Po4a::Po->new({ 'porefs' => 'none' });
929 $doc->{TT}{po_out}->set_charset('UTF-8');
930 # do the actual work
931 $doc->parse;
932 IkiWiki::prep_writefile(basename($potfile),dirname($potfile));
933 $doc->writepo($potfile);
936 sub refreshpofiles ($@) {
937 my $masterfile=shift;
938 my @pofiles=@_;
940 my $potfile=potfile($masterfile);
941 if (! -e $potfile) {
942 error("po(refreshpofiles) ".sprintf(gettext("POT file (%s) does not exist"), $potfile));
945 foreach my $pofile (@pofiles) {
946 IkiWiki::prep_writefile(basename($pofile),dirname($pofile));
948 if (! -e $pofile) {
949 # If the po file exists in an underlay, copy it
950 # from there.
951 my ($pobase)=$pofile=~/^\Q$config{srcdir}\E\/?(.*)$/;
952 foreach my $dir (@{$config{underlaydirs}}) {
953 if (-e "$dir/$pobase") {
954 File::Copy::syscopy("$dir/$pobase",$pofile)
955 or error("po(refreshpofiles) ".
956 sprintf(gettext("failed to copy underlay PO file to %s"),
957 $pofile));
962 if (-e $pofile) {
963 system("msgmerge", "--previous", "-q", "-U", "--backup=none", $pofile, $potfile) == 0
964 or error("po(refreshpofiles) ".
965 sprintf(gettext("failed to update %s"),
966 $pofile));
968 else {
969 File::Copy::syscopy($potfile,$pofile)
970 or error("po(refreshpofiles) ".
971 sprintf(gettext("failed to copy the POT file to %s"),
972 $pofile));
977 sub buildtranslationscache() {
978 # use istranslation's side-effect
979 map istranslation($_), (keys %pagesources);
982 sub resettranslationscache() {
983 undef %translations;
986 sub flushmemoizecache() {
987 Memoize::flush_cache("istranslatable");
988 Memoize::flush_cache("_istranslation");
989 Memoize::flush_cache("percenttranslated");
992 sub urlto_with_orig_beautiful_urlpath($$) {
993 my $to=shift;
994 my $from=shift;
996 inject(name => "IkiWiki::beautify_urlpath", call => $origsubs{'beautify_urlpath'});
997 my $res=urlto($to, $from);
998 inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath);
1000 return $res;
1003 sub percenttranslated ($) {
1004 my $page=shift;
1006 $page=~s/^\///;
1007 return gettext("N/A") unless istranslation($page);
1008 my $file=srcfile($pagesources{$page});
1009 my $masterfile = srcfile($pagesources{masterpage($page)});
1010 my $doc=Locale::Po4a::Chooser::new(po4a_type($masterfile),
1011 po4a_options($masterfile));
1012 $doc->process(
1013 'po_in_name' => [ $file ],
1014 'file_in_name' => [ $masterfile ],
1015 'file_in_charset' => 'UTF-8',
1016 'file_out_charset' => 'UTF-8',
1017 ) or error("po(percenttranslated) ".
1018 sprintf(gettext("failed to translate %s"), $page));
1019 my ($percent,$hit,$queries) = $doc->stats();
1020 $percent =~ s/\.[0-9]+$//;
1021 return $percent;
1024 sub languagename ($) {
1025 my $code=shift;
1027 return $master_language_name
1028 if $code eq $master_language_code;
1029 return $slavelanguages{$code}
1030 if defined $slavelanguages{$code};
1031 return;
1034 sub otherlanguagesloop ($) {
1035 my $page=shift;
1037 my @ret;
1038 if (istranslation($page)) {
1039 push @ret, {
1040 url => urlto_with_orig_beautiful_urlpath(masterpage($page), $page),
1041 code => $master_language_code,
1042 language => $master_language_name,
1043 master => 1,
1046 foreach my $lang (@{otherlanguages_codes($page)}) {
1047 next if $lang eq $master_language_code;
1048 my $otherpage = otherlanguage_page($page, $lang);
1049 push @ret, {
1050 url => urlto_with_orig_beautiful_urlpath($otherpage, $page),
1051 code => $lang,
1052 language => languagename($lang),
1053 percent => percenttranslated($otherpage),
1056 return @ret;
1059 sub homepageurl (;$) {
1060 my $page=shift;
1062 return urlto('', $page);
1065 sub ishomepage ($) {
1066 my $page = shift;
1068 return 1 if $page eq 'index';
1069 map { return 1 if $page eq 'index.'.$_ } @slavelanguages;
1070 return undef;
1073 sub deletetranslations ($) {
1074 my $deletedmasterfile=shift;
1076 my $deletedmasterpage=pagename($deletedmasterfile);
1077 my @todelete;
1078 map {
1079 my $file = newpagefile($deletedmasterpage.'.'.$_, 'po');
1080 my $absfile = "$config{srcdir}/$file";
1081 if (-e $absfile && ! -l $absfile && ! -d $absfile) {
1082 push @todelete, $file;
1084 } @slavelanguages;
1086 map {
1087 if ($config{rcs}) {
1088 IkiWiki::rcs_remove($_);
1090 else {
1091 IkiWiki::prune("$config{srcdir}/$_");
1093 } @todelete;
1095 if (@todelete) {
1096 commit_and_refresh(
1097 gettext("removed obsolete PO files"));
1101 sub commit_and_refresh ($) {
1102 my $msg = shift;
1104 if ($config{rcs}) {
1105 IkiWiki::disable_commit_hook();
1106 IkiWiki::rcs_commit_staged(
1107 message => $msg,
1109 IkiWiki::enable_commit_hook();
1110 IkiWiki::rcs_update();
1112 # Reinitialize module's private variables.
1113 resetalreadyfiltered();
1114 resettranslationscache();
1115 flushmemoizecache();
1116 # Trigger a wiki refresh.
1117 require IkiWiki::Render;
1118 # without preliminary saveindex/loadindex, refresh()
1119 # complains about a lot of uninitialized variables
1120 IkiWiki::saveindex();
1121 IkiWiki::loadindex();
1122 IkiWiki::refresh();
1123 IkiWiki::saveindex();
1126 sub po_to_markup ($$) {
1127 my ($page, $content) = (shift, shift);
1129 $content = '' unless defined $content;
1130 $content = decode_utf8(encode_utf8($content));
1131 # CRLF line terminators make poor Locale::Po4a feel bad
1132 $content=~s/\r\n/\n/g;
1134 # There are incompatibilities between some File::Temp versions
1135 # (including 0.18, bundled with Lenny's perl-modules package)
1136 # and others (e.g. 0.20, previously present in the archive as
1137 # a standalone package): under certain circumstances, some
1138 # return a relative filename, whereas others return an absolute one;
1139 # we here use this module in a way that is at least compatible
1140 # with 0.18 and 0.20. Beware, hit'n'run refactorers!
1141 my $infile = new File::Temp(TEMPLATE => "ikiwiki-po-filter-in.XXXXXXXXXX",
1142 DIR => File::Spec->tmpdir,
1143 UNLINK => 1)->filename;
1144 my $outfile = new File::Temp(TEMPLATE => "ikiwiki-po-filter-out.XXXXXXXXXX",
1145 DIR => File::Spec->tmpdir,
1146 UNLINK => 1)->filename;
1148 my $fail = sub ($) {
1149 my $msg = "po(po_to_markup) - $page : " . shift;
1150 error($msg, sub { unlink $infile, $outfile});
1153 writefile(basename($infile), File::Spec->tmpdir, $content)
1154 or return $fail->(sprintf(gettext("failed to write %s"), $infile));
1156 my $masterfile = srcfile($pagesources{masterpage($page)});
1157 my $doc=Locale::Po4a::Chooser::new(po4a_type($masterfile),
1158 po4a_options($masterfile));
1159 $doc->process(
1160 'po_in_name' => [ $infile ],
1161 'file_in_name' => [ $masterfile ],
1162 'file_in_charset' => 'UTF-8',
1163 'file_out_charset' => 'UTF-8',
1164 ) or return $fail->(gettext("failed to translate"));
1165 $doc->write($outfile)
1166 or return $fail->(sprintf(gettext("failed to write %s"), $outfile));
1168 $content = readfile($outfile);
1170 # Unlinking should happen automatically, thanks to File::Temp,
1171 # but it does not work here, probably because of the way writefile()
1172 # and Locale::Po4a::write() work.
1173 unlink $infile, $outfile;
1175 return $content;
1178 # returns a SuccessReason or FailReason object
1179 sub isvalidpo ($) {
1180 my $content = shift;
1182 # NB: we don't use po_to_markup here, since Po4a parser does
1183 # not mind invalid PO content
1184 $content = '' unless defined $content;
1185 $content = decode_utf8(encode_utf8($content));
1187 # There are incompatibilities between some File::Temp versions
1188 # (including 0.18, bundled with Lenny's perl-modules package)
1189 # and others (e.g. 0.20, previously present in the archive as
1190 # a standalone package): under certain circumstances, some
1191 # return a relative filename, whereas others return an absolute one;
1192 # we here use this module in a way that is at least compatible
1193 # with 0.18 and 0.20. Beware, hit'n'run refactorers!
1194 my $infile = new File::Temp(TEMPLATE => "ikiwiki-po-isvalidpo.XXXXXXXXXX",
1195 DIR => File::Spec->tmpdir,
1196 UNLINK => 1)->filename;
1198 my $fail = sub ($) {
1199 my $msg = '[po/isvalidpo] ' . shift;
1200 unlink $infile;
1201 return IkiWiki::FailReason->new("$msg");
1204 writefile(basename($infile), File::Spec->tmpdir, $content)
1205 or return $fail->(sprintf(gettext("failed to write %s"), $infile));
1207 my $res = (system("msgfmt", "--check", $infile, "-o", "/dev/null") == 0);
1209 # Unlinking should happen automatically, thanks to File::Temp,
1210 # but it does not work here, probably because of the way writefile()
1211 # and Locale::Po4a::write() work.
1212 unlink $infile;
1214 if ($res) {
1215 return IkiWiki::SuccessReason->new("valid gettext data");
1217 return IkiWiki::FailReason->new(gettext("invalid gettext data, go back ".
1218 "to previous page to continue edit"));
1221 sub po4a_type ($) {
1222 my $file = shift;
1224 my $pagetype = pagetype($file);
1225 if ($pagetype eq 'html') {
1226 return 'xhtml';
1228 return 'text';
1231 sub po4a_options($) {
1232 my $file = shift;
1234 my %options;
1235 my $pagetype = pagetype($file);
1237 if ($pagetype eq 'html') {
1238 # how to disable options is not consistent across po4a modules
1239 $options{includessi} = '';
1240 $options{includeexternal} = 0;
1242 elsif ($pagetype eq 'mdwn') {
1243 $options{markdown} = 1;
1245 else {
1246 $options{markdown} = 0;
1249 return %options;
1252 sub splitlangpair ($) {
1253 my $pair=shift;
1255 my ($code, $name) = ( $pair =~ /^([a-z]{2})\|(.+)$/ );
1256 if (! defined $code || ! defined $name ||
1257 ! length $code || ! length $name) {
1258 # not a fatal error to avoid breaking if used with web setup
1259 warn sprintf(gettext("%s has invalid syntax: must use CODE|NAME"),
1260 $pair);
1263 return $code, $name;
1266 sub joinlangpair ($$) {
1267 my $code=shift;
1268 my $name=shift;
1270 return "$code|$name";
1273 # ,----
1274 # | PageSpecs
1275 # `----
1277 package IkiWiki::PageSpec;
1279 sub match_istranslation ($;@) {
1280 my $page=shift;
1282 if (IkiWiki::Plugin::po::istranslation($page)) {
1283 return IkiWiki::SuccessReason->new("is a translation page");
1285 else {
1286 return IkiWiki::FailReason->new("is not a translation page");
1290 sub match_istranslatable ($;@) {
1291 my $page=shift;
1293 if (IkiWiki::Plugin::po::istranslatable($page)) {
1294 return IkiWiki::SuccessReason->new("is set as translatable in po_translatable_pages");
1296 else {
1297 return IkiWiki::FailReason->new("is not set as translatable in po_translatable_pages");
1301 sub match_lang ($$;@) {
1302 my $page=shift;
1303 my $wanted=shift;
1305 my $regexp=IkiWiki::glob2re($wanted);
1306 my $lang=IkiWiki::Plugin::po::lang($page);
1307 if ($lang !~ $regexp) {
1308 return IkiWiki::FailReason->new("file language is $lang, not $wanted");
1310 else {
1311 return IkiWiki::SuccessReason->new("file language is $wanted");
1315 sub match_currentlang ($$;@) {
1316 my $page=shift;
1317 shift;
1318 my %params=@_;
1320 return IkiWiki::FailReason->new("no location provided") unless exists $params{location};
1322 my $currentlang=IkiWiki::Plugin::po::lang($params{location});
1323 my $lang=IkiWiki::Plugin::po::lang($page);
1325 if ($lang eq $currentlang) {
1326 return IkiWiki::SuccessReason->new("file language is the same as current one, i.e. $currentlang");
1328 else {
1329 return IkiWiki::FailReason->new("file language is $lang, whereas current language is $currentlang");
1333 sub match_needstranslation ($$;@) {
1334 my $page=shift;
1335 my $wanted=shift;
1337 if (defined $wanted && $wanted ne "") {
1338 if ($wanted !~ /^\d+$/) {
1339 return IkiWiki::FailReason->new("parameter is not an integer");
1341 elsif ($wanted > 100) {
1342 return IkiWiki::FailReason->new("parameter is greater than 100");
1345 else {
1346 $wanted=100;
1349 my $percenttranslated=IkiWiki::Plugin::po::percenttranslated($page);
1350 if ($percenttranslated eq 'N/A') {
1351 return IkiWiki::FailReason->new("file is not a translatable page");
1353 elsif ($percenttranslated < $wanted) {
1354 return IkiWiki::SuccessReason->new("file has $percenttranslated translated");
1356 else {
1357 return IkiWiki::FailReason->new("file is translated enough");