ExtractTask.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536
  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 full path you would like to extract?\nExample: %s\n[Q]uit [D]one", $defaultPath);
  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 full path you would like to output?\nExample: %s\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, full paths are needed.')))
  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, full paths are needed.')))
  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, full path is needed]'));
  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, full path to file is needed]'));
  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 = array();
  294. while (count($strings) < $mapCount && ($this->__tokens[$position] == ',' || $this->__tokens[$position][0] == T_CONSTANT_ENCAPSED_STRING)) {
  295. if ($this->__tokens[$position][0] == T_CONSTANT_ENCAPSED_STRING) {
  296. $strings[] = $this->__tokens[$position][1];
  297. }
  298. $position++;
  299. }
  300. if ($mapCount == count($strings)) {
  301. extract(array_combine($map, $strings));
  302. if (!isset($domain)) {
  303. $domain = '\'default\'';
  304. }
  305. $string = $this->__formatString($singular);
  306. if (isset($plural)) {
  307. $string .= "\0" . $this->__formatString($plural);
  308. }
  309. $this->__strings[$this->__formatString($domain)][$string][$this->__file][] = $line;
  310. } else {
  311. $this->__markerError($this->__file, $line, $functionName, $count);
  312. }
  313. }
  314. $count++;
  315. }
  316. }
  317. /**
  318. * Build the translate template file contents out of obtained strings
  319. *
  320. * @return void
  321. * @access private
  322. */
  323. function __buildFiles() {
  324. foreach ($this->__strings as $domain => $strings) {
  325. foreach ($strings as $string => $files) {
  326. $occurrences = array();
  327. foreach ($files as $file => $lines) {
  328. $occurrences[] = $file . ':' . implode(';', $lines);
  329. }
  330. $occurrences = implode("\n#: ", $occurrences);
  331. $header = '#: ' . str_replace($this->__paths, '', $occurrences) . "\n";
  332. if (strpos($string, "\0") === false) {
  333. $sentence = "msgid \"{$string}\"\n";
  334. $sentence .= "msgstr \"\"\n\n";
  335. } else {
  336. list($singular, $plural) = explode("\0", $string);
  337. $sentence = "msgid \"{$singular}\"\n";
  338. $sentence .= "msgid_plural \"{$plural}\"\n";
  339. $sentence .= "msgstr[0] \"\"\n";
  340. $sentence .= "msgstr[1] \"\"\n\n";
  341. }
  342. $this->__store($domain, $header, $sentence);
  343. if ($domain != 'default' && $this->__merge) {
  344. $this->__store('default', $header, $sentence);
  345. }
  346. }
  347. }
  348. }
  349. /**
  350. * Prepare a file to be stored
  351. *
  352. * @return void
  353. * @access private
  354. */
  355. function __store($domain, $header, $sentence) {
  356. if (!isset($this->__storage[$domain])) {
  357. $this->__storage[$domain] = array();
  358. }
  359. if (!isset($this->__storage[$domain][$sentence])) {
  360. $this->__storage[$domain][$sentence] = $header;
  361. } else {
  362. $this->__storage[$domain][$sentence] .= $header;
  363. }
  364. }
  365. /**
  366. * Write the files that need to be stored
  367. *
  368. * @return void
  369. * @access private
  370. */
  371. function __writeFiles() {
  372. $overwriteAll = false;
  373. foreach ($this->__storage as $domain => $sentences) {
  374. $output = $this->__writeHeader();
  375. foreach ($sentences as $sentence => $header) {
  376. $output .= $header . $sentence;
  377. }
  378. $filename = $domain . '.pot';
  379. $File = new File($this->__output . $filename);
  380. $response = '';
  381. while ($overwriteAll === false && $File->exists() && strtoupper($response) !== 'Y') {
  382. $this->out();
  383. $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');
  384. if (strtoupper($response) === 'N') {
  385. $response = '';
  386. while ($response == '') {
  387. $response = $this->in(__d('cake_console', "What would you like to name this file?\nExample: %s", 'new_' . $filename), null, 'new_' . $filename);
  388. $File = new File($this->__output . $response);
  389. $filename = $response;
  390. }
  391. } elseif (strtoupper($response) === 'A') {
  392. $overwriteAll = true;
  393. }
  394. }
  395. $File->write($output);
  396. $File->close();
  397. }
  398. }
  399. /**
  400. * Build the translation template header
  401. *
  402. * @return string Translation template header
  403. * @access private
  404. */
  405. function __writeHeader() {
  406. $output = "# LANGUAGE translation of CakePHP Application\n";
  407. $output .= "# Copyright YEAR NAME <EMAIL@ADDRESS>\n";
  408. $output .= "#\n";
  409. $output .= "#, fuzzy\n";
  410. $output .= "msgid \"\"\n";
  411. $output .= "msgstr \"\"\n";
  412. $output .= "\"Project-Id-Version: PROJECT VERSION\\n\"\n";
  413. $output .= "\"POT-Creation-Date: " . date("Y-m-d H:iO") . "\\n\"\n";
  414. $output .= "\"PO-Revision-Date: YYYY-mm-DD HH:MM+ZZZZ\\n\"\n";
  415. $output .= "\"Last-Translator: NAME <EMAIL@ADDRESS>\\n\"\n";
  416. $output .= "\"Language-Team: LANGUAGE <EMAIL@ADDRESS>\\n\"\n";
  417. $output .= "\"MIME-Version: 1.0\\n\"\n";
  418. $output .= "\"Content-Type: text/plain; charset=utf-8\\n\"\n";
  419. $output .= "\"Content-Transfer-Encoding: 8bit\\n\"\n";
  420. $output .= "\"Plural-Forms: nplurals=INTEGER; plural=EXPRESSION;\\n\"\n\n";
  421. return $output;
  422. }
  423. /**
  424. * Format a string to be added as a translateable string
  425. *
  426. * @param string $string String to format
  427. * @return string Formatted string
  428. * @access private
  429. */
  430. function __formatString($string) {
  431. $quote = substr($string, 0, 1);
  432. $string = substr($string, 1, -1);
  433. if ($quote == '"') {
  434. $string = stripcslashes($string);
  435. } else {
  436. $string = strtr($string, array("\\'" => "'", "\\\\" => "\\"));
  437. }
  438. $string = str_replace("\r\n", "\n", $string);
  439. return addcslashes($string, "\0..\37\\\"");
  440. }
  441. /**
  442. * Indicate an invalid marker on a processed file
  443. *
  444. * @param string $file File where invalid marker resides
  445. * @param integer $line Line number
  446. * @param string $marker Marker found
  447. * @param integer $count Count
  448. * @return void
  449. * @access private
  450. */
  451. function __markerError($file, $line, $marker, $count) {
  452. $this->out(__d('cake_console', "Invalid marker content in %s:%s\n* %s(", $file, $line, $marker), true);
  453. $count += 2;
  454. $tokenCount = count($this->__tokens);
  455. $parenthesis = 1;
  456. while ((($tokenCount - $count) > 0) && $parenthesis) {
  457. if (is_array($this->__tokens[$count])) {
  458. $this->out($this->__tokens[$count][1], false);
  459. } else {
  460. $this->out($this->__tokens[$count], false);
  461. if ($this->__tokens[$count] == '(') {
  462. $parenthesis++;
  463. }
  464. if ($this->__tokens[$count] == ')') {
  465. $parenthesis--;
  466. }
  467. }
  468. $count++;
  469. }
  470. $this->out("\n", true);
  471. }
  472. /**
  473. * Search files that may contain translateable strings
  474. *
  475. * @return void
  476. * @access private
  477. */
  478. function __searchFiles() {
  479. $pattern = false;
  480. if (!empty($this->_exclude)) {
  481. $pattern = '/[\/\\\\]' . implode('|', $this->_exclude) . '[\/\\\\]/';
  482. }
  483. foreach ($this->__paths as $path) {
  484. $Folder = new Folder($path);
  485. $files = $Folder->findRecursive('.*\.(php|ctp|thtml|inc|tpl)', true);
  486. if (!empty($pattern)) {
  487. foreach ($files as $i => $file) {
  488. if (preg_match($pattern, $file)) {
  489. unset($files[$i]);
  490. }
  491. }
  492. $files = array_values($files);
  493. }
  494. $this->__files = array_merge($this->__files, $files);
  495. }
  496. }
  497. }