summaryrefslogtreecommitdiff
path: root/IkiWiki/Plugin/po.pm
blob: a920618faf5fa49ca053b46f1d67c23320ef9443 (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. # Do not allow to create pages of type po: they are automatically created.
  427. # The main reason to do so is to bypass the "favor the type of linking page
  428. # on page creation" logic, which is unsuitable when a broken link is clicked
  429. # on a slave (PO) page.
  430. sub formbuilder (@) {
  431. my %params=@_;
  432. my $form=$params{form};
  433. my $q=$params{cgi};
  434. return unless (defined $form->field("do") && $form->field("do") eq "create");
  435. for my $field ($form->field) {
  436. next unless "$field" eq "type";
  437. if ($field->type eq 'select') {
  438. # remove po from the types list
  439. my @types = grep { $_ ne 'po' } $field->options;
  440. $field->options(\@types) if scalar @types;
  441. }
  442. else {
  443. # make sure the default value is not po;
  444. # does this case actually happen?
  445. debug "po(formbuilder) ".gettext("type field is not select - not implemented yet");
  446. }
  447. }
  448. }
  449. # ,----
  450. # | Injected functions
  451. # `----
  452. # Implement po_link_to 'current' and 'negotiated' settings.
  453. sub mybestlink ($$) {
  454. my $page=shift;
  455. my $link=shift;
  456. my $res=$origsubs{'bestlink'}->(masterpage($page), $link);
  457. if (length $res
  458. && ($config{po_link_to} eq "current" || $config{po_link_to} eq "negotiated")
  459. && istranslatable($res)
  460. && istranslation($page)) {
  461. return $res . "." . lang($page);
  462. }
  463. return $res;
  464. }
  465. sub mybeautify_urlpath ($) {
  466. my $url=shift;
  467. my $res=$origsubs{'beautify_urlpath'}->($url);
  468. if ($config{po_link_to} eq "negotiated") {
  469. $res =~ s!/\Qindex.$config{po_master_language}{code}.$config{htmlext}\E$!/!;
  470. $res =~ s!/\Qindex.$config{htmlext}\E$!/!;
  471. map {
  472. $res =~ s!/\Qindex.$_.$config{htmlext}\E$!/!;
  473. } (keys %{$config{po_slave_languages}});
  474. }
  475. return $res;
  476. }
  477. sub mytargetpage ($$) {
  478. my $page=shift;
  479. my $ext=shift;
  480. if (istranslation($page) || istranslatable($page)) {
  481. my ($masterpage, $lang) = (masterpage($page), lang($page));
  482. if (! $config{usedirs} || $masterpage eq 'index') {
  483. return $masterpage . "." . $lang . "." . $ext;
  484. }
  485. else {
  486. return $masterpage . "/index." . $lang . "." . $ext;
  487. }
  488. }
  489. return $origsubs{'targetpage'}->($page, $ext);
  490. }
  491. sub myurlto ($$;$) {
  492. my $to=shift;
  493. my $from=shift;
  494. my $absolute=shift;
  495. # workaround hard-coded /index.$config{htmlext} in IkiWiki::urlto()
  496. if (! length $to
  497. && $config{po_link_to} eq "current"
  498. && istranslatable('index')) {
  499. return IkiWiki::beautify_urlpath(IkiWiki::baseurl($from) . "index." . lang($from) . ".$config{htmlext}");
  500. }
  501. # avoid using our injected beautify_urlpath if run by cgi_editpage,
  502. # so that one is redirected to the just-edited page rather than to the
  503. # negociated translation; to prevent unnecessary fiddling with caller/inject,
  504. # we only do so when our beautify_urlpath would actually do what we want to
  505. # avoid, i.e. when po_link_to = negotiated
  506. if ($config{po_link_to} eq "negotiated") {
  507. my @caller = caller(1);
  508. my $run_by_editpage = 0;
  509. $run_by_editpage = 1 if (exists $caller[3] && defined $caller[3]
  510. && $caller[3] eq "IkiWiki::cgi_editpage");
  511. inject(name => "IkiWiki::beautify_urlpath", call => $origsubs{'beautify_urlpath'})
  512. if $run_by_editpage;
  513. my $res = $origsubs{'urlto'}->($to,$from,$absolute);
  514. inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath)
  515. if $run_by_editpage;
  516. return $res;
  517. }
  518. else {
  519. return $origsubs{'urlto'}->($to,$from,$absolute)
  520. }
  521. }
  522. sub mynicepagetitle ($;$) {
  523. my ($page, $unescaped) = (shift, shift);
  524. my $res = $origsubs{'nicepagetitle'}->($page, $unescaped);
  525. return $res unless istranslation($page);
  526. return $res unless $config{po_translation_status_in_links};
  527. return $res.' ('.percenttranslated($page).'&nbsp;%)';
  528. }
  529. # ,----
  530. # | Blackboxes for private data
  531. # `----
  532. {
  533. my %filtered;
  534. sub alreadyfiltered($$) {
  535. my $page=shift;
  536. my $destpage=shift;
  537. return ( exists $filtered{$page}{$destpage}
  538. && $filtered{$page}{$destpage} eq 1 );
  539. }
  540. sub setalreadyfiltered($$) {
  541. my $page=shift;
  542. my $destpage=shift;
  543. $filtered{$page}{$destpage}=1;
  544. }
  545. sub unsetalreadyfiltered($$) {
  546. my $page=shift;
  547. my $destpage=shift;
  548. if (exists $filtered{$page}{$destpage}) {
  549. delete $filtered{$page}{$destpage};
  550. }
  551. }
  552. sub resetalreadyfiltered() {
  553. undef %filtered;
  554. }
  555. }
  556. # ,----
  557. # | Helper functions
  558. # `----
  559. sub maybe_add_leading_slash ($;$) {
  560. my $str=shift;
  561. my $add=shift;
  562. $add=1 unless defined $add;
  563. return '/' . $str if $add;
  564. return $str;
  565. }
  566. sub istranslatablefile ($) {
  567. my $file=shift;
  568. return 0 unless defined $file;
  569. return 0 if (defined pagetype($file) && pagetype($file) eq 'po');
  570. return 0 if $file =~ /\.pot$/;
  571. return 1 if pagespec_match(pagename($file), $config{po_translatable_pages});
  572. return;
  573. }
  574. sub istranslatable ($) {
  575. my $page=shift;
  576. $page=~s#^/##;
  577. return 1 if istranslatablefile($pagesources{$page});
  578. return;
  579. }
  580. sub _istranslation ($) {
  581. my $page=shift;
  582. my $hasleadingslash = ($page=~s#^/##);
  583. my $file=$pagesources{$page};
  584. return 0 unless (defined $file
  585. && defined pagetype($file)
  586. && pagetype($file) eq 'po');
  587. return 0 if $file =~ /\.pot$/;
  588. my ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
  589. return 0 unless (defined $masterpage && defined $lang
  590. && length $masterpage && length $lang
  591. && defined $pagesources{$masterpage}
  592. && defined $config{po_slave_languages}{$lang});
  593. return (maybe_add_leading_slash($masterpage, $hasleadingslash), $lang)
  594. if istranslatable($masterpage);
  595. }
  596. sub istranslation ($) {
  597. my $page=shift;
  598. if (1 < (my ($masterpage, $lang) = _istranslation($page))) {
  599. my $hasleadingslash = ($masterpage=~s#^/##);
  600. $translations{$masterpage}{$lang}=$page unless exists $translations{$masterpage}{$lang};
  601. return (maybe_add_leading_slash($masterpage, $hasleadingslash), $lang);
  602. }
  603. return;
  604. }
  605. sub masterpage ($) {
  606. my $page=shift;
  607. if ( 1 < (my ($masterpage, $lang) = _istranslation($page))) {
  608. return $masterpage;
  609. }
  610. return $page;
  611. }
  612. sub lang ($) {
  613. my $page=shift;
  614. if (1 < (my ($masterpage, $lang) = _istranslation($page))) {
  615. return $lang;
  616. }
  617. return $config{po_master_language}{code};
  618. }
  619. sub islanguagecode ($) {
  620. my $code=shift;
  621. return ($code =~ /^[a-z]{2}$/);
  622. }
  623. sub otherlanguage ($$) {
  624. my $page=shift;
  625. my $code=shift;
  626. return masterpage($page) if $code eq $config{po_master_language}{code};
  627. return masterpage($page) . '.' . $code;
  628. }
  629. sub otherlanguages ($) {
  630. my $page=shift;
  631. my %ret;
  632. return \%ret unless (istranslation($page) || istranslatable($page));
  633. my $curlang=lang($page);
  634. foreach my $lang
  635. ($config{po_master_language}{code}, keys %{$config{po_slave_languages}}) {
  636. next if $lang eq $curlang;
  637. $ret{$lang}=otherlanguage($page, $lang);
  638. }
  639. return \%ret;
  640. }
  641. sub potfile ($) {
  642. my $masterfile=shift;
  643. (my $name, my $dir, my $suffix) = fileparse($masterfile, qr/\.[^.]*/);
  644. $dir='' if $dir eq './';
  645. return File::Spec->catpath('', $dir, $name . ".pot");
  646. }
  647. sub pofile ($$) {
  648. my $masterfile=shift;
  649. my $lang=shift;
  650. (my $name, my $dir, my $suffix) = fileparse($masterfile, qr/\.[^.]*/);
  651. $dir='' if $dir eq './';
  652. return File::Spec->catpath('', $dir, $name . "." . $lang . ".po");
  653. }
  654. sub pofiles ($) {
  655. my $masterfile=shift;
  656. return map pofile($masterfile, $_), (keys %{$config{po_slave_languages}});
  657. }
  658. sub refreshpot ($) {
  659. my $masterfile=shift;
  660. my $potfile=potfile($masterfile);
  661. my %options = ("markdown" => (pagetype($masterfile) eq 'mdwn') ? 1 : 0);
  662. my $doc=Locale::Po4a::Chooser::new('text',%options);
  663. $doc->{TT}{utf_mode} = 1;
  664. $doc->{TT}{file_in_charset} = 'utf-8';
  665. $doc->{TT}{file_out_charset} = 'utf-8';
  666. $doc->read($masterfile);
  667. # let's cheat a bit to force porefs option to be passed to Locale::Po4a::Po;
  668. # this is undocument use of internal Locale::Po4a::TransTractor's data,
  669. # compulsory since this module prevents us from using the porefs option.
  670. $doc->{TT}{po_out}=Locale::Po4a::Po->new({ 'porefs' => 'none' });
  671. $doc->{TT}{po_out}->set_charset('utf-8');
  672. # do the actual work
  673. $doc->parse;
  674. IkiWiki::prep_writefile(basename($potfile),dirname($potfile));
  675. $doc->writepo($potfile);
  676. }
  677. sub refreshpofiles ($@) {
  678. my $masterfile=shift;
  679. my @pofiles=@_;
  680. my $potfile=potfile($masterfile);
  681. (-e $potfile)
  682. or error("po(refreshpofiles) ".sprintf(gettext("POT file (%s) does not exist"),
  683. $potfile));
  684. foreach my $pofile (@pofiles) {
  685. IkiWiki::prep_writefile(basename($pofile),dirname($pofile));
  686. if (-e $pofile) {
  687. system("msgmerge", "-U", "--backup=none", $pofile, $potfile) == 0
  688. or error("po(refreshpofiles) ".
  689. sprintf(gettext("failed to update %s"),
  690. $pofile));
  691. }
  692. else {
  693. File::Copy::syscopy($potfile,$pofile)
  694. or error("po(refreshpofiles) ".
  695. sprintf(gettext("failed to copy the POT file to %s"),
  696. $pofile));
  697. }
  698. }
  699. }
  700. sub buildtranslationscache() {
  701. # use istranslation's side-effect
  702. map istranslation($_), (keys %pagesources);
  703. }
  704. sub resettranslationscache() {
  705. undef %translations;
  706. }
  707. sub flushmemoizecache() {
  708. Memoize::flush_cache("istranslatable");
  709. Memoize::flush_cache("_istranslation");
  710. Memoize::flush_cache("percenttranslated");
  711. }
  712. sub urlto_with_orig_beautiful_urlpath($$) {
  713. my $to=shift;
  714. my $from=shift;
  715. inject(name => "IkiWiki::beautify_urlpath", call => $origsubs{'beautify_urlpath'});
  716. my $res=urlto($to, $from);
  717. inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath);
  718. return $res;
  719. }
  720. sub percenttranslated ($) {
  721. my $page=shift;
  722. $page=~s/^\///;
  723. return gettext("N/A") unless istranslation($page);
  724. my $file=srcfile($pagesources{$page});
  725. my $masterfile = srcfile($pagesources{masterpage($page)});
  726. my %options = (
  727. "markdown" => (pagetype($masterfile) eq 'mdwn') ? 1 : 0,
  728. );
  729. my $doc=Locale::Po4a::Chooser::new('text',%options);
  730. $doc->process(
  731. 'po_in_name' => [ $file ],
  732. 'file_in_name' => [ $masterfile ],
  733. 'file_in_charset' => 'utf-8',
  734. 'file_out_charset' => 'utf-8',
  735. ) or error("po(percenttranslated) ".
  736. sprintf(gettext("failed to translate %s"), $page));
  737. my ($percent,$hit,$queries) = $doc->stats();
  738. $percent =~ s/\.[0-9]+$//;
  739. return $percent;
  740. }
  741. sub languagename ($) {
  742. my $code=shift;
  743. return $config{po_master_language}{name}
  744. if $code eq $config{po_master_language}{code};
  745. return $config{po_slave_languages}{$code}
  746. if defined $config{po_slave_languages}{$code};
  747. return;
  748. }
  749. sub otherlanguagesloop ($) {
  750. my $page=shift;
  751. my @ret;
  752. my %otherpages=%{otherlanguages($page)};
  753. while (my ($lang, $otherpage) = each %otherpages) {
  754. if (istranslation($page) && masterpage($page) eq $otherpage) {
  755. push @ret, {
  756. url => urlto_with_orig_beautiful_urlpath($otherpage, $page),
  757. code => $lang,
  758. language => languagename($lang),
  759. master => 1,
  760. };
  761. }
  762. else {
  763. push @ret, {
  764. url => urlto_with_orig_beautiful_urlpath($otherpage, $page),
  765. code => $lang,
  766. language => languagename($lang),
  767. percent => percenttranslated($otherpage),
  768. }
  769. }
  770. }
  771. return sort {
  772. return -1 if $a->{code} eq $config{po_master_language}{code};
  773. return 1 if $b->{code} eq $config{po_master_language}{code};
  774. return $a->{language} cmp $b->{language};
  775. } @ret;
  776. }
  777. sub homepageurl (;$) {
  778. my $page=shift;
  779. return urlto('', $page);
  780. }
  781. sub deletetranslations ($) {
  782. my $deletedmasterfile=shift;
  783. my $deletedmasterpage=pagename($deletedmasterfile);
  784. my @todelete;
  785. map {
  786. my $file = newpagefile($deletedmasterpage.'.'.$_, 'po');
  787. my $absfile = "$config{srcdir}/$file";
  788. if (-e $absfile && ! -l $absfile && ! -d $absfile) {
  789. push @todelete, $file;
  790. }
  791. } keys %{$config{po_slave_languages}};
  792. map {
  793. if ($config{rcs}) {
  794. IkiWiki::rcs_remove($_);
  795. }
  796. else {
  797. IkiWiki::prune("$config{srcdir}/$_");
  798. }
  799. } @todelete;
  800. if (scalar @todelete) {
  801. commit_and_refresh(
  802. gettext("removed obsolete PO files"),
  803. "IkiWiki::Plugin::po::deletetranslations");
  804. }
  805. }
  806. sub commit_and_refresh ($$) {
  807. my ($msg, $author) = (shift, shift);
  808. if ($config{rcs}) {
  809. IkiWiki::disable_commit_hook();
  810. IkiWiki::rcs_commit_staged($msg, $author, "127.0.0.1");
  811. IkiWiki::enable_commit_hook();
  812. IkiWiki::rcs_update();
  813. }
  814. # Reinitialize module's private variables.
  815. resetalreadyfiltered();
  816. resettranslationscache();
  817. flushmemoizecache();
  818. # Trigger a wiki refresh.
  819. require IkiWiki::Render;
  820. # without preliminary saveindex/loadindex, refresh()
  821. # complains about a lot of uninitialized variables
  822. IkiWiki::saveindex();
  823. IkiWiki::loadindex();
  824. IkiWiki::refresh();
  825. IkiWiki::saveindex();
  826. }
  827. # on success, returns the filtered content.
  828. # on error, if $nonfatal, warn and return undef; else, error out.
  829. sub po_to_markup ($$;$) {
  830. my ($page, $content) = (shift, shift);
  831. my $nonfatal = shift;
  832. $content = '' unless defined $content;
  833. $content = decode_utf8(encode_utf8($content));
  834. # CRLF line terminators make poor Locale::Po4a feel bad
  835. $content=~s/\r\n/\n/g;
  836. # There are incompatibilities between some File::Temp versions
  837. # (including 0.18, bundled with Lenny's perl-modules package)
  838. # and others (e.g. 0.20, previously present in the archive as
  839. # a standalone package): under certain circumstances, some
  840. # return a relative filename, whereas others return an absolute one;
  841. # we here use this module in a way that is at least compatible
  842. # with 0.18 and 0.20. Beware, hit'n'run refactorers!
  843. my $infile = new File::Temp(TEMPLATE => "ikiwiki-po-filter-in.XXXXXXXXXX",
  844. DIR => File::Spec->tmpdir,
  845. UNLINK => 1)->filename;
  846. my $outfile = new File::Temp(TEMPLATE => "ikiwiki-po-filter-out.XXXXXXXXXX",
  847. DIR => File::Spec->tmpdir,
  848. UNLINK => 1)->filename;
  849. my $fail = sub ($) {
  850. my $msg = "po(po_to_markup) - $page : " . shift;
  851. if ($nonfatal) {
  852. warn $msg;
  853. return undef;
  854. }
  855. error($msg, sub { unlink $infile, $outfile});
  856. };
  857. writefile(basename($infile), File::Spec->tmpdir, $content)
  858. or return $fail->(sprintf(gettext("failed to write %s"), $infile));
  859. my $masterfile = srcfile($pagesources{masterpage($page)});
  860. my %options = (
  861. "markdown" => (pagetype($masterfile) eq 'mdwn') ? 1 : 0,
  862. );
  863. my $doc=Locale::Po4a::Chooser::new('text',%options);
  864. $doc->process(
  865. 'po_in_name' => [ $infile ],
  866. 'file_in_name' => [ $masterfile ],
  867. 'file_in_charset' => 'utf-8',
  868. 'file_out_charset' => 'utf-8',
  869. ) or return $fail->(gettext("failed to translate"));
  870. $doc->write($outfile)
  871. or return $fail->(sprintf(gettext("failed to write %s"), $outfile));
  872. $content = readfile($outfile)
  873. or return $fail->(sprintf(gettext("failed to read %s"), $outfile));
  874. # Unlinking should happen automatically, thanks to File::Temp,
  875. # but it does not work here, probably because of the way writefile()
  876. # and Locale::Po4a::write() work.
  877. unlink $infile, $outfile;
  878. return $content;
  879. }
  880. # returns a SuccessReason or FailReason object
  881. sub isvalidpo ($) {
  882. my $content = shift;
  883. # NB: we don't use po_to_markup here, since Po4a parser does
  884. # not mind invalid PO content
  885. $content = '' unless defined $content;
  886. $content = decode_utf8(encode_utf8($content));
  887. # There are incompatibilities between some File::Temp versions
  888. # (including 0.18, bundled with Lenny's perl-modules package)
  889. # and others (e.g. 0.20, previously present in the archive as
  890. # a standalone package): under certain circumstances, some
  891. # return a relative filename, whereas others return an absolute one;
  892. # we here use this module in a way that is at least compatible
  893. # with 0.18 and 0.20. Beware, hit'n'run refactorers!
  894. my $infile = new File::Temp(TEMPLATE => "ikiwiki-po-isvalidpo.XXXXXXXXXX",
  895. DIR => File::Spec->tmpdir,
  896. UNLINK => 1)->filename;
  897. my $fail = sub ($) {
  898. my $msg = '[po/isvalidpo] ' . shift;
  899. unlink $infile;
  900. return IkiWiki::FailReason->new("$msg");
  901. };
  902. writefile(basename($infile), File::Spec->tmpdir, $content)
  903. or return $fail->(sprintf(gettext("failed to write %s"), $infile));
  904. my $res = (system("msgfmt", "--check", $infile, "-o", "/dev/null") == 0);
  905. # Unlinking should happen automatically, thanks to File::Temp,
  906. # but it does not work here, probably because of the way writefile()
  907. # and Locale::Po4a::write() work.
  908. unlink $infile;
  909. if ($res) {
  910. return IkiWiki::SuccessReason->new("valid gettext data");
  911. }
  912. return IkiWiki::FailReason->new("invalid gettext data");
  913. }
  914. # ,----
  915. # | PageSpec's
  916. # `----
  917. package IkiWiki::PageSpec;
  918. use warnings;
  919. use strict;
  920. use IkiWiki 2.00;
  921. sub match_istranslation ($;@) {
  922. my $page=shift;
  923. if (IkiWiki::Plugin::po::istranslation($page)) {
  924. return IkiWiki::SuccessReason->new("is a translation page");
  925. }
  926. else {
  927. return IkiWiki::FailReason->new("is not a translation page");
  928. }
  929. }
  930. sub match_istranslatable ($;@) {
  931. my $page=shift;
  932. if (IkiWiki::Plugin::po::istranslatable($page)) {
  933. return IkiWiki::SuccessReason->new("is set as translatable in po_translatable_pages");
  934. }
  935. else {
  936. return IkiWiki::FailReason->new("is not set as translatable in po_translatable_pages");
  937. }
  938. }
  939. sub match_lang ($$;@) {
  940. my $page=shift;
  941. my $wanted=shift;
  942. my $regexp=IkiWiki::glob2re($wanted);
  943. my $lang=IkiWiki::Plugin::po::lang($page);
  944. if ($lang!~/^$regexp$/i) {
  945. return IkiWiki::FailReason->new("file language is $lang, not $wanted");
  946. }
  947. else {
  948. return IkiWiki::SuccessReason->new("file language is $wanted");
  949. }
  950. }
  951. sub match_currentlang ($$;@) {
  952. my $page=shift;
  953. shift;
  954. my %params=@_;
  955. return IkiWiki::FailReason->new("no location provided") unless exists $params{location};
  956. my $currentlang=IkiWiki::Plugin::po::lang($params{location});
  957. my $lang=IkiWiki::Plugin::po::lang($page);
  958. if ($lang eq $currentlang) {
  959. return IkiWiki::SuccessReason->new("file language is the same as current one, i.e. $currentlang");
  960. }
  961. else {
  962. return IkiWiki::FailReason->new("file language is $lang, whereas current language is $currentlang");
  963. }
  964. }
  965. 1