ExtractTask.php 23 KB

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