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