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