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