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