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