summaryrefslogtreecommitdiff
path: root/IkiWiki/Plugin/po.pm
blob: f3530faf32d1b710d84c6abc6acb5dfa6182141f (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. }
  200. sub scan (@) {
  201. my %params=@_;
  202. my $page=$params{page};
  203. my $content=$params{content};
  204. my $run_by_po=$params{run_by_po};
  205. # Massage the recorded state of internal links so that:
  206. # - it matches the actually generated links, rather than the links as
  207. # written in the pages' source
  208. # - backlinks are consistent in all cases
  209. # A second scan pass is made over translation pages, so as an
  210. # optimization, we only do so on the second pass in this case,
  211. # i.e. when this hook is called by itself.
  212. if ($run_by_po && istranslation($page)) {
  213. # replace the occurence of $destpage in $links{$page}
  214. my @orig_links = @{$links{$page}};
  215. $links{$page} = [];
  216. foreach my $destpage (@orig_links) {
  217. if (istranslatedto($destpage, lang($page))) {
  218. add_link($page, $destpage . '.' . lang($page));
  219. }
  220. else {
  221. add_link($page, $destpage);
  222. }
  223. }
  224. }
  225. # No second scan pass is done for a non-translation page, so
  226. # links massaging must happen on first pass in this case.
  227. elsif (! $run_by_po && ! istranslatable($page) && ! istranslation($page)) {
  228. foreach my $destpage (@{$links{$page}}) {
  229. if (istranslatable($destpage)) {
  230. # make sure any destpage's translations has
  231. # $page in its backlinks
  232. foreach my $link (values %{otherlanguages_pages($destpage)}) {
  233. add_link($page, $link);
  234. }
  235. }
  236. }
  237. }
  238. # Re-run the preprocess hooks in scan mode, then the scan hooks,
  239. # over the po-to-markup converted content
  240. return if $run_by_po; # avoid looping endlessly
  241. return unless istranslation($page);
  242. $content = po_to_markup($page, $content);
  243. require IkiWiki;
  244. IkiWiki::preprocess($page, $page, $content, 1);
  245. IkiWiki::run_hooks(scan => sub {
  246. shift->(
  247. page => $page,
  248. content => $content,
  249. run_by_po => 1,
  250. );
  251. });
  252. }
  253. # We use filter to convert PO to the master page's format,
  254. # since the rest of ikiwiki should not work on PO files.
  255. sub filter (@) {
  256. my %params = @_;
  257. my $page = $params{page};
  258. my $destpage = $params{destpage};
  259. my $content = $params{content};
  260. if (istranslation($page) && ! alreadyfiltered($page, $destpage)) {
  261. $content = po_to_markup($page, $content);
  262. setalreadyfiltered($page, $destpage);
  263. }
  264. return $content;
  265. }
  266. sub htmlize (@) {
  267. my %params=@_;
  268. my $page = $params{page};
  269. my $content = $params{content};
  270. # ignore PO files this plugin did not create
  271. return $content unless istranslation($page);
  272. # force content to be htmlize'd as if it was the same type as the master page
  273. return IkiWiki::htmlize($page, $page,
  274. pagetype(srcfile($pagesources{masterpage($page)})),
  275. $content);
  276. }
  277. sub pagetemplate (@) {
  278. my %params=@_;
  279. my $page=$params{page};
  280. my $destpage=$params{destpage};
  281. my $template=$params{template};
  282. my ($masterpage, $lang) = istranslation($page);
  283. if (istranslation($page) && $template->query(name => "percenttranslated")) {
  284. $template->param(percenttranslated => percenttranslated($page));
  285. }
  286. if ($template->query(name => "istranslation")) {
  287. $template->param(istranslation => scalar istranslation($page));
  288. }
  289. if ($template->query(name => "istranslatable")) {
  290. $template->param(istranslatable => istranslatable($page));
  291. }
  292. if ($template->query(name => "HOMEPAGEURL")) {
  293. $template->param(homepageurl => homepageurl($page));
  294. }
  295. if ($template->query(name => "otherlanguages")) {
  296. $template->param(otherlanguages => [otherlanguagesloop($page)]);
  297. map add_depends($page, $_), (values %{otherlanguages_pages($page)});
  298. }
  299. if ($config{discussion} && istranslation($page)) {
  300. if ($page !~ /.*\/\Q$config{discussionpage}\E$/i &&
  301. (length $config{cgiurl} ||
  302. exists $links{$masterpage."/".lc($config{discussionpage})})) {
  303. $template->param('discussionlink' => htmllink(
  304. $page,
  305. $destpage,
  306. $masterpage . '/' . $config{discussionpage},
  307. noimageinline => 1,
  308. forcesubpage => 0,
  309. linktext => $config{discussionpage},
  310. ));
  311. }
  312. }
  313. # Remove broken parentlink to ./index.html on home page's translations.
  314. # It works because this hook has the "last" parameter set, to ensure it
  315. # runs after parentlinks' own pagetemplate hook.
  316. if ($template->param('parentlinks')
  317. && istranslation($page)
  318. && $masterpage eq "index") {
  319. $template->param('parentlinks' => []);
  320. }
  321. if (ishomepage($page) && $template->query(name => "title")) {
  322. $template->param(title => $config{wikiname});
  323. }
  324. }
  325. # Add the renamed page translations to the list of to-be-renamed pages.
  326. sub renamepages (@) {
  327. my %params = @_;
  328. my %torename = %{$params{torename}};
  329. my $session = $params{session};
  330. # Save the page(s) the user asked to rename, so that our
  331. # canrename hook can tell the difference between:
  332. # - a translation being renamed as a consequence of its master page
  333. # being renamed
  334. # - a user trying to directly rename a translation
  335. # This is why this hook has to be run first, before the list of pages
  336. # to rename is modified by other plugins.
  337. my @orig_torename;
  338. @orig_torename=@{$session->param("po_orig_torename")}
  339. if defined $session->param("po_orig_torename");
  340. push @orig_torename, $torename{src};
  341. $session->param(po_orig_torename => \@orig_torename);
  342. IkiWiki::cgi_savesession($session);
  343. return () unless istranslatable($torename{src});
  344. my @ret;
  345. my %otherpages=%{otherlanguages_pages($torename{src})};
  346. while (my ($lang, $otherpage) = each %otherpages) {
  347. push @ret, {
  348. src => $otherpage,
  349. srcfile => $pagesources{$otherpage},
  350. dest => otherlanguage_page($torename{dest}, $lang),
  351. destfile => $torename{dest}.".".$lang.".po",
  352. required => 0,
  353. };
  354. }
  355. return @ret;
  356. }
  357. sub mydelete (@) {
  358. my @deleted=@_;
  359. map { deletetranslations($_) } grep istranslatablefile($_), @deleted;
  360. }
  361. sub change (@) {
  362. my @rendered=@_;
  363. my $updated_po_files=0;
  364. # Refresh/create POT and PO files as needed.
  365. foreach my $file (grep {istranslatablefile($_)} @rendered) {
  366. my $masterfile=srcfile($file);
  367. my $page=pagename($file);
  368. my $updated_pot_file=0;
  369. # Avoid touching underlay files.
  370. next if $masterfile ne "$config{srcdir}/$file";
  371. # Only refresh POT file if it does not exist, or if
  372. # the source was changed: don't if only the HTML was
  373. # refreshed, e.g. because of a dependency.
  374. if ((grep { $_ eq $pagesources{$page} } @origneedsbuild) ||
  375. ! -e potfile($masterfile)) {
  376. refreshpot($masterfile);
  377. $updated_pot_file=1;
  378. }
  379. my @pofiles;
  380. foreach my $po (pofiles($masterfile)) {
  381. next if ! $updated_pot_file && -e $po;
  382. next if grep { $po=~/\Q$_\E/ } @{$config{underlaydirs}};
  383. push @pofiles, $po;
  384. }
  385. if (@pofiles) {
  386. refreshpofiles($masterfile, @pofiles);
  387. map { s/^\Q$config{srcdir}\E\/*//; IkiWiki::rcs_add($_) } @pofiles if $config{rcs};
  388. $updated_po_files=1;
  389. }
  390. }
  391. if ($updated_po_files) {
  392. commit_and_refresh(
  393. gettext("updated PO files"));
  394. }
  395. }
  396. sub checkcontent (@) {
  397. my %params=@_;
  398. if (istranslation($params{page})) {
  399. my $res = isvalidpo($params{content});
  400. if ($res) {
  401. return undef;
  402. }
  403. else {
  404. return "$res";
  405. }
  406. }
  407. return undef;
  408. }
  409. sub canremove (@) {
  410. my %params = @_;
  411. if (istranslation($params{page})) {
  412. return gettext("Can not remove a translation. If the master page is removed, ".
  413. "however, its translations will be removed as well.");
  414. }
  415. return undef;
  416. }
  417. sub canrename (@) {
  418. my %params = @_;
  419. my $session = $params{session};
  420. if (istranslation($params{src})) {
  421. my $masterpage = masterpage($params{src});
  422. # Tell the difference between:
  423. # - a translation being renamed as a consequence of its master page
  424. # being renamed, which is allowed
  425. # - a user trying to directly rename a translation, which is forbidden
  426. # by looking for the master page in the list of to-be-renamed pages we
  427. # saved early in the renaming process.
  428. my $orig_torename = $session->param("po_orig_torename");
  429. unless (grep { $_ eq $masterpage } @{$orig_torename}) {
  430. return gettext("Can not rename a translation. If the master page is renamed, ".
  431. "however, its translations will be renamed as well.");
  432. }
  433. }
  434. return undef;
  435. }
  436. # As we're previewing or saving a page, the content may have
  437. # changed, so tell the next filter() invocation it must not be lazy.
  438. sub editcontent () {
  439. my %params=@_;
  440. unsetalreadyfiltered($params{page}, $params{page});
  441. return $params{content};
  442. }
  443. sub formbuilder_setup (@) {
  444. my %params=@_;
  445. my $form=$params{form};
  446. my $q=$params{cgi};
  447. return unless defined $form->field("do");
  448. if ($form->field("do") eq "create") {
  449. # Warn the user: new pages must be written in master language.
  450. my $template=template("pocreatepage.tmpl");
  451. $template->param(LANG => $config{po_master_language}{name});
  452. $form->tmpl_param(message => $template->output);
  453. }
  454. elsif ($form->field("do") eq "edit") {
  455. # Remove the rename/remove buttons on slave pages.
  456. # This has to be done after the rename/remove plugins have added
  457. # their buttons, which is why this hook must be run last.
  458. # The canrename/canremove hooks already ensure this is forbidden
  459. # at the backend level, so this is only UI sugar.
  460. if (istranslation($form->field("page"))) {
  461. map {
  462. for (my $i = 0; $i < @{$params{buttons}}; $i++) {
  463. if (@{$params{buttons}}[$i] eq $_) {
  464. delete @{$params{buttons}}[$i];
  465. last;
  466. }
  467. }
  468. } qw(Rename Remove);
  469. }
  470. }
  471. }
  472. sub formbuilder (@) {
  473. my %params=@_;
  474. my $form=$params{form};
  475. my $q=$params{cgi};
  476. return unless defined $form->field("do");
  477. # Do not allow to create pages of type po: they are automatically created.
  478. # The main reason to do so is to bypass the "favor the type of linking page
  479. # on page creation" logic, which is unsuitable when a broken link is clicked
  480. # on a slave (PO) page.
  481. # This cannot be done in the formbuilder_setup hook as the list of types is
  482. # computed later.
  483. if ($form->field("do") eq "create") {
  484. foreach my $field ($form->field) {
  485. next unless "$field" eq "type";
  486. next unless $field->type eq 'select';
  487. my $orig_value = $field->value;
  488. # remove po from the list of types
  489. my @types = grep { $_->[0] ne 'po' } $field->options;
  490. $field->options(\@types) if @types;
  491. # favor the type of linking page's masterpage
  492. if ($orig_value eq 'po') {
  493. my ($from, $type);
  494. if (defined $form->field('from')) {
  495. ($from)=$form->field('from')=~/$config{wiki_file_regexp}/;
  496. $from = masterpage($from);
  497. }
  498. if (defined $from && exists $pagesources{$from}) {
  499. $type=pagetype($pagesources{$from});
  500. }
  501. $type=$config{default_pageext} unless defined $type;
  502. $field->value($type) ;
  503. }
  504. }
  505. }
  506. }
  507. # ,----
  508. # | Injected functions
  509. # `----
  510. # Implement po_link_to 'current' and 'negotiated' settings.
  511. sub mybestlink ($$) {
  512. my $page=shift;
  513. my $link=shift;
  514. return $origsubs{'bestlink'}->($page, $link)
  515. if defined $config{po_link_to} && $config{po_link_to} eq "default";
  516. my $res=$origsubs{'bestlink'}->(masterpage($page), $link);
  517. my @caller = caller(1);
  518. if (length $res
  519. && istranslatedto($res, lang($page))
  520. && istranslation($page)
  521. && !(exists $caller[3] && defined $caller[3]
  522. && ($caller[3] eq "IkiWiki::PageSpec::match_link"))) {
  523. return $res . "." . lang($page);
  524. }
  525. return $res;
  526. }
  527. sub mybeautify_urlpath ($) {
  528. my $url=shift;
  529. my $res=$origsubs{'beautify_urlpath'}->($url);
  530. if (defined $config{po_link_to} && $config{po_link_to} eq "negotiated") {
  531. $res =~ s!/\Qindex.$config{po_master_language}{code}.$config{htmlext}\E$!/!;
  532. $res =~ s!/\Qindex.$config{htmlext}\E$!/!;
  533. map {
  534. $res =~ s!/\Qindex.$_.$config{htmlext}\E$!/!;
  535. } @slavelanguages;
  536. }
  537. return $res;
  538. }
  539. sub mytargetpage ($$) {
  540. my $page=shift;
  541. my $ext=shift;
  542. if (istranslation($page) || istranslatable($page)) {
  543. my ($masterpage, $lang) = (masterpage($page), lang($page));
  544. if (! $config{usedirs} || $masterpage eq 'index') {
  545. return $masterpage . "." . $lang . "." . $ext;
  546. }
  547. else {
  548. return $masterpage . "/index." . $lang . "." . $ext;
  549. }
  550. }
  551. return $origsubs{'targetpage'}->($page, $ext);
  552. }
  553. sub myurlto ($$;$) {
  554. my $to=shift;
  555. my $from=shift;
  556. my $absolute=shift;
  557. # workaround hard-coded /index.$config{htmlext} in IkiWiki::urlto()
  558. if (! length $to
  559. && $config{po_link_to} eq "current"
  560. && istranslatable('index')) {
  561. return IkiWiki::beautify_urlpath(IkiWiki::baseurl($from) . "index." . lang($from) . ".$config{htmlext}");
  562. }
  563. # avoid using our injected beautify_urlpath if run by cgi_editpage,
  564. # so that one is redirected to the just-edited page rather than to the
  565. # negociated translation; to prevent unnecessary fiddling with caller/inject,
  566. # we only do so when our beautify_urlpath would actually do what we want to
  567. # avoid, i.e. when po_link_to = negotiated.
  568. # also avoid doing so when run by cgi_goto, so that the links on recentchanges
  569. # page actually lead to the exact page they pretend to.
  570. if ($config{po_link_to} eq "negotiated") {
  571. my @caller = caller(1);
  572. my $use_orig = 0;
  573. $use_orig = 1 if (exists $caller[3] && defined $caller[3]
  574. && ($caller[3] eq "IkiWiki::cgi_editpage" ||
  575. $caller[3] eq "IkiWiki::Plugin::goto::cgi_goto")
  576. );
  577. inject(name => "IkiWiki::beautify_urlpath", call => $origsubs{'beautify_urlpath'})
  578. if $use_orig;
  579. my $res = $origsubs{'urlto'}->($to,$from,$absolute);
  580. inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath)
  581. if $use_orig;
  582. return $res;
  583. }
  584. else {
  585. return $origsubs{'urlto'}->($to,$from,$absolute)
  586. }
  587. }
  588. sub mycgiurl (@) {
  589. my %params=@_;
  590. # slave pages have no subpages
  591. if (istranslation($params{'from'})) {
  592. $params{'from'} = masterpage($params{'from'});
  593. }
  594. return $origsubs{'cgiurl'}->(%params);
  595. }
  596. sub myrootpage (@) {
  597. my %params=@_;
  598. my $rootpage;
  599. if (exists $params{rootpage}) {
  600. $rootpage=$origsubs{'bestlink'}->($params{page}, $params{rootpage});
  601. if (!length $rootpage) {
  602. $rootpage=$params{rootpage};
  603. }
  604. }
  605. else {
  606. $rootpage=masterpage($params{page});
  607. }
  608. return $rootpage;
  609. }
  610. sub myisselflink ($$) {
  611. my $page=shift;
  612. my $link=shift;
  613. return 1 if $origsubs{'isselflink'}->($page, $link);
  614. if (istranslation($page)) {
  615. return $origsubs{'isselflink'}->(masterpage($page), $link);
  616. }
  617. return;
  618. }
  619. # ,----
  620. # | Blackboxes for private data
  621. # `----
  622. {
  623. my %filtered;
  624. sub alreadyfiltered($$) {
  625. my $page=shift;
  626. my $destpage=shift;
  627. return exists $filtered{$page}{$destpage}
  628. && $filtered{$page}{$destpage} eq 1;
  629. }
  630. sub setalreadyfiltered($$) {
  631. my $page=shift;
  632. my $destpage=shift;
  633. $filtered{$page}{$destpage}=1;
  634. }
  635. sub unsetalreadyfiltered($$) {
  636. my $page=shift;
  637. my $destpage=shift;
  638. if (exists $filtered{$page}{$destpage}) {
  639. delete $filtered{$page}{$destpage};
  640. }
  641. }
  642. sub resetalreadyfiltered() {
  643. undef %filtered;
  644. }
  645. }
  646. # ,----
  647. # | Helper functions
  648. # `----
  649. sub maybe_add_leading_slash ($;$) {
  650. my $str=shift;
  651. my $add=shift;
  652. $add=1 unless defined $add;
  653. return '/' . $str if $add;
  654. return $str;
  655. }
  656. sub istranslatablefile ($) {
  657. my $file=shift;
  658. return 0 unless defined $file;
  659. my $type=pagetype($file);
  660. return 0 if ! defined $type || $type eq 'po';
  661. return 0 if $file =~ /\.pot$/;
  662. return 0 if ! defined $config{po_translatable_pages};
  663. return 1 if pagespec_match(pagename($file), $config{po_translatable_pages});
  664. return;
  665. }
  666. sub istranslatable ($) {
  667. my $page=shift;
  668. $page=~s#^/##;
  669. return 1 if istranslatablefile($pagesources{$page});
  670. return;
  671. }
  672. sub istranslatedto ($$) {
  673. my $page=shift;
  674. my $destlang = shift;
  675. $page=~s#^/##;
  676. return 0 unless istranslatable($page);
  677. exists $pagesources{otherlanguage_page($page, $destlang)};
  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. if ($lang eq $config{po_master_language}{code} ||
  741. istranslatedto(masterpage($page), $lang)) {
  742. push @ret, $lang;
  743. }
  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, $_), @slavelanguages;
  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.'.$_ } @slavelanguages;
  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. } @slavelanguages;
  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