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