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