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