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