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