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