PageRenderTime 64ms CodeModel.GetById 33ms RepoModel.GetById 0ms app.codeStats 0ms

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

https://bitbucket.org/dosm123/crm
PHP | 700 lines | 479 code | 51 blank | 170 comment | 100 complexity | 3142ce65a4d84fd8b7ad9b418cbbb27b MD5 | raw file
Possible License(s): LGPL-3.0, GPL-3.0, LGPL-2.1
  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 indexed by domain.
  65. *
  66. * @var array
  67. */
  68. protected $_translations = 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. } elseif (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. } elseif (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. * Add a translation to the internal translations property
  178. *
  179. * Takes care of duplicate translations
  180. *
  181. * @param string $domain
  182. * @param string $msgid
  183. * @param array $details
  184. */
  185. protected function _addTranslation($domain, $msgid, $details = array()) {
  186. if (empty($this->_translations[$domain][$msgid])) {
  187. $this->_translations[$domain][$msgid] = array(
  188. 'msgid_plural' => false
  189. );
  190. }
  191. if (isset($details['msgid_plural'])) {
  192. $this->_translations[$domain][$msgid]['msgid_plural'] = $details['msgid_plural'];
  193. }
  194. if (isset($details['file'])) {
  195. $line = 0;
  196. if (isset($details['line'])) {
  197. $line = $details['line'];
  198. }
  199. $this->_translations[$domain][$msgid]['references'][$details['file']][] = $line;
  200. }
  201. }
  202. /**
  203. * Extract text
  204. *
  205. * @return void
  206. */
  207. protected function _extract() {
  208. $this->out();
  209. $this->out();
  210. $this->out(__d('cake_console', 'Extracting...'));
  211. $this->hr();
  212. $this->out(__d('cake_console', 'Paths:'));
  213. foreach ($this->_paths as $path) {
  214. $this->out(' ' . $path);
  215. }
  216. $this->out(__d('cake_console', 'Output Directory: ') . $this->_output);
  217. $this->hr();
  218. $this->_extractTokens();
  219. $this->_extractValidationMessages();
  220. $this->_buildFiles();
  221. $this->_writeFiles();
  222. $this->_paths = $this->_files = $this->_storage = array();
  223. $this->_translations = $this->_tokens = array();
  224. $this->_extractValidation = true;
  225. $this->out();
  226. $this->out(__d('cake_console', 'Done.'));
  227. }
  228. /**
  229. * Get & configure the option parser
  230. *
  231. * @return void
  232. */
  233. public function getOptionParser() {
  234. $parser = parent::getOptionParser();
  235. return $parser->description(__d('cake_console', 'CakePHP Language String Extraction:'))
  236. ->addOption('app', array('help' => __d('cake_console', 'Directory where your application is located.')))
  237. ->addOption('paths', array('help' => __d('cake_console', 'Comma separated list of paths.')))
  238. ->addOption('merge', array(
  239. 'help' => __d('cake_console', 'Merge all domain strings into the default.po file.'),
  240. 'choices' => array('yes', 'no')
  241. ))
  242. ->addOption('output', array('help' => __d('cake_console', 'Full path to output directory.')))
  243. ->addOption('files', array('help' => __d('cake_console', 'Comma separated list of files.')))
  244. ->addOption('exclude-plugins', array(
  245. 'boolean' => true,
  246. 'default' => true,
  247. 'help' => __d('cake_console', 'Ignores all files in plugins if this command is run inside from the same app directory.')
  248. ))
  249. ->addOption('plugin', array(
  250. 'help' => __d('cake_console', 'Extracts tokens only from the plugin specified and puts the result in the plugin\'s Locale directory.')
  251. ))
  252. ->addOption('ignore-model-validation', array(
  253. 'boolean' => true,
  254. 'default' => false,
  255. 'help' => __d('cake_console', 'Ignores validation messages in the $validate property.' .
  256. ' If this flag is not set and the command is run from the same app directory,' .
  257. ' all messages in model validation rules will be extracted as tokens.')
  258. ))
  259. ->addOption('validation-domain', array(
  260. 'help' => __d('cake_console', 'If set to a value, the localization domain to be used for model validation messages.')
  261. ))
  262. ->addOption('exclude', array(
  263. 'help' => __d('cake_console', 'Comma separated list of directories to exclude.' .
  264. ' Any path containing a path segment with the provided values will be skipped. E.g. test,vendors')
  265. ));
  266. }
  267. /**
  268. * Extract tokens out of all files to be processed
  269. *
  270. * @return void
  271. */
  272. protected function _extractTokens() {
  273. foreach ($this->_files as $file) {
  274. $this->_file = $file;
  275. $this->out(__d('cake_console', 'Processing %s...', $file));
  276. $code = file_get_contents($file);
  277. $allTokens = token_get_all($code);
  278. $this->_tokens = array();
  279. foreach ($allTokens as $token) {
  280. if (!is_array($token) || ($token[0] != T_WHITESPACE && $token[0] != T_INLINE_HTML)) {
  281. $this->_tokens[] = $token;
  282. }
  283. }
  284. unset($allTokens);
  285. $this->_parse('__', array('singular'));
  286. $this->_parse('__n', array('singular', 'plural'));
  287. $this->_parse('__d', array('domain', 'singular'));
  288. $this->_parse('__c', array('singular'));
  289. $this->_parse('__dc', array('domain', 'singular'));
  290. $this->_parse('__dn', array('domain', 'singular', 'plural'));
  291. $this->_parse('__dcn', array('domain', 'singular', 'plural'));
  292. }
  293. }
  294. /**
  295. * Parse tokens
  296. *
  297. * @param string $functionName Function name that indicates translatable string (e.g: '__')
  298. * @param array $map Array containing what variables it will find (e.g: domain, singular, plural)
  299. * @return void
  300. */
  301. protected function _parse($functionName, $map) {
  302. $count = 0;
  303. $tokenCount = count($this->_tokens);
  304. while (($tokenCount - $count) > 1) {
  305. $countToken = $this->_tokens[$count];
  306. $firstParenthesis = $this->_tokens[$count + 1];
  307. if (!is_array($countToken)) {
  308. $count++;
  309. continue;
  310. }
  311. list($type, $string, $line) = $countToken;
  312. if (($type == T_STRING) && ($string == $functionName) && ($firstParenthesis == '(')) {
  313. $position = $count;
  314. $depth = 0;
  315. while ($depth == 0) {
  316. if ($this->_tokens[$position] == '(') {
  317. $depth++;
  318. } elseif ($this->_tokens[$position] == ')') {
  319. $depth--;
  320. }
  321. $position++;
  322. }
  323. $mapCount = count($map);
  324. $strings = $this->_getStrings($position, $mapCount);
  325. if ($mapCount == count($strings)) {
  326. extract(array_combine($map, $strings));
  327. $domain = isset($domain) ? $domain : 'default';
  328. $details = array(
  329. 'file' => $this->_file,
  330. 'line' => $line,
  331. );
  332. if (isset($plural)) {
  333. $details['msgid_plural'] = $plural;
  334. }
  335. $this->_addTranslation($domain, $singular, $details);
  336. } else {
  337. $this->_markerError($this->_file, $line, $functionName, $count);
  338. }
  339. }
  340. $count++;
  341. }
  342. }
  343. /**
  344. * Looks for models in the application and extracts the validation messages
  345. * to be added to the translation map
  346. *
  347. * @return void
  348. */
  349. protected function _extractValidationMessages() {
  350. if (!$this->_extractValidation) {
  351. return;
  352. }
  353. App::uses('AppModel', 'Model');
  354. $plugin = null;
  355. if (!empty($this->params['plugin'])) {
  356. App::uses($this->params['plugin'] . 'AppModel', $this->params['plugin'] . '.Model');
  357. $plugin = $this->params['plugin'] . '.';
  358. }
  359. $models = App::objects($plugin . 'Model', null, false);
  360. foreach ($models as $model) {
  361. App::uses($model, $plugin . 'Model');
  362. $reflection = new ReflectionClass($model);
  363. if (!$reflection->isSubClassOf('Model')) {
  364. continue;
  365. }
  366. $properties = $reflection->getDefaultProperties();
  367. $validate = $properties['validate'];
  368. if (empty($validate)) {
  369. continue;
  370. }
  371. $file = $reflection->getFileName();
  372. $domain = $this->_validationDomain;
  373. if (!empty($properties['validationDomain'])) {
  374. $domain = $properties['validationDomain'];
  375. }
  376. foreach ($validate as $field => $rules) {
  377. $this->_processValidationRules($field, $rules, $file, $domain);
  378. }
  379. }
  380. }
  381. /**
  382. * Process a validation rule for a field and looks for a message to be added
  383. * to the translation map
  384. *
  385. * @param string $field the name of the field that is being processed
  386. * @param array $rules the set of validation rules for the field
  387. * @param string $file the file name where this validation rule was found
  388. * @param string $domain default domain to bind the validations to
  389. * @return void
  390. */
  391. protected function _processValidationRules($field, $rules, $file, $domain) {
  392. if (!is_array($rules)) {
  393. return;
  394. }
  395. $dims = Set::countDim($rules);
  396. if ($dims == 1 || ($dims == 2 && isset($rules['message']))) {
  397. $rules = array($rules);
  398. }
  399. foreach ($rules as $rule => $validateProp) {
  400. $msgid = null;
  401. if (isset($validateProp['message'])) {
  402. if (is_array($validateProp['message'])) {
  403. $msgid = $validateProp['message'][0];
  404. } else {
  405. $msgid = $validateProp['message'];
  406. }
  407. } elseif (is_string($rule)) {
  408. $msgid = $rule;
  409. }
  410. if ($msgid) {
  411. $details = array(
  412. 'file' => $file,
  413. 'line' => 'validation for field ' . $field
  414. );
  415. $this->_addTranslation($domain, $msgid, $details);
  416. }
  417. }
  418. }
  419. /**
  420. * Build the translate template file contents out of obtained strings
  421. *
  422. * @return void
  423. */
  424. protected function _buildFiles() {
  425. foreach ($this->_translations as $domain => $translations) {
  426. foreach ($translations as $msgid => $details) {
  427. $plural = $details['msgid_plural'];
  428. $files = $details['references'];
  429. $occurrences = array();
  430. foreach ($files as $file => $lines) {
  431. $lines = array_unique($lines);
  432. $occurrences[] = $file . ':' . implode(';', $lines);
  433. }
  434. $occurrences = implode("\n#: ", $occurrences);
  435. $header = '#: ' . str_replace($this->_paths, '', $occurrences) . "\n";
  436. if ($plural === false) {
  437. $sentence = "msgid \"{$msgid}\"\n";
  438. $sentence .= "msgstr \"\"\n\n";
  439. } else {
  440. $sentence = "msgid \"{$msgid}\"\n";
  441. $sentence .= "msgid_plural \"{$plural}\"\n";
  442. $sentence .= "msgstr[0] \"\"\n";
  443. $sentence .= "msgstr[1] \"\"\n\n";
  444. }
  445. $this->_store($domain, $header, $sentence);
  446. if ($domain != 'default' && $this->_merge) {
  447. $this->_store('default', $header, $sentence);
  448. }
  449. }
  450. }
  451. }
  452. /**
  453. * Prepare a file to be stored
  454. *
  455. * @param string $domain
  456. * @param string $header
  457. * @param string $sentence
  458. * @return void
  459. */
  460. protected function _store($domain, $header, $sentence) {
  461. if (!isset($this->_storage[$domain])) {
  462. $this->_storage[$domain] = array();
  463. }
  464. if (!isset($this->_storage[$domain][$sentence])) {
  465. $this->_storage[$domain][$sentence] = $header;
  466. } else {
  467. $this->_storage[$domain][$sentence] .= $header;
  468. }
  469. }
  470. /**
  471. * Write the files that need to be stored
  472. *
  473. * @return void
  474. */
  475. protected function _writeFiles() {
  476. $overwriteAll = false;
  477. foreach ($this->_storage as $domain => $sentences) {
  478. $output = $this->_writeHeader();
  479. foreach ($sentences as $sentence => $header) {
  480. $output .= $header . $sentence;
  481. }
  482. $filename = $domain . '.pot';
  483. $File = new File($this->_output . $filename);
  484. $response = '';
  485. while ($overwriteAll === false && $File->exists() && strtoupper($response) !== 'Y') {
  486. $this->out();
  487. $response = $this->in(
  488. __d('cake_console', 'Error: %s already exists in this location. Overwrite? [Y]es, [N]o, [A]ll', $filename),
  489. array('y', 'n', 'a'),
  490. 'y'
  491. );
  492. if (strtoupper($response) === 'N') {
  493. $response = '';
  494. while ($response == '') {
  495. $response = $this->in(__d('cake_console', "What would you like to name this file?"), null, 'new_' . $filename);
  496. $File = new File($this->_output . $response);
  497. $filename = $response;
  498. }
  499. } elseif (strtoupper($response) === 'A') {
  500. $overwriteAll = true;
  501. }
  502. }
  503. $File->write($output);
  504. $File->close();
  505. }
  506. }
  507. /**
  508. * Build the translation template header
  509. *
  510. * @return string Translation template header
  511. */
  512. protected function _writeHeader() {
  513. $output = "# LANGUAGE translation of CakePHP Application\n";
  514. $output .= "# Copyright YEAR NAME <EMAIL@ADDRESS>\n";
  515. $output .= "#\n";
  516. $output .= "#, fuzzy\n";
  517. $output .= "msgid \"\"\n";
  518. $output .= "msgstr \"\"\n";
  519. $output .= "\"Project-Id-Version: PROJECT VERSION\\n\"\n";
  520. $output .= "\"POT-Creation-Date: " . date("Y-m-d H:iO") . "\\n\"\n";
  521. $output .= "\"PO-Revision-Date: YYYY-mm-DD HH:MM+ZZZZ\\n\"\n";
  522. $output .= "\"Last-Translator: NAME <EMAIL@ADDRESS>\\n\"\n";
  523. $output .= "\"Language-Team: LANGUAGE <EMAIL@ADDRESS>\\n\"\n";
  524. $output .= "\"MIME-Version: 1.0\\n\"\n";
  525. $output .= "\"Content-Type: text/plain; charset=utf-8\\n\"\n";
  526. $output .= "\"Content-Transfer-Encoding: 8bit\\n\"\n";
  527. $output .= "\"Plural-Forms: nplurals=INTEGER; plural=EXPRESSION;\\n\"\n\n";
  528. return $output;
  529. }
  530. /**
  531. * Get the strings from the position forward
  532. *
  533. * @param integer $position Actual position on tokens array
  534. * @param integer $target Number of strings to extract
  535. * @return array Strings extracted
  536. */
  537. protected function _getStrings(&$position, $target) {
  538. $strings = array();
  539. $count = count($strings);
  540. while ($count < $target && ($this->_tokens[$position] == ',' || $this->_tokens[$position][0] == T_CONSTANT_ENCAPSED_STRING)) {
  541. $count = count($strings);
  542. if ($this->_tokens[$position][0] == T_CONSTANT_ENCAPSED_STRING && $this->_tokens[$position + 1] == '.') {
  543. $string = '';
  544. while ($this->_tokens[$position][0] == T_CONSTANT_ENCAPSED_STRING || $this->_tokens[$position] == '.') {
  545. if ($this->_tokens[$position][0] == T_CONSTANT_ENCAPSED_STRING) {
  546. $string .= $this->_formatString($this->_tokens[$position][1]);
  547. }
  548. $position++;
  549. }
  550. $strings[] = $string;
  551. } elseif ($this->_tokens[$position][0] == T_CONSTANT_ENCAPSED_STRING) {
  552. $strings[] = $this->_formatString($this->_tokens[$position][1]);
  553. }
  554. $position++;
  555. }
  556. return $strings;
  557. }
  558. /**
  559. * Format a string to be added as a translatable string
  560. *
  561. * @param string $string String to format
  562. * @return string Formatted string
  563. */
  564. protected function _formatString($string) {
  565. $quote = substr($string, 0, 1);
  566. $string = substr($string, 1, -1);
  567. if ($quote == '"') {
  568. $string = stripcslashes($string);
  569. } else {
  570. $string = strtr($string, array("\\'" => "'", "\\\\" => "\\"));
  571. }
  572. $string = str_replace("\r\n", "\n", $string);
  573. return addcslashes($string, "\0..\37\\\"");
  574. }
  575. /**
  576. * Indicate an invalid marker on a processed file
  577. *
  578. * @param string $file File where invalid marker resides
  579. * @param integer $line Line number
  580. * @param string $marker Marker found
  581. * @param integer $count Count
  582. * @return void
  583. */
  584. protected function _markerError($file, $line, $marker, $count) {
  585. $this->out(__d('cake_console', "Invalid marker content in %s:%s\n* %s(", $file, $line, $marker), true);
  586. $count += 2;
  587. $tokenCount = count($this->_tokens);
  588. $parenthesis = 1;
  589. while ((($tokenCount - $count) > 0) && $parenthesis) {
  590. if (is_array($this->_tokens[$count])) {
  591. $this->out($this->_tokens[$count][1], false);
  592. } else {
  593. $this->out($this->_tokens[$count], false);
  594. if ($this->_tokens[$count] == '(') {
  595. $parenthesis++;
  596. }
  597. if ($this->_tokens[$count] == ')') {
  598. $parenthesis--;
  599. }
  600. }
  601. $count++;
  602. }
  603. $this->out("\n", true);
  604. }
  605. /**
  606. * Search files that may contain translatable strings
  607. *
  608. * @return void
  609. */
  610. protected function _searchFiles() {
  611. $pattern = false;
  612. if (!empty($this->_exclude)) {
  613. $exclude = array();
  614. foreach ($this->_exclude as $e) {
  615. if (DS !== '\\' && $e[0] !== DS) {
  616. $e = DS . $e;
  617. }
  618. $exclude[] = preg_quote($e, '/');
  619. }
  620. $pattern = '/' . implode('|', $exclude) . '/';
  621. }
  622. foreach ($this->_paths as $path) {
  623. $Folder = new Folder($path);
  624. $files = $Folder->findRecursive('.*\.(php|ctp|thtml|inc|tpl)', true);
  625. if (!empty($pattern)) {
  626. foreach ($files as $i => $file) {
  627. if (preg_match($pattern, $file)) {
  628. unset($files[$i]);
  629. }
  630. }
  631. $files = array_values($files);
  632. }
  633. $this->_files = array_merge($this->_files, $files);
  634. }
  635. }
  636. /**
  637. * Returns whether this execution is meant to extract string only from directories in folder represented by the
  638. * APP constant, i.e. this task is extracting strings from same application.
  639. *
  640. * @return boolean
  641. */
  642. protected function _isExtractingApp() {
  643. return $this->_paths === array(APP);
  644. }
  645. }