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