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