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