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