ExtractTask.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553
  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 private
  32. */
  33. private $__paths = array();
  34. /**
  35. * Files from where to extract
  36. *
  37. * @var array
  38. * @access private
  39. */
  40. private $__files = array();
  41. /**
  42. * Merge all domains string into the default.pot file
  43. *
  44. * @var boolean
  45. * @access private
  46. */
  47. private $__merge = false;
  48. /**
  49. * Current file being processed
  50. *
  51. * @var string
  52. * @access private
  53. */
  54. private $__file = null;
  55. /**
  56. * Contains all content waiting to be write
  57. *
  58. * @var string
  59. * @access private
  60. */
  61. private $__storage = array();
  62. /**
  63. * Extracted tokens
  64. *
  65. * @var array
  66. * @access private
  67. */
  68. private $__tokens = array();
  69. /**
  70. * Extracted strings
  71. *
  72. * @var array
  73. * @access private
  74. */
  75. private $__strings = array();
  76. /**
  77. * Destination path
  78. *
  79. * @var string
  80. * @access private
  81. */
  82. private $__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 private
  94. */
  95. 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_PATH;
  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 (isset($this->params['output'])) {
  125. $this->__output = $this->params['output'];
  126. } else {
  127. $message = __d('cake_console', "What is the path you would like to output?\n[Q]uit", $this->__paths[0] . DS . 'locale');
  128. while (true) {
  129. $response = $this->in($message, null, $this->__paths[0] . DS . 'locale');
  130. if (strtoupper($response) === 'Q') {
  131. $this->out(__d('cake_console', 'Extract Aborted'));
  132. $this->_stop();
  133. } elseif (is_dir($response)) {
  134. $this->__output = $response . DS;
  135. break;
  136. } else {
  137. $this->err(__d('cake_console', 'The directory path you supplied was not found. Please try again.'));
  138. }
  139. $this->out();
  140. }
  141. }
  142. if (isset($this->params['merge'])) {
  143. $this->__merge = !(strtolower($this->params['merge']) === 'no');
  144. } else {
  145. $this->out();
  146. $response = $this->in(__d('cake_console', 'Would you like to merge all domains strings into the default.pot file?'), array('y', 'n'), 'n');
  147. $this->__merge = strtolower($response) === 'y';
  148. }
  149. if (empty($this->__files)) {
  150. $this->__searchFiles();
  151. }
  152. $this->__extract();
  153. }
  154. /**
  155. * Extract text
  156. *
  157. * @return void
  158. * @access private
  159. */
  160. function __extract() {
  161. $this->out();
  162. $this->out();
  163. $this->out(__d('cake_console', 'Extracting...'));
  164. $this->hr();
  165. $this->out(__d('cake_console', 'Paths:'));
  166. foreach ($this->__paths as $path) {
  167. $this->out(' ' . $path);
  168. }
  169. $this->out(__d('cake_console', 'Output Directory: ') . $this->__output);
  170. $this->hr();
  171. $this->__extractTokens();
  172. $this->__buildFiles();
  173. $this->__writeFiles();
  174. $this->__paths = $this->__files = $this->__storage = array();
  175. $this->__strings = $this->__tokens = array();
  176. $this->out();
  177. $this->out(__d('cake_console', 'Done.'));
  178. }
  179. /**
  180. * Get & configure the option parser
  181. *
  182. * @return void
  183. */
  184. public function getOptionParser() {
  185. $parser = parent::getOptionParser();
  186. return $parser->description(__d('cake_console', 'CakePHP Language String Extraction:'))
  187. ->addOption('app', array('help' => __d('cake_console', 'Directory where your application is located.')))
  188. ->addOption('paths', array('help' => __d('cake_console', 'Comma separted list of paths.')))
  189. ->addOption('merge', array(
  190. 'help' => __d('cake_console', 'Merge all domain strings into the default.po file.'),
  191. 'choices' => array('yes', 'no')
  192. ))
  193. ->addOption('output', array('help' => __d('cake_console', 'Full path to output directory.')))
  194. ->addOption('files', array('help' => __d('cake_console', 'Comma separated list of files.')))
  195. ->addOption('exclude', array(
  196. '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')
  197. ));
  198. }
  199. /**
  200. * Show help options
  201. *
  202. * @return void
  203. */
  204. public function help() {
  205. $this->out(__d('cake_console', 'CakePHP Language String Extraction:'));
  206. $this->hr();
  207. $this->out(__d('cake_console', 'The Extract script generates .pot file(s) with translations'));
  208. $this->out(__d('cake_console', 'By default the .pot file(s) will be place in the locale directory of -app'));
  209. $this->out(__d('cake_console', 'By default -app is ROOT/app'));
  210. $this->hr();
  211. $this->out(__d('cake_console', 'Usage: cake i18n extract <command> <param1> <param2>...'));
  212. $this->out();
  213. $this->out(__d('cake_console', 'Params:'));
  214. $this->out(__d('cake_console', ' -app [path...]: directory where your application is located'));
  215. $this->out(__d('cake_console', ' -root [path...]: path to install'));
  216. $this->out(__d('cake_console', ' -core [path...]: path to cake directory'));
  217. $this->out(__d('cake_console', ' -paths [comma separated list of paths]'));
  218. $this->out(__d('cake_console', ' -merge [yes|no]: Merge all domains strings into the default.pot file'));
  219. $this->out(__d('cake_console', ' -output [path...]: Full path to output directory'));
  220. $this->out(__d('cake_console', ' -files: [comma separated list of files]'));
  221. $this->out();
  222. $this->out(__d('cake_console', 'Commands:'));
  223. $this->out(__d('cake_console', ' cake i18n extract help: Shows this help message.'));
  224. $this->out();
  225. }
  226. /**
  227. * Extract tokens out of all files to be processed
  228. *
  229. * @return void
  230. * @access private
  231. */
  232. function __extractTokens() {
  233. foreach ($this->__files as $file) {
  234. $this->__file = $file;
  235. $this->out(__d('cake_console', 'Processing %s...', $file));
  236. $code = file_get_contents($file);
  237. $allTokens = token_get_all($code);
  238. $this->__tokens = array();
  239. $lineNumber = 1;
  240. foreach ($allTokens as $token) {
  241. if ((!is_array($token)) || (($token[0] != T_WHITESPACE) && ($token[0] != T_INLINE_HTML))) {
  242. if (is_array($token)) {
  243. $token[] = $lineNumber;
  244. }
  245. $this->__tokens[] = $token;
  246. }
  247. if (is_array($token)) {
  248. $lineNumber += count(explode("\n", $token[1])) - 1;
  249. } else {
  250. $lineNumber += count(explode("\n", $token)) - 1;
  251. }
  252. }
  253. unset($allTokens);
  254. $this->__parse('__', array('singular'));
  255. $this->__parse('__n', array('singular', 'plural'));
  256. $this->__parse('__d', array('domain', 'singular'));
  257. $this->__parse('__c', array('singular'));
  258. $this->__parse('__dc', array('domain', 'singular'));
  259. $this->__parse('__dn', array('domain', 'singular', 'plural'));
  260. $this->__parse('__dcn', array('domain', 'singular', 'plural'));
  261. }
  262. }
  263. /**
  264. * Parse tokens
  265. *
  266. * @param string $functionName Function name that indicates translatable string (e.g: '__')
  267. * @param array $map Array containing what variables it will find (e.g: domain, singular, plural)
  268. * @return void
  269. * @access private
  270. */
  271. function __parse($functionName, $map) {
  272. $count = 0;
  273. $tokenCount = count($this->__tokens);
  274. while (($tokenCount - $count) > 1) {
  275. list($countToken, $firstParenthesis) = array($this->__tokens[$count], $this->__tokens[$count + 1]);
  276. if (!is_array($countToken)) {
  277. $count++;
  278. continue;
  279. }
  280. list($type, $string, $line) = $countToken;
  281. if (($type == T_STRING) && ($string == $functionName) && ($firstParenthesis == '(')) {
  282. $position = $count;
  283. $depth = 0;
  284. while ($depth == 0) {
  285. if ($this->__tokens[$position] == '(') {
  286. $depth++;
  287. } elseif ($this->__tokens[$position] == ')') {
  288. $depth--;
  289. }
  290. $position++;
  291. }
  292. $mapCount = count($map);
  293. $strings = $this->__getStrings($position, $mapCount);
  294. if ($mapCount == count($strings)) {
  295. extract(array_combine($map, $strings));
  296. $domain = isset($domain) ? $domain : 'default';
  297. $string = isset($plural) ? $singular . "\0" . $plural : $singular;
  298. $this->__strings[$domain][$string][$this->__file][] = $line;
  299. } else {
  300. $this->__markerError($this->__file, $line, $functionName, $count);
  301. }
  302. }
  303. $count++;
  304. }
  305. }
  306. /**
  307. * Build the translate template file contents out of obtained strings
  308. *
  309. * @return void
  310. * @access private
  311. */
  312. function __buildFiles() {
  313. foreach ($this->__strings as $domain => $strings) {
  314. foreach ($strings as $string => $files) {
  315. $occurrences = array();
  316. foreach ($files as $file => $lines) {
  317. $occurrences[] = $file . ':' . implode(';', $lines);
  318. }
  319. $occurrences = implode("\n#: ", $occurrences);
  320. $header = '#: ' . str_replace($this->__paths, '', $occurrences) . "\n";
  321. if (strpos($string, "\0") === false) {
  322. $sentence = "msgid \"{$string}\"\n";
  323. $sentence .= "msgstr \"\"\n\n";
  324. } else {
  325. list($singular, $plural) = explode("\0", $string);
  326. $sentence = "msgid \"{$singular}\"\n";
  327. $sentence .= "msgid_plural \"{$plural}\"\n";
  328. $sentence .= "msgstr[0] \"\"\n";
  329. $sentence .= "msgstr[1] \"\"\n\n";
  330. }
  331. $this->__store($domain, $header, $sentence);
  332. if ($domain != 'default' && $this->__merge) {
  333. $this->__store('default', $header, $sentence);
  334. }
  335. }
  336. }
  337. }
  338. /**
  339. * Prepare a file to be stored
  340. *
  341. * @return void
  342. * @access private
  343. */
  344. function __store($domain, $header, $sentence) {
  345. if (!isset($this->__storage[$domain])) {
  346. $this->__storage[$domain] = array();
  347. }
  348. if (!isset($this->__storage[$domain][$sentence])) {
  349. $this->__storage[$domain][$sentence] = $header;
  350. } else {
  351. $this->__storage[$domain][$sentence] .= $header;
  352. }
  353. }
  354. /**
  355. * Write the files that need to be stored
  356. *
  357. * @return void
  358. * @access private
  359. */
  360. function __writeFiles() {
  361. $overwriteAll = false;
  362. foreach ($this->__storage as $domain => $sentences) {
  363. $output = $this->__writeHeader();
  364. foreach ($sentences as $sentence => $header) {
  365. $output .= $header . $sentence;
  366. }
  367. $filename = $domain . '.pot';
  368. $File = new File($this->__output . $filename);
  369. $response = '';
  370. while ($overwriteAll === false && $File->exists() && strtoupper($response) !== 'Y') {
  371. $this->out();
  372. $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');
  373. if (strtoupper($response) === 'N') {
  374. $response = '';
  375. while ($response == '') {
  376. $response = $this->in(__d('cake_console', "What would you like to name this file?"), null, 'new_' . $filename);
  377. $File = new File($this->__output . $response);
  378. $filename = $response;
  379. }
  380. } elseif (strtoupper($response) === 'A') {
  381. $overwriteAll = true;
  382. }
  383. }
  384. $File->write($output);
  385. $File->close();
  386. }
  387. }
  388. /**
  389. * Build the translation template header
  390. *
  391. * @return string Translation template header
  392. * @access private
  393. */
  394. function __writeHeader() {
  395. $output = "# LANGUAGE translation of CakePHP Application\n";
  396. $output .= "# Copyright YEAR NAME <EMAIL@ADDRESS>\n";
  397. $output .= "#\n";
  398. $output .= "#, fuzzy\n";
  399. $output .= "msgid \"\"\n";
  400. $output .= "msgstr \"\"\n";
  401. $output .= "\"Project-Id-Version: PROJECT VERSION\\n\"\n";
  402. $output .= "\"POT-Creation-Date: " . date("Y-m-d H:iO") . "\\n\"\n";
  403. $output .= "\"PO-Revision-Date: YYYY-mm-DD HH:MM+ZZZZ\\n\"\n";
  404. $output .= "\"Last-Translator: NAME <EMAIL@ADDRESS>\\n\"\n";
  405. $output .= "\"Language-Team: LANGUAGE <EMAIL@ADDRESS>\\n\"\n";
  406. $output .= "\"MIME-Version: 1.0\\n\"\n";
  407. $output .= "\"Content-Type: text/plain; charset=utf-8\\n\"\n";
  408. $output .= "\"Content-Transfer-Encoding: 8bit\\n\"\n";
  409. $output .= "\"Plural-Forms: nplurals=INTEGER; plural=EXPRESSION;\\n\"\n\n";
  410. return $output;
  411. }
  412. /**
  413. * Get the strings from the position forward
  414. *
  415. * @param int $position Actual position on tokens array
  416. * @param int $target Number of strings to extract
  417. * @return array Strings extracted
  418. * @access private
  419. */
  420. function __getStrings(&$position, $target) {
  421. $strings = array();
  422. while (count($strings) < $target && ($this->__tokens[$position] == ',' || $this->__tokens[$position][0] == T_CONSTANT_ENCAPSED_STRING)) {
  423. if ($this->__tokens[$position][0] == T_CONSTANT_ENCAPSED_STRING && $this->__tokens[$position+1] == '.') {
  424. $string = '';
  425. while ($this->__tokens[$position][0] == T_CONSTANT_ENCAPSED_STRING || $this->__tokens[$position] == '.') {
  426. if ($this->__tokens[$position][0] == T_CONSTANT_ENCAPSED_STRING) {
  427. $string .= $this->__formatString($this->__tokens[$position][1]);
  428. }
  429. $position++;
  430. }
  431. $strings[] = $string;
  432. } else if ($this->__tokens[$position][0] == T_CONSTANT_ENCAPSED_STRING) {
  433. $strings[] = $this->__formatString($this->__tokens[$position][1]);
  434. }
  435. $position++;
  436. }
  437. return $strings;
  438. }
  439. /**
  440. * Format a string to be added as a translateable string
  441. *
  442. * @param string $string String to format
  443. * @return string Formatted string
  444. * @access private
  445. */
  446. function __formatString($string) {
  447. $quote = substr($string, 0, 1);
  448. $string = substr($string, 1, -1);
  449. if ($quote == '"') {
  450. $string = stripcslashes($string);
  451. } else {
  452. $string = strtr($string, array("\\'" => "'", "\\\\" => "\\"));
  453. }
  454. $string = str_replace("\r\n", "\n", $string);
  455. return addcslashes($string, "\0..\37\\\"");
  456. }
  457. /**
  458. * Indicate an invalid marker on a processed file
  459. *
  460. * @param string $file File where invalid marker resides
  461. * @param integer $line Line number
  462. * @param string $marker Marker found
  463. * @param integer $count Count
  464. * @return void
  465. * @access private
  466. */
  467. function __markerError($file, $line, $marker, $count) {
  468. $this->out(__d('cake_console', "Invalid marker content in %s:%s\n* %s(", $file, $line, $marker), true);
  469. $count += 2;
  470. $tokenCount = count($this->__tokens);
  471. $parenthesis = 1;
  472. while ((($tokenCount - $count) > 0) && $parenthesis) {
  473. if (is_array($this->__tokens[$count])) {
  474. $this->out($this->__tokens[$count][1], false);
  475. } else {
  476. $this->out($this->__tokens[$count], false);
  477. if ($this->__tokens[$count] == '(') {
  478. $parenthesis++;
  479. }
  480. if ($this->__tokens[$count] == ')') {
  481. $parenthesis--;
  482. }
  483. }
  484. $count++;
  485. }
  486. $this->out("\n", true);
  487. }
  488. /**
  489. * Search files that may contain translateable strings
  490. *
  491. * @return void
  492. * @access private
  493. */
  494. function __searchFiles() {
  495. $pattern = false;
  496. if (!empty($this->_exclude)) {
  497. $pattern = '/[\/\\\\]' . implode('|', $this->_exclude) . '[\/\\\\]/';
  498. }
  499. foreach ($this->__paths as $path) {
  500. $Folder = new Folder($path);
  501. $files = $Folder->findRecursive('.*\.(php|ctp|thtml|inc|tpl)', true);
  502. if (!empty($pattern)) {
  503. foreach ($files as $i => $file) {
  504. if (preg_match($pattern, $file)) {
  505. unset($files[$i]);
  506. }
  507. }
  508. $files = array_values($files);
  509. }
  510. $this->__files = array_merge($this->__files, $files);
  511. }
  512. }
  513. }