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