ExtractTask.php 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789
  1. <?php
  2. /**
  3. * Language string extractor
  4. *
  5. * PHP 5
  6. *
  7. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  8. * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  9. *
  10. * Licensed under The MIT License
  11. * For full copyright and license information, please see the LICENSE.txt
  12. * Redistributions of files must retain the above copyright notice.
  13. *
  14. * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  15. * @link http://cakephp.org CakePHP(tm) Project
  16. * @since CakePHP(tm) v 1.2.0.5012
  17. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  18. */
  19. App::uses('AppShell', 'Console/Command');
  20. App::uses('File', 'Utility');
  21. App::uses('Folder', 'Utility');
  22. App::uses('Hash', 'Utility');
  23. /**
  24. * Language string extractor
  25. *
  26. * @package Cake.Console.Command.Task
  27. */
  28. class ExtractTask extends AppShell {
  29. /**
  30. * Paths to use when looking for strings
  31. *
  32. * @var string
  33. */
  34. protected $_paths = array();
  35. /**
  36. * Files from where to extract
  37. *
  38. * @var array
  39. */
  40. protected $_files = array();
  41. /**
  42. * Merge all domains string into the default.pot file
  43. *
  44. * @var boolean
  45. */
  46. protected $_merge = false;
  47. /**
  48. * Current file being processed
  49. *
  50. * @var string
  51. */
  52. protected $_file = null;
  53. /**
  54. * Contains all content waiting to be write
  55. *
  56. * @var string
  57. */
  58. protected $_storage = array();
  59. /**
  60. * Extracted tokens
  61. *
  62. * @var array
  63. */
  64. protected $_tokens = array();
  65. /**
  66. * Extracted strings indexed by domain.
  67. *
  68. * @var array
  69. */
  70. protected $_translations = array();
  71. /**
  72. * Destination path
  73. *
  74. * @var string
  75. */
  76. protected $_output = null;
  77. /**
  78. * An array of directories to exclude.
  79. *
  80. * @var array
  81. */
  82. protected $_exclude = array();
  83. /**
  84. * Holds whether this call should extract model validation messages
  85. *
  86. * @var boolean
  87. */
  88. protected $_extractValidation = true;
  89. /**
  90. * Holds the validation string domain to use for validation messages when extracting
  91. *
  92. * @var boolean
  93. */
  94. protected $_validationDomain = 'default';
  95. /**
  96. * Holds whether this call should extract the CakePHP Lib messages
  97. *
  98. * @var boolean
  99. */
  100. protected $_extractCore = false;
  101. /**
  102. * Method to interact with the User and get path selections.
  103. *
  104. * @return void
  105. */
  106. protected function _getPaths() {
  107. $defaultPath = APP;
  108. while (true) {
  109. $currentPaths = count($this->_paths) > 0 ? $this->_paths : array('None');
  110. $message = __d(
  111. 'cake_console',
  112. "Current paths: %s\nWhat is the path you would like to extract?\n[Q]uit [D]one",
  113. implode(', ', $currentPaths)
  114. );
  115. $response = $this->in($message, null, $defaultPath);
  116. if (strtoupper($response) === 'Q') {
  117. $this->out(__d('cake_console', 'Extract Aborted'));
  118. return $this->_stop();
  119. } elseif (strtoupper($response) === 'D' && count($this->_paths)) {
  120. $this->out();
  121. return;
  122. } elseif (strtoupper($response) === 'D') {
  123. $this->err(__d('cake_console', '<warning>No directories selected.</warning> Please choose a directory.'));
  124. } elseif (is_dir($response)) {
  125. $this->_paths[] = $response;
  126. $defaultPath = 'D';
  127. } else {
  128. $this->err(__d('cake_console', 'The directory path you supplied was not found. Please try again.'));
  129. }
  130. $this->out();
  131. }
  132. }
  133. /**
  134. * Execution method always used for tasks
  135. *
  136. * @return void
  137. */
  138. public function execute() {
  139. if (!empty($this->params['exclude'])) {
  140. $this->_exclude = explode(',', $this->params['exclude']);
  141. }
  142. if (isset($this->params['files']) && !is_array($this->params['files'])) {
  143. $this->_files = explode(',', $this->params['files']);
  144. }
  145. if (isset($this->params['paths'])) {
  146. $this->_paths = explode(',', $this->params['paths']);
  147. } elseif (isset($this->params['plugin'])) {
  148. $plugin = Inflector::camelize($this->params['plugin']);
  149. if (!CakePlugin::loaded($plugin)) {
  150. CakePlugin::load($plugin);
  151. }
  152. $this->_paths = array(CakePlugin::path($plugin));
  153. $this->params['plugin'] = $plugin;
  154. } else {
  155. $this->_getPaths();
  156. }
  157. if (isset($this->params['extract-core'])) {
  158. $this->_extractCore = !(strtolower($this->params['extract-core']) === 'no');
  159. } else {
  160. $response = $this->in(__d('cake_console', 'Would you like to extract the messages from the CakePHP core?'), array('y', 'n'), 'n');
  161. $this->_extractCore = strtolower($response) === 'y';
  162. }
  163. if (!empty($this->params['exclude-plugins']) && $this->_isExtractingApp()) {
  164. $this->_exclude = array_merge($this->_exclude, App::path('plugins'));
  165. }
  166. if (!empty($this->params['ignore-model-validation']) || (!$this->_isExtractingApp() && empty($plugin))) {
  167. $this->_extractValidation = false;
  168. }
  169. if (!empty($this->params['validation-domain'])) {
  170. $this->_validationDomain = $this->params['validation-domain'];
  171. }
  172. if ($this->_extractCore) {
  173. $this->_paths[] = CAKE;
  174. $this->_exclude = array_merge($this->_exclude, array(
  175. CAKE . 'Test',
  176. CAKE . 'Console' . DS . 'Templates'
  177. ));
  178. }
  179. if (isset($this->params['output'])) {
  180. $this->_output = $this->params['output'];
  181. } elseif (isset($this->params['plugin'])) {
  182. $this->_output = $this->_paths[0] . DS . 'Locale';
  183. } else {
  184. $message = __d('cake_console', "What is the path you would like to output?\n[Q]uit", $this->_paths[0] . DS . 'Locale');
  185. while (true) {
  186. $response = $this->in($message, null, rtrim($this->_paths[0], DS) . DS . 'Locale');
  187. if (strtoupper($response) === 'Q') {
  188. $this->out(__d('cake_console', 'Extract Aborted'));
  189. return $this->_stop();
  190. } elseif ($this->_isPathUsable($response)) {
  191. $this->_output = $response . DS;
  192. break;
  193. } else {
  194. $this->err(__d('cake_console', 'The directory path you supplied was not found. Please try again.'));
  195. }
  196. $this->out();
  197. }
  198. }
  199. if (isset($this->params['merge'])) {
  200. $this->_merge = !(strtolower($this->params['merge']) === 'no');
  201. } else {
  202. $this->out();
  203. $response = $this->in(__d('cake_console', 'Would you like to merge all domains strings into the default.pot file?'), array('y', 'n'), 'n');
  204. $this->_merge = strtolower($response) === 'y';
  205. }
  206. if (empty($this->_files)) {
  207. $this->_searchFiles();
  208. }
  209. $this->_output = rtrim($this->_output, DS) . DS;
  210. if (!$this->_isPathUsable($this->_output)) {
  211. $this->err(__d('cake_console', 'The output directory %s was not found or writable.', $this->_output));
  212. return $this->_stop();
  213. }
  214. $this->_extract();
  215. }
  216. /**
  217. * Add a translation to the internal translations property
  218. *
  219. * Takes care of duplicate translations
  220. *
  221. * @param string $domain
  222. * @param string $msgid
  223. * @param array $details
  224. * @return void
  225. */
  226. protected function _addTranslation($domain, $msgid, $details = array()) {
  227. if (empty($this->_translations[$domain][$msgid])) {
  228. $this->_translations[$domain][$msgid] = array(
  229. 'msgid_plural' => false
  230. );
  231. }
  232. if (isset($details['msgid_plural'])) {
  233. $this->_translations[$domain][$msgid]['msgid_plural'] = $details['msgid_plural'];
  234. }
  235. if (isset($details['file'])) {
  236. $line = 0;
  237. if (isset($details['line'])) {
  238. $line = $details['line'];
  239. }
  240. $this->_translations[$domain][$msgid]['references'][$details['file']][] = $line;
  241. }
  242. }
  243. /**
  244. * Extract text
  245. *
  246. * @return void
  247. */
  248. protected function _extract() {
  249. $this->out();
  250. $this->out();
  251. $this->out(__d('cake_console', 'Extracting...'));
  252. $this->hr();
  253. $this->out(__d('cake_console', 'Paths:'));
  254. foreach ($this->_paths as $path) {
  255. $this->out(' ' . $path);
  256. }
  257. $this->out(__d('cake_console', 'Output Directory: ') . $this->_output);
  258. $this->hr();
  259. $this->_extractTokens();
  260. $this->_extractValidationMessages();
  261. $this->_buildFiles();
  262. $this->_writeFiles();
  263. $this->_paths = $this->_files = $this->_storage = array();
  264. $this->_translations = $this->_tokens = array();
  265. $this->_extractValidation = true;
  266. $this->out();
  267. $this->out(__d('cake_console', 'Done.'));
  268. }
  269. /**
  270. * Get & configure the option parser
  271. *
  272. * @return void
  273. */
  274. public function getOptionParser() {
  275. $parser = parent::getOptionParser();
  276. return $parser->description(__d('cake_console', 'CakePHP Language String Extraction:'))
  277. ->addOption('app', array('help' => __d('cake_console', 'Directory where your application is located.')))
  278. ->addOption('paths', array('help' => __d('cake_console', 'Comma separated list of paths.')))
  279. ->addOption('merge', array(
  280. 'help' => __d('cake_console', 'Merge all domain strings into the default.po file.'),
  281. 'choices' => array('yes', 'no')
  282. ))
  283. ->addOption('output', array('help' => __d('cake_console', 'Full path to output directory.')))
  284. ->addOption('files', array('help' => __d('cake_console', 'Comma separated list of files.')))
  285. ->addOption('exclude-plugins', array(
  286. 'boolean' => true,
  287. 'default' => true,
  288. 'help' => __d('cake_console', 'Ignores all files in plugins if this command is run inside from the same app directory.')
  289. ))
  290. ->addOption('plugin', array(
  291. 'help' => __d('cake_console', 'Extracts tokens only from the plugin specified and puts the result in the plugin\'s Locale directory.')
  292. ))
  293. ->addOption('ignore-model-validation', array(
  294. 'boolean' => true,
  295. 'default' => false,
  296. 'help' => __d('cake_console', 'Ignores validation messages in the $validate property.' .
  297. ' If this flag is not set and the command is run from the same app directory,' .
  298. ' all messages in model validation rules will be extracted as tokens.')
  299. ))
  300. ->addOption('validation-domain', array(
  301. 'help' => __d('cake_console', 'If set to a value, the localization domain to be used for model validation messages.')
  302. ))
  303. ->addOption('exclude', array(
  304. 'help' => __d('cake_console', 'Comma separated list of directories to exclude.' .
  305. ' Any path containing a path segment with the provided values will be skipped. E.g. test,vendors')
  306. ))
  307. ->addOption('overwrite', array(
  308. 'boolean' => true,
  309. 'default' => false,
  310. 'help' => __d('cake_console', 'Always overwrite existing .pot files.')
  311. ))
  312. ->addOption('extract-core', array(
  313. 'help' => __d('cake_console', 'Extract messages from the CakePHP core libs.'),
  314. 'choices' => array('yes', 'no')
  315. ));
  316. }
  317. /**
  318. * Extract tokens out of all files to be processed
  319. *
  320. * @return void
  321. */
  322. protected function _extractTokens() {
  323. foreach ($this->_files as $file) {
  324. $this->_file = $file;
  325. $this->out(__d('cake_console', 'Processing %s...', $file));
  326. $code = file_get_contents($file);
  327. $allTokens = token_get_all($code);
  328. $this->_tokens = array();
  329. foreach ($allTokens as $token) {
  330. if (!is_array($token) || ($token[0] != T_WHITESPACE && $token[0] != T_INLINE_HTML)) {
  331. $this->_tokens[] = $token;
  332. }
  333. }
  334. unset($allTokens);
  335. $this->_parse('__', array('singular'));
  336. $this->_parse('__n', array('singular', 'plural'));
  337. $this->_parse('__d', array('domain', 'singular'));
  338. $this->_parse('__c', array('singular'));
  339. $this->_parse('__dc', array('domain', 'singular'));
  340. $this->_parse('__dn', array('domain', 'singular', 'plural'));
  341. $this->_parse('__dcn', array('domain', 'singular', 'plural'));
  342. }
  343. }
  344. /**
  345. * Parse tokens
  346. *
  347. * @param string $functionName Function name that indicates translatable string (e.g: '__')
  348. * @param array $map Array containing what variables it will find (e.g: domain, singular, plural)
  349. * @return void
  350. */
  351. protected function _parse($functionName, $map) {
  352. $count = 0;
  353. $tokenCount = count($this->_tokens);
  354. while (($tokenCount - $count) > 1) {
  355. $countToken = $this->_tokens[$count];
  356. $firstParenthesis = $this->_tokens[$count + 1];
  357. if (!is_array($countToken)) {
  358. $count++;
  359. continue;
  360. }
  361. list($type, $string, $line) = $countToken;
  362. if (($type == T_STRING) && ($string == $functionName) && ($firstParenthesis === '(')) {
  363. $position = $count;
  364. $depth = 0;
  365. while (!$depth) {
  366. if ($this->_tokens[$position] === '(') {
  367. $depth++;
  368. } elseif ($this->_tokens[$position] === ')') {
  369. $depth--;
  370. }
  371. $position++;
  372. }
  373. $mapCount = count($map);
  374. $strings = $this->_getStrings($position, $mapCount);
  375. if ($mapCount == count($strings)) {
  376. extract(array_combine($map, $strings));
  377. $domain = isset($domain) ? $domain : 'default';
  378. $details = array(
  379. 'file' => $this->_file,
  380. 'line' => $line,
  381. );
  382. if (isset($plural)) {
  383. $details['msgid_plural'] = $plural;
  384. }
  385. $this->_addTranslation($domain, $singular, $details);
  386. } else {
  387. $this->_markerError($this->_file, $line, $functionName, $count);
  388. }
  389. }
  390. $count++;
  391. }
  392. }
  393. /**
  394. * Looks for models in the application and extracts the validation messages
  395. * to be added to the translation map
  396. *
  397. * @return void
  398. */
  399. protected function _extractValidationMessages() {
  400. if (!$this->_extractValidation) {
  401. return;
  402. }
  403. $plugins = array(null);
  404. if (empty($this->params['exclude-plugins'])) {
  405. $plugins = array_merge($plugins, App::objects('plugin', null, false));
  406. }
  407. foreach ($plugins as $plugin) {
  408. $this->_extractPluginValidationMessages($plugin);
  409. }
  410. }
  411. /**
  412. * Extract validation messages from application or plugin models
  413. *
  414. * @param string $plugin Plugin name or `null` to process application models
  415. * @return void
  416. */
  417. protected function _extractPluginValidationMessages($plugin = null) {
  418. App::uses('AppModel', 'Model');
  419. if (!empty($plugin)) {
  420. if (!CakePlugin::loaded($plugin)) {
  421. return;
  422. }
  423. App::uses($plugin . 'AppModel', $plugin . '.Model');
  424. $plugin = $plugin . '.';
  425. }
  426. $models = App::objects($plugin . 'Model', null, false);
  427. foreach ($models as $model) {
  428. App::uses($model, $plugin . 'Model');
  429. $reflection = new ReflectionClass($model);
  430. if (!$reflection->isSubClassOf('Model')) {
  431. continue;
  432. }
  433. $properties = $reflection->getDefaultProperties();
  434. $validate = $properties['validate'];
  435. if (empty($validate)) {
  436. continue;
  437. }
  438. $file = $reflection->getFileName();
  439. $domain = $this->_validationDomain;
  440. if (!empty($properties['validationDomain'])) {
  441. $domain = $properties['validationDomain'];
  442. }
  443. foreach ($validate as $field => $rules) {
  444. $this->_processValidationRules($field, $rules, $file, $domain);
  445. }
  446. }
  447. }
  448. /**
  449. * Process a validation rule for a field and looks for a message to be added
  450. * to the translation map
  451. *
  452. * @param string $field the name of the field that is being processed
  453. * @param array $rules the set of validation rules for the field
  454. * @param string $file the file name where this validation rule was found
  455. * @param string $domain default domain to bind the validations to
  456. * @return void
  457. */
  458. protected function _processValidationRules($field, $rules, $file, $domain) {
  459. if (!is_array($rules)) {
  460. return;
  461. }
  462. $dims = Hash::dimensions($rules);
  463. if ($dims === 1 || ($dims === 2 && isset($rules['message']))) {
  464. $rules = array($rules);
  465. }
  466. foreach ($rules as $rule => $validateProp) {
  467. $msgid = null;
  468. if (isset($validateProp['message'])) {
  469. if (is_array($validateProp['message'])) {
  470. $msgid = $validateProp['message'][0];
  471. } else {
  472. $msgid = $validateProp['message'];
  473. }
  474. } elseif (is_string($rule)) {
  475. $msgid = $rule;
  476. }
  477. if ($msgid) {
  478. $details = array(
  479. 'file' => $file,
  480. 'line' => 'validation for field ' . $field
  481. );
  482. $this->_addTranslation($domain, $msgid, $details);
  483. }
  484. }
  485. }
  486. /**
  487. * Build the translate template file contents out of obtained strings
  488. *
  489. * @return void
  490. */
  491. protected function _buildFiles() {
  492. $paths = $this->_paths;
  493. $paths[] = realpath(APP) . DS;
  494. foreach ($this->_translations as $domain => $translations) {
  495. foreach ($translations as $msgid => $details) {
  496. $plural = $details['msgid_plural'];
  497. $files = $details['references'];
  498. $occurrences = array();
  499. foreach ($files as $file => $lines) {
  500. $lines = array_unique($lines);
  501. $occurrences[] = $file . ':' . implode(';', $lines);
  502. }
  503. $occurrences = implode("\n#: ", $occurrences);
  504. $header = '#: ' . str_replace(DS, '/', str_replace($paths, '', $occurrences)) . "\n";
  505. if ($plural === false) {
  506. $sentence = "msgid \"{$msgid}\"\n";
  507. $sentence .= "msgstr \"\"\n\n";
  508. } else {
  509. $sentence = "msgid \"{$msgid}\"\n";
  510. $sentence .= "msgid_plural \"{$plural}\"\n";
  511. $sentence .= "msgstr[0] \"\"\n";
  512. $sentence .= "msgstr[1] \"\"\n\n";
  513. }
  514. $this->_store($domain, $header, $sentence);
  515. if ($domain !== 'default' && $this->_merge) {
  516. $this->_store('default', $header, $sentence);
  517. }
  518. }
  519. }
  520. }
  521. /**
  522. * Prepare a file to be stored
  523. *
  524. * @param string $domain
  525. * @param string $header
  526. * @param string $sentence
  527. * @return void
  528. */
  529. protected function _store($domain, $header, $sentence) {
  530. if (!isset($this->_storage[$domain])) {
  531. $this->_storage[$domain] = array();
  532. }
  533. if (!isset($this->_storage[$domain][$sentence])) {
  534. $this->_storage[$domain][$sentence] = $header;
  535. } else {
  536. $this->_storage[$domain][$sentence] .= $header;
  537. }
  538. }
  539. /**
  540. * Write the files that need to be stored
  541. *
  542. * @return void
  543. */
  544. protected function _writeFiles() {
  545. $overwriteAll = false;
  546. if (!empty($this->params['overwrite'])) {
  547. $overwriteAll = true;
  548. }
  549. foreach ($this->_storage as $domain => $sentences) {
  550. $output = $this->_writeHeader();
  551. foreach ($sentences as $sentence => $header) {
  552. $output .= $header . $sentence;
  553. }
  554. $filename = $domain . '.pot';
  555. $File = new File($this->_output . $filename);
  556. $response = '';
  557. while ($overwriteAll === false && $File->exists() && strtoupper($response) !== 'Y') {
  558. $this->out();
  559. $response = $this->in(
  560. __d('cake_console', 'Error: %s already exists in this location. Overwrite? [Y]es, [N]o, [A]ll', $filename),
  561. array('y', 'n', 'a'),
  562. 'y'
  563. );
  564. if (strtoupper($response) === 'N') {
  565. $response = '';
  566. while (!$response) {
  567. $response = $this->in(__d('cake_console', "What would you like to name this file?"), null, 'new_' . $filename);
  568. $File = new File($this->_output . $response);
  569. $filename = $response;
  570. }
  571. } elseif (strtoupper($response) === 'A') {
  572. $overwriteAll = true;
  573. }
  574. }
  575. $File->write($output);
  576. $File->close();
  577. }
  578. }
  579. /**
  580. * Build the translation template header
  581. *
  582. * @return string Translation template header
  583. */
  584. protected function _writeHeader() {
  585. $output = "# LANGUAGE translation of CakePHP Application\n";
  586. $output .= "# Copyright YEAR NAME <EMAIL@ADDRESS>\n";
  587. $output .= "#\n";
  588. $output .= "#, fuzzy\n";
  589. $output .= "msgid \"\"\n";
  590. $output .= "msgstr \"\"\n";
  591. $output .= "\"Project-Id-Version: PROJECT VERSION\\n\"\n";
  592. $output .= "\"POT-Creation-Date: " . date("Y-m-d H:iO") . "\\n\"\n";
  593. $output .= "\"PO-Revision-Date: YYYY-mm-DD HH:MM+ZZZZ\\n\"\n";
  594. $output .= "\"Last-Translator: NAME <EMAIL@ADDRESS>\\n\"\n";
  595. $output .= "\"Language-Team: LANGUAGE <EMAIL@ADDRESS>\\n\"\n";
  596. $output .= "\"MIME-Version: 1.0\\n\"\n";
  597. $output .= "\"Content-Type: text/plain; charset=utf-8\\n\"\n";
  598. $output .= "\"Content-Transfer-Encoding: 8bit\\n\"\n";
  599. $output .= "\"Plural-Forms: nplurals=INTEGER; plural=EXPRESSION;\\n\"\n\n";
  600. return $output;
  601. }
  602. /**
  603. * Get the strings from the position forward
  604. *
  605. * @param integer $position Actual position on tokens array
  606. * @param integer $target Number of strings to extract
  607. * @return array Strings extracted
  608. */
  609. protected function _getStrings(&$position, $target) {
  610. $strings = array();
  611. $count = count($strings);
  612. while ($count < $target && ($this->_tokens[$position] === ',' || $this->_tokens[$position][0] == T_CONSTANT_ENCAPSED_STRING)) {
  613. $count = count($strings);
  614. if ($this->_tokens[$position][0] == T_CONSTANT_ENCAPSED_STRING && $this->_tokens[$position + 1] === '.') {
  615. $string = '';
  616. while ($this->_tokens[$position][0] == T_CONSTANT_ENCAPSED_STRING || $this->_tokens[$position] === '.') {
  617. if ($this->_tokens[$position][0] == T_CONSTANT_ENCAPSED_STRING) {
  618. $string .= $this->_formatString($this->_tokens[$position][1]);
  619. }
  620. $position++;
  621. }
  622. $strings[] = $string;
  623. } elseif ($this->_tokens[$position][0] == T_CONSTANT_ENCAPSED_STRING) {
  624. $strings[] = $this->_formatString($this->_tokens[$position][1]);
  625. }
  626. $position++;
  627. }
  628. return $strings;
  629. }
  630. /**
  631. * Format a string to be added as a translatable string
  632. *
  633. * @param string $string String to format
  634. * @return string Formatted string
  635. */
  636. protected function _formatString($string) {
  637. $quote = substr($string, 0, 1);
  638. $string = substr($string, 1, -1);
  639. if ($quote === '"') {
  640. $string = stripcslashes($string);
  641. } else {
  642. $string = strtr($string, array("\\'" => "'", "\\\\" => "\\"));
  643. }
  644. $string = str_replace("\r\n", "\n", $string);
  645. return addcslashes($string, "\0..\37\\\"");
  646. }
  647. /**
  648. * Indicate an invalid marker on a processed file
  649. *
  650. * @param string $file File where invalid marker resides
  651. * @param integer $line Line number
  652. * @param string $marker Marker found
  653. * @param integer $count Count
  654. * @return void
  655. */
  656. protected function _markerError($file, $line, $marker, $count) {
  657. $this->out(__d('cake_console', "Invalid marker content in %s:%s\n* %s(", $file, $line, $marker));
  658. $count += 2;
  659. $tokenCount = count($this->_tokens);
  660. $parenthesis = 1;
  661. while ((($tokenCount - $count) > 0) && $parenthesis) {
  662. if (is_array($this->_tokens[$count])) {
  663. $this->out($this->_tokens[$count][1], false);
  664. } else {
  665. $this->out($this->_tokens[$count], false);
  666. if ($this->_tokens[$count] === '(') {
  667. $parenthesis++;
  668. }
  669. if ($this->_tokens[$count] === ')') {
  670. $parenthesis--;
  671. }
  672. }
  673. $count++;
  674. }
  675. $this->out("\n", true);
  676. }
  677. /**
  678. * Search files that may contain translatable strings
  679. *
  680. * @return void
  681. */
  682. protected function _searchFiles() {
  683. $pattern = false;
  684. if (!empty($this->_exclude)) {
  685. $exclude = array();
  686. foreach ($this->_exclude as $e) {
  687. if (DS !== '\\' && $e[0] !== DS) {
  688. $e = DS . $e;
  689. }
  690. $exclude[] = preg_quote($e, '/');
  691. }
  692. $pattern = '/' . implode('|', $exclude) . '/';
  693. }
  694. foreach ($this->_paths as $path) {
  695. $Folder = new Folder($path);
  696. $files = $Folder->findRecursive('.*\.(php|ctp|thtml|inc|tpl)', true);
  697. if (!empty($pattern)) {
  698. foreach ($files as $i => $file) {
  699. if (preg_match($pattern, $file)) {
  700. unset($files[$i]);
  701. }
  702. }
  703. $files = array_values($files);
  704. }
  705. $this->_files = array_merge($this->_files, $files);
  706. }
  707. }
  708. /**
  709. * Returns whether this execution is meant to extract string only from directories in folder represented by the
  710. * APP constant, i.e. this task is extracting strings from same application.
  711. *
  712. * @return boolean
  713. */
  714. protected function _isExtractingApp() {
  715. return $this->_paths === array(APP);
  716. }
  717. /**
  718. * Checks whether or not a given path is usable for writing.
  719. *
  720. * @param string $path Path to folder
  721. * @return boolean true if it exists and is writable, false otherwise
  722. */
  723. protected function _isPathUsable($path) {
  724. return is_dir($path) && is_writable($path);
  725. }
  726. }