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