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