summaryrefslogtreecommitdiff
path: root/IkiWiki/Plugin/po.pm
blob: 6c6bb2cd140af1d52fd280cdc43e5da217e86ebb (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 %params = @_;
  302. my @torename = @{$params{torename}};
  303. my $session = $params{session};
  304. # Save the page(s) the user asked to rename, so that our
  305. # canrename hook can tell the difference between:
  306. # - a translation being renamed as a consequence of its master page
  307. # being renamed
  308. # - a user trying to directly rename a translation
  309. # This is why this hook has to be run first, before the list of pages
  310. # to rename is modified by other plugins.
  311. $session->param(po_orig_torename => \@torename);
  312. IkiWiki::cgi_savesession($session);
  313. my @ret=@torename;
  314. # iterate on @torename and push onto @ret, so that we don't iterate
  315. # on the items we added ourselves
  316. foreach my $rename (@torename) {
  317. next unless istranslatable($rename->{src});
  318. my %otherpages=%{otherlanguages($rename->{src})};
  319. while (my ($lang, $otherpage) = each %otherpages) {
  320. push @ret, {
  321. src => $otherpage,
  322. srcfile => $pagesources{$otherpage},
  323. dest => otherlanguage($rename->{dest}, $lang),
  324. destfile => $rename->{dest}.".".$lang.".po",
  325. required => 0,
  326. };
  327. }
  328. }
  329. return @ret;
  330. }
  331. sub mydelete(@) {
  332. my @deleted=@_;
  333. map { deletetranslations($_) } grep istranslatablefile($_), @deleted;
  334. }
  335. sub change(@) {
  336. my @rendered=@_;
  337. # All meta titles are first extracted at scan time, i.e. before we turn
  338. # PO files back into translated markdown; escaping of double-quotes in
  339. # PO files breaks the meta plugin's parsing enough to save ugly titles
  340. # to %pagestate at this time.
  341. #
  342. # Then, at render time, every page's passes on row through the Great
  343. # Rendering Chain (filter->preprocess->linkify->htmlize), and the meta
  344. # plugin's preprocess hook is this time in a position to correctly
  345. # extract the titles from slave pages.
  346. #
  347. # This is, unfortunately, too late: if the page A, linking to the page B,
  348. # is rendered before B, it will display the wrongly-extracted meta title
  349. # as the link text to B.
  350. #
  351. # On the one hand, such a corner case only happens on rebuild: on
  352. # refresh, every rendered page is fixed to contain correct meta titles.
  353. # On the other hand, it can take some time to get every page fixed.
  354. # We therefore re-render every rendered page after a rebuild to fix them
  355. # at once. As this more or less doubles the time needed to rebuild the
  356. # wiki, we do so only when really needed.
  357. if (@rendered
  358. && exists $config{rebuild} && defined $config{rebuild} && $config{rebuild}
  359. && UNIVERSAL::can("IkiWiki::Plugin::meta", "getsetup")
  360. && exists $config{meta_overrides_page_title}
  361. && defined $config{meta_overrides_page_title}
  362. && $config{meta_overrides_page_title}) {
  363. debug(sprintf(gettext("re-rendering all pages to fix meta titles")));
  364. resetalreadyfiltered();
  365. require IkiWiki::Render;
  366. foreach my $file (@rendered) {
  367. debug(sprintf(gettext("rendering %s"), $file));
  368. IkiWiki::render($file);
  369. }
  370. }
  371. my $updated_po_files=0;
  372. # Refresh/create POT and PO files as needed.
  373. foreach my $file (grep {istranslatablefile($_)} @rendered) {
  374. my $page=pagename($file);
  375. my $masterfile=srcfile($file);
  376. my $updated_pot_file=0;
  377. # Only refresh Pot file if it does not exist, or if
  378. # $pagesources{$page} was changed: don't if only the HTML was
  379. # refreshed, e.g. because of a dependency.
  380. if ((grep { $_ eq $pagesources{$page} } @origneedsbuild)
  381. || ! -e potfile($masterfile)) {
  382. refreshpot($masterfile);
  383. $updated_pot_file=1;
  384. }
  385. my @pofiles;
  386. map {
  387. push @pofiles, $_ if ($updated_pot_file || ! -e $_);
  388. } (pofiles($masterfile));
  389. if (@pofiles) {
  390. refreshpofiles($masterfile, @pofiles);
  391. map { IkiWiki::rcs_add($_) } @pofiles if $config{rcs};
  392. $updated_po_files=1;
  393. }
  394. }
  395. if ($updated_po_files) {
  396. commit_and_refresh(
  397. gettext("updated PO files"),
  398. "IkiWiki::Plugin::po::change");
  399. }
  400. }
  401. sub checkcontent (@) {
  402. my %params=@_;
  403. if (istranslation($params{page})) {
  404. my $res = isvalidpo($params{content});
  405. if ($res) {
  406. return undef;
  407. }
  408. else {
  409. return "$res";
  410. }
  411. }
  412. return undef;
  413. }
  414. sub canremove (@) {
  415. my %params = @_;
  416. if (istranslation($params{page})) {
  417. return gettext("Can not remove a translation. Removing the master page, ".
  418. "though, removes its translations as well.");
  419. }
  420. return undef;
  421. }
  422. sub canrename (@) {
  423. my %params = @_;
  424. my $session = $params{session};
  425. if (istranslation($params{src})) {
  426. my $masterpage = masterpage($params{src});
  427. # Tell the difference between:
  428. # - a translation being renamed as a consequence of its master page
  429. # being renamed, which is allowed
  430. # - a user trying to directly rename a translation, which is forbidden
  431. # by looking for the master page in the list of to-be-renamed pages we
  432. # saved early in the renaming process.
  433. my $orig_torename = $session->param("po_orig_torename");
  434. unless (grep { $_->{src} eq $masterpage } @{$orig_torename}) {
  435. return gettext("Can not rename a translation. Renaming the master page, ".
  436. "though, renames its translations as well.");
  437. }
  438. }
  439. return undef;
  440. }
  441. # As we're previewing or saving a page, the content may have
  442. # changed, so tell the next filter() invocation it must not be lazy.
  443. sub editcontent () {
  444. my %params=@_;
  445. unsetalreadyfiltered($params{page}, $params{page});
  446. return $params{content};
  447. }
  448. sub formbuilder_setup (@) {
  449. my %params=@_;
  450. my $form=$params{form};
  451. my $q=$params{cgi};
  452. return unless defined $form->field("do");
  453. if ($form->field("do") eq "create") {
  454. # Warn the user: new pages must be written in master language.
  455. my $template=template("pocreatepage.tmpl");
  456. $template->param(LANG => $config{po_master_language}{name});
  457. $form->tmpl_param(message => $template->output);
  458. }
  459. elsif ($form->field("do") eq "edit") {
  460. # Remove the rename/remove buttons on slave pages.
  461. # This has to be done after the rename/remove plugins have added
  462. # their buttons, which is why this hook must be run last.
  463. # The canrename/canremove hooks already ensure this is forbidden
  464. # at the backend level, so this is only UI sugar.
  465. if (istranslation($form->field("page"))) {
  466. map {
  467. for (my $i = 0; $i < @{$params{buttons}}; $i++) {
  468. if (@{$params{buttons}}[$i] eq $_) {
  469. delete @{$params{buttons}}[$i];
  470. last;
  471. }
  472. }
  473. } qw(Rename Remove);
  474. }
  475. }
  476. }
  477. sub formbuilder (@) {
  478. my %params=@_;
  479. my $form=$params{form};
  480. my $q=$params{cgi};
  481. return unless defined $form->field("do");
  482. # Do not allow to create pages of type po: they are automatically created.
  483. # The main reason to do so is to bypass the "favor the type of linking page
  484. # on page creation" logic, which is unsuitable when a broken link is clicked
  485. # on a slave (PO) page.
  486. # This cannot be done in the formbuilder_setup hook as the list of types is
  487. # computed later.
  488. if ($form->field("do") eq "create") {
  489. foreach my $field ($form->field) {
  490. next unless "$field" eq "type";
  491. if ($field->type eq 'select') {
  492. # remove po from the list of types
  493. my @types = grep { $_ ne 'po' } $field->options;
  494. $field->options(\@types) if @types;
  495. }
  496. }
  497. }
  498. }
  499. # ,----
  500. # | Injected functions
  501. # `----
  502. # Implement po_link_to 'current' and 'negotiated' settings.
  503. sub mybestlink ($$) {
  504. my $page=shift;
  505. my $link=shift;
  506. my $res=$origsubs{'bestlink'}->(masterpage($page), $link);
  507. if (length $res
  508. && ($config{po_link_to} eq "current" || $config{po_link_to} eq "negotiated")
  509. && istranslatable($res)
  510. && istranslation($page)) {
  511. return $res . "." . lang($page);
  512. }
  513. return $res;
  514. }
  515. sub mybeautify_urlpath ($) {
  516. my $url=shift;
  517. my $res=$origsubs{'beautify_urlpath'}->($url);
  518. if ($config{po_link_to} eq "negotiated") {
  519. $res =~ s!/\Qindex.$config{po_master_language}{code}.$config{htmlext}\E$!/!;
  520. $res =~ s!/\Qindex.$config{htmlext}\E$!/!;
  521. map {
  522. $res =~ s!/\Qindex.$_.$config{htmlext}\E$!/!;
  523. } (keys %{$config{po_slave_languages}});
  524. }
  525. return $res;
  526. }
  527. sub mytargetpage ($$) {
  528. my $page=shift;
  529. my $ext=shift;
  530. if (istranslation($page) || istranslatable($page)) {
  531. my ($masterpage, $lang) = (masterpage($page), lang($page));
  532. if (! $config{usedirs} || $masterpage eq 'index') {
  533. return $masterpage . "." . $lang . "." . $ext;
  534. }
  535. else {
  536. return $masterpage . "/index." . $lang . "." . $ext;
  537. }
  538. }
  539. return $origsubs{'targetpage'}->($page, $ext);
  540. }
  541. sub myurlto ($$;$) {
  542. my $to=shift;
  543. my $from=shift;
  544. my $absolute=shift;
  545. # workaround hard-coded /index.$config{htmlext} in IkiWiki::urlto()
  546. if (! length $to
  547. && $config{po_link_to} eq "current"
  548. && istranslatable('index')) {
  549. return IkiWiki::beautify_urlpath(IkiWiki::baseurl($from) . "index." . lang($from) . ".$config{htmlext}");
  550. }
  551. # avoid using our injected beautify_urlpath if run by cgi_editpage,
  552. # so that one is redirected to the just-edited page rather than to the
  553. # negociated translation; to prevent unnecessary fiddling with caller/inject,
  554. # we only do so when our beautify_urlpath would actually do what we want to
  555. # avoid, i.e. when po_link_to = negotiated
  556. if ($config{po_link_to} eq "negotiated") {
  557. my @caller = caller(1);
  558. my $run_by_editpage = 0;
  559. $run_by_editpage = 1 if (exists $caller[3] && defined $caller[3]
  560. && $caller[3] eq "IkiWiki::cgi_editpage");
  561. inject(name => "IkiWiki::beautify_urlpath", call => $origsubs{'beautify_urlpath'})
  562. if $run_by_editpage;
  563. my $res = $origsubs{'urlto'}->($to,$from,$absolute);
  564. inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath)
  565. if $run_by_editpage;
  566. return $res;
  567. }
  568. else {
  569. return $origsubs{'urlto'}->($to,$from,$absolute)
  570. }
  571. }
  572. sub mynicepagetitle ($;$) {
  573. my ($page, $unescaped) = (shift, shift);
  574. my $res = $origsubs{'nicepagetitle'}->($page, $unescaped);
  575. return $res unless istranslation($page);
  576. return $res unless $config{po_translation_status_in_links};
  577. my @caller = caller(1);
  578. return $res if (exists $caller[3] && defined $caller[3]
  579. && $caller[3] eq "IkiWiki::Plugin::parentlinks::parentlinks");
  580. return $res.' ('.percenttranslated($page).'&nbsp;%)';
  581. }
  582. sub mycgiurl (@) {
  583. my %params=@_;
  584. # slave pages have no subpages
  585. if (istranslation($params{'from'})) {
  586. $params{'from'} = masterpage($params{'from'});
  587. }
  588. return $origsubs{'cgiurl'}->(%params);
  589. }
  590. # ,----
  591. # | Blackboxes for private data
  592. # `----
  593. {
  594. my %filtered;
  595. sub alreadyfiltered($$) {
  596. my $page=shift;
  597. my $destpage=shift;
  598. return exists $filtered{$page}{$destpage}
  599. && $filtered{$page}{$destpage} eq 1;
  600. }
  601. sub setalreadyfiltered($$) {
  602. my $page=shift;
  603. my $destpage=shift;
  604. $filtered{$page}{$destpage}=1;
  605. }
  606. sub unsetalreadyfiltered($$) {
  607. my $page=shift;
  608. my $destpage=shift;
  609. if (exists $filtered{$page}{$destpage}) {
  610. delete $filtered{$page}{$destpage};
  611. }
  612. }
  613. sub resetalreadyfiltered() {
  614. undef %filtered;
  615. }
  616. }
  617. # ,----
  618. # | Helper functions
  619. # `----
  620. sub maybe_add_leading_slash ($;$) {
  621. my $str=shift;
  622. my $add=shift;
  623. $add=1 unless defined $add;
  624. return '/' . $str if $add;
  625. return $str;
  626. }
  627. sub istranslatablefile ($) {
  628. my $file=shift;
  629. return 0 unless defined $file;
  630. return 0 if defined pagetype($file) && pagetype($file) eq 'po';
  631. return 0 if $file =~ /\.pot$/;
  632. return 0 unless -e "$config{srcdir}/$file"; # underlay dirs may be read-only
  633. return 1 if pagespec_match(pagename($file), $config{po_translatable_pages});
  634. return;
  635. }
  636. sub istranslatable ($) {
  637. my $page=shift;
  638. $page=~s#^/##;
  639. return 1 if istranslatablefile($pagesources{$page});
  640. return;
  641. }
  642. sub _istranslation ($) {
  643. my $page=shift;
  644. $page='' unless defined $page && length $page;
  645. my $hasleadingslash = ($page=~s#^/##);
  646. my $file=$pagesources{$page};
  647. return 0 unless defined $file
  648. && defined pagetype($file)
  649. && pagetype($file) eq 'po';
  650. return 0 if $file =~ /\.pot$/;
  651. my ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
  652. return 0 unless defined $masterpage && defined $lang
  653. && length $masterpage && length $lang
  654. && defined $pagesources{$masterpage}
  655. && defined $config{po_slave_languages}{$lang};
  656. return (maybe_add_leading_slash($masterpage, $hasleadingslash), $lang)
  657. if istranslatable($masterpage);
  658. }
  659. sub istranslation ($) {
  660. my $page=shift;
  661. if (1 < (my ($masterpage, $lang) = _istranslation($page))) {
  662. my $hasleadingslash = ($masterpage=~s#^/##);
  663. $translations{$masterpage}{$lang}=$page unless exists $translations{$masterpage}{$lang};
  664. return (maybe_add_leading_slash($masterpage, $hasleadingslash), $lang);
  665. }
  666. return "";
  667. }
  668. sub masterpage ($) {
  669. my $page=shift;
  670. if ( 1 < (my ($masterpage, $lang) = _istranslation($page))) {
  671. return $masterpage;
  672. }
  673. return $page;
  674. }
  675. sub lang ($) {
  676. my $page=shift;
  677. if (1 < (my ($masterpage, $lang) = _istranslation($page))) {
  678. return $lang;
  679. }
  680. return $config{po_master_language}{code};
  681. }
  682. sub islanguagecode ($) {
  683. my $code=shift;
  684. return $code =~ /^[a-z]{2}$/;
  685. }
  686. sub otherlanguage ($$) {
  687. my $page=shift;
  688. my $code=shift;
  689. return masterpage($page) if $code eq $config{po_master_language}{code};
  690. return masterpage($page) . '.' . $code;
  691. }
  692. sub otherlanguages ($) {
  693. my $page=shift;
  694. my %ret;
  695. return \%ret unless istranslation($page) || istranslatable($page);
  696. my $curlang=lang($page);
  697. foreach my $lang
  698. ($config{po_master_language}{code}, keys %{$config{po_slave_languages}}) {
  699. next if $lang eq $curlang;
  700. $ret{$lang}=otherlanguage($page, $lang);
  701. }
  702. return \%ret;
  703. }
  704. sub potfile ($) {
  705. my $masterfile=shift;
  706. (my $name, my $dir, my $suffix) = fileparse($masterfile, qr/\.[^.]*/);
  707. $dir='' if $dir eq './';
  708. return File::Spec->catpath('', $dir, $name . ".pot");
  709. }
  710. sub pofile ($$) {
  711. my $masterfile=shift;
  712. my $lang=shift;
  713. (my $name, my $dir, my $suffix) = fileparse($masterfile, qr/\.[^.]*/);
  714. $dir='' if $dir eq './';
  715. return File::Spec->catpath('', $dir, $name . "." . $lang . ".po");
  716. }
  717. sub pofiles ($) {
  718. my $masterfile=shift;
  719. return map pofile($masterfile, $_), (keys %{$config{po_slave_languages}});
  720. }
  721. sub refreshpot ($) {
  722. my $masterfile=shift;
  723. my $potfile=potfile($masterfile);
  724. my %options = ("markdown" => (pagetype($masterfile) eq 'mdwn') ? 1 : 0);
  725. my $doc=Locale::Po4a::Chooser::new('text',%options);
  726. $doc->{TT}{utf_mode} = 1;
  727. $doc->{TT}{file_in_charset} = 'utf-8';
  728. $doc->{TT}{file_out_charset} = 'utf-8';
  729. $doc->read($masterfile);
  730. # let's cheat a bit to force porefs option to be passed to Locale::Po4a::Po;
  731. # this is undocument use of internal Locale::Po4a::TransTractor's data,
  732. # compulsory since this module prevents us from using the porefs option.
  733. $doc->{TT}{po_out}=Locale::Po4a::Po->new({ 'porefs' => 'none' });
  734. $doc->{TT}{po_out}->set_charset('utf-8');
  735. # do the actual work
  736. $doc->parse;
  737. IkiWiki::prep_writefile(basename($potfile),dirname($potfile));
  738. $doc->writepo($potfile);
  739. }
  740. sub refreshpofiles ($@) {
  741. my $masterfile=shift;
  742. my @pofiles=@_;
  743. my $potfile=potfile($masterfile);
  744. if (! -e $potfile) {
  745. error("po(refreshpofiles) ".sprintf(gettext("POT file (%s) does not exist"), $potfile));
  746. }
  747. foreach my $pofile (@pofiles) {
  748. IkiWiki::prep_writefile(basename($pofile),dirname($pofile));
  749. if (-e $pofile) {
  750. system("msgmerge", "-U", "--backup=none", $pofile, $potfile) == 0
  751. or error("po(refreshpofiles) ".
  752. sprintf(gettext("failed to update %s"),
  753. $pofile));
  754. }
  755. else {
  756. File::Copy::syscopy($potfile,$pofile)
  757. or error("po(refreshpofiles) ".
  758. sprintf(gettext("failed to copy the POT file to %s"),
  759. $pofile));
  760. }
  761. }
  762. }
  763. sub buildtranslationscache() {
  764. # use istranslation's side-effect
  765. map istranslation($_), (keys %pagesources);
  766. }
  767. sub resettranslationscache() {
  768. undef %translations;
  769. }
  770. sub flushmemoizecache() {
  771. Memoize::flush_cache("istranslatable");
  772. Memoize::flush_cache("_istranslation");
  773. Memoize::flush_cache("percenttranslated");
  774. }
  775. sub urlto_with_orig_beautiful_urlpath($$) {
  776. my $to=shift;
  777. my $from=shift;
  778. inject(name => "IkiWiki::beautify_urlpath", call => $origsubs{'beautify_urlpath'});
  779. my $res=urlto($to, $from);
  780. inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath);
  781. return $res;
  782. }
  783. sub percenttranslated ($) {
  784. my $page=shift;
  785. $page=~s/^\///;
  786. return gettext("N/A") unless istranslation($page);
  787. my $file=srcfile($pagesources{$page});
  788. my $masterfile = srcfile($pagesources{masterpage($page)});
  789. my %options = (
  790. "markdown" => (pagetype($masterfile) eq 'mdwn') ? 1 : 0,
  791. );
  792. my $doc=Locale::Po4a::Chooser::new('text',%options);
  793. $doc->process(
  794. 'po_in_name' => [ $file ],
  795. 'file_in_name' => [ $masterfile ],
  796. 'file_in_charset' => 'utf-8',
  797. 'file_out_charset' => 'utf-8',
  798. ) or error("po(percenttranslated) ".
  799. sprintf(gettext("failed to translate %s"), $page));
  800. my ($percent,$hit,$queries) = $doc->stats();
  801. $percent =~ s/\.[0-9]+$//;
  802. return $percent;
  803. }
  804. sub languagename ($) {
  805. my $code=shift;
  806. return $config{po_master_language}{name}
  807. if $code eq $config{po_master_language}{code};
  808. return $config{po_slave_languages}{$code}
  809. if defined $config{po_slave_languages}{$code};
  810. return;
  811. }
  812. sub otherlanguagesloop ($) {
  813. my $page=shift;
  814. my @ret;
  815. my %otherpages=%{otherlanguages($page)};
  816. while (my ($lang, $otherpage) = each %otherpages) {
  817. if (istranslation($page) && masterpage($page) eq $otherpage) {
  818. push @ret, {
  819. url => urlto_with_orig_beautiful_urlpath($otherpage, $page),
  820. code => $lang,
  821. language => languagename($lang),
  822. master => 1,
  823. };
  824. }
  825. else {
  826. push @ret, {
  827. url => urlto_with_orig_beautiful_urlpath($otherpage, $page),
  828. code => $lang,
  829. language => languagename($lang),
  830. percent => percenttranslated($otherpage),
  831. }
  832. }
  833. }
  834. return sort {
  835. return -1 if $a->{code} eq $config{po_master_language}{code};
  836. return 1 if $b->{code} eq $config{po_master_language}{code};
  837. return $a->{language} cmp $b->{language};
  838. } @ret;
  839. }
  840. sub homepageurl (;$) {
  841. my $page=shift;
  842. return urlto('', $page);
  843. }
  844. sub deletetranslations ($) {
  845. my $deletedmasterfile=shift;
  846. my $deletedmasterpage=pagename($deletedmasterfile);
  847. my @todelete;
  848. map {
  849. my $file = newpagefile($deletedmasterpage.'.'.$_, 'po');
  850. my $absfile = "$config{srcdir}/$file";
  851. if (-e $absfile && ! -l $absfile && ! -d $absfile) {
  852. push @todelete, $file;
  853. }
  854. } keys %{$config{po_slave_languages}};
  855. map {
  856. if ($config{rcs}) {
  857. IkiWiki::rcs_remove($_);
  858. }
  859. else {
  860. IkiWiki::prune("$config{srcdir}/$_");
  861. }
  862. } @todelete;
  863. if (@todelete) {
  864. commit_and_refresh(
  865. gettext("removed obsolete PO files"),
  866. "IkiWiki::Plugin::po::deletetranslations");
  867. }
  868. }
  869. sub commit_and_refresh ($$) {
  870. my ($msg, $author) = (shift, shift);
  871. if ($config{rcs}) {
  872. IkiWiki::disable_commit_hook();
  873. IkiWiki::rcs_commit_staged($msg, $author, "127.0.0.1");
  874. IkiWiki::enable_commit_hook();
  875. IkiWiki::rcs_update();
  876. }
  877. # Reinitialize module's private variables.
  878. resetalreadyfiltered();
  879. resettranslationscache();
  880. flushmemoizecache();
  881. # Trigger a wiki refresh.
  882. require IkiWiki::Render;
  883. # without preliminary saveindex/loadindex, refresh()
  884. # complains about a lot of uninitialized variables
  885. IkiWiki::saveindex();
  886. IkiWiki::loadindex();
  887. IkiWiki::refresh();
  888. IkiWiki::saveindex();
  889. }
  890. # on success, returns the filtered content.
  891. # on error, if $nonfatal, warn and return undef; else, error out.
  892. sub po_to_markup ($$;$) {
  893. my ($page, $content) = (shift, shift);
  894. my $nonfatal = shift;
  895. $content = '' unless defined $content;
  896. $content = decode_utf8(encode_utf8($content));
  897. # CRLF line terminators make poor Locale::Po4a feel bad
  898. $content=~s/\r\n/\n/g;
  899. # There are incompatibilities between some File::Temp versions
  900. # (including 0.18, bundled with Lenny's perl-modules package)
  901. # and others (e.g. 0.20, previously present in the archive as
  902. # a standalone package): under certain circumstances, some
  903. # return a relative filename, whereas others return an absolute one;
  904. # we here use this module in a way that is at least compatible
  905. # with 0.18 and 0.20. Beware, hit'n'run refactorers!
  906. my $infile = new File::Temp(TEMPLATE => "ikiwiki-po-filter-in.XXXXXXXXXX",
  907. DIR => File::Spec->tmpdir,
  908. UNLINK => 1)->filename;
  909. my $outfile = new File::Temp(TEMPLATE => "ikiwiki-po-filter-out.XXXXXXXXXX",
  910. DIR => File::Spec->tmpdir,
  911. UNLINK => 1)->filename;
  912. my $fail = sub ($) {
  913. my $msg = "po(po_to_markup) - $page : " . shift;
  914. if ($nonfatal) {
  915. warn $msg;
  916. return undef;
  917. }
  918. error($msg, sub { unlink $infile, $outfile});
  919. };
  920. writefile(basename($infile), File::Spec->tmpdir, $content)
  921. or return $fail->(sprintf(gettext("failed to write %s"), $infile));
  922. my $masterfile = srcfile($pagesources{masterpage($page)});
  923. my %options = (
  924. "markdown" => (pagetype($masterfile) eq 'mdwn') ? 1 : 0,
  925. );
  926. my $doc=Locale::Po4a::Chooser::new('text',%options);
  927. $doc->process(
  928. 'po_in_name' => [ $infile ],
  929. 'file_in_name' => [ $masterfile ],
  930. 'file_in_charset' => 'utf-8',
  931. 'file_out_charset' => 'utf-8',
  932. ) or return $fail->(gettext("failed to translate"));
  933. $doc->write($outfile)
  934. or return $fail->(sprintf(gettext("failed to write %s"), $outfile));
  935. $content = readfile($outfile)
  936. or return $fail->(sprintf(gettext("failed to read %s"), $outfile));
  937. # Unlinking should happen automatically, thanks to File::Temp,
  938. # but it does not work here, probably because of the way writefile()
  939. # and Locale::Po4a::write() work.
  940. unlink $infile, $outfile;
  941. return $content;
  942. }
  943. # returns a SuccessReason or FailReason object
  944. sub isvalidpo ($) {
  945. my $content = shift;
  946. # NB: we don't use po_to_markup here, since Po4a parser does
  947. # not mind invalid PO content
  948. $content = '' unless defined $content;
  949. $content = decode_utf8(encode_utf8($content));
  950. # There are incompatibilities between some File::Temp versions
  951. # (including 0.18, bundled with Lenny's perl-modules package)
  952. # and others (e.g. 0.20, previously present in the archive as
  953. # a standalone package): under certain circumstances, some
  954. # return a relative filename, whereas others return an absolute one;
  955. # we here use this module in a way that is at least compatible
  956. # with 0.18 and 0.20. Beware, hit'n'run refactorers!
  957. my $infile = new File::Temp(TEMPLATE => "ikiwiki-po-isvalidpo.XXXXXXXXXX",
  958. DIR => File::Spec->tmpdir,
  959. UNLINK => 1)->filename;
  960. my $fail = sub ($) {
  961. my $msg = '[po/isvalidpo] ' . shift;
  962. unlink $infile;
  963. return IkiWiki::FailReason->new("$msg");
  964. };
  965. writefile(basename($infile), File::Spec->tmpdir, $content)
  966. or return $fail->(sprintf(gettext("failed to write %s"), $infile));
  967. my $res = (system("msgfmt", "--check", $infile, "-o", "/dev/null") == 0);
  968. # Unlinking should happen automatically, thanks to File::Temp,
  969. # but it does not work here, probably because of the way writefile()
  970. # and Locale::Po4a::write() work.
  971. unlink $infile;
  972. if ($res) {
  973. return IkiWiki::SuccessReason->new("valid gettext data");
  974. }
  975. return IkiWiki::FailReason->new("invalid gettext data, go back ".
  976. "to previous page to go on with edit");
  977. }
  978. # ,----
  979. # | PageSpecs
  980. # `----
  981. package IkiWiki::PageSpec;
  982. sub match_istranslation ($;@) {
  983. my $page=shift;
  984. if (IkiWiki::Plugin::po::istranslation($page)) {
  985. return IkiWiki::SuccessReason->new("is a translation page");
  986. }
  987. else {
  988. return IkiWiki::FailReason->new("is not a translation page");
  989. }
  990. }
  991. sub match_istranslatable ($;@) {
  992. my $page=shift;
  993. if (IkiWiki::Plugin::po::istranslatable($page)) {
  994. return IkiWiki::SuccessReason->new("is set as translatable in po_translatable_pages");
  995. }
  996. else {
  997. return IkiWiki::FailReason->new("is not set as translatable in po_translatable_pages");
  998. }
  999. }
  1000. sub match_lang ($$;@) {
  1001. my $page=shift;
  1002. my $wanted=shift;
  1003. my $regexp=IkiWiki::glob2re($wanted);
  1004. my $lang=IkiWiki::Plugin::po::lang($page);
  1005. if ($lang !~ /^$regexp$/i) {
  1006. return IkiWiki::FailReason->new("file language is $lang, not $wanted");
  1007. }
  1008. else {
  1009. return IkiWiki::SuccessReason->new("file language is $wanted");
  1010. }
  1011. }
  1012. sub match_currentlang ($$;@) {
  1013. my $page=shift;
  1014. shift;
  1015. my %params=@_;
  1016. return IkiWiki::FailReason->new("no location provided") unless exists $params{location};
  1017. my $currentlang=IkiWiki::Plugin::po::lang($params{location});
  1018. my $lang=IkiWiki::Plugin::po::lang($page);
  1019. if ($lang eq $currentlang) {
  1020. return IkiWiki::SuccessReason->new("file language is the same as current one, i.e. $currentlang");
  1021. }
  1022. else {
  1023. return IkiWiki::FailReason->new("file language is $lang, whereas current language is $currentlang");
  1024. }
  1025. }
  1026. 1