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