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