summaryrefslogtreecommitdiff
path: root/IkiWiki/Plugin/po.pm
blob: 5d0d9e79dd26074344a642f524d098101e4a21c8 (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,
  78. },
  79. po_master_language => {
  80. type => "string",
  81. example => {
  82. 'code' => 'en',
  83. 'name' => 'English'
  84. },
  85. description => "master language (non-PO files)",
  86. safe => 1,
  87. rebuild => 1,
  88. },
  89. po_slave_languages => {
  90. type => "string",
  91. example => {
  92. 'fr' => 'Français',
  93. 'es' => 'Español',
  94. 'de' => 'Deutsch'
  95. },
  96. description => "slave languages (PO files)",
  97. safe => 1,
  98. rebuild => 1,
  99. },
  100. po_translatable_pages => {
  101. type => "pagespec",
  102. example => "* and !*/Discussion",
  103. description => "PageSpec controlling which pages are translatable",
  104. link => "ikiwiki/PageSpec",
  105. safe => 1,
  106. rebuild => 1,
  107. },
  108. po_link_to => {
  109. type => "string",
  110. example => "current",
  111. description => "internal linking behavior (default/current/negotiated)",
  112. safe => 1,
  113. rebuild => 1,
  114. },
  115. }
  116. sub checkconfig () {
  117. foreach my $field (qw{po_master_language}) {
  118. if (! exists $config{$field} || ! defined $config{$field}) {
  119. error(sprintf(gettext("Must specify %s when using the %s plugin"),
  120. $field, 'po'));
  121. }
  122. }
  123. map {
  124. islanguagecode($_)
  125. or error(sprintf(gettext("%s is not a valid language code"), $_));
  126. } ($config{po_master_language}{code}, keys %{$config{po_slave_languages}});
  127. if (! exists $config{po_translatable_pages} ||
  128. ! defined $config{po_translatable_pages}) {
  129. $config{po_translatable_pages}="";
  130. }
  131. if (! exists $config{po_link_to} ||
  132. ! defined $config{po_link_to}) {
  133. $config{po_link_to}='default';
  134. }
  135. elsif ($config{po_link_to} !~ /^(default|current|negotiated)$/) {
  136. warn(sprintf(gettext('%s is not a valid value for po_link_to, falling back to po_link_to=default'),
  137. $config{po_link_to}));
  138. $config{po_link_to}='default';
  139. }
  140. elsif ($config{po_link_to} eq "negotiated" && ! $config{usedirs}) {
  141. warn(gettext('po_link_to=negotiated requires usedirs to be enabled, falling back to po_link_to=default'));
  142. $config{po_link_to}='default';
  143. }
  144. push @{$config{wiki_file_prune_regexps}}, qr/\.pot$/;
  145. # Translated versions of the underlays are added if available.
  146. foreach my $underlay ("basewiki",
  147. map { m/^\Q$config{underlaydirbase}\E\/*(.*)/ }
  148. reverse @{$config{underlaydirs}}) {
  149. next if $underlay=~/^locale\//;
  150. # Underlays containing the po files for slave languages.
  151. foreach my $ll (keys %{$config{po_slave_languages}}) {
  152. add_underlay("po/$ll/$underlay")
  153. if -d "$config{underlaydirbase}/po/$ll/$underlay";
  154. }
  155. if ($config{po_master_language}{code} ne 'en') {
  156. # Add underlay containing translated source files
  157. # for the master language.
  158. add_underlay("locale/$config{po_master_language}{code}/$underlay");
  159. }
  160. }
  161. }
  162. sub needsbuild () {
  163. my $needsbuild=shift;
  164. # backup @needsbuild content so that change() can know whether
  165. # a given master page was rendered because its source file was changed
  166. @origneedsbuild=(@$needsbuild);
  167. flushmemoizecache();
  168. buildtranslationscache();
  169. # make existing translations depend on the corresponding master page
  170. foreach my $master (keys %translations) {
  171. map add_depends($_, $master), values %{otherlanguages($master)};
  172. }
  173. }
  174. # Massage the recorded state of internal links so that:
  175. # - it matches the actually generated links, rather than the links as written
  176. # in the pages' source
  177. # - backlinks are consistent in all cases
  178. sub scan (@) {
  179. my %params=@_;
  180. my $page=$params{page};
  181. my $content=$params{content};
  182. if (istranslation($page)) {
  183. foreach my $destpage (@{$links{$page}}) {
  184. if (istranslatable($destpage)) {
  185. # replace the occurence of $destpage in $links{$page}
  186. for (my $i=0; $i<@{$links{$page}}; $i++) {
  187. if (@{$links{$page}}[$i] eq $destpage) {
  188. @{$links{$page}}[$i] = $destpage . '.' . lang($page);
  189. last;
  190. }
  191. }
  192. }
  193. }
  194. }
  195. elsif (! istranslatable($page) && ! istranslation($page)) {
  196. foreach my $destpage (@{$links{$page}}) {
  197. if (istranslatable($destpage)) {
  198. # make sure any destpage's translations has
  199. # $page in its backlinks
  200. push @{$links{$page}},
  201. values %{otherlanguages($destpage)};
  202. }
  203. }
  204. }
  205. }
  206. # We use filter to convert PO to the master page's format,
  207. # since the rest of ikiwiki should not work on PO files.
  208. sub filter (@) {
  209. my %params = @_;
  210. my $page = $params{page};
  211. my $destpage = $params{destpage};
  212. my $content = $params{content};
  213. if (istranslation($page) && ! alreadyfiltered($page, $destpage)) {
  214. $content = po_to_markup($page, $content);
  215. setalreadyfiltered($page, $destpage);
  216. }
  217. return $content;
  218. }
  219. sub htmlize (@) {
  220. my %params=@_;
  221. my $page = $params{page};
  222. my $content = $params{content};
  223. # ignore PO files this plugin did not create
  224. return $content unless istranslation($page);
  225. # force content to be htmlize'd as if it was the same type as the master page
  226. return IkiWiki::htmlize($page, $page,
  227. pagetype(srcfile($pagesources{masterpage($page)})),
  228. $content);
  229. }
  230. sub pagetemplate (@) {
  231. my %params=@_;
  232. my $page=$params{page};
  233. my $destpage=$params{destpage};
  234. my $template=$params{template};
  235. my ($masterpage, $lang) = istranslation($page);
  236. if (istranslation($page) && $template->query(name => "percenttranslated")) {
  237. $template->param(percenttranslated => percenttranslated($page));
  238. }
  239. if ($template->query(name => "istranslation")) {
  240. $template->param(istranslation => scalar istranslation($page));
  241. }
  242. if ($template->query(name => "istranslatable")) {
  243. $template->param(istranslatable => istranslatable($page));
  244. }
  245. if ($template->query(name => "HOMEPAGEURL")) {
  246. $template->param(homepageurl => homepageurl($page));
  247. }
  248. if ($template->query(name => "otherlanguages")) {
  249. $template->param(otherlanguages => [otherlanguagesloop($page)]);
  250. map add_depends($page, $_), (values %{otherlanguages($page)});
  251. }
  252. if ($config{discussion} && istranslation($page)) {
  253. if ($page !~ /.*\/\Q$config{discussionpage}\E$/i &&
  254. (length $config{cgiurl} ||
  255. exists $links{$masterpage."/".lc($config{discussionpage})})) {
  256. $template->param('discussionlink' => htmllink(
  257. $page,
  258. $destpage,
  259. $masterpage . '/' . $config{discussionpage},
  260. noimageinline => 1,
  261. forcesubpage => 0,
  262. linktext => $config{discussionpage},
  263. ));
  264. }
  265. }
  266. # Remove broken parentlink to ./index.html on home page's translations.
  267. # It works because this hook has the "last" parameter set, to ensure it
  268. # runs after parentlinks' own pagetemplate hook.
  269. if ($template->param('parentlinks')
  270. && istranslation($page)
  271. && $masterpage eq "index") {
  272. $template->param('parentlinks' => []);
  273. }
  274. if (ishomepage($page) && $template->query(name => "title")) {
  275. $template->param(title => $config{wikiname});
  276. }
  277. } # }}}
  278. # Add the renamed page translations to the list of to-be-renamed pages.
  279. sub renamepages (@) {
  280. my %params = @_;
  281. my %torename = %{$params{torename}};
  282. my $session = $params{session};
  283. # Save the page(s) the user asked to rename, so that our
  284. # canrename hook can tell the difference between:
  285. # - a translation being renamed as a consequence of its master page
  286. # being renamed
  287. # - a user trying to directly rename a translation
  288. # This is why this hook has to be run first, before the list of pages
  289. # to rename is modified by other plugins.
  290. my @orig_torename;
  291. @orig_torename=@{$session->param("po_orig_torename")}
  292. if defined $session->param("po_orig_torename");
  293. push @orig_torename, $torename{src};
  294. $session->param(po_orig_torename => \@orig_torename);
  295. IkiWiki::cgi_savesession($session);
  296. return () unless istranslatable($torename{src});
  297. my @ret;
  298. my %otherpages=%{otherlanguages($torename{src})};
  299. while (my ($lang, $otherpage) = each %otherpages) {
  300. push @ret, {
  301. src => $otherpage,
  302. srcfile => $pagesources{$otherpage},
  303. dest => otherlanguage($torename{dest}, $lang),
  304. destfile => $torename{dest}.".".$lang.".po",
  305. required => 0,
  306. };
  307. }
  308. return @ret;
  309. }
  310. sub mydelete (@) {
  311. my @deleted=@_;
  312. map { deletetranslations($_) } grep istranslatablefile($_), @deleted;
  313. }
  314. sub change (@) {
  315. my @rendered=@_;
  316. # All meta titles are first extracted at scan time, i.e. before we turn
  317. # PO files back into translated markdown; escaping of double-quotes in
  318. # PO files breaks the meta plugin's parsing enough to save ugly titles
  319. # to %pagestate at this time.
  320. #
  321. # Then, at render time, every page passes in turn through the Great
  322. # Rendering Chain (filter->preprocess->linkify->htmlize), and the meta
  323. # plugin's preprocess hook is this time in a position to correctly
  324. # extract the titles from slave pages.
  325. #
  326. # This is, unfortunately, too late: if the page A, linking to the page
  327. # B, is rendered before B, it will display the wrongly-extracted meta
  328. # title as the link text to B.
  329. #
  330. # On the one hand, such a corner case only happens on rebuild: on
  331. # refresh, every rendered page is fixed to contain correct meta titles.
  332. # On the other hand, it can take some time to get every page fixed.
  333. # We therefore re-render every rendered page after a rebuild to fix them
  334. # at once. As this more or less doubles the time needed to rebuild the
  335. # wiki, we do so only when really needed.
  336. if (@rendered
  337. && exists $config{rebuild} && defined $config{rebuild} && $config{rebuild}
  338. && UNIVERSAL::can("IkiWiki::Plugin::meta", "getsetup")
  339. && exists $config{meta_overrides_page_title}
  340. && defined $config{meta_overrides_page_title}
  341. && $config{meta_overrides_page_title}) {
  342. debug(sprintf(gettext("rebuilding all pages to fix meta titles")));
  343. resetalreadyfiltered();
  344. require IkiWiki::Render;
  345. foreach my $file (@rendered) {
  346. debug(sprintf(gettext("building %s"), $file));
  347. IkiWiki::render($file);
  348. }
  349. }
  350. my $updated_po_files=0;
  351. # Refresh/create POT and PO files as needed.
  352. # (But avoid doing so if they are in an underlay directory.)
  353. foreach my $file (grep {istranslatablefile($_)} @rendered) {
  354. my $masterfile=srcfile($file);
  355. my $page=pagename($file);
  356. my $updated_pot_file=0;
  357. # Only refresh POT file if it does not exist, or if
  358. # $pagesources{$page} was changed: don't if only the HTML was
  359. # refreshed, e.g. because of a dependency.
  360. if ($masterfile eq "$config{srcdir}/$file" &&
  361. ((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. # on success, returns the filtered content.
  919. # on error, if $nonfatal, warn and return undef; else, error out.
  920. sub po_to_markup ($$;$) {
  921. my ($page, $content) = (shift, shift);
  922. my $nonfatal = shift;
  923. $content = '' unless defined $content;
  924. $content = decode_utf8(encode_utf8($content));
  925. # CRLF line terminators make poor Locale::Po4a feel bad
  926. $content=~s/\r\n/\n/g;
  927. # There are incompatibilities between some File::Temp versions
  928. # (including 0.18, bundled with Lenny's perl-modules package)
  929. # and others (e.g. 0.20, previously present in the archive as
  930. # a standalone package): under certain circumstances, some
  931. # return a relative filename, whereas others return an absolute one;
  932. # we here use this module in a way that is at least compatible
  933. # with 0.18 and 0.20. Beware, hit'n'run refactorers!
  934. my $infile = new File::Temp(TEMPLATE => "ikiwiki-po-filter-in.XXXXXXXXXX",
  935. DIR => File::Spec->tmpdir,
  936. UNLINK => 1)->filename;
  937. my $outfile = new File::Temp(TEMPLATE => "ikiwiki-po-filter-out.XXXXXXXXXX",
  938. DIR => File::Spec->tmpdir,
  939. UNLINK => 1)->filename;
  940. my $fail = sub ($) {
  941. my $msg = "po(po_to_markup) - $page : " . shift;
  942. if ($nonfatal) {
  943. warn $msg;
  944. return undef;
  945. }
  946. error($msg, sub { unlink $infile, $outfile});
  947. };
  948. writefile(basename($infile), File::Spec->tmpdir, $content)
  949. or return $fail->(sprintf(gettext("failed to write %s"), $infile));
  950. my $masterfile = srcfile($pagesources{masterpage($page)});
  951. my %options = (
  952. "markdown" => (pagetype($masterfile) eq 'mdwn') ? 1 : 0,
  953. );
  954. my $doc=Locale::Po4a::Chooser::new('text',%options);
  955. $doc->process(
  956. 'po_in_name' => [ $infile ],
  957. 'file_in_name' => [ $masterfile ],
  958. 'file_in_charset' => 'utf-8',
  959. 'file_out_charset' => 'utf-8',
  960. ) or return $fail->(gettext("failed to translate"));
  961. $doc->write($outfile)
  962. or return $fail->(sprintf(gettext("failed to write %s"), $outfile));
  963. $content = readfile($outfile)
  964. or return $fail->(sprintf(gettext("failed to read %s"), $outfile));
  965. # Unlinking should happen automatically, thanks to File::Temp,
  966. # but it does not work here, probably because of the way writefile()
  967. # and Locale::Po4a::write() work.
  968. unlink $infile, $outfile;
  969. return $content;
  970. }
  971. # returns a SuccessReason or FailReason object
  972. sub isvalidpo ($) {
  973. my $content = shift;
  974. # NB: we don't use po_to_markup here, since Po4a parser does
  975. # not mind invalid PO content
  976. $content = '' unless defined $content;
  977. $content = decode_utf8(encode_utf8($content));
  978. # There are incompatibilities between some File::Temp versions
  979. # (including 0.18, bundled with Lenny's perl-modules package)
  980. # and others (e.g. 0.20, previously present in the archive as
  981. # a standalone package): under certain circumstances, some
  982. # return a relative filename, whereas others return an absolute one;
  983. # we here use this module in a way that is at least compatible
  984. # with 0.18 and 0.20. Beware, hit'n'run refactorers!
  985. my $infile = new File::Temp(TEMPLATE => "ikiwiki-po-isvalidpo.XXXXXXXXXX",
  986. DIR => File::Spec->tmpdir,
  987. UNLINK => 1)->filename;
  988. my $fail = sub ($) {
  989. my $msg = '[po/isvalidpo] ' . shift;
  990. unlink $infile;
  991. return IkiWiki::FailReason->new("$msg");
  992. };
  993. writefile(basename($infile), File::Spec->tmpdir, $content)
  994. or return $fail->(sprintf(gettext("failed to write %s"), $infile));
  995. my $res = (system("msgfmt", "--check", $infile, "-o", "/dev/null") == 0);
  996. # Unlinking should happen automatically, thanks to File::Temp,
  997. # but it does not work here, probably because of the way writefile()
  998. # and Locale::Po4a::write() work.
  999. unlink $infile;
  1000. if ($res) {
  1001. return IkiWiki::SuccessReason->new("valid gettext data");
  1002. }
  1003. return IkiWiki::FailReason->new(gettext("invalid gettext data, go back ".
  1004. "to previous page to continue edit"));
  1005. }
  1006. # ,----
  1007. # | PageSpecs
  1008. # `----
  1009. package IkiWiki::PageSpec;
  1010. sub match_istranslation ($;@) {
  1011. my $page=shift;
  1012. if (IkiWiki::Plugin::po::istranslation($page)) {
  1013. return IkiWiki::SuccessReason->new("is a translation page");
  1014. }
  1015. else {
  1016. return IkiWiki::FailReason->new("is not a translation page");
  1017. }
  1018. }
  1019. sub match_istranslatable ($;@) {
  1020. my $page=shift;
  1021. if (IkiWiki::Plugin::po::istranslatable($page)) {
  1022. return IkiWiki::SuccessReason->new("is set as translatable in po_translatable_pages");
  1023. }
  1024. else {
  1025. return IkiWiki::FailReason->new("is not set as translatable in po_translatable_pages");
  1026. }
  1027. }
  1028. sub match_lang ($$;@) {
  1029. my $page=shift;
  1030. my $wanted=shift;
  1031. my $regexp=IkiWiki::glob2re($wanted);
  1032. my $lang=IkiWiki::Plugin::po::lang($page);
  1033. if ($lang !~ /^$regexp$/i) {
  1034. return IkiWiki::FailReason->new("file language is $lang, not $wanted");
  1035. }
  1036. else {
  1037. return IkiWiki::SuccessReason->new("file language is $wanted");
  1038. }
  1039. }
  1040. sub match_currentlang ($$;@) {
  1041. my $page=shift;
  1042. shift;
  1043. my %params=@_;
  1044. return IkiWiki::FailReason->new("no location provided") unless exists $params{location};
  1045. my $currentlang=IkiWiki::Plugin::po::lang($params{location});
  1046. my $lang=IkiWiki::Plugin::po::lang($page);
  1047. if ($lang eq $currentlang) {
  1048. return IkiWiki::SuccessReason->new("file language is the same as current one, i.e. $currentlang");
  1049. }
  1050. else {
  1051. return IkiWiki::FailReason->new("file language is $lang, whereas current language is $currentlang");
  1052. }
  1053. }
  1054. 1