summaryrefslogtreecommitdiff
path: root/IkiWiki/Plugin/po.pm
blob: 2dad3b60b898c5e1a3a8b3fb838413fda21b2dfa (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. use UNIVERSAL;
  20. my %translations;
  21. my @origneedsbuild;
  22. my %origsubs;
  23. memoize("istranslatable");
  24. memoize("_istranslation");
  25. memoize("percenttranslated");
  26. sub import {
  27. hook(type => "getsetup", id => "po", call => \&getsetup);
  28. hook(type => "checkconfig", id => "po", call => \&checkconfig);
  29. hook(type => "needsbuild", id => "po", call => \&needsbuild);
  30. hook(type => "scan", id => "po", call => \&scan, last =>1);
  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 => "postscan", id => "po", call => \&postscan);
  35. hook(type => "rename", id => "po", call => \&renamepages);
  36. hook(type => "delete", id => "po", call => \&mydelete);
  37. hook(type => "change", id => "po", call => \&change);
  38. hook(type => "canremove", id => "po", call => \&canremove);
  39. hook(type => "canrename", id => "po", call => \&canrename);
  40. hook(type => "editcontent", id => "po", call => \&editcontent);
  41. $origsubs{'bestlink'}=\&IkiWiki::bestlink;
  42. inject(name => "IkiWiki::bestlink", call => \&mybestlink);
  43. $origsubs{'beautify_urlpath'}=\&IkiWiki::beautify_urlpath;
  44. inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath);
  45. $origsubs{'targetpage'}=\&IkiWiki::targetpage;
  46. inject(name => "IkiWiki::targetpage", call => \&mytargetpage);
  47. $origsubs{'urlto'}=\&IkiWiki::urlto;
  48. inject(name => "IkiWiki::urlto", call => \&myurlto);
  49. $origsubs{'nicepagetitle'}=\&IkiWiki::nicepagetitle;
  50. inject(name => "IkiWiki::nicepagetitle", call => \&mynicepagetitle);
  51. }
  52. # ,----
  53. # | Table of contents
  54. # `----
  55. # 1. Hooks
  56. # 2. Injected functions
  57. # 3. Blackboxes for private data
  58. # 4. Helper functions
  59. # 5. PageSpec's
  60. # ,----
  61. # | Hooks
  62. # `----
  63. sub getsetup () {
  64. return
  65. plugin => {
  66. safe => 0,
  67. rebuild => 1,
  68. },
  69. po_master_language => {
  70. type => "string",
  71. example => {
  72. 'code' => 'en',
  73. 'name' => 'English'
  74. },
  75. description => "master language (non-PO files)",
  76. safe => 1,
  77. rebuild => 1,
  78. },
  79. po_slave_languages => {
  80. type => "string",
  81. example => {
  82. 'fr' => 'Français',
  83. 'es' => 'Castellano',
  84. 'de' => 'Deutsch'
  85. },
  86. description => "slave languages (PO files)",
  87. safe => 1,
  88. rebuild => 1,
  89. },
  90. po_translatable_pages => {
  91. type => "pagespec",
  92. example => "!*/Discussion",
  93. description => "PageSpec controlling which pages are translatable",
  94. link => "ikiwiki/PageSpec",
  95. safe => 1,
  96. rebuild => 1,
  97. },
  98. po_link_to => {
  99. type => "string",
  100. example => "current",
  101. description => "internal linking behavior (default/current/negotiated)",
  102. safe => 1,
  103. rebuild => 1,
  104. },
  105. po_translation_status_in_links => {
  106. type => "boolean",
  107. example => 1,
  108. description => "display translation status in links to translations",
  109. safe => 1,
  110. rebuild => 1,
  111. },
  112. }
  113. sub checkconfig () {
  114. foreach my $field (qw{po_master_language po_slave_languages}) {
  115. if (! exists $config{$field} || ! defined $config{$field}) {
  116. error(sprintf(gettext("Must specify %s"), $field));
  117. }
  118. }
  119. if (! (keys %{$config{po_slave_languages}})) {
  120. error(gettext("At least one slave language must be defined in po_slave_languages"));
  121. }
  122. map {
  123. islanguagecode($_)
  124. or error(sprintf(gettext("%s is not a valid language code"), $_));
  125. } ($config{po_master_language}{code}, keys %{$config{po_slave_languages}});
  126. if (! exists $config{po_translatable_pages} ||
  127. ! defined $config{po_translatable_pages}) {
  128. $config{po_translatable_pages}="";
  129. }
  130. if (! exists $config{po_link_to} ||
  131. ! defined $config{po_link_to}) {
  132. $config{po_link_to}='default';
  133. }
  134. elsif (! grep {
  135. $config{po_link_to} eq $_
  136. } ('default', 'current', 'negotiated')) {
  137. warn(sprintf(gettext('po_link_to=%s is not a valid setting, falling back to po_link_to=default'),
  138. $config{po_link_to}));
  139. $config{po_link_to}='default';
  140. }
  141. elsif ($config{po_link_to} eq "negotiated" && ! $config{usedirs}) {
  142. warn(gettext('po_link_to=negotiated requires usedirs to be enabled, falling back to po_link_to=default'));
  143. $config{po_link_to}='default';
  144. }
  145. if (! exists $config{po_translation_status_in_links} ||
  146. ! defined $config{po_translation_status_in_links}) {
  147. $config{po_translation_status_in_links}=1;
  148. }
  149. push @{$config{wiki_file_prune_regexps}}, qr/\.pot$/;
  150. }
  151. sub needsbuild () {
  152. my $needsbuild=shift;
  153. # backup @needsbuild content so that change() can know whether
  154. # a given master page was rendered because its source file was changed
  155. @origneedsbuild=(@$needsbuild);
  156. flushmemoizecache();
  157. buildtranslationscache();
  158. # make existing translations depend on the corresponding master page
  159. foreach my $master (keys %translations) {
  160. map add_depends($_, $master), values %{otherlanguages($master)};
  161. }
  162. }
  163. # Massage the recorded state of internal links so that:
  164. # - it matches the actually generated links, rather than the links as written
  165. # in the pages' source
  166. # - backlinks are consistent in all cases
  167. sub scan (@) {
  168. my %params=@_;
  169. my $page=$params{page};
  170. my $content=$params{content};
  171. return unless UNIVERSAL::can("IkiWiki::Plugin::link", "import");
  172. if (istranslation($page)) {
  173. foreach my $destpage (@{$links{$page}}) {
  174. if (istranslatable($destpage)) {
  175. # replace one occurence of $destpage in $links{$page}
  176. # (we only want to replace the one that was added by
  177. # IkiWiki::Plugin::link::scan, other occurences may be
  178. # there for other reasons)
  179. for (my $i=0; $i<@{$links{$page}}; $i++) {
  180. if (@{$links{$page}}[$i] eq $destpage) {
  181. @{$links{$page}}[$i] = $destpage . '.' . lang($page);
  182. last;
  183. }
  184. }
  185. }
  186. }
  187. }
  188. elsif (! istranslatable($page) && ! istranslation($page)) {
  189. foreach my $destpage (@{$links{$page}}) {
  190. if (istranslatable($destpage)) {
  191. # make sure any destpage's translations has
  192. # $page in its backlinks
  193. push @{$links{$page}},
  194. values %{otherlanguages($destpage)};
  195. }
  196. }
  197. }
  198. }
  199. # We use filter to convert PO to the master page's format,
  200. # since the rest of ikiwiki should not work on PO files.
  201. sub filter (@) {
  202. my %params = @_;
  203. my $page = $params{page};
  204. my $destpage = $params{destpage};
  205. my $content = decode_utf8(encode_utf8($params{content}));
  206. return $content if ( ! istranslation($page)
  207. || alreadyfiltered($page, $destpage) );
  208. # CRLF line terminators make poor Locale::Po4a feel bad
  209. $content=~s/\r\n/\n/g;
  210. # There are incompatibilities between some File::Temp versions
  211. # (including 0.18, bundled with Lenny's perl-modules package)
  212. # and others (e.g. 0.20, previously present in the archive as
  213. # a standalone package): under certain circumstances, some
  214. # return a relative filename, whereas others return an absolute one;
  215. # we here use this module in a way that is at least compatible
  216. # with 0.18 and 0.20. Beware, hit'n'run refactorers!
  217. my $infile = new File::Temp(TEMPLATE => "ikiwiki-po-filter-in.XXXXXXXXXX",
  218. DIR => File::Spec->tmpdir,
  219. UNLINK => 1)->filename;
  220. my $outfile = new File::Temp(TEMPLATE => "ikiwiki-po-filter-out.XXXXXXXXXX",
  221. DIR => File::Spec->tmpdir,
  222. UNLINK => 1)->filename;
  223. writefile(basename($infile), File::Spec->tmpdir, $content);
  224. my $masterfile = srcfile($pagesources{masterpage($page)});
  225. my %options = (
  226. "markdown" => (pagetype($masterfile) eq 'mdwn') ? 1 : 0,
  227. );
  228. my $doc=Locale::Po4a::Chooser::new('text',%options);
  229. $doc->process(
  230. 'po_in_name' => [ $infile ],
  231. 'file_in_name' => [ $masterfile ],
  232. 'file_in_charset' => 'utf-8',
  233. 'file_out_charset' => 'utf-8',
  234. ) or error("[po/filter:$page]: failed to translate");
  235. $doc->write($outfile) or error("[po/filter:$page] could not write $outfile");
  236. $content = readfile($outfile) or error("[po/filter:$page] could not read $outfile");
  237. # Unlinking should happen automatically, thanks to File::Temp,
  238. # but it does not work here, probably because of the way writefile()
  239. # and Locale::Po4a::write() work.
  240. unlink $infile, $outfile;
  241. setalreadyfiltered($page, $destpage);
  242. return $content;
  243. }
  244. sub htmlize (@) {
  245. my %params=@_;
  246. my $page = $params{page};
  247. my $content = $params{content};
  248. # ignore PO files this plugin did not create
  249. return $content unless istranslation($page);
  250. # force content to be htmlize'd as if it was the same type as the master page
  251. return IkiWiki::htmlize($page, $page,
  252. pagetype(srcfile($pagesources{masterpage($page)})),
  253. $content);
  254. }
  255. sub pagetemplate (@) {
  256. my %params=@_;
  257. my $page=$params{page};
  258. my $destpage=$params{destpage};
  259. my $template=$params{template};
  260. my ($masterpage, $lang) = istranslation($page);
  261. if (istranslation($page) && $template->query(name => "percenttranslated")) {
  262. $template->param(percenttranslated => percenttranslated($page));
  263. }
  264. if ($template->query(name => "istranslation")) {
  265. $template->param(istranslation => scalar istranslation($page));
  266. }
  267. if ($template->query(name => "istranslatable")) {
  268. $template->param(istranslatable => istranslatable($page));
  269. }
  270. if ($template->query(name => "HOMEPAGEURL")) {
  271. $template->param(homepageurl => homepageurl($page));
  272. }
  273. if ($template->query(name => "otherlanguages")) {
  274. $template->param(otherlanguages => [otherlanguagesloop($page)]);
  275. map add_depends($page, $_), (values %{otherlanguages($page)});
  276. }
  277. # Rely on IkiWiki::Render's genpage() to decide wether
  278. # a discussion link should appear on $page; this is not
  279. # totally accurate, though: some broken links may be generated
  280. # when cgiurl is disabled.
  281. # This compromise avoids some code duplication, and will probably
  282. # prevent future breakage when ikiwiki internals change.
  283. # Known limitations are preferred to future random bugs.
  284. if ($template->param('discussionlink') && istranslation($page)) {
  285. $template->param('discussionlink' => htmllink(
  286. $page,
  287. $destpage,
  288. $masterpage . '/' . gettext("Discussion"),
  289. noimageinline => 1,
  290. forcesubpage => 0,
  291. linktext => gettext("Discussion"),
  292. ));
  293. }
  294. # Remove broken parentlink to ./index.html on home page's translations.
  295. # It works because this hook has the "last" parameter set, to ensure it
  296. # runs after parentlinks' own pagetemplate hook.
  297. if ($template->param('parentlinks')
  298. && istranslation($page)
  299. && $masterpage eq "index") {
  300. $template->param('parentlinks' => []);
  301. }
  302. } # }}}
  303. sub postscan (@) {
  304. my %params = @_;
  305. my $page = $params{page};
  306. # backlinks involve back-dependencies, so that nicepagetitle effects,
  307. # such as translation status displayed in links, are updated
  308. use IkiWiki::Render;
  309. map add_depends($page, $_), keys %{$IkiWiki::backlinks{$page}};
  310. }
  311. # Add the renamed page translations to the list of to-be-renamed pages.
  312. sub renamepages() {
  313. my $torename=shift;
  314. my @torename=@{$torename};
  315. foreach my $rename (@torename) {
  316. next unless istranslatable($rename->{src});
  317. my %otherpages=%{otherlanguages($rename->{src})};
  318. while (my ($lang, $otherpage) = each %otherpages) {
  319. push @{$torename}, {
  320. src => $otherpage,
  321. srcfile => $pagesources{$otherpage},
  322. dest => otherlanguage($rename->{dest}, $lang),
  323. destfile => $rename->{dest}.".".$lang.".po",
  324. required => 0,
  325. };
  326. }
  327. }
  328. }
  329. sub mydelete(@) {
  330. my @deleted=@_;
  331. map { deletetranslations($_) } grep istranslatablefile($_), @deleted;
  332. }
  333. sub change(@) {
  334. my @rendered=@_;
  335. my $updated_po_files=0;
  336. # Refresh/create POT and PO files as needed.
  337. foreach my $file (grep {istranslatablefile($_)} @rendered) {
  338. my $page=pagename($file);
  339. my $masterfile=srcfile($file);
  340. my $updated_pot_file=0;
  341. # Only refresh Pot file if it does not exist, or if
  342. # $pagesources{$page} was changed: don't if only the HTML was
  343. # refreshed, e.g. because of a dependency.
  344. if ((grep { $_ eq $pagesources{$page} } @origneedsbuild)
  345. || ! -e potfile($masterfile)) {
  346. refreshpot($masterfile);
  347. $updated_pot_file=1;
  348. }
  349. my @pofiles;
  350. map {
  351. push @pofiles, $_ if ($updated_pot_file || ! -e $_);
  352. } (pofiles($masterfile));
  353. if (@pofiles) {
  354. refreshpofiles($masterfile, @pofiles);
  355. map { IkiWiki::rcs_add($_) } @pofiles if $config{rcs};
  356. $updated_po_files=1;
  357. }
  358. }
  359. if ($updated_po_files) {
  360. commit_and_refresh(
  361. gettext("updated PO files"),
  362. "IkiWiki::Plugin::po::change");
  363. }
  364. }
  365. sub canremove ($$$) {
  366. my ($page, $cgi, $session) = (shift, shift, shift);
  367. if (istranslation($page)) {
  368. return gettext("Can not remove a translation. Removing the master page,".
  369. "though, removes its translations as well.");
  370. }
  371. return undef;
  372. }
  373. sub canrename ($$$) {
  374. my ($page, $cgi, $session) = (shift, shift, shift);
  375. if (istranslation($page)) {
  376. return gettext("Can not rename a translation. Renaming the master page,".
  377. "though, renames its translations as well.");
  378. }
  379. return undef;
  380. }
  381. # As we're previewing or saving a page, the content may have
  382. # changed, so tell the next filter() invocation it must not be lazy.
  383. sub editcontent () {
  384. my %params=@_;
  385. unsetalreadyfiltered($params{page}, $params{page});
  386. return $params{content};
  387. }
  388. # ,----
  389. # | Injected functions
  390. # `----
  391. # Implement po_link_to 'current' and 'negotiated' settings.
  392. sub mybestlink ($$) {
  393. my $page=shift;
  394. my $link=shift;
  395. my $res=$origsubs{'bestlink'}->(masterpage($page), $link);
  396. if (length $res
  397. && ($config{po_link_to} eq "current" || $config{po_link_to} eq "negotiated")
  398. && istranslatable($res)
  399. && istranslation($page)) {
  400. return $res . "." . lang($page);
  401. }
  402. return $res;
  403. }
  404. sub mybeautify_urlpath ($) {
  405. my $url=shift;
  406. my $res=$origsubs{'beautify_urlpath'}->($url);
  407. if ($config{po_link_to} eq "negotiated") {
  408. $res =~ s!/\Qindex.$config{po_master_language}{code}.$config{htmlext}\E$!/!;
  409. $res =~ s!/\Qindex.$config{htmlext}\E$!/!;
  410. map {
  411. $res =~ s!/\Qindex.$_.$config{htmlext}\E$!/!;
  412. } (keys %{$config{po_slave_languages}});
  413. }
  414. return $res;
  415. }
  416. sub mytargetpage ($$) {
  417. my $page=shift;
  418. my $ext=shift;
  419. if (istranslation($page) || istranslatable($page)) {
  420. my ($masterpage, $lang) = (masterpage($page), lang($page));
  421. if (! $config{usedirs} || $masterpage eq 'index') {
  422. return $masterpage . "." . $lang . "." . $ext;
  423. }
  424. else {
  425. return $masterpage . "/index." . $lang . "." . $ext;
  426. }
  427. }
  428. return $origsubs{'targetpage'}->($page, $ext);
  429. }
  430. sub myurlto ($$;$) {
  431. my $to=shift;
  432. my $from=shift;
  433. my $absolute=shift;
  434. # workaround hard-coded /index.$config{htmlext} in IkiWiki::urlto()
  435. if (! length $to
  436. && $config{po_link_to} eq "current"
  437. && istranslatable('index')) {
  438. return IkiWiki::beautify_urlpath(IkiWiki::baseurl($from) . "index." . lang($from) . ".$config{htmlext}");
  439. }
  440. # avoid using our injected beautify_urlpath if run by cgi_editpage,
  441. # so that one is redirected to the just-edited page rather than to the
  442. # negociated translation; to prevent unnecessary fiddling with caller/inject,
  443. # we only do so when our beautify_urlpath would actually do what we want to
  444. # avoid, i.e. when po_link_to = negotiated
  445. if ($config{po_link_to} eq "negotiated") {
  446. my @caller = caller(1);
  447. my $run_by_editpage = 0;
  448. $run_by_editpage = 1 if (exists $caller[3] && defined $caller[3]
  449. && $caller[3] eq "IkiWiki::cgi_editpage");
  450. inject(name => "IkiWiki::beautify_urlpath", call => $origsubs{'beautify_urlpath'})
  451. if $run_by_editpage;
  452. my $res = $origsubs{'urlto'}->($to,$from,$absolute);
  453. inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath)
  454. if $run_by_editpage;
  455. return $res;
  456. }
  457. else {
  458. return $origsubs{'urlto'}->($to,$from,$absolute)
  459. }
  460. }
  461. sub mynicepagetitle ($;$) {
  462. my ($page, $unescaped) = (shift, shift);
  463. my $res = $origsubs{'nicepagetitle'}->($page, $unescaped);
  464. return $res unless istranslation($page);
  465. return $res unless $config{po_translation_status_in_links};
  466. return $res.' ('.percenttranslated($page).' %)';
  467. }
  468. # ,----
  469. # | Blackboxes for private data
  470. # `----
  471. {
  472. my %filtered;
  473. sub alreadyfiltered($$) {
  474. my $page=shift;
  475. my $destpage=shift;
  476. return ( exists $filtered{$page}{$destpage}
  477. && $filtered{$page}{$destpage} eq 1 );
  478. }
  479. sub setalreadyfiltered($$) {
  480. my $page=shift;
  481. my $destpage=shift;
  482. $filtered{$page}{$destpage}=1;
  483. }
  484. sub unsetalreadyfiltered($$) {
  485. my $page=shift;
  486. my $destpage=shift;
  487. if (exists $filtered{$page}{$destpage}) {
  488. delete $filtered{$page}{$destpage};
  489. }
  490. }
  491. sub resetalreadyfiltered() {
  492. undef %filtered;
  493. }
  494. }
  495. # ,----
  496. # | Helper functions
  497. # `----
  498. sub maybe_add_leading_slash ($;$) {
  499. my $str=shift;
  500. my $add=shift;
  501. $add=1 unless defined $add;
  502. return '/' . $str if $add;
  503. return $str;
  504. }
  505. sub istranslatablefile ($) {
  506. my $file=shift;
  507. return 0 unless defined $file;
  508. return 0 if (defined pagetype($file) && pagetype($file) eq 'po');
  509. return 0 if $file =~ /\.pot$/;
  510. return 1 if pagespec_match(pagename($file), $config{po_translatable_pages});
  511. return;
  512. }
  513. sub istranslatable ($) {
  514. my $page=shift;
  515. $page=~s#^/##;
  516. return 1 if istranslatablefile($pagesources{$page});
  517. return;
  518. }
  519. sub _istranslation ($) {
  520. my $page=shift;
  521. my $hasleadingslash = ($page=~s#^/##);
  522. my $file=$pagesources{$page};
  523. return 0 unless (defined $file
  524. && defined pagetype($file)
  525. && pagetype($file) eq 'po');
  526. return 0 if $file =~ /\.pot$/;
  527. my ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
  528. return 0 unless (defined $masterpage && defined $lang
  529. && length $masterpage && length $lang
  530. && defined $pagesources{$masterpage}
  531. && defined $config{po_slave_languages}{$lang});
  532. return (maybe_add_leading_slash($masterpage, $hasleadingslash), $lang)
  533. if istranslatable($masterpage);
  534. }
  535. sub istranslation ($) {
  536. my $page=shift;
  537. if (1 < (my ($masterpage, $lang) = _istranslation($page))) {
  538. my $hasleadingslash = ($masterpage=~s#^/##);
  539. $translations{$masterpage}{$lang}=$page unless exists $translations{$masterpage}{$lang};
  540. return (maybe_add_leading_slash($masterpage, $hasleadingslash), $lang);
  541. }
  542. return;
  543. }
  544. sub masterpage ($) {
  545. my $page=shift;
  546. if ( 1 < (my ($masterpage, $lang) = _istranslation($page))) {
  547. return $masterpage;
  548. }
  549. return $page;
  550. }
  551. sub lang ($) {
  552. my $page=shift;
  553. if (1 < (my ($masterpage, $lang) = _istranslation($page))) {
  554. return $lang;
  555. }
  556. return $config{po_master_language}{code};
  557. }
  558. sub islanguagecode ($) {
  559. my $code=shift;
  560. return ($code =~ /^[a-z]{2}$/);
  561. }
  562. sub otherlanguage ($$) {
  563. my $page=shift;
  564. my $code=shift;
  565. return masterpage($page) if $code eq $config{po_master_language}{code};
  566. return masterpage($page) . '.' . $code;
  567. }
  568. sub otherlanguages ($) {
  569. my $page=shift;
  570. my %ret;
  571. return \%ret unless (istranslation($page) || istranslatable($page));
  572. my $curlang=lang($page);
  573. foreach my $lang
  574. ($config{po_master_language}{code}, keys %{$config{po_slave_languages}}) {
  575. next if $lang eq $curlang;
  576. $ret{$lang}=otherlanguage($page, $lang);
  577. }
  578. return \%ret;
  579. }
  580. sub potfile ($) {
  581. my $masterfile=shift;
  582. (my $name, my $dir, my $suffix) = fileparse($masterfile, qr/\.[^.]*/);
  583. $dir='' if $dir eq './';
  584. return File::Spec->catpath('', $dir, $name . ".pot");
  585. }
  586. sub pofile ($$) {
  587. my $masterfile=shift;
  588. my $lang=shift;
  589. (my $name, my $dir, my $suffix) = fileparse($masterfile, qr/\.[^.]*/);
  590. $dir='' if $dir eq './';
  591. return File::Spec->catpath('', $dir, $name . "." . $lang . ".po");
  592. }
  593. sub pofiles ($) {
  594. my $masterfile=shift;
  595. return map pofile($masterfile, $_), (keys %{$config{po_slave_languages}});
  596. }
  597. sub refreshpot ($) {
  598. my $masterfile=shift;
  599. my $potfile=potfile($masterfile);
  600. my %options = ("markdown" => (pagetype($masterfile) eq 'mdwn') ? 1 : 0);
  601. my $doc=Locale::Po4a::Chooser::new('text',%options);
  602. $doc->{TT}{utf_mode} = 1;
  603. $doc->{TT}{file_in_charset} = 'utf-8';
  604. $doc->{TT}{file_out_charset} = 'utf-8';
  605. $doc->read($masterfile);
  606. # let's cheat a bit to force porefs option to be passed to Locale::Po4a::Po;
  607. # this is undocument use of internal Locale::Po4a::TransTractor's data,
  608. # compulsory since this module prevents us from using the porefs option.
  609. $doc->{TT}{po_out}=Locale::Po4a::Po->new({ 'porefs' => 'none' });
  610. $doc->{TT}{po_out}->set_charset('utf-8');
  611. # do the actual work
  612. $doc->parse;
  613. IkiWiki::prep_writefile(basename($potfile),dirname($potfile));
  614. $doc->writepo($potfile);
  615. }
  616. sub refreshpofiles ($@) {
  617. my $masterfile=shift;
  618. my @pofiles=@_;
  619. my $potfile=potfile($masterfile);
  620. error("[po/refreshpofiles] POT file ($potfile) does not exist") unless (-e $potfile);
  621. foreach my $pofile (@pofiles) {
  622. IkiWiki::prep_writefile(basename($pofile),dirname($pofile));
  623. if (-e $pofile) {
  624. system("msgmerge", "-U", "--backup=none", $pofile, $potfile) == 0
  625. or error("[po/refreshpofiles:$pofile] failed to update");
  626. }
  627. else {
  628. File::Copy::syscopy($potfile,$pofile)
  629. or error("[po/refreshpofiles:$pofile] failed to copy the POT file");
  630. }
  631. }
  632. }
  633. sub buildtranslationscache() {
  634. # use istranslation's side-effect
  635. map istranslation($_), (keys %pagesources);
  636. }
  637. sub resettranslationscache() {
  638. undef %translations;
  639. }
  640. sub flushmemoizecache() {
  641. Memoize::flush_cache("istranslatable");
  642. Memoize::flush_cache("_istranslation");
  643. Memoize::flush_cache("percenttranslated");
  644. }
  645. sub urlto_with_orig_beautiful_urlpath($$) {
  646. my $to=shift;
  647. my $from=shift;
  648. inject(name => "IkiWiki::beautify_urlpath", call => $origsubs{'beautify_urlpath'});
  649. my $res=urlto($to, $from);
  650. inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath);
  651. return $res;
  652. }
  653. sub percenttranslated ($) {
  654. my $page=shift;
  655. $page=~s/^\///;
  656. return gettext("N/A") unless istranslation($page);
  657. my $file=srcfile($pagesources{$page});
  658. my $masterfile = srcfile($pagesources{masterpage($page)});
  659. my %options = (
  660. "markdown" => (pagetype($masterfile) eq 'mdwn') ? 1 : 0,
  661. );
  662. my $doc=Locale::Po4a::Chooser::new('text',%options);
  663. $doc->process(
  664. 'po_in_name' => [ $file ],
  665. 'file_in_name' => [ $masterfile ],
  666. 'file_in_charset' => 'utf-8',
  667. 'file_out_charset' => 'utf-8',
  668. ) or error("[po/percenttranslated:$page]: failed to translate");
  669. my ($percent,$hit,$queries) = $doc->stats();
  670. return $percent;
  671. }
  672. sub languagename ($) {
  673. my $code=shift;
  674. return $config{po_master_language}{name}
  675. if $code eq $config{po_master_language}{code};
  676. return $config{po_slave_languages}{$code}
  677. if defined $config{po_slave_languages}{$code};
  678. return;
  679. }
  680. sub otherlanguagesloop ($) {
  681. my $page=shift;
  682. my @ret;
  683. my %otherpages=%{otherlanguages($page)};
  684. while (my ($lang, $otherpage) = each %otherpages) {
  685. if (istranslation($page) && masterpage($page) eq $otherpage) {
  686. push @ret, {
  687. url => urlto_with_orig_beautiful_urlpath($otherpage, $page),
  688. code => $lang,
  689. language => languagename($lang),
  690. master => 1,
  691. };
  692. }
  693. else {
  694. push @ret, {
  695. url => urlto_with_orig_beautiful_urlpath($otherpage, $page),
  696. code => $lang,
  697. language => languagename($lang),
  698. percent => percenttranslated($otherpage),
  699. }
  700. }
  701. }
  702. return sort {
  703. return -1 if $a->{code} eq $config{po_master_language}{code};
  704. return 1 if $b->{code} eq $config{po_master_language}{code};
  705. return $a->{language} cmp $b->{language};
  706. } @ret;
  707. }
  708. sub homepageurl (;$) {
  709. my $page=shift;
  710. return urlto('', $page);
  711. }
  712. sub deletetranslations ($) {
  713. my $deletedmasterfile=shift;
  714. my $deletedmasterpage=pagename($deletedmasterfile);
  715. my @todelete;
  716. map {
  717. my $file = newpagefile($deletedmasterpage.'.'.$_, 'po');
  718. my $absfile = "$config{srcdir}/$file";
  719. if (-e $absfile && ! -l $absfile && ! -d $absfile) {
  720. push @todelete, $file;
  721. }
  722. } keys %{$config{po_slave_languages}};
  723. map {
  724. if ($config{rcs}) {
  725. IkiWiki::rcs_remove($_);
  726. }
  727. else {
  728. IkiWiki::prune("$config{srcdir}/$_");
  729. }
  730. } @todelete;
  731. if (scalar @todelete) {
  732. commit_and_refresh(
  733. gettext("removed obsolete PO files"),
  734. "IkiWiki::Plugin::po::deletetranslations");
  735. }
  736. }
  737. sub commit_and_refresh ($$) {
  738. my ($msg, $author) = (shift, shift);
  739. if ($config{rcs}) {
  740. IkiWiki::disable_commit_hook();
  741. IkiWiki::rcs_commit_staged($msg, $author, "127.0.0.1");
  742. IkiWiki::enable_commit_hook();
  743. IkiWiki::rcs_update();
  744. }
  745. # Reinitialize module's private variables.
  746. resetalreadyfiltered();
  747. resettranslationscache();
  748. flushmemoizecache();
  749. # Trigger a wiki refresh.
  750. require IkiWiki::Render;
  751. # without preliminary saveindex/loadindex, refresh()
  752. # complains about a lot of uninitialized variables
  753. IkiWiki::saveindex();
  754. IkiWiki::loadindex();
  755. IkiWiki::refresh();
  756. IkiWiki::saveindex();
  757. }
  758. # ,----
  759. # | PageSpec's
  760. # `----
  761. package IkiWiki::PageSpec;
  762. use warnings;
  763. use strict;
  764. use IkiWiki 2.00;
  765. sub match_istranslation ($;@) {
  766. my $page=shift;
  767. if (IkiWiki::Plugin::po::istranslation($page)) {
  768. return IkiWiki::SuccessReason->new("is a translation page");
  769. }
  770. else {
  771. return IkiWiki::FailReason->new("is not a translation page");
  772. }
  773. }
  774. sub match_istranslatable ($;@) {
  775. my $page=shift;
  776. if (IkiWiki::Plugin::po::istranslatable($page)) {
  777. return IkiWiki::SuccessReason->new("is set as translatable in po_translatable_pages");
  778. }
  779. else {
  780. return IkiWiki::FailReason->new("is not set as translatable in po_translatable_pages");
  781. }
  782. }
  783. sub match_lang ($$;@) {
  784. my $page=shift;
  785. my $wanted=shift;
  786. my $regexp=IkiWiki::glob2re($wanted);
  787. my $lang=IkiWiki::Plugin::po::lang($page);
  788. if ($lang!~/^$regexp$/i) {
  789. return IkiWiki::FailReason->new("file language is $lang, not $wanted");
  790. }
  791. else {
  792. return IkiWiki::SuccessReason->new("file language is $wanted");
  793. }
  794. }
  795. sub match_currentlang ($$;@) {
  796. my $page=shift;
  797. shift;
  798. my %params=@_;
  799. return IkiWiki::FailReason->new("no location provided") unless exists $params{location};
  800. my $currentlang=IkiWiki::Plugin::po::lang($params{location});
  801. my $lang=IkiWiki::Plugin::po::lang($page);
  802. if ($lang eq $currentlang) {
  803. return IkiWiki::SuccessReason->new("file language is the same as current one, i.e. $currentlang");
  804. }
  805. else {
  806. return IkiWiki::FailReason->new("file language is $lang, whereas current language is $currentlang");
  807. }
  808. }
  809. 1