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