ExtractTask.php 24 KB

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