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