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