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