PageRenderTime 51ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

/cake/console/libs/tasks/extract.php

http://github.com/Datawalke/Coordino
PHP | 514 lines | 338 code | 34 blank | 142 comment | 86 complexity | dcea4fcf4ac4ea69dad2109ce4c00b57 MD5 | raw file
  1. <?php
  2. /**
  3. * Language string extractor
  4. *
  5. * PHP versions 4 and 5
  6. *
  7. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  8. * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
  9. *
  10. * Licensed under The MIT License
  11. * Redistributions of files must retain the above copyright notice.
  12. *
  13. * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
  14. * @link http://cakephp.org CakePHP(tm) Project
  15. * @package cake
  16. * @subpackage cake.cake.console.libs
  17. * @since CakePHP(tm) v 1.2.0.5012
  18. * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
  19. */
  20. /**
  21. * Language string extractor
  22. *
  23. * @package cake
  24. * @subpackage cake.cake.console.libs.tasks
  25. */
  26. class ExtractTask extends Shell {
  27. /**
  28. * Paths to use when looking for strings
  29. *
  30. * @var string
  31. * @access private
  32. */
  33. var $__paths = array();
  34. /**
  35. * Files from where to extract
  36. *
  37. * @var array
  38. * @access private
  39. */
  40. var $__files = array();
  41. /**
  42. * Merge all domains string into the default.pot file
  43. *
  44. * @var boolean
  45. * @access private
  46. */
  47. var $__merge = false;
  48. /**
  49. * Current file being processed
  50. *
  51. * @var string
  52. * @access private
  53. */
  54. var $__file = null;
  55. /**
  56. * Contains all content waiting to be write
  57. *
  58. * @var string
  59. * @access private
  60. */
  61. var $__storage = array();
  62. /**
  63. * Extracted tokens
  64. *
  65. * @var array
  66. * @access private
  67. */
  68. var $__tokens = array();
  69. /**
  70. * Extracted strings
  71. *
  72. * @var array
  73. * @access private
  74. */
  75. var $__strings = array();
  76. /**
  77. * Destination path
  78. *
  79. * @var string
  80. * @access private
  81. */
  82. var $__output = null;
  83. /**
  84. * Execution method always used for tasks
  85. *
  86. * @return void
  87. * @access private
  88. */
  89. function execute() {
  90. if (isset($this->params['files']) && !is_array($this->params['files'])) {
  91. $this->__files = explode(',', $this->params['files']);
  92. }
  93. if (isset($this->params['paths'])) {
  94. $this->__paths = explode(',', $this->params['paths']);
  95. } else {
  96. $defaultPath = $this->params['working'];
  97. $message = sprintf(__("What is the full path you would like to extract?\nExample: %s\n[Q]uit [D]one", true), $this->params['root'] . DS . 'myapp');
  98. while (true) {
  99. $response = $this->in($message, null, $defaultPath);
  100. if (strtoupper($response) === 'Q') {
  101. $this->out(__('Extract Aborted', true));
  102. $this->_stop();
  103. } elseif (strtoupper($response) === 'D') {
  104. $this->out();
  105. break;
  106. } elseif (is_dir($response)) {
  107. $this->__paths[] = $response;
  108. $defaultPath = 'D';
  109. } else {
  110. $this->err(__('The directory path you supplied was not found. Please try again.', true));
  111. }
  112. $this->out();
  113. }
  114. }
  115. if (isset($this->params['output'])) {
  116. $this->__output = $this->params['output'];
  117. } else {
  118. $message = sprintf(__("What is the full path you would like to output?\nExample: %s\n[Q]uit", true), $this->__paths[0] . DS . 'locale');
  119. while (true) {
  120. $response = $this->in($message, null, $this->__paths[0] . DS . 'locale');
  121. if (strtoupper($response) === 'Q') {
  122. $this->out(__('Extract Aborted', true));
  123. $this->_stop();
  124. } elseif (is_dir($response)) {
  125. $this->__output = $response . DS;
  126. break;
  127. } else {
  128. $this->err(__('The directory path you supplied was not found. Please try again.', true));
  129. }
  130. $this->out();
  131. }
  132. }
  133. if (isset($this->params['merge'])) {
  134. $this->__merge = !(strtolower($this->params['merge']) === 'no');
  135. } else {
  136. $this->out();
  137. $response = $this->in(sprintf(__('Would you like to merge all domains strings into the default.pot file?', true)), array('y', 'n'), 'n');
  138. $this->__merge = strtolower($response) === 'y';
  139. }
  140. if (empty($this->__files)) {
  141. $this->__searchFiles();
  142. }
  143. $this->__extract();
  144. }
  145. /**
  146. * Extract text
  147. *
  148. * @return void
  149. * @access private
  150. */
  151. function __extract() {
  152. $this->out();
  153. $this->out();
  154. $this->out(__('Extracting...', true));
  155. $this->hr();
  156. $this->out(__('Paths:', true));
  157. foreach ($this->__paths as $path) {
  158. $this->out(' ' . $path);
  159. }
  160. $this->out(__('Output Directory: ', true) . $this->__output);
  161. $this->hr();
  162. $this->__extractTokens();
  163. $this->__buildFiles();
  164. $this->__writeFiles();
  165. $this->__paths = $this->__files = $this->__storage = array();
  166. $this->__strings = $this->__tokens = array();
  167. $this->out();
  168. $this->out(__('Done.', true));
  169. }
  170. /**
  171. * Show help options
  172. *
  173. * @return void
  174. * @access public
  175. */
  176. function help() {
  177. $this->out(__('CakePHP Language String Extraction:', true));
  178. $this->hr();
  179. $this->out(__('The Extract script generates .pot file(s) with translations', true));
  180. $this->out(__('By default the .pot file(s) will be place in the locale directory of -app', true));
  181. $this->out(__('By default -app is ROOT/app', true));
  182. $this->hr();
  183. $this->out(__('Usage: cake i18n extract <command> <param1> <param2>...', true));
  184. $this->out();
  185. $this->out(__('Params:', true));
  186. $this->out(__(' -app [path...]: directory where your application is located', true));
  187. $this->out(__(' -root [path...]: path to install', true));
  188. $this->out(__(' -core [path...]: path to cake directory', true));
  189. $this->out(__(' -paths [comma separated list of paths, full path is needed]', true));
  190. $this->out(__(' -merge [yes|no]: Merge all domains strings into the default.pot file', true));
  191. $this->out(__(' -output [path...]: Full path to output directory', true));
  192. $this->out(__(' -files: [comma separated list of files, full path to file is needed]', true));
  193. $this->out();
  194. $this->out(__('Commands:', true));
  195. $this->out(__(' cake i18n extract help: Shows this help message.', true));
  196. $this->out();
  197. }
  198. /**
  199. * Extract tokens out of all files to be processed
  200. *
  201. * @return void
  202. * @access private
  203. */
  204. function __extractTokens() {
  205. foreach ($this->__files as $file) {
  206. $this->__file = $file;
  207. $this->out(sprintf(__('Processing %s...', true), $file));
  208. $code = file_get_contents($file);
  209. $allTokens = token_get_all($code);
  210. $this->__tokens = array();
  211. $lineNumber = 1;
  212. foreach ($allTokens as $token) {
  213. if ((!is_array($token)) || (($token[0] != T_WHITESPACE) && ($token[0] != T_INLINE_HTML))) {
  214. if (is_array($token)) {
  215. $token[] = $lineNumber;
  216. }
  217. $this->__tokens[] = $token;
  218. }
  219. if (is_array($token)) {
  220. $lineNumber += count(explode("\n", $token[1])) - 1;
  221. } else {
  222. $lineNumber += count(explode("\n", $token)) - 1;
  223. }
  224. }
  225. unset($allTokens);
  226. $this->__parse('__', array('singular'));
  227. $this->__parse('__n', array('singular', 'plural'));
  228. $this->__parse('__d', array('domain', 'singular'));
  229. $this->__parse('__c', array('singular'));
  230. $this->__parse('__dc', array('domain', 'singular'));
  231. $this->__parse('__dn', array('domain', 'singular', 'plural'));
  232. $this->__parse('__dcn', array('domain', 'singular', 'plural'));
  233. }
  234. }
  235. /**
  236. * Parse tokens
  237. *
  238. * @param string $functionName Function name that indicates translatable string (e.g: '__')
  239. * @param array $map Array containing what variables it will find (e.g: domain, singular, plural)
  240. * @return void
  241. * @access private
  242. */
  243. function __parse($functionName, $map) {
  244. $count = 0;
  245. $tokenCount = count($this->__tokens);
  246. while (($tokenCount - $count) > 1) {
  247. list($countToken, $firstParenthesis) = array($this->__tokens[$count], $this->__tokens[$count + 1]);
  248. if (!is_array($countToken)) {
  249. $count++;
  250. continue;
  251. }
  252. list($type, $string, $line) = $countToken;
  253. if (($type == T_STRING) && ($string == $functionName) && ($firstParenthesis == '(')) {
  254. $position = $count;
  255. $depth = 0;
  256. while ($depth == 0) {
  257. if ($this->__tokens[$position] == '(') {
  258. $depth++;
  259. } elseif ($this->__tokens[$position] == ')') {
  260. $depth--;
  261. }
  262. $position++;
  263. }
  264. $mapCount = count($map);
  265. $strings = $this->__getStrings($position, $mapCount);
  266. if ($mapCount == count($strings)) {
  267. extract(array_combine($map, $strings));
  268. $domain = isset($domain) ? $domain : 'default';
  269. $string = isset($plural) ? $singular . "\0" . $plural : $singular;
  270. $this->__strings[$domain][$string][$this->__file][] = $line;
  271. } else {
  272. $this->__markerError($this->__file, $line, $functionName, $count);
  273. }
  274. }
  275. $count++;
  276. }
  277. }
  278. /**
  279. * Get the strings from the position forward
  280. *
  281. * @param integer $position Actual position on tokens array
  282. * @param integer $target Number of strings to extract
  283. * @return array Strings extracted
  284. */
  285. function __getStrings($position, $target) {
  286. $strings = array();
  287. while (count($strings) < $target && ($this->__tokens[$position] == ',' || $this->__tokens[$position][0] == T_CONSTANT_ENCAPSED_STRING)) {
  288. $condition1 = ($this->__tokens[$position][0] == T_CONSTANT_ENCAPSED_STRING && $this->__tokens[$position+1] == '.');
  289. $condition2 = ($this->__tokens[$position][0] == T_CONSTANT_ENCAPSED_STRING && $this->__tokens[$position+1][0] == T_COMMENT);
  290. if ($condition1 || $condition2) {
  291. $string = '';
  292. while ($this->__tokens[$position][0] == T_CONSTANT_ENCAPSED_STRING || $this->__tokens[$position][0] == T_COMMENT || $this->__tokens[$position] == '.') {
  293. if ($this->__tokens[$position][0] == T_CONSTANT_ENCAPSED_STRING) {
  294. $string .= $this->__formatString($this->__tokens[$position][1]);
  295. }
  296. $position++;
  297. }
  298. if ($this->__tokens[$position][0] == T_COMMENT || $this->__tokens[$position] == ',' || $this->__tokens[$position] == ')') {
  299. $strings[] = $string;
  300. }
  301. } else if ($this->__tokens[$position][0] == T_CONSTANT_ENCAPSED_STRING) {
  302. $strings[] = $this->__formatString($this->__tokens[$position][1]);
  303. }
  304. $position++;
  305. }
  306. return $strings;
  307. }
  308. /**
  309. * Build the translate template file contents out of obtained strings
  310. *
  311. * @return void
  312. * @access private
  313. */
  314. function __buildFiles() {
  315. foreach ($this->__strings as $domain => $strings) {
  316. foreach ($strings as $string => $files) {
  317. $occurrences = array();
  318. foreach ($files as $file => $lines) {
  319. $occurrences[] = $file . ':' . implode(';', $lines);
  320. }
  321. $occurrences = implode("\n#: ", $occurrences);
  322. $header = '#: ' . str_replace($this->__paths, '', $occurrences) . "\n";
  323. if (strpos($string, "\0") === false) {
  324. $sentence = "msgid \"{$string}\"\n";
  325. $sentence .= "msgstr \"\"\n\n";
  326. } else {
  327. list($singular, $plural) = explode("\0", $string);
  328. $sentence = "msgid \"{$singular}\"\n";
  329. $sentence .= "msgid_plural \"{$plural}\"\n";
  330. $sentence .= "msgstr[0] \"\"\n";
  331. $sentence .= "msgstr[1] \"\"\n\n";
  332. }
  333. $this->__store($domain, $header, $sentence);
  334. if ($domain != 'default' && $this->__merge) {
  335. $this->__store('default', $header, $sentence);
  336. }
  337. }
  338. }
  339. }
  340. /**
  341. * Prepare a file to be stored
  342. *
  343. * @return void
  344. * @access private
  345. */
  346. function __store($domain, $header, $sentence) {
  347. if (!isset($this->__storage[$domain])) {
  348. $this->__storage[$domain] = array();
  349. }
  350. if (!isset($this->__storage[$domain][$sentence])) {
  351. $this->__storage[$domain][$sentence] = $header;
  352. } else {
  353. $this->__storage[$domain][$sentence] .= $header;
  354. }
  355. }
  356. /**
  357. * Write the files that need to be stored
  358. *
  359. * @return void
  360. * @access private
  361. */
  362. function __writeFiles() {
  363. $overwriteAll = false;
  364. foreach ($this->__storage as $domain => $sentences) {
  365. $output = $this->__writeHeader();
  366. foreach ($sentences as $sentence => $header) {
  367. $output .= $header . $sentence;
  368. }
  369. $filename = $domain . '.pot';
  370. $File = new File($this->__output . $filename);
  371. $response = '';
  372. while ($overwriteAll === false && $File->exists() && strtoupper($response) !== 'Y') {
  373. $this->out();
  374. $response = $this->in(sprintf(__('Error: %s already exists in this location. Overwrite? [Y]es, [N]o, [A]ll', true), $filename), array('y', 'n', 'a'), 'y');
  375. if (strtoupper($response) === 'N') {
  376. $response = '';
  377. while ($response == '') {
  378. $response = $this->in(sprintf(__("What would you like to name this file?\nExample: %s", true), 'new_' . $filename), null, 'new_' . $filename);
  379. $File = new File($this->__output . $response);
  380. $filename = $response;
  381. }
  382. } elseif (strtoupper($response) === 'A') {
  383. $overwriteAll = true;
  384. }
  385. }
  386. $File->write($output);
  387. $File->close();
  388. }
  389. }
  390. /**
  391. * Build the translation template header
  392. *
  393. * @return string Translation template header
  394. * @access private
  395. */
  396. function __writeHeader() {
  397. $output = "# LANGUAGE translation of CakePHP Application\n";
  398. $output .= "# Copyright YEAR NAME <EMAIL@ADDRESS>\n";
  399. $output .= "#\n";
  400. $output .= "#, fuzzy\n";
  401. $output .= "msgid \"\"\n";
  402. $output .= "msgstr \"\"\n";
  403. $output .= "\"Project-Id-Version: PROJECT VERSION\\n\"\n";
  404. $output .= "\"POT-Creation-Date: " . date("Y-m-d H:iO") . "\\n\"\n";
  405. $output .= "\"PO-Revision-Date: YYYY-mm-DD HH:MM+ZZZZ\\n\"\n";
  406. $output .= "\"Last-Translator: NAME <EMAIL@ADDRESS>\\n\"\n";
  407. $output .= "\"Language-Team: LANGUAGE <EMAIL@ADDRESS>\\n\"\n";
  408. $output .= "\"MIME-Version: 1.0\\n\"\n";
  409. $output .= "\"Content-Type: text/plain; charset=utf-8\\n\"\n";
  410. $output .= "\"Content-Transfer-Encoding: 8bit\\n\"\n";
  411. $output .= "\"Plural-Forms: nplurals=INTEGER; plural=EXPRESSION;\\n\"\n\n";
  412. return $output;
  413. }
  414. /**
  415. * Format a string to be added as a translateable string
  416. *
  417. * @param string $string String to format
  418. * @return string Formatted string
  419. * @access private
  420. */
  421. function __formatString($string) {
  422. $quote = substr($string, 0, 1);
  423. $string = substr($string, 1, -1);
  424. if ($quote == '"') {
  425. $string = stripcslashes($string);
  426. } else {
  427. $string = strtr($string, array("\\'" => "'", "\\\\" => "\\"));
  428. }
  429. $string = str_replace("\r\n", "\n", $string);
  430. return addcslashes($string, "\0..\37\\\"");
  431. }
  432. /**
  433. * Indicate an invalid marker on a processed file
  434. *
  435. * @param string $file File where invalid marker resides
  436. * @param integer $line Line number
  437. * @param string $marker Marker found
  438. * @param integer $count Count
  439. * @return void
  440. * @access private
  441. */
  442. function __markerError($file, $line, $marker, $count) {
  443. $this->out(sprintf(__("Invalid marker content in %s:%s\n* %s(", true), $file, $line, $marker), true);
  444. $count += 2;
  445. $tokenCount = count($this->__tokens);
  446. $parenthesis = 1;
  447. while ((($tokenCount - $count) > 0) && $parenthesis) {
  448. if (is_array($this->__tokens[$count])) {
  449. $this->out($this->__tokens[$count][1], false);
  450. } else {
  451. $this->out($this->__tokens[$count], false);
  452. if ($this->__tokens[$count] == '(') {
  453. $parenthesis++;
  454. }
  455. if ($this->__tokens[$count] == ')') {
  456. $parenthesis--;
  457. }
  458. }
  459. $count++;
  460. }
  461. $this->out("\n", true);
  462. }
  463. /**
  464. * Search files that may contain translateable strings
  465. *
  466. * @return void
  467. * @access private
  468. */
  469. function __searchFiles() {
  470. foreach ($this->__paths as $path) {
  471. $Folder = new Folder($path);
  472. $files = $Folder->findRecursive('.*\.(php|ctp|thtml|inc|tpl)', true);
  473. $this->__files = array_merge($this->__files, $files);
  474. }
  475. }
  476. }