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