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