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