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