summaryrefslogtreecommitdiff
path: root/IkiWiki/Plugin/po.pm
blob: f8801185e2450152f2155fb01ff1da5fdcee607f (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. IkiWiki::render($file, sprintf(gettext("building %s"), $file));
  347. }
  348. }
  349. my $updated_po_files=0;
  350. # Refresh/create POT and PO files as needed.
  351. foreach my $file (grep {istranslatablefile($_)} @rendered) {
  352. my $masterfile=srcfile($file);
  353. my $page=pagename($file);
  354. my $updated_pot_file=0;
  355. # Avoid touching underlay files.
  356. next if $masterfile ne "$config{srcdir}/$file";
  357. # Only refresh POT file if it does not exist, or if
  358. # the source was changed: don't if only the HTML was
  359. # refreshed, e.g. because of a dependency.
  360. if ((grep { $_ eq $pagesources{$page} } @origneedsbuild) ||
  361. ! -e potfile($masterfile)) {
  362. refreshpot($masterfile);
  363. $updated_pot_file=1;
  364. }
  365. my @pofiles;
  366. foreach my $po (pofiles($masterfile)) {
  367. next if ! $updated_pot_file && -e $po;
  368. next if grep { $po=~/\Q$_\E/ } @{$config{underlaydirs}};
  369. push @pofiles, $po;
  370. }
  371. if (@pofiles) {
  372. refreshpofiles($masterfile, @pofiles);
  373. map { s/^\Q$config{srcdir}\E\/*//; IkiWiki::rcs_add($_) } @pofiles if $config{rcs};
  374. $updated_po_files=1;
  375. }
  376. }
  377. if ($updated_po_files) {
  378. commit_and_refresh(
  379. gettext("updated PO files"),
  380. "IkiWiki::Plugin::po::change");
  381. }
  382. }
  383. sub checkcontent (@) {
  384. my %params=@_;
  385. if (istranslation($params{page})) {
  386. my $res = isvalidpo($params{content});
  387. if ($res) {
  388. return undef;
  389. }
  390. else {
  391. return "$res";
  392. }
  393. }
  394. return undef;
  395. }
  396. sub canremove (@) {
  397. my %params = @_;
  398. if (istranslation($params{page})) {
  399. return gettext("Can not remove a translation. If the master page is removed, ".
  400. "however, its translations will be removed as well.");
  401. }
  402. return undef;
  403. }
  404. sub canrename (@) {
  405. my %params = @_;
  406. my $session = $params{session};
  407. if (istranslation($params{src})) {
  408. my $masterpage = masterpage($params{src});
  409. # Tell the difference between:
  410. # - a translation being renamed as a consequence of its master page
  411. # being renamed, which is allowed
  412. # - a user trying to directly rename a translation, which is forbidden
  413. # by looking for the master page in the list of to-be-renamed pages we
  414. # saved early in the renaming process.
  415. my $orig_torename = $session->param("po_orig_torename");
  416. unless (grep { $_ eq $masterpage } @{$orig_torename}) {
  417. return gettext("Can not rename a translation. If the master page is renamed, ".
  418. "however, its translations will be renamed as well.");
  419. }
  420. }
  421. return undef;
  422. }
  423. # As we're previewing or saving a page, the content may have
  424. # changed, so tell the next filter() invocation it must not be lazy.
  425. sub editcontent () {
  426. my %params=@_;
  427. unsetalreadyfiltered($params{page}, $params{page});
  428. return $params{content};
  429. }
  430. sub formbuilder_setup (@) {
  431. my %params=@_;
  432. my $form=$params{form};
  433. my $q=$params{cgi};
  434. return unless defined $form->field("do");
  435. if ($form->field("do") eq "create") {
  436. # Warn the user: new pages must be written in master language.
  437. my $template=template("pocreatepage.tmpl");
  438. $template->param(LANG => $config{po_master_language}{name});
  439. $form->tmpl_param(message => $template->output);
  440. }
  441. elsif ($form->field("do") eq "edit") {
  442. # Remove the rename/remove buttons on slave pages.
  443. # This has to be done after the rename/remove plugins have added
  444. # their buttons, which is why this hook must be run last.
  445. # The canrename/canremove hooks already ensure this is forbidden
  446. # at the backend level, so this is only UI sugar.
  447. if (istranslation($form->field("page"))) {
  448. map {
  449. for (my $i = 0; $i < @{$params{buttons}}; $i++) {
  450. if (@{$params{buttons}}[$i] eq $_) {
  451. delete @{$params{buttons}}[$i];
  452. last;
  453. }
  454. }
  455. } qw(Rename Remove);
  456. }
  457. }
  458. }
  459. sub formbuilder (@) {
  460. my %params=@_;
  461. my $form=$params{form};
  462. my $q=$params{cgi};
  463. return unless defined $form->field("do");
  464. # Do not allow to create pages of type po: they are automatically created.
  465. # The main reason to do so is to bypass the "favor the type of linking page
  466. # on page creation" logic, which is unsuitable when a broken link is clicked
  467. # on a slave (PO) page.
  468. # This cannot be done in the formbuilder_setup hook as the list of types is
  469. # computed later.
  470. if ($form->field("do") eq "create") {
  471. foreach my $field ($form->field) {
  472. next unless "$field" eq "type";
  473. next unless $field->type eq 'select';
  474. my $orig_value = $field->value;
  475. # remove po from the list of types
  476. my @types = grep { $_->[0] ne 'po' } $field->options;
  477. $field->options(\@types) if @types;
  478. # favor the type of linking page's masterpage
  479. if ($orig_value eq 'po') {
  480. my ($from, $type);
  481. if (defined $form->field('from')) {
  482. ($from)=$form->field('from')=~/$config{wiki_file_regexp}/;
  483. $from = masterpage($from);
  484. }
  485. if (defined $from && exists $pagesources{$from}) {
  486. $type=pagetype($pagesources{$from});
  487. }
  488. $type=$config{default_pageext} unless defined $type;
  489. $field->value($type) ;
  490. }
  491. }
  492. }
  493. }
  494. # ,----
  495. # | Injected functions
  496. # `----
  497. # Implement po_link_to 'current' and 'negotiated' settings.
  498. sub mybestlink ($$) {
  499. my $page=shift;
  500. my $link=shift;
  501. return $origsubs{'bestlink'}->($page, $link)
  502. if $config{po_link_to} eq "default";
  503. my $res=$origsubs{'bestlink'}->(masterpage($page), $link);
  504. my @caller = caller(1);
  505. if (length $res
  506. && istranslatable($res)
  507. && istranslation($page)
  508. && !(exists $caller[3] && defined $caller[3]
  509. && ($caller[3] eq "IkiWiki::PageSpec::match_link"))) {
  510. return $res . "." . lang($page);
  511. }
  512. return $res;
  513. }
  514. sub mybeautify_urlpath ($) {
  515. my $url=shift;
  516. my $res=$origsubs{'beautify_urlpath'}->($url);
  517. if ($config{po_link_to} eq "negotiated") {
  518. $res =~ s!/\Qindex.$config{po_master_language}{code}.$config{htmlext}\E$!/!;
  519. $res =~ s!/\Qindex.$config{htmlext}\E$!/!;
  520. map {
  521. $res =~ s!/\Qindex.$_.$config{htmlext}\E$!/!;
  522. } (keys %{$config{po_slave_languages}});
  523. }
  524. return $res;
  525. }
  526. sub mytargetpage ($$) {
  527. my $page=shift;
  528. my $ext=shift;
  529. if (istranslation($page) || istranslatable($page)) {
  530. my ($masterpage, $lang) = (masterpage($page), lang($page));
  531. if (! $config{usedirs} || $masterpage eq 'index') {
  532. return $masterpage . "." . $lang . "." . $ext;
  533. }
  534. else {
  535. return $masterpage . "/index." . $lang . "." . $ext;
  536. }
  537. }
  538. return $origsubs{'targetpage'}->($page, $ext);
  539. }
  540. sub myurlto ($$;$) {
  541. my $to=shift;
  542. my $from=shift;
  543. my $absolute=shift;
  544. # workaround hard-coded /index.$config{htmlext} in IkiWiki::urlto()
  545. if (! length $to
  546. && $config{po_link_to} eq "current"
  547. && istranslatable('index')) {
  548. return IkiWiki::beautify_urlpath(IkiWiki::baseurl($from) . "index." . lang($from) . ".$config{htmlext}");
  549. }
  550. # avoid using our injected beautify_urlpath if run by cgi_editpage,
  551. # so that one is redirected to the just-edited page rather than to the
  552. # negociated translation; to prevent unnecessary fiddling with caller/inject,
  553. # we only do so when our beautify_urlpath would actually do what we want to
  554. # avoid, i.e. when po_link_to = negotiated.
  555. # also avoid doing so when run by cgi_goto, so that the links on recentchanges
  556. # page actually lead to the exact page they pretend to.
  557. if ($config{po_link_to} eq "negotiated") {
  558. my @caller = caller(1);
  559. my $use_orig = 0;
  560. $use_orig = 1 if (exists $caller[3] && defined $caller[3]
  561. && ($caller[3] eq "IkiWiki::cgi_editpage" ||
  562. $caller[3] eq "IkiWiki::Plugin::goto::cgi_goto")
  563. );
  564. inject(name => "IkiWiki::beautify_urlpath", call => $origsubs{'beautify_urlpath'})
  565. if $use_orig;
  566. my $res = $origsubs{'urlto'}->($to,$from,$absolute);
  567. inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath)
  568. if $use_orig;
  569. return $res;
  570. }
  571. else {
  572. return $origsubs{'urlto'}->($to,$from,$absolute)
  573. }
  574. }
  575. sub mycgiurl (@) {
  576. my %params=@_;
  577. # slave pages have no subpages
  578. if (istranslation($params{'from'})) {
  579. $params{'from'} = masterpage($params{'from'});
  580. }
  581. return $origsubs{'cgiurl'}->(%params);
  582. }
  583. sub myrootpage (@) {
  584. my %params=@_;
  585. my $rootpage;
  586. if (exists $params{rootpage}) {
  587. $rootpage=$origsubs{'bestlink'}->($params{page}, $params{rootpage});
  588. if (!length $rootpage) {
  589. $rootpage=$params{rootpage};
  590. }
  591. }
  592. else {
  593. $rootpage=masterpage($params{page});
  594. }
  595. return $rootpage;
  596. }
  597. # ,----
  598. # | Blackboxes for private data
  599. # `----
  600. {
  601. my %filtered;
  602. sub alreadyfiltered($$) {
  603. my $page=shift;
  604. my $destpage=shift;
  605. return exists $filtered{$page}{$destpage}
  606. && $filtered{$page}{$destpage} eq 1;
  607. }
  608. sub setalreadyfiltered($$) {
  609. my $page=shift;
  610. my $destpage=shift;
  611. $filtered{$page}{$destpage}=1;
  612. }
  613. sub unsetalreadyfiltered($$) {
  614. my $page=shift;
  615. my $destpage=shift;
  616. if (exists $filtered{$page}{$destpage}) {
  617. delete $filtered{$page}{$destpage};
  618. }
  619. }
  620. sub resetalreadyfiltered() {
  621. undef %filtered;
  622. }
  623. }
  624. # ,----
  625. # | Helper functions
  626. # `----
  627. sub maybe_add_leading_slash ($;$) {
  628. my $str=shift;
  629. my $add=shift;
  630. $add=1 unless defined $add;
  631. return '/' . $str if $add;
  632. return $str;
  633. }
  634. sub istranslatablefile ($) {
  635. my $file=shift;
  636. return 0 unless defined $file;
  637. my $type=pagetype($file);
  638. return 0 if ! defined $type || $type eq 'po';
  639. return 0 if $file =~ /\.pot$/;
  640. return 1 if pagespec_match(pagename($file), $config{po_translatable_pages});
  641. return;
  642. }
  643. sub istranslatable ($) {
  644. my $page=shift;
  645. $page=~s#^/##;
  646. return 1 if istranslatablefile($pagesources{$page});
  647. return;
  648. }
  649. sub _istranslation ($) {
  650. my $page=shift;
  651. $page='' unless defined $page && length $page;
  652. my $hasleadingslash = ($page=~s#^/##);
  653. my $file=$pagesources{$page};
  654. return 0 unless defined $file
  655. && defined pagetype($file)
  656. && pagetype($file) eq 'po';
  657. return 0 if $file =~ /\.pot$/;
  658. my ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
  659. return 0 unless defined $masterpage && defined $lang
  660. && length $masterpage && length $lang
  661. && defined $pagesources{$masterpage}
  662. && defined $config{po_slave_languages}{$lang};
  663. return (maybe_add_leading_slash($masterpage, $hasleadingslash), $lang)
  664. if istranslatable($masterpage);
  665. }
  666. sub istranslation ($) {
  667. my $page=shift;
  668. if (1 < (my ($masterpage, $lang) = _istranslation($page))) {
  669. my $hasleadingslash = ($masterpage=~s#^/##);
  670. $translations{$masterpage}{$lang}=$page unless exists $translations{$masterpage}{$lang};
  671. return (maybe_add_leading_slash($masterpage, $hasleadingslash), $lang);
  672. }
  673. return "";
  674. }
  675. sub masterpage ($) {
  676. my $page=shift;
  677. if ( 1 < (my ($masterpage, $lang) = _istranslation($page))) {
  678. return $masterpage;
  679. }
  680. return $page;
  681. }
  682. sub lang ($) {
  683. my $page=shift;
  684. if (1 < (my ($masterpage, $lang) = _istranslation($page))) {
  685. return $lang;
  686. }
  687. return $config{po_master_language}{code};
  688. }
  689. sub islanguagecode ($) {
  690. my $code=shift;
  691. return $code =~ /^[a-z]{2}$/;
  692. }
  693. sub otherlanguage ($$) {
  694. my $page=shift;
  695. my $code=shift;
  696. return masterpage($page) if $code eq $config{po_master_language}{code};
  697. return masterpage($page) . '.' . $code;
  698. }
  699. sub otherlanguages ($) {
  700. my $page=shift;
  701. my %ret;
  702. return \%ret unless istranslation($page) || istranslatable($page);
  703. my $curlang=lang($page);
  704. foreach my $lang
  705. ($config{po_master_language}{code}, keys %{$config{po_slave_languages}}) {
  706. next if $lang eq $curlang;
  707. $ret{$lang}=otherlanguage($page, $lang);
  708. }
  709. return \%ret;
  710. }
  711. sub potfile ($) {
  712. my $masterfile=shift;
  713. (my $name, my $dir, my $suffix) = fileparse($masterfile, qr/\.[^.]*/);
  714. $dir='' if $dir eq './';
  715. return File::Spec->catpath('', $dir, $name . ".pot");
  716. }
  717. sub pofile ($$) {
  718. my $masterfile=shift;
  719. my $lang=shift;
  720. (my $name, my $dir, my $suffix) = fileparse($masterfile, qr/\.[^.]*/);
  721. $dir='' if $dir eq './';
  722. return File::Spec->catpath('', $dir, $name . "." . $lang . ".po");
  723. }
  724. sub pofiles ($) {
  725. my $masterfile=shift;
  726. return map pofile($masterfile, $_), (keys %{$config{po_slave_languages}});
  727. }
  728. sub refreshpot ($) {
  729. my $masterfile=shift;
  730. my $potfile=potfile($masterfile);
  731. my %options = ("markdown" => (pagetype($masterfile) eq 'mdwn') ? 1 : 0);
  732. my $doc=Locale::Po4a::Chooser::new('text',%options);
  733. $doc->{TT}{utf_mode} = 1;
  734. $doc->{TT}{file_in_charset} = 'utf-8';
  735. $doc->{TT}{file_out_charset} = 'utf-8';
  736. $doc->read($masterfile);
  737. # let's cheat a bit to force porefs option to be passed to
  738. # Locale::Po4a::Po; this is undocument use of internal
  739. # Locale::Po4a::TransTractor's data, compulsory since this module
  740. # prevents us from using the porefs option.
  741. $doc->{TT}{po_out}=Locale::Po4a::Po->new({ 'porefs' => 'none' });
  742. $doc->{TT}{po_out}->set_charset('utf-8');
  743. # do the actual work
  744. $doc->parse;
  745. IkiWiki::prep_writefile(basename($potfile),dirname($potfile));
  746. $doc->writepo($potfile);
  747. }
  748. sub refreshpofiles ($@) {
  749. my $masterfile=shift;
  750. my @pofiles=@_;
  751. my $potfile=potfile($masterfile);
  752. if (! -e $potfile) {
  753. error("po(refreshpofiles) ".sprintf(gettext("POT file (%s) does not exist"), $potfile));
  754. }
  755. foreach my $pofile (@pofiles) {
  756. IkiWiki::prep_writefile(basename($pofile),dirname($pofile));
  757. if (! -e $pofile) {
  758. # If the po file exists in an underlay, copy it
  759. # from there.
  760. my ($pobase)=$pofile=~/^\Q$config{srcdir}\E\/?(.*)$/;
  761. foreach my $dir (@{$config{underlaydirs}}) {
  762. if (-e "$dir/$pobase") {
  763. File::Copy::syscopy("$dir/$pobase",$pofile)
  764. or error("po(refreshpofiles) ".
  765. sprintf(gettext("failed to copy underlay PO file to %s"),
  766. $pofile));
  767. }
  768. }
  769. }
  770. if (-e $pofile) {
  771. system("msgmerge", "--previous", "-q", "-U", "--backup=none", $pofile, $potfile) == 0
  772. or error("po(refreshpofiles) ".
  773. sprintf(gettext("failed to update %s"),
  774. $pofile));
  775. }
  776. else {
  777. File::Copy::syscopy($potfile,$pofile)
  778. or error("po(refreshpofiles) ".
  779. sprintf(gettext("failed to copy the POT file to %s"),
  780. $pofile));
  781. }
  782. }
  783. }
  784. sub buildtranslationscache() {
  785. # use istranslation's side-effect
  786. map istranslation($_), (keys %pagesources);
  787. }
  788. sub resettranslationscache() {
  789. undef %translations;
  790. }
  791. sub flushmemoizecache() {
  792. Memoize::flush_cache("istranslatable");
  793. Memoize::flush_cache("_istranslation");
  794. Memoize::flush_cache("percenttranslated");
  795. }
  796. sub urlto_with_orig_beautiful_urlpath($$) {
  797. my $to=shift;
  798. my $from=shift;
  799. inject(name => "IkiWiki::beautify_urlpath", call => $origsubs{'beautify_urlpath'});
  800. my $res=urlto($to, $from);
  801. inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath);
  802. return $res;
  803. }
  804. sub percenttranslated ($) {
  805. my $page=shift;
  806. $page=~s/^\///;
  807. return gettext("N/A") unless istranslation($page);
  808. my $file=srcfile($pagesources{$page});
  809. my $masterfile = srcfile($pagesources{masterpage($page)});
  810. my %options = (
  811. "markdown" => (pagetype($masterfile) eq 'mdwn') ? 1 : 0,
  812. );
  813. my $doc=Locale::Po4a::Chooser::new('text',%options);
  814. $doc->process(
  815. 'po_in_name' => [ $file ],
  816. 'file_in_name' => [ $masterfile ],
  817. 'file_in_charset' => 'utf-8',
  818. 'file_out_charset' => 'utf-8',
  819. ) or error("po(percenttranslated) ".
  820. sprintf(gettext("failed to translate %s"), $page));
  821. my ($percent,$hit,$queries) = $doc->stats();
  822. $percent =~ s/\.[0-9]+$//;
  823. return $percent;
  824. }
  825. sub languagename ($) {
  826. my $code=shift;
  827. return $config{po_master_language}{name}
  828. if $code eq $config{po_master_language}{code};
  829. return $config{po_slave_languages}{$code}
  830. if defined $config{po_slave_languages}{$code};
  831. return;
  832. }
  833. sub otherlanguagesloop ($) {
  834. my $page=shift;
  835. my @ret;
  836. my %otherpages=%{otherlanguages($page)};
  837. while (my ($lang, $otherpage) = each %otherpages) {
  838. if (istranslation($page) && masterpage($page) eq $otherpage) {
  839. push @ret, {
  840. url => urlto_with_orig_beautiful_urlpath($otherpage, $page),
  841. code => $lang,
  842. language => languagename($lang),
  843. master => 1,
  844. };
  845. }
  846. elsif (istranslation($otherpage)) {
  847. push @ret, {
  848. url => urlto_with_orig_beautiful_urlpath($otherpage, $page),
  849. code => $lang,
  850. language => languagename($lang),
  851. percent => percenttranslated($otherpage),
  852. }
  853. }
  854. }
  855. return sort {
  856. return -1 if $a->{code} eq $config{po_master_language}{code};
  857. return 1 if $b->{code} eq $config{po_master_language}{code};
  858. return $a->{language} cmp $b->{language};
  859. } @ret;
  860. }
  861. sub homepageurl (;$) {
  862. my $page=shift;
  863. return urlto('', $page);
  864. }
  865. sub ishomepage ($) {
  866. my $page = shift;
  867. return 1 if $page eq 'index';
  868. map { return 1 if $page eq 'index.'.$_ } keys %{$config{po_slave_languages}};
  869. return undef;
  870. }
  871. sub deletetranslations ($) {
  872. my $deletedmasterfile=shift;
  873. my $deletedmasterpage=pagename($deletedmasterfile);
  874. my @todelete;
  875. map {
  876. my $file = newpagefile($deletedmasterpage.'.'.$_, 'po');
  877. my $absfile = "$config{srcdir}/$file";
  878. if (-e $absfile && ! -l $absfile && ! -d $absfile) {
  879. push @todelete, $file;
  880. }
  881. } keys %{$config{po_slave_languages}};
  882. map {
  883. if ($config{rcs}) {
  884. IkiWiki::rcs_remove($_);
  885. }
  886. else {
  887. IkiWiki::prune("$config{srcdir}/$_");
  888. }
  889. } @todelete;
  890. if (@todelete) {
  891. commit_and_refresh(
  892. gettext("removed obsolete PO files"),
  893. "IkiWiki::Plugin::po::deletetranslations");
  894. }
  895. }
  896. sub commit_and_refresh ($$) {
  897. my ($msg, $author) = (shift, shift);
  898. if ($config{rcs}) {
  899. IkiWiki::disable_commit_hook();
  900. IkiWiki::rcs_commit_staged($msg, $author, "127.0.0.1");
  901. IkiWiki::enable_commit_hook();
  902. IkiWiki::rcs_update();
  903. }
  904. # Reinitialize module's private variables.
  905. resetalreadyfiltered();
  906. resettranslationscache();
  907. flushmemoizecache();
  908. # Trigger a wiki refresh.
  909. require IkiWiki::Render;
  910. # without preliminary saveindex/loadindex, refresh()
  911. # complains about a lot of uninitialized variables
  912. IkiWiki::saveindex();
  913. IkiWiki::loadindex();
  914. IkiWiki::refresh();
  915. IkiWiki::saveindex();
  916. }
  917. sub po_to_markup ($$) {
  918. my ($page, $content) = (shift, shift);
  919. $content = '' unless defined $content;
  920. $content = decode_utf8(encode_utf8($content));
  921. # CRLF line terminators make poor Locale::Po4a feel bad
  922. $content=~s/\r\n/\n/g;
  923. # There are incompatibilities between some File::Temp versions
  924. # (including 0.18, bundled with Lenny's perl-modules package)
  925. # and others (e.g. 0.20, previously present in the archive as
  926. # a standalone package): under certain circumstances, some
  927. # return a relative filename, whereas others return an absolute one;
  928. # we here use this module in a way that is at least compatible
  929. # with 0.18 and 0.20. Beware, hit'n'run refactorers!
  930. my $infile = new File::Temp(TEMPLATE => "ikiwiki-po-filter-in.XXXXXXXXXX",
  931. DIR => File::Spec->tmpdir,
  932. UNLINK => 1)->filename;
  933. my $outfile = new File::Temp(TEMPLATE => "ikiwiki-po-filter-out.XXXXXXXXXX",
  934. DIR => File::Spec->tmpdir,
  935. UNLINK => 1)->filename;
  936. my $fail = sub ($) {
  937. my $msg = "po(po_to_markup) - $page : " . shift;
  938. error($msg, sub { unlink $infile, $outfile});
  939. };
  940. writefile(basename($infile), File::Spec->tmpdir, $content)
  941. or return $fail->(sprintf(gettext("failed to write %s"), $infile));
  942. my $masterfile = srcfile($pagesources{masterpage($page)});
  943. my %options = (
  944. "markdown" => (pagetype($masterfile) eq 'mdwn') ? 1 : 0,
  945. );
  946. my $doc=Locale::Po4a::Chooser::new('text',%options);
  947. $doc->process(
  948. 'po_in_name' => [ $infile ],
  949. 'file_in_name' => [ $masterfile ],
  950. 'file_in_charset' => 'utf-8',
  951. 'file_out_charset' => 'utf-8',
  952. ) or return $fail->(gettext("failed to translate"));
  953. $doc->write($outfile)
  954. or return $fail->(sprintf(gettext("failed to write %s"), $outfile));
  955. $content = readfile($outfile);
  956. # Unlinking should happen automatically, thanks to File::Temp,
  957. # but it does not work here, probably because of the way writefile()
  958. # and Locale::Po4a::write() work.
  959. unlink $infile, $outfile;
  960. return $content;
  961. }
  962. # returns a SuccessReason or FailReason object
  963. sub isvalidpo ($) {
  964. my $content = shift;
  965. # NB: we don't use po_to_markup here, since Po4a parser does
  966. # not mind invalid PO content
  967. $content = '' unless defined $content;
  968. $content = decode_utf8(encode_utf8($content));
  969. # There are incompatibilities between some File::Temp versions
  970. # (including 0.18, bundled with Lenny's perl-modules package)
  971. # and others (e.g. 0.20, previously present in the archive as
  972. # a standalone package): under certain circumstances, some
  973. # return a relative filename, whereas others return an absolute one;
  974. # we here use this module in a way that is at least compatible
  975. # with 0.18 and 0.20. Beware, hit'n'run refactorers!
  976. my $infile = new File::Temp(TEMPLATE => "ikiwiki-po-isvalidpo.XXXXXXXXXX",
  977. DIR => File::Spec->tmpdir,
  978. UNLINK => 1)->filename;
  979. my $fail = sub ($) {
  980. my $msg = '[po/isvalidpo] ' . shift;
  981. unlink $infile;
  982. return IkiWiki::FailReason->new("$msg");
  983. };
  984. writefile(basename($infile), File::Spec->tmpdir, $content)
  985. or return $fail->(sprintf(gettext("failed to write %s"), $infile));
  986. my $res = (system("msgfmt", "--check", $infile, "-o", "/dev/null") == 0);
  987. # Unlinking should happen automatically, thanks to File::Temp,
  988. # but it does not work here, probably because of the way writefile()
  989. # and Locale::Po4a::write() work.
  990. unlink $infile;
  991. if ($res) {
  992. return IkiWiki::SuccessReason->new("valid gettext data");
  993. }
  994. return IkiWiki::FailReason->new(gettext("invalid gettext data, go back ".
  995. "to previous page to continue edit"));
  996. }
  997. # ,----
  998. # | PageSpecs
  999. # `----
  1000. package IkiWiki::PageSpec;
  1001. sub match_istranslation ($;@) {
  1002. my $page=shift;
  1003. if (IkiWiki::Plugin::po::istranslation($page)) {
  1004. return IkiWiki::SuccessReason->new("is a translation page");
  1005. }
  1006. else {
  1007. return IkiWiki::FailReason->new("is not a translation page");
  1008. }
  1009. }
  1010. sub match_istranslatable ($;@) {
  1011. my $page=shift;
  1012. if (IkiWiki::Plugin::po::istranslatable($page)) {
  1013. return IkiWiki::SuccessReason->new("is set as translatable in po_translatable_pages");
  1014. }
  1015. else {
  1016. return IkiWiki::FailReason->new("is not set as translatable in po_translatable_pages");
  1017. }
  1018. }
  1019. sub match_lang ($$;@) {
  1020. my $page=shift;
  1021. my $wanted=shift;
  1022. my $regexp=IkiWiki::glob2re($wanted);
  1023. my $lang=IkiWiki::Plugin::po::lang($page);
  1024. if ($lang !~ /^$regexp$/i) {
  1025. return IkiWiki::FailReason->new("file language is $lang, not $wanted");
  1026. }
  1027. else {
  1028. return IkiWiki::SuccessReason->new("file language is $wanted");
  1029. }
  1030. }
  1031. sub match_currentlang ($$;@) {
  1032. my $page=shift;
  1033. shift;
  1034. my %params=@_;
  1035. return IkiWiki::FailReason->new("no location provided") unless exists $params{location};
  1036. my $currentlang=IkiWiki::Plugin::po::lang($params{location});
  1037. my $lang=IkiWiki::Plugin::po::lang($page);
  1038. if ($lang eq $currentlang) {
  1039. return IkiWiki::SuccessReason->new("file language is the same as current one, i.e. $currentlang");
  1040. }
  1041. else {
  1042. return IkiWiki::FailReason->new("file language is $lang, whereas current language is $currentlang");
  1043. }
  1044. }
  1045. 1