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