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