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