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;
13 eval q{use Locale::Po4a::Common qw(nowrapi18n !/.*/)};
15 print STDERR gettext("warning: Old po4a detected! Recommend upgrade to 0.35.")."\n";
16 eval q{use Locale::Po4a::Common qw(!/.*/)};
19 use Locale::Po4a::Chooser;
32 memoize("istranslatable");
33 memoize("_istranslation");
34 memoize("percenttranslated");
37 hook(type => "getsetup", id => "po", call => \&getsetup);
38 hook(type => "checkconfig", id => "po", call => \&checkconfig);
39 hook(type => "needsbuild", id => "po", call => \&needsbuild);
40 hook(type => "scan", id => "po", call => \&scan, last => 1);
41 hook(type => "filter", id => "po", call => \&filter);
42 hook(type => "htmlize", id => "po", call => \&htmlize);
43 hook(type => "pagetemplate", id => "po", call => \&pagetemplate, last => 1);
44 hook(type => "rename", id => "po", call => \&renamepages, first => 1);
45 hook(type => "delete", id => "po", call => \&mydelete);
46 hook(type => "change", id => "po", call => \&change);
47 hook(type => "checkcontent", id => "po", call => \&checkcontent);
48 hook(type => "canremove", id => "po", call => \&canremove);
49 hook(type => "canrename", id => "po", call => \&canrename);
50 hook(type => "editcontent", id => "po", call => \&editcontent);
51 hook(type => "formbuilder_setup", id => "po", call => \&formbuilder_setup, last => 1);
52 hook(type => "formbuilder", id => "po", call => \&formbuilder);
54 $origsubs{'bestlink'}=\&IkiWiki::bestlink;
55 inject(name => "IkiWiki::bestlink", call => \&mybestlink);
56 $origsubs{'beautify_urlpath'}=\&IkiWiki::beautify_urlpath;
57 inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath);
58 $origsubs{'targetpage'}=\&IkiWiki::targetpage;
59 inject(name => "IkiWiki::targetpage", call => \&mytargetpage);
60 $origsubs{'urlto'}=\&IkiWiki::urlto;
61 inject(name => "IkiWiki::urlto", call => \&myurlto);
62 $origsubs{'cgiurl'}=\&IkiWiki::cgiurl;
63 inject(name => "IkiWiki::cgiurl", call => \&mycgiurl);
72 # 2. Injected functions
73 # 3. Blackboxes for private data
88 po_master_language => {
94 description => "master language (non-PO files)",
98 po_slave_languages => {
105 description => "slave languages (PO files)",
109 po_translatable_pages => {
111 example => "* and !*/Discussion",
112 description => "PageSpec controlling which pages are translatable",
113 link => "ikiwiki/PageSpec",
119 example => "current",
120 description => "internal linking behavior (default/current/negotiated)",
127 foreach my $field (qw{po_master_language}) {
128 if (! exists $config{$field} || ! defined $config{$field}) {
129 error(sprintf(gettext("Must specify %s when using the %s plugin"),
136 or error(sprintf(gettext("%s is not a valid language code"), $_));
137 } ($config{po_master_language}{code}, keys %{$config{po_slave_languages}});
139 if (! exists $config{po_translatable_pages} ||
140 ! defined $config{po_translatable_pages}) {
141 $config{po_translatable_pages}="";
143 if (! exists $config{po_link_to} ||
144 ! defined $config{po_link_to}) {
145 $config{po_link_to}='default';
147 elsif ($config{po_link_to} !~ /^(default|current|negotiated)$/) {
148 warn(sprintf(gettext('%s is not a valid value for po_link_to, falling back to po_link_to=default'),
149 $config{po_link_to}));
150 $config{po_link_to}='default';
152 elsif ($config{po_link_to} eq "negotiated" && ! $config{usedirs}) {
153 warn(gettext('po_link_to=negotiated requires usedirs to be enabled, falling back to po_link_to=default'));
154 $config{po_link_to}='default';
157 push @{$config{wiki_file_prune_regexps}}, qr/\.pot$/;
159 # Translated versions of the underlays are added if available.
160 foreach my $underlay ("basewiki",
161 map { m/^\Q$config{underlaydirbase}\E\/*(.*)/ }
162 reverse @{$config{underlaydirs}}) {
163 next if $underlay=~/^locale\//;
165 # Underlays containing the po files for slave languages.
166 foreach my $ll (keys %{$config{po_slave_languages}}) {
167 add_underlay("po/$ll/$underlay")
168 if -d "$config{underlaydirbase}/po/$ll/$underlay";
171 if ($config{po_master_language}{code} ne 'en') {
172 # Add underlay containing translated source files
173 # for the master language.
174 add_underlay("locale/$config{po_master_language}{code}/$underlay");
180 my $needsbuild=shift;
182 # backup @needsbuild content so that change() can know whether
183 # a given master page was rendered because its source file was changed
184 @origneedsbuild=(@$needsbuild);
187 buildtranslationscache();
189 # make existing translations depend on the corresponding master page
190 foreach my $master (keys %translations) {
191 map add_depends($_, $master), values %{otherlanguages($master)};
195 # Massage the recorded state of internal links so that:
196 # - it matches the actually generated links, rather than the links as written
197 # in the pages' source
198 # - backlinks are consistent in all cases
201 my $page=$params{page};
202 my $content=$params{content};
204 if (istranslation($page)) {
205 foreach my $destpage (@{$links{$page}}) {
206 if (istranslatable($destpage)) {
207 # replace one occurence of $destpage in $links{$page}
208 # (we only want to replace the one that was added by
209 # IkiWiki::Plugin::link::scan, other occurences may be
210 # there for other reasons)
211 for (my $i=0; $i<@{$links{$page}}; $i++) {
212 if (@{$links{$page}}[$i] eq $destpage) {
213 @{$links{$page}}[$i] = $destpage . '.' . lang($page);
220 elsif (! istranslatable($page) && ! istranslation($page)) {
221 foreach my $destpage (@{$links{$page}}) {
222 if (istranslatable($destpage)) {
223 # make sure any destpage's translations has
224 # $page in its backlinks
225 push @{$links{$page}},
226 values %{otherlanguages($destpage)};
232 # We use filter to convert PO to the master page's format,
233 # since the rest of ikiwiki should not work on PO files.
237 my $page = $params{page};
238 my $destpage = $params{destpage};
239 my $content = $params{content};
240 if (istranslation($page) && ! alreadyfiltered($page, $destpage)) {
241 $content = po_to_markup($page, $content);
242 setalreadyfiltered($page, $destpage);
250 my $page = $params{page};
251 my $content = $params{content};
253 # ignore PO files this plugin did not create
254 return $content unless istranslation($page);
256 # force content to be htmlize'd as if it was the same type as the master page
257 return IkiWiki::htmlize($page, $page,
258 pagetype(srcfile($pagesources{masterpage($page)})),
262 sub pagetemplate (@) {
264 my $page=$params{page};
265 my $destpage=$params{destpage};
266 my $template=$params{template};
268 my ($masterpage, $lang) = istranslation($page);
270 if (istranslation($page) && $template->query(name => "percenttranslated")) {
271 $template->param(percenttranslated => percenttranslated($page));
273 if ($template->query(name => "istranslation")) {
274 $template->param(istranslation => scalar istranslation($page));
276 if ($template->query(name => "istranslatable")) {
277 $template->param(istranslatable => istranslatable($page));
279 if ($template->query(name => "HOMEPAGEURL")) {
280 $template->param(homepageurl => homepageurl($page));
282 if ($template->query(name => "otherlanguages")) {
283 $template->param(otherlanguages => [otherlanguagesloop($page)]);
284 map add_depends($page, $_), (values %{otherlanguages($page)});
286 if ($config{discussion} && istranslation($page)) {
287 if ($page !~ /.*\/\Q$config{discussionpage}\E$/i &&
288 (length $config{cgiurl} ||
289 exists $links{$masterpage."/".lc($config{discussionpage})})) {
290 $template->param('discussionlink' => htmllink(
293 $masterpage . '/' . $config{discussionpage},
296 linktext => $config{discussionpage},
300 # Remove broken parentlink to ./index.html on home page's translations.
301 # It works because this hook has the "last" parameter set, to ensure it
302 # runs after parentlinks' own pagetemplate hook.
303 if ($template->param('parentlinks')
304 && istranslation($page)
305 && $masterpage eq "index") {
306 $template->param('parentlinks' => []);
310 # Add the renamed page translations to the list of to-be-renamed pages.
311 sub renamepages (@) {
314 my %torename = %{$params{torename}};
315 my $session = $params{session};
317 # Save the page(s) the user asked to rename, so that our
318 # canrename hook can tell the difference between:
319 # - a translation being renamed as a consequence of its master page
321 # - a user trying to directly rename a translation
322 # This is why this hook has to be run first, before the list of pages
323 # to rename is modified by other plugins.
325 @orig_torename=@{$session->param("po_orig_torename")}
326 if defined $session->param("po_orig_torename");
327 push @orig_torename, $torename{src};
328 $session->param(po_orig_torename => \@orig_torename);
329 IkiWiki::cgi_savesession($session);
331 return () unless istranslatable($torename{src});
334 my %otherpages=%{otherlanguages($torename{src})};
335 while (my ($lang, $otherpage) = each %otherpages) {
338 srcfile => $pagesources{$otherpage},
339 dest => otherlanguage($torename{dest}, $lang),
340 destfile => $torename{dest}.".".$lang.".po",
350 map { deletetranslations($_) } grep istranslatablefile($_), @deleted;
356 # All meta titles are first extracted at scan time, i.e. before we turn
357 # PO files back into translated markdown; escaping of double-quotes in
358 # PO files breaks the meta plugin's parsing enough to save ugly titles
359 # to %pagestate at this time.
361 # Then, at render time, every page passes in turn through the Great
362 # Rendering Chain (filter->preprocess->linkify->htmlize), and the meta
363 # plugin's preprocess hook is this time in a position to correctly
364 # extract the titles from slave pages.
366 # This is, unfortunately, too late: if the page A, linking to the page
367 # B, is rendered before B, it will display the wrongly-extracted meta
368 # title as the link text to B.
370 # On the one hand, such a corner case only happens on rebuild: on
371 # refresh, every rendered page is fixed to contain correct meta titles.
372 # On the other hand, it can take some time to get every page fixed.
373 # We therefore re-render every rendered page after a rebuild to fix them
374 # at once. As this more or less doubles the time needed to rebuild the
375 # wiki, we do so only when really needed.
378 && exists $config{rebuild} && defined $config{rebuild} && $config{rebuild}
379 && UNIVERSAL::can("IkiWiki::Plugin::meta", "getsetup")
380 && exists $config{meta_overrides_page_title}
381 && defined $config{meta_overrides_page_title}
382 && $config{meta_overrides_page_title}) {
383 debug(sprintf(gettext("rebuilding all pages to fix meta titles")));
384 resetalreadyfiltered();
385 require IkiWiki::Render;
386 foreach my $file (@rendered) {
387 debug(sprintf(gettext("building %s"), $file));
388 IkiWiki::render($file);
392 my $updated_po_files=0;
394 # Refresh/create POT and PO files as needed.
395 # (But avoid doing so if they are in an underlay directory.)
396 foreach my $file (grep {istranslatablefile($_)} @rendered) {
397 my $masterfile=srcfile($file);
398 my $page=pagename($file);
399 my $updated_pot_file=0;
400 # Only refresh POT file if it does not exist, or if
401 # $pagesources{$page} was changed: don't if only the HTML was
402 # refreshed, e.g. because of a dependency.
403 if ($masterfile eq "$config{srcdir}/$file" &&
404 ((grep { $_ eq $pagesources{$page} } @origneedsbuild)
405 || ! -e potfile($masterfile))) {
406 refreshpot($masterfile);
410 foreach my $po (pofiles($masterfile)) {
411 next if ! $updated_pot_file && ! -e $po;
412 next if grep { $po=~/\Q$_\E/ } @{$config{underlaydirs}};
416 refreshpofiles($masterfile, @pofiles);
417 map { IkiWiki::rcs_add($_) } @pofiles if $config{rcs};
422 if ($updated_po_files) {
424 gettext("updated PO files"),
425 "IkiWiki::Plugin::po::change");
429 sub checkcontent (@) {
432 if (istranslation($params{page})) {
433 my $res = isvalidpo($params{content});
447 if (istranslation($params{page})) {
448 return gettext("Can not remove a translation. If the master page is removed, ".
449 "however, its translations will be removed as well.");
456 my $session = $params{session};
458 if (istranslation($params{src})) {
459 my $masterpage = masterpage($params{src});
460 # Tell the difference between:
461 # - a translation being renamed as a consequence of its master page
462 # being renamed, which is allowed
463 # - a user trying to directly rename a translation, which is forbidden
464 # by looking for the master page in the list of to-be-renamed pages we
465 # saved early in the renaming process.
466 my $orig_torename = $session->param("po_orig_torename");
467 unless (grep { $_ eq $masterpage } @{$orig_torename}) {
468 return gettext("Can not rename a translation. If the master page is renamed, ".
469 "however, its translations will be renamed as well.");
475 # As we're previewing or saving a page, the content may have
476 # changed, so tell the next filter() invocation it must not be lazy.
480 unsetalreadyfiltered($params{page}, $params{page});
481 return $params{content};
484 sub formbuilder_setup (@) {
486 my $form=$params{form};
489 return unless defined $form->field("do");
491 if ($form->field("do") eq "create") {
492 # Warn the user: new pages must be written in master language.
493 my $template=template("pocreatepage.tmpl");
494 $template->param(LANG => $config{po_master_language}{name});
495 $form->tmpl_param(message => $template->output);
497 elsif ($form->field("do") eq "edit") {
498 # Remove the rename/remove buttons on slave pages.
499 # This has to be done after the rename/remove plugins have added
500 # their buttons, which is why this hook must be run last.
501 # The canrename/canremove hooks already ensure this is forbidden
502 # at the backend level, so this is only UI sugar.
503 if (istranslation($form->field("page"))) {
505 for (my $i = 0; $i < @{$params{buttons}}; $i++) {
506 if (@{$params{buttons}}[$i] eq $_) {
507 delete @{$params{buttons}}[$i];
516 sub formbuilder (@) {
518 my $form=$params{form};
521 return unless defined $form->field("do");
523 # Do not allow to create pages of type po: they are automatically created.
524 # The main reason to do so is to bypass the "favor the type of linking page
525 # on page creation" logic, which is unsuitable when a broken link is clicked
526 # on a slave (PO) page.
527 # This cannot be done in the formbuilder_setup hook as the list of types is
529 if ($form->field("do") eq "create") {
530 foreach my $field ($form->field) {
531 next unless "$field" eq "type";
532 if ($field->type eq 'select') {
533 # remove po from the list of types
534 my @types = grep { $_ ne 'po' } $field->options;
535 $field->options(\@types) if @types;
542 # | Injected functions
545 # Implement po_link_to 'current' and 'negotiated' settings.
546 sub mybestlink ($$) {
550 my $res=$origsubs{'bestlink'}->(masterpage($page), $link);
552 && ($config{po_link_to} eq "current" || $config{po_link_to} eq "negotiated")
553 && istranslatable($res)
554 && istranslation($page)) {
555 return $res . "." . lang($page);
560 sub mybeautify_urlpath ($) {
563 my $res=$origsubs{'beautify_urlpath'}->($url);
564 if ($config{po_link_to} eq "negotiated") {
565 $res =~ s!/\Qindex.$config{po_master_language}{code}.$config{htmlext}\E$!/!;
566 $res =~ s!/\Qindex.$config{htmlext}\E$!/!;
568 $res =~ s!/\Qindex.$_.$config{htmlext}\E$!/!;
569 } (keys %{$config{po_slave_languages}});
574 sub mytargetpage ($$) {
578 if (istranslation($page) || istranslatable($page)) {
579 my ($masterpage, $lang) = (masterpage($page), lang($page));
580 if (! $config{usedirs} || $masterpage eq 'index') {
581 return $masterpage . "." . $lang . "." . $ext;
584 return $masterpage . "/index." . $lang . "." . $ext;
587 return $origsubs{'targetpage'}->($page, $ext);
595 # workaround hard-coded /index.$config{htmlext} in IkiWiki::urlto()
597 && $config{po_link_to} eq "current"
598 && istranslatable('index')) {
599 return IkiWiki::beautify_urlpath(IkiWiki::baseurl($from) . "index." . lang($from) . ".$config{htmlext}");
601 # avoid using our injected beautify_urlpath if run by cgi_editpage,
602 # so that one is redirected to the just-edited page rather than to the
603 # negociated translation; to prevent unnecessary fiddling with caller/inject,
604 # we only do so when our beautify_urlpath would actually do what we want to
605 # avoid, i.e. when po_link_to = negotiated
606 if ($config{po_link_to} eq "negotiated") {
607 my @caller = caller(1);
608 my $run_by_editpage = 0;
609 $run_by_editpage = 1 if (exists $caller[3] && defined $caller[3]
610 && $caller[3] eq "IkiWiki::cgi_editpage");
611 inject(name => "IkiWiki::beautify_urlpath", call => $origsubs{'beautify_urlpath'})
613 my $res = $origsubs{'urlto'}->($to,$from,$absolute);
614 inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath)
619 return $origsubs{'urlto'}->($to,$from,$absolute)
626 # slave pages have no subpages
627 if (istranslation($params{'from'})) {
628 $params{'from'} = masterpage($params{'from'});
630 return $origsubs{'cgiurl'}->(%params);
634 # | Blackboxes for private data
640 sub alreadyfiltered($$) {
644 return exists $filtered{$page}{$destpage}
645 && $filtered{$page}{$destpage} eq 1;
648 sub setalreadyfiltered($$) {
652 $filtered{$page}{$destpage}=1;
655 sub unsetalreadyfiltered($$) {
659 if (exists $filtered{$page}{$destpage}) {
660 delete $filtered{$page}{$destpage};
664 sub resetalreadyfiltered() {
673 sub maybe_add_leading_slash ($;$) {
676 $add=1 unless defined $add;
677 return '/' . $str if $add;
681 sub istranslatablefile ($) {
684 return 0 unless defined $file;
685 my $type=pagetype($file);
686 return 0 if ! defined $type || $type eq 'po';
687 return 0 if $file =~ /\.pot$/;
688 return 1 if pagespec_match(pagename($file), $config{po_translatable_pages});
692 sub istranslatable ($) {
696 return 1 if istranslatablefile($pagesources{$page});
700 sub _istranslation ($) {
703 $page='' unless defined $page && length $page;
704 my $hasleadingslash = ($page=~s#^/##);
705 my $file=$pagesources{$page};
706 return 0 unless defined $file
707 && defined pagetype($file)
708 && pagetype($file) eq 'po';
709 return 0 if $file =~ /\.pot$/;
711 my ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
712 return 0 unless defined $masterpage && defined $lang
713 && length $masterpage && length $lang
714 && defined $pagesources{$masterpage}
715 && defined $config{po_slave_languages}{$lang};
717 return (maybe_add_leading_slash($masterpage, $hasleadingslash), $lang)
718 if istranslatable($masterpage);
721 sub istranslation ($) {
724 if (1 < (my ($masterpage, $lang) = _istranslation($page))) {
725 my $hasleadingslash = ($masterpage=~s#^/##);
726 $translations{$masterpage}{$lang}=$page unless exists $translations{$masterpage}{$lang};
727 return (maybe_add_leading_slash($masterpage, $hasleadingslash), $lang);
735 if ( 1 < (my ($masterpage, $lang) = _istranslation($page))) {
744 if (1 < (my ($masterpage, $lang) = _istranslation($page))) {
747 return $config{po_master_language}{code};
750 sub islanguagecode ($) {
753 return $code =~ /^[a-z]{2}$/;
756 sub otherlanguage ($$) {
760 return masterpage($page) if $code eq $config{po_master_language}{code};
761 return masterpage($page) . '.' . $code;
764 sub otherlanguages ($) {
768 return \%ret unless istranslation($page) || istranslatable($page);
769 my $curlang=lang($page);
771 ($config{po_master_language}{code}, keys %{$config{po_slave_languages}}) {
772 next if $lang eq $curlang;
773 $ret{$lang}=otherlanguage($page, $lang);
779 my $masterfile=shift;
781 (my $name, my $dir, my $suffix) = fileparse($masterfile, qr/\.[^.]*/);
782 $dir='' if $dir eq './';
783 return File::Spec->catpath('', $dir, $name . ".pot");
787 my $masterfile=shift;
790 (my $name, my $dir, my $suffix) = fileparse($masterfile, qr/\.[^.]*/);
791 $dir='' if $dir eq './';
792 return File::Spec->catpath('', $dir, $name . "." . $lang . ".po");
796 my $masterfile=shift;
798 return map pofile($masterfile, $_), (keys %{$config{po_slave_languages}});
802 my $masterfile=shift;
804 my $potfile=potfile($masterfile);
805 my %options = ("markdown" => (pagetype($masterfile) eq 'mdwn') ? 1 : 0);
806 my $doc=Locale::Po4a::Chooser::new('text',%options);
807 $doc->{TT}{utf_mode} = 1;
808 $doc->{TT}{file_in_charset} = 'utf-8';
809 $doc->{TT}{file_out_charset} = 'utf-8';
810 $doc->read($masterfile);
811 # let's cheat a bit to force porefs option to be passed to
812 # Locale::Po4a::Po; this is undocument use of internal
813 # Locale::Po4a::TransTractor's data, compulsory since this module
814 # prevents us from using the porefs option.
815 $doc->{TT}{po_out}=Locale::Po4a::Po->new({ 'porefs' => 'none' });
816 $doc->{TT}{po_out}->set_charset('utf-8');
819 IkiWiki::prep_writefile(basename($potfile),dirname($potfile));
820 $doc->writepo($potfile);
823 sub refreshpofiles ($@) {
824 my $masterfile=shift;
827 my $potfile=potfile($masterfile);
829 error("po(refreshpofiles) ".sprintf(gettext("POT file (%s) does not exist"), $potfile));
832 foreach my $pofile (@pofiles) {
833 IkiWiki::prep_writefile(basename($pofile),dirname($pofile));
836 # If the po file exists in an underlay, copy it
838 my ($pobase)=$pofile=~/^\Q$config{srcdir}\E\/?(.*)$/;
839 foreach my $dir (@{$config{underlaydirs}}) {
840 if (-e "$dir/$pobase") {
841 File::Copy::syscopy("$dir/$pobase",$pofile)
842 or error("po(refreshpofiles) ".
843 sprintf(gettext("failed to copy underlay PO file to %s"),
850 system("msgmerge", "--previous", "-q", "-U", "--backup=none", $pofile, $potfile) == 0
851 or error("po(refreshpofiles) ".
852 sprintf(gettext("failed to update %s"),
856 File::Copy::syscopy($potfile,$pofile)
857 or error("po(refreshpofiles) ".
858 sprintf(gettext("failed to copy the POT file to %s"),
864 sub buildtranslationscache() {
865 # use istranslation's side-effect
866 map istranslation($_), (keys %pagesources);
869 sub resettranslationscache() {
873 sub flushmemoizecache() {
874 Memoize::flush_cache("istranslatable");
875 Memoize::flush_cache("_istranslation");
876 Memoize::flush_cache("percenttranslated");
879 sub urlto_with_orig_beautiful_urlpath($$) {
883 inject(name => "IkiWiki::beautify_urlpath", call => $origsubs{'beautify_urlpath'});
884 my $res=urlto($to, $from);
885 inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath);
890 sub percenttranslated ($) {
894 return gettext("N/A") unless istranslation($page);
895 my $file=srcfile($pagesources{$page});
896 my $masterfile = srcfile($pagesources{masterpage($page)});
898 "markdown" => (pagetype($masterfile) eq 'mdwn') ? 1 : 0,
900 my $doc=Locale::Po4a::Chooser::new('text',%options);
902 'po_in_name' => [ $file ],
903 'file_in_name' => [ $masterfile ],
904 'file_in_charset' => 'utf-8',
905 'file_out_charset' => 'utf-8',
906 ) or error("po(percenttranslated) ".
907 sprintf(gettext("failed to translate %s"), $page));
908 my ($percent,$hit,$queries) = $doc->stats();
909 $percent =~ s/\.[0-9]+$//;
913 sub languagename ($) {
916 return $config{po_master_language}{name}
917 if $code eq $config{po_master_language}{code};
918 return $config{po_slave_languages}{$code}
919 if defined $config{po_slave_languages}{$code};
923 sub otherlanguagesloop ($) {
927 my %otherpages=%{otherlanguages($page)};
928 while (my ($lang, $otherpage) = each %otherpages) {
929 if (istranslation($page) && masterpage($page) eq $otherpage) {
931 url => urlto_with_orig_beautiful_urlpath($otherpage, $page),
933 language => languagename($lang),
937 elsif (istranslation($otherpage)) {
939 url => urlto_with_orig_beautiful_urlpath($otherpage, $page),
941 language => languagename($lang),
942 percent => percenttranslated($otherpage),
947 return -1 if $a->{code} eq $config{po_master_language}{code};
948 return 1 if $b->{code} eq $config{po_master_language}{code};
949 return $a->{language} cmp $b->{language};
953 sub homepageurl (;$) {
956 return urlto('', $page);
959 sub deletetranslations ($) {
960 my $deletedmasterfile=shift;
962 my $deletedmasterpage=pagename($deletedmasterfile);
965 my $file = newpagefile($deletedmasterpage.'.'.$_, 'po');
966 my $absfile = "$config{srcdir}/$file";
967 if (-e $absfile && ! -l $absfile && ! -d $absfile) {
968 push @todelete, $file;
970 } keys %{$config{po_slave_languages}};
974 IkiWiki::rcs_remove($_);
977 IkiWiki::prune("$config{srcdir}/$_");
983 gettext("removed obsolete PO files"),
984 "IkiWiki::Plugin::po::deletetranslations");
988 sub commit_and_refresh ($$) {
989 my ($msg, $author) = (shift, shift);
992 IkiWiki::disable_commit_hook();
993 IkiWiki::rcs_commit_staged($msg, $author, "127.0.0.1");
994 IkiWiki::enable_commit_hook();
995 IkiWiki::rcs_update();
997 # Reinitialize module's private variables.
998 resetalreadyfiltered();
999 resettranslationscache();
1000 flushmemoizecache();
1001 # Trigger a wiki refresh.
1002 require IkiWiki::Render;
1003 # without preliminary saveindex/loadindex, refresh()
1004 # complains about a lot of uninitialized variables
1005 IkiWiki::saveindex();
1006 IkiWiki::loadindex();
1008 IkiWiki::saveindex();
1011 # on success, returns the filtered content.
1012 # on error, if $nonfatal, warn and return undef; else, error out.
1013 sub po_to_markup ($$;$) {
1014 my ($page, $content) = (shift, shift);
1015 my $nonfatal = shift;
1017 $content = '' unless defined $content;
1018 $content = decode_utf8(encode_utf8($content));
1019 # CRLF line terminators make poor Locale::Po4a feel bad
1020 $content=~s/\r\n/\n/g;
1022 # There are incompatibilities between some File::Temp versions
1023 # (including 0.18, bundled with Lenny's perl-modules package)
1024 # and others (e.g. 0.20, previously present in the archive as
1025 # a standalone package): under certain circumstances, some
1026 # return a relative filename, whereas others return an absolute one;
1027 # we here use this module in a way that is at least compatible
1028 # with 0.18 and 0.20. Beware, hit'n'run refactorers!
1029 my $infile = new File::Temp(TEMPLATE => "ikiwiki-po-filter-in.XXXXXXXXXX",
1030 DIR => File::Spec->tmpdir,
1031 UNLINK => 1)->filename;
1032 my $outfile = new File::Temp(TEMPLATE => "ikiwiki-po-filter-out.XXXXXXXXXX",
1033 DIR => File::Spec->tmpdir,
1034 UNLINK => 1)->filename;
1036 my $fail = sub ($) {
1037 my $msg = "po(po_to_markup) - $page : " . shift;
1042 error($msg, sub { unlink $infile, $outfile});
1045 writefile(basename($infile), File::Spec->tmpdir, $content)
1046 or return $fail->(sprintf(gettext("failed to write %s"), $infile));
1048 my $masterfile = srcfile($pagesources{masterpage($page)});
1050 "markdown" => (pagetype($masterfile) eq 'mdwn') ? 1 : 0,
1052 my $doc=Locale::Po4a::Chooser::new('text',%options);
1054 'po_in_name' => [ $infile ],
1055 'file_in_name' => [ $masterfile ],
1056 'file_in_charset' => 'utf-8',
1057 'file_out_charset' => 'utf-8',
1058 ) or return $fail->(gettext("failed to translate"));
1059 $doc->write($outfile)
1060 or return $fail->(sprintf(gettext("failed to write %s"), $outfile));
1062 $content = readfile($outfile)
1063 or return $fail->(sprintf(gettext("failed to read %s"), $outfile));
1065 # Unlinking should happen automatically, thanks to File::Temp,
1066 # but it does not work here, probably because of the way writefile()
1067 # and Locale::Po4a::write() work.
1068 unlink $infile, $outfile;
1073 # returns a SuccessReason or FailReason object
1075 my $content = shift;
1077 # NB: we don't use po_to_markup here, since Po4a parser does
1078 # not mind invalid PO content
1079 $content = '' unless defined $content;
1080 $content = decode_utf8(encode_utf8($content));
1082 # There are incompatibilities between some File::Temp versions
1083 # (including 0.18, bundled with Lenny's perl-modules package)
1084 # and others (e.g. 0.20, previously present in the archive as
1085 # a standalone package): under certain circumstances, some
1086 # return a relative filename, whereas others return an absolute one;
1087 # we here use this module in a way that is at least compatible
1088 # with 0.18 and 0.20. Beware, hit'n'run refactorers!
1089 my $infile = new File::Temp(TEMPLATE => "ikiwiki-po-isvalidpo.XXXXXXXXXX",
1090 DIR => File::Spec->tmpdir,
1091 UNLINK => 1)->filename;
1093 my $fail = sub ($) {
1094 my $msg = '[po/isvalidpo] ' . shift;
1096 return IkiWiki::FailReason->new("$msg");
1099 writefile(basename($infile), File::Spec->tmpdir, $content)
1100 or return $fail->(sprintf(gettext("failed to write %s"), $infile));
1102 my $res = (system("msgfmt", "--check", $infile, "-o", "/dev/null") == 0);
1104 # Unlinking should happen automatically, thanks to File::Temp,
1105 # but it does not work here, probably because of the way writefile()
1106 # and Locale::Po4a::write() work.
1110 return IkiWiki::SuccessReason->new("valid gettext data");
1112 return IkiWiki::FailReason->new(gettext("invalid gettext data, go back ".
1113 "to previous page to continue edit"));
1120 package IkiWiki::PageSpec;
1122 sub match_istranslation ($;@) {
1125 if (IkiWiki::Plugin::po::istranslation($page)) {
1126 return IkiWiki::SuccessReason->new("is a translation page");
1129 return IkiWiki::FailReason->new("is not a translation page");
1133 sub match_istranslatable ($;@) {
1136 if (IkiWiki::Plugin::po::istranslatable($page)) {
1137 return IkiWiki::SuccessReason->new("is set as translatable in po_translatable_pages");
1140 return IkiWiki::FailReason->new("is not set as translatable in po_translatable_pages");
1144 sub match_lang ($$;@) {
1148 my $regexp=IkiWiki::glob2re($wanted);
1149 my $lang=IkiWiki::Plugin::po::lang($page);
1150 if ($lang !~ /^$regexp$/i) {
1151 return IkiWiki::FailReason->new("file language is $lang, not $wanted");
1154 return IkiWiki::SuccessReason->new("file language is $wanted");
1158 sub match_currentlang ($$;@) {
1163 return IkiWiki::FailReason->new("no location provided") unless exists $params{location};
1165 my $currentlang=IkiWiki::Plugin::po::lang($params{location});
1166 my $lang=IkiWiki::Plugin::po::lang($page);
1168 if ($lang eq $currentlang) {
1169 return IkiWiki::SuccessReason->new("file language is the same as current one, i.e. $currentlang");
1172 return IkiWiki::FailReason->new("file language is $lang, whereas current language is $currentlang");