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