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