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