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