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