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