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