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