summaryrefslogtreecommitdiff
path: root/IkiWiki/Plugin/po.pm
blob: cfba839958d0be0569b3b2de9316f01f2e754899 (plain)
  1. #!/usr/bin/perl
  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;
  8. use warnings;
  9. use strict;
  10. use IkiWiki 2.00;
  11. use Encode;
  12. use Locale::Po4a::Chooser;
  13. use Locale::Po4a::Po;
  14. use File::Basename;
  15. use File::Copy;
  16. use File::Spec;
  17. use File::Temp;
  18. use Memoize;
  19. my %translations;
  20. our %filtered;
  21. memoize("_istranslation");
  22. memoize("percenttranslated");
  23. # FIXME: memoizing istranslatable() makes some test cases fail once every
  24. # two tries; this may be related to the artificial way the testsuite is
  25. # run, or not.
  26. # memoize("istranslatable");
  27. # backup references to subs that will be overriden
  28. my %origsubs;
  29. sub import { #{{{
  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 => "filter", id => "po", call => \&filter);
  34. hook(type => "htmlize", id => "po", call => \&htmlize);
  35. hook(type => "pagetemplate", id => "po", call => \&pagetemplate, last => 1);
  36. hook(type => "editcontent", id => "po", call => \&editcontent);
  37. $origsubs{'bestlink'}=\&IkiWiki::bestlink;
  38. inject(name => "IkiWiki::bestlink", call => \&mybestlink);
  39. $origsubs{'beautify_urlpath'}=\&IkiWiki::beautify_urlpath;
  40. inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath);
  41. $origsubs{'targetpage'}=\&IkiWiki::targetpage;
  42. inject(name => "IkiWiki::targetpage", call => \&mytargetpage);
  43. } #}}}
  44. sub getsetup () { #{{{
  45. return
  46. plugin => {
  47. safe => 0,
  48. rebuild => 1, # format plugin & changes html filenames
  49. },
  50. po_master_language => {
  51. type => "string",
  52. example => {
  53. 'code' => 'en',
  54. 'name' => 'English'
  55. },
  56. description => "master language (non-PO files)",
  57. safe => 1,
  58. rebuild => 1,
  59. },
  60. po_slave_languages => {
  61. type => "string",
  62. example => {
  63. 'fr' => 'Français',
  64. 'es' => 'Castellano',
  65. 'de' => 'Deutsch'
  66. },
  67. description => "slave languages (PO files)",
  68. safe => 1,
  69. rebuild => 1,
  70. },
  71. po_translatable_pages => {
  72. type => "pagespec",
  73. example => "!*/Discussion",
  74. description => "PageSpec controlling which pages are translatable",
  75. link => "ikiwiki/PageSpec",
  76. safe => 1,
  77. rebuild => 1,
  78. },
  79. po_link_to => {
  80. type => "string",
  81. example => "current",
  82. description => "internal linking behavior (default/current/negotiated)",
  83. safe => 1,
  84. rebuild => 1,
  85. },
  86. } #}}}
  87. sub islanguagecode ($) { #{{{
  88. my $code=shift;
  89. return ($code =~ /^[a-z]{2}$/);
  90. } #}}}
  91. sub checkconfig () { #{{{
  92. foreach my $field (qw{po_master_language po_slave_languages}) {
  93. if (! exists $config{$field} || ! defined $config{$field}) {
  94. error(sprintf(gettext("Must specify %s"), $field));
  95. }
  96. }
  97. map {
  98. islanguagecode($_)
  99. or error(sprintf(gettext("%s is not a valid language code"), $_));
  100. } ($config{po_master_language}{code}, keys %{$config{po_slave_languages}});
  101. if (! exists $config{po_translatable_pages} ||
  102. ! defined $config{po_translatable_pages}) {
  103. $config{po_translatable_pages}="";
  104. }
  105. if (! exists $config{po_link_to} ||
  106. ! defined $config{po_link_to}) {
  107. $config{po_link_to}='default';
  108. }
  109. elsif (! grep {
  110. $config{po_link_to} eq $_
  111. } ('default', 'current', 'negotiated')) {
  112. warn(sprintf(gettext('po_link_to=%s is not a valid setting, falling back to po_link_to=default'),
  113. $config{po_link_to}));
  114. $config{po_link_to}='default';
  115. }
  116. elsif ($config{po_link_to} eq "negotiated" && ! $config{usedirs}) {
  117. warn(gettext('po_link_to=negotiated requires usedirs to be enabled, falling back to po_link_to=default'));
  118. $config{po_link_to}='default';
  119. }
  120. push @{$config{wiki_file_prune_regexps}}, qr/\.pot$/;
  121. } #}}}
  122. sub potfile ($) { #{{{
  123. my $masterfile=shift;
  124. (my $name, my $dir, my $suffix) = fileparse($masterfile, qr/\.[^.]*/);
  125. $dir='' if $dir eq './';
  126. return File::Spec->catpath('', $dir, $name . ".pot");
  127. } #}}}
  128. sub pofile ($$) { #{{{
  129. my $masterfile=shift;
  130. my $lang=shift;
  131. (my $name, my $dir, my $suffix) = fileparse($masterfile, qr/\.[^.]*/);
  132. $dir='' if $dir eq './';
  133. return File::Spec->catpath('', $dir, $name . "." . $lang . ".po");
  134. } #}}}
  135. sub refreshpot ($) { #{{{
  136. my $masterfile=shift;
  137. my $potfile=potfile($masterfile);
  138. my %options = ("markdown" => (pagetype($masterfile) eq 'mdwn') ? 1 : 0);
  139. my $doc=Locale::Po4a::Chooser::new('text',%options);
  140. $doc->read($masterfile);
  141. $doc->{TT}{utf_mode} = 1;
  142. $doc->{TT}{file_in_charset} = 'utf-8';
  143. $doc->{TT}{file_out_charset} = 'utf-8';
  144. # let's cheat a bit to force porefs option to be passed to Locale::Po4a::Po;
  145. # this is undocument use of internal Locale::Po4a::TransTractor's data,
  146. # compulsory since this module prevents us from using the porefs option.
  147. my %po_options = ('porefs' => 'none');
  148. $doc->{TT}{po_out}=Locale::Po4a::Po->new(\%po_options);
  149. $doc->{TT}{po_out}->set_charset('utf-8');
  150. # do the actual work
  151. $doc->parse;
  152. IkiWiki::prep_writefile(basename($potfile),dirname($potfile));
  153. $doc->writepo($potfile);
  154. } #}}}
  155. sub refreshpofiles ($@) { #{{{
  156. my $masterfile=shift;
  157. my @pofiles=@_;
  158. my $potfile=potfile($masterfile);
  159. error("[po/refreshpofiles] POT file ($potfile) does not exist") unless (-e $potfile);
  160. foreach my $pofile (@pofiles) {
  161. IkiWiki::prep_writefile(basename($pofile),dirname($pofile));
  162. if (-e $pofile) {
  163. system("msgmerge", "-U", "--backup=none", $pofile, $potfile) == 0
  164. or error("[po/refreshpofiles:$pofile] failed to update");
  165. }
  166. else {
  167. File::Copy::syscopy($potfile,$pofile)
  168. or error("[po/refreshpofiles:$pofile] failed to copy the POT file");
  169. }
  170. }
  171. } #}}}
  172. sub needsbuild () { #{{{
  173. my $needsbuild=shift;
  174. # build %translations, using istranslation's side-effect
  175. foreach my $page (keys %pagesources) {
  176. istranslation($page);
  177. }
  178. # refresh/create POT and PO files as needed
  179. my $updated_po_files=0;
  180. foreach my $page (keys %pagesources) {
  181. if (istranslatable($page)) {
  182. my $pageneedsbuild = grep { $_ eq $pagesources{$page} } @$needsbuild;
  183. my $updated_pot_file=0;
  184. my $file=srcfile($pagesources{$page});
  185. if ($pageneedsbuild || ! -e potfile($file)) {
  186. refreshpot($file);
  187. $updated_pot_file=1;
  188. }
  189. my @pofiles;
  190. foreach my $lang (keys %{$config{po_slave_languages}}) {
  191. my $pofile=pofile($file, $lang);
  192. my $pofile_rel=pofile($pagesources{$page}, $lang);
  193. if ($pageneedsbuild || $updated_pot_file || ! -e $pofile) {
  194. push @pofiles, $pofile;
  195. push @$needsbuild, $pofile_rel
  196. unless grep { $_ eq $pofile_rel } @$needsbuild;
  197. }
  198. }
  199. if (@pofiles) {
  200. refreshpofiles($file, @pofiles);
  201. map { IkiWiki::rcs_add($_); } @pofiles if ($config{rcs});
  202. $updated_po_files = 1;
  203. }
  204. }
  205. }
  206. # check staged changes in
  207. if ($updated_po_files) {
  208. if ($config{rcs}) {
  209. IkiWiki::disable_commit_hook();
  210. IkiWiki::rcs_commit_staged(gettext("updated PO files"),
  211. "refreshpofiles", "127.0.0.1");
  212. IkiWiki::enable_commit_hook();
  213. IkiWiki::rcs_update();
  214. }
  215. # refresh module's private variables
  216. undef %filtered;
  217. undef %translations;
  218. foreach my $page (keys %pagesources) {
  219. istranslation($page);
  220. }
  221. }
  222. # make existing translations depend on the corresponding master page
  223. foreach my $master (keys %translations) {
  224. foreach my $slave (values %{$translations{$master}}) {
  225. add_depends($slave, $master);
  226. }
  227. }
  228. } #}}}
  229. sub mytargetpage ($$) { #{{{
  230. my $page=shift;
  231. my $ext=shift;
  232. if (istranslation($page)) {
  233. my ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
  234. if (! $config{usedirs} || $masterpage eq 'index') {
  235. return $masterpage . "." . $lang . "." . $ext;
  236. }
  237. else {
  238. return $masterpage . "/index." . $lang . "." . $ext;
  239. }
  240. }
  241. elsif (istranslatable($page)) {
  242. if (! $config{usedirs} || $page eq 'index') {
  243. return $page . "." . $config{po_master_language}{code} . "." . $ext;
  244. }
  245. else {
  246. return $page . "/index." . $config{po_master_language}{code} . "." . $ext;
  247. }
  248. }
  249. return $origsubs{'targetpage'}->($page, $ext);
  250. } #}}}
  251. sub mybeautify_urlpath ($) { #{{{
  252. my $url=shift;
  253. my $res=$origsubs{'beautify_urlpath'}->($url);
  254. if ($config{po_link_to} eq "negotiated") {
  255. $res =~ s!/\Qindex.$config{po_master_language}{code}.$config{htmlext}\E$!/!;
  256. }
  257. return $res;
  258. } #}}}
  259. sub urlto_with_orig_beautiful_urlpath($$) { #{{{
  260. my $to=shift;
  261. my $from=shift;
  262. inject(name => "IkiWiki::beautify_urlpath", call => $origsubs{'beautify_urlpath'});
  263. my $res=urlto($to, $from);
  264. inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath);
  265. return $res;
  266. } #}}}
  267. sub mybestlink ($$) { #{{{
  268. my $page=shift;
  269. my $link=shift;
  270. my $res=$origsubs{'bestlink'}->($page, $link);
  271. if (length $res) {
  272. if ($config{po_link_to} eq "current"
  273. && istranslatable($res)
  274. && istranslation($page)) {
  275. my ($masterpage, $curlang) = ($page =~ /(.*)[.]([a-z]{2})$/);
  276. return $res . "." . $curlang;
  277. }
  278. else {
  279. return $res;
  280. }
  281. }
  282. return "";
  283. } #}}}
  284. # We use filter to convert PO to the master page's format,
  285. # since the rest of ikiwiki should not work on PO files.
  286. sub filter (@) { #{{{
  287. my %params = @_;
  288. my $page = $params{page};
  289. my $destpage = $params{destpage};
  290. my $content = decode_utf8(encode_utf8($params{content}));
  291. return $content if ( ! istranslation($page)
  292. || ( exists $filtered{$page}{$destpage}
  293. && $filtered{$page}{$destpage} eq 1 ));
  294. # CRLF line terminators make poor Locale::Po4a feel bad
  295. $content=~s/\r\n/\n/g;
  296. # Implementation notes
  297. #
  298. # 1. Locale::Po4a reads/writes from/to files, and I'm too lazy
  299. # to learn how to disguise a variable as a file.
  300. # 2. There are incompatibilities between some File::Temp versions
  301. # (including 0.18, bundled with Lenny's perl-modules package)
  302. # and others (e.g. 0.20, previously present in the archive as
  303. # a standalone package): under certain circumstances, some
  304. # return a relative filename, whereas others return an absolute one;
  305. # we here use this module in a way that is at least compatible
  306. # with 0.18 and 0.20. Beware, hit'n'run refactorers!
  307. my $infile = new File::Temp(TEMPLATE => "ikiwiki-po-filter-in.XXXXXXXXXX",
  308. DIR => File::Spec->tmpdir,
  309. UNLINK => 1)->filename;
  310. my $outfile = new File::Temp(TEMPLATE => "ikiwiki-po-filter-out.XXXXXXXXXX",
  311. DIR => File::Spec->tmpdir,
  312. UNLINK => 1)->filename;
  313. writefile(basename($infile), File::Spec->tmpdir, $content);
  314. my ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
  315. my $masterfile = srcfile($pagesources{$masterpage});
  316. my (@pos,@masters);
  317. push @pos,$infile;
  318. push @masters,$masterfile;
  319. my %options = (
  320. "markdown" => (pagetype($masterfile) eq 'mdwn') ? 1 : 0,
  321. );
  322. my $doc=Locale::Po4a::Chooser::new('text',%options);
  323. $doc->process(
  324. 'po_in_name' => \@pos,
  325. 'file_in_name' => \@masters,
  326. 'file_in_charset' => 'utf-8',
  327. 'file_out_charset' => 'utf-8',
  328. ) or error("[po/filter:$infile]: failed to translate");
  329. $doc->write($outfile) or error("[po/filter:$infile] could not write $outfile");
  330. $content = readfile($outfile) or error("[po/filter:$infile] could not read $outfile");
  331. # Unlinking should happen automatically, thanks to File::Temp,
  332. # but it does not work here, probably because of the way writefile()
  333. # and Locale::Po4a::write() work.
  334. unlink $infile, $outfile;
  335. $filtered{$page}{$destpage}=1;
  336. return $content;
  337. } #}}}
  338. sub htmlize (@) { #{{{
  339. my %params=@_;
  340. my $page = $params{page};
  341. my $content = $params{content};
  342. my ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
  343. my $masterfile = srcfile($pagesources{$masterpage});
  344. # force content to be htmlize'd as if it was the same type as the master page
  345. return IkiWiki::htmlize($page, $page, pagetype($masterfile), $content);
  346. } #}}}
  347. sub percenttranslated ($) { #{{{
  348. my $page=shift;
  349. return gettext("N/A") unless (istranslation($page));
  350. my ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
  351. my $file=srcfile($pagesources{$page});
  352. my $masterfile = srcfile($pagesources{$masterpage});
  353. my (@pos,@masters);
  354. push @pos,$file;
  355. push @masters,$masterfile;
  356. my %options = (
  357. "markdown" => (pagetype($masterfile) eq 'mdwn') ? 1 : 0,
  358. );
  359. my $doc=Locale::Po4a::Chooser::new('text',%options);
  360. $doc->process(
  361. 'po_in_name' => \@pos,
  362. 'file_in_name' => \@masters,
  363. 'file_in_charset' => 'utf-8',
  364. 'file_out_charset' => 'utf-8',
  365. ) or error("[po/percenttranslated:$file]: failed to translate");
  366. my ($percent,$hit,$queries) = $doc->stats();
  367. return $percent;
  368. } #}}}
  369. sub otherlanguages ($) { #{{{
  370. my $page=shift;
  371. my @ret;
  372. if (istranslatable($page)) {
  373. foreach my $lang (sort keys %{$translations{$page}}) {
  374. my $translation = $translations{$page}{$lang};
  375. push @ret, {
  376. url => urlto($translation, $page),
  377. code => $lang,
  378. language => $config{po_slave_languages}{$lang},
  379. percent => percenttranslated($translation),
  380. };
  381. }
  382. }
  383. elsif (istranslation($page)) {
  384. my ($masterpage, $curlang) = ($page =~ /(.*)[.]([a-z]{2})$/);
  385. push @ret, {
  386. url => urlto_with_orig_beautiful_urlpath($masterpage, $page),
  387. code => $config{po_master_language}{code},
  388. language => $config{po_master_language}{name},
  389. master => 1,
  390. };
  391. foreach my $lang (sort keys %{$translations{$masterpage}}) {
  392. push @ret, {
  393. url => urlto($translations{$masterpage}{$lang}, $page),
  394. code => $lang,
  395. language => $config{po_slave_languages}{$lang},
  396. percent => percenttranslated($translations{$masterpage}{$lang}),
  397. } unless ($lang eq $curlang);
  398. }
  399. }
  400. return @ret;
  401. } #}}}
  402. sub pagetemplate (@) { #{{{
  403. my %params=@_;
  404. my $page=$params{page};
  405. my $destpage=$params{destpage};
  406. my $template=$params{template};
  407. my ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/) if istranslation($page);
  408. if (istranslation($page) && $template->query(name => "percenttranslated")) {
  409. $template->param(percenttranslated => percenttranslated($page));
  410. }
  411. if ($template->query(name => "istranslation")) {
  412. $template->param(istranslation => istranslation($page));
  413. }
  414. if ($template->query(name => "istranslatable")) {
  415. $template->param(istranslatable => istranslatable($page));
  416. }
  417. if ($template->query(name => "otherlanguages")) {
  418. $template->param(otherlanguages => [otherlanguages($page)]);
  419. if (istranslatable($page)) {
  420. foreach my $translation (values %{$translations{$page}}) {
  421. add_depends($page, $translation);
  422. }
  423. }
  424. elsif (istranslation($page)) {
  425. add_depends($page, $masterpage);
  426. foreach my $translation (values %{$translations{$masterpage}}) {
  427. add_depends($page, $translation);
  428. }
  429. }
  430. }
  431. # Rely on IkiWiki::Render's genpage() to decide wether
  432. # a discussion link should appear on $page; this is not
  433. # totally accurate, though: some broken links may be generated
  434. # when cgiurl is disabled.
  435. # This compromise avoids some code duplication, and will probably
  436. # prevent future breakage when ikiwiki internals change.
  437. # Known limitations are preferred to future random bugs.
  438. if ($template->param('discussionlink') && istranslation($page)) {
  439. $template->param('discussionlink' => htmllink(
  440. $page,
  441. $destpage,
  442. $masterpage . '/' . gettext("Discussion"),
  443. noimageinline => 1,
  444. forcesubpage => 0,
  445. linktext => gettext("Discussion"),
  446. ));
  447. }
  448. # remove broken parentlink to ./index.html on home page's translations
  449. if ($template->param('parentlinks')
  450. && istranslation($page)
  451. && $masterpage eq "index") {
  452. $template->param('parentlinks' => []);
  453. }
  454. } # }}}
  455. sub editcontent () { #{{{
  456. my %params=@_;
  457. # as we're previewing or saving a page, the content may have
  458. # changed, so tell the next filter() invocation it must not be lazy
  459. if (exists $filtered{$params{page}}{$params{page}}) {
  460. delete $filtered{$params{page}}{$params{page}};
  461. }
  462. return $params{content};
  463. } #}}}
  464. sub istranslatable ($) { #{{{
  465. my $page=shift;
  466. my $file=$pagesources{$page};
  467. if (! defined $file
  468. || (defined pagetype($file) && pagetype($file) eq 'po')
  469. || $file =~ /\.pot$/) {
  470. return 0;
  471. }
  472. return pagespec_match($page, $config{po_translatable_pages});
  473. } #}}}
  474. sub _istranslation ($) { #{{{
  475. my $page=shift;
  476. my $file=$pagesources{$page};
  477. if (! defined $file) {
  478. return IkiWiki::FailReason->new("no file specified");
  479. }
  480. if (! defined $file
  481. || ! defined pagetype($file)
  482. || ! pagetype($file) eq 'po'
  483. || $file =~ /\.pot$/) {
  484. return 0;
  485. }
  486. my ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
  487. if (! defined $masterpage || ! defined $lang
  488. || ! (length($masterpage) > 0) || ! (length($lang) > 0)
  489. || ! defined $pagesources{$masterpage}
  490. || ! defined $config{po_slave_languages}{$lang}) {
  491. return 0;
  492. }
  493. return istranslatable($masterpage);
  494. } #}}}
  495. sub istranslation ($) { #{{{
  496. my $page=shift;
  497. if (_istranslation($page)) {
  498. my ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
  499. $translations{$masterpage}{$lang}=$page unless exists $translations{$masterpage}{$lang};
  500. return 1;
  501. }
  502. return 0;
  503. } #}}}
  504. package IkiWiki::PageSpec;
  505. use warnings;
  506. use strict;
  507. use IkiWiki 2.00;
  508. sub match_istranslation ($;@) { #{{{
  509. my $page=shift;
  510. if (IkiWiki::Plugin::po::istranslation($page)) {
  511. return IkiWiki::SuccessReason->new("is a translation page");
  512. }
  513. else {
  514. return IkiWiki::FailReason->new("is not a translation page");
  515. }
  516. } #}}}
  517. sub match_istranslatable ($;@) { #{{{
  518. my $page=shift;
  519. if (IkiWiki::Plugin::po::istranslatable($page)) {
  520. return IkiWiki::SuccessReason->new("is set as translatable in po_translatable_pages");
  521. }
  522. else {
  523. return IkiWiki::FailReason->new("is not set as translatable in po_translatable_pages");
  524. }
  525. } #}}}
  526. sub match_lang ($$;@) { #{{{
  527. my $page=shift;
  528. my $wanted=shift;
  529. my $regexp=IkiWiki::glob2re($wanted);
  530. my $lang;
  531. my $masterpage;
  532. if (IkiWiki::Plugin::po::istranslation($page)) {
  533. ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
  534. }
  535. else {
  536. $lang = $config{po_master_language}{code};
  537. }
  538. if ($lang!~/^$regexp$/i) {
  539. return IkiWiki::FailReason->new("file language is $lang, not $wanted");
  540. }
  541. else {
  542. return IkiWiki::SuccessReason->new("file language is $wanted");
  543. }
  544. } #}}}
  545. sub match_currentlang ($$;@) { #{{{
  546. my $page=shift;
  547. shift;
  548. my %params=@_;
  549. my ($currentmasterpage, $currentlang, $masterpage, $lang);
  550. return IkiWiki::FailReason->new("no location provided") unless exists $params{location};
  551. if (IkiWiki::Plugin::po::istranslation($params{location})) {
  552. ($currentmasterpage, $currentlang) = ($params{location} =~ /(.*)[.]([a-z]{2})$/);
  553. }
  554. else {
  555. $currentlang = $config{po_master_language}{code};
  556. }
  557. if (IkiWiki::Plugin::po::istranslation($page)) {
  558. ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
  559. }
  560. else {
  561. $lang = $config{po_master_language}{code};
  562. }
  563. if ($lang eq $currentlang) {
  564. return IkiWiki::SuccessReason->new("file language is the same as current one, i.e. $currentlang");
  565. }
  566. else {
  567. return IkiWiki::FailReason->new("file language is $lang, whereas current language is $currentlang");
  568. }
  569. } #}}}
  570. 1