ExtractTask.php 16 KB

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