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