]> sipb.mit.edu Git - ikiwiki.git/blob - IkiWiki/Plugin/po.pm
(no commit message)
[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         my $lang_code = istranslation($page) ? lang($page) : $master_language_code;
347         if ($template->query(name => "lang_code")) {
348                 $template->param(lang_code => $lang_code);
349         }
350         if ($template->query(name => "lang_name")) {
351                 $template->param(lang_name => languagename($lang_code));
352         }
353         if ($template->query(name => "HOMEPAGEURL")) {
354                 $template->param(homepageurl => homepageurl($page));
355         }
356         if ($template->query(name => "otherlanguages")) {
357                 $template->param(otherlanguages => [otherlanguagesloop($page)]);
358                 map add_depends($page, $_), (values %{otherlanguages_pages($page)});
359         }
360         if ($config{discussion} && istranslation($page)) {
361                 if ($page !~ /.*\/\Q$config{discussionpage}\E$/i &&
362                    (length $config{cgiurl} ||
363                     exists $links{$masterpage."/".lc($config{discussionpage})})) {
364                         $template->param('discussionlink' => htmllink(
365                                 $page,
366                                 $destpage,
367                                 $masterpage . '/' . $config{discussionpage},
368                                 noimageinline => 1,
369                                 forcesubpage => 0,
370                                 linktext => $config{discussionpage},
371                 ));
372                 }
373         }
374         # Remove broken parentlink to ./index.html on home page's translations.
375         # It works because this hook has the "last" parameter set, to ensure it
376         # runs after parentlinks' own pagetemplate hook.
377         if ($template->param('parentlinks')
378             && istranslation($page)
379             && $masterpage eq "index") {
380                 $template->param('parentlinks' => []);
381         }
382         if (ishomepage($page) && $template->query(name => "title")
383             && !$template->param("title_overridden")) {
384                 $template->param(title => $config{wikiname});
385         }
386 }
387
388 # Add the renamed page translations to the list of to-be-renamed pages.
389 sub renamepages (@) {
390         my %params = @_;
391
392         my %torename = %{$params{torename}};
393         my $session = $params{session};
394
395         # Save the page(s) the user asked to rename, so that our
396         # canrename hook can tell the difference between:
397         #  - a translation being renamed as a consequence of its master page
398         #    being renamed
399         #  - a user trying to directly rename a translation
400         # This is why this hook has to be run first, before the list of pages
401         # to rename is modified by other plugins.
402         my @orig_torename;
403         @orig_torename=@{$session->param("po_orig_torename")}
404                 if defined $session->param("po_orig_torename");
405         push @orig_torename, $torename{src};
406         $session->param(po_orig_torename => \@orig_torename);
407         IkiWiki::cgi_savesession($session);
408
409         return () unless istranslatable($torename{src});
410
411         my @ret;
412         my %otherpages=%{otherlanguages_pages($torename{src})};
413         while (my ($lang, $otherpage) = each %otherpages) {
414                 push @ret, {
415                         src => $otherpage,
416                         srcfile => $pagesources{$otherpage},
417                         dest => otherlanguage_page($torename{dest}, $lang),
418                         destfile => $torename{dest}.".".$lang.".po",
419                         required => 0,
420                 };
421         }
422         return @ret;
423 }
424
425 sub mydelete (@) {
426         my @deleted=@_;
427
428         map { deletetranslations($_) } grep istranslatablefile($_), @deleted;
429 }
430
431 sub change (@) {
432         my @rendered=@_;
433
434         my $updated_po_files=0;
435
436         # Refresh/create POT and PO files as needed.
437         foreach my $file (grep {istranslatablefile($_)} @rendered) {
438                 my $masterfile=srcfile($file);
439                 my $page=pagename($file);
440                 my $updated_pot_file=0;
441
442                 # Avoid touching underlay files.
443                 next if $masterfile ne "$config{srcdir}/$file";
444
445                 # Only refresh POT file if it does not exist, or if
446                 # the source was changed: don't if only the HTML was
447                 # refreshed, e.g. because of a dependency.
448                 if ((grep { $_ eq $pagesources{$page} } @origneedsbuild) ||
449                     ! -e potfile($masterfile)) {
450                         refreshpot($masterfile);
451                         $updated_pot_file=1;
452                 }
453                 my @pofiles;
454                 foreach my $po (pofiles($masterfile)) {
455                         next if ! $updated_pot_file && -e $po;
456                         next if grep { $po=~/\Q$_\E/ } @{$config{underlaydirs}};
457                         push @pofiles, $po;
458                 }
459                 if (@pofiles) {
460                         refreshpofiles($masterfile, @pofiles);
461                         map { s/^\Q$config{srcdir}\E\/*//; IkiWiki::rcs_add($_) } @pofiles if $config{rcs};
462                         $updated_po_files=1;
463                 }
464         }
465
466         if ($updated_po_files) {
467                 commit_and_refresh(
468                         gettext("updated PO files"));
469         }
470 }
471
472 sub checkcontent (@) {
473         my %params=@_;
474
475         if (istranslation($params{page})) {
476                 my $res = isvalidpo($params{content});
477                 if ($res) {
478                         return undef;
479                 }
480                 else {
481                         return "$res";
482                 }
483         }
484         return undef;
485 }
486
487 sub canremove (@) {
488         my %params = @_;
489
490         if (istranslation($params{page})) {
491                 return gettext("Can not remove a translation. If the master page is removed, ".
492                                "however, its translations will be removed as well.");
493         }
494         return undef;
495 }
496
497 sub canrename (@) {
498         my %params = @_;
499         my $session = $params{session};
500
501         if (istranslation($params{src})) {
502                 my $masterpage = masterpage($params{src});
503                 # Tell the difference between:
504                 #  - a translation being renamed as a consequence of its master page
505                 #    being renamed, which is allowed
506                 #  - a user trying to directly rename a translation, which is forbidden
507                 # by looking for the master page in the list of to-be-renamed pages we
508                 # saved early in the renaming process.
509                 my $orig_torename = $session->param("po_orig_torename");
510                 unless (grep { $_ eq $masterpage } @{$orig_torename}) {
511                         return gettext("Can not rename a translation. If the master page is renamed, ".
512                                        "however, its translations will be renamed as well.");
513                 }
514         }
515         return undef;
516 }
517
518 # As we're previewing or saving a page, the content may have
519 # changed, so tell the next filter() invocation it must not be lazy.
520 sub editcontent () {
521         my %params=@_;
522
523         unsetalreadyfiltered($params{page}, $params{page});
524         return $params{content};
525 }
526
527 sub formbuilder_setup (@) {
528         my %params=@_;
529         my $form=$params{form};
530         my $q=$params{cgi};
531
532         return unless defined $form->field("do");
533
534         if ($form->field("do") eq "create") {
535                 # Warn the user: new pages must be written in master language.
536                 my $template=template("pocreatepage.tmpl");
537                 $template->param(LANG => $master_language_name);
538                 $form->tmpl_param(message => $template->output);
539         }
540         elsif ($form->field("do") eq "edit") {
541                 # Remove the rename/remove buttons on slave pages.
542                 # This has to be done after the rename/remove plugins have added
543                 # their buttons, which is why this hook must be run last.
544                 # The canrename/canremove hooks already ensure this is forbidden
545                 # at the backend level, so this is only UI sugar.
546                 if (istranslation($form->field("page"))) {
547                         map {
548                                 for (my $i = 0; $i < @{$params{buttons}}; $i++) {
549                                         if (@{$params{buttons}}[$i] eq $_) {
550                                                 delete  @{$params{buttons}}[$i];
551                                                 last;
552                                         }
553                                 }
554                         } qw(Rename Remove);
555                 }
556         }
557 }
558
559 sub formbuilder (@) {
560         my %params=@_;
561         my $form=$params{form};
562         my $q=$params{cgi};
563
564         return unless defined $form->field("do");
565
566         # Do not allow to create pages of type po: they are automatically created.
567         # The main reason to do so is to bypass the "favor the type of linking page
568         # on page creation" logic, which is unsuitable when a broken link is clicked
569         # on a slave (PO) page.
570         # This cannot be done in the formbuilder_setup hook as the list of types is
571         # computed later.
572         if ($form->field("do") eq "create") {
573                 foreach my $field ($form->field) {
574                         next unless "$field" eq "type";
575                         next unless $field->type eq 'select';
576                         my $orig_value = $field->value;
577                         # remove po from the list of types
578                         my @types = grep { $_->[0] ne 'po' } $field->options;
579                         $field->options(\@types) if @types;
580                         # favor the type of linking page's masterpage
581                         if ($orig_value eq 'po') {
582                                 my ($from, $type);
583                                 if (defined $form->field('from')) {
584                                         ($from)=$form->field('from')=~/$config{wiki_file_regexp}/;
585                                         $from = masterpage($from);
586                                 }
587                                 if (defined $from && exists $pagesources{$from}) {
588                                         $type=pagetype($pagesources{$from});
589                                 }
590                                 $type=$config{default_pageext} unless defined $type;
591                                 $field->value($type) ;
592                         }
593                 }
594         }
595 }
596
597 # ,----
598 # | Injected functions
599 # `----
600
601 # Implement po_link_to 'current' and 'negotiated' settings.
602 sub mybestlink ($$) {
603         my $page=shift;
604         my $link=shift;
605
606         return $origsubs{'bestlink'}->($page, $link)
607                 if defined $config{po_link_to} && $config{po_link_to} eq "default";
608
609         my $res=$origsubs{'bestlink'}->(masterpage($page), $link);
610         my @caller = caller(1);
611         if (length $res
612             && istranslatedto($res, lang($page))
613             && istranslation($page)
614             &&  !(exists $caller[3] && defined $caller[3]
615                   && ($caller[3] eq "IkiWiki::PageSpec::match_link"))) {
616                 return $res . "." . lang($page);
617         }
618         return $res;
619 }
620
621 sub mybeautify_urlpath ($) {
622         my $url=shift;
623
624         my $res=$origsubs{'beautify_urlpath'}->($url);
625         if (defined $config{po_link_to} && $config{po_link_to} eq "negotiated") {
626                 $res =~ s!/\Qindex.$master_language_code.$config{htmlext}\E$!/!;
627                 $res =~ s!/\Qindex.$config{htmlext}\E$!/!;
628                 map {
629                         $res =~ s!/\Qindex.$_.$config{htmlext}\E$!/!;
630                 } @slavelanguages;
631         }
632         return $res;
633 }
634
635 sub mytargetpage ($$;$) {
636         my $page=shift;
637         my $ext=shift;
638         my $filename=shift;
639
640         if (istranslation($page) || istranslatable($page)) {
641                 my ($masterpage, $lang) = (masterpage($page), lang($page));
642                 if (defined $filename) {
643                         return $masterpage . "/" . $filename . "." . $lang . "." . $ext;
644                 }
645                 elsif (! $config{usedirs} || $masterpage eq 'index') {
646                         return $masterpage . "." . $lang . "." . $ext;
647                 }
648                 else {
649                         return $masterpage . "/index." . $lang . "." . $ext;
650                 }
651         }
652         return $origsubs{'targetpage'}->($page, $ext, $filename);
653 }
654
655 sub myurlto ($;$$) {
656         my $to=shift;
657         my $from=shift;
658         my $absolute=shift;
659
660         # workaround hard-coded /index.$config{htmlext} in IkiWiki::urlto()
661         if (! length $to
662             && $config{po_link_to} eq "current"
663             && istranslatable('index')) {
664                 if (defined $from) {
665                         return IkiWiki::beautify_urlpath(IkiWiki::baseurl($from) . "index." . lang($from) . ".$config{htmlext}");
666                 }
667                 else {
668                         return $origsubs{'urlto'}->($to,$from,$absolute);
669                 }
670         }
671         # avoid using our injected beautify_urlpath if run by cgi_editpage,
672         # so that one is redirected to the just-edited page rather than to the
673         # negociated translation; to prevent unnecessary fiddling with caller/inject,
674         # we only do so when our beautify_urlpath would actually do what we want to
675         # avoid, i.e. when po_link_to = negotiated.
676         # also avoid doing so when run by cgi_goto, so that the links on recentchanges
677         # page actually lead to the exact page they pretend to.
678         if ($config{po_link_to} eq "negotiated") {
679                 my @caller = caller(1);
680                 my $use_orig = 0;
681                 $use_orig = 1 if (exists $caller[3] && defined $caller[3]
682                                  && ($caller[3] eq "IkiWiki::cgi_editpage" ||
683                                      $caller[3] eq "IkiWiki::Plugin::goto::cgi_goto")
684                                  );
685                 inject(name => "IkiWiki::beautify_urlpath", call => $origsubs{'beautify_urlpath'})
686                         if $use_orig;
687                 my $res = $origsubs{'urlto'}->($to,$from,$absolute);
688                 inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath)
689                         if $use_orig;
690                 return $res;
691         }
692         else {
693                 return $origsubs{'urlto'}->($to,$from,$absolute)
694         }
695 }
696
697 sub mycgiurl (@) {
698         my %params=@_;
699
700         # slave pages have no subpages
701         if (istranslation($params{'from'})) {
702                 $params{'from'} = masterpage($params{'from'});
703         }
704         return $origsubs{'cgiurl'}->(%params);
705 }
706
707 sub myrootpage (@) {
708         my %params=@_;
709
710         my $rootpage;
711         if (exists $params{rootpage}) {
712                 $rootpage=$origsubs{'bestlink'}->($params{page}, $params{rootpage});
713                 if (!length $rootpage) {
714                         $rootpage=$params{rootpage};
715                 }
716         }
717         else {
718                 $rootpage=masterpage($params{page});
719         }
720         return $rootpage;
721 }
722
723 sub myisselflink ($$) {
724         my $page=shift;
725         my $link=shift;
726
727         return 1 if $origsubs{'isselflink'}->($page, $link);
728         if (istranslation($page)) {
729                 return $origsubs{'isselflink'}->(masterpage($page), $link);
730         }
731         return;
732 }
733
734 # ,----
735 # | Blackboxes for private data
736 # `----
737
738 {
739         my %filtered;
740
741         sub alreadyfiltered($$) {
742                 my $page=shift;
743                 my $destpage=shift;
744
745                 return exists $filtered{$page}{$destpage}
746                          && $filtered{$page}{$destpage} eq 1;
747         }
748
749         sub setalreadyfiltered($$) {
750                 my $page=shift;
751                 my $destpage=shift;
752
753                 $filtered{$page}{$destpage}=1;
754         }
755
756         sub unsetalreadyfiltered($$) {
757                 my $page=shift;
758                 my $destpage=shift;
759
760                 if (exists $filtered{$page}{$destpage}) {
761                         delete $filtered{$page}{$destpage};
762                 }
763         }
764
765         sub resetalreadyfiltered() {
766                 undef %filtered;
767         }
768 }
769
770 # ,----
771 # | Helper functions
772 # `----
773
774 sub maybe_add_leading_slash ($;$) {
775         my $str=shift;
776         my $add=shift;
777         $add=1 unless defined $add;
778         return '/' . $str if $add;
779         return $str;
780 }
781
782 sub istranslatablefile ($) {
783         my $file=shift;
784
785         return 0 unless defined $file;
786         my $type=pagetype($file);
787         return 0 if ! defined $type || $type eq 'po';
788         return 0 if $file =~ /\.pot$/;
789         return 0 if ! defined $config{po_translatable_pages};
790         return 1 if pagespec_match(pagename($file), $config{po_translatable_pages});
791         return;
792 }
793
794 sub istranslatable ($) {
795         my $page=shift;
796
797         $page=~s#^/##;
798         return 1 if istranslatablefile($pagesources{$page});
799         return;
800 }
801
802 sub istranslatedto ($$) {
803         my $page=shift;
804         my $destlang = shift;
805
806         $page=~s#^/##;
807         return 0 unless istranslatable($page);
808         exists $pagesources{otherlanguage_page($page, $destlang)};
809 }
810
811 sub _istranslation ($) {
812         my $page=shift;
813
814         $page='' unless defined $page && length $page;
815         my $hasleadingslash = ($page=~s#^/##);
816         my $file=$pagesources{$page};
817         return 0 unless defined $file
818                          && defined pagetype($file)
819                          && pagetype($file) eq 'po';
820         return 0 if $file =~ /\.pot$/;
821
822         my ($masterpage, $lang) = ($page =~ /(.*)[.]($language_code_pattern)$/);
823         return 0 unless defined $masterpage && defined $lang
824                          && length $masterpage && length $lang
825                          && defined $pagesources{$masterpage}
826                          && defined $slavelanguages{$lang};
827
828         return (maybe_add_leading_slash($masterpage, $hasleadingslash), $lang)
829                 if istranslatable($masterpage);
830 }
831
832 sub istranslation ($) {
833         my $page=shift;
834
835         if (1 < (my ($masterpage, $lang) = _istranslation($page))) {
836                 my $hasleadingslash = ($masterpage=~s#^/##);
837                 $translations{$masterpage}{$lang}=$page unless exists $translations{$masterpage}{$lang};
838                 return (maybe_add_leading_slash($masterpage, $hasleadingslash), $lang);
839         }
840         return "";
841 }
842
843 sub masterpage ($) {
844         my $page=shift;
845
846         if ( 1 < (my ($masterpage, $lang) = _istranslation($page))) {
847                 return $masterpage;
848         }
849         return $page;
850 }
851
852 sub lang ($) {
853         my $page=shift;
854
855         if (1 < (my ($masterpage, $lang) = _istranslation($page))) {
856                 return $lang;
857         }
858         return $master_language_code;
859 }
860
861 sub islanguagecode ($) {
862         my $code=shift;
863
864         return $code =~ /^$language_code_pattern$/;
865 }
866
867 sub otherlanguage_page ($$) {
868         my $page=shift;
869         my $code=shift;
870
871         return masterpage($page) if $code eq $master_language_code;
872         return masterpage($page) . '.' . $code;
873 }
874
875 # Returns the list of other languages codes: the master language comes first,
876 # then the codes are ordered the same way as in po_slave_languages, if it is
877 # an array, or in the language name lexical order, if it is a hash.
878 sub otherlanguages_codes ($) {
879         my $page=shift;
880
881         my @ret;
882         return \@ret unless istranslation($page) || istranslatable($page);
883         my $curlang=lang($page);
884         foreach my $lang
885                 ($master_language_code, @slavelanguages) {
886                 next if $lang eq $curlang;
887                 if ($lang eq $master_language_code ||
888                     istranslatedto(masterpage($page), $lang)) {
889                         push @ret, $lang;
890                 }
891         }
892         return \@ret;
893 }
894
895 sub otherlanguages_pages ($) {
896         my $page=shift;
897
898         my %ret;
899         map {
900                 $ret{$_} = otherlanguage_page($page, $_)
901         } @{otherlanguages_codes($page)};
902
903         return \%ret;
904 }
905
906 sub potfile ($) {
907         my $masterfile=shift;
908
909         (my $name, my $dir, my $suffix) = fileparse($masterfile, qr/\.[^.]*/);
910         $dir='' if $dir eq './';
911         return File::Spec->catpath('', $dir, $name . ".pot");
912 }
913
914 sub pofile ($$) {
915         my $masterfile=shift;
916         my $lang=shift;
917
918         (my $name, my $dir, my $suffix) = fileparse($masterfile, qr/\.[^.]*/);
919         $dir='' if $dir eq './';
920         return File::Spec->catpath('', $dir, $name . "." . $lang . ".po");
921 }
922
923 sub pofiles ($) {
924         my $masterfile=shift;
925
926         return map pofile($masterfile, $_), @slavelanguages;
927 }
928
929 sub refreshpot ($) {
930         my $masterfile=shift;
931
932         my $potfile=potfile($masterfile);
933         my $doc=Locale::Po4a::Chooser::new(po4a_type($masterfile),
934                                            po4a_options($masterfile));
935         $doc->{TT}{utf_mode} = 1;
936         $doc->{TT}{file_in_charset} = 'UTF-8';
937         $doc->{TT}{file_out_charset} = 'UTF-8';
938         $doc->read($masterfile);
939         # let's cheat a bit to force porefs option to be passed to
940         # Locale::Po4a::Po; this is undocument use of internal
941         # Locale::Po4a::TransTractor's data, compulsory since this module
942         # prevents us from using the porefs option.
943         $doc->{TT}{po_out}=Locale::Po4a::Po->new({ 'porefs' => 'none' });
944         $doc->{TT}{po_out}->set_charset('UTF-8');
945         # do the actual work
946         $doc->parse;
947         IkiWiki::prep_writefile(basename($potfile),dirname($potfile));
948         $doc->writepo($potfile);
949 }
950
951 sub refreshpofiles ($@) {
952         my $masterfile=shift;
953         my @pofiles=@_;
954
955         my $potfile=potfile($masterfile);
956         if (! -e $potfile) {
957                 error("po(refreshpofiles) ".sprintf(gettext("POT file (%s) does not exist"), $potfile));
958         }
959
960         foreach my $pofile (@pofiles) {
961                 IkiWiki::prep_writefile(basename($pofile),dirname($pofile));
962
963                 if (! -e $pofile) {
964                         # If the po file exists in an underlay, copy it
965                         # from there.
966                         my ($pobase)=$pofile=~/^\Q$config{srcdir}\E\/?(.*)$/;
967                         foreach my $dir (@{$config{underlaydirs}}) {
968                                 if (-e "$dir/$pobase") {
969                                         File::Copy::syscopy("$dir/$pobase",$pofile)
970                                                 or error("po(refreshpofiles) ".
971                                                          sprintf(gettext("failed to copy underlay PO file to %s"),
972                                                                  $pofile));
973                                 }
974                         }
975                 }
976
977                 if (-e $pofile) {
978                         system("msgmerge", "--previous", "-q", "-U", "--backup=none", $pofile, $potfile) == 0
979                                 or error("po(refreshpofiles) ".
980                                          sprintf(gettext("failed to update %s"),
981                                                  $pofile));
982                 }
983                 else {
984                         File::Copy::syscopy($potfile,$pofile)
985                                 or error("po(refreshpofiles) ".
986                                          sprintf(gettext("failed to copy the POT file to %s"),
987                                                  $pofile));
988                 }
989         }
990 }
991
992 sub buildtranslationscache() {
993         # use istranslation's side-effect
994         map istranslation($_), (keys %pagesources);
995 }
996
997 sub resettranslationscache() {
998         undef %translations;
999 }
1000
1001 sub flushmemoizecache() {
1002         Memoize::flush_cache("istranslatable");
1003         Memoize::flush_cache("_istranslation");
1004         Memoize::flush_cache("percenttranslated");
1005 }
1006
1007 sub urlto_with_orig_beautiful_urlpath($$) {
1008         my $to=shift;
1009         my $from=shift;
1010
1011         inject(name => "IkiWiki::beautify_urlpath", call => $origsubs{'beautify_urlpath'});
1012         my $res=urlto($to, $from);
1013         inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath);
1014
1015         return $res;
1016 }
1017
1018 sub percenttranslated ($) {
1019         my $page=shift;
1020
1021         $page=~s/^\///;
1022         return gettext("N/A") unless istranslation($page);
1023         my $file=srcfile($pagesources{$page});
1024         my $masterfile = srcfile($pagesources{masterpage($page)});
1025         my $doc=Locale::Po4a::Chooser::new(po4a_type($masterfile),
1026                                            po4a_options($masterfile));
1027         $doc->process(
1028                 'po_in_name'    => [ $file ],
1029                 'file_in_name'  => [ $masterfile ],
1030                 'file_in_charset'  => 'UTF-8',
1031                 'file_out_charset' => 'UTF-8',
1032         ) or error("po(percenttranslated) ".
1033                    sprintf(gettext("failed to translate %s"), $page));
1034         my ($percent,$hit,$queries) = $doc->stats();
1035         $percent =~ s/\.[0-9]+$//;
1036         return $percent;
1037 }
1038
1039 sub languagename ($) {
1040         my $code=shift;
1041
1042         return $master_language_name
1043                 if $code eq $master_language_code;
1044         return $slavelanguages{$code}
1045                 if defined $slavelanguages{$code};
1046         return;
1047 }
1048
1049 sub otherlanguagesloop ($) {
1050         my $page=shift;
1051
1052         my @ret;
1053         if (istranslation($page)) {
1054                 push @ret, {
1055                         url => urlto_with_orig_beautiful_urlpath(masterpage($page), $page),
1056                         code => $master_language_code,
1057                         language => $master_language_name,
1058                         master => 1,
1059                 };
1060         }
1061         foreach my $lang (@{otherlanguages_codes($page)}) {
1062                 next if $lang eq $master_language_code;
1063                 my $otherpage = otherlanguage_page($page, $lang);
1064                 push @ret, {
1065                         url => urlto_with_orig_beautiful_urlpath($otherpage, $page),
1066                         code => $lang,
1067                         language => languagename($lang),
1068                         percent => percenttranslated($otherpage),
1069                 }
1070         }
1071         return @ret;
1072 }
1073
1074 sub homepageurl (;$) {
1075         my $page=shift;
1076
1077         return urlto('', $page);
1078 }
1079
1080 sub ishomepage ($) {
1081         my $page = shift;
1082
1083         return 1 if $page eq 'index';
1084         map { return 1 if $page eq 'index.'.$_ } @slavelanguages;
1085         return undef;
1086 }
1087
1088 sub deletetranslations ($) {
1089         my $deletedmasterfile=shift;
1090
1091         my $deletedmasterpage=pagename($deletedmasterfile);
1092         my @todelete;
1093         map {
1094                 my $file = newpagefile($deletedmasterpage.'.'.$_, 'po');
1095                 my $absfile = "$config{srcdir}/$file";
1096                 if (-e $absfile && ! -l $absfile && ! -d $absfile) {
1097                         push @todelete, $file;
1098                 }
1099         } @slavelanguages;
1100
1101         map {
1102                 if ($config{rcs}) {
1103                         IkiWiki::rcs_remove($_);
1104                 }
1105                 else {
1106                         IkiWiki::prune("$config{srcdir}/$_");
1107                 }
1108         } @todelete;
1109
1110         if (@todelete) {
1111                 commit_and_refresh(
1112                         gettext("removed obsolete PO files"));
1113         }
1114 }
1115
1116 sub commit_and_refresh ($) {
1117         my $msg = shift;
1118
1119         if ($config{rcs}) {
1120                 IkiWiki::disable_commit_hook();
1121                 IkiWiki::rcs_commit_staged(
1122                         message => $msg,
1123                 );
1124                 IkiWiki::enable_commit_hook();
1125                 IkiWiki::rcs_update();
1126         }
1127         # Reinitialize module's private variables.
1128         resetalreadyfiltered();
1129         resettranslationscache();
1130         flushmemoizecache();
1131         # Trigger a wiki refresh.
1132         require IkiWiki::Render;
1133         # without preliminary saveindex/loadindex, refresh()
1134         # complains about a lot of uninitialized variables
1135         IkiWiki::saveindex();
1136         IkiWiki::loadindex();
1137         IkiWiki::refresh();
1138         IkiWiki::saveindex();
1139 }
1140
1141 sub po_to_markup ($$) {
1142         my ($page, $content) = (shift, shift);
1143
1144         $content = '' unless defined $content;
1145         $content = decode_utf8(encode_utf8($content));
1146         # CRLF line terminators make poor Locale::Po4a feel bad
1147         $content=~s/\r\n/\n/g;
1148
1149         # There are incompatibilities between some File::Temp versions
1150         # (including 0.18, bundled with Lenny's perl-modules package)
1151         # and others (e.g. 0.20, previously present in the archive as
1152         # a standalone package): under certain circumstances, some
1153         # return a relative filename, whereas others return an absolute one;
1154         # we here use this module in a way that is at least compatible
1155         # with 0.18 and 0.20. Beware, hit'n'run refactorers!
1156         my $infile = new File::Temp(TEMPLATE => "ikiwiki-po-filter-in.XXXXXXXXXX",
1157                                     DIR => File::Spec->tmpdir,
1158                                     UNLINK => 1)->filename;
1159         my $outfile = new File::Temp(TEMPLATE => "ikiwiki-po-filter-out.XXXXXXXXXX",
1160                                      DIR => File::Spec->tmpdir,
1161                                      UNLINK => 1)->filename;
1162
1163         my $fail = sub ($) {
1164                 my $msg = "po(po_to_markup) - $page : " . shift;
1165                 error($msg, sub { unlink $infile, $outfile});
1166         };
1167
1168         writefile(basename($infile), File::Spec->tmpdir, $content)
1169                 or return $fail->(sprintf(gettext("failed to write %s"), $infile));
1170
1171         my $masterfile = srcfile($pagesources{masterpage($page)});
1172         my $doc=Locale::Po4a::Chooser::new(po4a_type($masterfile),
1173                                            po4a_options($masterfile));
1174         $doc->process(
1175                 'po_in_name'    => [ $infile ],
1176                 'file_in_name'  => [ $masterfile ],
1177                 'file_in_charset'  => 'UTF-8',
1178                 'file_out_charset' => 'UTF-8',
1179         ) or return $fail->(gettext("failed to translate"));
1180         $doc->write($outfile)
1181                 or return $fail->(sprintf(gettext("failed to write %s"), $outfile));
1182
1183         $content = readfile($outfile);
1184
1185         # Unlinking should happen automatically, thanks to File::Temp,
1186         # but it does not work here, probably because of the way writefile()
1187         # and Locale::Po4a::write() work.
1188         unlink $infile, $outfile;
1189
1190         return $content;
1191 }
1192
1193 # returns a SuccessReason or FailReason object
1194 sub isvalidpo ($) {
1195         my $content = shift;
1196
1197         # NB: we don't use po_to_markup here, since Po4a parser does
1198         # not mind invalid PO content
1199         $content = '' unless defined $content;
1200         $content = decode_utf8(encode_utf8($content));
1201
1202         # There are incompatibilities between some File::Temp versions
1203         # (including 0.18, bundled with Lenny's perl-modules package)
1204         # and others (e.g. 0.20, previously present in the archive as
1205         # a standalone package): under certain circumstances, some
1206         # return a relative filename, whereas others return an absolute one;
1207         # we here use this module in a way that is at least compatible
1208         # with 0.18 and 0.20. Beware, hit'n'run refactorers!
1209         my $infile = new File::Temp(TEMPLATE => "ikiwiki-po-isvalidpo.XXXXXXXXXX",
1210                                     DIR => File::Spec->tmpdir,
1211                                     UNLINK => 1)->filename;
1212
1213         my $fail = sub ($) {
1214                 my $msg = '[po/isvalidpo] ' . shift;
1215                 unlink $infile;
1216                 return IkiWiki::FailReason->new("$msg");
1217         };
1218
1219         writefile(basename($infile), File::Spec->tmpdir, $content)
1220                 or return $fail->(sprintf(gettext("failed to write %s"), $infile));
1221
1222         my $res = (system("msgfmt", "--check", $infile, "-o", "/dev/null") == 0);
1223
1224         # Unlinking should happen automatically, thanks to File::Temp,
1225         # but it does not work here, probably because of the way writefile()
1226         # and Locale::Po4a::write() work.
1227         unlink $infile;
1228
1229         if ($res) {
1230                 return IkiWiki::SuccessReason->new("valid gettext data");
1231         }
1232         return IkiWiki::FailReason->new(gettext("invalid gettext data, go back ".
1233                                         "to previous page to continue edit"));
1234 }
1235
1236 sub po4a_type ($) {
1237         my $file = shift;
1238
1239         my $pagetype = pagetype($file);
1240         if ($pagetype eq 'html') {
1241                 return 'xhtml';
1242         }
1243         return 'text';
1244 }
1245
1246 sub po4a_options($) {
1247         my $file = shift;
1248
1249         my %options;
1250         my $pagetype = pagetype($file);
1251
1252         if ($pagetype eq 'html') {
1253                 # how to disable options is not consistent across po4a modules
1254                 $options{includessi} = '';
1255                 $options{includeexternal} = 0;
1256                 $options{ontagerror} = 'warn';
1257         }
1258         elsif ($pagetype eq 'mdwn') {
1259                 $options{markdown} = 1;
1260         }
1261         else {
1262                 $options{markdown} = 0;
1263         }
1264
1265         return %options;
1266 }
1267
1268 sub splitlangpair ($) {
1269         my $pair=shift;
1270
1271         my ($code, $name) = ( $pair =~ /^($language_code_pattern)\|(.+)$/ );
1272         if (! defined $code || ! defined $name ||
1273             ! length $code || ! length $name) {
1274                 # not a fatal error to avoid breaking if used with web setup
1275                 warn sprintf(gettext("%s has invalid syntax: must use CODE|NAME"),
1276                         $pair);
1277         }
1278
1279         return $code, $name;
1280 }
1281
1282 sub joinlangpair ($$) {
1283         my $code=shift;
1284         my $name=shift;
1285
1286         return "$code|$name";
1287 }
1288
1289 # ,----
1290 # | PageSpecs
1291 # `----
1292
1293 package IkiWiki::PageSpec;
1294
1295 sub match_istranslation ($;@) {
1296         my $page=shift;
1297
1298         if (IkiWiki::Plugin::po::istranslation($page)) {
1299                 return IkiWiki::SuccessReason->new("is a translation page");
1300         }
1301         else {
1302                 return IkiWiki::FailReason->new("is not a translation page");
1303         }
1304 }
1305
1306 sub match_istranslatable ($;@) {
1307         my $page=shift;
1308
1309         if (IkiWiki::Plugin::po::istranslatable($page)) {
1310                 return IkiWiki::SuccessReason->new("is set as translatable in po_translatable_pages");
1311         }
1312         else {
1313                 return IkiWiki::FailReason->new("is not set as translatable in po_translatable_pages");
1314         }
1315 }
1316
1317 sub match_lang ($$;@) {
1318         my $page=shift;
1319         my $wanted=shift;
1320
1321         my $regexp=IkiWiki::glob2re($wanted);
1322         my $lang=IkiWiki::Plugin::po::lang($page);
1323         if ($lang !~ $regexp) {
1324                 return IkiWiki::FailReason->new("file language is $lang, not $wanted");
1325         }
1326         else {
1327                 return IkiWiki::SuccessReason->new("file language is $wanted");
1328         }
1329 }
1330
1331 sub match_currentlang ($$;@) {
1332         my $page=shift;
1333         shift;
1334         my %params=@_;
1335
1336         return IkiWiki::FailReason->new("no location provided") unless exists $params{location};
1337
1338         my $currentlang=IkiWiki::Plugin::po::lang($params{location});
1339         my $lang=IkiWiki::Plugin::po::lang($page);
1340
1341         if ($lang eq $currentlang) {
1342                 return IkiWiki::SuccessReason->new("file language is the same as current one, i.e. $currentlang");
1343         }
1344         else {
1345                 return IkiWiki::FailReason->new("file language is $lang, whereas current language is $currentlang");
1346         }
1347 }
1348
1349 sub match_needstranslation ($$;@) {
1350         my $page=shift;
1351         my $wanted=shift;
1352
1353         if (defined $wanted && $wanted ne "") {
1354                 if ($wanted !~ /^\d+$/) {
1355                         return IkiWiki::FailReason->new("parameter is not an integer");
1356                 }
1357                 elsif ($wanted > 100) {
1358                         return IkiWiki::FailReason->new("parameter is greater than 100");
1359                 }
1360         }
1361         else {
1362                 $wanted=100;
1363         }
1364
1365         my $percenttranslated=IkiWiki::Plugin::po::percenttranslated($page);
1366         if ($percenttranslated eq 'N/A') {
1367                 return IkiWiki::FailReason->new("file is not a translatable page");
1368         }
1369         elsif ($percenttranslated < $wanted) {
1370                 return IkiWiki::SuccessReason->new("file has $percenttranslated translated");
1371         }
1372         else {
1373                 return IkiWiki::FailReason->new("file is translated enough");
1374         }
1375 }
1376
1377 1