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