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