summaryrefslogtreecommitdiff
path: root/IkiWiki/Plugin/po.pm
blob: 9ccc79268b7564a159815da059e6de6adaba8439 (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. my $filename=shift;
  559. if (istranslation($page) || istranslatable($page)) {
  560. my ($masterpage, $lang) = (masterpage($page), lang($page));
  561. if (defined $filename) {
  562. return $masterpage . "/" . $filename . "." . $lang . "." . $ext;
  563. }
  564. elsif (! $config{usedirs} || $masterpage eq 'index') {
  565. return $masterpage . "." . $lang . "." . $ext;
  566. }
  567. else {
  568. return $masterpage . "/index." . $lang . "." . $ext;
  569. }
  570. }
  571. return $origsubs{'targetpage'}->($page, $ext, $filename);
  572. }
  573. sub myurlto ($;$$) {
  574. my $to=shift;
  575. my $from=shift;
  576. my $absolute=shift;
  577. # workaround hard-coded /index.$config{htmlext} in IkiWiki::urlto()
  578. if (! length $to
  579. && $config{po_link_to} eq "current"
  580. && istranslatable('index')) {
  581. if (defined $from) {
  582. return IkiWiki::beautify_urlpath(IkiWiki::baseurl($from) . "index." . lang($from) . ".$config{htmlext}");
  583. }
  584. else {
  585. return $origsubs{'urlto'}->($to,$from,$absolute);
  586. }
  587. }
  588. # avoid using our injected beautify_urlpath if run by cgi_editpage,
  589. # so that one is redirected to the just-edited page rather than to the
  590. # negociated translation; to prevent unnecessary fiddling with caller/inject,
  591. # we only do so when our beautify_urlpath would actually do what we want to
  592. # avoid, i.e. when po_link_to = negotiated.
  593. # also avoid doing so when run by cgi_goto, so that the links on recentchanges
  594. # page actually lead to the exact page they pretend to.
  595. if ($config{po_link_to} eq "negotiated") {
  596. my @caller = caller(1);
  597. my $use_orig = 0;
  598. $use_orig = 1 if (exists $caller[3] && defined $caller[3]
  599. && ($caller[3] eq "IkiWiki::cgi_editpage" ||
  600. $caller[3] eq "IkiWiki::Plugin::goto::cgi_goto")
  601. );
  602. inject(name => "IkiWiki::beautify_urlpath", call => $origsubs{'beautify_urlpath'})
  603. if $use_orig;
  604. my $res = $origsubs{'urlto'}->($to,$from,$absolute);
  605. inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath)
  606. if $use_orig;
  607. return $res;
  608. }
  609. else {
  610. return $origsubs{'urlto'}->($to,$from,$absolute)
  611. }
  612. }
  613. sub mycgiurl (@) {
  614. my %params=@_;
  615. # slave pages have no subpages
  616. if (istranslation($params{'from'})) {
  617. $params{'from'} = masterpage($params{'from'});
  618. }
  619. return $origsubs{'cgiurl'}->(%params);
  620. }
  621. sub myrootpage (@) {
  622. my %params=@_;
  623. my $rootpage;
  624. if (exists $params{rootpage}) {
  625. $rootpage=$origsubs{'bestlink'}->($params{page}, $params{rootpage});
  626. if (!length $rootpage) {
  627. $rootpage=$params{rootpage};
  628. }
  629. }
  630. else {
  631. $rootpage=masterpage($params{page});
  632. }
  633. return $rootpage;
  634. }
  635. sub myisselflink ($$) {
  636. my $page=shift;
  637. my $link=shift;
  638. return 1 if $origsubs{'isselflink'}->($page, $link);
  639. if (istranslation($page)) {
  640. return $origsubs{'isselflink'}->(masterpage($page), $link);
  641. }
  642. return;
  643. }
  644. # ,----
  645. # | Blackboxes for private data
  646. # `----
  647. {
  648. my %filtered;
  649. sub alreadyfiltered($$) {
  650. my $page=shift;
  651. my $destpage=shift;
  652. return exists $filtered{$page}{$destpage}
  653. && $filtered{$page}{$destpage} eq 1;
  654. }
  655. sub setalreadyfiltered($$) {
  656. my $page=shift;
  657. my $destpage=shift;
  658. $filtered{$page}{$destpage}=1;
  659. }
  660. sub unsetalreadyfiltered($$) {
  661. my $page=shift;
  662. my $destpage=shift;
  663. if (exists $filtered{$page}{$destpage}) {
  664. delete $filtered{$page}{$destpage};
  665. }
  666. }
  667. sub resetalreadyfiltered() {
  668. undef %filtered;
  669. }
  670. }
  671. # ,----
  672. # | Helper functions
  673. # `----
  674. sub maybe_add_leading_slash ($;$) {
  675. my $str=shift;
  676. my $add=shift;
  677. $add=1 unless defined $add;
  678. return '/' . $str if $add;
  679. return $str;
  680. }
  681. sub istranslatablefile ($) {
  682. my $file=shift;
  683. return 0 unless defined $file;
  684. my $type=pagetype($file);
  685. return 0 if ! defined $type || $type eq 'po';
  686. return 0 if $file =~ /\.pot$/;
  687. return 0 if ! defined $config{po_translatable_pages};
  688. return 1 if pagespec_match(pagename($file), $config{po_translatable_pages});
  689. return;
  690. }
  691. sub istranslatable ($) {
  692. my $page=shift;
  693. $page=~s#^/##;
  694. return 1 if istranslatablefile($pagesources{$page});
  695. return;
  696. }
  697. sub istranslatedto ($$) {
  698. my $page=shift;
  699. my $destlang = shift;
  700. $page=~s#^/##;
  701. return 0 unless istranslatable($page);
  702. exists $pagesources{otherlanguage_page($page, $destlang)};
  703. }
  704. sub _istranslation ($) {
  705. my $page=shift;
  706. $page='' unless defined $page && length $page;
  707. my $hasleadingslash = ($page=~s#^/##);
  708. my $file=$pagesources{$page};
  709. return 0 unless defined $file
  710. && defined pagetype($file)
  711. && pagetype($file) eq 'po';
  712. return 0 if $file =~ /\.pot$/;
  713. my ($masterpage, $lang) = ($page =~ /(.*)[.]([a-z]{2})$/);
  714. return 0 unless defined $masterpage && defined $lang
  715. && length $masterpage && length $lang
  716. && defined $pagesources{$masterpage}
  717. && defined $slavelanguages{$lang};
  718. return (maybe_add_leading_slash($masterpage, $hasleadingslash), $lang)
  719. if istranslatable($masterpage);
  720. }
  721. sub istranslation ($) {
  722. my $page=shift;
  723. if (1 < (my ($masterpage, $lang) = _istranslation($page))) {
  724. my $hasleadingslash = ($masterpage=~s#^/##);
  725. $translations{$masterpage}{$lang}=$page unless exists $translations{$masterpage}{$lang};
  726. return (maybe_add_leading_slash($masterpage, $hasleadingslash), $lang);
  727. }
  728. return "";
  729. }
  730. sub masterpage ($) {
  731. my $page=shift;
  732. if ( 1 < (my ($masterpage, $lang) = _istranslation($page))) {
  733. return $masterpage;
  734. }
  735. return $page;
  736. }
  737. sub lang ($) {
  738. my $page=shift;
  739. if (1 < (my ($masterpage, $lang) = _istranslation($page))) {
  740. return $lang;
  741. }
  742. return $master_language_code;
  743. }
  744. sub islanguagecode ($) {
  745. my $code=shift;
  746. return $code =~ /^[a-z]{2}$/;
  747. }
  748. sub otherlanguage_page ($$) {
  749. my $page=shift;
  750. my $code=shift;
  751. return masterpage($page) if $code eq $master_language_code;
  752. return masterpage($page) . '.' . $code;
  753. }
  754. # Returns the list of other languages codes: the master language comes first,
  755. # then the codes are ordered the same way as in po_slave_languages, if it is
  756. # an array, or in the language name lexical order, if it is a hash.
  757. sub otherlanguages_codes ($) {
  758. my $page=shift;
  759. my @ret;
  760. return \@ret unless istranslation($page) || istranslatable($page);
  761. my $curlang=lang($page);
  762. foreach my $lang
  763. ($master_language_code, @slavelanguages) {
  764. next if $lang eq $curlang;
  765. if ($lang eq $master_language_code ||
  766. istranslatedto(masterpage($page), $lang)) {
  767. push @ret, $lang;
  768. }
  769. }
  770. return \@ret;
  771. }
  772. sub otherlanguages_pages ($) {
  773. my $page=shift;
  774. my %ret;
  775. map {
  776. $ret{$_} = otherlanguage_page($page, $_)
  777. } @{otherlanguages_codes($page)};
  778. return \%ret;
  779. }
  780. sub potfile ($) {
  781. my $masterfile=shift;
  782. (my $name, my $dir, my $suffix) = fileparse($masterfile, qr/\.[^.]*/);
  783. $dir='' if $dir eq './';
  784. return File::Spec->catpath('', $dir, $name . ".pot");
  785. }
  786. sub pofile ($$) {
  787. my $masterfile=shift;
  788. my $lang=shift;
  789. (my $name, my $dir, my $suffix) = fileparse($masterfile, qr/\.[^.]*/);
  790. $dir='' if $dir eq './';
  791. return File::Spec->catpath('', $dir, $name . "." . $lang . ".po");
  792. }
  793. sub pofiles ($) {
  794. my $masterfile=shift;
  795. return map pofile($masterfile, $_), @slavelanguages;
  796. }
  797. sub refreshpot ($) {
  798. my $masterfile=shift;
  799. my $potfile=potfile($masterfile);
  800. my $doc=Locale::Po4a::Chooser::new(po4a_type($masterfile),
  801. po4a_options($masterfile));
  802. $doc->{TT}{utf_mode} = 1;
  803. $doc->{TT}{file_in_charset} = 'UTF-8';
  804. $doc->{TT}{file_out_charset} = 'UTF-8';
  805. $doc->read($masterfile);
  806. # let's cheat a bit to force porefs option to be passed to
  807. # Locale::Po4a::Po; this is undocument use of internal
  808. # Locale::Po4a::TransTractor's data, compulsory since this module
  809. # prevents us from using the porefs option.
  810. $doc->{TT}{po_out}=Locale::Po4a::Po->new({ 'porefs' => 'none' });
  811. $doc->{TT}{po_out}->set_charset('UTF-8');
  812. # do the actual work
  813. $doc->parse;
  814. IkiWiki::prep_writefile(basename($potfile),dirname($potfile));
  815. $doc->writepo($potfile);
  816. }
  817. sub refreshpofiles ($@) {
  818. my $masterfile=shift;
  819. my @pofiles=@_;
  820. my $potfile=potfile($masterfile);
  821. if (! -e $potfile) {
  822. error("po(refreshpofiles) ".sprintf(gettext("POT file (%s) does not exist"), $potfile));
  823. }
  824. foreach my $pofile (@pofiles) {
  825. IkiWiki::prep_writefile(basename($pofile),dirname($pofile));
  826. if (! -e $pofile) {
  827. # If the po file exists in an underlay, copy it
  828. # from there.
  829. my ($pobase)=$pofile=~/^\Q$config{srcdir}\E\/?(.*)$/;
  830. foreach my $dir (@{$config{underlaydirs}}) {
  831. if (-e "$dir/$pobase") {
  832. File::Copy::syscopy("$dir/$pobase",$pofile)
  833. or error("po(refreshpofiles) ".
  834. sprintf(gettext("failed to copy underlay PO file to %s"),
  835. $pofile));
  836. }
  837. }
  838. }
  839. if (-e $pofile) {
  840. system("msgmerge", "--previous", "-q", "-U", "--backup=none", $pofile, $potfile) == 0
  841. or error("po(refreshpofiles) ".
  842. sprintf(gettext("failed to update %s"),
  843. $pofile));
  844. }
  845. else {
  846. File::Copy::syscopy($potfile,$pofile)
  847. or error("po(refreshpofiles) ".
  848. sprintf(gettext("failed to copy the POT file to %s"),
  849. $pofile));
  850. }
  851. }
  852. }
  853. sub buildtranslationscache() {
  854. # use istranslation's side-effect
  855. map istranslation($_), (keys %pagesources);
  856. }
  857. sub resettranslationscache() {
  858. undef %translations;
  859. }
  860. sub flushmemoizecache() {
  861. Memoize::flush_cache("istranslatable");
  862. Memoize::flush_cache("_istranslation");
  863. Memoize::flush_cache("percenttranslated");
  864. }
  865. sub urlto_with_orig_beautiful_urlpath($$) {
  866. my $to=shift;
  867. my $from=shift;
  868. inject(name => "IkiWiki::beautify_urlpath", call => $origsubs{'beautify_urlpath'});
  869. my $res=urlto($to, $from);
  870. inject(name => "IkiWiki::beautify_urlpath", call => \&mybeautify_urlpath);
  871. return $res;
  872. }
  873. sub percenttranslated ($) {
  874. my $page=shift;
  875. $page=~s/^\///;
  876. return gettext("N/A") unless istranslation($page);
  877. my $file=srcfile($pagesources{$page});
  878. my $masterfile = srcfile($pagesources{masterpage($page)});
  879. my $doc=Locale::Po4a::Chooser::new(po4a_type($masterfile),
  880. po4a_options($masterfile));
  881. $doc->process(
  882. 'po_in_name' => [ $file ],
  883. 'file_in_name' => [ $masterfile ],
  884. 'file_in_charset' => 'UTF-8',
  885. 'file_out_charset' => 'UTF-8',
  886. ) or error("po(percenttranslated) ".
  887. sprintf(gettext("failed to translate %s"), $page));
  888. my ($percent,$hit,$queries) = $doc->stats();
  889. $percent =~ s/\.[0-9]+$//;
  890. return $percent;
  891. }
  892. sub languagename ($) {
  893. my $code=shift;
  894. return $master_language_name
  895. if $code eq $master_language_code;
  896. return $slavelanguages{$code}
  897. if defined $slavelanguages{$code};
  898. return;
  899. }
  900. sub otherlanguagesloop ($) {
  901. my $page=shift;
  902. my @ret;
  903. if (istranslation($page)) {
  904. push @ret, {
  905. url => urlto_with_orig_beautiful_urlpath(masterpage($page), $page),
  906. code => $master_language_code,
  907. language => $master_language_name,
  908. master => 1,
  909. };
  910. }
  911. foreach my $lang (@{otherlanguages_codes($page)}) {
  912. next if $lang eq $master_language_code;
  913. my $otherpage = otherlanguage_page($page, $lang);
  914. push @ret, {
  915. url => urlto_with_orig_beautiful_urlpath($otherpage, $page),
  916. code => $lang,
  917. language => languagename($lang),
  918. percent => percenttranslated($otherpage),
  919. }
  920. }
  921. return @ret;
  922. }
  923. sub homepageurl (;$) {
  924. my $page=shift;
  925. return urlto('', $page);
  926. }
  927. sub ishomepage ($) {
  928. my $page = shift;
  929. return 1 if $page eq 'index';
  930. map { return 1 if $page eq 'index.'.$_ } @slavelanguages;
  931. return undef;
  932. }
  933. sub deletetranslations ($) {
  934. my $deletedmasterfile=shift;
  935. my $deletedmasterpage=pagename($deletedmasterfile);
  936. my @todelete;
  937. map {
  938. my $file = newpagefile($deletedmasterpage.'.'.$_, 'po');
  939. my $absfile = "$config{srcdir}/$file";
  940. if (-e $absfile && ! -l $absfile && ! -d $absfile) {
  941. push @todelete, $file;
  942. }
  943. } @slavelanguages;
  944. map {
  945. if ($config{rcs}) {
  946. IkiWiki::rcs_remove($_);
  947. }
  948. else {
  949. IkiWiki::prune("$config{srcdir}/$_");
  950. }
  951. } @todelete;
  952. if (@todelete) {
  953. commit_and_refresh(
  954. gettext("removed obsolete PO files"));
  955. }
  956. }
  957. sub commit_and_refresh ($) {
  958. my $msg = shift;
  959. if ($config{rcs}) {
  960. IkiWiki::disable_commit_hook();
  961. IkiWiki::rcs_commit_staged(
  962. message => $msg,
  963. );
  964. IkiWiki::enable_commit_hook();
  965. IkiWiki::rcs_update();
  966. }
  967. # Reinitialize module's private variables.
  968. resetalreadyfiltered();
  969. resettranslationscache();
  970. flushmemoizecache();
  971. # Trigger a wiki refresh.
  972. require IkiWiki::Render;
  973. # without preliminary saveindex/loadindex, refresh()
  974. # complains about a lot of uninitialized variables
  975. IkiWiki::saveindex();
  976. IkiWiki::loadindex();
  977. IkiWiki::refresh();
  978. IkiWiki::saveindex();
  979. }
  980. sub po_to_markup ($$) {
  981. my ($page, $content) = (shift, shift);
  982. $content = '' unless defined $content;
  983. $content = decode_utf8(encode_utf8($content));
  984. # CRLF line terminators make poor Locale::Po4a feel bad
  985. $content=~s/\r\n/\n/g;
  986. # There are incompatibilities between some File::Temp versions
  987. # (including 0.18, bundled with Lenny's perl-modules package)
  988. # and others (e.g. 0.20, previously present in the archive as
  989. # a standalone package): under certain circumstances, some
  990. # return a relative filename, whereas others return an absolute one;
  991. # we here use this module in a way that is at least compatible
  992. # with 0.18 and 0.20. Beware, hit'n'run refactorers!
  993. my $infile = new File::Temp(TEMPLATE => "ikiwiki-po-filter-in.XXXXXXXXXX",
  994. DIR => File::Spec->tmpdir,
  995. UNLINK => 1)->filename;
  996. my $outfile = new File::Temp(TEMPLATE => "ikiwiki-po-filter-out.XXXXXXXXXX",
  997. DIR => File::Spec->tmpdir,
  998. UNLINK => 1)->filename;
  999. my $fail = sub ($) {
  1000. my $msg = "po(po_to_markup) - $page : " . shift;
  1001. error($msg, sub { unlink $infile, $outfile});
  1002. };
  1003. writefile(basename($infile), File::Spec->tmpdir, $content)
  1004. or return $fail->(sprintf(gettext("failed to write %s"), $infile));
  1005. my $masterfile = srcfile($pagesources{masterpage($page)});
  1006. my $doc=Locale::Po4a::Chooser::new(po4a_type($masterfile),
  1007. po4a_options($masterfile));
  1008. $doc->process(
  1009. 'po_in_name' => [ $infile ],
  1010. 'file_in_name' => [ $masterfile ],
  1011. 'file_in_charset' => 'UTF-8',
  1012. 'file_out_charset' => 'UTF-8',
  1013. ) or return $fail->(gettext("failed to translate"));
  1014. $doc->write($outfile)
  1015. or return $fail->(sprintf(gettext("failed to write %s"), $outfile));
  1016. $content = readfile($outfile);
  1017. # Unlinking should happen automatically, thanks to File::Temp,
  1018. # but it does not work here, probably because of the way writefile()
  1019. # and Locale::Po4a::write() work.
  1020. unlink $infile, $outfile;
  1021. return $content;
  1022. }
  1023. # returns a SuccessReason or FailReason object
  1024. sub isvalidpo ($) {
  1025. my $content = shift;
  1026. # NB: we don't use po_to_markup here, since Po4a parser does
  1027. # not mind invalid PO content
  1028. $content = '' unless defined $content;
  1029. $content = decode_utf8(encode_utf8($content));
  1030. # There are incompatibilities between some File::Temp versions
  1031. # (including 0.18, bundled with Lenny's perl-modules package)
  1032. # and others (e.g. 0.20, previously present in the archive as
  1033. # a standalone package): under certain circumstances, some
  1034. # return a relative filename, whereas others return an absolute one;
  1035. # we here use this module in a way that is at least compatible
  1036. # with 0.18 and 0.20. Beware, hit'n'run refactorers!
  1037. my $infile = new File::Temp(TEMPLATE => "ikiwiki-po-isvalidpo.XXXXXXXXXX",
  1038. DIR => File::Spec->tmpdir,
  1039. UNLINK => 1)->filename;
  1040. my $fail = sub ($) {
  1041. my $msg = '[po/isvalidpo] ' . shift;
  1042. unlink $infile;
  1043. return IkiWiki::FailReason->new("$msg");
  1044. };
  1045. writefile(basename($infile), File::Spec->tmpdir, $content)
  1046. or return $fail->(sprintf(gettext("failed to write %s"), $infile));
  1047. my $res = (system("msgfmt", "--check", $infile, "-o", "/dev/null") == 0);
  1048. # Unlinking should happen automatically, thanks to File::Temp,
  1049. # but it does not work here, probably because of the way writefile()
  1050. # and Locale::Po4a::write() work.
  1051. unlink $infile;
  1052. if ($res) {
  1053. return IkiWiki::SuccessReason->new("valid gettext data");
  1054. }
  1055. return IkiWiki::FailReason->new(gettext("invalid gettext data, go back ".
  1056. "to previous page to continue edit"));
  1057. }
  1058. sub po4a_type ($) {
  1059. my $file = shift;
  1060. my $pagetype = pagetype($file);
  1061. if ($pagetype eq 'html') {
  1062. return 'xhtml';
  1063. }
  1064. return 'text';
  1065. }
  1066. sub po4a_options($) {
  1067. my $file = shift;
  1068. my %options;
  1069. my $pagetype = pagetype($file);
  1070. if ($pagetype eq 'html') {
  1071. # how to disable options is not consistent across po4a modules
  1072. $options{includessi} = '';
  1073. $options{includeexternal} = 0;
  1074. }
  1075. elsif ($pagetype eq 'mdwn') {
  1076. $options{markdown} = 1;
  1077. }
  1078. else {
  1079. $options{markdown} = 0;
  1080. }
  1081. return %options;
  1082. }
  1083. sub splitlangpair ($) {
  1084. my $pair=shift;
  1085. my ($code, $name) = ( $pair =~ /^([a-z]{2})\|(.+)$/ );
  1086. if (! defined $code || ! defined $name ||
  1087. ! length $code || ! length $name) {
  1088. # not a fatal error to avoid breaking if used with web setup
  1089. warn sprintf(gettext("%s has invalid syntax: must use CODE|NAME"),
  1090. $pair);
  1091. }
  1092. return $code, $name;
  1093. }
  1094. sub joinlangpair ($$) {
  1095. my $code=shift;
  1096. my $name=shift;
  1097. return "$code|$name";
  1098. }
  1099. # ,----
  1100. # | PageSpecs
  1101. # `----
  1102. package IkiWiki::PageSpec;
  1103. sub match_istranslation ($;@) {
  1104. my $page=shift;
  1105. if (IkiWiki::Plugin::po::istranslation($page)) {
  1106. return IkiWiki::SuccessReason->new("is a translation page");
  1107. }
  1108. else {
  1109. return IkiWiki::FailReason->new("is not a translation page");
  1110. }
  1111. }
  1112. sub match_istranslatable ($;@) {
  1113. my $page=shift;
  1114. if (IkiWiki::Plugin::po::istranslatable($page)) {
  1115. return IkiWiki::SuccessReason->new("is set as translatable in po_translatable_pages");
  1116. }
  1117. else {
  1118. return IkiWiki::FailReason->new("is not set as translatable in po_translatable_pages");
  1119. }
  1120. }
  1121. sub match_lang ($$;@) {
  1122. my $page=shift;
  1123. my $wanted=shift;
  1124. my $regexp=IkiWiki::glob2re($wanted);
  1125. my $lang=IkiWiki::Plugin::po::lang($page);
  1126. if ($lang !~ $regexp) {
  1127. return IkiWiki::FailReason->new("file language is $lang, not $wanted");
  1128. }
  1129. else {
  1130. return IkiWiki::SuccessReason->new("file language is $wanted");
  1131. }
  1132. }
  1133. sub match_currentlang ($$;@) {
  1134. my $page=shift;
  1135. shift;
  1136. my %params=@_;
  1137. return IkiWiki::FailReason->new("no location provided") unless exists $params{location};
  1138. my $currentlang=IkiWiki::Plugin::po::lang($params{location});
  1139. my $lang=IkiWiki::Plugin::po::lang($page);
  1140. if ($lang eq $currentlang) {
  1141. return IkiWiki::SuccessReason->new("file language is the same as current one, i.e. $currentlang");
  1142. }
  1143. else {
  1144. return IkiWiki::FailReason->new("file language is $lang, whereas current language is $currentlang");
  1145. }
  1146. }
  1147. sub match_needstranslation ($$;@) {
  1148. my $page=shift;
  1149. my $wanted=shift;
  1150. if (defined $wanted && $wanted ne "") {
  1151. if ($wanted !~ /^\d+$/) {
  1152. return IkiWiki::FailReason->new("parameter is not an integer");
  1153. }
  1154. elsif ($wanted > 100) {
  1155. return IkiWiki::FailReason->new("parameter is greater than 100");
  1156. }
  1157. }
  1158. else {
  1159. $wanted=100;
  1160. }
  1161. my $percenttranslated=IkiWiki::Plugin::po::percenttranslated($page);
  1162. if ($percenttranslated eq 'N/A') {
  1163. return IkiWiki::FailReason->new("file is not a translatable page");
  1164. }
  1165. elsif ($percenttranslated < $wanted) {
  1166. return IkiWiki::SuccessReason->new("file has $percenttranslated translated");
  1167. }
  1168. else {
  1169. return IkiWiki::FailReason->new("file is translated enough");
  1170. }
  1171. }
  1172. 1