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