ExtractTask.php 24 KB

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