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