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