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 use Locale::Po4a::Common qw(nowrapi18n !/.*/);
14 use Locale::Po4a::Chooser;
27 memoize("istranslatable");
28 memoize("_istranslation");
29 memoize("percenttranslated");
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 => "rename", id => "po", call => \&renamepages, first => 1);
40 hook(type => "delete", id => "po", call => \&mydelete);
41 hook(type => "change", id => "po", call => \&change);
42 hook(type => "checkcontent", id => "po", call => \&checkcontent);
43 hook(type => "canremove", id => "po", call => \&canremove);
44 hook(type => "canrename", id => "po", call => \&canrename);
45 hook(type => "editcontent", id => "po", call => \&editcontent);
46 hook(type => "formbuilder_setup", id => "po", call => \&formbuilder_setup, last => 1);
47 hook(type => "formbuilder", id => "po", call => \&formbuilder);
49 $origsubs{'bestlink'}=\&IkiWiki::bestlink;
50 inject(name => "IkiWiki::bestlink", call => \&mybestlink);
51 $origsubs{'beautify_urlpath'}=\&IkiWiki::beautify_urlpath;
52 inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath);
53 $origsubs{'targetpage'}=\&IkiWiki::targetpage;
54 inject(name => "IkiWiki::targetpage", call => \&mytargetpage);
55 $origsubs{'urlto'}=\&IkiWiki::urlto;
56 inject(name => "IkiWiki::urlto", call => \&myurlto);
57 $origsubs{'cgiurl'}=\&IkiWiki::cgiurl;
58 inject(name => "IkiWiki::cgiurl", call => \&mycgiurl);
67 # 2. Injected functions
68 # 3. Blackboxes for private data
83 po_master_language => {
89 description => "master language (non-PO files)",
93 po_slave_languages => {
100 description => "slave languages (PO files)",
104 po_translatable_pages => {
106 example => "* and !*/Discussion",
107 description => "PageSpec controlling which pages are translatable",
108 link => "ikiwiki/PageSpec",
114 example => "current",
115 description => "internal linking behavior (default/current/negotiated)",
122 foreach my $field (qw{po_master_language}) {
123 if (! exists $config{$field} || ! defined $config{$field}) {
124 error(sprintf(gettext("Must specify %s when using the %s plugin"),
131 or error(sprintf(gettext("%s is not a valid language code"), $_));
132 } ($config{po_master_language}{code}, keys %{$config{po_slave_languages}});
134 if (! exists $config{po_translatable_pages} ||
135 ! defined $config{po_translatable_pages}) {
136 $config{po_translatable_pages}="";
138 if (! exists $config{po_link_to} ||
139 ! defined $config{po_link_to}) {
140 $config{po_link_to}='default';
142 elsif ($config{po_link_to} !~ /^(default|current|negotiated)$/) {
143 warn(sprintf(gettext('%s is not a valid value for po_link_to, falling back to po_link_to=default'),
144 $config{po_link_to}));
145 $config{po_link_to}='default';
147 elsif ($config{po_link_to} eq "negotiated" && ! $config{usedirs}) {
148 warn(gettext('po_link_to=negotiated requires usedirs to be enabled, falling back to po_link_to=default'));
149 $config{po_link_to}='default';
152 push @{$config{wiki_file_prune_regexps}}, qr/\.pot$/;
154 # Translated versions of the underlays are added if available.
155 foreach my $underlay ("basewiki", map { m/^\Q$config{underlaydirbase}\E\/*(.*)/ } reverse @{$config{underlaydirs}}) {
156 next if $underlay=~/^locale\//;
158 # Add underlays containing the po files for slave languages.
159 foreach my $ll (keys %{$config{po_slave_languages}}) {
160 add_underlay("locale/mo/$underlay")
161 if -d "$config{underlaydirbase}/locale/mo/$underlay";
164 if ($config{po_master_language}{code} ne 'en') {
165 # Add underlay containing translated source files
166 # for the master language.
167 add_underlay("locale/$config{po_master_language}{code}/$underlay");
173 my $needsbuild=shift;
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);
180 buildtranslationscache();
182 # make existing translations depend on the corresponding master page
183 foreach my $master (keys %translations) {
184 map add_depends($_, $master), values %{otherlanguages($master)};
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
194 my $page=$params{page};
195 my $content=$params{content};
197 if (istranslation($page)) {
198 foreach my $destpage (@{$links{$page}}) {
199 if (istranslatable($destpage)) {
200 # replace one occurence of $destpage in $links{$page}
201 # (we only want to replace the one that was added by
202 # IkiWiki::Plugin::link::scan, other occurences may be
203 # there for other reasons)
204 for (my $i=0; $i<@{$links{$page}}; $i++) {
205 if (@{$links{$page}}[$i] eq $destpage) {
206 @{$links{$page}}[$i] = $destpage . '.' . lang($page);
213 elsif (! istranslatable($page) && ! istranslation($page)) {
214 foreach my $destpage (@{$links{$page}}) {
215 if (istranslatable($destpage)) {
216 # make sure any destpage's translations has
217 # $page in its backlinks
218 push @{$links{$page}},
219 values %{otherlanguages($destpage)};
225 # We use filter to convert PO to the master page's format,
226 # since the rest of ikiwiki should not work on PO files.
230 my $page = $params{page};
231 my $destpage = $params{destpage};
232 my $content = $params{content};
233 if (istranslation($page) && ! alreadyfiltered($page, $destpage)) {
234 $content = po_to_markup($page, $content);
235 setalreadyfiltered($page, $destpage);
243 my $page = $params{page};
244 my $content = $params{content};
246 # ignore PO files this plugin did not create
247 return $content unless istranslation($page);
249 # force content to be htmlize'd as if it was the same type as the master page
250 return IkiWiki::htmlize($page, $page,
251 pagetype(srcfile($pagesources{masterpage($page)})),
255 sub pagetemplate (@) {
257 my $page=$params{page};
258 my $destpage=$params{destpage};
259 my $template=$params{template};
261 my ($masterpage, $lang) = istranslation($page);
263 if (istranslation($page) && $template->query(name => "percenttranslated")) {
264 $template->param(percenttranslated => percenttranslated($page));
266 if ($template->query(name => "istranslation")) {
267 $template->param(istranslation => scalar istranslation($page));
269 if ($template->query(name => "istranslatable")) {
270 $template->param(istranslatable => istranslatable($page));
272 if ($template->query(name => "HOMEPAGEURL")) {
273 $template->param(homepageurl => homepageurl($page));
275 if ($template->query(name => "otherlanguages")) {
276 $template->param(otherlanguages => [otherlanguagesloop($page)]);
277 map add_depends($page, $_), (values %{otherlanguages($page)});
279 if ($config{discussion} && istranslation($page)) {
280 my $discussionlink=gettext("discussion");
281 if ($page !~ /.*\/\Q$discussionlink\E$/i &&
282 (length $config{cgiurl} ||
283 exists $links{$masterpage."/".$discussionlink})) {
284 $template->param('discussionlink' => htmllink(
287 $masterpage . '/' . gettext("Discussion"),
290 linktext => gettext("Discussion"),
294 # Remove broken parentlink to ./index.html on home page's translations.
295 # It works because this hook has the "last" parameter set, to ensure it
296 # runs after parentlinks' own pagetemplate hook.
297 if ($template->param('parentlinks')
298 && istranslation($page)
299 && $masterpage eq "index") {
300 $template->param('parentlinks' => []);
304 # Add the renamed page translations to the list of to-be-renamed pages.
305 sub renamepages (@) {
308 my %torename = %{$params{torename}};
309 my $session = $params{session};
311 # Save the page(s) the user asked to rename, so that our
312 # canrename hook can tell the difference between:
313 # - a translation being renamed as a consequence of its master page
315 # - a user trying to directly rename a translation
316 # This is why this hook has to be run first, before the list of pages
317 # to rename is modified by other plugins.
319 @orig_torename=@{$session->param("po_orig_torename")}
320 if defined $session->param("po_orig_torename");
321 push @orig_torename, $torename{src};
322 $session->param(po_orig_torename => \@orig_torename);
323 IkiWiki::cgi_savesession($session);
325 return () unless istranslatable($torename{src});
328 my %otherpages=%{otherlanguages($torename{src})};
329 while (my ($lang, $otherpage) = each %otherpages) {
332 srcfile => $pagesources{$otherpage},
333 dest => otherlanguage($torename{dest}, $lang),
334 destfile => $torename{dest}.".".$lang.".po",
344 map { deletetranslations($_) } grep istranslatablefile($_), @deleted;
350 # All meta titles are first extracted at scan time, i.e. before we turn
351 # PO files back into translated markdown; escaping of double-quotes in
352 # PO files breaks the meta plugin's parsing enough to save ugly titles
353 # to %pagestate at this time.
355 # Then, at render time, every page passes in turn through the Great
356 # Rendering Chain (filter->preprocess->linkify->htmlize), and the meta
357 # plugin's preprocess hook is this time in a position to correctly
358 # extract the titles from slave pages.
360 # This is, unfortunately, too late: if the page A, linking to the page
361 # B, is rendered before B, it will display the wrongly-extracted meta
362 # title as the link text to B.
364 # On the one hand, such a corner case only happens on rebuild: on
365 # refresh, every rendered page is fixed to contain correct meta titles.
366 # On the other hand, it can take some time to get every page fixed.
367 # We therefore re-render every rendered page after a rebuild to fix them
368 # at once. As this more or less doubles the time needed to rebuild the
369 # wiki, we do so only when really needed.
372 && exists $config{rebuild} && defined $config{rebuild} && $config{rebuild}
373 && UNIVERSAL::can("IkiWiki::Plugin::meta", "getsetup")
374 && exists $config{meta_overrides_page_title}
375 && defined $config{meta_overrides_page_title}
376 && $config{meta_overrides_page_title}) {
377 debug(sprintf(gettext("re-rendering all pages to fix meta titles")));
378 resetalreadyfiltered();
379 require IkiWiki::Render;
380 foreach my $file (@rendered) {
381 debug(sprintf(gettext("rendering %s"), $file));
382 IkiWiki::render($file);
386 my $updated_po_files=0;
388 # Refresh/create POT and PO files as needed.
389 # (But avoid doing so if they are in an underlay directory.)
390 foreach my $file (grep {istranslatablefile($_)} @rendered) {
391 my $masterfile=srcfile($file);
392 my $page=pagename($file);
393 my $updated_pot_file=0;
394 # Only refresh POT file if it does not exist, or if
395 # $pagesources{$page} was changed: don't if only the HTML was
396 # refreshed, e.g. because of a dependency.
397 if ($masterfile eq "$config{srcdir}/$file" &&
398 ((grep { $_ eq $pagesources{$page} } @origneedsbuild)
399 || ! -e potfile($masterfile))) {
400 refreshpot($masterfile);
404 foreach my $po (pofiles($masterfile)) {
405 next if ! $updated_pot_file && ! -e $po;
406 next if grep { $po=~/\Q$_\E/ } @{$config{underlaydirs}};
410 refreshpofiles($masterfile, @pofiles);
411 map { IkiWiki::rcs_add($_) } @pofiles if $config{rcs};
416 if ($updated_po_files) {
418 gettext("updated PO files"),
419 "IkiWiki::Plugin::po::change");
423 sub checkcontent (@) {
426 if (istranslation($params{page})) {
427 my $res = isvalidpo($params{content});
441 if (istranslation($params{page})) {
442 return gettext("Can not remove a translation. Removing the master page, ".
443 "though, removes its translations as well.");
450 my $session = $params{session};
452 if (istranslation($params{src})) {
453 my $masterpage = masterpage($params{src});
454 # Tell the difference between:
455 # - a translation being renamed as a consequence of its master page
456 # being renamed, which is allowed
457 # - a user trying to directly rename a translation, which is forbidden
458 # by looking for the master page in the list of to-be-renamed pages we
459 # saved early in the renaming process.
460 my $orig_torename = $session->param("po_orig_torename");
461 unless (grep { $_ eq $masterpage } @{$orig_torename}) {
462 return gettext("Can not rename a translation. Renaming the master page, ".
463 "though, renames its translations as well.");
469 # As we're previewing or saving a page, the content may have
470 # changed, so tell the next filter() invocation it must not be lazy.
474 unsetalreadyfiltered($params{page}, $params{page});
475 return $params{content};
478 sub formbuilder_setup (@) {
480 my $form=$params{form};
483 return unless defined $form->field("do");
485 if ($form->field("do") eq "create") {
486 # Warn the user: new pages must be written in master language.
487 my $template=template("pocreatepage.tmpl");
488 $template->param(LANG => $config{po_master_language}{name});
489 $form->tmpl_param(message => $template->output);
491 elsif ($form->field("do") eq "edit") {
492 # Remove the rename/remove buttons on slave pages.
493 # This has to be done after the rename/remove plugins have added
494 # their buttons, which is why this hook must be run last.
495 # The canrename/canremove hooks already ensure this is forbidden
496 # at the backend level, so this is only UI sugar.
497 if (istranslation($form->field("page"))) {
499 for (my $i = 0; $i < @{$params{buttons}}; $i++) {
500 if (@{$params{buttons}}[$i] eq $_) {
501 delete @{$params{buttons}}[$i];
510 sub formbuilder (@) {
512 my $form=$params{form};
515 return unless defined $form->field("do");
517 # Do not allow to create pages of type po: they are automatically created.
518 # The main reason to do so is to bypass the "favor the type of linking page
519 # on page creation" logic, which is unsuitable when a broken link is clicked
520 # on a slave (PO) page.
521 # This cannot be done in the formbuilder_setup hook as the list of types is
523 if ($form->field("do") eq "create") {
524 foreach my $field ($form->field) {
525 next unless "$field" eq "type";
526 if ($field->type eq 'select') {
527 # remove po from the list of types
528 my @types = grep { $_ ne 'po' } $field->options;
529 $field->options(\@types) if @types;
536 # | Injected functions
539 # Implement po_link_to 'current' and 'negotiated' settings.
540 sub mybestlink ($$) {
544 my $res=$origsubs{'bestlink'}->(masterpage($page), $link);
546 && ($config{po_link_to} eq "current" || $config{po_link_to} eq "negotiated")
547 && istranslatable($res)
548 && istranslation($page)) {
549 return $res . "." . lang($page);
554 sub mybeautify_urlpath ($) {
557 my $res=$origsubs{'beautify_urlpath'}->($url);
558 if ($config{po_link_to} eq "negotiated") {
559 $res =~ s!/\Qindex.$config{po_master_language}{code}.$config{htmlext}\E$!/!;
560 $res =~ s!/\Qindex.$config{htmlext}\E$!/!;
562 $res =~ s!/\Qindex.$_.$config{htmlext}\E$!/!;
563 } (keys %{$config{po_slave_languages}});
568 sub mytargetpage ($$) {
572 if (istranslation($page) || istranslatable($page)) {
573 my ($masterpage, $lang) = (masterpage($page), lang($page));
574 if (! $config{usedirs} || $masterpage eq 'index') {
575 return $masterpage . "." . $lang . "." . $ext;
578 return $masterpage . "/index." . $lang . "." . $ext;
581 return $origsubs{'targetpage'}->($page, $ext);
589 # workaround hard-coded /index.$config{htmlext} in IkiWiki::urlto()
591 && $config{po_link_to} eq "current"
592 && istranslatable('index')) {
593 return IkiWiki::beautify_urlpath(IkiWiki::baseurl($from) . "index." . lang($from) . ".$config{htmlext}");
595 # avoid using our injected beautify_urlpath if run by cgi_editpage,
596 # so that one is redirected to the just-edited page rather than to the
597 # negociated translation; to prevent unnecessary fiddling with caller/inject,
598 # we only do so when our beautify_urlpath would actually do what we want to
599 # avoid, i.e. when po_link_to = negotiated
600 if ($config{po_link_to} eq "negotiated") {
601 my @caller = caller(1);
602 my $run_by_editpage = 0;
603 $run_by_editpage = 1 if (exists $caller[3] && defined $caller[3]
604 && $caller[3] eq "IkiWiki::cgi_editpage");
605 inject(name => "IkiWiki::beautify_urlpath", call => $origsubs{'beautify_urlpath'})
607 my $res = $origsubs{'urlto'}->($to,$from,$absolute);
608 inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath)
613 return $origsubs{'urlto'}->($to,$from,$absolute)
620 # slave pages have no subpages
621 if (istranslation($params{'from'})) {
622 $params{'from'} = masterpage($params{'from'});
624 return $origsubs{'cgiurl'}->(%params);
628 # | Blackboxes for private data
634 sub alreadyfiltered($$) {
638 return exists $filtered{$page}{$destpage}
639 && $filtered{$page}{$destpage} eq 1;
642 sub setalreadyfiltered($$) {
646 $filtered{$page}{$destpage}=1;
649 sub unsetalreadyfiltered($$) {
653 if (exists $filtered{$page}{$destpage}) {
654 delete $filtered{$page}{$destpage};
658 sub resetalreadyfiltered() {
667 sub maybe_add_leading_slash ($;$) {
670 $add=1 unless defined $add;
671 return '/' . $str if $add;
675 sub istranslatablefile ($) {
678 return 0 unless defined $file;
679 my $type=pagetype($file);
680 return 0 if ! defined $type || $type eq 'po';
681 return 0 if $file =~ /\.pot$/;
682 return 1 if pagespec_match(pagename($file), $config{po_translatable_pages});
686 sub istranslatable ($) {
690 return 1 if istranslatablefile($pagesources{$page});
694 sub _istranslation ($) {
697 $page='' unless defined $page && length $page;
698 my $hasleadingslash = ($page=~s#^/##);
699 my $file=$pagesources{$page};
700 return 0 unless defined $file
701 && defined pagetype($file)
702 && pagetype($file) eq 'po';
703 return 0 if $file =~ /\.pot$/;
705 my ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
706 return 0 unless defined $masterpage && defined $lang
707 && length $masterpage && length $lang
708 && defined $pagesources{$masterpage}
709 && defined $config{po_slave_languages}{$lang};
711 return (maybe_add_leading_slash($masterpage, $hasleadingslash), $lang)
712 if istranslatable($masterpage);
715 sub istranslation ($) {
718 if (1 < (my ($masterpage, $lang) = _istranslation($page))) {
719 my $hasleadingslash = ($masterpage=~s#^/##);
720 $translations{$masterpage}{$lang}=$page unless exists $translations{$masterpage}{$lang};
721 return (maybe_add_leading_slash($masterpage, $hasleadingslash), $lang);
729 if ( 1 < (my ($masterpage, $lang) = _istranslation($page))) {
738 if (1 < (my ($masterpage, $lang) = _istranslation($page))) {
741 return $config{po_master_language}{code};
744 sub islanguagecode ($) {
747 return $code =~ /^[a-z]{2}$/;
750 sub otherlanguage ($$) {
754 return masterpage($page) if $code eq $config{po_master_language}{code};
755 return masterpage($page) . '.' . $code;
758 sub otherlanguages ($) {
762 return \%ret unless istranslation($page) || istranslatable($page);
763 my $curlang=lang($page);
765 ($config{po_master_language}{code}, keys %{$config{po_slave_languages}}) {
766 next if $lang eq $curlang;
767 $ret{$lang}=otherlanguage($page, $lang);
773 my $masterfile=shift;
775 (my $name, my $dir, my $suffix) = fileparse($masterfile, qr/\.[^.]*/);
776 $dir='' if $dir eq './';
777 return File::Spec->catpath('', $dir, $name . ".pot");
781 my $masterfile=shift;
784 (my $name, my $dir, my $suffix) = fileparse($masterfile, qr/\.[^.]*/);
785 $dir='' if $dir eq './';
786 return File::Spec->catpath('', $dir, $name . "." . $lang . ".po");
790 my $masterfile=shift;
792 return map pofile($masterfile, $_), (keys %{$config{po_slave_languages}});
796 my $masterfile=shift;
798 my $potfile=potfile($masterfile);
799 my %options = ("markdown" => (pagetype($masterfile) eq 'mdwn') ? 1 : 0);
800 my $doc=Locale::Po4a::Chooser::new('text',%options);
801 $doc->{TT}{utf_mode} = 1;
802 $doc->{TT}{file_in_charset} = 'utf-8';
803 $doc->{TT}{file_out_charset} = 'utf-8';
804 $doc->read($masterfile);
805 # let's cheat a bit to force porefs option to be passed to
806 # Locale::Po4a::Po; this is undocument use of internal
807 # Locale::Po4a::TransTractor's data, compulsory since this module
808 # prevents us from using the porefs option.
809 $doc->{TT}{po_out}=Locale::Po4a::Po->new({ 'porefs' => 'none' });
810 $doc->{TT}{po_out}->set_charset('utf-8');
813 IkiWiki::prep_writefile(basename($potfile),dirname($potfile));
814 $doc->writepo($potfile);
817 sub refreshpofiles ($@) {
818 my $masterfile=shift;
821 my $potfile=potfile($masterfile);
823 error("po(refreshpofiles) ".sprintf(gettext("POT file (%s) does not exist"), $potfile));
826 foreach my $pofile (@pofiles) {
827 IkiWiki::prep_writefile(basename($pofile),dirname($pofile));
829 system("msgmerge", "-q", "-U", "--backup=none", $pofile, $potfile) == 0
830 or error("po(refreshpofiles) ".
831 sprintf(gettext("failed to update %s"),
835 File::Copy::syscopy($potfile,$pofile)
836 or error("po(refreshpofiles) ".
837 sprintf(gettext("failed to copy the POT file to %s"),
843 sub buildtranslationscache() {
844 # use istranslation's side-effect
845 map istranslation($_), (keys %pagesources);
848 sub resettranslationscache() {
852 sub flushmemoizecache() {
853 Memoize::flush_cache("istranslatable");
854 Memoize::flush_cache("_istranslation");
855 Memoize::flush_cache("percenttranslated");
858 sub urlto_with_orig_beautiful_urlpath($$) {
862 inject(name => "IkiWiki::beautify_urlpath", call => $origsubs{'beautify_urlpath'});
863 my $res=urlto($to, $from);
864 inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath);
869 sub percenttranslated ($) {
873 return gettext("N/A") unless istranslation($page);
874 my $file=srcfile($pagesources{$page});
875 my $masterfile = srcfile($pagesources{masterpage($page)});
877 "markdown" => (pagetype($masterfile) eq 'mdwn') ? 1 : 0,
879 my $doc=Locale::Po4a::Chooser::new('text',%options);
881 'po_in_name' => [ $file ],
882 'file_in_name' => [ $masterfile ],
883 'file_in_charset' => 'utf-8',
884 'file_out_charset' => 'utf-8',
885 ) or error("po(percenttranslated) ".
886 sprintf(gettext("failed to translate %s"), $page));
887 my ($percent,$hit,$queries) = $doc->stats();
888 $percent =~ s/\.[0-9]+$//;
892 sub languagename ($) {
895 return $config{po_master_language}{name}
896 if $code eq $config{po_master_language}{code};
897 return $config{po_slave_languages}{$code}
898 if defined $config{po_slave_languages}{$code};
902 sub otherlanguagesloop ($) {
906 my %otherpages=%{otherlanguages($page)};
907 while (my ($lang, $otherpage) = each %otherpages) {
908 if (istranslation($page) && masterpage($page) eq $otherpage) {
910 url => urlto_with_orig_beautiful_urlpath($otherpage, $page),
912 language => languagename($lang),
918 url => urlto_with_orig_beautiful_urlpath($otherpage, $page),
920 language => languagename($lang),
921 percent => percenttranslated($otherpage),
926 return -1 if $a->{code} eq $config{po_master_language}{code};
927 return 1 if $b->{code} eq $config{po_master_language}{code};
928 return $a->{language} cmp $b->{language};
932 sub homepageurl (;$) {
935 return urlto('', $page);
938 sub deletetranslations ($) {
939 my $deletedmasterfile=shift;
941 my $deletedmasterpage=pagename($deletedmasterfile);
944 my $file = newpagefile($deletedmasterpage.'.'.$_, 'po');
945 my $absfile = "$config{srcdir}/$file";
946 if (-e $absfile && ! -l $absfile && ! -d $absfile) {
947 push @todelete, $file;
949 } keys %{$config{po_slave_languages}};
953 IkiWiki::rcs_remove($_);
956 IkiWiki::prune("$config{srcdir}/$_");
962 gettext("removed obsolete PO files"),
963 "IkiWiki::Plugin::po::deletetranslations");
967 sub commit_and_refresh ($$) {
968 my ($msg, $author) = (shift, shift);
971 IkiWiki::disable_commit_hook();
972 IkiWiki::rcs_commit_staged($msg, $author, "127.0.0.1");
973 IkiWiki::enable_commit_hook();
974 IkiWiki::rcs_update();
976 # Reinitialize module's private variables.
977 resetalreadyfiltered();
978 resettranslationscache();
980 # Trigger a wiki refresh.
981 require IkiWiki::Render;
982 # without preliminary saveindex/loadindex, refresh()
983 # complains about a lot of uninitialized variables
984 IkiWiki::saveindex();
985 IkiWiki::loadindex();
987 IkiWiki::saveindex();
990 # on success, returns the filtered content.
991 # on error, if $nonfatal, warn and return undef; else, error out.
992 sub po_to_markup ($$;$) {
993 my ($page, $content) = (shift, shift);
994 my $nonfatal = shift;
996 $content = '' unless defined $content;
997 $content = decode_utf8(encode_utf8($content));
998 # CRLF line terminators make poor Locale::Po4a feel bad
999 $content=~s/\r\n/\n/g;
1001 # There are incompatibilities between some File::Temp versions
1002 # (including 0.18, bundled with Lenny's perl-modules package)
1003 # and others (e.g. 0.20, previously present in the archive as
1004 # a standalone package): under certain circumstances, some
1005 # return a relative filename, whereas others return an absolute one;
1006 # we here use this module in a way that is at least compatible
1007 # with 0.18 and 0.20. Beware, hit'n'run refactorers!
1008 my $infile = new File::Temp(TEMPLATE => "ikiwiki-po-filter-in.XXXXXXXXXX",
1009 DIR => File::Spec->tmpdir,
1010 UNLINK => 1)->filename;
1011 my $outfile = new File::Temp(TEMPLATE => "ikiwiki-po-filter-out.XXXXXXXXXX",
1012 DIR => File::Spec->tmpdir,
1013 UNLINK => 1)->filename;
1015 my $fail = sub ($) {
1016 my $msg = "po(po_to_markup) - $page : " . shift;
1021 error($msg, sub { unlink $infile, $outfile});
1024 writefile(basename($infile), File::Spec->tmpdir, $content)
1025 or return $fail->(sprintf(gettext("failed to write %s"), $infile));
1027 my $masterfile = srcfile($pagesources{masterpage($page)});
1029 "markdown" => (pagetype($masterfile) eq 'mdwn') ? 1 : 0,
1031 my $doc=Locale::Po4a::Chooser::new('text',%options);
1033 'po_in_name' => [ $infile ],
1034 'file_in_name' => [ $masterfile ],
1035 'file_in_charset' => 'utf-8',
1036 'file_out_charset' => 'utf-8',
1037 ) or return $fail->(gettext("failed to translate"));
1038 $doc->write($outfile)
1039 or return $fail->(sprintf(gettext("failed to write %s"), $outfile));
1041 $content = readfile($outfile)
1042 or return $fail->(sprintf(gettext("failed to read %s"), $outfile));
1044 # Unlinking should happen automatically, thanks to File::Temp,
1045 # but it does not work here, probably because of the way writefile()
1046 # and Locale::Po4a::write() work.
1047 unlink $infile, $outfile;
1052 # returns a SuccessReason or FailReason object
1054 my $content = shift;
1056 # NB: we don't use po_to_markup here, since Po4a parser does
1057 # not mind invalid PO content
1058 $content = '' unless defined $content;
1059 $content = decode_utf8(encode_utf8($content));
1061 # There are incompatibilities between some File::Temp versions
1062 # (including 0.18, bundled with Lenny's perl-modules package)
1063 # and others (e.g. 0.20, previously present in the archive as
1064 # a standalone package): under certain circumstances, some
1065 # return a relative filename, whereas others return an absolute one;
1066 # we here use this module in a way that is at least compatible
1067 # with 0.18 and 0.20. Beware, hit'n'run refactorers!
1068 my $infile = new File::Temp(TEMPLATE => "ikiwiki-po-isvalidpo.XXXXXXXXXX",
1069 DIR => File::Spec->tmpdir,
1070 UNLINK => 1)->filename;
1072 my $fail = sub ($) {
1073 my $msg = '[po/isvalidpo] ' . shift;
1075 return IkiWiki::FailReason->new("$msg");
1078 writefile(basename($infile), File::Spec->tmpdir, $content)
1079 or return $fail->(sprintf(gettext("failed to write %s"), $infile));
1081 my $res = (system("msgfmt", "--check", $infile, "-o", "/dev/null") == 0);
1083 # Unlinking should happen automatically, thanks to File::Temp,
1084 # but it does not work here, probably because of the way writefile()
1085 # and Locale::Po4a::write() work.
1089 return IkiWiki::SuccessReason->new("valid gettext data");
1091 return IkiWiki::FailReason->new("invalid gettext data, go back ".
1092 "to previous page to go on with edit");
1099 package IkiWiki::PageSpec;
1101 sub match_istranslation ($;@) {
1104 if (IkiWiki::Plugin::po::istranslation($page)) {
1105 return IkiWiki::SuccessReason->new("is a translation page");
1108 return IkiWiki::FailReason->new("is not a translation page");
1112 sub match_istranslatable ($;@) {
1115 if (IkiWiki::Plugin::po::istranslatable($page)) {
1116 return IkiWiki::SuccessReason->new("is set as translatable in po_translatable_pages");
1119 return IkiWiki::FailReason->new("is not set as translatable in po_translatable_pages");
1123 sub match_lang ($$;@) {
1127 my $regexp=IkiWiki::glob2re($wanted);
1128 my $lang=IkiWiki::Plugin::po::lang($page);
1129 if ($lang !~ /^$regexp$/i) {
1130 return IkiWiki::FailReason->new("file language is $lang, not $wanted");
1133 return IkiWiki::SuccessReason->new("file language is $wanted");
1137 sub match_currentlang ($$;@) {
1142 return IkiWiki::FailReason->new("no location provided") unless exists $params{location};
1144 my $currentlang=IkiWiki::Plugin::po::lang($params{location});
1145 my $lang=IkiWiki::Plugin::po::lang($page);
1147 if ($lang eq $currentlang) {
1148 return IkiWiki::SuccessReason->new("file language is the same as current one, i.e. $currentlang");
1151 return IkiWiki::FailReason->new("file language is $lang, whereas current language is $currentlang");