summaryrefslogtreecommitdiff
path: root/IkiWiki/Plugin/po.pm
blob: 6395ebdc2f99f91e3316b89cb017d157e895f81b (plain)
  1. #!/usr/bin/perl
  2. # .po as a wiki page type
  3. # Licensed under GPL v2 or greater
  4. # Copyright (C) 2008-2009 intrigeri <intrigeri@boum.org>
  5. # inspired by the GPL'd po4a-translate,
  6. # which is Copyright 2002, 2003, 2004 by Martin Quinson (mquinson#debian.org)
  7. package IkiWiki::Plugin::po;
  8. use warnings;
  9. use strict;
  10. use IkiWiki 3.00;
  11. use Encode;
  12. eval q{use Locale::Po4a::Common qw(nowrapi18n !/.*/)};
  13. if ($@) {
  14. print STDERR gettext("warning: Old po4a detected! Recommend upgrade to 0.35.")."\n";
  15. eval q{use Locale::Po4a::Common qw(!/.*/)};
  16. die $@ if $@;
  17. }
  18. use Locale::Po4a::Chooser;
  19. use Locale::Po4a::Po;
  20. use File::Basename;
  21. use File::Copy;
  22. use File::Spec;
  23. use File::Temp;
  24. use Memoize;
  25. use UNIVERSAL;
  26. my %translations;
  27. my @origneedsbuild;
  28. my %origsubs;
  29. my @slavelanguages; # language codes ordered as in config po_slave_languages
  30. memoize("istranslatable");
  31. memoize("_istranslation");
  32. memoize("percenttranslated");
  33. sub import {
  34. hook(type => "getsetup", id => "po", call => \&getsetup);
  35. hook(type => "checkconfig", id => "po", call => \&checkconfig);
  36. hook(type => "needsbuild", id => "po", call => \&needsbuild);
  37. hook(type => "scan", id => "po", call => \&scan, last => 1);
  38. hook(type => "filter", id => "po", call => \&filter);
  39. hook(type => "htmlize", id => "po", call => \&htmlize);
  40. hook(type => "pagetemplate", id => "po", call => \&pagetemplate, last => 1);
  41. hook(type => "rename", id => "po", call => \&renamepages, first => 1);
  42. hook(type => "delete", id => "po", call => \&mydelete);
  43. hook(type => "change", id => "po", call => \&change);
  44. hook(type => "checkcontent", id => "po", call => \&checkcontent);
  45. hook(type => "canremove", id => "po", call => \&canremove);
  46. hook(type => "canrename", id => "po", call => \&canrename);
  47. hook(type => "editcontent", id => "po", call => \&editcontent);
  48. hook(type => "formbuilder_setup", id => "po", call => \&formbuilder_setup, last => 1);
  49. hook(type => "formbuilder", id => "po", call => \&formbuilder);
  50. if (! %origsubs) {
  51. $origsubs{'bestlink'}=\&IkiWiki::bestlink;
  52. inject(name => "IkiWiki::bestlink", call => \&mybestlink);
  53. $origsubs{'beautify_urlpath'}=\&IkiWiki::beautify_urlpath;
  54. inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath);
  55. $origsubs{'targetpage'}=\&IkiWiki::targetpage;
  56. inject(name => "IkiWiki::targetpage", call => \&mytargetpage);
  57. $origsubs{'urlto'}=\&IkiWiki::urlto;
  58. inject(name => "IkiWiki::urlto", call => \&myurlto);
  59. $origsubs{'cgiurl'}=\&IkiWiki::cgiurl;
  60. inject(name => "IkiWiki::cgiurl", call => \&mycgiurl);
  61. $origsubs{'rootpage'}=\&IkiWiki::rootpage;
  62. inject(name => "IkiWiki::rootpage", call => \&myrootpage);
  63. $origsubs{'isselflink'}=\&IkiWiki::isselflink;
  64. inject(name => "IkiWiki::isselflink", call => \&myisselflink);
  65. }
  66. }
  67. # ,----
  68. # | Table of contents
  69. # `----
  70. # 1. Hooks
  71. # 2. Injected functions
  72. # 3. Blackboxes for private data
  73. # 4. Helper functions
  74. # 5. PageSpecs
  75. # ,----
  76. # | Hooks
  77. # `----
  78. sub getsetup () {
  79. return
  80. plugin => {
  81. safe => 0,
  82. rebuild => 1, # format plugin
  83. section => "format",
  84. },
  85. po_master_language => {
  86. type => "string",
  87. example => {
  88. 'code' => 'en',
  89. 'name' => 'English'
  90. },
  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 (PO files)",
  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. foreach my $field (qw{po_master_language}) {
  124. if (! exists $config{$field} || ! defined $config{$field}) {
  125. error(sprintf(gettext("Must specify %s when using the %s plugin"),
  126. $field, 'po'));
  127. }
  128. }
  129. if (ref $config{po_slave_languages} eq 'ARRAY') {
  130. my %slaves;
  131. foreach my $pair (@{$config{po_slave_languages}}) {
  132. my ($code, $name) = ( $pair =~ /^([a-z]{2})\|(.+)$/ );
  133. if (!defined $code || !defined $name) {
  134. error(sprintf(gettext("%s has invalid syntax: must use CODE|NAME"),
  135. $pair));
  136. }
  137. $slaves{$code} = $name;
  138. push @slavelanguages, $code;
  139. }
  140. $config{po_slave_languages} = \%slaves;
  141. }
  142. elsif (ref $config{po_slave_languages} eq 'HASH') {
  143. @slavelanguages = sort {
  144. $config{po_slave_languages}->{$a} cmp $config{po_slave_languages}->{$b};
  145. } keys %{$config{po_slave_languages}};
  146. }
  147. delete $config{po_slave_languages}{$config{po_master_language}{code}};;
  148. map {
  149. islanguagecode($_)
  150. or error(sprintf(gettext("%s is not a valid language code"), $_));
  151. } ($config{po_master_language}{code}, @slavelanguages);
  152. if (! exists $config{po_translatable_pages} ||
  153. ! defined $config{po_translatable_pages}) {
  154. $config{po_translatable_pages}="";
  155. }
  156. if (! exists $config{po_link_to} ||
  157. ! defined $config{po_link_to}) {
  158. $config{po_link_to}='default';
  159. }
  160. elsif ($config{po_link_to} !~ /^(default|current|negotiated)$/) {
  161. warn(sprintf(gettext('%s is not a valid value for po_link_to, falling back to po_link_to=default'),
  162. $config{po_link_to}));
  163. $config{po_link_to}='default';
  164. }
  165. elsif ($config{po_link_to} eq "negotiated" && ! $config{usedirs}) {
  166. warn(gettext('po_link_to=negotiated requires usedirs to be enabled, falling back to po_link_to=default'));
  167. $config{po_link_to}='default';
  168. }
  169. push @{$config{wiki_file_prune_regexps}}, qr/\.pot$/;
  170. # Translated versions of the underlays are added if available.
  171. foreach my $underlay ("basewiki",
  172. map { m/^\Q$config{underlaydirbase}\E\/*(.*)/ }
  173. reverse @{$config{underlaydirs}}) {
  174. next if $underlay=~/^locale\//;
  175. # Underlays containing the po files for slave languages.
  176. foreach my $ll (@slavelanguages) {
  177. add_underlay("po/$ll/$underlay")
  178. if -d "$config{underlaydirbase}/po/$ll/$underlay";
  179. }
  180. if ($config{po_master_language}{code} ne 'en') {
  181. # Add underlay containing translated source files
  182. # for the master language.
  183. add_underlay("locale/$config{po_master_language}{code}/$underlay")
  184. if -d "$config{underlaydirbase}/locale/$config{po_master_language}{code}/$underlay";
  185. }
  186. }
  187. }
  188. sub needsbuild () {
  189. my $needsbuild=shift;
  190. # backup @needsbuild content so that change() can know whether
  191. # a given master page was rendered because its source file was changed
  192. @origneedsbuild=(@$needsbuild);
  193. flushmemoizecache();
  194. buildtranslationscache();
  195. # make existing translations depend on the corresponding master page
  196. foreach my $master (keys %translations) {
  197. map add_depends($_, $master), values %{otherlanguages_pages($master)};
  198. }
  199. }
  200. # Massage the recorded state of internal links so that:
  201. # - it matches the actually generated links, rather than the links as written
  202. # in the pages' source
  203. # - backlinks are consistent in all cases
  204. sub scan (@) {
  205. my %params=@_;
  206. my $page=$params{page};
  207. my $content=$params{content};
  208. if (istranslation($page)) {
  209. foreach my $destpage (@{$links{$page}}) {
  210. if (istranslatable($destpage)) {
  211. # replace the occurence of $destpage in $links{$page}
  212. for (my $i=0; $i<@{$links{$page}}; $i++) {
  213. if (@{$links{$page}}[$i] eq $destpage) {
  214. @{$links{$page}}[$i] = $destpage . '.' . lang($page);
  215. last;
  216. }
  217. }
  218. }
  219. }
  220. }
  221. elsif (! istranslatable($page) && ! istranslation($page)) {
  222. foreach my $destpage (@{$links{$page}}) {
  223. if (istranslatable($destpage)) {
  224. # make sure any destpage's translations has
  225. # $page in its backlinks
  226. push @{$links{$page}},
  227. values %{otherlanguages_pages($destpage)};
  228. }
  229. }
  230. }
  231. }
  232. # We use filter to convert PO to the master page's format,
  233. # since the rest of ikiwiki should not work on PO files.
  234. sub filter (@) {
  235. my %params = @_;
  236. my $page = $params{page};
  237. my $destpage = $params{destpage};
  238. my $content = $params{content};
  239. if (istranslation($page) && ! alreadyfiltered($page, $destpage)) {
  240. $content = po_to_markup($page, $content);
  241. setalreadyfiltered($page, $destpage);
  242. }
  243. return $content;
  244. }
  245. sub htmlize (@) {
  246. my %params=@_;
  247. my $page = $params{page};
  248. my $content = $params{content};
  249. # ignore PO files this plugin did not create
  250. return $content unless istranslation($page);
  251. # force content to be htmlize'd as if it was the same type as the master page
  252. return IkiWiki::htmlize($page, $page,
  253. pagetype(srcfile($pagesources{masterpage($page)})),
  254. $content);
  255. }
  256. sub pagetemplate (@) {
  257. my %params=@_;
  258. my $page=$params{page};
  259. my $destpage=$params{destpage};
  260. my $template=$params{template};
  261. my ($masterpage, $lang) = istranslation($page);
  262. if (istranslation($page) && $template->query(name => "percenttranslated")) {
  263. $template->param(percenttranslated => percenttranslated($page));
  264. }
  265. if ($template->query(name => "istranslation")) {
  266. $template->param(istranslation => scalar istranslation($page));
  267. }
  268. if ($template->query(name => "istranslatable")) {
  269. $template->param(istranslatable => istranslatable($page));
  270. }
  271. if ($template->query(name => "HOMEPAGEURL")) {
  272. $template->param(homepageurl => homepageurl($page));
  273. }
  274. if ($template->query(name => "otherlanguages")) {
  275. $template->param(otherlanguages => [otherlanguagesloop($page)]);
  276. map add_depends($page, $_), (values %{otherlanguages_pages($page)});
  277. }
  278. if ($config{discussion} && istranslation($page)) {
  279. if ($page !~ /.*\/\Q$config{discussionpage}\E$/i &&
  280. (length $config{cgiurl} ||
  281. exists $links{$masterpage."/".lc($config{discussionpage})})) {
  282. $template->param('discussionlink' => htmllink(
  283. $page,
  284. $destpage,
  285. $masterpage . '/' . $config{discussionpage},
  286. noimageinline => 1,
  287. forcesubpage => 0,
  288. linktext => $config{discussionpage},
  289. ));
  290. }
  291. }
  292. # Remove broken parentlink to ./index.html on home page's translations.
  293. # It works because this hook has the "last" parameter set, to ensure it
  294. # runs after parentlinks' own pagetemplate hook.
  295. if ($template->param('parentlinks')
  296. && istranslation($page)
  297. && $masterpage eq "index") {
  298. $template->param('parentlinks' => []);
  299. }
  300. if (ishomepage($page) && $template->query(name => "title")) {
  301. $template->param(title => $config{wikiname});
  302. }
  303. }
  304. # Add the renamed page translations to the list of to-be-renamed pages.
  305. sub renamepages (@) {
  306. my %params = @_;
  307. my %torename = %{$params{torename}};
  308. my $session = $params{session};
  309. # Save the page(s) the user asked to rename, so that our
  310. # canrename hook can tell the difference between:
  311. # - a translation being renamed as a consequence of its master page
  312. # being renamed
  313. # - a user trying to directly rename a translation
  314. # This is why this hook has to be run first, before the list of pages
  315. # to rename is modified by other plugins.
  316. my @orig_torename;
  317. @orig_torename=@{$session->param("po_orig_torename")}
  318. if defined $session->param("po_orig_torename");
  319. push @orig_torename, $torename{src};
  320. $session->param(po_orig_torename => \@orig_torename);
  321. IkiWiki::cgi_savesession($session);
  322. return () unless istranslatable($torename{src});
  323. my @ret;
  324. my %otherpages=%{otherlanguages_pages($torename{src})};
  325. while (my ($lang, $otherpage) = each %otherpages) {
  326. push @ret, {
  327. src => $otherpage,
  328. srcfile => $pagesources{$otherpage},
  329. dest => otherlanguage_page($torename{dest}, $lang),
  330. destfile => $torename{dest}.".".$lang.".po",
  331. required => 0,
  332. };
  333. }
  334. return @ret;
  335. }
  336. sub mydelete (@) {
  337. my @deleted=@_;
  338. map { deletetranslations($_) } grep istranslatablefile($_), @deleted;
  339. }
  340. sub change (@) {
  341. my @rendered=@_;
  342. # All meta titles are first extracted at scan time, i.e. before we turn
  343. # PO files back into translated markdown; escaping of double-quotes in
  344. # PO files breaks the meta plugin's parsing enough to save ugly titles
  345. # to %pagestate at this time.
  346. #
  347. # Then, at render time, every page passes in turn through the Great
  348. # Rendering Chain (filter->preprocess->linkify->htmlize), and the meta
  349. # plugin's preprocess hook is this time in a position to correctly
  350. # extract the titles from slave pages.
  351. #
  352. # This is, unfortunately, too late: if the page A, linking to the page
  353. # B, is rendered before B, it will display the wrongly-extracted meta
  354. # title as the link text to B.
  355. #
  356. # On the one hand, such a corner case only happens on rebuild: on
  357. # refresh, every rendered page is fixed to contain correct meta titles.
  358. # On the other hand, it can take some time to get every page fixed.
  359. # We therefore re-render every rendered page after a rebuild to fix them
  360. # at once. As this more or less doubles the time needed to rebuild the
  361. # wiki, we do so only when really needed.
  362. if (@rendered
  363. && exists $config{rebuild} && defined $config{rebuild} && $config{rebuild}
  364. && UNIVERSAL::can("IkiWiki::Plugin::meta", "getsetup")
  365. && exists $config{meta_overrides_page_title}
  366. && defined $config{meta_overrides_page_title}
  367. && $config{meta_overrides_page_title}) {
  368. debug(sprintf(gettext("rebuilding all pages to fix meta titles")));
  369. resetalreadyfiltered();
  370. require IkiWiki::Render;
  371. foreach my $file (@rendered) {
  372. IkiWiki::render($file, sprintf(gettext("building %s"), $file));
  373. }
  374. }
  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 => $config{po_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. && istranslatable($res)
  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.$config{po_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. return IkiWiki::beautify_urlpath(IkiWiki::baseurl($from) . "index." . lang($from) . ".$config{htmlext}");
  574. }
  575. # avoid using our injected beautify_urlpath if run by cgi_editpage,
  576. # so that one is redirected to the just-edited page rather than to the
  577. # negociated translation; to prevent unnecessary fiddling with caller/inject,
  578. # we only do so when our beautify_urlpath would actually do what we want to
  579. # avoid, i.e. when po_link_to = negotiated.
  580. # also avoid doing so when run by cgi_goto, so that the links on recentchanges
  581. # page actually lead to the exact page they pretend to.
  582. if ($config{po_link_to} eq "negotiated") {
  583. my @caller = caller(1);
  584. my $use_orig = 0;
  585. $use_orig = 1 if (exists $caller[3] && defined $caller[3]
  586. && ($caller[3] eq "IkiWiki::cgi_editpage" ||
  587. $caller[3] eq "IkiWiki::Plugin::goto::cgi_goto")
  588. );
  589. inject(name => "IkiWiki::beautify_urlpath", call => $origsubs{'beautify_urlpath'})
  590. if $use_orig;
  591. my $res = $origsubs{'urlto'}->($to,$from,$absolute);
  592. inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath)
  593. if $use_orig;
  594. return $res;
  595. }
  596. else {
  597. return $origsubs{'urlto'}->($to,$from,$absolute)
  598. }
  599. }
  600. sub mycgiurl (@) {
  601. my %params=@_;
  602. # slave pages have no subpages
  603. if (istranslation($params{'from'})) {
  604. $params{'from'} = masterpage($params{'from'});
  605. }
  606. return $origsubs{'cgiurl'}->(%params);
  607. }
  608. sub myrootpage (@) {
  609. my %params=@_;
  610. my $rootpage;
  611. if (exists $params{rootpage}) {
  612. $rootpage=$origsubs{'bestlink'}->($params{page}, $params{rootpage});
  613. if (!length $rootpage) {
  614. $rootpage=$params{rootpage};
  615. }
  616. }
  617. else {
  618. $rootpage=masterpage($params{page});
  619. }
  620. return $rootpage;
  621. }
  622. sub myisselflink ($$) {
  623. my $page=shift;
  624. my $link=shift;
  625. return 1 if $origsubs{'isselflink'}->($page, $link);
  626. if (istranslation($page)) {
  627. return $origsubs{'isselflink'}->(masterpage($page), $link);
  628. }
  629. return;
  630. }
  631. # ,----
  632. # | Blackboxes for private data
  633. # `----
  634. {
  635. my %filtered;
  636. sub alreadyfiltered($$) {
  637. my $page=shift;
  638. my $destpage=shift;
  639. return exists $filtered{$page}{$destpage}
  640. && $filtered{$page}{$destpage} eq 1;
  641. }
  642. sub setalreadyfiltered($$) {
  643. my $page=shift;
  644. my $destpage=shift;
  645. $filtered{$page}{$destpage}=1;
  646. }
  647. sub unsetalreadyfiltered($$) {
  648. my $page=shift;
  649. my $destpage=shift;
  650. if (exists $filtered{$page}{$destpage}) {
  651. delete $filtered{$page}{$destpage};
  652. }
  653. }
  654. sub resetalreadyfiltered() {
  655. undef %filtered;
  656. }
  657. }
  658. # ,----
  659. # | Helper functions
  660. # `----
  661. sub maybe_add_leading_slash ($;$) {
  662. my $str=shift;
  663. my $add=shift;
  664. $add=1 unless defined $add;
  665. return '/' . $str if $add;
  666. return $str;
  667. }
  668. sub istranslatablefile ($) {
  669. my $file=shift;
  670. return 0 unless defined $file;
  671. my $type=pagetype($file);
  672. return 0 if ! defined $type || $type eq 'po';
  673. return 0 if $file =~ /\.pot$/;
  674. return 0 if ! defined $config{po_translatable_pages};
  675. return 1 if pagespec_match(pagename($file), $config{po_translatable_pages});
  676. return;
  677. }
  678. sub istranslatable ($) {
  679. my $page=shift;
  680. $page=~s#^/##;
  681. return 1 if istranslatablefile($pagesources{$page});
  682. return;
  683. }
  684. sub _istranslation ($) {
  685. my $page=shift;
  686. $page='' unless defined $page && length $page;
  687. my $hasleadingslash = ($page=~s#^/##);
  688. my $file=$pagesources{$page};
  689. return 0 unless defined $file
  690. && defined pagetype($file)
  691. && pagetype($file) eq 'po';
  692. return 0 if $file =~ /\.pot$/;
  693. my ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
  694. return 0 unless defined $masterpage && defined $lang
  695. && length $masterpage && length $lang
  696. && defined $pagesources{$masterpage}
  697. && defined $config{po_slave_languages}{$lang};
  698. return (maybe_add_leading_slash($masterpage, $hasleadingslash), $lang)
  699. if istranslatable($masterpage);
  700. }
  701. sub istranslation ($) {
  702. my $page=shift;
  703. if (1 < (my ($masterpage, $lang) = _istranslation($page))) {
  704. my $hasleadingslash = ($masterpage=~s#^/##);
  705. $translations{$masterpage}{$lang}=$page unless exists $translations{$masterpage}{$lang};
  706. return (maybe_add_leading_slash($masterpage, $hasleadingslash), $lang);
  707. }
  708. return "";
  709. }
  710. sub masterpage ($) {
  711. my $page=shift;
  712. if ( 1 < (my ($masterpage, $lang) = _istranslation($page))) {
  713. return $masterpage;
  714. }
  715. return $page;
  716. }
  717. sub lang ($) {
  718. my $page=shift;
  719. if (1 < (my ($masterpage, $lang) = _istranslation($page))) {
  720. return $lang;
  721. }
  722. return $config{po_master_language}{code};
  723. }
  724. sub islanguagecode ($) {
  725. my $code=shift;
  726. return $code =~ /^[a-z]{2}$/;
  727. }
  728. sub otherlanguage_page ($$) {
  729. my $page=shift;
  730. my $code=shift;
  731. return masterpage($page) if $code eq $config{po_master_language}{code};
  732. return masterpage($page) . '.' . $code;
  733. }
  734. # Returns the list of other languages codes: the master language comes first,
  735. # then the codes are ordered the same way as in po_slave_languages, if it is
  736. # an array, or in the language name lexical order, if it is a hash.
  737. sub otherlanguages_codes ($) {
  738. my $page=shift;
  739. my @ret;
  740. return \@ret unless istranslation($page) || istranslatable($page);
  741. my $curlang=lang($page);
  742. foreach my $lang
  743. ($config{po_master_language}{code}, @slavelanguages) {
  744. next if $lang eq $curlang;
  745. push @ret, $lang;
  746. }
  747. return \@ret;
  748. }
  749. sub otherlanguages_pages ($) {
  750. my $page=shift;
  751. my %ret;
  752. map {
  753. $ret{$_} = otherlanguage_page($page, $_)
  754. } @{otherlanguages_codes($page)};
  755. return \%ret;
  756. }
  757. sub potfile ($) {
  758. my $masterfile=shift;
  759. (my $name, my $dir, my $suffix) = fileparse($masterfile, qr/\.[^.]*/);
  760. $dir='' if $dir eq './';
  761. return File::Spec->catpath('', $dir, $name . ".pot");
  762. }
  763. sub pofile ($$) {
  764. my $masterfile=shift;
  765. my $lang=shift;
  766. (my $name, my $dir, my $suffix) = fileparse($masterfile, qr/\.[^.]*/);
  767. $dir='' if $dir eq './';
  768. return File::Spec->catpath('', $dir, $name . "." . $lang . ".po");
  769. }
  770. sub pofiles ($) {
  771. my $masterfile=shift;
  772. return map pofile($masterfile, $_), @slavelanguages;
  773. }
  774. sub refreshpot ($) {
  775. my $masterfile=shift;
  776. my $potfile=potfile($masterfile);
  777. my $doc=Locale::Po4a::Chooser::new(po4a_type($masterfile),
  778. po4a_options($masterfile));
  779. $doc->{TT}{utf_mode} = 1;
  780. $doc->{TT}{file_in_charset} = 'UTF-8';
  781. $doc->{TT}{file_out_charset} = 'UTF-8';
  782. $doc->read($masterfile);
  783. # let's cheat a bit to force porefs option to be passed to
  784. # Locale::Po4a::Po; this is undocument use of internal
  785. # Locale::Po4a::TransTractor's data, compulsory since this module
  786. # prevents us from using the porefs option.
  787. $doc->{TT}{po_out}=Locale::Po4a::Po->new({ 'porefs' => 'none' });
  788. $doc->{TT}{po_out}->set_charset('UTF-8');
  789. # do the actual work
  790. $doc->parse;
  791. IkiWiki::prep_writefile(basename($potfile),dirname($potfile));
  792. $doc->writepo($potfile);
  793. }
  794. sub refreshpofiles ($@) {
  795. my $masterfile=shift;
  796. my @pofiles=@_;
  797. my $potfile=potfile($masterfile);
  798. if (! -e $potfile) {
  799. error("po(refreshpofiles) ".sprintf(gettext("POT file (%s) does not exist"), $potfile));
  800. }
  801. foreach my $pofile (@pofiles) {
  802. IkiWiki::prep_writefile(basename($pofile),dirname($pofile));
  803. if (! -e $pofile) {
  804. # If the po file exists in an underlay, copy it
  805. # from there.
  806. my ($pobase)=$pofile=~/^\Q$config{srcdir}\E\/?(.*)$/;
  807. foreach my $dir (@{$config{underlaydirs}}) {
  808. if (-e "$dir/$pobase") {
  809. File::Copy::syscopy("$dir/$pobase",$pofile)
  810. or error("po(refreshpofiles) ".
  811. sprintf(gettext("failed to copy underlay PO file to %s"),
  812. $pofile));
  813. }
  814. }
  815. }
  816. if (-e $pofile) {
  817. system("msgmerge", "--previous", "-q", "-U", "--backup=none", $pofile, $potfile) == 0
  818. or error("po(refreshpofiles) ".
  819. sprintf(gettext("failed to update %s"),
  820. $pofile));
  821. }
  822. else {
  823. File::Copy::syscopy($potfile,$pofile)
  824. or error("po(refreshpofiles) ".
  825. sprintf(gettext("failed to copy the POT file to %s"),
  826. $pofile));
  827. }
  828. }
  829. }
  830. sub buildtranslationscache() {
  831. # use istranslation's side-effect
  832. map istranslation($_), (keys %pagesources);
  833. }
  834. sub resettranslationscache() {
  835. undef %translations;
  836. }
  837. sub flushmemoizecache() {
  838. Memoize::flush_cache("istranslatable");
  839. Memoize::flush_cache("_istranslation");
  840. Memoize::flush_cache("percenttranslated");
  841. }
  842. sub urlto_with_orig_beautiful_urlpath($$) {
  843. my $to=shift;
  844. my $from=shift;
  845. inject(name => "IkiWiki::beautify_urlpath", call => $origsubs{'beautify_urlpath'});
  846. my $res=urlto($to, $from);
  847. inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath);
  848. return $res;
  849. }
  850. sub percenttranslated ($) {
  851. my $page=shift;
  852. $page=~s/^\///;
  853. return gettext("N/A") unless istranslation($page);
  854. my $file=srcfile($pagesources{$page});
  855. my $masterfile = srcfile($pagesources{masterpage($page)});
  856. my $doc=Locale::Po4a::Chooser::new(po4a_type($masterfile),
  857. po4a_options($masterfile));
  858. $doc->process(
  859. 'po_in_name' => [ $file ],
  860. 'file_in_name' => [ $masterfile ],
  861. 'file_in_charset' => 'UTF-8',
  862. 'file_out_charset' => 'UTF-8',
  863. ) or error("po(percenttranslated) ".
  864. sprintf(gettext("failed to translate %s"), $page));
  865. my ($percent,$hit,$queries) = $doc->stats();
  866. $percent =~ s/\.[0-9]+$//;
  867. return $percent;
  868. }
  869. sub languagename ($) {
  870. my $code=shift;
  871. return $config{po_master_language}{name}
  872. if $code eq $config{po_master_language}{code};
  873. return $config{po_slave_languages}{$code}
  874. if defined $config{po_slave_languages}{$code};
  875. return;
  876. }
  877. sub otherlanguagesloop ($) {
  878. my $page=shift;
  879. my @ret;
  880. if (istranslation($page)) {
  881. push @ret, {
  882. url => urlto_with_orig_beautiful_urlpath(masterpage($page), $page),
  883. code => $config{po_master_language}{code},
  884. language => $config{po_master_language}{name},
  885. master => 1,
  886. };
  887. }
  888. foreach my $lang (@{otherlanguages_codes($page)}) {
  889. next if $lang eq $config{po_master_language}{code};
  890. my $otherpage = otherlanguage_page($page, $lang);
  891. push @ret, {
  892. url => urlto_with_orig_beautiful_urlpath($otherpage, $page),
  893. code => $lang,
  894. language => languagename($lang),
  895. percent => percenttranslated($otherpage),
  896. }
  897. }
  898. return @ret;
  899. }
  900. sub homepageurl (;$) {
  901. my $page=shift;
  902. return urlto('', $page);
  903. }
  904. sub ishomepage ($) {
  905. my $page = shift;
  906. return 1 if $page eq 'index';
  907. map { return 1 if $page eq 'index.'.$_ } @slavelanguages;
  908. return undef;
  909. }
  910. sub deletetranslations ($) {
  911. my $deletedmasterfile=shift;
  912. my $deletedmasterpage=pagename($deletedmasterfile);
  913. my @todelete;
  914. map {
  915. my $file = newpagefile($deletedmasterpage.'.'.$_, 'po');
  916. my $absfile = "$config{srcdir}/$file";
  917. if (-e $absfile && ! -l $absfile && ! -d $absfile) {
  918. push @todelete, $file;
  919. }
  920. } @slavelanguages;
  921. map {
  922. if ($config{rcs}) {
  923. IkiWiki::rcs_remove($_);
  924. }
  925. else {
  926. IkiWiki::prune("$config{srcdir}/$_");
  927. }
  928. } @todelete;
  929. if (@todelete) {
  930. commit_and_refresh(
  931. gettext("removed obsolete PO files"));
  932. }
  933. }
  934. sub commit_and_refresh ($) {
  935. my $msg = shift;
  936. if ($config{rcs}) {
  937. IkiWiki::disable_commit_hook();
  938. IkiWiki::rcs_commit_staged(
  939. message => $msg,
  940. );
  941. IkiWiki::enable_commit_hook();
  942. IkiWiki::rcs_update();
  943. }
  944. # Reinitialize module's private variables.
  945. resetalreadyfiltered();
  946. resettranslationscache();
  947. flushmemoizecache();
  948. # Trigger a wiki refresh.
  949. require IkiWiki::Render;
  950. # without preliminary saveindex/loadindex, refresh()
  951. # complains about a lot of uninitialized variables
  952. IkiWiki::saveindex();
  953. IkiWiki::loadindex();
  954. IkiWiki::refresh();
  955. IkiWiki::saveindex();
  956. }
  957. sub po_to_markup ($$) {
  958. my ($page, $content) = (shift, shift);
  959. $content = '' unless defined $content;
  960. $content = decode_utf8(encode_utf8($content));
  961. # CRLF line terminators make poor Locale::Po4a feel bad
  962. $content=~s/\r\n/\n/g;
  963. # There are incompatibilities between some File::Temp versions
  964. # (including 0.18, bundled with Lenny's perl-modules package)
  965. # and others (e.g. 0.20, previously present in the archive as
  966. # a standalone package): under certain circumstances, some
  967. # return a relative filename, whereas others return an absolute one;
  968. # we here use this module in a way that is at least compatible
  969. # with 0.18 and 0.20. Beware, hit'n'run refactorers!
  970. my $infile = new File::Temp(TEMPLATE => "ikiwiki-po-filter-in.XXXXXXXXXX",
  971. DIR => File::Spec->tmpdir,
  972. UNLINK => 1)->filename;
  973. my $outfile = new File::Temp(TEMPLATE => "ikiwiki-po-filter-out.XXXXXXXXXX",
  974. DIR => File::Spec->tmpdir,
  975. UNLINK => 1)->filename;
  976. my $fail = sub ($) {
  977. my $msg = "po(po_to_markup) - $page : " . shift;
  978. error($msg, sub { unlink $infile, $outfile});
  979. };
  980. writefile(basename($infile), File::Spec->tmpdir, $content)
  981. or return $fail->(sprintf(gettext("failed to write %s"), $infile));
  982. my $masterfile = srcfile($pagesources{masterpage($page)});
  983. my $doc=Locale::Po4a::Chooser::new(po4a_type($masterfile),
  984. po4a_options($masterfile));
  985. $doc->process(
  986. 'po_in_name' => [ $infile ],
  987. 'file_in_name' => [ $masterfile ],
  988. 'file_in_charset' => 'UTF-8',
  989. 'file_out_charset' => 'UTF-8',
  990. ) or return $fail->(gettext("failed to translate"));
  991. $doc->write($outfile)
  992. or return $fail->(sprintf(gettext("failed to write %s"), $outfile));
  993. $content = readfile($outfile);
  994. # Unlinking should happen automatically, thanks to File::Temp,
  995. # but it does not work here, probably because of the way writefile()
  996. # and Locale::Po4a::write() work.
  997. unlink $infile, $outfile;
  998. return $content;
  999. }
  1000. # returns a SuccessReason or FailReason object
  1001. sub isvalidpo ($) {
  1002. my $content = shift;
  1003. # NB: we don't use po_to_markup here, since Po4a parser does
  1004. # not mind invalid PO content
  1005. $content = '' unless defined $content;
  1006. $content = decode_utf8(encode_utf8($content));
  1007. # There are incompatibilities between some File::Temp versions
  1008. # (including 0.18, bundled with Lenny's perl-modules package)
  1009. # and others (e.g. 0.20, previously present in the archive as
  1010. # a standalone package): under certain circumstances, some
  1011. # return a relative filename, whereas others return an absolute one;
  1012. # we here use this module in a way that is at least compatible
  1013. # with 0.18 and 0.20. Beware, hit'n'run refactorers!
  1014. my $infile = new File::Temp(TEMPLATE => "ikiwiki-po-isvalidpo.XXXXXXXXXX",
  1015. DIR => File::Spec->tmpdir,
  1016. UNLINK => 1)->filename;
  1017. my $fail = sub ($) {
  1018. my $msg = '[po/isvalidpo] ' . shift;
  1019. unlink $infile;
  1020. return IkiWiki::FailReason->new("$msg");
  1021. };
  1022. writefile(basename($infile), File::Spec->tmpdir, $content)
  1023. or return $fail->(sprintf(gettext("failed to write %s"), $infile));
  1024. my $res = (system("msgfmt", "--check", $infile, "-o", "/dev/null") == 0);
  1025. # Unlinking should happen automatically, thanks to File::Temp,
  1026. # but it does not work here, probably because of the way writefile()
  1027. # and Locale::Po4a::write() work.
  1028. unlink $infile;
  1029. if ($res) {
  1030. return IkiWiki::SuccessReason->new("valid gettext data");
  1031. }
  1032. return IkiWiki::FailReason->new(gettext("invalid gettext data, go back ".
  1033. "to previous page to continue edit"));
  1034. }
  1035. sub po4a_type ($) {
  1036. my $file = shift;
  1037. my $pagetype = pagetype($file);
  1038. if ($pagetype eq 'html') {
  1039. return 'xhtml';
  1040. }
  1041. return 'text';
  1042. }
  1043. sub po4a_options($) {
  1044. my $file = shift;
  1045. my %options;
  1046. my $pagetype = pagetype($file);
  1047. if ($pagetype eq 'html') {
  1048. # how to disable options is not consistent across po4a modules
  1049. $options{includessi} = '';
  1050. $options{includeexternal} = 0;
  1051. }
  1052. elsif ($pagetype eq 'mdwn') {
  1053. $options{markdown} = 1;
  1054. }
  1055. else {
  1056. $options{markdown} = 0;
  1057. }
  1058. return %options;
  1059. }
  1060. # ,----
  1061. # | PageSpecs
  1062. # `----
  1063. package IkiWiki::PageSpec;
  1064. sub match_istranslation ($;@) {
  1065. my $page=shift;
  1066. if (IkiWiki::Plugin::po::istranslation($page)) {
  1067. return IkiWiki::SuccessReason->new("is a translation page");
  1068. }
  1069. else {
  1070. return IkiWiki::FailReason->new("is not a translation page");
  1071. }
  1072. }
  1073. sub match_istranslatable ($;@) {
  1074. my $page=shift;
  1075. if (IkiWiki::Plugin::po::istranslatable($page)) {
  1076. return IkiWiki::SuccessReason->new("is set as translatable in po_translatable_pages");
  1077. }
  1078. else {
  1079. return IkiWiki::FailReason->new("is not set as translatable in po_translatable_pages");
  1080. }
  1081. }
  1082. sub match_lang ($$;@) {
  1083. my $page=shift;
  1084. my $wanted=shift;
  1085. my $regexp=IkiWiki::glob2re($wanted);
  1086. my $lang=IkiWiki::Plugin::po::lang($page);
  1087. if ($lang !~ /^$regexp$/i) {
  1088. return IkiWiki::FailReason->new("file language is $lang, not $wanted");
  1089. }
  1090. else {
  1091. return IkiWiki::SuccessReason->new("file language is $wanted");
  1092. }
  1093. }
  1094. sub match_currentlang ($$;@) {
  1095. my $page=shift;
  1096. shift;
  1097. my %params=@_;
  1098. return IkiWiki::FailReason->new("no location provided") unless exists $params{location};
  1099. my $currentlang=IkiWiki::Plugin::po::lang($params{location});
  1100. my $lang=IkiWiki::Plugin::po::lang($page);
  1101. if ($lang eq $currentlang) {
  1102. return IkiWiki::SuccessReason->new("file language is the same as current one, i.e. $currentlang");
  1103. }
  1104. else {
  1105. return IkiWiki::FailReason->new("file language is $lang, whereas current language is $currentlang");
  1106. }
  1107. }
  1108. sub match_needstranslation ($$;@) {
  1109. my $page=shift;
  1110. my $wanted=shift;
  1111. if (defined $wanted && $wanted ne "") {
  1112. if ($wanted !~ /^\d+$/) {
  1113. return IkiWiki::FailReason->new("parameter is not an integer");
  1114. }
  1115. elsif ($wanted > 100) {
  1116. return IkiWiki::FailReason->new("parameter is greater than 100");
  1117. }
  1118. }
  1119. else {
  1120. $wanted=100;
  1121. }
  1122. my $percenttranslated=IkiWiki::Plugin::po::percenttranslated($page);
  1123. if ($percenttranslated eq 'N/A') {
  1124. return IkiWiki::FailReason->new("file is not a translatable page");
  1125. }
  1126. elsif ($percenttranslated < $wanted) {
  1127. return IkiWiki::SuccessReason->new("file has $percenttranslated translated");
  1128. }
  1129. else {
  1130. return IkiWiki::FailReason->new("file is translated enough");
  1131. }
  1132. }
  1133. 1