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