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