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