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