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