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