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