]> sipb.mit.edu Git - ikiwiki.git/blob - IkiWiki/Plugin/po.pm
61331edebf3a2c6a67fa709fb14defbf783d1d34
[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         my $template=template("pocreatepage.tmpl");
451         $template->param(LANG => $config{po_master_language}{name});
452         $form->tmpl_param(message => $template->output);
453 }
454
455
456 # ,----
457 # | Injected functions
458 # `----
459
460 # Implement po_link_to 'current' and 'negotiated' settings.
461 sub mybestlink ($$) {
462         my $page=shift;
463         my $link=shift;
464
465         my $res=$origsubs{'bestlink'}->(masterpage($page), $link);
466         if (length $res
467             && ($config{po_link_to} eq "current" || $config{po_link_to} eq "negotiated")
468             && istranslatable($res)
469             && istranslation($page)) {
470                 return $res . "." . lang($page);
471         }
472         return $res;
473 }
474
475 sub mybeautify_urlpath ($) {
476         my $url=shift;
477
478         my $res=$origsubs{'beautify_urlpath'}->($url);
479         if ($config{po_link_to} eq "negotiated") {
480                 $res =~ s!/\Qindex.$config{po_master_language}{code}.$config{htmlext}\E$!/!;
481                 $res =~ s!/\Qindex.$config{htmlext}\E$!/!;
482                 map {
483                         $res =~ s!/\Qindex.$_.$config{htmlext}\E$!/!;
484                 } (keys %{$config{po_slave_languages}});
485         }
486         return $res;
487 }
488
489 sub mytargetpage ($$) {
490         my $page=shift;
491         my $ext=shift;
492
493         if (istranslation($page) || istranslatable($page)) {
494                 my ($masterpage, $lang) = (masterpage($page), lang($page));
495                 if (! $config{usedirs} || $masterpage eq 'index') {
496                         return $masterpage . "." . $lang . "." . $ext;
497                 }
498                 else {
499                         return $masterpage . "/index." . $lang . "." . $ext;
500                 }
501         }
502         return $origsubs{'targetpage'}->($page, $ext);
503 }
504
505 sub myurlto ($$;$) {
506         my $to=shift;
507         my $from=shift;
508         my $absolute=shift;
509
510         # workaround hard-coded /index.$config{htmlext} in IkiWiki::urlto()
511         if (! length $to
512             && $config{po_link_to} eq "current"
513             && istranslatable('index')) {
514                 return IkiWiki::beautify_urlpath(IkiWiki::baseurl($from) . "index." . lang($from) . ".$config{htmlext}");
515         }
516         # avoid using our injected beautify_urlpath if run by cgi_editpage,
517         # so that one is redirected to the just-edited page rather than to the
518         # negociated translation; to prevent unnecessary fiddling with caller/inject,
519         # we only do so when our beautify_urlpath would actually do what we want to
520         # avoid, i.e. when po_link_to = negotiated
521         if ($config{po_link_to} eq "negotiated") {
522                 my @caller = caller(1);
523                 my $run_by_editpage = 0;
524                 $run_by_editpage = 1 if (exists $caller[3] && defined $caller[3]
525                                          && $caller[3] eq "IkiWiki::cgi_editpage");
526                 inject(name => "IkiWiki::beautify_urlpath", call => $origsubs{'beautify_urlpath'})
527                         if $run_by_editpage;
528                 my $res = $origsubs{'urlto'}->($to,$from,$absolute);
529                 inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath)
530                         if $run_by_editpage;
531                 return $res;
532         }
533         else {
534                 return $origsubs{'urlto'}->($to,$from,$absolute)
535         }
536 }
537
538 sub mynicepagetitle ($;$) {
539         my ($page, $unescaped) = (shift, shift);
540
541         my $res = $origsubs{'nicepagetitle'}->($page, $unescaped);
542         return $res unless istranslation($page);
543         return $res unless $config{po_translation_status_in_links};
544         return $res.' ('.percenttranslated($page).'&nbsp;%)';
545 }
546
547 # ,----
548 # | Blackboxes for private data
549 # `----
550
551 {
552         my %filtered;
553
554         sub alreadyfiltered($$) {
555                 my $page=shift;
556                 my $destpage=shift;
557
558                 return ( exists $filtered{$page}{$destpage}
559                          && $filtered{$page}{$destpage} eq 1 );
560         }
561
562         sub setalreadyfiltered($$) {
563                 my $page=shift;
564                 my $destpage=shift;
565
566                 $filtered{$page}{$destpage}=1;
567         }
568
569         sub unsetalreadyfiltered($$) {
570                 my $page=shift;
571                 my $destpage=shift;
572
573                 if (exists $filtered{$page}{$destpage}) {
574                         delete $filtered{$page}{$destpage};
575                 }
576         }
577
578         sub resetalreadyfiltered() {
579                 undef %filtered;
580         }
581 }
582
583 # ,----
584 # | Helper functions
585 # `----
586
587 sub maybe_add_leading_slash ($;$) {
588         my $str=shift;
589         my $add=shift;
590         $add=1 unless defined $add;
591         return '/' . $str if $add;
592         return $str;
593 }
594
595 sub istranslatablefile ($) {
596         my $file=shift;
597
598         return 0 unless defined $file;
599         return 0 if (defined pagetype($file) && pagetype($file) eq 'po');
600         return 0 if $file =~ /\.pot$/;
601         return 1 if pagespec_match(pagename($file), $config{po_translatable_pages});
602         return;
603 }
604
605 sub istranslatable ($) {
606         my $page=shift;
607
608         $page=~s#^/##;
609         return 1 if istranslatablefile($pagesources{$page});
610         return;
611 }
612
613 sub _istranslation ($) {
614         my $page=shift;
615
616         my $hasleadingslash = ($page=~s#^/##);
617         my $file=$pagesources{$page};
618         return 0 unless (defined $file
619                          && defined pagetype($file)
620                          && pagetype($file) eq 'po');
621         return 0 if $file =~ /\.pot$/;
622
623         my ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
624         return 0 unless (defined $masterpage && defined $lang
625                          && length $masterpage && length $lang
626                          && defined $pagesources{$masterpage}
627                          && defined $config{po_slave_languages}{$lang});
628
629         return (maybe_add_leading_slash($masterpage, $hasleadingslash), $lang)
630                 if istranslatable($masterpage);
631 }
632
633 sub istranslation ($) {
634         my $page=shift;
635
636         if (1 < (my ($masterpage, $lang) = _istranslation($page))) {
637                 my $hasleadingslash = ($masterpage=~s#^/##);
638                 $translations{$masterpage}{$lang}=$page unless exists $translations{$masterpage}{$lang};
639                 return (maybe_add_leading_slash($masterpage, $hasleadingslash), $lang);
640         }
641         return;
642 }
643
644 sub masterpage ($) {
645         my $page=shift;
646
647         if ( 1 < (my ($masterpage, $lang) = _istranslation($page))) {
648                 return $masterpage;
649         }
650         return $page;
651 }
652
653 sub lang ($) {
654         my $page=shift;
655
656         if (1 < (my ($masterpage, $lang) = _istranslation($page))) {
657                 return $lang;
658         }
659         return $config{po_master_language}{code};
660 }
661
662 sub islanguagecode ($) {
663         my $code=shift;
664
665         return ($code =~ /^[a-z]{2}$/);
666 }
667
668 sub otherlanguage ($$) {
669         my $page=shift;
670         my $code=shift;
671
672         return masterpage($page) if $code eq $config{po_master_language}{code};
673         return masterpage($page) . '.' . $code;
674 }
675
676 sub otherlanguages ($) {
677         my $page=shift;
678
679         my %ret;
680         return \%ret unless (istranslation($page) || istranslatable($page));
681         my $curlang=lang($page);
682         foreach my $lang
683                 ($config{po_master_language}{code}, keys %{$config{po_slave_languages}}) {
684                 next if $lang eq $curlang;
685                 $ret{$lang}=otherlanguage($page, $lang);
686         }
687         return \%ret;
688 }
689
690 sub potfile ($) {
691         my $masterfile=shift;
692
693         (my $name, my $dir, my $suffix) = fileparse($masterfile, qr/\.[^.]*/);
694         $dir='' if $dir eq './';
695         return File::Spec->catpath('', $dir, $name . ".pot");
696 }
697
698 sub pofile ($$) {
699         my $masterfile=shift;
700         my $lang=shift;
701
702         (my $name, my $dir, my $suffix) = fileparse($masterfile, qr/\.[^.]*/);
703         $dir='' if $dir eq './';
704         return File::Spec->catpath('', $dir, $name . "." . $lang . ".po");
705 }
706
707 sub pofiles ($) {
708         my $masterfile=shift;
709
710         return map pofile($masterfile, $_), (keys %{$config{po_slave_languages}});
711 }
712
713 sub refreshpot ($) {
714         my $masterfile=shift;
715
716         my $potfile=potfile($masterfile);
717         my %options = ("markdown" => (pagetype($masterfile) eq 'mdwn') ? 1 : 0);
718         my $doc=Locale::Po4a::Chooser::new('text',%options);
719         $doc->{TT}{utf_mode} = 1;
720         $doc->{TT}{file_in_charset} = 'utf-8';
721         $doc->{TT}{file_out_charset} = 'utf-8';
722         $doc->read($masterfile);
723         # let's cheat a bit to force porefs option to be passed to Locale::Po4a::Po;
724         # this is undocument use of internal Locale::Po4a::TransTractor's data,
725         # compulsory since this module prevents us from using the porefs option.
726         $doc->{TT}{po_out}=Locale::Po4a::Po->new({ 'porefs' => 'none' });
727         $doc->{TT}{po_out}->set_charset('utf-8');
728         # do the actual work
729         $doc->parse;
730         IkiWiki::prep_writefile(basename($potfile),dirname($potfile));
731         $doc->writepo($potfile);
732 }
733
734 sub refreshpofiles ($@) {
735         my $masterfile=shift;
736         my @pofiles=@_;
737
738         my $potfile=potfile($masterfile);
739         error("[po/refreshpofiles] POT file ($potfile) does not exist") unless (-e $potfile);
740
741         foreach my $pofile (@pofiles) {
742                 IkiWiki::prep_writefile(basename($pofile),dirname($pofile));
743                 if (-e $pofile) {
744                         system("msgmerge", "-U", "--backup=none", $pofile, $potfile) == 0
745                                 or error("[po/refreshpofiles:$pofile] failed to update");
746                 }
747                 else {
748                         File::Copy::syscopy($potfile,$pofile)
749                                 or error("[po/refreshpofiles:$pofile] failed to copy the POT file");
750                 }
751         }
752 }
753
754 sub buildtranslationscache() {
755         # use istranslation's side-effect
756         map istranslation($_), (keys %pagesources);
757 }
758
759 sub resettranslationscache() {
760         undef %translations;
761 }
762
763 sub flushmemoizecache() {
764         Memoize::flush_cache("istranslatable");
765         Memoize::flush_cache("_istranslation");
766         Memoize::flush_cache("percenttranslated");
767 }
768
769 sub urlto_with_orig_beautiful_urlpath($$) {
770         my $to=shift;
771         my $from=shift;
772
773         inject(name => "IkiWiki::beautify_urlpath", call => $origsubs{'beautify_urlpath'});
774         my $res=urlto($to, $from);
775         inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath);
776
777         return $res;
778 }
779
780 sub percenttranslated ($) {
781         my $page=shift;
782
783         $page=~s/^\///;
784         return gettext("N/A") unless istranslation($page);
785         my $file=srcfile($pagesources{$page});
786         my $masterfile = srcfile($pagesources{masterpage($page)});
787         my %options = (
788                 "markdown" => (pagetype($masterfile) eq 'mdwn') ? 1 : 0,
789         );
790         my $doc=Locale::Po4a::Chooser::new('text',%options);
791         $doc->process(
792                 'po_in_name'    => [ $file ],
793                 'file_in_name'  => [ $masterfile ],
794                 'file_in_charset'  => 'utf-8',
795                 'file_out_charset' => 'utf-8',
796         ) or error("[po/percenttranslated:$page]: failed to translate");
797         my ($percent,$hit,$queries) = $doc->stats();
798         $percent =~ s/\.[0-9]+$//;
799         return $percent;
800 }
801
802 sub languagename ($) {
803         my $code=shift;
804
805         return $config{po_master_language}{name}
806                 if $code eq $config{po_master_language}{code};
807         return $config{po_slave_languages}{$code}
808                 if defined $config{po_slave_languages}{$code};
809         return;
810 }
811
812 sub otherlanguagesloop ($) {
813         my $page=shift;
814
815         my @ret;
816         my %otherpages=%{otherlanguages($page)};
817         while (my ($lang, $otherpage) = each %otherpages) {
818                 if (istranslation($page) && masterpage($page) eq $otherpage) {
819                         push @ret, {
820                                 url => urlto_with_orig_beautiful_urlpath($otherpage, $page),
821                                 code => $lang,
822                                 language => languagename($lang),
823                                 master => 1,
824                         };
825                 }
826                 else {
827                         push @ret, {
828                                 url => urlto_with_orig_beautiful_urlpath($otherpage, $page),
829                                 code => $lang,
830                                 language => languagename($lang),
831                                 percent => percenttranslated($otherpage),
832                         }
833                 }
834         }
835         return sort {
836                         return -1 if $a->{code} eq $config{po_master_language}{code};
837                         return 1 if $b->{code} eq $config{po_master_language}{code};
838                         return $a->{language} cmp $b->{language};
839                 } @ret;
840 }
841
842 sub homepageurl (;$) {
843         my $page=shift;
844
845         return urlto('', $page);
846 }
847
848 sub deletetranslations ($) {
849         my $deletedmasterfile=shift;
850
851         my $deletedmasterpage=pagename($deletedmasterfile);
852         my @todelete;
853         map {
854                 my $file = newpagefile($deletedmasterpage.'.'.$_, 'po');
855                 my $absfile = "$config{srcdir}/$file";
856                 if (-e $absfile && ! -l $absfile && ! -d $absfile) {
857                         push @todelete, $file;
858                 }
859         } keys %{$config{po_slave_languages}};
860
861         map {
862                 if ($config{rcs}) {
863                         IkiWiki::rcs_remove($_);
864                 }
865                 else {
866                         IkiWiki::prune("$config{srcdir}/$_");
867                 }
868         } @todelete;
869
870         if (scalar @todelete) {
871                 commit_and_refresh(
872                         gettext("removed obsolete PO files"),
873                         "IkiWiki::Plugin::po::deletetranslations");
874         }
875 }
876
877 sub commit_and_refresh ($$) {
878         my ($msg, $author) = (shift, shift);
879
880         if ($config{rcs}) {
881                 IkiWiki::disable_commit_hook();
882                 IkiWiki::rcs_commit_staged($msg, $author, "127.0.0.1");
883                 IkiWiki::enable_commit_hook();
884                 IkiWiki::rcs_update();
885         }
886         # Reinitialize module's private variables.
887         resetalreadyfiltered();
888         resettranslationscache();
889         flushmemoizecache();
890         # Trigger a wiki refresh.
891         require IkiWiki::Render;
892         # without preliminary saveindex/loadindex, refresh()
893         # complains about a lot of uninitialized variables
894         IkiWiki::saveindex();
895         IkiWiki::loadindex();
896         IkiWiki::refresh();
897         IkiWiki::saveindex();
898 }
899
900 # on success, returns the filtered content.
901 # on error, if $nonfatal, warn and return undef; else, error out.
902 sub po_to_markup ($$;$) {
903         my ($page, $content) = (shift, shift);
904         my $nonfatal = shift;
905
906         $content = '' unless defined $content;
907         $content = decode_utf8(encode_utf8($content));
908         # CRLF line terminators make poor Locale::Po4a feel bad
909         $content=~s/\r\n/\n/g;
910
911         # There are incompatibilities between some File::Temp versions
912         # (including 0.18, bundled with Lenny's perl-modules package)
913         # and others (e.g. 0.20, previously present in the archive as
914         # a standalone package): under certain circumstances, some
915         # return a relative filename, whereas others return an absolute one;
916         # we here use this module in a way that is at least compatible
917         # with 0.18 and 0.20. Beware, hit'n'run refactorers!
918         my $infile = new File::Temp(TEMPLATE => "ikiwiki-po-filter-in.XXXXXXXXXX",
919                                     DIR => File::Spec->tmpdir,
920                                     UNLINK => 1)->filename;
921         my $outfile = new File::Temp(TEMPLATE => "ikiwiki-po-filter-out.XXXXXXXXXX",
922                                      DIR => File::Spec->tmpdir,
923                                      UNLINK => 1)->filename;
924
925         sub failure ($) {
926                 my $msg = '[po/po_to_markup:'.$page.'] ' . shift;
927                 if ($nonfatal) {
928                         warn $msg;
929                         return undef;
930                 }
931                 error($msg, sub { unlink $infile, $outfile});
932         }
933
934         writefile(basename($infile), File::Spec->tmpdir, $content)
935                 or return failure("failed to write $infile");
936
937         my $masterfile = srcfile($pagesources{masterpage($page)});
938         my %options = (
939                 "markdown" => (pagetype($masterfile) eq 'mdwn') ? 1 : 0,
940         );
941         my $doc=Locale::Po4a::Chooser::new('text',%options);
942         $doc->process(
943                 'po_in_name'    => [ $infile ],
944                 'file_in_name'  => [ $masterfile ],
945                 'file_in_charset'  => 'utf-8',
946                 'file_out_charset' => 'utf-8',
947         ) or return failure("failed to translate");
948         $doc->write($outfile) or return failure("could not write $outfile");
949
950         $content = readfile($outfile) or return failure("could not read $outfile");
951
952         # Unlinking should happen automatically, thanks to File::Temp,
953         # but it does not work here, probably because of the way writefile()
954         # and Locale::Po4a::write() work.
955         unlink $infile, $outfile;
956
957         return $content;
958 }
959
960 # returns a SuccessReason or FailReason object
961 sub isvalidpo ($) {
962         my $content = shift;
963
964         # NB: we don't use po_to_markup here, since Po4a parser does
965         # not mind invalid PO content
966         $content = '' unless defined $content;
967         $content = decode_utf8(encode_utf8($content));
968
969         # There are incompatibilities between some File::Temp versions
970         # (including 0.18, bundled with Lenny's perl-modules package)
971         # and others (e.g. 0.20, previously present in the archive as
972         # a standalone package): under certain circumstances, some
973         # return a relative filename, whereas others return an absolute one;
974         # we here use this module in a way that is at least compatible
975         # with 0.18 and 0.20. Beware, hit'n'run refactorers!
976         my $infile = new File::Temp(TEMPLATE => "ikiwiki-po-isvalidpo.XXXXXXXXXX",
977                                     DIR => File::Spec->tmpdir,
978                                     UNLINK => 1)->filename;
979
980         sub failure ($) {
981                 my $msg = '[po/isvalidpo] ' . shift;
982                 unlink $infile;
983                 return IkiWiki::FailReason->new("$msg");
984         }
985
986         writefile(basename($infile), File::Spec->tmpdir, $content)
987                 or return failure("failed to write $infile");
988
989         my $res = (system("msgfmt", "--check", $infile, "-o", "/dev/null") == 0);
990
991         # Unlinking should happen automatically, thanks to File::Temp,
992         # but it does not work here, probably because of the way writefile()
993         # and Locale::Po4a::write() work.
994         unlink $infile;
995
996         if ($res) {
997             return IkiWiki::SuccessReason->new("valid gettext data");
998         }
999         return IkiWiki::FailReason->new("invalid gettext data");
1000 }
1001
1002 # ,----
1003 # | PageSpec's
1004 # `----
1005
1006 package IkiWiki::PageSpec;
1007 use warnings;
1008 use strict;
1009 use IkiWiki 2.00;
1010
1011 sub match_istranslation ($;@) {
1012         my $page=shift;
1013
1014         if (IkiWiki::Plugin::po::istranslation($page)) {
1015                 return IkiWiki::SuccessReason->new("is a translation page");
1016         }
1017         else {
1018                 return IkiWiki::FailReason->new("is not a translation page");
1019         }
1020 }
1021
1022 sub match_istranslatable ($;@) {
1023         my $page=shift;
1024
1025         if (IkiWiki::Plugin::po::istranslatable($page)) {
1026                 return IkiWiki::SuccessReason->new("is set as translatable in po_translatable_pages");
1027         }
1028         else {
1029                 return IkiWiki::FailReason->new("is not set as translatable in po_translatable_pages");
1030         }
1031 }
1032
1033 sub match_lang ($$;@) {
1034         my $page=shift;
1035         my $wanted=shift;
1036
1037         my $regexp=IkiWiki::glob2re($wanted);
1038         my $lang=IkiWiki::Plugin::po::lang($page);
1039         if ($lang!~/^$regexp$/i) {
1040                 return IkiWiki::FailReason->new("file language is $lang, not $wanted");
1041         }
1042         else {
1043                 return IkiWiki::SuccessReason->new("file language is $wanted");
1044         }
1045 }
1046
1047 sub match_currentlang ($$;@) {
1048         my $page=shift;
1049         shift;
1050         my %params=@_;
1051
1052         return IkiWiki::FailReason->new("no location provided") unless exists $params{location};
1053
1054         my $currentlang=IkiWiki::Plugin::po::lang($params{location});
1055         my $lang=IkiWiki::Plugin::po::lang($page);
1056
1057         if ($lang eq $currentlang) {
1058                 return IkiWiki::SuccessReason->new("file language is the same as current one, i.e. $currentlang");
1059         }
1060         else {
1061                 return IkiWiki::FailReason->new("file language is $lang, whereas current language is $currentlang");
1062         }
1063 }
1064
1065 1