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