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