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