po(istranslatablefile): extracted this from istranslatable
[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 $page (map pagename($_), @rendered) {
335                 next unless istranslatable($page);
336                 my $file=srcfile($pagesources{$page});
337                 my $updated_pot_file=0;
338                 # Only refresh Pot file if it does not exist, or if
339                 # $pagesources{$page} was changed: don't if only the HTML was
340                 # refreshed, e.g. because of a dependency.
341                 if ((grep { $_ eq $pagesources{$page} } @origneedsbuild)
342                     || ! -e potfile($file)) {
343                         refreshpot($file);
344                         $updated_pot_file=1;
345                 }
346                 my @pofiles;
347                 map {
348                         push @pofiles, $_ if ($updated_pot_file || ! -e $_);
349                 } (pofiles($file));
350                 if (@pofiles) {
351                         refreshpofiles($file, @pofiles);
352                         map { IkiWiki::rcs_add($_); } @pofiles if ($config{rcs});
353                         $updated_po_files=1;
354                 }
355         }
356
357         if ($updated_po_files) {
358                 # Check staged changes in.
359                 if ($config{rcs}) {
360                         IkiWiki::disable_commit_hook();
361                         IkiWiki::rcs_commit_staged(gettext("updated PO files"),
362                                 "IkiWiki::Plugin::po::change", "127.0.0.1");
363                         IkiWiki::enable_commit_hook();
364                         IkiWiki::rcs_update();
365                 }
366                 # Reinitialize module's private variables.
367                 resetalreadyfiltered();
368                 resettranslationscache();
369                 flushmemoizecache();
370                 # Trigger a wiki refresh.
371                 require IkiWiki::Render;
372                 # without preliminary saveindex/loadindex, refresh()
373                 # complains about a lot of uninitialized variables
374                 IkiWiki::saveindex();
375                 IkiWiki::loadindex();
376                 IkiWiki::refresh();
377                 IkiWiki::saveindex();
378         }
379 } #}}}
380
381 # As we're previewing or saving a page, the content may have
382 # changed, so tell the next filter() invocation it must not be lazy.
383 sub editcontent () { #{{{
384         my %params=@_;
385
386         unsetalreadyfiltered($params{page}, $params{page});
387         return $params{content};
388 } #}}}
389
390
391 # ,----
392 # | Injected functions
393 # `----
394
395 # Implement po_link_to 'current' and 'negotiated' settings.
396 sub mybestlink ($$) { #{{{
397         my $page=shift;
398         my $link=shift;
399
400         my $res=$origsubs{'bestlink'}->(masterpage($page), $link);
401         if (length $res
402             && ($config{po_link_to} eq "current" || $config{po_link_to} eq "negotiated")
403             && istranslatable($res)
404             && istranslation($page)) {
405                 return $res . "." . lang($page);
406         }
407         return $res;
408 } #}}}
409
410 sub mybeautify_urlpath ($) { #{{{
411         my $url=shift;
412
413         my $res=$origsubs{'beautify_urlpath'}->($url);
414         if ($config{po_link_to} eq "negotiated") {
415                 $res =~ s!/\Qindex.$config{po_master_language}{code}.$config{htmlext}\E$!/!;
416                 $res =~ s!/\Qindex.$config{htmlext}\E$!/!;
417                 map {
418                         $res =~ s!/\Qindex.$_.$config{htmlext}\E$!/!;
419                 } (keys %{$config{po_slave_languages}});
420         }
421         return $res;
422 } #}}}
423
424 sub mytargetpage ($$) { #{{{
425         my $page=shift;
426         my $ext=shift;
427
428         if (istranslation($page) || istranslatable($page)) {
429                 my ($masterpage, $lang) = (masterpage($page), lang($page));
430                 if (! $config{usedirs} || $masterpage eq 'index') {
431                         return $masterpage . "." . $lang . "." . $ext;
432                 }
433                 else {
434                         return $masterpage . "/index." . $lang . "." . $ext;
435                 }
436         }
437         return $origsubs{'targetpage'}->($page, $ext);
438 } #}}}
439
440 sub myurlto ($$;$) { #{{{
441         my $to=shift;
442         my $from=shift;
443         my $absolute=shift;
444
445         # workaround hard-coded /index.$config{htmlext} in IkiWiki::urlto()
446         if (! length $to
447             && $config{po_link_to} eq "current"
448             && istranslatable('index')) {
449                 return IkiWiki::beautify_urlpath(IkiWiki::baseurl($from) . "index." . lang($from) . ".$config{htmlext}");
450         }
451         return $origsubs{'urlto'}->($to,$from,$absolute);
452 } #}}}
453
454
455 # ,----
456 # | Blackboxes for private data
457 # `----
458
459 {
460         my %filtered;
461
462         sub alreadyfiltered($$) { #{{{
463                 my $page=shift;
464                 my $destpage=shift;
465
466                 return ( exists $filtered{$page}{$destpage}
467                          && $filtered{$page}{$destpage} eq 1 );
468         } #}}}
469
470         sub setalreadyfiltered($$) { #{{{
471                 my $page=shift;
472                 my $destpage=shift;
473
474                 $filtered{$page}{$destpage}=1;
475         } #}}}
476
477         sub unsetalreadyfiltered($$) { #{{{
478                 my $page=shift;
479                 my $destpage=shift;
480
481                 if (exists $filtered{$page}{$destpage}) {
482                         delete $filtered{$page}{$destpage};
483                 }
484         } #}}}
485
486         sub resetalreadyfiltered() { #{{{
487                 undef %filtered;
488         } #}}}
489 }
490
491
492 # ,----
493 # | Helper functions
494 # `----
495
496 sub maybe_add_leading_slash ($;$) { #{{{
497         my $str=shift;
498         my $add=shift;
499         $add=1 unless defined $add;
500         return '/' . $str if $add;
501         return $str;
502 } #}}}
503
504 sub istranslatablefile ($) { #{{{
505         my $file=shift;
506
507         return 0 unless defined $file;
508         return 0 if (defined pagetype($file) && pagetype($file) eq 'po');
509         return 0 if $file =~ /\.pot$/;
510         return 1 if pagespec_match(pagename($file), $config{po_translatable_pages});
511         return;
512 } #}}}
513
514 sub istranslatable ($) { #{{{
515         my $page=shift;
516
517         $page=~s#^/##;
518         return 1 if istranslatablefile($pagesources{$page});
519         return;
520 } #}}}
521
522 sub _istranslation ($) { #{{{
523         my $page=shift;
524
525         my $hasleadingslash = ($page=~s#^/##);
526         my $file=$pagesources{$page};
527         return 0 unless (defined $file
528                          && defined pagetype($file)
529                          && pagetype($file) eq 'po');
530         return 0 if $file =~ /\.pot$/;
531
532         my ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
533         return 0 unless (defined $masterpage && defined $lang
534                          && length $masterpage && length $lang
535                          && defined $pagesources{$masterpage}
536                          && defined $config{po_slave_languages}{$lang});
537
538         return (maybe_add_leading_slash($masterpage, $hasleadingslash), $lang)
539                 if istranslatable($masterpage);
540 } #}}}
541
542 sub istranslation ($) { #{{{
543         my $page=shift;
544
545         if (1 < (my ($masterpage, $lang) = _istranslation($page))) {
546                 my $hasleadingslash = ($masterpage=~s#^/##);
547                 $translations{$masterpage}{$lang}=$page unless exists $translations{$masterpage}{$lang};
548                 return (maybe_add_leading_slash($masterpage, $hasleadingslash), $lang);
549         }
550         return;
551 } #}}}
552
553 sub masterpage ($) { #{{{
554         my $page=shift;
555
556         if ( 1 < (my ($masterpage, $lang) = _istranslation($page))) {
557                 return $masterpage;
558         }
559         return $page;
560 } #}}}
561
562 sub lang ($) { #{{{
563         my $page=shift;
564
565         if (1 < (my ($masterpage, $lang) = _istranslation($page))) {
566                 return $lang;
567         }
568         return $config{po_master_language}{code};
569 } #}}}
570
571 sub islanguagecode ($) { #{{{
572         my $code=shift;
573
574         return ($code =~ /^[a-z]{2}$/);
575 } #}}}
576
577 sub otherlanguage ($$) { #{{{
578         my $page=shift;
579         my $code=shift;
580
581         return masterpage($page) if $code eq $config{po_master_language}{code};
582         return masterpage($page) . '.' . $code;
583 } #}}}
584
585 sub otherlanguages ($) { #{{{
586         my $page=shift;
587
588         my %ret;
589         return \%ret unless (istranslation($page) || istranslatable($page));
590         my $curlang=lang($page);
591         foreach my $lang
592                 ($config{po_master_language}{code}, keys %{$config{po_slave_languages}}) {
593                 next if $lang eq $curlang;
594                 $ret{$lang}=otherlanguage($page, $lang);
595         }
596         return \%ret;
597 } #}}}
598
599 sub potfile ($) { #{{{
600         my $masterfile=shift;
601
602         (my $name, my $dir, my $suffix) = fileparse($masterfile, qr/\.[^.]*/);
603         $dir='' if $dir eq './';
604         return File::Spec->catpath('', $dir, $name . ".pot");
605 } #}}}
606
607 sub pofile ($$) { #{{{
608         my $masterfile=shift;
609         my $lang=shift;
610
611         (my $name, my $dir, my $suffix) = fileparse($masterfile, qr/\.[^.]*/);
612         $dir='' if $dir eq './';
613         return File::Spec->catpath('', $dir, $name . "." . $lang . ".po");
614 } #}}}
615
616 sub pofiles ($) { #{{{
617         my $masterfile=shift;
618
619         return map pofile($masterfile, $_), (keys %{$config{po_slave_languages}});
620 } #}}}
621
622 sub refreshpot ($) { #{{{
623         my $masterfile=shift;
624
625         my $potfile=potfile($masterfile);
626         my %options = ("markdown" => (pagetype($masterfile) eq 'mdwn') ? 1 : 0);
627         my $doc=Locale::Po4a::Chooser::new('text',%options);
628         $doc->{TT}{utf_mode} = 1;
629         $doc->{TT}{file_in_charset} = 'utf-8';
630         $doc->{TT}{file_out_charset} = 'utf-8';
631         $doc->read($masterfile);
632         # let's cheat a bit to force porefs option to be passed to Locale::Po4a::Po;
633         # this is undocument use of internal Locale::Po4a::TransTractor's data,
634         # compulsory since this module prevents us from using the porefs option.
635         my %po_options = ('porefs' => 'none');
636         $doc->{TT}{po_out}=Locale::Po4a::Po->new(\%po_options);
637         $doc->{TT}{po_out}->set_charset('utf-8');
638         # do the actual work
639         $doc->parse;
640         IkiWiki::prep_writefile(basename($potfile),dirname($potfile));
641         $doc->writepo($potfile);
642 } #}}}
643
644 sub refreshpofiles ($@) { #{{{
645         my $masterfile=shift;
646         my @pofiles=@_;
647
648         my $potfile=potfile($masterfile);
649         error("[po/refreshpofiles] POT file ($potfile) does not exist") unless (-e $potfile);
650
651         foreach my $pofile (@pofiles) {
652                 IkiWiki::prep_writefile(basename($pofile),dirname($pofile));
653                 if (-e $pofile) {
654                         system("msgmerge", "-U", "--backup=none", $pofile, $potfile) == 0
655                                 or error("[po/refreshpofiles:$pofile] failed to update");
656                 }
657                 else {
658                         File::Copy::syscopy($potfile,$pofile)
659                                 or error("[po/refreshpofiles:$pofile] failed to copy the POT file");
660                 }
661         }
662 } #}}}
663
664 sub buildtranslationscache() { #{{{
665         # use istranslation's side-effect
666         map istranslation($_), (keys %pagesources);
667 } #}}}
668
669 sub resettranslationscache() { #{{{
670         undef %translations;
671 } #}}}
672
673 sub flushmemoizecache() { #{{{
674         Memoize::flush_cache("istranslatable");
675         Memoize::flush_cache("_istranslation");
676         Memoize::flush_cache("percenttranslated");
677 } #}}}
678
679 sub urlto_with_orig_beautiful_urlpath($$) { #{{{
680         my $to=shift;
681         my $from=shift;
682
683         inject(name => "IkiWiki::beautify_urlpath", call => $origsubs{'beautify_urlpath'});
684         my $res=urlto($to, $from);
685         inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath);
686
687         return $res;
688 } #}}}
689
690 sub percenttranslated ($) { #{{{
691         my $page=shift;
692
693         return gettext("N/A") unless istranslation($page);
694         my $file=srcfile($pagesources{$page});
695         my $masterfile = srcfile($pagesources{masterpage($page)});
696         my (@pos,@masters);
697         push @pos,$file;
698         push @masters,$masterfile;
699         my %options = (
700                 "markdown" => (pagetype($masterfile) eq 'mdwn') ? 1 : 0,
701         );
702         my $doc=Locale::Po4a::Chooser::new('text',%options);
703         $doc->process(
704                 'po_in_name'    => \@pos,
705                 'file_in_name'  => \@masters,
706                 'file_in_charset'  => 'utf-8',
707                 'file_out_charset' => 'utf-8',
708         ) or error("[po/percenttranslated:$page]: failed to translate");
709         my ($percent,$hit,$queries) = $doc->stats();
710         return $percent;
711 } #}}}
712
713 sub languagename ($) { #{{{
714         my $code=shift;
715
716         return $config{po_master_language}{name}
717                 if $code eq $config{po_master_language}{code};
718         return $config{po_slave_languages}{$code}
719                 if defined $config{po_slave_languages}{$code};
720         return;
721 } #}}}
722
723 sub otherlanguagesloop ($) { #{{{
724         my $page=shift;
725
726         my @ret;
727         my %otherpages=%{otherlanguages($page)};
728         while (my ($lang, $otherpage) = each %otherpages) {
729                 if (istranslation($page) && masterpage($page) eq $otherpage) {
730                         push @ret, {
731                                 url => urlto_with_orig_beautiful_urlpath($otherpage, $page),
732                                 code => $lang,
733                                 language => languagename($lang),
734                                 master => 1,
735                         };
736                 }
737                 else {
738                         push @ret, {
739                                 url => urlto_with_orig_beautiful_urlpath($otherpage, $page),
740                                 code => $lang,
741                                 language => languagename($lang),
742                                 percent => percenttranslated($otherpage),
743                         }
744                 }
745         }
746         return sort {
747                         return -1 if $a->{code} eq $config{po_master_language}{code};
748                         return 1 if $b->{code} eq $config{po_master_language}{code};
749                         return $a->{language} cmp $b->{language};
750                 } @ret;
751 } #}}}
752
753 sub homepageurl (;$) { #{{{
754         my $page=shift;
755
756         return urlto('', $page);
757 } #}}}
758
759 # ,----
760 # | PageSpec's
761 # `----
762
763 package IkiWiki::PageSpec;
764 use warnings;
765 use strict;
766 use IkiWiki 2.00;
767
768 sub match_istranslation ($;@) { #{{{
769         my $page=shift;
770
771         if (IkiWiki::Plugin::po::istranslation($page)) {
772                 return IkiWiki::SuccessReason->new("is a translation page");
773         }
774         else {
775                 return IkiWiki::FailReason->new("is not a translation page");
776         }
777 } #}}}
778
779 sub match_istranslatable ($;@) { #{{{
780         my $page=shift;
781
782         if (IkiWiki::Plugin::po::istranslatable($page)) {
783                 return IkiWiki::SuccessReason->new("is set as translatable in po_translatable_pages");
784         }
785         else {
786                 return IkiWiki::FailReason->new("is not set as translatable in po_translatable_pages");
787         }
788 } #}}}
789
790 sub match_lang ($$;@) { #{{{
791         my $page=shift;
792         my $wanted=shift;
793
794         my $regexp=IkiWiki::glob2re($wanted);
795         my $lang=IkiWiki::Plugin::po::lang($page);
796         if ($lang!~/^$regexp$/i) {
797                 return IkiWiki::FailReason->new("file language is $lang, not $wanted");
798         }
799         else {
800                 return IkiWiki::SuccessReason->new("file language is $wanted");
801         }
802 } #}}}
803
804 sub match_currentlang ($$;@) { #{{{
805         my $page=shift;
806         shift;
807         my %params=@_;
808
809         return IkiWiki::FailReason->new("no location provided") unless exists $params{location};
810
811         my $currentlang=IkiWiki::Plugin::po::lang($params{location});
812         my $lang=IkiWiki::Plugin::po::lang($page);
813
814         if ($lang eq $currentlang) {
815                 return IkiWiki::SuccessReason->new("file language is the same as current one, i.e. $currentlang");
816         }
817         else {
818                 return IkiWiki::FailReason->new("file language is $lang, whereas current language is $currentlang");
819         }
820 } #}}}
821
822 1