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