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