summaryrefslogtreecommitdiff
path: root/IkiWiki/Plugin/po.pm
blob: 0a970284cdc41fbc831f4cd809d34f41dbc63b43 (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. BEGIN {
  13. eval 'use Locale::Po4a::Common qw(nowrapi18n)';
  14. if ($@) {
  15. warning(sprintf(gettext('%s is too old, can not disable %s; '.
  16. 'a denial of service can thus be '.
  17. 'triggered by malicious content'),
  18. 'Locale::Po4a', 'Text::WrapI18N'));
  19. eval 'use Locale::Po4a::Common';
  20. }
  21. }
  22. use Locale::Po4a::Chooser;
  23. use Locale::Po4a::Po;
  24. use File::Basename;
  25. use File::Copy;
  26. use File::Spec;
  27. use File::Temp;
  28. use Memoize;
  29. use UNIVERSAL;
  30. my %translations;
  31. my @origneedsbuild;
  32. my %origsubs;
  33. memoize("istranslatable");
  34. memoize("_istranslation");
  35. memoize("percenttranslated");
  36. sub import {
  37. hook(type => "getsetup", id => "po", call => \&getsetup);
  38. hook(type => "checkconfig", id => "po", call => \&checkconfig);
  39. hook(type => "needsbuild", id => "po", call => \&needsbuild);
  40. hook(type => "scan", id => "po", call => \&scan, last =>1);
  41. hook(type => "filter", id => "po", call => \&filter);
  42. hook(type => "htmlize", id => "po", call => \&htmlize);
  43. hook(type => "pagetemplate", id => "po", call => \&pagetemplate, last => 1);
  44. hook(type => "postscan", id => "po", call => \&postscan);
  45. hook(type => "rename", id => "po", call => \&renamepages, first => 1);
  46. hook(type => "delete", id => "po", call => \&mydelete);
  47. hook(type => "change", id => "po", call => \&change);
  48. hook(type => "cansave", id => "po", call => \&cansave);
  49. hook(type => "canremove", id => "po", call => \&canremove);
  50. hook(type => "canrename", id => "po", call => \&canrename);
  51. hook(type => "editcontent", id => "po", call => \&editcontent);
  52. hook(type => "formbuilder_setup", id => "po", call => \&formbuilder_setup, last => 1);
  53. hook(type => "formbuilder", id => "po", call => \&formbuilder);
  54. $origsubs{'bestlink'}=\&IkiWiki::bestlink;
  55. inject(name => "IkiWiki::bestlink", call => \&mybestlink);
  56. $origsubs{'beautify_urlpath'}=\&IkiWiki::beautify_urlpath;
  57. inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath);
  58. $origsubs{'targetpage'}=\&IkiWiki::targetpage;
  59. inject(name => "IkiWiki::targetpage", call => \&mytargetpage);
  60. $origsubs{'urlto'}=\&IkiWiki::urlto;
  61. inject(name => "IkiWiki::urlto", call => \&myurlto);
  62. $origsubs{'nicepagetitle'}=\&IkiWiki::nicepagetitle;
  63. inject(name => "IkiWiki::nicepagetitle", call => \&mynicepagetitle);
  64. $origsubs{'cgiurl'}=\&IkiWiki::cgiurl;
  65. inject(name => "IkiWiki::cgiurl", call => \&mycgiurl);
  66. }
  67. # ,----
  68. # | Table of contents
  69. # `----
  70. # 1. Hooks
  71. # 2. Injected functions
  72. # 3. Blackboxes for private data
  73. # 4. Helper functions
  74. # 5. PageSpec's
  75. # ,----
  76. # | Hooks
  77. # `----
  78. sub getsetup () {
  79. return
  80. plugin => {
  81. safe => 0,
  82. rebuild => 1,
  83. },
  84. po_master_language => {
  85. type => "string",
  86. example => {
  87. 'code' => 'en',
  88. 'name' => 'English'
  89. },
  90. description => "master language (non-PO files)",
  91. safe => 1,
  92. rebuild => 1,
  93. },
  94. po_slave_languages => {
  95. type => "string",
  96. example => {
  97. 'fr' => 'Français',
  98. 'es' => 'Castellano',
  99. 'de' => 'Deutsch'
  100. },
  101. description => "slave languages (PO files)",
  102. safe => 1,
  103. rebuild => 1,
  104. },
  105. po_translatable_pages => {
  106. type => "pagespec",
  107. example => "!*/Discussion",
  108. description => "PageSpec controlling which pages are translatable",
  109. link => "ikiwiki/PageSpec",
  110. safe => 1,
  111. rebuild => 1,
  112. },
  113. po_link_to => {
  114. type => "string",
  115. example => "current",
  116. description => "internal linking behavior (default/current/negotiated)",
  117. safe => 1,
  118. rebuild => 1,
  119. },
  120. po_translation_status_in_links => {
  121. type => "boolean",
  122. example => 1,
  123. description => "display translation status in links to translations",
  124. safe => 1,
  125. rebuild => 1,
  126. },
  127. }
  128. sub checkconfig () {
  129. foreach my $field (qw{po_master_language po_slave_languages}) {
  130. if (! exists $config{$field} || ! defined $config{$field}) {
  131. error(sprintf(gettext("Must specify %s when using the %s plugin"),
  132. $field, 'po'));
  133. }
  134. }
  135. if (! (keys %{$config{po_slave_languages}})) {
  136. error(gettext("At least one slave language must be defined ".
  137. "in po_slave_languages when using the po plugin"));
  138. }
  139. map {
  140. islanguagecode($_)
  141. or error(sprintf(gettext("%s is not a valid language code"), $_));
  142. } ($config{po_master_language}{code}, keys %{$config{po_slave_languages}});
  143. if (! exists $config{po_translatable_pages} ||
  144. ! defined $config{po_translatable_pages}) {
  145. $config{po_translatable_pages}="";
  146. }
  147. if (! exists $config{po_link_to} ||
  148. ! defined $config{po_link_to}) {
  149. $config{po_link_to}='default';
  150. }
  151. elsif (! grep {
  152. $config{po_link_to} eq $_
  153. } ('default', 'current', 'negotiated')) {
  154. warn(sprintf(gettext('%s is not a valid value for po_link_to, falling back to po_link_to=default'),
  155. $config{po_link_to}));
  156. $config{po_link_to}='default';
  157. }
  158. elsif ($config{po_link_to} eq "negotiated" && ! $config{usedirs}) {
  159. warn(gettext('po_link_to=negotiated requires usedirs to be enabled, falling back to po_link_to=default'));
  160. $config{po_link_to}='default';
  161. }
  162. if (! exists $config{po_translation_status_in_links} ||
  163. ! defined $config{po_translation_status_in_links}) {
  164. $config{po_translation_status_in_links}=1;
  165. }
  166. push @{$config{wiki_file_prune_regexps}}, qr/\.pot$/;
  167. }
  168. sub needsbuild () {
  169. my $needsbuild=shift;
  170. # backup @needsbuild content so that change() can know whether
  171. # a given master page was rendered because its source file was changed
  172. @origneedsbuild=(@$needsbuild);
  173. flushmemoizecache();
  174. buildtranslationscache();
  175. # make existing translations depend on the corresponding master page
  176. foreach my $master (keys %translations) {
  177. map add_depends($_, $master), values %{otherlanguages($master)};
  178. }
  179. }
  180. # Massage the recorded state of internal links so that:
  181. # - it matches the actually generated links, rather than the links as written
  182. # in the pages' source
  183. # - backlinks are consistent in all cases
  184. sub scan (@) {
  185. my %params=@_;
  186. my $page=$params{page};
  187. my $content=$params{content};
  188. return unless UNIVERSAL::can("IkiWiki::Plugin::link", "import");
  189. if (istranslation($page)) {
  190. foreach my $destpage (@{$links{$page}}) {
  191. if (istranslatable($destpage)) {
  192. # replace one occurence of $destpage in $links{$page}
  193. # (we only want to replace the one that was added by
  194. # IkiWiki::Plugin::link::scan, other occurences may be
  195. # there for other reasons)
  196. for (my $i=0; $i<@{$links{$page}}; $i++) {
  197. if (@{$links{$page}}[$i] eq $destpage) {
  198. @{$links{$page}}[$i] = $destpage . '.' . lang($page);
  199. last;
  200. }
  201. }
  202. }
  203. }
  204. }
  205. elsif (! istranslatable($page) && ! istranslation($page)) {
  206. foreach my $destpage (@{$links{$page}}) {
  207. if (istranslatable($destpage)) {
  208. # make sure any destpage's translations has
  209. # $page in its backlinks
  210. push @{$links{$page}},
  211. values %{otherlanguages($destpage)};
  212. }
  213. }
  214. }
  215. }
  216. # We use filter to convert PO to the master page's format,
  217. # since the rest of ikiwiki should not work on PO files.
  218. sub filter (@) {
  219. my %params = @_;
  220. my $page = $params{page};
  221. my $destpage = $params{destpage};
  222. my $content = $params{content};
  223. if (istranslation($page) && ! alreadyfiltered($page, $destpage)) {
  224. $content = po_to_markup($page, $content);
  225. setalreadyfiltered($page, $destpage);
  226. }
  227. return $content;
  228. }
  229. sub htmlize (@) {
  230. my %params=@_;
  231. my $page = $params{page};
  232. my $content = $params{content};
  233. # ignore PO files this plugin did not create
  234. return $content unless istranslation($page);
  235. # force content to be htmlize'd as if it was the same type as the master page
  236. return IkiWiki::htmlize($page, $page,
  237. pagetype(srcfile($pagesources{masterpage($page)})),
  238. $content);
  239. }
  240. sub pagetemplate (@) {
  241. my %params=@_;
  242. my $page=$params{page};
  243. my $destpage=$params{destpage};
  244. my $template=$params{template};
  245. my ($masterpage, $lang) = istranslation($page);
  246. if (istranslation($page) && $template->query(name => "percenttranslated")) {
  247. $template->param(percenttranslated => percenttranslated($page));
  248. }
  249. if ($template->query(name => "istranslation")) {
  250. $template->param(istranslation => scalar istranslation($page));
  251. }
  252. if ($template->query(name => "istranslatable")) {
  253. $template->param(istranslatable => istranslatable($page));
  254. }
  255. if ($template->query(name => "HOMEPAGEURL")) {
  256. $template->param(homepageurl => homepageurl($page));
  257. }
  258. if ($template->query(name => "otherlanguages")) {
  259. $template->param(otherlanguages => [otherlanguagesloop($page)]);
  260. map add_depends($page, $_), (values %{otherlanguages($page)});
  261. }
  262. # Rely on IkiWiki::Render's genpage() to decide wether
  263. # a discussion link should appear on $page; this is not
  264. # totally accurate, though: some broken links may be generated
  265. # when cgiurl is disabled.
  266. # This compromise avoids some code duplication, and will probably
  267. # prevent future breakage when ikiwiki internals change.
  268. # Known limitations are preferred to future random bugs.
  269. if ($template->param('discussionlink') && istranslation($page)) {
  270. $template->param('discussionlink' => htmllink(
  271. $page,
  272. $destpage,
  273. $masterpage . '/' . gettext("Discussion"),
  274. noimageinline => 1,
  275. forcesubpage => 0,
  276. linktext => gettext("Discussion"),
  277. ));
  278. }
  279. # Remove broken parentlink to ./index.html on home page's translations.
  280. # It works because this hook has the "last" parameter set, to ensure it
  281. # runs after parentlinks' own pagetemplate hook.
  282. if ($template->param('parentlinks')
  283. && istranslation($page)
  284. && $masterpage eq "index") {
  285. $template->param('parentlinks' => []);
  286. }
  287. } # }}}
  288. sub postscan (@) {
  289. my %params = @_;
  290. my $page = $params{page};
  291. # backlinks involve back-dependencies, so that nicepagetitle effects,
  292. # such as translation status displayed in links, are updated
  293. use IkiWiki::Render;
  294. map add_depends($page, $_), keys %{$IkiWiki::backlinks{$page}};
  295. }
  296. # Add the renamed page translations to the list of to-be-renamed pages.
  297. sub renamepages($$$) {
  298. my ($torename, $cgi, $session) = (shift, shift, shift);
  299. # copy the initial array, so that we can iterate on it AND
  300. # modify it at the same time, without iterating on the items we
  301. # pushed on it ourselves
  302. my @torename=@{$torename};
  303. # Save the page(s) the user asked to rename, so that our
  304. # canrename hook can tell the difference between:
  305. # - a translation being renamed as a consequence of its master page
  306. # being renamed
  307. # - a user trying to directly rename a translation
  308. # This is why this hook has to be run first, before @torename is modified
  309. # by other plugins.
  310. $session->param(po_orig_torename => [ @torename ]);
  311. IkiWiki::cgi_savesession($session);
  312. foreach my $rename (@torename) {
  313. next unless istranslatable($rename->{src});
  314. my %otherpages=%{otherlanguages($rename->{src})};
  315. while (my ($lang, $otherpage) = each %otherpages) {
  316. push @{$torename}, {
  317. src => $otherpage,
  318. srcfile => $pagesources{$otherpage},
  319. dest => otherlanguage($rename->{dest}, $lang),
  320. destfile => $rename->{dest}.".".$lang.".po",
  321. required => 0,
  322. };
  323. }
  324. }
  325. }
  326. sub mydelete(@) {
  327. my @deleted=@_;
  328. map { deletetranslations($_) } grep istranslatablefile($_), @deleted;
  329. }
  330. sub change(@) {
  331. my @rendered=@_;
  332. # All meta titles are first extracted at scan time, i.e. before we turn
  333. # PO files back into translated markdown; escaping of double-quotes in
  334. # PO files breaks the meta plugin's parsing enough to save ugly titles
  335. # to %pagestate at this time.
  336. #
  337. # Then, at render time, every page's passes on row through the Great
  338. # Rendering Chain (filter->preprocess->linkify->htmlize), and the meta
  339. # plugin's preprocess hook is this time in a position to correctly
  340. # extract the titles from slave pages.
  341. #
  342. # This is, unfortunately, too late: if the page A, linking to the page B,
  343. # is rendered before B, it will display the wrongly-extracted meta title
  344. # as the link text to B.
  345. #
  346. # On the one hand, such a corner case only happens on rebuild: on
  347. # refresh, every rendered page is fixed to contain correct meta titles.
  348. # On the other hand, it can take some time to get every page fixed.
  349. # We therefore re-render every rendered page after a rebuild to fix them
  350. # at once. As this more or less doubles the time needed to rebuild the
  351. # wiki, we do so only when really needed.
  352. if (scalar @rendered
  353. && exists $config{rebuild} && defined $config{rebuild} && $config{rebuild}
  354. && UNIVERSAL::can("IkiWiki::Plugin::meta", "getsetup")
  355. && exists $config{meta_overrides_page_title}
  356. && defined $config{meta_overrides_page_title}
  357. && $config{meta_overrides_page_title}) {
  358. debug(sprintf(gettext("re-rendering all pages to fix meta titles")));
  359. resetalreadyfiltered();
  360. require IkiWiki::Render;
  361. foreach my $file (@rendered) {
  362. debug(sprintf(gettext("rendering %s"), $file));
  363. IkiWiki::render($file);
  364. }
  365. }
  366. my $updated_po_files=0;
  367. # Refresh/create POT and PO files as needed.
  368. foreach my $file (grep {istranslatablefile($_)} @rendered) {
  369. my $page=pagename($file);
  370. my $masterfile=srcfile($file);
  371. my $updated_pot_file=0;
  372. # Only refresh Pot file if it does not exist, or if
  373. # $pagesources{$page} was changed: don't if only the HTML was
  374. # refreshed, e.g. because of a dependency.
  375. if ((grep { $_ eq $pagesources{$page} } @origneedsbuild)
  376. || ! -e potfile($masterfile)) {
  377. refreshpot($masterfile);
  378. $updated_pot_file=1;
  379. }
  380. my @pofiles;
  381. map {
  382. push @pofiles, $_ if ($updated_pot_file || ! -e $_);
  383. } (pofiles($masterfile));
  384. if (@pofiles) {
  385. refreshpofiles($masterfile, @pofiles);
  386. map { IkiWiki::rcs_add($_) } @pofiles if $config{rcs};
  387. $updated_po_files=1;
  388. }
  389. }
  390. if ($updated_po_files) {
  391. commit_and_refresh(
  392. gettext("updated PO files"),
  393. "IkiWiki::Plugin::po::change");
  394. }
  395. }
  396. sub cansave ($$$$) {
  397. my ($page, $content, $cgi, $session) = (shift, shift, shift, shift);
  398. if (istranslation($page)) {
  399. my $res = isvalidpo($content);
  400. if ($res) {
  401. return undef;
  402. }
  403. else {
  404. return "$res";
  405. }
  406. }
  407. return undef;
  408. }
  409. sub canremove ($$$) {
  410. my ($page, $cgi, $session) = (shift, shift, shift);
  411. if (istranslation($page)) {
  412. return gettext("Can not remove a translation. Removing the master page, ".
  413. "though, removes its translations as well.");
  414. }
  415. return undef;
  416. }
  417. sub canrename ($$@) {
  418. my ($cgi, $session) = (shift, shift);
  419. my %params = @_;
  420. if (istranslation($params{src})) {
  421. my $masterpage = masterpage($params{src});
  422. # Tell the difference between:
  423. # - a translation being renamed as a consequence of its master page
  424. # being renamed, which is allowed
  425. # - a user trying to directly rename a translation, which is forbidden
  426. # by looking for the master page in the list of to-be-renamed pages we
  427. # saved early in the renaming process.
  428. my $orig_torename = $session->param("po_orig_torename");
  429. unless (scalar grep { $_->{src} eq $masterpage } @{$orig_torename}) {
  430. return gettext("Can not rename a translation. Renaming the master page, ".
  431. "though, renames its translations as well.");
  432. }
  433. }
  434. return undef;
  435. }
  436. # As we're previewing or saving a page, the content may have
  437. # changed, so tell the next filter() invocation it must not be lazy.
  438. sub editcontent () {
  439. my %params=@_;
  440. unsetalreadyfiltered($params{page}, $params{page});
  441. return $params{content};
  442. }
  443. sub formbuilder_setup (@) {
  444. my %params=@_;
  445. my $form=$params{form};
  446. my $q=$params{cgi};
  447. return unless defined $form->field("do");
  448. if ($form->field("do") eq "create") {
  449. # Warn the user: new pages must be written in master language.
  450. my $template=template("pocreatepage.tmpl");
  451. $template->param(LANG => $config{po_master_language}{name});
  452. $form->tmpl_param(message => $template->output);
  453. }
  454. elsif ($form->field("do") eq "edit") {
  455. # Remove the rename/remove buttons on slave pages.
  456. # This has to be done after the rename/remove plugins have added
  457. # their buttons, which is why this hook must be run last.
  458. # The canrename/canremove hooks already ensure this is forbidden
  459. # at the backend level, so this is only UI sugar.
  460. if (istranslation($form->field("page"))) {
  461. map {
  462. for (my $i = 0; $i < @{$params{buttons}}; $i++) {
  463. if (@{$params{buttons}}[$i] eq $_) {
  464. delete @{$params{buttons}}[$i];
  465. last;
  466. }
  467. }
  468. } qw(Rename Remove);
  469. }
  470. }
  471. }
  472. sub formbuilder (@) {
  473. my %params=@_;
  474. my $form=$params{form};
  475. my $q=$params{cgi};
  476. return unless defined $form->field("do");
  477. # Do not allow to create pages of type po: they are automatically created.
  478. # The main reason to do so is to bypass the "favor the type of linking page
  479. # on page creation" logic, which is unsuitable when a broken link is clicked
  480. # on a slave (PO) page.
  481. # This cannot be done in the formbuilder_setup hook as the list of types is
  482. # computed later.
  483. if ($form->field("do") eq "create") {
  484. for my $field ($form->field) {
  485. next unless "$field" eq "type";
  486. if ($field->type eq 'select') {
  487. # remove po from the list of types
  488. my @types = grep { $_ ne 'po' } $field->options;
  489. $field->options(\@types) if scalar @types;
  490. }
  491. else {
  492. # make sure the default value is not po;
  493. # does this case actually happen?
  494. debug "po(formbuilder) ".gettext("type field is not select - not implemented yet");
  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. (-e $potfile)
  745. or error("po(refreshpofiles) ".sprintf(gettext("POT file (%s) does not exist"),
  746. $potfile));
  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 (scalar @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. # | PageSpec's
  980. # `----
  981. package IkiWiki::PageSpec;
  982. use warnings;
  983. use strict;
  984. use IkiWiki 2.00;
  985. sub match_istranslation ($;@) {
  986. my $page=shift;
  987. if (IkiWiki::Plugin::po::istranslation($page)) {
  988. return IkiWiki::SuccessReason->new("is a translation page");
  989. }
  990. else {
  991. return IkiWiki::FailReason->new("is not a translation page");
  992. }
  993. }
  994. sub match_istranslatable ($;@) {
  995. my $page=shift;
  996. if (IkiWiki::Plugin::po::istranslatable($page)) {
  997. return IkiWiki::SuccessReason->new("is set as translatable in po_translatable_pages");
  998. }
  999. else {
  1000. return IkiWiki::FailReason->new("is not set as translatable in po_translatable_pages");
  1001. }
  1002. }
  1003. sub match_lang ($$;@) {
  1004. my $page=shift;
  1005. my $wanted=shift;
  1006. my $regexp=IkiWiki::glob2re($wanted);
  1007. my $lang=IkiWiki::Plugin::po::lang($page);
  1008. if ($lang!~/^$regexp$/i) {
  1009. return IkiWiki::FailReason->new("file language is $lang, not $wanted");
  1010. }
  1011. else {
  1012. return IkiWiki::SuccessReason->new("file language is $wanted");
  1013. }
  1014. }
  1015. sub match_currentlang ($$;@) {
  1016. my $page=shift;
  1017. shift;
  1018. my %params=@_;
  1019. return IkiWiki::FailReason->new("no location provided") unless exists $params{location};
  1020. my $currentlang=IkiWiki::Plugin::po::lang($params{location});
  1021. my $lang=IkiWiki::Plugin::po::lang($page);
  1022. if ($lang eq $currentlang) {
  1023. return IkiWiki::SuccessReason->new("file language is the same as current one, i.e. $currentlang");
  1024. }
  1025. else {
  1026. return IkiWiki::FailReason->new("file language is $lang, whereas current language is $currentlang");
  1027. }
  1028. }
  1029. 1