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