ExtractTask.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616
  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. * Holds whether this call should extract model validation messages
  91. *
  92. * @var boolean
  93. */
  94. protected $_extractValidation = true;
  95. /**
  96. * Execution method always used for tasks
  97. *
  98. * @return void
  99. * @access public
  100. */
  101. public function execute() {
  102. if (!empty($this->params['exclude'])) {
  103. $this->_exclude = explode(',', $this->params['exclude']);
  104. }
  105. if (isset($this->params['files']) && !is_array($this->params['files'])) {
  106. $this->_files = explode(',', $this->params['files']);
  107. }
  108. if (isset($this->params['paths'])) {
  109. $this->_paths = explode(',', $this->params['paths']);
  110. } else {
  111. $defaultPath = APP;
  112. $message = __d('cake_console', "What is the path you would like to extract?\n[Q]uit [D]one");
  113. while (true) {
  114. $response = $this->in($message, null, $defaultPath);
  115. if (strtoupper($response) === 'Q') {
  116. $this->out(__d('cake_console', 'Extract Aborted'));
  117. $this->_stop();
  118. } elseif (strtoupper($response) === 'D') {
  119. $this->out();
  120. break;
  121. } elseif (is_dir($response)) {
  122. $this->_paths[] = $response;
  123. $defaultPath = 'D';
  124. } else {
  125. $this->err(__d('cake_console', 'The directory path you supplied was not found. Please try again.'));
  126. }
  127. $this->out();
  128. }
  129. }
  130. if (!empty($this->params['exclude-plugins']) && $this->_isExtractingApp()) {
  131. $this->_exclude = array_merge($this->_exclude, App::path('plugins'));
  132. }
  133. if (!empty($this->params['ignore-model-validation']) || !$this->_isExtractingApp()) {
  134. $this->_extractValidation = false;
  135. }
  136. if (isset($this->params['output'])) {
  137. $this->_output = $this->params['output'];
  138. } else {
  139. $message = __d('cake_console', "What is the path you would like to output?\n[Q]uit", $this->_paths[0] . DS . 'locale');
  140. while (true) {
  141. $response = $this->in($message, null, $this->_paths[0] . DS . 'locale');
  142. if (strtoupper($response) === 'Q') {
  143. $this->out(__d('cake_console', 'Extract Aborted'));
  144. $this->_stop();
  145. } elseif (is_dir($response)) {
  146. $this->_output = $response . DS;
  147. break;
  148. } else {
  149. $this->err(__d('cake_console', 'The directory path you supplied was not found. Please try again.'));
  150. }
  151. $this->out();
  152. }
  153. }
  154. if (isset($this->params['merge'])) {
  155. $this->_merge = !(strtolower($this->params['merge']) === 'no');
  156. } else {
  157. $this->out();
  158. $response = $this->in(__d('cake_console', 'Would you like to merge all domains strings into the default.pot file?'), array('y', 'n'), 'n');
  159. $this->_merge = strtolower($response) === 'y';
  160. }
  161. if (empty($this->_files)) {
  162. $this->_searchFiles();
  163. }
  164. $this->_extract();
  165. }
  166. /**
  167. * Extract text
  168. *
  169. * @return void
  170. * @access protected
  171. */
  172. protected function _extract() {
  173. $this->out();
  174. $this->out();
  175. $this->out(__d('cake_console', 'Extracting...'));
  176. $this->hr();
  177. $this->out(__d('cake_console', 'Paths:'));
  178. foreach ($this->_paths as $path) {
  179. $this->out(' ' . $path);
  180. }
  181. $this->out(__d('cake_console', 'Output Directory: ') . $this->_output);
  182. $this->hr();
  183. $this->_extractTokens();
  184. $this->_extractValidationMessages();
  185. $this->_buildFiles();
  186. $this->_writeFiles();
  187. $this->_paths = $this->_files = $this->_storage = array();
  188. $this->_strings = $this->_tokens = array();
  189. $this->_extractValidation = true;
  190. $this->out();
  191. $this->out(__d('cake_console', 'Done.'));
  192. }
  193. /**
  194. * Get & configure the option parser
  195. *
  196. * @return void
  197. */
  198. public function getOptionParser() {
  199. $parser = parent::getOptionParser();
  200. return $parser->description(__d('cake_console', 'CakePHP Language String Extraction:'))
  201. ->addOption('app', array('help' => __d('cake_console', 'Directory where your application is located.')))
  202. ->addOption('paths', array('help' => __d('cake_console', 'Comma separated list of paths.')))
  203. ->addOption('merge', array(
  204. 'help' => __d('cake_console', 'Merge all domain strings into the default.po file.'),
  205. 'choices' => array('yes', 'no')
  206. ))
  207. ->addOption('output', array('help' => __d('cake_console', 'Full path to output directory.')))
  208. ->addOption('files', array('help' => __d('cake_console', 'Comma separated list of files.')))
  209. ->addOption('exclude-plugins', array(
  210. 'boolean' => true,
  211. 'default' => true,
  212. 'help' => __d('cake_console', 'Ignores all files in plugins.')
  213. ))
  214. ->addOption('ignore-model-validation', array(
  215. 'boolean' => true,
  216. 'default' => false,
  217. 'help' => __d('cake_console', 'Ignores validation messages in the $validate property. Needs to be run in from the same app directory')
  218. ))
  219. ->addOption('validation-domain', array(
  220. 'help' => __d('cake_console', 'If set to a value, the localization domain to be used for model validation messages')
  221. ))
  222. ->addOption('exclude', array(
  223. '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')
  224. ));
  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. * Looks for models in the application and extracts the validation messages
  299. * to be added to the translation map
  300. *
  301. * @return void
  302. */
  303. protected function _extractValidationMessages() {
  304. if (!$this->_extractValidation) {
  305. return;
  306. }
  307. $models = App::objects('Model');
  308. App::uses('AppModel', 'Model');
  309. foreach ($models as $model) {
  310. App::uses($model, 'Model');
  311. $reflection = new ReflectionClass($model);
  312. $properties = $reflection->getDefaultProperties();
  313. $validate = $properties['validate'];
  314. if (empty($validate)) {
  315. continue;
  316. }
  317. $file = $reflection->getFileName();
  318. $domain = 'default';
  319. foreach ($validate as $field => $rules) {
  320. $this->_processValidationRules($field, $rules, $file, $domain);
  321. }
  322. }
  323. }
  324. /**
  325. * Process a validation rule for a field and looks for a message to be added
  326. * to the translation map
  327. *
  328. * @param string $field the name of the field that is being processed
  329. * @param array $rules the set of validation rules for the field
  330. * @param string $file the file name where this validation rule was found
  331. * @param string domain default domain to bind the validations to
  332. * @return void
  333. */
  334. protected function _processValidationRules($field, $rules, $file, $domain) {
  335. if (is_array($rules)) {
  336. $dims = Set::countDim($rules);
  337. if ($dims == 1 || ($dims == 2 && isset($rules['message']))) {
  338. $rules = array($rules);
  339. }
  340. foreach ($rules as $rule => $validateProp) {
  341. if (isset($validateProp['message'])) {
  342. $this->_strings[$domain][$validateProp['message']][$file][] = 'validation for field ' . $field;
  343. }
  344. }
  345. }
  346. }
  347. /**
  348. * Build the translate template file contents out of obtained strings
  349. *
  350. * @return void
  351. * @access protected
  352. */
  353. protected function _buildFiles() {
  354. foreach ($this->_strings as $domain => $strings) {
  355. foreach ($strings as $string => $files) {
  356. $occurrences = array();
  357. foreach ($files as $file => $lines) {
  358. $occurrences[] = $file . ':' . implode(';', $lines);
  359. }
  360. $occurrences = implode("\n#: ", $occurrences);
  361. $header = '#: ' . str_replace($this->_paths, '', $occurrences) . "\n";
  362. if (strpos($string, "\0") === false) {
  363. $sentence = "msgid \"{$string}\"\n";
  364. $sentence .= "msgstr \"\"\n\n";
  365. } else {
  366. list($singular, $plural) = explode("\0", $string);
  367. $sentence = "msgid \"{$singular}\"\n";
  368. $sentence .= "msgid_plural \"{$plural}\"\n";
  369. $sentence .= "msgstr[0] \"\"\n";
  370. $sentence .= "msgstr[1] \"\"\n\n";
  371. }
  372. $this->_store($domain, $header, $sentence);
  373. if ($domain != 'default' && $this->_merge) {
  374. $this->_store('default', $header, $sentence);
  375. }
  376. }
  377. }
  378. }
  379. /**
  380. * Prepare a file to be stored
  381. *
  382. * @return void
  383. * @access protected
  384. */
  385. protected function _store($domain, $header, $sentence) {
  386. if (!isset($this->_storage[$domain])) {
  387. $this->_storage[$domain] = array();
  388. }
  389. if (!isset($this->_storage[$domain][$sentence])) {
  390. $this->_storage[$domain][$sentence] = $header;
  391. } else {
  392. $this->_storage[$domain][$sentence] .= $header;
  393. }
  394. }
  395. /**
  396. * Write the files that need to be stored
  397. *
  398. * @return void
  399. * @access protected
  400. */
  401. protected function _writeFiles() {
  402. $overwriteAll = false;
  403. foreach ($this->_storage as $domain => $sentences) {
  404. $output = $this->_writeHeader();
  405. foreach ($sentences as $sentence => $header) {
  406. $output .= $header . $sentence;
  407. }
  408. $filename = $domain . '.pot';
  409. $File = new File($this->_output . $filename);
  410. $response = '';
  411. while ($overwriteAll === false && $File->exists() && strtoupper($response) !== 'Y') {
  412. $this->out();
  413. $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');
  414. if (strtoupper($response) === 'N') {
  415. $response = '';
  416. while ($response == '') {
  417. $response = $this->in(__d('cake_console', "What would you like to name this file?"), null, 'new_' . $filename);
  418. $File = new File($this->_output . $response);
  419. $filename = $response;
  420. }
  421. } elseif (strtoupper($response) === 'A') {
  422. $overwriteAll = true;
  423. }
  424. }
  425. $File->write($output);
  426. $File->close();
  427. }
  428. }
  429. /**
  430. * Build the translation template header
  431. *
  432. * @return string Translation template header
  433. * @access protected
  434. */
  435. protected function _writeHeader() {
  436. $output = "# LANGUAGE translation of CakePHP Application\n";
  437. $output .= "# Copyright YEAR NAME <EMAIL@ADDRESS>\n";
  438. $output .= "#\n";
  439. $output .= "#, fuzzy\n";
  440. $output .= "msgid \"\"\n";
  441. $output .= "msgstr \"\"\n";
  442. $output .= "\"Project-Id-Version: PROJECT VERSION\\n\"\n";
  443. $output .= "\"POT-Creation-Date: " . date("Y-m-d H:iO") . "\\n\"\n";
  444. $output .= "\"PO-Revision-Date: YYYY-mm-DD HH:MM+ZZZZ\\n\"\n";
  445. $output .= "\"Last-Translator: NAME <EMAIL@ADDRESS>\\n\"\n";
  446. $output .= "\"Language-Team: LANGUAGE <EMAIL@ADDRESS>\\n\"\n";
  447. $output .= "\"MIME-Version: 1.0\\n\"\n";
  448. $output .= "\"Content-Type: text/plain; charset=utf-8\\n\"\n";
  449. $output .= "\"Content-Transfer-Encoding: 8bit\\n\"\n";
  450. $output .= "\"Plural-Forms: nplurals=INTEGER; plural=EXPRESSION;\\n\"\n\n";
  451. return $output;
  452. }
  453. /**
  454. * Get the strings from the position forward
  455. *
  456. * @param int $position Actual position on tokens array
  457. * @param int $target Number of strings to extract
  458. * @return array Strings extracted
  459. * @access protected
  460. */
  461. protected function _getStrings(&$position, $target) {
  462. $strings = array();
  463. while (count($strings) < $target && ($this->_tokens[$position] == ',' || $this->_tokens[$position][0] == T_CONSTANT_ENCAPSED_STRING)) {
  464. if ($this->_tokens[$position][0] == T_CONSTANT_ENCAPSED_STRING && $this->_tokens[$position+1] == '.') {
  465. $string = '';
  466. while ($this->_tokens[$position][0] == T_CONSTANT_ENCAPSED_STRING || $this->_tokens[$position] == '.') {
  467. if ($this->_tokens[$position][0] == T_CONSTANT_ENCAPSED_STRING) {
  468. $string .= $this->_formatString($this->_tokens[$position][1]);
  469. }
  470. $position++;
  471. }
  472. $strings[] = $string;
  473. } else if ($this->_tokens[$position][0] == T_CONSTANT_ENCAPSED_STRING) {
  474. $strings[] = $this->_formatString($this->_tokens[$position][1]);
  475. }
  476. $position++;
  477. }
  478. return $strings;
  479. }
  480. /**
  481. * Format a string to be added as a translatable string
  482. *
  483. * @param string $string String to format
  484. * @return string Formatted string
  485. * @access protected
  486. */
  487. protected function _formatString($string) {
  488. $quote = substr($string, 0, 1);
  489. $string = substr($string, 1, -1);
  490. if ($quote == '"') {
  491. $string = stripcslashes($string);
  492. } else {
  493. $string = strtr($string, array("\\'" => "'", "\\\\" => "\\"));
  494. }
  495. $string = str_replace("\r\n", "\n", $string);
  496. return addcslashes($string, "\0..\37\\\"");
  497. }
  498. /**
  499. * Indicate an invalid marker on a processed file
  500. *
  501. * @param string $file File where invalid marker resides
  502. * @param integer $line Line number
  503. * @param string $marker Marker found
  504. * @param integer $count Count
  505. * @return void
  506. * @access protected
  507. */
  508. protected function _markerError($file, $line, $marker, $count) {
  509. $this->out(__d('cake_console', "Invalid marker content in %s:%s\n* %s(", $file, $line, $marker), true);
  510. $count += 2;
  511. $tokenCount = count($this->_tokens);
  512. $parenthesis = 1;
  513. while ((($tokenCount - $count) > 0) && $parenthesis) {
  514. if (is_array($this->_tokens[$count])) {
  515. $this->out($this->_tokens[$count][1], false);
  516. } else {
  517. $this->out($this->_tokens[$count], false);
  518. if ($this->_tokens[$count] == '(') {
  519. $parenthesis++;
  520. }
  521. if ($this->_tokens[$count] == ')') {
  522. $parenthesis--;
  523. }
  524. }
  525. $count++;
  526. }
  527. $this->out("\n", true);
  528. }
  529. /**
  530. * Search files that may contain translatable strings
  531. *
  532. * @return void
  533. * @access protected
  534. */
  535. protected function _searchFiles() {
  536. $pattern = false;
  537. if (!empty($this->_exclude)) {
  538. $exclude = array();
  539. foreach ($this->_exclude as $e) {
  540. if ($e[0] !== DS) {
  541. $e = DS . $e;
  542. }
  543. $exclude[] = preg_quote($e, '/');
  544. }
  545. $pattern = '/' . implode('|', $exclude) . '/';
  546. }
  547. foreach ($this->_paths as $path) {
  548. $Folder = new Folder($path);
  549. $files = $Folder->findRecursive('.*\.(php|ctp|thtml|inc|tpl)', true);
  550. if (!empty($pattern)) {
  551. foreach ($files as $i => $file) {
  552. if (preg_match($pattern, $file)) {
  553. unset($files[$i]);
  554. }
  555. }
  556. $files = array_values($files);
  557. }
  558. $this->_files = array_merge($this->_files, $files);
  559. }
  560. }
  561. /**
  562. * Returns whether this execution is meant to extract string only from directories in folder represented by the
  563. * APP constant, i.e. this task is extracting strings from same application.
  564. *
  565. * @return boolean
  566. */
  567. protected function _isExtractingApp() {
  568. return $this->_paths === array(APP);
  569. }
  570. }