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