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