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