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