ExtractTask.php 21 KB

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