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