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