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