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