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