ExtractTask.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549
  1. <?php
  2. /**
  3. * Language string extractor
  4. *
  5. * PHP 5
  6. *
  7. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  8. * Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
  9. *
  10. * Licensed under The MIT License
  11. * Redistributions of files must retain the above copyright notice.
  12. *
  13. * @copyright Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
  14. * @link http://cakephp.org CakePHP(tm) Project
  15. * @package cake.console.shells.tasks
  16. * @since CakePHP(tm) v 1.2.0.5012
  17. * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
  18. */
  19. App::uses('File', 'Utility');
  20. App::uses('Folder', 'Utility');
  21. /**
  22. * Language string extractor
  23. *
  24. * @package cake.console.shells.tasks
  25. */
  26. class ExtractTask extends Shell {
  27. /**
  28. * Paths to use when looking for strings
  29. *
  30. * @var string
  31. * @access protected
  32. */
  33. protected $_paths = array();
  34. /**
  35. * Files from where to extract
  36. *
  37. * @var array
  38. * @access protected
  39. */
  40. protected $_files = array();
  41. /**
  42. * Merge all domains string into the default.pot file
  43. *
  44. * @var boolean
  45. * @access protected
  46. */
  47. protected $_merge = false;
  48. /**
  49. * Current file being processed
  50. *
  51. * @var string
  52. * @access protected
  53. */
  54. protected $_file = null;
  55. /**
  56. * Contains all content waiting to be write
  57. *
  58. * @var string
  59. * @access protected
  60. */
  61. protected $_storage = array();
  62. /**
  63. * Extracted tokens
  64. *
  65. * @var array
  66. * @access protected
  67. */
  68. protected $_tokens = array();
  69. /**
  70. * Extracted strings
  71. *
  72. * @var array
  73. * @access protected
  74. */
  75. protected $_strings = array();
  76. /**
  77. * Destination path
  78. *
  79. * @var string
  80. * @access protected
  81. */
  82. protected $_output = null;
  83. /**
  84. * An array of directories to exclude.
  85. *
  86. * @var array
  87. */
  88. protected $_exclude = array();
  89. /**
  90. * Execution method always used for tasks
  91. *
  92. * @return void
  93. * @access public
  94. */
  95. public function execute() {
  96. if (!empty($this->params['exclude'])) {
  97. $this->_exclude = explode(',', $this->params['exclude']);
  98. }
  99. if (isset($this->params['files']) && !is_array($this->params['files'])) {
  100. $this->_files = explode(',', $this->params['files']);
  101. }
  102. if (isset($this->params['paths'])) {
  103. $this->_paths = explode(',', $this->params['paths']);
  104. } else {
  105. $defaultPath = APP;
  106. $message = __d('cake_console', "What is the path you would like to extract?\n[Q]uit [D]one");
  107. while (true) {
  108. $response = $this->in($message, null, $defaultPath);
  109. if (strtoupper($response) === 'Q') {
  110. $this->out(__d('cake_console', 'Extract Aborted'));
  111. $this->_stop();
  112. } elseif (strtoupper($response) === 'D') {
  113. $this->out();
  114. break;
  115. } elseif (is_dir($response)) {
  116. $this->_paths[] = $response;
  117. $defaultPath = 'D';
  118. } else {
  119. $this->err(__d('cake_console', 'The directory path you supplied was not found. Please try again.'));
  120. }
  121. $this->out();
  122. }
  123. }
  124. if (!empty($this->params['exclude-plugins']) && $this->_isExtractingApp()) {
  125. $this->_exclude = array_merge($this->_exclude, App::path('plugins'));
  126. }
  127. if (isset($this->params['output'])) {
  128. $this->_output = $this->params['output'];
  129. } else {
  130. $message = __d('cake_console', "What is the path you would like to output?\n[Q]uit", $this->_paths[0] . DS . 'locale');
  131. while (true) {
  132. $response = $this->in($message, null, $this->_paths[0] . DS . 'locale');
  133. if (strtoupper($response) === 'Q') {
  134. $this->out(__d('cake_console', 'Extract Aborted'));
  135. $this->_stop();
  136. } elseif (is_dir($response)) {
  137. $this->_output = $response . DS;
  138. break;
  139. } else {
  140. $this->err(__d('cake_console', 'The directory path you supplied was not found. Please try again.'));
  141. }
  142. $this->out();
  143. }
  144. }
  145. if (isset($this->params['merge'])) {
  146. $this->_merge = !(strtolower($this->params['merge']) === 'no');
  147. } else {
  148. $this->out();
  149. $response = $this->in(__d('cake_console', 'Would you like to merge all domains strings into the default.pot file?'), array('y', 'n'), 'n');
  150. $this->_merge = strtolower($response) === 'y';
  151. }
  152. if (empty($this->_files)) {
  153. $this->_searchFiles();
  154. }
  155. $this->_extract();
  156. }
  157. /**
  158. * Extract text
  159. *
  160. * @return void
  161. * @access protected
  162. */
  163. protected function _extract() {
  164. $this->out();
  165. $this->out();
  166. $this->out(__d('cake_console', 'Extracting...'));
  167. $this->hr();
  168. $this->out(__d('cake_console', 'Paths:'));
  169. foreach ($this->_paths as $path) {
  170. $this->out(' ' . $path);
  171. }
  172. $this->out(__d('cake_console', 'Output Directory: ') . $this->_output);
  173. $this->hr();
  174. $this->_extractTokens();
  175. $this->_buildFiles();
  176. $this->_writeFiles();
  177. $this->_paths = $this->_files = $this->_storage = array();
  178. $this->_strings = $this->_tokens = array();
  179. $this->out();
  180. $this->out(__d('cake_console', 'Done.'));
  181. }
  182. /**
  183. * Get & configure the option parser
  184. *
  185. * @return void
  186. */
  187. public function getOptionParser() {
  188. $parser = parent::getOptionParser();
  189. return $parser->description(__d('cake_console', 'CakePHP Language String Extraction:'))
  190. ->addOption('app', array('help' => __d('cake_console', 'Directory where your application is located.')))
  191. ->addOption('paths', array('help' => __d('cake_console', 'Comma separated list of paths.')))
  192. ->addOption('merge', array(
  193. 'help' => __d('cake_console', 'Merge all domain strings into the default.po file.'),
  194. 'choices' => array('yes', 'no')
  195. ))
  196. ->addOption('output', array('help' => __d('cake_console', 'Full path to output directory.')))
  197. ->addOption('files', array('help' => __d('cake_console', 'Comma separated list of files.')))
  198. ->addOption('exclude-plugins', array(
  199. 'boolean' => true,
  200. 'default' => true,
  201. 'help' => __d('cake_console', 'Ignores all files in plugins.')
  202. ))
  203. ->addOption('ignore-model-validation', array(
  204. 'boolean' => true,
  205. 'default' => false,
  206. 'help' => __d('cake_console', 'Ignores validation messages in the $validate property. Needs to be run in from the same app directory')
  207. ))
  208. ->addOption('validation-domain', array(
  209. 'help' => __d('cake_console', 'If set to a value, the localization domain to be used for model validation messages')
  210. ))
  211. ->addOption('exclude', array(
  212. 'help' => __d('cake_console', 'Comma separated list of directories to exclude. Any path containing a path segment with the provided values will be skipped. E.g. test,vendors')
  213. ));
  214. }
  215. /**
  216. * Extract tokens out of all files to be processed
  217. *
  218. * @return void
  219. * @access protected
  220. */
  221. protected function _extractTokens() {
  222. foreach ($this->_files as $file) {
  223. $this->_file = $file;
  224. $this->out(__d('cake_console', 'Processing %s...', $file));
  225. $code = file_get_contents($file);
  226. $allTokens = token_get_all($code);
  227. $this->_tokens = array();
  228. foreach ($allTokens as $token) {
  229. if (!is_array($token) || ($token[0] != T_WHITESPACE && $token[0] != T_INLINE_HTML)) {
  230. $this->_tokens[] = $token;
  231. }
  232. }
  233. unset($allTokens);
  234. $this->_parse('__', array('singular'));
  235. $this->_parse('__n', array('singular', 'plural'));
  236. $this->_parse('__d', array('domain', 'singular'));
  237. $this->_parse('__c', array('singular'));
  238. $this->_parse('__dc', array('domain', 'singular'));
  239. $this->_parse('__dn', array('domain', 'singular', 'plural'));
  240. $this->_parse('__dcn', array('domain', 'singular', 'plural'));
  241. }
  242. }
  243. /**
  244. * Parse tokens
  245. *
  246. * @param string $functionName Function name that indicates translatable string (e.g: '__')
  247. * @param array $map Array containing what variables it will find (e.g: domain, singular, plural)
  248. * @return void
  249. * @access protected
  250. */
  251. protected function _parse($functionName, $map) {
  252. $count = 0;
  253. $tokenCount = count($this->_tokens);
  254. while (($tokenCount - $count) > 1) {
  255. list($countToken, $firstParenthesis) = array($this->_tokens[$count], $this->_tokens[$count + 1]);
  256. if (!is_array($countToken)) {
  257. $count++;
  258. continue;
  259. }
  260. list($type, $string, $line) = $countToken;
  261. if (($type == T_STRING) && ($string == $functionName) && ($firstParenthesis == '(')) {
  262. $position = $count;
  263. $depth = 0;
  264. while ($depth == 0) {
  265. if ($this->_tokens[$position] == '(') {
  266. $depth++;
  267. } elseif ($this->_tokens[$position] == ')') {
  268. $depth--;
  269. }
  270. $position++;
  271. }
  272. $mapCount = count($map);
  273. $strings = $this->_getStrings($position, $mapCount);
  274. if ($mapCount == count($strings)) {
  275. extract(array_combine($map, $strings));
  276. $domain = isset($domain) ? $domain : 'default';
  277. $string = isset($plural) ? $singular . "\0" . $plural : $singular;
  278. $this->_strings[$domain][$string][$this->_file][] = $line;
  279. } else {
  280. $this->_markerError($this->_file, $line, $functionName, $count);
  281. }
  282. }
  283. $count++;
  284. }
  285. }
  286. /**
  287. * Build the translate template file contents out of obtained strings
  288. *
  289. * @return void
  290. * @access protected
  291. */
  292. protected function _buildFiles() {
  293. foreach ($this->_strings as $domain => $strings) {
  294. foreach ($strings as $string => $files) {
  295. $occurrences = array();
  296. foreach ($files as $file => $lines) {
  297. $occurrences[] = $file . ':' . implode(';', $lines);
  298. }
  299. $occurrences = implode("\n#: ", $occurrences);
  300. $header = '#: ' . str_replace($this->_paths, '', $occurrences) . "\n";
  301. if (strpos($string, "\0") === false) {
  302. $sentence = "msgid \"{$string}\"\n";
  303. $sentence .= "msgstr \"\"\n\n";
  304. } else {
  305. list($singular, $plural) = explode("\0", $string);
  306. $sentence = "msgid \"{$singular}\"\n";
  307. $sentence .= "msgid_plural \"{$plural}\"\n";
  308. $sentence .= "msgstr[0] \"\"\n";
  309. $sentence .= "msgstr[1] \"\"\n\n";
  310. }
  311. $this->_store($domain, $header, $sentence);
  312. if ($domain != 'default' && $this->_merge) {
  313. $this->_store('default', $header, $sentence);
  314. }
  315. }
  316. }
  317. }
  318. /**
  319. * Prepare a file to be stored
  320. *
  321. * @return void
  322. * @access protected
  323. */
  324. protected function _store($domain, $header, $sentence) {
  325. if (!isset($this->_storage[$domain])) {
  326. $this->_storage[$domain] = array();
  327. }
  328. if (!isset($this->_storage[$domain][$sentence])) {
  329. $this->_storage[$domain][$sentence] = $header;
  330. } else {
  331. $this->_storage[$domain][$sentence] .= $header;
  332. }
  333. }
  334. /**
  335. * Write the files that need to be stored
  336. *
  337. * @return void
  338. * @access protected
  339. */
  340. protected function _writeFiles() {
  341. $overwriteAll = false;
  342. foreach ($this->_storage as $domain => $sentences) {
  343. $output = $this->_writeHeader();
  344. foreach ($sentences as $sentence => $header) {
  345. $output .= $header . $sentence;
  346. }
  347. $filename = $domain . '.pot';
  348. $File = new File($this->_output . $filename);
  349. $response = '';
  350. while ($overwriteAll === false && $File->exists() && strtoupper($response) !== 'Y') {
  351. $this->out();
  352. $response = $this->in(__d('cake_console', 'Error: %s already exists in this location. Overwrite? [Y]es, [N]o, [A]ll', $filename), array('y', 'n', 'a'), 'y');
  353. if (strtoupper($response) === 'N') {
  354. $response = '';
  355. while ($response == '') {
  356. $response = $this->in(__d('cake_console', "What would you like to name this file?"), null, 'new_' . $filename);
  357. $File = new File($this->_output . $response);
  358. $filename = $response;
  359. }
  360. } elseif (strtoupper($response) === 'A') {
  361. $overwriteAll = true;
  362. }
  363. }
  364. $File->write($output);
  365. $File->close();
  366. }
  367. }
  368. /**
  369. * Build the translation template header
  370. *
  371. * @return string Translation template header
  372. * @access protected
  373. */
  374. protected function _writeHeader() {
  375. $output = "# LANGUAGE translation of CakePHP Application\n";
  376. $output .= "# Copyright YEAR NAME <EMAIL@ADDRESS>\n";
  377. $output .= "#\n";
  378. $output .= "#, fuzzy\n";
  379. $output .= "msgid \"\"\n";
  380. $output .= "msgstr \"\"\n";
  381. $output .= "\"Project-Id-Version: PROJECT VERSION\\n\"\n";
  382. $output .= "\"POT-Creation-Date: " . date("Y-m-d H:iO") . "\\n\"\n";
  383. $output .= "\"PO-Revision-Date: YYYY-mm-DD HH:MM+ZZZZ\\n\"\n";
  384. $output .= "\"Last-Translator: NAME <EMAIL@ADDRESS>\\n\"\n";
  385. $output .= "\"Language-Team: LANGUAGE <EMAIL@ADDRESS>\\n\"\n";
  386. $output .= "\"MIME-Version: 1.0\\n\"\n";
  387. $output .= "\"Content-Type: text/plain; charset=utf-8\\n\"\n";
  388. $output .= "\"Content-Transfer-Encoding: 8bit\\n\"\n";
  389. $output .= "\"Plural-Forms: nplurals=INTEGER; plural=EXPRESSION;\\n\"\n\n";
  390. return $output;
  391. }
  392. /**
  393. * Get the strings from the position forward
  394. *
  395. * @param int $position Actual position on tokens array
  396. * @param int $target Number of strings to extract
  397. * @return array Strings extracted
  398. * @access protected
  399. */
  400. protected function _getStrings(&$position, $target) {
  401. $strings = array();
  402. while (count($strings) < $target && ($this->_tokens[$position] == ',' || $this->_tokens[$position][0] == T_CONSTANT_ENCAPSED_STRING)) {
  403. if ($this->_tokens[$position][0] == T_CONSTANT_ENCAPSED_STRING && $this->_tokens[$position+1] == '.') {
  404. $string = '';
  405. while ($this->_tokens[$position][0] == T_CONSTANT_ENCAPSED_STRING || $this->_tokens[$position] == '.') {
  406. if ($this->_tokens[$position][0] == T_CONSTANT_ENCAPSED_STRING) {
  407. $string .= $this->_formatString($this->_tokens[$position][1]);
  408. }
  409. $position++;
  410. }
  411. $strings[] = $string;
  412. } else if ($this->_tokens[$position][0] == T_CONSTANT_ENCAPSED_STRING) {
  413. $strings[] = $this->_formatString($this->_tokens[$position][1]);
  414. }
  415. $position++;
  416. }
  417. return $strings;
  418. }
  419. /**
  420. * Format a string to be added as a translatable string
  421. *
  422. * @param string $string String to format
  423. * @return string Formatted string
  424. * @access protected
  425. */
  426. protected function _formatString($string) {
  427. $quote = substr($string, 0, 1);
  428. $string = substr($string, 1, -1);
  429. if ($quote == '"') {
  430. $string = stripcslashes($string);
  431. } else {
  432. $string = strtr($string, array("\\'" => "'", "\\\\" => "\\"));
  433. }
  434. $string = str_replace("\r\n", "\n", $string);
  435. return addcslashes($string, "\0..\37\\\"");
  436. }
  437. /**
  438. * Indicate an invalid marker on a processed file
  439. *
  440. * @param string $file File where invalid marker resides
  441. * @param integer $line Line number
  442. * @param string $marker Marker found
  443. * @param integer $count Count
  444. * @return void
  445. * @access protected
  446. */
  447. protected function _markerError($file, $line, $marker, $count) {
  448. $this->out(__d('cake_console', "Invalid marker content in %s:%s\n* %s(", $file, $line, $marker), true);
  449. $count += 2;
  450. $tokenCount = count($this->_tokens);
  451. $parenthesis = 1;
  452. while ((($tokenCount - $count) > 0) && $parenthesis) {
  453. if (is_array($this->_tokens[$count])) {
  454. $this->out($this->_tokens[$count][1], false);
  455. } else {
  456. $this->out($this->_tokens[$count], false);
  457. if ($this->_tokens[$count] == '(') {
  458. $parenthesis++;
  459. }
  460. if ($this->_tokens[$count] == ')') {
  461. $parenthesis--;
  462. }
  463. }
  464. $count++;
  465. }
  466. $this->out("\n", true);
  467. }
  468. /**
  469. * Search files that may contain translatable strings
  470. *
  471. * @return void
  472. * @access protected
  473. */
  474. protected function _searchFiles() {
  475. $pattern = false;
  476. if (!empty($this->_exclude)) {
  477. $exclude = array();
  478. foreach ($this->_exclude as $e) {
  479. if ($e[0] !== DS) {
  480. $e = DS . $e;
  481. }
  482. $exclude[] = preg_quote($e, '/');
  483. }
  484. $pattern = '/' . implode('|', $exclude) . '/';
  485. }
  486. foreach ($this->_paths as $path) {
  487. $Folder = new Folder($path);
  488. $files = $Folder->findRecursive('.*\.(php|ctp|thtml|inc|tpl)', true);
  489. if (!empty($pattern)) {
  490. foreach ($files as $i => $file) {
  491. if (preg_match($pattern, $file)) {
  492. unset($files[$i]);
  493. }
  494. }
  495. $files = array_values($files);
  496. }
  497. $this->_files = array_merge($this->_files, $files);
  498. }
  499. }
  500. /**
  501. * Returns whether this execution is meant to extract string only from directories in folder represented by the
  502. * APP constant, i.e. this task is extracting strings from same application.
  503. *
  504. * @return boolean
  505. */
  506. protected function _isExtractingApp() {
  507. return $this->_paths === array(APP);
  508. }
  509. }