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