]> sipb.mit.edu Git - ikiwiki.git/blob - IkiWiki/Plugin/po.pm
Merge branch 'master' of ssh://git.ikiwiki.info/srv/git/ikiwiki.info
[ikiwiki.git] / IkiWiki / Plugin / po.pm
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;
8
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 $@;
18 }
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;
27
28 my %translations;
29 my @origneedsbuild;
30 my %origsubs;
31
32 memoize("istranslatable");
33 memoize("_istranslation");
34 memoize("percenttranslated");
35
36 sub import {
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);
53
54         $origsubs{'beautify_urlpath'}=\&IkiWiki::beautify_urlpath;
55         inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath);
56         $origsubs{'targetpage'}=\&IkiWiki::targetpage;
57         inject(name => "IkiWiki::targetpage", call => \&mytargetpage);
58         $origsubs{'urlto'}=\&IkiWiki::urlto;
59         inject(name => "IkiWiki::urlto", call => \&myurlto);
60         $origsubs{'cgiurl'}=\&IkiWiki::cgiurl;
61         inject(name => "IkiWiki::cgiurl", call => \&mycgiurl);
62         $origsubs{'rootpage'}=\&IkiWiki::rootpage;
63         inject(name => "IkiWiki::rootpage", call => \&myrootpage);
64 }
65
66
67 # ,----
68 # | Table of contents
69 # `----
70
71 # 1. Hooks
72 # 2. Injected functions
73 # 3. Blackboxes for private data
74 # 4. Helper functions
75 # 5. PageSpecs
76
77
78 # ,----
79 # | Hooks
80 # `----
81
82 sub getsetup () {
83         return
84                 plugin => {
85                         safe => 0,
86                         rebuild => 1,
87                 },
88                 po_master_language => {
89                         type => "string",
90                         example => {
91                                 'code' => 'en',
92                                 'name' => 'English'
93                         },
94                         description => "master language (non-PO files)",
95                         safe => 1,
96                         rebuild => 1,
97                 },
98                 po_slave_languages => {
99                         type => "string",
100                         example => {
101                                 'fr' => 'Français',
102                                 'es' => 'Español',
103                                 'de' => 'Deutsch'
104                         },
105                         description => "slave languages (PO files)",
106                         safe => 1,
107                         rebuild => 1,
108                 },
109                 po_translatable_pages => {
110                         type => "pagespec",
111                         example => "* and !*/Discussion",
112                         description => "PageSpec controlling which pages are translatable",
113                         link => "ikiwiki/PageSpec",
114                         safe => 1,
115                         rebuild => 1,
116                 },
117                 po_link_to => {
118                         type => "string",
119                         example => "current",
120                         description => "internal linking behavior (default/current/negotiated)",
121                         safe => 1,
122                         rebuild => 1,
123                 },
124 }
125
126 sub checkconfig () {
127         foreach my $field (qw{po_master_language}) {
128                 if (! exists $config{$field} || ! defined $config{$field}) {
129                         error(sprintf(gettext("Must specify %s when using the %s plugin"),
130                                       $field, 'po'));
131                 }
132         }
133
134         map {
135                 islanguagecode($_)
136                         or error(sprintf(gettext("%s is not a valid language code"), $_));
137         } ($config{po_master_language}{code}, keys %{$config{po_slave_languages}});
138
139         if (! exists $config{po_translatable_pages} ||
140             ! defined $config{po_translatable_pages}) {
141                 $config{po_translatable_pages}="";
142         }
143         if (! exists $config{po_link_to} ||
144             ! defined $config{po_link_to}) {
145                 $config{po_link_to}='default';
146         }
147         elsif ($config{po_link_to} !~ /^(default|current|negotiated)$/) {
148                 warn(sprintf(gettext('%s is not a valid value for po_link_to, falling back to po_link_to=default'),
149                              $config{po_link_to}));
150                 $config{po_link_to}='default';
151         }
152         elsif ($config{po_link_to} eq "negotiated" && ! $config{usedirs}) {
153                 warn(gettext('po_link_to=negotiated requires usedirs to be enabled, falling back to po_link_to=default'));
154                 $config{po_link_to}='default';
155         }
156         unless ($config{po_link_to} eq 'default') {
157                 if (! exists $origsubs{'bestlink'}) {
158                         $origsubs{'bestlink'}=\&IkiWiki::bestlink;
159                         inject(name => "IkiWiki::bestlink", call => \&mybestlink);
160                 }
161         }
162
163         push @{$config{wiki_file_prune_regexps}}, qr/\.pot$/;
164
165         # Translated versions of the underlays are added if available.
166         foreach my $underlay ("basewiki",
167                               map { m/^\Q$config{underlaydirbase}\E\/*(.*)/ }
168                                   reverse @{$config{underlaydirs}}) {
169                 next if $underlay=~/^locale\//;
170
171                 # Underlays containing the po files for slave languages.
172                 foreach my $ll (keys %{$config{po_slave_languages}}) {
173                         add_underlay("po/$ll/$underlay")
174                                 if -d "$config{underlaydirbase}/po/$ll/$underlay";
175                 }
176         
177                 if ($config{po_master_language}{code} ne 'en') {
178                         # Add underlay containing translated source files
179                         # for the master language.
180                         add_underlay("locale/$config{po_master_language}{code}/$underlay");
181                 }
182         }
183 }
184
185 sub needsbuild () {
186         my $needsbuild=shift;
187
188         # backup @needsbuild content so that change() can know whether
189         # a given master page was rendered because its source file was changed
190         @origneedsbuild=(@$needsbuild);
191
192         flushmemoizecache();
193         buildtranslationscache();
194
195         # make existing translations depend on the corresponding master page
196         foreach my $master (keys %translations) {
197                 map add_depends($_, $master), values %{otherlanguages($master)};
198         }
199 }
200
201 # Massage the recorded state of internal links so that:
202 # - it matches the actually generated links, rather than the links as written
203 #   in the pages' source
204 # - backlinks are consistent in all cases
205 sub scan (@) {
206         my %params=@_;
207         my $page=$params{page};
208         my $content=$params{content};
209
210         if (istranslation($page)) {
211                 foreach my $destpage (@{$links{$page}}) {
212                         if (istranslatable($destpage)) {
213                                 # replace the occurence of $destpage in $links{$page}
214                                 for (my $i=0; $i<@{$links{$page}}; $i++) {
215                                         if (@{$links{$page}}[$i] eq $destpage) {
216                                                 @{$links{$page}}[$i] = $destpage . '.' . lang($page);
217                                                 last;
218                                         }
219                                 }
220                         }
221                 }
222         }
223         elsif (! istranslatable($page) && ! istranslation($page)) {
224                 foreach my $destpage (@{$links{$page}}) {
225                         if (istranslatable($destpage)) {
226                                 # make sure any destpage's translations has
227                                 # $page in its backlinks
228                                 push @{$links{$page}},
229                                         values %{otherlanguages($destpage)};
230                         }
231                 }
232         }
233 }
234
235 # We use filter to convert PO to the master page's format,
236 # since the rest of ikiwiki should not work on PO files.
237 sub filter (@) {
238         my %params = @_;
239
240         my $page = $params{page};
241         my $destpage = $params{destpage};
242         my $content = $params{content};
243         if (istranslation($page) && ! alreadyfiltered($page, $destpage)) {
244                 $content = po_to_markup($page, $content);
245                 setalreadyfiltered($page, $destpage);
246         }
247         return $content;
248 }
249
250 sub htmlize (@) {
251         my %params=@_;
252
253         my $page = $params{page};
254         my $content = $params{content};
255
256         # ignore PO files this plugin did not create
257         return $content unless istranslation($page);
258
259         # force content to be htmlize'd as if it was the same type as the master page
260         return IkiWiki::htmlize($page, $page,
261                 pagetype(srcfile($pagesources{masterpage($page)})),
262                 $content);
263 }
264
265 sub pagetemplate (@) {
266         my %params=@_;
267         my $page=$params{page};
268         my $destpage=$params{destpage};
269         my $template=$params{template};
270
271         my ($masterpage, $lang) = istranslation($page);
272
273         if (istranslation($page) && $template->query(name => "percenttranslated")) {
274                 $template->param(percenttranslated => percenttranslated($page));
275         }
276         if ($template->query(name => "istranslation")) {
277                 $template->param(istranslation => scalar istranslation($page));
278         }
279         if ($template->query(name => "istranslatable")) {
280                 $template->param(istranslatable => istranslatable($page));
281         }
282         if ($template->query(name => "HOMEPAGEURL")) {
283                 $template->param(homepageurl => homepageurl($page));
284         }
285         if ($template->query(name => "otherlanguages")) {
286                 $template->param(otherlanguages => [otherlanguagesloop($page)]);
287                 map add_depends($page, $_), (values %{otherlanguages($page)});
288         }
289         if ($config{discussion} && istranslation($page)) {
290                 if ($page !~ /.*\/\Q$config{discussionpage}\E$/i &&
291                    (length $config{cgiurl} ||
292                     exists $links{$masterpage."/".lc($config{discussionpage})})) {
293                         $template->param('discussionlink' => htmllink(
294                                 $page,
295                                 $destpage,
296                                 $masterpage . '/' . $config{discussionpage},
297                                 noimageinline => 1,
298                                 forcesubpage => 0,
299                                 linktext => $config{discussionpage},
300                 ));
301                 }
302         }
303         # Remove broken parentlink to ./index.html on home page's translations.
304         # It works because this hook has the "last" parameter set, to ensure it
305         # runs after parentlinks' own pagetemplate hook.
306         if ($template->param('parentlinks')
307             && istranslation($page)
308             && $masterpage eq "index") {
309                 $template->param('parentlinks' => []);
310         }
311         if (ishomepage($page) && $template->query(name => "title")) {
312                 $template->param(title => $config{wikiname});
313         }
314 } # }}}
315
316 # Add the renamed page translations to the list of to-be-renamed pages.
317 sub renamepages (@) {
318         my %params = @_;
319
320         my %torename = %{$params{torename}};
321         my $session = $params{session};
322
323         # Save the page(s) the user asked to rename, so that our
324         # canrename hook can tell the difference between:
325         #  - a translation being renamed as a consequence of its master page
326         #    being renamed
327         #  - a user trying to directly rename a translation
328         # This is why this hook has to be run first, before the list of pages
329         # to rename is modified by other plugins.
330         my @orig_torename;
331         @orig_torename=@{$session->param("po_orig_torename")}
332                 if defined $session->param("po_orig_torename");
333         push @orig_torename, $torename{src};
334         $session->param(po_orig_torename => \@orig_torename);
335         IkiWiki::cgi_savesession($session);
336
337         return () unless istranslatable($torename{src});
338
339         my @ret;
340         my %otherpages=%{otherlanguages($torename{src})};
341         while (my ($lang, $otherpage) = each %otherpages) {
342                 push @ret, {
343                         src => $otherpage,
344                         srcfile => $pagesources{$otherpage},
345                         dest => otherlanguage($torename{dest}, $lang),
346                         destfile => $torename{dest}.".".$lang.".po",
347                         required => 0,
348                 };
349         }
350         return @ret;
351 }
352
353 sub mydelete (@) {
354         my @deleted=@_;
355
356         map { deletetranslations($_) } grep istranslatablefile($_), @deleted;
357 }
358
359 sub change (@) {
360         my @rendered=@_;
361
362         # All meta titles are first extracted at scan time, i.e. before we turn
363         # PO files back into translated markdown; escaping of double-quotes in
364         # PO files breaks the meta plugin's parsing enough to save ugly titles
365         # to %pagestate at this time.
366         #
367         # Then, at render time, every page passes in turn through the Great
368         # Rendering Chain (filter->preprocess->linkify->htmlize), and the meta
369         # plugin's preprocess hook is this time in a position to correctly
370         # extract the titles from slave pages.
371         #
372         # This is, unfortunately, too late: if the page A, linking to the page
373         # B, is rendered before B, it will display the wrongly-extracted meta
374         # title as the link text to B.
375         #
376         # On the one hand, such a corner case only happens on rebuild: on
377         # refresh, every rendered page is fixed to contain correct meta titles.
378         # On the other hand, it can take some time to get every page fixed.
379         # We therefore re-render every rendered page after a rebuild to fix them
380         # at once. As this more or less doubles the time needed to rebuild the
381         # wiki, we do so only when really needed.
382
383         if (@rendered
384             && exists $config{rebuild} && defined $config{rebuild} && $config{rebuild}
385             && UNIVERSAL::can("IkiWiki::Plugin::meta", "getsetup")
386             && exists $config{meta_overrides_page_title}
387             && defined $config{meta_overrides_page_title}
388             && $config{meta_overrides_page_title}) {
389                 debug(sprintf(gettext("rebuilding all pages to fix meta titles")));
390                 resetalreadyfiltered();
391                 require IkiWiki::Render;
392                 foreach my $file (@rendered) {
393                         debug(sprintf(gettext("building %s"), $file));
394                         IkiWiki::render($file);
395                 }
396         }
397
398         my $updated_po_files=0;
399
400         # Refresh/create POT and PO files as needed.
401         # (But avoid doing so if they are in an underlay directory.)
402         foreach my $file (grep {istranslatablefile($_)} @rendered) {
403                 my $masterfile=srcfile($file);
404                 my $page=pagename($file);
405                 my $updated_pot_file=0;
406                 # Only refresh POT file if it does not exist, or if
407                 # $pagesources{$page} was changed: don't if only the HTML was
408                 # refreshed, e.g. because of a dependency.
409                 if ($masterfile eq "$config{srcdir}/$file" &&
410                    ((grep { $_ eq $pagesources{$page} } @origneedsbuild)
411                     || ! -e potfile($masterfile))) {
412                         refreshpot($masterfile);
413                         $updated_pot_file=1;
414                 }
415                 my @pofiles;
416                 foreach my $po (pofiles($masterfile)) {
417                         next if ! $updated_pot_file && ! -e $po;
418                         next if grep { $po=~/\Q$_\E/ } @{$config{underlaydirs}};
419                         push @pofiles, $po;
420                 }
421                 if (@pofiles) {
422                         refreshpofiles($masterfile, @pofiles);
423                         map { s/^\Q$config{srcdir}\E\/*//; IkiWiki::rcs_add($_) } @pofiles if $config{rcs};
424                         $updated_po_files=1;
425                 }
426         }
427
428         if ($updated_po_files) {
429                 commit_and_refresh(
430                         gettext("updated PO files"),
431                         "IkiWiki::Plugin::po::change");
432         }
433 }
434
435 sub checkcontent (@) {
436         my %params=@_;
437
438         if (istranslation($params{page})) {
439                 my $res = isvalidpo($params{content});
440                 if ($res) {
441                         return undef;
442                 }
443                 else {
444                         return "$res";
445                 }
446         }
447         return undef;
448 }
449
450 sub canremove (@) {
451         my %params = @_;
452
453         if (istranslation($params{page})) {
454                 return gettext("Can not remove a translation. If the master page is removed, ".
455                                "however, its translations will be removed as well.");
456         }
457         return undef;
458 }
459
460 sub canrename (@) {
461         my %params = @_;
462         my $session = $params{session};
463
464         if (istranslation($params{src})) {
465                 my $masterpage = masterpage($params{src});
466                 # Tell the difference between:
467                 #  - a translation being renamed as a consequence of its master page
468                 #    being renamed, which is allowed
469                 #  - a user trying to directly rename a translation, which is forbidden
470                 # by looking for the master page in the list of to-be-renamed pages we
471                 # saved early in the renaming process.
472                 my $orig_torename = $session->param("po_orig_torename");
473                 unless (grep { $_ eq $masterpage } @{$orig_torename}) {
474                         return gettext("Can not rename a translation. If the master page is renamed, ".
475                                        "however, its translations will be renamed as well.");
476                 }
477         }
478         return undef;
479 }
480
481 # As we're previewing or saving a page, the content may have
482 # changed, so tell the next filter() invocation it must not be lazy.
483 sub editcontent () {
484         my %params=@_;
485
486         unsetalreadyfiltered($params{page}, $params{page});
487         return $params{content};
488 }
489
490 sub formbuilder_setup (@) {
491         my %params=@_;
492         my $form=$params{form};
493         my $q=$params{cgi};
494
495         return unless defined $form->field("do");
496
497         if ($form->field("do") eq "create") {
498                 # Warn the user: new pages must be written in master language.
499                 my $template=template("pocreatepage.tmpl");
500                 $template->param(LANG => $config{po_master_language}{name});
501                 $form->tmpl_param(message => $template->output);
502         }
503         elsif ($form->field("do") eq "edit") {
504                 # Remove the rename/remove buttons on slave pages.
505                 # This has to be done after the rename/remove plugins have added
506                 # their buttons, which is why this hook must be run last.
507                 # The canrename/canremove hooks already ensure this is forbidden
508                 # at the backend level, so this is only UI sugar.
509                 if (istranslation($form->field("page"))) {
510                         map {
511                                 for (my $i = 0; $i < @{$params{buttons}}; $i++) {
512                                         if (@{$params{buttons}}[$i] eq $_) {
513                                                 delete  @{$params{buttons}}[$i];
514                                                 last;
515                                         }
516                                 }
517                         } qw(Rename Remove);
518                 }
519         }
520 }
521
522 sub formbuilder (@) {
523         my %params=@_;
524         my $form=$params{form};
525         my $q=$params{cgi};
526
527         return unless defined $form->field("do");
528
529         # Do not allow to create pages of type po: they are automatically created.
530         # The main reason to do so is to bypass the "favor the type of linking page
531         # on page creation" logic, which is unsuitable when a broken link is clicked
532         # on a slave (PO) page.
533         # This cannot be done in the formbuilder_setup hook as the list of types is
534         # computed later.
535         if ($form->field("do") eq "create") {
536                 foreach my $field ($form->field) {
537                         next unless "$field" eq "type";
538                         next unless $field->type eq 'select';
539                         my $orig_value = $field->value;
540                         # remove po from the list of types
541                         my @types = grep { $_->[0] ne 'po' } $field->options;
542                         $field->options(\@types) if @types;
543                         # favor the type of linking page's masterpage
544                         if ($orig_value eq 'po') {
545                                 my ($from, $type);
546                                 if (defined $form->field('from')) {
547                                         ($from)=$form->field('from')=~/$config{wiki_file_regexp}/;
548                                         $from = masterpage($from);
549                                 }
550                                 if (defined $from && exists $pagesources{$from}) {
551                                         $type=pagetype($pagesources{$from});
552                                 }
553                                 $type=$config{default_pageext} unless defined $type;
554                                 $field->value($type) ;
555                         }
556                 }
557         }
558 }
559
560 # ,----
561 # | Injected functions
562 # `----
563
564 # Implement po_link_to 'current' and 'negotiated' settings.
565 # Not injected otherwise.
566 sub mybestlink ($$) {
567         my $page=shift;
568         my $link=shift;
569
570         my $res=$origsubs{'bestlink'}->(masterpage($page), $link);
571         my @caller = caller(1);
572         if (length $res
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);
578         }
579         return $res;
580 }
581
582 sub mybeautify_urlpath ($) {
583         my $url=shift;
584
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$!/!;
589                 map {
590                         $res =~ s!/\Qindex.$_.$config{htmlext}\E$!/!;
591                 } (keys %{$config{po_slave_languages}});
592         }
593         return $res;
594 }
595
596 sub mytargetpage ($$) {
597         my $page=shift;
598         my $ext=shift;
599
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;
604                 }
605                 else {
606                         return $masterpage . "/index." . $lang . "." . $ext;
607                 }
608         }
609         return $origsubs{'targetpage'}->($page, $ext);
610 }
611
612 sub myurlto ($$;$) {
613         my $to=shift;
614         my $from=shift;
615         my $absolute=shift;
616
617         # workaround hard-coded /index.$config{htmlext} in IkiWiki::urlto()
618         if (! length $to
619             && $config{po_link_to} eq "current"
620             && istranslatable('index')) {
621                 return IkiWiki::beautify_urlpath(IkiWiki::baseurl($from) . "index." . lang($from) . ".$config{htmlext}");
622         }
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);
632                 my $use_orig = 0;
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")
636                                  );
637                 inject(name => "IkiWiki::beautify_urlpath", call => $origsubs{'beautify_urlpath'})
638                         if $use_orig;
639                 my $res = $origsubs{'urlto'}->($to,$from,$absolute);
640                 inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath)
641                         if $use_orig;
642                 return $res;
643         }
644         else {
645                 return $origsubs{'urlto'}->($to,$from,$absolute)
646         }
647 }
648
649 sub mycgiurl (@) {
650         my %params=@_;
651
652         # slave pages have no subpages
653         if (istranslation($params{'from'})) {
654                 $params{'from'} = masterpage($params{'from'});
655         }
656         return $origsubs{'cgiurl'}->(%params);
657 }
658
659 sub myrootpage (@) {
660         my %params=@_;
661
662         my $rootpage;
663         if (exists $params{rootpage}) {
664                 $rootpage=$origsubs{'bestlink'}->($params{page}, $params{rootpage});
665                 if (!length $rootpage) {
666                         $rootpage=$params{rootpage};
667                 }
668         }
669         else {
670                 $rootpage=masterpage($params{page});
671         }
672         return $rootpage;
673 }
674
675 # ,----
676 # | Blackboxes for private data
677 # `----
678
679 {
680         my %filtered;
681
682         sub alreadyfiltered($$) {
683                 my $page=shift;
684                 my $destpage=shift;
685
686                 return exists $filtered{$page}{$destpage}
687                          && $filtered{$page}{$destpage} eq 1;
688         }
689
690         sub setalreadyfiltered($$) {
691                 my $page=shift;
692                 my $destpage=shift;
693
694                 $filtered{$page}{$destpage}=1;
695         }
696
697         sub unsetalreadyfiltered($$) {
698                 my $page=shift;
699                 my $destpage=shift;
700
701                 if (exists $filtered{$page}{$destpage}) {
702                         delete $filtered{$page}{$destpage};
703                 }
704         }
705
706         sub resetalreadyfiltered() {
707                 undef %filtered;
708         }
709 }
710
711 # ,----
712 # | Helper functions
713 # `----
714
715 sub maybe_add_leading_slash ($;$) {
716         my $str=shift;
717         my $add=shift;
718         $add=1 unless defined $add;
719         return '/' . $str if $add;
720         return $str;
721 }
722
723 sub istranslatablefile ($) {
724         my $file=shift;
725
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});
731         return;
732 }
733
734 sub istranslatable ($) {
735         my $page=shift;
736
737         $page=~s#^/##;
738         return 1 if istranslatablefile($pagesources{$page});
739         return;
740 }
741
742 sub _istranslation ($) {
743         my $page=shift;
744
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$/;
752
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};
758
759         return (maybe_add_leading_slash($masterpage, $hasleadingslash), $lang)
760                 if istranslatable($masterpage);
761 }
762
763 sub istranslation ($) {
764         my $page=shift;
765
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);
770         }
771         return "";
772 }
773
774 sub masterpage ($) {
775         my $page=shift;
776
777         if ( 1 < (my ($masterpage, $lang) = _istranslation($page))) {
778                 return $masterpage;
779         }
780         return $page;
781 }
782
783 sub lang ($) {
784         my $page=shift;
785
786         if (1 < (my ($masterpage, $lang) = _istranslation($page))) {
787                 return $lang;
788         }
789         return $config{po_master_language}{code};
790 }
791
792 sub islanguagecode ($) {
793         my $code=shift;
794
795         return $code =~ /^[a-z]{2}$/;
796 }
797
798 sub otherlanguage ($$) {
799         my $page=shift;
800         my $code=shift;
801
802         return masterpage($page) if $code eq $config{po_master_language}{code};
803         return masterpage($page) . '.' . $code;
804 }
805
806 sub otherlanguages ($) {
807         my $page=shift;
808
809         my %ret;
810         return \%ret unless istranslation($page) || istranslatable($page);
811         my $curlang=lang($page);
812         foreach my $lang
813                 ($config{po_master_language}{code}, keys %{$config{po_slave_languages}}) {
814                 next if $lang eq $curlang;
815                 $ret{$lang}=otherlanguage($page, $lang);
816         }
817         return \%ret;
818 }
819
820 sub potfile ($) {
821         my $masterfile=shift;
822
823         (my $name, my $dir, my $suffix) = fileparse($masterfile, qr/\.[^.]*/);
824         $dir='' if $dir eq './';
825         return File::Spec->catpath('', $dir, $name . ".pot");
826 }
827
828 sub pofile ($$) {
829         my $masterfile=shift;
830         my $lang=shift;
831
832         (my $name, my $dir, my $suffix) = fileparse($masterfile, qr/\.[^.]*/);
833         $dir='' if $dir eq './';
834         return File::Spec->catpath('', $dir, $name . "." . $lang . ".po");
835 }
836
837 sub pofiles ($) {
838         my $masterfile=shift;
839
840         return map pofile($masterfile, $_), (keys %{$config{po_slave_languages}});
841 }
842
843 sub refreshpot ($) {
844         my $masterfile=shift;
845
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');
859         # do the actual work
860         $doc->parse;
861         IkiWiki::prep_writefile(basename($potfile),dirname($potfile));
862         $doc->writepo($potfile);
863 }
864
865 sub refreshpofiles ($@) {
866         my $masterfile=shift;
867         my @pofiles=@_;
868
869         my $potfile=potfile($masterfile);
870         if (! -e $potfile) {
871                 error("po(refreshpofiles) ".sprintf(gettext("POT file (%s) does not exist"), $potfile));
872         }
873
874         foreach my $pofile (@pofiles) {
875                 IkiWiki::prep_writefile(basename($pofile),dirname($pofile));
876
877                 if (! -e $pofile) {
878                         # If the po file exists in an underlay, copy it
879                         # from there.
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"),
886                                                                  $pofile));
887                                 }
888                         }
889                 }
890
891                 if (-e $pofile) {
892                         system("msgmerge", "--previous", "-q", "-U", "--backup=none", $pofile, $potfile) == 0
893                                 or error("po(refreshpofiles) ".
894                                          sprintf(gettext("failed to update %s"),
895                                                  $pofile));
896                 }
897                 else {
898                         File::Copy::syscopy($potfile,$pofile)
899                                 or error("po(refreshpofiles) ".
900                                          sprintf(gettext("failed to copy the POT file to %s"),
901                                                  $pofile));
902                 }
903         }
904 }
905
906 sub buildtranslationscache() {
907         # use istranslation's side-effect
908         map istranslation($_), (keys %pagesources);
909 }
910
911 sub resettranslationscache() {
912         undef %translations;
913 }
914
915 sub flushmemoizecache() {
916         Memoize::flush_cache("istranslatable");
917         Memoize::flush_cache("_istranslation");
918         Memoize::flush_cache("percenttranslated");
919 }
920
921 sub urlto_with_orig_beautiful_urlpath($$) {
922         my $to=shift;
923         my $from=shift;
924
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);
928
929         return $res;
930 }
931
932 sub percenttranslated ($) {
933         my $page=shift;
934
935         $page=~s/^\///;
936         return gettext("N/A") unless istranslation($page);
937         my $file=srcfile($pagesources{$page});
938         my $masterfile = srcfile($pagesources{masterpage($page)});
939         my %options = (
940                 "markdown" => (pagetype($masterfile) eq 'mdwn') ? 1 : 0,
941         );
942         my $doc=Locale::Po4a::Chooser::new('text',%options);
943         $doc->process(
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]+$//;
952         return $percent;
953 }
954
955 sub languagename ($) {
956         my $code=shift;
957
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};
962         return;
963 }
964
965 sub otherlanguagesloop ($) {
966         my $page=shift;
967
968         my @ret;
969         my %otherpages=%{otherlanguages($page)};
970         while (my ($lang, $otherpage) = each %otherpages) {
971                 if (istranslation($page) && masterpage($page) eq $otherpage) {
972                         push @ret, {
973                                 url => urlto_with_orig_beautiful_urlpath($otherpage, $page),
974                                 code => $lang,
975                                 language => languagename($lang),
976                                 master => 1,
977                         };
978                 }
979                 elsif (istranslation($otherpage)) {
980                         push @ret, {
981                                 url => urlto_with_orig_beautiful_urlpath($otherpage, $page),
982                                 code => $lang,
983                                 language => languagename($lang),
984                                 percent => percenttranslated($otherpage),
985                         }
986                 }
987         }
988         return sort {
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};
992         } @ret;
993 }
994
995 sub homepageurl (;$) {
996         my $page=shift;
997
998         return urlto('', $page);
999 }
1000
1001 sub ishomepage ($) {
1002         my $page = shift;
1003
1004         return 1 if $page eq 'index';
1005         map { return 1 if $page eq 'index.'.$_ } keys %{$config{po_slave_languages}};
1006         return undef;
1007 }
1008
1009 sub deletetranslations ($) {
1010         my $deletedmasterfile=shift;
1011
1012         my $deletedmasterpage=pagename($deletedmasterfile);
1013         my @todelete;
1014         map {
1015                 my $file = newpagefile($deletedmasterpage.'.'.$_, 'po');
1016                 my $absfile = "$config{srcdir}/$file";
1017                 if (-e $absfile && ! -l $absfile && ! -d $absfile) {
1018                         push @todelete, $file;
1019                 }
1020         } keys %{$config{po_slave_languages}};
1021
1022         map {
1023                 if ($config{rcs}) {
1024                         IkiWiki::rcs_remove($_);
1025                 }
1026                 else {
1027                         IkiWiki::prune("$config{srcdir}/$_");
1028                 }
1029         } @todelete;
1030
1031         if (@todelete) {
1032                 commit_and_refresh(
1033                         gettext("removed obsolete PO files"),
1034                         "IkiWiki::Plugin::po::deletetranslations");
1035         }
1036 }
1037
1038 sub commit_and_refresh ($$) {
1039         my ($msg, $author) = (shift, shift);
1040
1041         if ($config{rcs}) {
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();
1046         }
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();
1057         IkiWiki::refresh();
1058         IkiWiki::saveindex();
1059 }
1060
1061 # on success, returns the filtered content.
1062 # on error, if $nonfatal, warn and return undef; else, error out.
1063 sub po_to_markup ($$;$) {
1064         my ($page, $content) = (shift, shift);
1065         my $nonfatal = shift;
1066
1067         $content = '' unless defined $content;
1068         $content = decode_utf8(encode_utf8($content));
1069         # CRLF line terminators make poor Locale::Po4a feel bad
1070         $content=~s/\r\n/\n/g;
1071
1072         # There are incompatibilities between some File::Temp versions
1073         # (including 0.18, bundled with Lenny's perl-modules package)
1074         # and others (e.g. 0.20, previously present in the archive as
1075         # a standalone package): under certain circumstances, some
1076         # return a relative filename, whereas others return an absolute one;
1077         # we here use this module in a way that is at least compatible
1078         # with 0.18 and 0.20. Beware, hit'n'run refactorers!
1079         my $infile = new File::Temp(TEMPLATE => "ikiwiki-po-filter-in.XXXXXXXXXX",
1080                                     DIR => File::Spec->tmpdir,
1081                                     UNLINK => 1)->filename;
1082         my $outfile = new File::Temp(TEMPLATE => "ikiwiki-po-filter-out.XXXXXXXXXX",
1083                                      DIR => File::Spec->tmpdir,
1084                                      UNLINK => 1)->filename;
1085
1086         my $fail = sub ($) {
1087                 my $msg = "po(po_to_markup) - $page : " . shift;
1088                 if ($nonfatal) {
1089                         warn $msg;
1090                         return undef;
1091                 }
1092                 error($msg, sub { unlink $infile, $outfile});
1093         };
1094
1095         writefile(basename($infile), File::Spec->tmpdir, $content)
1096                 or return $fail->(sprintf(gettext("failed to write %s"), $infile));
1097
1098         my $masterfile = srcfile($pagesources{masterpage($page)});
1099         my %options = (
1100                 "markdown" => (pagetype($masterfile) eq 'mdwn') ? 1 : 0,
1101         );
1102         my $doc=Locale::Po4a::Chooser::new('text',%options);
1103         $doc->process(
1104                 'po_in_name'    => [ $infile ],
1105                 'file_in_name'  => [ $masterfile ],
1106                 'file_in_charset'  => 'utf-8',
1107                 'file_out_charset' => 'utf-8',
1108         ) or return $fail->(gettext("failed to translate"));
1109         $doc->write($outfile)
1110                 or return $fail->(sprintf(gettext("failed to write %s"), $outfile));
1111
1112         $content = readfile($outfile)
1113                 or return $fail->(sprintf(gettext("failed to read %s"), $outfile));
1114
1115         # Unlinking should happen automatically, thanks to File::Temp,
1116         # but it does not work here, probably because of the way writefile()
1117         # and Locale::Po4a::write() work.
1118         unlink $infile, $outfile;
1119
1120         return $content;
1121 }
1122
1123 # returns a SuccessReason or FailReason object
1124 sub isvalidpo ($) {
1125         my $content = shift;
1126
1127         # NB: we don't use po_to_markup here, since Po4a parser does
1128         # not mind invalid PO content
1129         $content = '' unless defined $content;
1130         $content = decode_utf8(encode_utf8($content));
1131
1132         # There are incompatibilities between some File::Temp versions
1133         # (including 0.18, bundled with Lenny's perl-modules package)
1134         # and others (e.g. 0.20, previously present in the archive as
1135         # a standalone package): under certain circumstances, some
1136         # return a relative filename, whereas others return an absolute one;
1137         # we here use this module in a way that is at least compatible
1138         # with 0.18 and 0.20. Beware, hit'n'run refactorers!
1139         my $infile = new File::Temp(TEMPLATE => "ikiwiki-po-isvalidpo.XXXXXXXXXX",
1140                                     DIR => File::Spec->tmpdir,
1141                                     UNLINK => 1)->filename;
1142
1143         my $fail = sub ($) {
1144                 my $msg = '[po/isvalidpo] ' . shift;
1145                 unlink $infile;
1146                 return IkiWiki::FailReason->new("$msg");
1147         };
1148
1149         writefile(basename($infile), File::Spec->tmpdir, $content)
1150                 or return $fail->(sprintf(gettext("failed to write %s"), $infile));
1151
1152         my $res = (system("msgfmt", "--check", $infile, "-o", "/dev/null") == 0);
1153
1154         # Unlinking should happen automatically, thanks to File::Temp,
1155         # but it does not work here, probably because of the way writefile()
1156         # and Locale::Po4a::write() work.
1157         unlink $infile;
1158
1159         if ($res) {
1160             return IkiWiki::SuccessReason->new("valid gettext data");
1161         }
1162         return IkiWiki::FailReason->new(gettext("invalid gettext data, go back ".
1163                                         "to previous page to continue edit"));
1164 }
1165
1166 # ,----
1167 # | PageSpecs
1168 # `----
1169
1170 package IkiWiki::PageSpec;
1171
1172 sub match_istranslation ($;@) {
1173         my $page=shift;
1174
1175         if (IkiWiki::Plugin::po::istranslation($page)) {
1176                 return IkiWiki::SuccessReason->new("is a translation page");
1177         }
1178         else {
1179                 return IkiWiki::FailReason->new("is not a translation page");
1180         }
1181 }
1182
1183 sub match_istranslatable ($;@) {
1184         my $page=shift;
1185
1186         if (IkiWiki::Plugin::po::istranslatable($page)) {
1187                 return IkiWiki::SuccessReason->new("is set as translatable in po_translatable_pages");
1188         }
1189         else {
1190                 return IkiWiki::FailReason->new("is not set as translatable in po_translatable_pages");
1191         }
1192 }
1193
1194 sub match_lang ($$;@) {
1195         my $page=shift;
1196         my $wanted=shift;
1197
1198         my $regexp=IkiWiki::glob2re($wanted);
1199         my $lang=IkiWiki::Plugin::po::lang($page);
1200         if ($lang !~ /^$regexp$/i) {
1201                 return IkiWiki::FailReason->new("file language is $lang, not $wanted");
1202         }
1203         else {
1204                 return IkiWiki::SuccessReason->new("file language is $wanted");
1205         }
1206 }
1207
1208 sub match_currentlang ($$;@) {
1209         my $page=shift;
1210         shift;
1211         my %params=@_;
1212
1213         return IkiWiki::FailReason->new("no location provided") unless exists $params{location};
1214
1215         my $currentlang=IkiWiki::Plugin::po::lang($params{location});
1216         my $lang=IkiWiki::Plugin::po::lang($page);
1217
1218         if ($lang eq $currentlang) {
1219                 return IkiWiki::SuccessReason->new("file language is the same as current one, i.e. $currentlang");
1220         }
1221         else {
1222                 return IkiWiki::FailReason->new("file language is $lang, whereas current language is $currentlang");
1223         }
1224 }
1225
1226 1