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