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

/lib/Cake/Console/Command/Task/ExtractTask.php

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