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