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