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