PageRenderTime 45ms CodeModel.GetById 19ms RepoModel.GetById 1ms app.codeStats 0ms

/www/cake_1_3/cake/console/libs/tasks/extract.php

https://bitbucket.org/AzuiSleet/cdr-web/
PHP | 494 lines | 326 code | 33 blank | 135 comment | 65 complexity | e06a7a79bc18bd607f9110740de9861d MD5 | raw file
  1. <?php
  2. /**
  3. * Language string extractor
  4. *
  5. * PHP versions 4 and 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
  16. * @subpackage cake.cake.console.libs
  17. * @since CakePHP(tm) v 1.2.0.5012
  18. * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
  19. */
  20. /**
  21. * Language string extractor
  22. *
  23. * @package cake
  24. * @subpackage cake.cake.console.libs.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. var $__paths = array();
  34. /**
  35. * Files from where to extract
  36. *
  37. * @var array
  38. * @access private
  39. */
  40. var $__files = array();
  41. /**
  42. * Merge all domains string into the default.pot file
  43. *
  44. * @var boolean
  45. * @access private
  46. */
  47. var $__merge = false;
  48. /**
  49. * Current file being processed
  50. *
  51. * @var string
  52. * @access private
  53. */
  54. var $__file = null;
  55. /**
  56. * Contains all content waiting to be write
  57. *
  58. * @var string
  59. * @access private
  60. */
  61. var $__storage = array();
  62. /**
  63. * Extracted tokens
  64. *
  65. * @var array
  66. * @access private
  67. */
  68. var $__tokens = array();
  69. /**
  70. * Extracted strings
  71. *
  72. * @var array
  73. * @access private
  74. */
  75. var $__strings = array();
  76. /**
  77. * Destination path
  78. *
  79. * @var string
  80. * @access private
  81. */
  82. var $__output = null;
  83. /**
  84. * Execution method always used for tasks
  85. *
  86. * @return void
  87. * @access private
  88. */
  89. function execute() {
  90. if (isset($this->params['files']) && !is_array($this->params['files'])) {
  91. $this->__files = explode(',', $this->params['files']);
  92. }
  93. if (isset($this->params['paths'])) {
  94. $this->__paths = explode(',', $this->params['paths']);
  95. } else {
  96. $defaultPath = $this->params['working'];
  97. $message = sprintf(__("What is the full path you would like to extract?\nExample: %s\n[Q]uit [D]one", true), $this->params['root'] . DS . 'myapp');
  98. while (true) {
  99. $response = $this->in($message, null, $defaultPath);
  100. if (strtoupper($response) === 'Q') {
  101. $this->out(__('Extract Aborted', true));
  102. $this->_stop();
  103. } elseif (strtoupper($response) === 'D') {
  104. $this->out();
  105. break;
  106. } elseif (is_dir($response)) {
  107. $this->__paths[] = $response;
  108. $defaultPath = 'D';
  109. } else {
  110. $this->err(__('The directory path you supplied was not found. Please try again.', true));
  111. }
  112. $this->out();
  113. }
  114. }
  115. if (isset($this->params['output'])) {
  116. $this->__output = $this->params['output'];
  117. } else {
  118. $message = sprintf(__("What is the full path you would like to output?\nExample: %s\n[Q]uit", true), $this->__paths[0] . DS . 'locale');
  119. while (true) {
  120. $response = $this->in($message, null, $this->__paths[0] . DS . 'locale');
  121. if (strtoupper($response) === 'Q') {
  122. $this->out(__('Extract Aborted', true));
  123. $this->_stop();
  124. } elseif (is_dir($response)) {
  125. $this->__output = $response . DS;
  126. break;
  127. } else {
  128. $this->err(__('The directory path you supplied was not found. Please try again.', true));
  129. }
  130. $this->out();
  131. }
  132. }
  133. if (isset($this->params['merge'])) {
  134. $this->__merge = !(strtolower($this->params['merge']) === 'no');
  135. } else {
  136. $this->out();
  137. $response = $this->in(sprintf(__('Would you like to merge all domains strings into the default.pot file?', true)), array('y', 'n'), 'n');
  138. $this->__merge = strtolower($response) === 'y';
  139. }
  140. if (empty($this->__files)) {
  141. $this->__searchFiles();
  142. }
  143. $this->__extract();
  144. }
  145. /**
  146. * Extract text
  147. *
  148. * @return void
  149. * @access private
  150. */
  151. function __extract() {
  152. $this->out();
  153. $this->out();
  154. $this->out(__('Extracting...', true));
  155. $this->hr();
  156. $this->out(__('Paths:', true));
  157. foreach ($this->__paths as $path) {
  158. $this->out(' ' . $path);
  159. }
  160. $this->out(__('Output Directory: ', true) . $this->__output);
  161. $this->hr();
  162. $this->__extractTokens();
  163. $this->__buildFiles();
  164. $this->__writeFiles();
  165. $this->__paths = $this->__files = $this->__storage = array();
  166. $this->__strings = $this->__tokens = array();
  167. $this->out();
  168. $this->out(__('Done.', true));
  169. }
  170. /**
  171. * Show help options
  172. *
  173. * @return void
  174. * @access public
  175. */
  176. function help() {
  177. $this->out(__('CakePHP Language String Extraction:', true));
  178. $this->hr();
  179. $this->out(__('The Extract script generates .pot file(s) with translations', true));
  180. $this->out(__('By default the .pot file(s) will be place in the locale directory of -app', true));
  181. $this->out(__('By default -app is ROOT/app', true));
  182. $this->hr();
  183. $this->out(__('Usage: cake i18n extract <command> <param1> <param2>...', true));
  184. $this->out();
  185. $this->out(__('Params:', true));
  186. $this->out(__(' -app [path...]: directory where your application is located', true));
  187. $this->out(__(' -root [path...]: path to install', true));
  188. $this->out(__(' -core [path...]: path to cake directory', true));
  189. $this->out(__(' -paths [comma separated list of paths, full path is needed]', true));
  190. $this->out(__(' -merge [yes|no]: Merge all domains strings into the default.pot file', true));
  191. $this->out(__(' -output [path...]: Full path to output directory', true));
  192. $this->out(__(' -files: [comma separated list of files, full path to file is needed]', true));
  193. $this->out();
  194. $this->out(__('Commands:', true));
  195. $this->out(__(' cake i18n extract help: Shows this help message.', true));
  196. $this->out();
  197. }
  198. /**
  199. * Extract tokens out of all files to be processed
  200. *
  201. * @return void
  202. * @access private
  203. */
  204. function __extractTokens() {
  205. foreach ($this->__files as $file) {
  206. $this->__file = $file;
  207. $this->out(sprintf(__('Processing %s...', true), $file));
  208. $code = file_get_contents($file);
  209. $allTokens = token_get_all($code);
  210. $this->__tokens = array();
  211. $lineNumber = 1;
  212. foreach ($allTokens as $token) {
  213. if ((!is_array($token)) || (($token[0] != T_WHITESPACE) && ($token[0] != T_INLINE_HTML))) {
  214. if (is_array($token)) {
  215. $token[] = $lineNumber;
  216. }
  217. $this->__tokens[] = $token;
  218. }
  219. if (is_array($token)) {
  220. $lineNumber += count(explode("\n", $token[1])) - 1;
  221. } else {
  222. $lineNumber += count(explode("\n", $token)) - 1;
  223. }
  224. }
  225. unset($allTokens);
  226. $this->__parse('__', array('singular'));
  227. $this->__parse('__n', array('singular', 'plural'));
  228. $this->__parse('__d', array('domain', 'singular'));
  229. $this->__parse('__c', array('singular'));
  230. $this->__parse('__dc', array('domain', 'singular'));
  231. $this->__parse('__dn', array('domain', 'singular', 'plural'));
  232. $this->__parse('__dcn', array('domain', 'singular', 'plural'));
  233. }
  234. }
  235. /**
  236. * Parse tokens
  237. *
  238. * @param string $functionName Function name that indicates translatable string (e.g: '__')
  239. * @param array $map Array containing what variables it will find (e.g: domain, singular, plural)
  240. * @return void
  241. * @access private
  242. */
  243. function __parse($functionName, $map) {
  244. $count = 0;
  245. $tokenCount = count($this->__tokens);
  246. while (($tokenCount - $count) > 1) {
  247. list($countToken, $firstParenthesis) = array($this->__tokens[$count], $this->__tokens[$count + 1]);
  248. if (!is_array($countToken)) {
  249. $count++;
  250. continue;
  251. }
  252. list($type, $string, $line) = $countToken;
  253. if (($type == T_STRING) && ($string == $functionName) && ($firstParenthesis == '(')) {
  254. $position = $count;
  255. $depth = 0;
  256. while ($depth == 0) {
  257. if ($this->__tokens[$position] == '(') {
  258. $depth++;
  259. } elseif ($this->__tokens[$position] == ')') {
  260. $depth--;
  261. }
  262. $position++;
  263. }
  264. $mapCount = count($map);
  265. $strings = array();
  266. while (count($strings) < $mapCount && ($this->__tokens[$position] == ',' || $this->__tokens[$position][0] == T_CONSTANT_ENCAPSED_STRING)) {
  267. if ($this->__tokens[$position][0] == T_CONSTANT_ENCAPSED_STRING) {
  268. $strings[] = $this->__tokens[$position][1];
  269. }
  270. $position++;
  271. }
  272. if ($mapCount == count($strings)) {
  273. extract(array_combine($map, $strings));
  274. if (!isset($domain)) {
  275. $domain = '\'default\'';
  276. }
  277. $string = $this->__formatString($singular);
  278. if (isset($plural)) {
  279. $string .= "\0" . $this->__formatString($plural);
  280. }
  281. $this->__strings[$this->__formatString($domain)][$string][$this->__file][] = $line;
  282. } else {
  283. $this->__markerError($this->__file, $line, $functionName, $count);
  284. }
  285. }
  286. $count++;
  287. }
  288. }
  289. /**
  290. * Build the translate template file contents out of obtained strings
  291. *
  292. * @return void
  293. * @access private
  294. */
  295. function __buildFiles() {
  296. foreach ($this->__strings as $domain => $strings) {
  297. foreach ($strings as $string => $files) {
  298. $occurrences = array();
  299. foreach ($files as $file => $lines) {
  300. $occurrences[] = $file . ':' . implode(';', $lines);
  301. }
  302. $occurrences = implode("\n#: ", $occurrences);
  303. $header = '#: ' . str_replace($this->__paths, '', $occurrences) . "\n";
  304. if (strpos($string, "\0") === false) {
  305. $sentence = "msgid \"{$string}\"\n";
  306. $sentence .= "msgstr \"\"\n\n";
  307. } else {
  308. list($singular, $plural) = explode("\0", $string);
  309. $sentence = "msgid \"{$singular}\"\n";
  310. $sentence .= "msgid_plural \"{$plural}\"\n";
  311. $sentence .= "msgstr[0] \"\"\n";
  312. $sentence .= "msgstr[1] \"\"\n\n";
  313. }
  314. $this->__store($domain, $header, $sentence);
  315. if ($domain != 'default' && $this->__merge) {
  316. $this->__store('default', $header, $sentence);
  317. }
  318. }
  319. }
  320. }
  321. /**
  322. * Prepare a file to be stored
  323. *
  324. * @return void
  325. * @access private
  326. */
  327. function __store($domain, $header, $sentence) {
  328. if (!isset($this->__storage[$domain])) {
  329. $this->__storage[$domain] = array();
  330. }
  331. if (!isset($this->__storage[$domain][$sentence])) {
  332. $this->__storage[$domain][$sentence] = $header;
  333. } else {
  334. $this->__storage[$domain][$sentence] .= $header;
  335. }
  336. }
  337. /**
  338. * Write the files that need to be stored
  339. *
  340. * @return void
  341. * @access private
  342. */
  343. function __writeFiles() {
  344. $overwriteAll = false;
  345. foreach ($this->__storage as $domain => $sentences) {
  346. $output = $this->__writeHeader();
  347. foreach ($sentences as $sentence => $header) {
  348. $output .= $header . $sentence;
  349. }
  350. $filename = $domain . '.pot';
  351. $File = new File($this->__output . $filename);
  352. $response = '';
  353. while ($overwriteAll === false && $File->exists() && strtoupper($response) !== 'Y') {
  354. $this->out();
  355. $response = $this->in(sprintf(__('Error: %s already exists in this location. Overwrite? [Y]es, [N]o, [A]ll', true), $filename), array('y', 'n', 'a'), 'y');
  356. if (strtoupper($response) === 'N') {
  357. $response = '';
  358. while ($response == '') {
  359. $response = $this->in(sprintf(__("What would you like to name this file?\nExample: %s", true), 'new_' . $filename), null, 'new_' . $filename);
  360. $File = new File($this->__output . $response);
  361. $filename = $response;
  362. }
  363. } elseif (strtoupper($response) === 'A') {
  364. $overwriteAll = true;
  365. }
  366. }
  367. $File->write($output);
  368. $File->close();
  369. }
  370. }
  371. /**
  372. * Build the translation template header
  373. *
  374. * @return string Translation template header
  375. * @access private
  376. */
  377. function __writeHeader() {
  378. $output = "# LANGUAGE translation of CakePHP Application\n";
  379. $output .= "# Copyright YEAR NAME <EMAIL@ADDRESS>\n";
  380. $output .= "#\n";
  381. $output .= "#, fuzzy\n";
  382. $output .= "msgid \"\"\n";
  383. $output .= "msgstr \"\"\n";
  384. $output .= "\"Project-Id-Version: PROJECT VERSION\\n\"\n";
  385. $output .= "\"POT-Creation-Date: " . date("Y-m-d H:iO") . "\\n\"\n";
  386. $output .= "\"PO-Revision-Date: YYYY-mm-DD HH:MM+ZZZZ\\n\"\n";
  387. $output .= "\"Last-Translator: NAME <EMAIL@ADDRESS>\\n\"\n";
  388. $output .= "\"Language-Team: LANGUAGE <EMAIL@ADDRESS>\\n\"\n";
  389. $output .= "\"MIME-Version: 1.0\\n\"\n";
  390. $output .= "\"Content-Type: text/plain; charset=utf-8\\n\"\n";
  391. $output .= "\"Content-Transfer-Encoding: 8bit\\n\"\n";
  392. $output .= "\"Plural-Forms: nplurals=INTEGER; plural=EXPRESSION;\\n\"\n\n";
  393. return $output;
  394. }
  395. /**
  396. * Format a string to be added as a translateable string
  397. *
  398. * @param string $string String to format
  399. * @return string Formatted string
  400. * @access private
  401. */
  402. function __formatString($string) {
  403. $quote = substr($string, 0, 1);
  404. $string = substr($string, 1, -1);
  405. if ($quote == '"') {
  406. $string = stripcslashes($string);
  407. } else {
  408. $string = strtr($string, array("\\'" => "'", "\\\\" => "\\"));
  409. }
  410. $string = str_replace("\r\n", "\n", $string);
  411. return addcslashes($string, "\0..\37\\\"");
  412. }
  413. /**
  414. * Indicate an invalid marker on a processed file
  415. *
  416. * @param string $file File where invalid marker resides
  417. * @param integer $line Line number
  418. * @param string $marker Marker found
  419. * @param integer $count Count
  420. * @return void
  421. * @access private
  422. */
  423. function __markerError($file, $line, $marker, $count) {
  424. $this->out(sprintf(__("Invalid marker content in %s:%s\n* %s(", true), $file, $line, $marker), true);
  425. $count += 2;
  426. $tokenCount = count($this->__tokens);
  427. $parenthesis = 1;
  428. while ((($tokenCount - $count) > 0) && $parenthesis) {
  429. if (is_array($this->__tokens[$count])) {
  430. $this->out($this->__tokens[$count][1], false);
  431. } else {
  432. $this->out($this->__tokens[$count], false);
  433. if ($this->__tokens[$count] == '(') {
  434. $parenthesis++;
  435. }
  436. if ($this->__tokens[$count] == ')') {
  437. $parenthesis--;
  438. }
  439. }
  440. $count++;
  441. }
  442. $this->out("\n", true);
  443. }
  444. /**
  445. * Search files that may contain translateable strings
  446. *
  447. * @return void
  448. * @access private
  449. */
  450. function __searchFiles() {
  451. foreach ($this->__paths as $path) {
  452. $Folder = new Folder($path);
  453. $files = $Folder->findRecursive('.*\.(php|ctp|thtml|inc|tpl)', true);
  454. $this->__files = array_merge($this->__files, $files);
  455. }
  456. }
  457. }