ExtractTask.php 22 KB

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