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