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