summaryrefslogtreecommitdiff
path: root/IkiWiki/Plugin/po.pm
blob: 3503fabc4ae85ec65a7788c8c3345cca955adacf (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. if (istranslation($page)) {
  166. foreach my $destpage (@{$links{$page}}) {
  167. if (istranslatable($destpage)) {
  168. # replace one occurence of $destpage in $links{$page}
  169. # (we only want to replace the one that was added by
  170. # IkiWiki::Plugin::link::scan, other occurences may be
  171. # there for other reasons)
  172. for (my $i=0; $i<@{$links{$page}}; $i++) {
  173. if (@{$links{$page}}[$i] eq $destpage) {
  174. @{$links{$page}}[$i] = $destpage . '.' . lang($page);
  175. last;
  176. }
  177. }
  178. }
  179. }
  180. }
  181. elsif (! istranslatable($page) && ! istranslation($page)) {
  182. foreach my $destpage (@{$links{$page}}) {
  183. if (istranslatable($destpage)) {
  184. # make sure any destpage's translations has
  185. # $page in its backlinks
  186. push @{$links{$page}},
  187. values %{otherlanguages($destpage)};
  188. }
  189. }
  190. }
  191. }
  192. # We use filter to convert PO to the master page's format,
  193. # since the rest of ikiwiki should not work on PO files.
  194. sub filter (@) {
  195. my %params = @_;
  196. my $page = $params{page};
  197. my $destpage = $params{destpage};
  198. my $content = $params{content};
  199. if (istranslation($page) && ! alreadyfiltered($page, $destpage)) {
  200. $content = po_to_markup($page, $content);
  201. setalreadyfiltered($page, $destpage);
  202. }
  203. return $content;
  204. }
  205. sub htmlize (@) {
  206. my %params=@_;
  207. my $page = $params{page};
  208. my $content = $params{content};
  209. # ignore PO files this plugin did not create
  210. return $content unless istranslation($page);
  211. # force content to be htmlize'd as if it was the same type as the master page
  212. return IkiWiki::htmlize($page, $page,
  213. pagetype(srcfile($pagesources{masterpage($page)})),
  214. $content);
  215. }
  216. sub pagetemplate (@) {
  217. my %params=@_;
  218. my $page=$params{page};
  219. my $destpage=$params{destpage};
  220. my $template=$params{template};
  221. my ($masterpage, $lang) = istranslation($page);
  222. if (istranslation($page) && $template->query(name => "percenttranslated")) {
  223. $template->param(percenttranslated => percenttranslated($page));
  224. }
  225. if ($template->query(name => "istranslation")) {
  226. $template->param(istranslation => scalar istranslation($page));
  227. }
  228. if ($template->query(name => "istranslatable")) {
  229. $template->param(istranslatable => istranslatable($page));
  230. }
  231. if ($template->query(name => "HOMEPAGEURL")) {
  232. $template->param(homepageurl => homepageurl($page));
  233. }
  234. if ($template->query(name => "otherlanguages")) {
  235. $template->param(otherlanguages => [otherlanguagesloop($page)]);
  236. map add_depends($page, $_), (values %{otherlanguages($page)});
  237. }
  238. # Rely on IkiWiki::Render's genpage() to decide wether
  239. # a discussion link should appear on $page; this is not
  240. # totally accurate, though: some broken links may be generated
  241. # when cgiurl is disabled.
  242. # This compromise avoids some code duplication, and will probably
  243. # prevent future breakage when ikiwiki internals change.
  244. # Known limitations are preferred to future random bugs.
  245. if ($template->param('discussionlink') && istranslation($page)) {
  246. $template->param('discussionlink' => htmllink(
  247. $page,
  248. $destpage,
  249. $masterpage . '/' . gettext("Discussion"),
  250. noimageinline => 1,
  251. forcesubpage => 0,
  252. linktext => gettext("Discussion"),
  253. ));
  254. }
  255. # Remove broken parentlink to ./index.html on home page's translations.
  256. # It works because this hook has the "last" parameter set, to ensure it
  257. # runs after parentlinks' own pagetemplate hook.
  258. if ($template->param('parentlinks')
  259. && istranslation($page)
  260. && $masterpage eq "index") {
  261. $template->param('parentlinks' => []);
  262. }
  263. } # }}}
  264. # Add the renamed page translations to the list of to-be-renamed pages.
  265. sub renamepages(@) {
  266. my %params = @_;
  267. my %torename = %{$params{torename}};
  268. my $session = $params{session};
  269. # Save the page(s) the user asked to rename, so that our
  270. # canrename hook can tell the difference between:
  271. # - a translation being renamed as a consequence of its master page
  272. # being renamed
  273. # - a user trying to directly rename a translation
  274. # This is why this hook has to be run first, before the list of pages
  275. # to rename is modified by other plugins.
  276. my @orig_torename;
  277. @orig_torename=@{$session->param("po_orig_torename")}
  278. if defined $session->param("po_orig_torename");
  279. push @orig_torename, $torename{src};
  280. $session->param(po_orig_torename => \@orig_torename);
  281. IkiWiki::cgi_savesession($session);
  282. return () unless istranslatable($torename{src});
  283. my @ret;
  284. my %otherpages=%{otherlanguages($torename{src})};
  285. while (my ($lang, $otherpage) = each %otherpages) {
  286. push @ret, {
  287. src => $otherpage,
  288. srcfile => $pagesources{$otherpage},
  289. dest => otherlanguage($torename{dest}, $lang),
  290. destfile => $torename{dest}.".".$lang.".po",
  291. required => 0,
  292. };
  293. }
  294. return @ret;
  295. }
  296. sub mydelete(@) {
  297. my @deleted=@_;
  298. map { deletetranslations($_) } grep istranslatablefile($_), @deleted;
  299. }
  300. sub change(@) {
  301. my @rendered=@_;
  302. # All meta titles are first extracted at scan time, i.e. before we turn
  303. # PO files back into translated markdown; escaping of double-quotes in
  304. # PO files breaks the meta plugin's parsing enough to save ugly titles
  305. # to %pagestate at this time.
  306. #
  307. # Then, at render time, every page's passes on row through the Great
  308. # Rendering Chain (filter->preprocess->linkify->htmlize), and the meta
  309. # plugin's preprocess hook is this time in a position to correctly
  310. # extract the titles from slave pages.
  311. #
  312. # This is, unfortunately, too late: if the page A, linking to the page B,
  313. # is rendered before B, it will display the wrongly-extracted meta title
  314. # as the link text to B.
  315. #
  316. # On the one hand, such a corner case only happens on rebuild: on
  317. # refresh, every rendered page is fixed to contain correct meta titles.
  318. # On the other hand, it can take some time to get every page fixed.
  319. # We therefore re-render every rendered page after a rebuild to fix them
  320. # at once. As this more or less doubles the time needed to rebuild the
  321. # wiki, we do so only when really needed.
  322. if (@rendered
  323. && exists $config{rebuild} && defined $config{rebuild} && $config{rebuild}
  324. && UNIVERSAL::can("IkiWiki::Plugin::meta", "getsetup")
  325. && exists $config{meta_overrides_page_title}
  326. && defined $config{meta_overrides_page_title}
  327. && $config{meta_overrides_page_title}) {
  328. debug(sprintf(gettext("re-rendering all pages to fix meta titles")));
  329. resetalreadyfiltered();
  330. require IkiWiki::Render;
  331. foreach my $file (@rendered) {
  332. debug(sprintf(gettext("rendering %s"), $file));
  333. IkiWiki::render($file);
  334. }
  335. }
  336. my $updated_po_files=0;
  337. # Refresh/create POT and PO files as needed.
  338. foreach my $file (grep {istranslatablefile($_)} @rendered) {
  339. my $page=pagename($file);
  340. my $masterfile=srcfile($file);
  341. my $updated_pot_file=0;
  342. # Only refresh Pot file if it does not exist, or if
  343. # $pagesources{$page} was changed: don't if only the HTML was
  344. # refreshed, e.g. because of a dependency.
  345. if ((grep { $_ eq $pagesources{$page} } @origneedsbuild)
  346. || ! -e potfile($masterfile)) {
  347. refreshpot($masterfile);
  348. $updated_pot_file=1;
  349. }
  350. my @pofiles;
  351. map {
  352. push @pofiles, $_ if ($updated_pot_file || ! -e $_);
  353. } (pofiles($masterfile));
  354. if (@pofiles) {
  355. refreshpofiles($masterfile, @pofiles);
  356. map { IkiWiki::rcs_add($_) } @pofiles if $config{rcs};
  357. $updated_po_files=1;
  358. }
  359. }
  360. if ($updated_po_files) {
  361. commit_and_refresh(
  362. gettext("updated PO files"),
  363. "IkiWiki::Plugin::po::change");
  364. }
  365. }
  366. sub checkcontent (@) {
  367. my %params=@_;
  368. if (istranslation($params{page})) {
  369. my $res = isvalidpo($params{content});
  370. if ($res) {
  371. return undef;
  372. }
  373. else {
  374. return "$res";
  375. }
  376. }
  377. return undef;
  378. }
  379. sub canremove (@) {
  380. my %params = @_;
  381. if (istranslation($params{page})) {
  382. return gettext("Can not remove a translation. Removing the master page, ".
  383. "though, removes its translations as well.");
  384. }
  385. return undef;
  386. }
  387. sub canrename (@) {
  388. my %params = @_;
  389. my $session = $params{session};
  390. if (istranslation($params{src})) {
  391. my $masterpage = masterpage($params{src});
  392. # Tell the difference between:
  393. # - a translation being renamed as a consequence of its master page
  394. # being renamed, which is allowed
  395. # - a user trying to directly rename a translation, which is forbidden
  396. # by looking for the master page in the list of to-be-renamed pages we
  397. # saved early in the renaming process.
  398. my $orig_torename = $session->param("po_orig_torename");
  399. unless (grep { $_ eq $masterpage } @{$orig_torename}) {
  400. return gettext("Can not rename a translation. Renaming the master page, ".
  401. "though, renames its translations as well.");
  402. }
  403. }
  404. return undef;
  405. }
  406. # As we're previewing or saving a page, the content may have
  407. # changed, so tell the next filter() invocation it must not be lazy.
  408. sub editcontent () {
  409. my %params=@_;
  410. unsetalreadyfiltered($params{page}, $params{page});
  411. return $params{content};
  412. }
  413. sub formbuilder_setup (@) {
  414. my %params=@_;
  415. my $form=$params{form};
  416. my $q=$params{cgi};
  417. return unless defined $form->field("do");
  418. if ($form->field("do") eq "create") {
  419. # Warn the user: new pages must be written in master language.
  420. my $template=template("pocreatepage.tmpl");
  421. $template->param(LANG => $config{po_master_language}{name});
  422. $form->tmpl_param(message => $template->output);
  423. }
  424. elsif ($form->field("do") eq "edit") {
  425. # Remove the rename/remove buttons on slave pages.
  426. # This has to be done after the rename/remove plugins have added
  427. # their buttons, which is why this hook must be run last.
  428. # The canrename/canremove hooks already ensure this is forbidden
  429. # at the backend level, so this is only UI sugar.
  430. if (istranslation($form->field("page"))) {
  431. map {
  432. for (my $i = 0; $i < @{$params{buttons}}; $i++) {
  433. if (@{$params{buttons}}[$i] eq $_) {
  434. delete @{$params{buttons}}[$i];
  435. last;
  436. }
  437. }
  438. } qw(Rename Remove);
  439. }
  440. }
  441. }
  442. sub formbuilder (@) {
  443. my %params=@_;
  444. my $form=$params{form};
  445. my $q=$params{cgi};
  446. return unless defined $form->field("do");
  447. # Do not allow to create pages of type po: they are automatically created.
  448. # The main reason to do so is to bypass the "favor the type of linking page
  449. # on page creation" logic, which is unsuitable when a broken link is clicked
  450. # on a slave (PO) page.
  451. # This cannot be done in the formbuilder_setup hook as the list of types is
  452. # computed later.
  453. if ($form->field("do") eq "create") {
  454. foreach my $field ($form->field) {
  455. next unless "$field" eq "type";
  456. if ($field->type eq 'select') {
  457. # remove po from the list of types
  458. my @types = grep { $_ ne 'po' } $field->options;
  459. $field->options(\@types) if @types;
  460. }
  461. }
  462. }
  463. }
  464. # ,----
  465. # | Injected functions
  466. # `----
  467. # Implement po_link_to 'current' and 'negotiated' settings.
  468. sub mybestlink ($$) {
  469. my $page=shift;
  470. my $link=shift;
  471. my $res=$origsubs{'bestlink'}->(masterpage($page), $link);
  472. if (length $res
  473. && ($config{po_link_to} eq "current" || $config{po_link_to} eq "negotiated")
  474. && istranslatable($res)
  475. && istranslation($page)) {
  476. return $res . "." . lang($page);
  477. }
  478. return $res;
  479. }
  480. sub mybeautify_urlpath ($) {
  481. my $url=shift;
  482. my $res=$origsubs{'beautify_urlpath'}->($url);
  483. if ($config{po_link_to} eq "negotiated") {
  484. $res =~ s!/\Qindex.$config{po_master_language}{code}.$config{htmlext}\E$!/!;
  485. $res =~ s!/\Qindex.$config{htmlext}\E$!/!;
  486. map {
  487. $res =~ s!/\Qindex.$_.$config{htmlext}\E$!/!;
  488. } (keys %{$config{po_slave_languages}});
  489. }
  490. return $res;
  491. }
  492. sub mytargetpage ($$) {
  493. my $page=shift;
  494. my $ext=shift;
  495. if (istranslation($page) || istranslatable($page)) {
  496. my ($masterpage, $lang) = (masterpage($page), lang($page));
  497. if (! $config{usedirs} || $masterpage eq 'index') {
  498. return $masterpage . "." . $lang . "." . $ext;
  499. }
  500. else {
  501. return $masterpage . "/index." . $lang . "." . $ext;
  502. }
  503. }
  504. return $origsubs{'targetpage'}->($page, $ext);
  505. }
  506. sub myurlto ($$;$) {
  507. my $to=shift;
  508. my $from=shift;
  509. my $absolute=shift;
  510. # workaround hard-coded /index.$config{htmlext} in IkiWiki::urlto()
  511. if (! length $to
  512. && $config{po_link_to} eq "current"
  513. && istranslatable('index')) {
  514. return IkiWiki::beautify_urlpath(IkiWiki::baseurl($from) . "index." . lang($from) . ".$config{htmlext}");
  515. }
  516. # avoid using our injected beautify_urlpath if run by cgi_editpage,
  517. # so that one is redirected to the just-edited page rather than to the
  518. # negociated translation; to prevent unnecessary fiddling with caller/inject,
  519. # we only do so when our beautify_urlpath would actually do what we want to
  520. # avoid, i.e. when po_link_to = negotiated
  521. if ($config{po_link_to} eq "negotiated") {
  522. my @caller = caller(1);
  523. my $run_by_editpage = 0;
  524. $run_by_editpage = 1 if (exists $caller[3] && defined $caller[3]
  525. && $caller[3] eq "IkiWiki::cgi_editpage");
  526. inject(name => "IkiWiki::beautify_urlpath", call => $origsubs{'beautify_urlpath'})
  527. if $run_by_editpage;
  528. my $res = $origsubs{'urlto'}->($to,$from,$absolute);
  529. inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath)
  530. if $run_by_editpage;
  531. return $res;
  532. }
  533. else {
  534. return $origsubs{'urlto'}->($to,$from,$absolute)
  535. }
  536. }
  537. sub mycgiurl (@) {
  538. my %params=@_;
  539. # slave pages have no subpages
  540. if (istranslation($params{'from'})) {
  541. $params{'from'} = masterpage($params{'from'});
  542. }
  543. return $origsubs{'cgiurl'}->(%params);
  544. }
  545. # ,----
  546. # | Blackboxes for private data
  547. # `----
  548. {
  549. my %filtered;
  550. sub alreadyfiltered($$) {
  551. my $page=shift;
  552. my $destpage=shift;
  553. return exists $filtered{$page}{$destpage}
  554. && $filtered{$page}{$destpage} eq 1;
  555. }
  556. sub setalreadyfiltered($$) {
  557. my $page=shift;
  558. my $destpage=shift;
  559. $filtered{$page}{$destpage}=1;
  560. }
  561. sub unsetalreadyfiltered($$) {
  562. my $page=shift;
  563. my $destpage=shift;
  564. if (exists $filtered{$page}{$destpage}) {
  565. delete $filtered{$page}{$destpage};
  566. }
  567. }
  568. sub resetalreadyfiltered() {
  569. undef %filtered;
  570. }
  571. }
  572. # ,----
  573. # | Helper functions
  574. # `----
  575. sub maybe_add_leading_slash ($;$) {
  576. my $str=shift;
  577. my $add=shift;
  578. $add=1 unless defined $add;
  579. return '/' . $str if $add;
  580. return $str;
  581. }
  582. sub istranslatablefile ($) {
  583. my $file=shift;
  584. return 0 unless defined $file;
  585. return 0 if defined pagetype($file) && pagetype($file) eq 'po';
  586. return 0 if $file =~ /\.pot$/;
  587. return 0 unless -e "$config{srcdir}/$file"; # underlay dirs may be read-only
  588. return 1 if pagespec_match(pagename($file), $config{po_translatable_pages});
  589. return;
  590. }
  591. sub istranslatable ($) {
  592. my $page=shift;
  593. $page=~s#^/##;
  594. return 1 if istranslatablefile($pagesources{$page});
  595. return;
  596. }
  597. sub _istranslation ($) {
  598. my $page=shift;
  599. $page='' unless defined $page && length $page;
  600. my $hasleadingslash = ($page=~s#^/##);
  601. my $file=$pagesources{$page};
  602. return 0 unless defined $file
  603. && defined pagetype($file)
  604. && pagetype($file) eq 'po';
  605. return 0 if $file =~ /\.pot$/;
  606. my ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
  607. return 0 unless defined $masterpage && defined $lang
  608. && length $masterpage && length $lang
  609. && defined $pagesources{$masterpage}
  610. && defined $config{po_slave_languages}{$lang};
  611. return (maybe_add_leading_slash($masterpage, $hasleadingslash), $lang)
  612. if istranslatable($masterpage);
  613. }
  614. sub istranslation ($) {
  615. my $page=shift;
  616. if (1 < (my ($masterpage, $lang) = _istranslation($page))) {
  617. my $hasleadingslash = ($masterpage=~s#^/##);
  618. $translations{$masterpage}{$lang}=$page unless exists $translations{$masterpage}{$lang};
  619. return (maybe_add_leading_slash($masterpage, $hasleadingslash), $lang);
  620. }
  621. return "";
  622. }
  623. sub masterpage ($) {
  624. my $page=shift;
  625. if ( 1 < (my ($masterpage, $lang) = _istranslation($page))) {
  626. return $masterpage;
  627. }
  628. return $page;
  629. }
  630. sub lang ($) {
  631. my $page=shift;
  632. if (1 < (my ($masterpage, $lang) = _istranslation($page))) {
  633. return $lang;
  634. }
  635. return $config{po_master_language}{code};
  636. }
  637. sub islanguagecode ($) {
  638. my $code=shift;
  639. return $code =~ /^[a-z]{2}$/;
  640. }
  641. sub otherlanguage ($$) {
  642. my $page=shift;
  643. my $code=shift;
  644. return masterpage($page) if $code eq $config{po_master_language}{code};
  645. return masterpage($page) . '.' . $code;
  646. }
  647. sub otherlanguages ($) {
  648. my $page=shift;
  649. my %ret;
  650. return \%ret unless istranslation($page) || istranslatable($page);
  651. my $curlang=lang($page);
  652. foreach my $lang
  653. ($config{po_master_language}{code}, keys %{$config{po_slave_languages}}) {
  654. next if $lang eq $curlang;
  655. $ret{$lang}=otherlanguage($page, $lang);
  656. }
  657. return \%ret;
  658. }
  659. sub potfile ($) {
  660. my $masterfile=shift;
  661. (my $name, my $dir, my $suffix) = fileparse($masterfile, qr/\.[^.]*/);
  662. $dir='' if $dir eq './';
  663. return File::Spec->catpath('', $dir, $name . ".pot");
  664. }
  665. sub pofile ($$) {
  666. my $masterfile=shift;
  667. my $lang=shift;
  668. (my $name, my $dir, my $suffix) = fileparse($masterfile, qr/\.[^.]*/);
  669. $dir='' if $dir eq './';
  670. return File::Spec->catpath('', $dir, $name . "." . $lang . ".po");
  671. }
  672. sub pofiles ($) {
  673. my $masterfile=shift;
  674. return map pofile($masterfile, $_), (keys %{$config{po_slave_languages}});
  675. }
  676. sub refreshpot ($) {
  677. my $masterfile=shift;
  678. my $potfile=potfile($masterfile);
  679. my %options = ("markdown" => (pagetype($masterfile) eq 'mdwn') ? 1 : 0);
  680. my $doc=Locale::Po4a::Chooser::new('text',%options);
  681. $doc->{TT}{utf_mode} = 1;
  682. $doc->{TT}{file_in_charset} = 'utf-8';
  683. $doc->{TT}{file_out_charset} = 'utf-8';
  684. $doc->read($masterfile);
  685. # let's cheat a bit to force porefs option to be passed to Locale::Po4a::Po;
  686. # this is undocument use of internal Locale::Po4a::TransTractor's data,
  687. # compulsory since this module 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