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