ExtractTask.php 19 KB

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