2 # .po as a wiki page type
3 # Licensed under GPL v2 or greater
4 # Copyright (C) 2008 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;
13 use Locale::Po4a::Chooser;
26 memoize("_istranslation");
27 memoize("percenttranslated");
30 hook(type => "getsetup", id => "po", call => \&getsetup);
31 hook(type => "checkconfig", id => "po", call => \&checkconfig);
32 hook(type => "needsbuild", id => "po", call => \&needsbuild);
33 hook(type => "scan", id => "po", call => \&scan, last =>1);
34 hook(type => "filter", id => "po", call => \&filter);
35 hook(type => "htmlize", id => "po", call => \&htmlize);
36 hook(type => "pagetemplate", id => "po", call => \&pagetemplate, last => 1);
37 hook(type => "change", id => "po", call => \&change);
38 hook(type => "editcontent", id => "po", call => \&editcontent);
40 $origsubs{'bestlink'}=\&IkiWiki::bestlink;
41 inject(name => "IkiWiki::bestlink", call => \&mybestlink);
42 $origsubs{'beautify_urlpath'}=\&IkiWiki::beautify_urlpath;
43 inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath);
44 $origsubs{'targetpage'}=\&IkiWiki::targetpage;
45 inject(name => "IkiWiki::targetpage", call => \&mytargetpage);
46 $origsubs{'urlto'}=\&IkiWiki::urlto;
47 inject(name => "IkiWiki::urlto", call => \&myurlto);
56 # 2. Injected functions
57 # 3. Blackboxes for private data
66 sub getsetup () { #{{{
72 po_master_language => {
78 description => "master language (non-PO files)",
82 po_slave_languages => {
89 description => "slave languages (PO files)",
93 po_translatable_pages => {
95 example => "!*/Discussion",
96 description => "PageSpec controlling which pages are translatable",
97 link => "ikiwiki/PageSpec",
103 example => "current",
104 description => "internal linking behavior (default/current/negotiated)",
110 sub checkconfig () { #{{{
111 foreach my $field (qw{po_master_language po_slave_languages}) {
112 if (! exists $config{$field} || ! defined $config{$field}) {
113 error(sprintf(gettext("Must specify %s"), $field));
116 if (! (keys %{$config{po_slave_languages}})) {
117 error(gettext("At least one slave language must be defined in po_slave_languages"));
121 or error(sprintf(gettext("%s is not a valid language code"), $_));
122 } ($config{po_master_language}{code}, keys %{$config{po_slave_languages}});
123 if (! exists $config{po_translatable_pages} ||
124 ! defined $config{po_translatable_pages}) {
125 $config{po_translatable_pages}="";
127 if (! exists $config{po_link_to} ||
128 ! defined $config{po_link_to}) {
129 $config{po_link_to}='default';
132 $config{po_link_to} eq $_
133 } ('default', 'current', 'negotiated')) {
134 warn(sprintf(gettext('po_link_to=%s is not a valid setting, falling back to po_link_to=default'),
135 $config{po_link_to}));
136 $config{po_link_to}='default';
138 elsif ($config{po_link_to} eq "negotiated" && ! $config{usedirs}) {
139 warn(gettext('po_link_to=negotiated requires usedirs to be enabled, falling back to po_link_to=default'));
140 $config{po_link_to}='default';
142 push @{$config{wiki_file_prune_regexps}}, qr/\.pot$/;
145 sub needsbuild () { #{{{
146 my $needsbuild=shift;
148 # backup @needsbuild content so that change() can know whether
149 # a given master page was rendered because its source file was changed
150 @origneedsbuild=(@$needsbuild);
152 buildtranslationscache();
154 # make existing translations depend on the corresponding master page
155 foreach my $master (keys %translations) {
156 map add_depends($_, $master), values %{otherlanguages($master)};
160 # Massage the recorded state of internal links so that:
161 # - it matches the actually generated links, rather than the links as written
162 # in the pages' source
163 # - backlinks are consistent in all cases
166 my $page=$params{page};
167 my $content=$params{content};
169 return unless UNIVERSAL::can("IkiWiki::Plugin::link", "import");
171 if (istranslation($page)) {
172 foreach my $destpage (@{$links{$page}}) {
173 if (istranslatable($destpage)) {
174 # replace one occurence of $destpage in $links{$page}
175 # (we only want to replace the one that was added by
176 # IkiWiki::Plugin::link::scan, other occurences may be
177 # there for other reasons)
178 for (my $i=0; $i<@{$links{$page}}; $i++) {
179 if (@{$links{$page}}[$i] eq $destpage) {
180 @{$links{$page}}[$i] = $destpage . '.' . lang($page);
187 elsif (! istranslatable($page) && ! istranslation($page)) {
188 foreach my $destpage (@{$links{$page}}) {
189 if (istranslatable($destpage)) {
190 # make sure any destpage's translations has
191 # $page in its backlinks
192 push @{$links{$page}},
193 values %{otherlanguages($destpage)};
199 # We use filter to convert PO to the master page's format,
200 # since the rest of ikiwiki should not work on PO files.
201 sub filter (@) { #{{{
204 my $page = $params{page};
205 my $destpage = $params{destpage};
206 my $content = decode_utf8(encode_utf8($params{content}));
208 return $content if ( ! istranslation($page)
209 || alreadyfiltered($page, $destpage) );
211 # CRLF line terminators make poor Locale::Po4a feel bad
212 $content=~s/\r\n/\n/g;
214 # Implementation notes
216 # 1. Locale::Po4a reads/writes from/to files, and I'm too lazy
217 # to learn how to disguise a variable as a file.
218 # 2. There are incompatibilities between some File::Temp versions
219 # (including 0.18, bundled with Lenny's perl-modules package)
220 # and others (e.g. 0.20, previously present in the archive as
221 # a standalone package): under certain circumstances, some
222 # return a relative filename, whereas others return an absolute one;
223 # we here use this module in a way that is at least compatible
224 # with 0.18 and 0.20. Beware, hit'n'run refactorers!
225 my $infile = new File::Temp(TEMPLATE => "ikiwiki-po-filter-in.XXXXXXXXXX",
226 DIR => File::Spec->tmpdir,
227 UNLINK => 1)->filename;
228 my $outfile = new File::Temp(TEMPLATE => "ikiwiki-po-filter-out.XXXXXXXXXX",
229 DIR => File::Spec->tmpdir,
230 UNLINK => 1)->filename;
232 writefile(basename($infile), File::Spec->tmpdir, $content);
234 my $masterfile = srcfile($pagesources{masterpage($page)});
237 push @masters,$masterfile;
239 "markdown" => (pagetype($masterfile) eq 'mdwn') ? 1 : 0,
241 my $doc=Locale::Po4a::Chooser::new('text',%options);
243 'po_in_name' => \@pos,
244 'file_in_name' => \@masters,
245 'file_in_charset' => 'utf-8',
246 'file_out_charset' => 'utf-8',
247 ) or error("[po/filter:$page]: failed to translate");
248 $doc->write($outfile) or error("[po/filter:$page] could not write $outfile");
249 $content = readfile($outfile) or error("[po/filter:$page] could not read $outfile");
251 # Unlinking should happen automatically, thanks to File::Temp,
252 # but it does not work here, probably because of the way writefile()
253 # and Locale::Po4a::write() work.
254 unlink $infile, $outfile;
256 setalreadyfiltered($page, $destpage);
260 sub htmlize (@) { #{{{
263 my $page = $params{page};
264 my $content = $params{content};
266 # ignore PO files this plugin did not create
267 return $content unless istranslation($page);
269 # force content to be htmlize'd as if it was the same type as the master page
270 return IkiWiki::htmlize($page, $page,
271 pagetype(srcfile($pagesources{masterpage($page)})),
275 sub pagetemplate (@) { #{{{
277 my $page=$params{page};
278 my $destpage=$params{destpage};
279 my $template=$params{template};
281 my ($masterpage, $lang) = istranslation($page);
283 if (istranslation($page) && $template->query(name => "percenttranslated")) {
284 $template->param(percenttranslated => percenttranslated($page));
286 if ($template->query(name => "istranslation")) {
287 $template->param(istranslation => scalar istranslation($page));
289 if ($template->query(name => "istranslatable")) {
290 $template->param(istranslatable => istranslatable($page));
292 if ($template->query(name => "HOMEPAGEURL")) {
293 $template->param(homepageurl => homepageurl($page));
295 if ($template->query(name => "otherlanguages")) {
296 $template->param(otherlanguages => [otherlanguagesloop($page)]);
297 map add_depends($page, $_), (values %{otherlanguages($page)});
299 # Rely on IkiWiki::Render's genpage() to decide wether
300 # a discussion link should appear on $page; this is not
301 # totally accurate, though: some broken links may be generated
302 # when cgiurl is disabled.
303 # This compromise avoids some code duplication, and will probably
304 # prevent future breakage when ikiwiki internals change.
305 # Known limitations are preferred to future random bugs.
306 if ($template->param('discussionlink') && istranslation($page)) {
307 $template->param('discussionlink' => htmllink(
310 $masterpage . '/' . gettext("Discussion"),
313 linktext => gettext("Discussion"),
316 # Remove broken parentlink to ./index.html on home page's translations.
317 # It works because this hook has the "last" parameter set, to ensure it
318 # runs after parentlinks' own pagetemplate hook.
319 if ($template->param('parentlinks')
320 && istranslation($page)
321 && $masterpage eq "index") {
322 $template->param('parentlinks' => []);
329 my $updated_po_files=0;
331 # Refresh/create POT and PO files as needed.
332 foreach my $page (map pagename($_), @rendered) {
333 next unless istranslatable($page);
334 my $file=srcfile($pagesources{$page});
335 my $updated_pot_file=0;
336 # Only refresh Pot file if it does not exist, or if
337 # $pagesources{$page} was changed: don't if only the HTML was
338 # refreshed, e.g. because of a dependency.
339 if ((grep { $_ eq $pagesources{$page} } @origneedsbuild)
340 || ! -e potfile($file)) {
346 push @pofiles, $_ if ($updated_pot_file || ! -e $_);
349 refreshpofiles($file, @pofiles);
350 map { IkiWiki::rcs_add($_); } @pofiles if ($config{rcs});
355 if ($updated_po_files) {
356 # Check staged changes in.
358 IkiWiki::disable_commit_hook();
359 IkiWiki::rcs_commit_staged(gettext("updated PO files"),
360 "IkiWiki::Plugin::po::change", "127.0.0.1");
361 IkiWiki::enable_commit_hook();
362 IkiWiki::rcs_update();
364 # Reinitialize module's private variables.
365 resetalreadyfiltered();
366 resettranslationscache();
367 # Trigger a wiki refresh.
368 require IkiWiki::Render;
369 # without preliminary saveindex/loadindex, refresh()
370 # complains about a lot of uninitialized variables
371 IkiWiki::saveindex();
372 IkiWiki::loadindex();
374 IkiWiki::saveindex();
378 # As we're previewing or saving a page, the content may have
379 # changed, so tell the next filter() invocation it must not be lazy.
380 sub editcontent () { #{{{
383 unsetalreadyfiltered($params{page}, $params{page});
384 return $params{content};
389 # | Injected functions
392 # Implement po_link_to 'current' and 'negotiated' settings.
393 sub mybestlink ($$) { #{{{
397 my $res=$origsubs{'bestlink'}->(masterpage($page), $link);
399 && ($config{po_link_to} eq "current" || $config{po_link_to} eq "negotiated")
400 && istranslatable($res)
401 && istranslation($page)) {
402 return $res . "." . lang($page);
407 sub mybeautify_urlpath ($) { #{{{
410 my $res=$origsubs{'beautify_urlpath'}->($url);
411 if ($config{po_link_to} eq "negotiated") {
412 $res =~ s!/\Qindex.$config{po_master_language}{code}.$config{htmlext}\E$!/!;
413 $res =~ s!/\Qindex.$config{htmlext}\E$!/!;
415 $res =~ s!/\Qindex.$_.$config{htmlext}\E$!/!;
416 } (keys %{$config{po_slave_languages}});
421 sub mytargetpage ($$) { #{{{
425 if (istranslation($page) || istranslatable($page)) {
426 my ($masterpage, $lang) = (masterpage($page), lang($page));
427 if (! $config{usedirs} || $masterpage eq 'index') {
428 return $masterpage . "." . $lang . "." . $ext;
431 return $masterpage . "/index." . $lang . "." . $ext;
434 return $origsubs{'targetpage'}->($page, $ext);
437 sub myurlto ($$;$) { #{{{
442 # workaround hard-coded /index.$config{htmlext} in IkiWiki::urlto()
444 && $config{po_link_to} eq "current"
445 && istranslatable('index')) {
446 return IkiWiki::beautify_urlpath(IkiWiki::baseurl($from) . "index." . lang($from) . ".$config{htmlext}");
448 return $origsubs{'urlto'}->($to,$from,$absolute);
453 # | Blackboxes for private data
459 sub alreadyfiltered($$) { #{{{
463 return ( exists $filtered{$page}{$destpage}
464 && $filtered{$page}{$destpage} eq 1 );
467 sub setalreadyfiltered($$) { #{{{
471 $filtered{$page}{$destpage}=1;
474 sub unsetalreadyfiltered($$) { #{{{
478 if (exists $filtered{$page}{$destpage}) {
479 delete $filtered{$page}{$destpage};
483 sub resetalreadyfiltered() { #{{{
493 sub maybe_add_leading_slash ($;$) { #{{{
496 $add=1 unless defined $add;
497 return '/' . $str if $add;
501 sub istranslatable ($) { #{{{
505 my $file=$pagesources{$page};
507 return 0 unless defined $file;
508 return 0 if (defined pagetype($file) && pagetype($file) eq 'po');
509 return 0 if $file =~ /\.pot$/;
510 return pagespec_match($page, $config{po_translatable_pages});
513 sub _istranslation ($) { #{{{
516 my $hasleadingslash = ($page=~s#^/##);
517 my $file=$pagesources{$page};
518 return 0 unless (defined $file
519 && defined pagetype($file)
520 && pagetype($file) eq 'po');
521 return 0 if $file =~ /\.pot$/;
523 my ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
524 return 0 unless (defined $masterpage && defined $lang
525 && length $masterpage && length $lang
526 && defined $pagesources{$masterpage}
527 && defined $config{po_slave_languages}{$lang});
529 return (maybe_add_leading_slash($masterpage, $hasleadingslash), $lang)
530 if istranslatable($masterpage);
533 sub istranslation ($) { #{{{
536 if (1 < (my ($masterpage, $lang) = _istranslation($page))) {
537 my $hasleadingslash = ($masterpage=~s#^/##);
538 $translations{$masterpage}{$lang}=$page unless exists $translations{$masterpage}{$lang};
539 return (maybe_add_leading_slash($masterpage, $hasleadingslash), $lang)
540 if istranslatable($masterpage);
545 sub masterpage ($) { #{{{
548 if ( 1 < (my ($masterpage, $lang) = _istranslation($page))) {
557 if (1 < (my ($masterpage, $lang) = _istranslation($page))) {
560 return $config{po_master_language}{code};
563 sub islanguagecode ($) { #{{{
566 return ($code =~ /^[a-z]{2}$/);
569 sub otherlanguages($) { #{{{
573 if (istranslatable($page)) {
574 %ret = %{$translations{$page}} if defined $translations{$page};
576 elsif (istranslation($page)) {
577 my $masterpage = masterpage($page);
578 $ret{$config{po_master_language}{code}} = $masterpage;
579 foreach my $lang (sort keys %{$translations{$masterpage}}) {
580 next if $lang eq lang($page);
581 $ret{$lang} = $translations{$masterpage}{$lang};
587 sub potfile ($) { #{{{
588 my $masterfile=shift;
590 (my $name, my $dir, my $suffix) = fileparse($masterfile, qr/\.[^.]*/);
591 $dir='' if $dir eq './';
592 return File::Spec->catpath('', $dir, $name . ".pot");
595 sub pofile ($$) { #{{{
596 my $masterfile=shift;
599 (my $name, my $dir, my $suffix) = fileparse($masterfile, qr/\.[^.]*/);
600 $dir='' if $dir eq './';
601 return File::Spec->catpath('', $dir, $name . "." . $lang . ".po");
604 sub pofiles ($) { #{{{
605 my $masterfile=shift;
607 return map pofile($masterfile, $_), (keys %{$config{po_slave_languages}});
610 sub refreshpot ($) { #{{{
611 my $masterfile=shift;
613 my $potfile=potfile($masterfile);
614 my %options = ("markdown" => (pagetype($masterfile) eq 'mdwn') ? 1 : 0);
615 my $doc=Locale::Po4a::Chooser::new('text',%options);
616 $doc->{TT}{utf_mode} = 1;
617 $doc->{TT}{file_in_charset} = 'utf-8';
618 $doc->{TT}{file_out_charset} = 'utf-8';
619 $doc->read($masterfile);
620 # let's cheat a bit to force porefs option to be passed to Locale::Po4a::Po;
621 # this is undocument use of internal Locale::Po4a::TransTractor's data,
622 # compulsory since this module prevents us from using the porefs option.
623 my %po_options = ('porefs' => 'none');
624 $doc->{TT}{po_out}=Locale::Po4a::Po->new(\%po_options);
625 $doc->{TT}{po_out}->set_charset('utf-8');
628 IkiWiki::prep_writefile(basename($potfile),dirname($potfile));
629 $doc->writepo($potfile);
632 sub refreshpofiles ($@) { #{{{
633 my $masterfile=shift;
636 my $potfile=potfile($masterfile);
637 error("[po/refreshpofiles] POT file ($potfile) does not exist") unless (-e $potfile);
639 foreach my $pofile (@pofiles) {
640 IkiWiki::prep_writefile(basename($pofile),dirname($pofile));
642 system("msgmerge", "-U", "--backup=none", $pofile, $potfile) == 0
643 or error("[po/refreshpofiles:$pofile] failed to update");
646 File::Copy::syscopy($potfile,$pofile)
647 or error("[po/refreshpofiles:$pofile] failed to copy the POT file");
652 sub buildtranslationscache() { #{{{
653 # use istranslation's side-effect
654 map istranslation($_), (keys %pagesources);
657 sub resettranslationscache() { #{{{
661 sub urlto_with_orig_beautiful_urlpath($$) { #{{{
665 inject(name => "IkiWiki::beautify_urlpath", call => $origsubs{'beautify_urlpath'});
666 my $res=urlto($to, $from);
667 inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath);
672 sub percenttranslated ($) { #{{{
675 return gettext("N/A") unless istranslation($page);
676 my $file=srcfile($pagesources{$page});
677 my $masterfile = srcfile($pagesources{masterpage($page)});
680 push @masters,$masterfile;
682 "markdown" => (pagetype($masterfile) eq 'mdwn') ? 1 : 0,
684 my $doc=Locale::Po4a::Chooser::new('text',%options);
686 'po_in_name' => \@pos,
687 'file_in_name' => \@masters,
688 'file_in_charset' => 'utf-8',
689 'file_out_charset' => 'utf-8',
690 ) or error("[po/percenttranslated:$page]: failed to translate");
691 my ($percent,$hit,$queries) = $doc->stats();
695 sub languagename ($) { #{{{
698 return $config{po_master_language}{name}
699 if $code eq $config{po_master_language}{code};
700 return $config{po_slave_languages}{$code}
701 if defined $config{po_slave_languages}{$code};
705 sub otherlanguagesloop ($) { #{{{
709 my %otherpages=%{otherlanguages($page)};
710 while (my ($lang, $otherpage) = each %otherpages) {
711 if (istranslation($page) && masterpage($page) eq $otherpage) {
713 url => urlto_with_orig_beautiful_urlpath($otherpage, $page),
715 language => languagename($lang),
721 url => urlto_with_orig_beautiful_urlpath($otherpage, $page),
723 language => languagename($lang),
724 percent => percenttranslated($otherpage),
729 return -1 if $a->{code} eq $config{po_master_language}{code};
730 return 1 if $b->{code} eq $config{po_master_language}{code};
731 return $a->{language} cmp $b->{language};
735 sub homepageurl (;$) { #{{{
738 return urlto('', $page);
745 package IkiWiki::PageSpec;
750 sub match_istranslation ($;@) { #{{{
753 if (IkiWiki::Plugin::po::istranslation($page)) {
754 return IkiWiki::SuccessReason->new("is a translation page");
757 return IkiWiki::FailReason->new("is not a translation page");
761 sub match_istranslatable ($;@) { #{{{
764 if (IkiWiki::Plugin::po::istranslatable($page)) {
765 return IkiWiki::SuccessReason->new("is set as translatable in po_translatable_pages");
768 return IkiWiki::FailReason->new("is not set as translatable in po_translatable_pages");
772 sub match_lang ($$;@) { #{{{
776 my $regexp=IkiWiki::glob2re($wanted);
777 my $lang=IkiWiki::Plugin::po::lang($page);
778 if ($lang!~/^$regexp$/i) {
779 return IkiWiki::FailReason->new("file language is $lang, not $wanted");
782 return IkiWiki::SuccessReason->new("file language is $wanted");
786 sub match_currentlang ($$;@) { #{{{
791 return IkiWiki::FailReason->new("no location provided") unless exists $params{location};
793 my $currentlang=IkiWiki::Plugin::po::lang($params{location});
794 my $lang=IkiWiki::Plugin::po::lang($page);
796 if ($lang eq $currentlang) {
797 return IkiWiki::SuccessReason->new("file language is the same as current one, i.e. $currentlang");
800 return IkiWiki::FailReason->new("file language is $lang, whereas current language is $currentlang");