summaryrefslogtreecommitdiff
path: root/IkiWiki/Plugin/po.pm
blob: 1b313a97931eb23df15bb3a4a5d169b9ba5d432f (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 the occurence of $destpage in $links{$page}
  184. for (my $i=0; $i<@{$links{$page}}; $i++) {
  185. if (@{$links{$page}}[$i] eq $destpage) {
  186. @{$links{$page}}[$i] = $destpage . '.' . lang($page);
  187. last;
  188. }
  189. }
  190. }
  191. }
  192. }
  193. elsif (! istranslatable($page) && ! istranslation($page)) {
  194. foreach my $destpage (@{$links{$page}}) {
  195. if (istranslatable($destpage)) {
  196. # make sure any destpage's translations has
  197. # $page in its backlinks
  198. push @{$links{$page}},
  199. values %{otherlanguages($destpage)};
  200. }
  201. }
  202. }
  203. }
  204. # We use filter to convert PO to the master page's format,
  205. # since the rest of ikiwiki should not work on PO files.
  206. sub filter (@) {
  207. my %params = @_;
  208. my $page = $params{page};
  209. my $destpage = $params{destpage};
  210. my $content = $params{content};
  211. if (istranslation($page) && ! alreadyfiltered($page, $destpage)) {
  212. $content = po_to_markup($page, $content);
  213. setalreadyfiltered($page, $destpage);
  214. }
  215. return $content;
  216. }
  217. sub htmlize (@) {
  218. my %params=@_;
  219. my $page = $params{page};
  220. my $content = $params{content};
  221. # ignore PO files this plugin did not create
  222. return $content unless istranslation($page);
  223. # force content to be htmlize'd as if it was the same type as the master page
  224. return IkiWiki::htmlize($page, $page,
  225. pagetype(srcfile($pagesources{masterpage($page)})),
  226. $content);
  227. }
  228. sub pagetemplate (@) {
  229. my %params=@_;
  230. my $page=$params{page};
  231. my $destpage=$params{destpage};
  232. my $template=$params{template};
  233. my ($masterpage, $lang) = istranslation($page);
  234. if (istranslation($page) && $template->query(name => "percenttranslated")) {
  235. $template->param(percenttranslated => percenttranslated($page));
  236. }
  237. if ($template->query(name => "istranslation")) {
  238. $template->param(istranslation => scalar istranslation($page));
  239. }
  240. if ($template->query(name => "istranslatable")) {
  241. $template->param(istranslatable => istranslatable($page));
  242. }
  243. if ($template->query(name => "HOMEPAGEURL")) {
  244. $template->param(homepageurl => homepageurl($page));
  245. }
  246. if ($template->query(name => "otherlanguages")) {
  247. $template->param(otherlanguages => [otherlanguagesloop($page)]);
  248. map add_depends($page, $_), (values %{otherlanguages($page)});
  249. }
  250. if ($config{discussion} && istranslation($page)) {
  251. if ($page !~ /.*\/\Q$config{discussionpage}\E$/i &&
  252. (length $config{cgiurl} ||
  253. exists $links{$masterpage."/".lc($config{discussionpage})})) {
  254. $template->param('discussionlink' => htmllink(
  255. $page,
  256. $destpage,
  257. $masterpage . '/' . $config{discussionpage},
  258. noimageinline => 1,
  259. forcesubpage => 0,
  260. linktext => $config{discussionpage},
  261. ));
  262. }
  263. }
  264. # Remove broken parentlink to ./index.html on home page's translations.
  265. # It works because this hook has the "last" parameter set, to ensure it
  266. # runs after parentlinks' own pagetemplate hook.
  267. if ($template->param('parentlinks')
  268. && istranslation($page)
  269. && $masterpage eq "index") {
  270. $template->param('parentlinks' => []);
  271. }
  272. if (ishomepage($page) && $template->query(name => "title")) {
  273. $template->param(title => $config{wikiname});
  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. my $res=$origsubs{'bestlink'}->(masterpage($page), $link);
  488. if (length $res
  489. && ($config{po_link_to} eq "current" || $config{po_link_to} eq "negotiated")
  490. && istranslatable($res)
  491. && istranslation($page)) {
  492. return $res . "." . lang($page);
  493. }
  494. return $res;
  495. }
  496. sub mybeautify_urlpath ($) {
  497. my $url=shift;
  498. my $res=$origsubs{'beautify_urlpath'}->($url);
  499. if ($config{po_link_to} eq "negotiated") {
  500. $res =~ s!/\Qindex.$config{po_master_language}{code}.$config{htmlext}\E$!/!;
  501. $res =~ s!/\Qindex.$config{htmlext}\E$!/!;
  502. map {
  503. $res =~ s!/\Qindex.$_.$config{htmlext}\E$!/!;
  504. } (keys %{$config{po_slave_languages}});
  505. }
  506. return $res;
  507. }
  508. sub mytargetpage ($$) {
  509. my $page=shift;
  510. my $ext=shift;
  511. if (istranslation($page) || istranslatable($page)) {
  512. my ($masterpage, $lang) = (masterpage($page), lang($page));
  513. if (! $config{usedirs} || $masterpage eq 'index') {
  514. return $masterpage . "." . $lang . "." . $ext;
  515. }
  516. else {
  517. return $masterpage . "/index." . $lang . "." . $ext;
  518. }
  519. }
  520. return $origsubs{'targetpage'}->($page, $ext);
  521. }
  522. sub myurlto ($$;$) {
  523. my $to=shift;
  524. my $from=shift;
  525. my $absolute=shift;
  526. # workaround hard-coded /index.$config{htmlext} in IkiWiki::urlto()
  527. if (! length $to
  528. && $config{po_link_to} eq "current"
  529. && istranslatable('index')) {
  530. return IkiWiki::beautify_urlpath(IkiWiki::baseurl($from) . "index." . lang($from) . ".$config{htmlext}");
  531. }
  532. # avoid using our injected beautify_urlpath if run by cgi_editpage,
  533. # so that one is redirected to the just-edited page rather than to the
  534. # negociated translation; to prevent unnecessary fiddling with caller/inject,
  535. # we only do so when our beautify_urlpath would actually do what we want to
  536. # avoid, i.e. when po_link_to = negotiated.
  537. # also avoid doing so when run by cgi_goto, so that the links on recentchanges
  538. # page actually lead to the exact page they pretend to.
  539. if ($config{po_link_to} eq "negotiated") {
  540. my @caller = caller(1);
  541. my $use_orig = 0;
  542. $use_orig = 1 if (exists $caller[3] && defined $caller[3]
  543. && ($caller[3] eq "IkiWiki::cgi_editpage" ||
  544. $caller[3] eq "IkiWiki::Plugin::goto::cgi_goto")
  545. );
  546. inject(name => "IkiWiki::beautify_urlpath", call => $origsubs{'beautify_urlpath'})
  547. if $use_orig;
  548. my $res = $origsubs{'urlto'}->($to,$from,$absolute);
  549. inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath)
  550. if $use_orig;
  551. return $res;
  552. }
  553. else {
  554. return $origsubs{'urlto'}->($to,$from,$absolute)
  555. }
  556. }
  557. sub mycgiurl (@) {
  558. my %params=@_;
  559. # slave pages have no subpages
  560. if (istranslation($params{'from'})) {
  561. $params{'from'} = masterpage($params{'from'});
  562. }
  563. return $origsubs{'cgiurl'}->(%params);
  564. }
  565. # ,----
  566. # | Blackboxes for private data
  567. # `----
  568. {
  569. my %filtered;
  570. sub alreadyfiltered($$) {
  571. my $page=shift;
  572. my $destpage=shift;
  573. return exists $filtered{$page}{$destpage}
  574. && $filtered{$page}{$destpage} eq 1;
  575. }
  576. sub setalreadyfiltered($$) {
  577. my $page=shift;
  578. my $destpage=shift;
  579. $filtered{$page}{$destpage}=1;
  580. }
  581. sub unsetalreadyfiltered($$) {
  582. my $page=shift;
  583. my $destpage=shift;
  584. if (exists $filtered{$page}{$destpage}) {
  585. delete $filtered{$page}{$destpage};
  586. }
  587. }
  588. sub resetalreadyfiltered() {
  589. undef %filtered;
  590. }
  591. }
  592. # ,----
  593. # | Helper functions
  594. # `----
  595. sub maybe_add_leading_slash ($;$) {
  596. my $str=shift;
  597. my $add=shift;
  598. $add=1 unless defined $add;
  599. return '/' . $str if $add;
  600. return $str;
  601. }
  602. sub istranslatablefile ($) {
  603. my $file=shift;
  604. return 0 unless defined $file;
  605. my $type=pagetype($file);
  606. return 0 if ! defined $type || $type eq 'po';
  607. return 0 if $file =~ /\.pot$/;
  608. return 1 if pagespec_match(pagename($file), $config{po_translatable_pages});
  609. return;
  610. }
  611. sub istranslatable ($) {
  612. my $page=shift;
  613. $page=~s#^/##;
  614. return 1 if istranslatablefile($pagesources{$page});
  615. return;
  616. }
  617. sub _istranslation ($) {
  618. my $page=shift;
  619. $page='' unless defined $page && length $page;
  620. my $hasleadingslash = ($page=~s#^/##);
  621. my $file=$pagesources{$page};
  622. return 0 unless defined $file
  623. && defined pagetype($file)
  624. && pagetype($file) eq 'po';
  625. return 0 if $file =~ /\.pot$/;
  626. my ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
  627. return 0 unless defined $masterpage && defined $lang
  628. && length $masterpage && length $lang
  629. && defined $pagesources{$masterpage}
  630. && defined $config{po_slave_languages}{$lang};
  631. return (maybe_add_leading_slash($masterpage, $hasleadingslash), $lang)
  632. if istranslatable($masterpage);
  633. }
  634. sub istranslation ($) {
  635. my $page=shift;
  636. if (1 < (my ($masterpage, $lang) = _istranslation($page))) {
  637. my $hasleadingslash = ($masterpage=~s#^/##);
  638. $translations{$masterpage}{$lang}=$page unless exists $translations{$masterpage}{$lang};
  639. return (maybe_add_leading_slash($masterpage, $hasleadingslash), $lang);
  640. }
  641. return "";
  642. }
  643. sub masterpage ($) {
  644. my $page=shift;
  645. if ( 1 < (my ($masterpage, $lang) = _istranslation($page))) {
  646. return $masterpage;
  647. }
  648. return $page;
  649. }
  650. sub lang ($) {
  651. my $page=shift;
  652. if (1 < (my ($masterpage, $lang) = _istranslation($page))) {
  653. return $lang;
  654. }
  655. return $config{po_master_language}{code};
  656. }
  657. sub islanguagecode ($) {
  658. my $code=shift;
  659. return $code =~ /^[a-z]{2}$/;
  660. }
  661. sub otherlanguage ($$) {
  662. my $page=shift;
  663. my $code=shift;
  664. return masterpage($page) if $code eq $config{po_master_language}{code};
  665. return masterpage($page) . '.' . $code;
  666. }
  667. sub otherlanguages ($) {
  668. my $page=shift;
  669. my %ret;
  670. return \%ret unless istranslation($page) || istranslatable($page);
  671. my $curlang=lang($page);
  672. foreach my $lang
  673. ($config{po_master_language}{code}, keys %{$config{po_slave_languages}}) {
  674. next if $lang eq $curlang;
  675. $ret{$lang}=otherlanguage($page, $lang);
  676. }
  677. return \%ret;
  678. }
  679. sub potfile ($) {
  680. my $masterfile=shift;
  681. (my $name, my $dir, my $suffix) = fileparse($masterfile, qr/\.[^.]*/);
  682. $dir='' if $dir eq './';
  683. return File::Spec->catpath('', $dir, $name . ".pot");
  684. }
  685. sub pofile ($$) {
  686. my $masterfile=shift;
  687. my $lang=shift;
  688. (my $name, my $dir, my $suffix) = fileparse($masterfile, qr/\.[^.]*/);
  689. $dir='' if $dir eq './';
  690. return File::Spec->catpath('', $dir, $name . "." . $lang . ".po");
  691. }
  692. sub pofiles ($) {
  693. my $masterfile=shift;
  694. return map pofile($masterfile, $_), (keys %{$config{po_slave_languages}});
  695. }
  696. sub refreshpot ($) {
  697. my $masterfile=shift;
  698. my $potfile=potfile($masterfile);
  699. my %options = ("markdown" => (pagetype($masterfile) eq 'mdwn') ? 1 : 0);
  700. my $doc=Locale::Po4a::Chooser::new('text',%options);
  701. $doc->{TT}{utf_mode} = 1;
  702. $doc->{TT}{file_in_charset} = 'utf-8';
  703. $doc->{TT}{file_out_charset} = 'utf-8';
  704. $doc->read($masterfile);
  705. # let's cheat a bit to force porefs option to be passed to
  706. # Locale::Po4a::Po; this is undocument use of internal
  707. # Locale::Po4a::TransTractor's data, compulsory since this module
  708. # prevents us from using the porefs option.
  709. $doc->{TT}{po_out}=Locale::Po4a::Po->new({ 'porefs' => 'none' });
  710. $doc->{TT}{po_out}->set_charset('utf-8');
  711. # do the actual work
  712. $doc->parse;
  713. IkiWiki::prep_writefile(basename($potfile),dirname($potfile));
  714. $doc->writepo($potfile);
  715. }
  716. sub refreshpofiles ($@) {
  717. my $masterfile=shift;
  718. my @pofiles=@_;
  719. my $potfile=potfile($masterfile);
  720. if (! -e $potfile) {
  721. error("po(refreshpofiles) ".sprintf(gettext("POT file (%s) does not exist"), $potfile));
  722. }
  723. foreach my $pofile (@pofiles) {
  724. IkiWiki::prep_writefile(basename($pofile),dirname($pofile));
  725. if (! -e $pofile) {
  726. # If the po file exists in an underlay, copy it
  727. # from there.
  728. my ($pobase)=$pofile=~/^\Q$config{srcdir}\E\/?(.*)$/;
  729. foreach my $dir (@{$config{underlaydirs}}) {
  730. if (-e "$dir/$pobase") {
  731. File::Copy::syscopy("$dir/$pobase",$pofile)
  732. or error("po(refreshpofiles) ".
  733. sprintf(gettext("failed to copy underlay PO file to %s"),
  734. $pofile));
  735. }
  736. }
  737. }
  738. if (-e $pofile) {
  739. system("msgmerge", "--previous", "-q", "-U", "--backup=none", $pofile, $potfile) == 0
  740. or error("po(refreshpofiles) ".
  741. sprintf(gettext("failed to update %s"),
  742. $pofile));
  743. }
  744. else {
  745. File::Copy::syscopy($potfile,$pofile)
  746. or error("po(refreshpofiles) ".
  747. sprintf(gettext("failed to copy the POT file to %s"),
  748. $pofile));
  749. }
  750. }
  751. }
  752. sub buildtranslationscache() {
  753. # use istranslation's side-effect
  754. map istranslation($_), (keys %pagesources);
  755. }
  756. sub resettranslationscache() {
  757. undef %translations;
  758. }
  759. sub flushmemoizecache() {
  760. Memoize::flush_cache("istranslatable");
  761. Memoize::flush_cache("_istranslation");
  762. Memoize::flush_cache("percenttranslated");
  763. }
  764. sub urlto_with_orig_beautiful_urlpath($$) {
  765. my $to=shift;
  766. my $from=shift;
  767. inject(name => "IkiWiki::beautify_urlpath", call => $origsubs{'beautify_urlpath'});
  768. my $res=urlto($to, $from);
  769. inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath);
  770. return $res;
  771. }
  772. sub percenttranslated ($) {
  773. my $page=shift;
  774. $page=~s/^\///;
  775. return gettext("N/A") unless istranslation($page);
  776. my $file=srcfile($pagesources{$page});
  777. my $masterfile = srcfile($pagesources{masterpage($page)});
  778. my %options = (
  779. "markdown" => (pagetype($masterfile) eq 'mdwn') ? 1 : 0,
  780. );
  781. my $doc=Locale::Po4a::Chooser::new('text',%options);
  782. $doc->process(
  783. 'po_in_name' => [ $file ],
  784. 'file_in_name' => [ $masterfile ],
  785. 'file_in_charset' => 'utf-8',
  786. 'file_out_charset' => 'utf-8',
  787. ) or error("po(percenttranslated) ".
  788. sprintf(gettext("failed to translate %s"), $page));
  789. my ($percent,$hit,$queries) = $doc->stats();
  790. $percent =~ s/\.[0-9]+$//;
  791. return $percent;
  792. }
  793. sub languagename ($) {
  794. my $code=shift;
  795. return $config{po_master_language}{name}
  796. if $code eq $config{po_master_language}{code};
  797. return $config{po_slave_languages}{$code}
  798. if defined $config{po_slave_languages}{$code};
  799. return;
  800. }
  801. sub otherlanguagesloop ($) {
  802. my $page=shift;
  803. my @ret;
  804. my %otherpages=%{otherlanguages($page)};
  805. while (my ($lang, $otherpage) = each %otherpages) {
  806. if (istranslation($page) && masterpage($page) eq $otherpage) {
  807. push @ret, {
  808. url => urlto_with_orig_beautiful_urlpath($otherpage, $page),
  809. code => $lang,
  810. language => languagename($lang),
  811. master => 1,
  812. };
  813. }
  814. elsif (istranslation($otherpage)) {
  815. push @ret, {
  816. url => urlto_with_orig_beautiful_urlpath($otherpage, $page),
  817. code => $lang,
  818. language => languagename($lang),
  819. percent => percenttranslated($otherpage),
  820. }
  821. }
  822. }
  823. return sort {
  824. return -1 if $a->{code} eq $config{po_master_language}{code};
  825. return 1 if $b->{code} eq $config{po_master_language}{code};
  826. return $a->{language} cmp $b->{language};
  827. } @ret;
  828. }
  829. sub homepageurl (;$) {
  830. my $page=shift;
  831. return urlto('', $page);
  832. }
  833. sub ishomepage ($) {
  834. my $page = shift;
  835. return 1 if $page eq 'index';
  836. map { return 1 if $page eq 'index.'.$_ } keys %{$config{po_slave_languages}};
  837. return undef;
  838. }
  839. sub deletetranslations ($) {
  840. my $deletedmasterfile=shift;
  841. my $deletedmasterpage=pagename($deletedmasterfile);
  842. my @todelete;
  843. map {
  844. my $file = newpagefile($deletedmasterpage.'.'.$_, 'po');
  845. my $absfile = "$config{srcdir}/$file";
  846. if (-e $absfile && ! -l $absfile && ! -d $absfile) {
  847. push @todelete, $file;
  848. }
  849. } keys %{$config{po_slave_languages}};
  850. map {
  851. if ($config{rcs}) {
  852. IkiWiki::rcs_remove($_);
  853. }
  854. else {
  855. IkiWiki::prune("$config{srcdir}/$_");
  856. }
  857. } @todelete;
  858. if (@todelete) {
  859. commit_and_refresh(
  860. gettext("removed obsolete PO files"),
  861. "IkiWiki::Plugin::po::deletetranslations");
  862. }
  863. }
  864. sub commit_and_refresh ($$) {
  865. my ($msg, $author) = (shift, shift);
  866. if ($config{rcs}) {
  867. IkiWiki::disable_commit_hook();
  868. IkiWiki::rcs_commit_staged($msg, $author, "127.0.0.1");
  869. IkiWiki::enable_commit_hook();
  870. IkiWiki::rcs_update();
  871. }
  872. # Reinitialize module's private variables.
  873. resetalreadyfiltered();
  874. resettranslationscache();
  875. flushmemoizecache();
  876. # Trigger a wiki refresh.
  877. require IkiWiki::Render;
  878. # without preliminary saveindex/loadindex, refresh()
  879. # complains about a lot of uninitialized variables
  880. IkiWiki::saveindex();
  881. IkiWiki::loadindex();
  882. IkiWiki::refresh();
  883. IkiWiki::saveindex();
  884. }
  885. # on success, returns the filtered content.
  886. # on error, if $nonfatal, warn and return undef; else, error out.
  887. sub po_to_markup ($$;$) {
  888. my ($page, $content) = (shift, shift);
  889. my $nonfatal = shift;
  890. $content = '' unless defined $content;
  891. $content = decode_utf8(encode_utf8($content));
  892. # CRLF line terminators make poor Locale::Po4a feel bad
  893. $content=~s/\r\n/\n/g;
  894. # There are incompatibilities between some File::Temp versions
  895. # (including 0.18, bundled with Lenny's perl-modules package)
  896. # and others (e.g. 0.20, previously present in the archive as
  897. # a standalone package): under certain circumstances, some
  898. # return a relative filename, whereas others return an absolute one;
  899. # we here use this module in a way that is at least compatible
  900. # with 0.18 and 0.20. Beware, hit'n'run refactorers!
  901. my $infile = new File::Temp(TEMPLATE => "ikiwiki-po-filter-in.XXXXXXXXXX",
  902. DIR => File::Spec->tmpdir,
  903. UNLINK => 1)->filename;
  904. my $outfile = new File::Temp(TEMPLATE => "ikiwiki-po-filter-out.XXXXXXXXXX",
  905. DIR => File::Spec->tmpdir,
  906. UNLINK => 1)->filename;
  907. my $fail = sub ($) {
  908. my $msg = "po(po_to_markup) - $page : " . shift;
  909. if ($nonfatal) {
  910. warn $msg;
  911. return undef;
  912. }
  913. error($msg, sub { unlink $infile, $outfile});
  914. };
  915. writefile(basename($infile), File::Spec->tmpdir, $content)
  916. or return $fail->(sprintf(gettext("failed to write %s"), $infile));
  917. my $masterfile = srcfile($pagesources{masterpage($page)});
  918. my %options = (
  919. "markdown" => (pagetype($masterfile) eq 'mdwn') ? 1 : 0,
  920. );
  921. my $doc=Locale::Po4a::Chooser::new('text',%options);
  922. $doc->process(
  923. 'po_in_name' => [ $infile ],
  924. 'file_in_name' => [ $masterfile ],
  925. 'file_in_charset' => 'utf-8',
  926. 'file_out_charset' => 'utf-8',
  927. ) or return $fail->(gettext("failed to translate"));
  928. $doc->write($outfile)
  929. or return $fail->(sprintf(gettext("failed to write %s"), $outfile));
  930. $content = readfile($outfile)
  931. or return $fail->(sprintf(gettext("failed to read %s"), $outfile));
  932. # Unlinking should happen automatically, thanks to File::Temp,
  933. # but it does not work here, probably because of the way writefile()
  934. # and Locale::Po4a::write() work.
  935. unlink $infile, $outfile;
  936. return $content;
  937. }
  938. # returns a SuccessReason or FailReason object
  939. sub isvalidpo ($) {
  940. my $content = shift;
  941. # NB: we don't use po_to_markup here, since Po4a parser does
  942. # not mind invalid PO content
  943. $content = '' unless defined $content;
  944. $content = decode_utf8(encode_utf8($content));
  945. # There are incompatibilities between some File::Temp versions
  946. # (including 0.18, bundled with Lenny's perl-modules package)
  947. # and others (e.g. 0.20, previously present in the archive as
  948. # a standalone package): under certain circumstances, some
  949. # return a relative filename, whereas others return an absolute one;
  950. # we here use this module in a way that is at least compatible
  951. # with 0.18 and 0.20. Beware, hit'n'run refactorers!
  952. my $infile = new File::Temp(TEMPLATE => "ikiwiki-po-isvalidpo.XXXXXXXXXX",
  953. DIR => File::Spec->tmpdir,
  954. UNLINK => 1)->filename;
  955. my $fail = sub ($) {
  956. my $msg = '[po/isvalidpo] ' . shift;
  957. unlink $infile;
  958. return IkiWiki::FailReason->new("$msg");
  959. };
  960. writefile(basename($infile), File::Spec->tmpdir, $content)
  961. or return $fail->(sprintf(gettext("failed to write %s"), $infile));
  962. my $res = (system("msgfmt", "--check", $infile, "-o", "/dev/null") == 0);
  963. # Unlinking should happen automatically, thanks to File::Temp,
  964. # but it does not work here, probably because of the way writefile()
  965. # and Locale::Po4a::write() work.
  966. unlink $infile;
  967. if ($res) {
  968. return IkiWiki::SuccessReason->new("valid gettext data");
  969. }
  970. return IkiWiki::FailReason->new(gettext("invalid gettext data, go back ".
  971. "to previous page to continue edit"));
  972. }
  973. # ,----
  974. # | PageSpecs
  975. # `----
  976. package IkiWiki::PageSpec;
  977. sub match_istranslation ($;@) {
  978. my $page=shift;
  979. if (IkiWiki::Plugin::po::istranslation($page)) {
  980. return IkiWiki::SuccessReason->new("is a translation page");
  981. }
  982. else {
  983. return IkiWiki::FailReason->new("is not a translation page");
  984. }
  985. }
  986. sub match_istranslatable ($;@) {
  987. my $page=shift;
  988. if (IkiWiki::Plugin::po::istranslatable($page)) {
  989. return IkiWiki::SuccessReason->new("is set as translatable in po_translatable_pages");
  990. }
  991. else {
  992. return IkiWiki::FailReason->new("is not set as translatable in po_translatable_pages");
  993. }
  994. }
  995. sub match_lang ($$;@) {
  996. my $page=shift;
  997. my $wanted=shift;
  998. my $regexp=IkiWiki::glob2re($wanted);
  999. my $lang=IkiWiki::Plugin::po::lang($page);
  1000. if ($lang !~ /^$regexp$/i) {
  1001. return IkiWiki::FailReason->new("file language is $lang, not $wanted");
  1002. }
  1003. else {
  1004. return IkiWiki::SuccessReason->new("file language is $wanted");
  1005. }
  1006. }
  1007. sub match_currentlang ($$;@) {
  1008. my $page=shift;
  1009. shift;
  1010. my %params=@_;
  1011. return IkiWiki::FailReason->new("no location provided") unless exists $params{location};
  1012. my $currentlang=IkiWiki::Plugin::po::lang($params{location});
  1013. my $lang=IkiWiki::Plugin::po::lang($page);
  1014. if ($lang eq $currentlang) {
  1015. return IkiWiki::SuccessReason->new("file language is the same as current one, i.e. $currentlang");
  1016. }
  1017. else {
  1018. return IkiWiki::FailReason->new("file language is $lang, whereas current language is $currentlang");
  1019. }
  1020. }
  1021. 1