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