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