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