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