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