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