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