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