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