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