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