ExtractTask.php 25 KB

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