]> sipb.mit.edu Git - ikiwiki.git/blob - IkiWiki/Plugin/po.pm
Merge remote-tracking branch 'anarcat/dev/syslog_utf8'
[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
27 my ($master_language_code, $master_language_name);
28 my %translations;
29 my @origneedsbuild;
30 my %origsubs;
31 my @slavelanguages; # language codes ordered as in config po_slave_languages
32 my %slavelanguages; # language code to name lookup
33 my $language_code_pattern = '[a-zA-Z]+(?:_[a-zA-Z]+)?';
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 => "rendered", id => "po", call => \&rendered);
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         my $lang_code = istranslation($page) ? lang($page) : $master_language_code;
346         if ($template->query(name => "lang_code")) {
347                 $template->param(lang_code => $lang_code);
348         }
349         if ($template->query(name => "html_lang_code")) {
350                 $template->param(html_lang_code => htmllangcode($lang_code));
351         }
352         if ($template->query(name => "html_lang_dir")) {
353                 $template->param(html_lang_dir => htmllangdir($lang_code));
354         }
355         if ($template->query(name => "lang_name")) {
356                 $template->param(lang_name => languagename($lang_code));
357         }
358         if ($template->query(name => "HOMEPAGEURL")) {
359                 $template->param(homepageurl => homepageurl($page));
360         }
361         if ($template->query(name => "otherlanguages")) {
362                 $template->param(otherlanguages => [otherlanguagesloop($page)]);
363                 map add_depends($page, $_), (values %{otherlanguages_pages($page)});
364         }
365         if ($config{discussion} && istranslation($page)) {
366                 if ($page !~ /.*\/\Q$config{discussionpage}\E$/i &&
367                    (length $config{cgiurl} ||
368                     exists $links{$masterpage."/".lc($config{discussionpage})})) {
369                         $template->param('discussionlink' => htmllink(
370                                 $page,
371                                 $destpage,
372                                 $masterpage . '/' . $config{discussionpage},
373                                 noimageinline => 1,
374                                 forcesubpage => 0,
375                                 linktext => $config{discussionpage},
376                 ));
377                 }
378         }
379         # Remove broken parentlink to ./index.html on home page's translations.
380         # It works because this hook has the "last" parameter set, to ensure it
381         # runs after parentlinks' own pagetemplate hook.
382         if ($template->param('parentlinks')
383             && istranslation($page)
384             && $masterpage eq "index") {
385                 $template->param('parentlinks' => []);
386         }
387         if (ishomepage($page) && $template->query(name => "title")
388             && !$template->param("title_overridden")) {
389                 $template->param(title => $config{wikiname});
390         }
391 }
392
393 # Add the renamed page translations to the list of to-be-renamed pages.
394 sub renamepages (@) {
395         my %params = @_;
396
397         my %torename = %{$params{torename}};
398         my $session = $params{session};
399
400         # Save the page(s) the user asked to rename, so that our
401         # canrename hook can tell the difference between:
402         #  - a translation being renamed as a consequence of its master page
403         #    being renamed
404         #  - a user trying to directly rename a translation
405         # This is why this hook has to be run first, before the list of pages
406         # to rename is modified by other plugins.
407         my @orig_torename;
408         @orig_torename=@{$session->param("po_orig_torename")}
409                 if defined $session->param("po_orig_torename");
410         push @orig_torename, $torename{src};
411         $session->param(po_orig_torename => \@orig_torename);
412         IkiWiki::cgi_savesession($session);
413
414         return () unless istranslatable($torename{src});
415
416         my @ret;
417         my %otherpages=%{otherlanguages_pages($torename{src})};
418         while (my ($lang, $otherpage) = each %otherpages) {
419                 push @ret, {
420                         src => $otherpage,
421                         srcfile => $pagesources{$otherpage},
422                         dest => otherlanguage_page($torename{dest}, $lang),
423                         destfile => $torename{dest}.".".$lang.".po",
424                         required => 0,
425                 };
426         }
427         return @ret;
428 }
429
430 sub mydelete (@) {
431         my @deleted=@_;
432
433         map { deletetranslations($_) } grep istranslatablefile($_), @deleted;
434 }
435
436 sub rendered (@) {
437         my @rendered=@_;
438
439         my $updated_po_files=0;
440
441         # Refresh/create POT and PO files as needed.
442         foreach my $file (grep {istranslatablefile($_)} @rendered) {
443                 my $masterfile=srcfile($file);
444                 my $page=pagename($file);
445                 my $updated_pot_file=0;
446
447                 # Avoid touching underlay files.
448                 next if $masterfile ne "$config{srcdir}/$file";
449
450                 # Only refresh POT file if it does not exist, or if
451                 # the source was changed: don't if only the HTML was
452                 # refreshed, e.g. because of a dependency.
453                 if ((grep { $_ eq $pagesources{$page} } @origneedsbuild) ||
454                     ! -e potfile($masterfile)) {
455                         refreshpot($masterfile);
456                         $updated_pot_file=1;
457                 }
458                 my @pofiles;
459                 foreach my $po (pofiles($masterfile)) {
460                         next if ! $updated_pot_file && -e $po;
461                         next if grep { $po=~/\Q$_\E/ } @{$config{underlaydirs}};
462                         push @pofiles, $po;
463                 }
464                 if (@pofiles) {
465                         refreshpofiles($masterfile, @pofiles);
466                         map { s/^\Q$config{srcdir}\E\/*//; IkiWiki::rcs_add($_) } @pofiles if $config{rcs};
467                         $updated_po_files=1;
468                 }
469         }
470
471         if ($updated_po_files) {
472                 commit_and_refresh(
473                         gettext("updated PO files"));
474         }
475 }
476
477 sub checkcontent (@) {
478         my %params=@_;
479
480         if (istranslation($params{page})) {
481                 my $res = isvalidpo($params{content});
482                 if ($res) {
483                         return undef;
484                 }
485                 else {
486                         return "$res";
487                 }
488         }
489         return undef;
490 }
491
492 sub canremove (@) {
493         my %params = @_;
494
495         if (istranslation($params{page})) {
496                 return gettext("Can not remove a translation. If the master page is removed, ".
497                                "however, its translations will be removed as well.");
498         }
499         return undef;
500 }
501
502 sub canrename (@) {
503         my %params = @_;
504         my $session = $params{session};
505
506         if (istranslation($params{src})) {
507                 my $masterpage = masterpage($params{src});
508                 # Tell the difference between:
509                 #  - a translation being renamed as a consequence of its master page
510                 #    being renamed, which is allowed
511                 #  - a user trying to directly rename a translation, which is forbidden
512                 # by looking for the master page in the list of to-be-renamed pages we
513                 # saved early in the renaming process.
514                 my $orig_torename = $session->param("po_orig_torename");
515                 unless (grep { $_ eq $masterpage } @{$orig_torename}) {
516                         return gettext("Can not rename a translation. If the master page is renamed, ".
517                                        "however, its translations will be renamed as well.");
518                 }
519         }
520         return undef;
521 }
522
523 # As we're previewing or saving a page, the content may have
524 # changed, so tell the next filter() invocation it must not be lazy.
525 sub editcontent () {
526         my %params=@_;
527
528         unsetalreadyfiltered($params{page}, $params{page});
529         return $params{content};
530 }
531
532 sub formbuilder_setup (@) {
533         my %params=@_;
534         my $form=$params{form};
535         my $q=$params{cgi};
536
537         return unless defined $form->field("do");
538
539         if ($form->field("do") eq "create") {
540                 # Warn the user: new pages must be written in master language.
541                 my $template=template("pocreatepage.tmpl");
542                 $template->param(LANG => $master_language_name);
543                 $form->tmpl_param(message => $template->output);
544         }
545         elsif ($form->field("do") eq "edit") {
546                 # Remove the rename/remove buttons on slave pages.
547                 # This has to be done after the rename/remove plugins have added
548                 # their buttons, which is why this hook must be run last.
549                 # The canrename/canremove hooks already ensure this is forbidden
550                 # at the backend level, so this is only UI sugar.
551                 if (istranslation($form->field("page"))) {
552                         map {
553                                 for (my $i = 0; $i < @{$params{buttons}}; $i++) {
554                                         if (@{$params{buttons}}[$i] eq $_) {
555                                                 delete  @{$params{buttons}}[$i];
556                                                 last;
557                                         }
558                                 }
559                         } qw(Rename Remove);
560                 }
561         }
562 }
563
564 sub formbuilder (@) {
565         my %params=@_;
566         my $form=$params{form};
567         my $q=$params{cgi};
568
569         return unless defined $form->field("do");
570
571         # Do not allow to create pages of type po: they are automatically created.
572         # The main reason to do so is to bypass the "favor the type of linking page
573         # on page creation" logic, which is unsuitable when a broken link is clicked
574         # on a slave (PO) page.
575         # This cannot be done in the formbuilder_setup hook as the list of types is
576         # computed later.
577         if ($form->field("do") eq "create") {
578                 foreach my $field ($form->field) {
579                         next unless "$field" eq "type";
580                         next unless $field->type eq 'select';
581                         my $orig_value = $field->value;
582                         # remove po from the list of types
583                         my @types = grep { $_->[0] ne 'po' } $field->options;
584                         $field->options(\@types) if @types;
585                         # favor the type of linking page's masterpage
586                         if ($orig_value eq 'po') {
587                                 my ($from, $type);
588                                 if (defined $form->field('from')) {
589                                         ($from)=$form->field('from')=~/$config{wiki_file_regexp}/;
590                                         $from = masterpage($from);
591                                 }
592                                 if (defined $from && exists $pagesources{$from}) {
593                                         $type=pagetype($pagesources{$from});
594                                 }
595                                 $type=$config{default_pageext} unless defined $type;
596                                 $field->value($type) ;
597                         }
598                 }
599         }
600 }
601
602 # ,----
603 # | Injected functions
604 # `----
605
606 # Implement po_link_to 'current' and 'negotiated' settings.
607 sub mybestlink ($$) {
608         my $page=shift;
609         my $link=shift;
610
611         return $origsubs{'bestlink'}->($page, $link)
612                 if defined $config{po_link_to} && $config{po_link_to} eq "default";
613
614         my $res=$origsubs{'bestlink'}->(masterpage($page), $link);
615         my @caller = caller(1);
616         if (length $res
617             && istranslatedto($res, lang($page))
618             && istranslation($page)
619             &&  !(exists $caller[3] && defined $caller[3]
620                   && ($caller[3] eq "IkiWiki::PageSpec::match_link"))) {
621                 return $res . "." . lang($page);
622         }
623         return $res;
624 }
625
626 sub mybeautify_urlpath ($) {
627         my $url=shift;
628
629         my $res=$origsubs{'beautify_urlpath'}->($url);
630         if (defined $config{po_link_to} && $config{po_link_to} eq "negotiated") {
631                 $res =~ s!/\Qindex.$master_language_code.$config{htmlext}\E$!/!;
632                 $res =~ s!/\Qindex.$config{htmlext}\E$!/!;
633                 map {
634                         $res =~ s!/\Qindex.$_.$config{htmlext}\E$!/!;
635                 } @slavelanguages;
636         }
637         return $res;
638 }
639
640 sub mytargetpage ($$;$) {
641         my $page=shift;
642         my $ext=shift;
643         my $filename=shift;
644
645         if (istranslation($page) || istranslatable($page)) {
646                 my ($masterpage, $lang) = (masterpage($page), lang($page));
647                 if (defined $filename) {
648                         return $masterpage . "/" . $filename . "." . $lang . "." . $ext;
649                 }
650                 elsif (! $config{usedirs} || $masterpage eq 'index') {
651                         return $masterpage . "." . $lang . "." . $ext;
652                 }
653                 else {
654                         return $masterpage . "/index." . $lang . "." . $ext;
655                 }
656         }
657         return $origsubs{'targetpage'}->($page, $ext, $filename);
658 }
659
660 sub myurlto ($;$$) {
661         my $to=shift;
662         my $from=shift;
663         my $absolute=shift;
664
665         # workaround hard-coded /index.$config{htmlext} in IkiWiki::urlto()
666         if (! length $to
667             && $config{po_link_to} eq "current"
668             && istranslatable('index')) {
669                 if (defined $from) {
670                         return IkiWiki::beautify_urlpath(IkiWiki::baseurl($from) . "index." . lang($from) . ".$config{htmlext}");
671                 }
672                 else {
673                         return $origsubs{'urlto'}->($to,$from,$absolute);
674                 }
675         }
676         # avoid using our injected beautify_urlpath if run by cgi_editpage,
677         # so that one is redirected to the just-edited page rather than to the
678         # negociated translation; to prevent unnecessary fiddling with caller/inject,
679         # we only do so when our beautify_urlpath would actually do what we want to
680         # avoid, i.e. when po_link_to = negotiated.
681         # also avoid doing so when run by cgi_goto, so that the links on recentchanges
682         # page actually lead to the exact page they pretend to.
683         if ($config{po_link_to} eq "negotiated") {
684                 my @caller = caller(1);
685                 my $use_orig = 0;
686                 $use_orig = 1 if (exists $caller[3] && defined $caller[3]
687                                  && ($caller[3] eq "IkiWiki::cgi_editpage" ||
688                                      $caller[3] eq "IkiWiki::Plugin::goto::cgi_goto")
689                                  );
690                 inject(name => "IkiWiki::beautify_urlpath", call => $origsubs{'beautify_urlpath'})
691                         if $use_orig;
692                 my $res = $origsubs{'urlto'}->($to,$from,$absolute);
693                 inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath)
694                         if $use_orig;
695                 return $res;
696         }
697         else {
698                 return $origsubs{'urlto'}->($to,$from,$absolute)
699         }
700 }
701
702 sub mycgiurl (@) {
703         my %params=@_;
704
705         # slave pages have no subpages
706         if (istranslation($params{'from'})) {
707                 $params{'from'} = masterpage($params{'from'});
708         }
709         return $origsubs{'cgiurl'}->(%params);
710 }
711
712 sub myrootpage (@) {
713         my %params=@_;
714
715         my $rootpage;
716         if (exists $params{rootpage}) {
717                 $rootpage=$origsubs{'bestlink'}->($params{page}, $params{rootpage});
718                 if (!length $rootpage) {
719                         $rootpage=$params{rootpage};
720                 }
721         }
722         else {
723                 $rootpage=masterpage($params{page});
724         }
725         return $rootpage;
726 }
727
728 sub myisselflink ($$) {
729         my $page=shift;
730         my $link=shift;
731
732         return 1 if $origsubs{'isselflink'}->($page, $link);
733         if (istranslation($page)) {
734                 return $origsubs{'isselflink'}->(masterpage($page), $link);
735         }
736         return;
737 }
738
739 # ,----
740 # | Blackboxes for private data
741 # `----
742
743 {
744         my %filtered;
745
746         sub alreadyfiltered($$) {
747                 my $page=shift;
748                 my $destpage=shift;
749
750                 return exists $filtered{$page}{$destpage}
751                          && $filtered{$page}{$destpage} eq 1;
752         }
753
754         sub setalreadyfiltered($$) {
755                 my $page=shift;
756                 my $destpage=shift;
757
758                 $filtered{$page}{$destpage}=1;
759         }
760
761         sub unsetalreadyfiltered($$) {
762                 my $page=shift;
763                 my $destpage=shift;
764
765                 if (exists $filtered{$page}{$destpage}) {
766                         delete $filtered{$page}{$destpage};
767                 }
768         }
769
770         sub resetalreadyfiltered() {
771                 undef %filtered;
772         }
773 }
774
775 # ,----
776 # | Helper functions
777 # `----
778
779 sub maybe_add_leading_slash ($;$) {
780         my $str=shift;
781         my $add=shift;
782         $add=1 unless defined $add;
783         return '/' . $str if $add;
784         return $str;
785 }
786
787 sub istranslatablefile ($) {
788         my $file=shift;
789
790         return 0 unless defined $file;
791         my $type=pagetype($file);
792         return 0 if ! defined $type || $type eq 'po';
793         return 0 if $file =~ /\.pot$/;
794         return 0 if ! defined $config{po_translatable_pages};
795         return 1 if pagespec_match(pagename($file), $config{po_translatable_pages});
796         return;
797 }
798
799 sub istranslatable ($) {
800         my $page=shift;
801
802         $page=~s#^/##;
803         return 1 if istranslatablefile($pagesources{$page});
804         return;
805 }
806
807 sub istranslatedto ($$) {
808         my $page=shift;
809         my $destlang = shift;
810
811         $page=~s#^/##;
812         return 0 unless istranslatable($page);
813         exists $pagesources{otherlanguage_page($page, $destlang)};
814 }
815
816 sub _istranslation ($) {
817         my $page=shift;
818
819         $page='' unless defined $page && length $page;
820         my $hasleadingslash = ($page=~s#^/##);
821         my $file=$pagesources{$page};
822         return 0 unless defined $file
823                          && defined pagetype($file)
824                          && pagetype($file) eq 'po';
825         return 0 if $file =~ /\.pot$/;
826
827         my ($masterpage, $lang) = ($page =~ /(.*)[.]($language_code_pattern)$/);
828         return 0 unless defined $masterpage && defined $lang
829                          && length $masterpage && length $lang
830                          && defined $pagesources{$masterpage}
831                          && defined $slavelanguages{$lang};
832
833         return (maybe_add_leading_slash($masterpage, $hasleadingslash), $lang)
834                 if istranslatable($masterpage);
835 }
836
837 sub istranslation ($) {
838         my $page=shift;
839
840         if (1 < (my ($masterpage, $lang) = _istranslation($page))) {
841                 my $hasleadingslash = ($masterpage=~s#^/##);
842                 $translations{$masterpage}{$lang}=$page unless exists $translations{$masterpage}{$lang};
843                 return (maybe_add_leading_slash($masterpage, $hasleadingslash), $lang);
844         }
845         return "";
846 }
847
848 sub masterpage ($) {
849         my $page=shift;
850
851         if ( 1 < (my ($masterpage, $lang) = _istranslation($page))) {
852                 return $masterpage;
853         }
854         return $page;
855 }
856
857 sub lang ($) {
858         my $page=shift;
859
860         if (1 < (my ($masterpage, $lang) = _istranslation($page))) {
861                 return $lang;
862         }
863         return $master_language_code;
864 }
865
866 sub htmllangcode ($) {
867         (my $lang = shift) =~ tr/_/-/;
868         return $lang;
869 }
870
871 sub htmllangdir ($) {
872         my $lang = shift;
873         if ($lang =~ /^(ar|fa|he)/) {
874                 return 'rtl';
875         }
876         return 'ltr';
877 }
878
879 sub islanguagecode ($) {
880         my $code=shift;
881
882         return $code =~ /^$language_code_pattern$/;
883 }
884
885 sub otherlanguage_page ($$) {
886         my $page=shift;
887         my $code=shift;
888
889         return masterpage($page) if $code eq $master_language_code;
890         return masterpage($page) . '.' . $code;
891 }
892
893 # Returns the list of other languages codes: the master language comes first,
894 # then the codes are ordered the same way as in po_slave_languages, if it is
895 # an array, or in the language name lexical order, if it is a hash.
896 sub otherlanguages_codes ($) {
897         my $page=shift;
898
899         my @ret;
900         return \@ret unless istranslation($page) || istranslatable($page);
901         my $curlang=lang($page);
902         foreach my $lang
903                 ($master_language_code, @slavelanguages) {
904                 next if $lang eq $curlang;
905                 if ($lang eq $master_language_code ||
906                     istranslatedto(masterpage($page), $lang)) {
907                         push @ret, $lang;
908                 }
909         }
910         return \@ret;
911 }
912
913 sub otherlanguages_pages ($) {
914         my $page=shift;
915
916         my %ret;
917         map {
918                 $ret{$_} = otherlanguage_page($page, $_)
919         } @{otherlanguages_codes($page)};
920
921         return \%ret;
922 }
923
924 sub potfile ($) {
925         my $masterfile=shift;
926
927         (my $name, my $dir, my $suffix) = fileparse($masterfile, qr/\.[^.]*/);
928         $dir='' if $dir eq './';
929         return File::Spec->catpath('', $dir, $name . ".pot");
930 }
931
932 sub pofile ($$) {
933         my $masterfile=shift;
934         my $lang=shift;
935
936         (my $name, my $dir, my $suffix) = fileparse($masterfile, qr/\.[^.]*/);
937         $dir='' if $dir eq './';
938         return File::Spec->catpath('', $dir, $name . "." . $lang . ".po");
939 }
940
941 sub pofiles ($) {
942         my $masterfile=shift;
943
944         return map pofile($masterfile, $_), @slavelanguages;
945 }
946
947 sub refreshpot ($) {
948         my $masterfile=shift;
949
950         my $potfile=potfile($masterfile);
951         my $doc=Locale::Po4a::Chooser::new(po4a_type($masterfile),
952                                            po4a_options($masterfile));
953         $doc->{TT}{utf_mode} = 1;
954         $doc->{TT}{file_in_charset} = 'UTF-8';
955         $doc->{TT}{file_out_charset} = 'UTF-8';
956         $doc->read($masterfile);
957         # let's cheat a bit to force porefs option to be passed to
958         # Locale::Po4a::Po; this is undocument use of internal
959         # Locale::Po4a::TransTractor's data, compulsory since this module
960         # prevents us from using the porefs option.
961         $doc->{TT}{po_out}=Locale::Po4a::Po->new({ 'porefs' => 'none' });
962         $doc->{TT}{po_out}->set_charset('UTF-8');
963         # do the actual work
964         $doc->parse;
965         IkiWiki::prep_writefile(basename($potfile),dirname($potfile));
966         $doc->writepo($potfile);
967 }
968
969 sub refreshpofiles ($@) {
970         my $masterfile=shift;
971         my @pofiles=@_;
972
973         my $potfile=potfile($masterfile);
974         if (! -e $potfile) {
975                 error("po(refreshpofiles) ".sprintf(gettext("POT file (%s) does not exist"), $potfile));
976         }
977
978         foreach my $pofile (@pofiles) {
979                 IkiWiki::prep_writefile(basename($pofile),dirname($pofile));
980
981                 if (! -e $pofile) {
982                         # If the po file exists in an underlay, copy it
983                         # from there.
984                         my ($pobase)=$pofile=~/^\Q$config{srcdir}\E\/?(.*)$/;
985                         foreach my $dir (@{$config{underlaydirs}}) {
986                                 if (-e "$dir/$pobase") {
987                                         File::Copy::syscopy("$dir/$pobase",$pofile)
988                                                 or error("po(refreshpofiles) ".
989                                                          sprintf(gettext("failed to copy underlay PO file to %s"),
990                                                                  $pofile));
991                                 }
992                         }
993                 }
994
995                 if (-e $pofile) {
996                         system("msgmerge", "--previous", "-q", "-U", "--backup=none", $pofile, $potfile) == 0
997                                 or error("po(refreshpofiles) ".
998                                          sprintf(gettext("failed to update %s"),
999                                                  $pofile));
1000                 }
1001                 else {
1002                         File::Copy::syscopy($potfile,$pofile)
1003                                 or error("po(refreshpofiles) ".
1004                                          sprintf(gettext("failed to copy the POT file to %s"),
1005                                                  $pofile));
1006                 }
1007         }
1008 }
1009
1010 sub buildtranslationscache() {
1011         # use istranslation's side-effect
1012         map istranslation($_), (keys %pagesources);
1013 }
1014
1015 sub resettranslationscache() {
1016         undef %translations;
1017 }
1018
1019 sub flushmemoizecache() {
1020         Memoize::flush_cache("istranslatable");
1021         Memoize::flush_cache("_istranslation");
1022         Memoize::flush_cache("percenttranslated");
1023 }
1024
1025 sub urlto_with_orig_beautiful_urlpath($$) {
1026         my $to=shift;
1027         my $from=shift;
1028
1029         inject(name => "IkiWiki::beautify_urlpath", call => $origsubs{'beautify_urlpath'});
1030         my $res=urlto($to, $from);
1031         inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath);
1032
1033         return $res;
1034 }
1035
1036 sub percenttranslated ($) {
1037         my $page=shift;
1038
1039         $page=~s/^\///;
1040         return gettext("N/A") unless istranslation($page);
1041         my $file=srcfile($pagesources{$page});
1042         my $masterfile = srcfile($pagesources{masterpage($page)});
1043         my $doc=Locale::Po4a::Chooser::new(po4a_type($masterfile),
1044                                            po4a_options($masterfile));
1045         $doc->process(
1046                 'po_in_name'    => [ $file ],
1047                 'file_in_name'  => [ $masterfile ],
1048                 'file_in_charset'  => 'UTF-8',
1049                 'file_out_charset' => 'UTF-8',
1050         ) or error("po(percenttranslated) ".
1051                    sprintf(gettext("failed to translate %s"), $page));
1052         my ($percent,$hit,$queries) = $doc->stats();
1053         $percent =~ s/\.[0-9]+$//;
1054         return $percent;
1055 }
1056
1057 sub languagename ($) {
1058         my $code=shift;
1059
1060         return $master_language_name
1061                 if $code eq $master_language_code;
1062         return $slavelanguages{$code}
1063                 if defined $slavelanguages{$code};
1064         return;
1065 }
1066
1067 sub otherlanguagesloop ($) {
1068         my $page=shift;
1069
1070         my @ret;
1071         if (istranslation($page)) {
1072                 push @ret, {
1073                         url => urlto_with_orig_beautiful_urlpath(masterpage($page), $page),
1074                         code => $master_language_code,
1075                         html_code => htmllangcode($master_language_code),
1076                         html_dir => htmllangdir($master_language_code),
1077                         language => $master_language_name,
1078                         master => 1,
1079                 };
1080         }
1081         foreach my $lang (@{otherlanguages_codes($page)}) {
1082                 next if $lang eq $master_language_code;
1083                 my $otherpage = otherlanguage_page($page, $lang);
1084                 push @ret, {
1085                         url => urlto_with_orig_beautiful_urlpath($otherpage, $page),
1086                         code => $lang,
1087                         html_code => htmllangcode($lang),
1088                         html_dir => htmllangdir($lang),
1089                         language => languagename($lang),
1090                         percent => percenttranslated($otherpage),
1091                 }
1092         }
1093         return @ret;
1094 }
1095
1096 sub homepageurl (;$) {
1097         my $page=shift;
1098
1099         return urlto('', $page);
1100 }
1101
1102 sub ishomepage ($) {
1103         my $page = shift;
1104
1105         return 1 if $page eq 'index';
1106         map { return 1 if $page eq 'index.'.$_ } @slavelanguages;
1107         return undef;
1108 }
1109
1110 sub deletetranslations ($) {
1111         my $deletedmasterfile=shift;
1112
1113         my $deletedmasterpage=pagename($deletedmasterfile);
1114         my @todelete;
1115         map {
1116                 my $file = newpagefile($deletedmasterpage.'.'.$_, 'po');
1117                 my $absfile = "$config{srcdir}/$file";
1118                 if (-e $absfile && ! -l $absfile && ! -d $absfile) {
1119                         push @todelete, $file;
1120                 }
1121         } @slavelanguages;
1122
1123         map {
1124                 if ($config{rcs}) {
1125                         IkiWiki::rcs_remove($_);
1126                 }
1127                 else {
1128                         IkiWiki::prune("$config{srcdir}/$_", $config{srcdir});
1129                 }
1130         } @todelete;
1131
1132         if (@todelete) {
1133                 commit_and_refresh(
1134                         gettext("removed obsolete PO files"));
1135         }
1136 }
1137
1138 sub commit_and_refresh ($) {
1139         my $msg = shift;
1140
1141         if ($config{rcs}) {
1142                 IkiWiki::disable_commit_hook();
1143                 IkiWiki::rcs_commit_staged(
1144                         message => $msg,
1145                 );
1146                 IkiWiki::enable_commit_hook();
1147                 IkiWiki::rcs_update();
1148         }
1149         # Reinitialize module's private variables.
1150         resetalreadyfiltered();
1151         resettranslationscache();
1152         flushmemoizecache();
1153         # Trigger a wiki refresh.
1154         require IkiWiki::Render;
1155         # without preliminary saveindex/loadindex, refresh()
1156         # complains about a lot of uninitialized variables
1157         IkiWiki::saveindex();
1158         IkiWiki::loadindex();
1159         IkiWiki::refresh();
1160         IkiWiki::saveindex();
1161 }
1162
1163 sub po_to_markup ($$) {
1164         my ($page, $content) = (shift, shift);
1165
1166         $content = '' unless defined $content;
1167         $content = decode_utf8(encode_utf8($content));
1168         # CRLF line terminators make poor Locale::Po4a feel bad
1169         $content=~s/\r\n/\n/g;
1170
1171         # There are incompatibilities between some File::Temp versions
1172         # (including 0.18, bundled with Lenny's perl-modules package)
1173         # and others (e.g. 0.20, previously present in the archive as
1174         # a standalone package): under certain circumstances, some
1175         # return a relative filename, whereas others return an absolute one;
1176         # we here use this module in a way that is at least compatible
1177         # with 0.18 and 0.20. Beware, hit'n'run refactorers!
1178         my $infile = new File::Temp(TEMPLATE => "ikiwiki-po-filter-in.XXXXXXXXXX",
1179                                     DIR => File::Spec->tmpdir,
1180                                     UNLINK => 1)->filename;
1181         my $outfile = new File::Temp(TEMPLATE => "ikiwiki-po-filter-out.XXXXXXXXXX",
1182                                      DIR => File::Spec->tmpdir,
1183                                      UNLINK => 1)->filename;
1184
1185         my $fail = sub ($) {
1186                 my $msg = "po(po_to_markup) - $page : " . shift;
1187                 error($msg, sub { unlink $infile, $outfile});
1188         };
1189
1190         writefile(basename($infile), File::Spec->tmpdir, $content)
1191                 or return $fail->(sprintf(gettext("failed to write %s"), $infile));
1192
1193         my $masterfile = srcfile($pagesources{masterpage($page)});
1194         my $doc=Locale::Po4a::Chooser::new(po4a_type($masterfile),
1195                                            po4a_options($masterfile));
1196         $doc->process(
1197                 'po_in_name'    => [ $infile ],
1198                 'file_in_name'  => [ $masterfile ],
1199                 'file_in_charset'  => 'UTF-8',
1200                 'file_out_charset' => 'UTF-8',
1201         ) or return $fail->(gettext("failed to translate"));
1202         $doc->write($outfile)
1203                 or return $fail->(sprintf(gettext("failed to write %s"), $outfile));
1204
1205         $content = readfile($outfile);
1206
1207         # Unlinking should happen automatically, thanks to File::Temp,
1208         # but it does not work here, probably because of the way writefile()
1209         # and Locale::Po4a::write() work.
1210         unlink $infile, $outfile;
1211
1212         return $content;
1213 }
1214
1215 # returns a SuccessReason or FailReason object
1216 sub isvalidpo ($) {
1217         my $content = shift;
1218
1219         # NB: we don't use po_to_markup here, since Po4a parser does
1220         # not mind invalid PO content
1221         $content = '' unless defined $content;
1222         $content = decode_utf8(encode_utf8($content));
1223
1224         # There are incompatibilities between some File::Temp versions
1225         # (including 0.18, bundled with Lenny's perl-modules package)
1226         # and others (e.g. 0.20, previously present in the archive as
1227         # a standalone package): under certain circumstances, some
1228         # return a relative filename, whereas others return an absolute one;
1229         # we here use this module in a way that is at least compatible
1230         # with 0.18 and 0.20. Beware, hit'n'run refactorers!
1231         my $infile = new File::Temp(TEMPLATE => "ikiwiki-po-isvalidpo.XXXXXXXXXX",
1232                                     DIR => File::Spec->tmpdir,
1233                                     UNLINK => 1)->filename;
1234
1235         my $fail = sub ($) {
1236                 my $msg = '[po/isvalidpo] ' . shift;
1237                 unlink $infile;
1238                 return IkiWiki::FailReason->new("$msg");
1239         };
1240
1241         writefile(basename($infile), File::Spec->tmpdir, $content)
1242                 or return $fail->(sprintf(gettext("failed to write %s"), $infile));
1243
1244         my $res = (system("msgfmt", "--check", $infile, "-o", "/dev/null") == 0);
1245
1246         # Unlinking should happen automatically, thanks to File::Temp,
1247         # but it does not work here, probably because of the way writefile()
1248         # and Locale::Po4a::write() work.
1249         unlink $infile;
1250
1251         if ($res) {
1252                 return IkiWiki::SuccessReason->new("valid gettext data");
1253         }
1254         return IkiWiki::FailReason->new(gettext("invalid gettext data, go back ".
1255                                         "to previous page to continue edit"));
1256 }
1257
1258 sub po4a_type ($) {
1259         my $file = shift;
1260
1261         my $pagetype = pagetype($file);
1262         if ($pagetype eq 'html') {
1263                 return 'xhtml';
1264         }
1265         return 'text';
1266 }
1267
1268 sub po4a_options($) {
1269         my $file = shift;
1270
1271         my %options;
1272         my $pagetype = pagetype($file);
1273
1274         if ($pagetype eq 'html') {
1275                 # how to disable options is not consistent across po4a modules
1276                 $options{includessi} = '';
1277                 $options{includeexternal} = 0;
1278                 $options{ontagerror} = 'warn';
1279         }
1280         elsif ($pagetype eq 'mdwn') {
1281                 $options{markdown} = 1;
1282         }
1283         else {
1284                 $options{markdown} = 0;
1285         }
1286
1287         return %options;
1288 }
1289
1290 sub splitlangpair ($) {
1291         my $pair=shift;
1292
1293         my ($code, $name) = ( $pair =~ /^($language_code_pattern)\|(.+)$/ );
1294         if (! defined $code || ! defined $name ||
1295             ! length $code || ! length $name) {
1296                 # not a fatal error to avoid breaking if used with web setup
1297                 warn sprintf(gettext("%s has invalid syntax: must use CODE|NAME"),
1298                         $pair);
1299         }
1300
1301         return $code, $name;
1302 }
1303
1304 sub joinlangpair ($$) {
1305         my $code=shift;
1306         my $name=shift;
1307
1308         return "$code|$name";
1309 }
1310
1311 # ,----
1312 # | PageSpecs
1313 # `----
1314
1315 package IkiWiki::PageSpec;
1316
1317 sub match_istranslation ($;@) {
1318         my $page=shift;
1319
1320         if (IkiWiki::Plugin::po::istranslation($page)) {
1321                 return IkiWiki::SuccessReason->new("is a translation page");
1322         }
1323         else {
1324                 return IkiWiki::FailReason->new("is not a translation page");
1325         }
1326 }
1327
1328 sub match_istranslatable ($;@) {
1329         my $page=shift;
1330
1331         if (IkiWiki::Plugin::po::istranslatable($page)) {
1332                 return IkiWiki::SuccessReason->new("is set as translatable in po_translatable_pages");
1333         }
1334         else {
1335                 return IkiWiki::FailReason->new("is not set as translatable in po_translatable_pages");
1336         }
1337 }
1338
1339 sub match_lang ($$;@) {
1340         my $page=shift;
1341         my $wanted=shift;
1342
1343         my $regexp=IkiWiki::glob2re($wanted);
1344         my $lang=IkiWiki::Plugin::po::lang($page);
1345         if ($lang !~ $regexp) {
1346                 return IkiWiki::FailReason->new("file language is $lang, not $wanted");
1347         }
1348         else {
1349                 return IkiWiki::SuccessReason->new("file language is $wanted");
1350         }
1351 }
1352
1353 sub match_currentlang ($$;@) {
1354         my $page=shift;
1355         shift;
1356         my %params=@_;
1357
1358         return IkiWiki::FailReason->new("no location provided") unless exists $params{location};
1359
1360         my $currentlang=IkiWiki::Plugin::po::lang($params{location});
1361         my $lang=IkiWiki::Plugin::po::lang($page);
1362
1363         if ($lang eq $currentlang) {
1364                 return IkiWiki::SuccessReason->new("file language is the same as current one, i.e. $currentlang");
1365         }
1366         else {
1367                 return IkiWiki::FailReason->new("file language is $lang, whereas current language is $currentlang");
1368         }
1369 }
1370
1371 sub match_needstranslation ($$;@) {
1372         my $page=shift;
1373         my $wanted=shift;
1374
1375         if (defined $wanted && $wanted ne "") {
1376                 if ($wanted !~ /^\d+$/) {
1377                         return IkiWiki::FailReason->new("parameter is not an integer");
1378                 }
1379                 elsif ($wanted > 100) {
1380                         return IkiWiki::FailReason->new("parameter is greater than 100");
1381                 }
1382         }
1383         else {
1384                 $wanted=100;
1385         }
1386
1387         my $percenttranslated=IkiWiki::Plugin::po::percenttranslated($page);
1388         if ($percenttranslated eq 'N/A') {
1389                 return IkiWiki::FailReason->new("file is not a translatable page");
1390         }
1391         elsif ($percenttranslated < $wanted) {
1392                 return IkiWiki::SuccessReason->new("file has $percenttranslated translated");
1393         }
1394         else {
1395                 return IkiWiki::FailReason->new("file is translated enough");
1396         }
1397 }
1398
1399 1