PageRenderTime 44ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 0ms

/cake/console/cake.php

https://github.com/msadouni/cakephp2x
PHP | 668 lines | 425 code | 62 blank | 181 comment | 68 complexity | b000af1e7eedd409246c1c380c3fba7e MD5 | raw file
  1. #!/usr/bin/php -q
  2. <?php
  3. /**
  4. * Command-line code generation utility to automate programmer chores.
  5. *
  6. * Shell dispatcher class
  7. *
  8. * PHP Version 5.x
  9. *
  10. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  11. * Copyright 2005-2009, Cake Software Foundation, Inc.
  12. *
  13. * Licensed under The MIT License
  14. * Redistributions of files must retain the above copyright notice.
  15. *
  16. * @copyright Copyright 2005-2009, Cake Software Foundation, Inc. (http://cakefoundation.org)
  17. * @link http://cakephp.org CakePHP(tm) Project
  18. * @package cake
  19. * @subpackage cake.cake.console
  20. * @since CakePHP(tm) v 1.2.0.5012
  21. * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
  22. */
  23. if (!defined('E_DEPRECATED')) {
  24. define('E_DEPRECATED', 8192);
  25. }
  26. /**
  27. * Shell dispatcher
  28. *
  29. * @package cake
  30. * @subpackage cake.cake.console
  31. */
  32. class ShellDispatcher {
  33. /**
  34. * Standard input stream.
  35. *
  36. * @var filehandle
  37. * @access public
  38. */
  39. var $stdin;
  40. /**
  41. * Standard output stream.
  42. *
  43. * @var filehandle
  44. * @access public
  45. */
  46. var $stdout;
  47. /**
  48. * Standard error stream.
  49. *
  50. * @var filehandle
  51. * @access public
  52. */
  53. var $stderr;
  54. /**
  55. * Contains command switches parsed from the command line.
  56. *
  57. * @var array
  58. * @access public
  59. */
  60. var $params = array();
  61. /**
  62. * Contains arguments parsed from the command line.
  63. *
  64. * @var array
  65. * @access public
  66. */
  67. var $args = array();
  68. /**
  69. * The file name of the shell that was invoked.
  70. *
  71. * @var string
  72. * @access public
  73. */
  74. var $shell = null;
  75. /**
  76. * The class name of the shell that was invoked.
  77. *
  78. * @var string
  79. * @access public
  80. */
  81. var $shellClass = null;
  82. /**
  83. * The command called if public methods are available.
  84. *
  85. * @var string
  86. * @access public
  87. */
  88. var $shellCommand = null;
  89. /**
  90. * The path locations of shells.
  91. *
  92. * @var array
  93. * @access public
  94. */
  95. var $shellPaths = array();
  96. /**
  97. * The path to the current shell location.
  98. *
  99. * @var string
  100. * @access public
  101. */
  102. var $shellPath = null;
  103. /**
  104. * The name of the shell in camelized.
  105. *
  106. * @var string
  107. * @access public
  108. */
  109. var $shellName = null;
  110. /**
  111. * Constructs this ShellDispatcher instance.
  112. *
  113. * @param array $args the argv.
  114. */
  115. function ShellDispatcher($args = array()) {
  116. $this->__construct($args);
  117. }
  118. /**
  119. * Constructor
  120. *
  121. * The execution of the script is stopped after dispatching the request with
  122. * a status code of either 0 or 1 according to the result of the dispatch.
  123. *
  124. * @param array $args the argv
  125. * @return void
  126. * @access public
  127. */
  128. function __construct($args = array()) {
  129. set_time_limit(0);
  130. $this->__initConstants();
  131. $this->parseParams($args);
  132. $this->_initEnvironment();
  133. $this->__buildPaths();
  134. $this->_stop($this->dispatch() === false ? 1 : 0);
  135. }
  136. /**
  137. * Defines core configuration.
  138. *
  139. * @access private
  140. */
  141. function __initConstants() {
  142. if (function_exists('ini_set')) {
  143. ini_set('display_errors', '1');
  144. ini_set('error_reporting', E_ALL & ~E_DEPRECATED);
  145. ini_set('html_errors', false);
  146. ini_set('implicit_flush', true);
  147. ini_set('max_execution_time', 0);
  148. }
  149. if (!defined('CAKE_CORE_INCLUDE_PATH')) {
  150. define('DS', DIRECTORY_SEPARATOR);
  151. define('CAKE_CORE_INCLUDE_PATH', dirname(dirname(dirname(__FILE__))));
  152. define('CORE_PATH', CAKE_CORE_INCLUDE_PATH . DS);
  153. define('DISABLE_DEFAULT_ERROR_HANDLING', false);
  154. define('CAKEPHP_SHELL', true);
  155. }
  156. require_once(CORE_PATH . 'cake' . DS . 'basics.php');
  157. }
  158. /**
  159. * Defines current working environment.
  160. *
  161. * @access protected
  162. */
  163. function _initEnvironment() {
  164. $this->stdin = fopen('php://stdin', 'r');
  165. $this->stdout = fopen('php://stdout', 'w');
  166. $this->stderr = fopen('php://stderr', 'w');
  167. if (!$this->__bootstrap()) {
  168. $this->stderr("\nCakePHP Console: ");
  169. $this->stderr("\nUnable to load Cake core:");
  170. $this->stderr("\tMake sure " . DS . 'cake' . DS . 'libs exists in ' . CAKE_CORE_INCLUDE_PATH);
  171. $this->_stop();
  172. }
  173. if (!isset($this->args[0]) || !isset($this->params['working'])) {
  174. $this->stderr("\nCakePHP Console: ");
  175. $this->stderr('This file has been loaded incorrectly and cannot continue.');
  176. $this->stderr('Please make sure that ' . DIRECTORY_SEPARATOR . 'cake' . DIRECTORY_SEPARATOR . 'console is in your system path,');
  177. $this->stderr('and check the manual for the correct usage of this command.');
  178. $this->stderr('(http://manual.cakephp.org/)');
  179. $this->_stop();
  180. }
  181. if (basename(__FILE__) != basename($this->args[0])) {
  182. $this->stderr("\nCakePHP Console: ");
  183. $this->stderr('Warning: the dispatcher may have been loaded incorrectly, which could lead to unexpected results...');
  184. if ($this->getInput('Continue anyway?', array('y', 'n'), 'y') == 'n') {
  185. $this->_stop();
  186. }
  187. }
  188. $this->shiftArgs();
  189. }
  190. /**
  191. * Builds the shell paths.
  192. *
  193. * @access private
  194. * @return void
  195. */
  196. function __buildPaths() {
  197. $paths = array();
  198. if (!class_exists('Folder')) {
  199. require LIBS . 'folder.php';
  200. }
  201. $plugins = App::objects('plugin', null, false);
  202. foreach ((array)$plugins as $plugin) {
  203. $pluginPath = App::pluginPath($plugin);
  204. $path = $pluginPath . 'vendors' . DS . 'shells' . DS;
  205. if (file_exists($path)) {
  206. $paths[] = $path;
  207. }
  208. }
  209. $vendorPaths = array_values(App::path('vendors'));
  210. foreach ($vendorPaths as $vendorPath) {
  211. $path = rtrim($vendorPath, DS) . DS . 'shells' . DS;
  212. if (file_exists($path)) {
  213. $paths[] = $path;
  214. }
  215. }
  216. $this->shellPaths = array_values(array_unique(array_merge($paths, App::path('shells'))));
  217. }
  218. /**
  219. * Initializes the environment and loads the Cake core.
  220. *
  221. * @return boolean Success.
  222. * @access private
  223. */
  224. function __bootstrap() {
  225. define('ROOT', $this->params['root']);
  226. define('APP_DIR', $this->params['app']);
  227. define('APP_PATH', $this->params['working'] . DS);
  228. define('WWW_ROOT', APP_PATH . $this->params['webroot'] . DS);
  229. $includes = array(
  230. CORE_PATH . 'cake' . DS . 'config' . DS . 'paths.php',
  231. CORE_PATH . 'cake' . DS . 'libs' . DS . 'object.php',
  232. CORE_PATH . 'cake' . DS . 'libs' . DS . 'inflector.php',
  233. CORE_PATH . 'cake' . DS . 'libs' . DS . 'configure.php',
  234. CORE_PATH . 'cake' . DS . 'libs' . DS . 'file.php',
  235. CORE_PATH . 'cake' . DS . 'libs' . DS . 'cache.php',
  236. CORE_PATH . 'cake' . DS . 'libs' . DS . 'string.php',
  237. CORE_PATH . 'cake' . DS . 'libs' . DS . 'class_registry.php',
  238. CORE_PATH . 'cake' . DS . 'console' . DS . 'error.php'
  239. );
  240. foreach ($includes as $inc) {
  241. if (!require($inc)) {
  242. $this->stderr("Failed to load Cake core file {$inc}");
  243. return false;
  244. }
  245. }
  246. Configure::init(file_exists(CONFIGS . 'bootstrap.php'));
  247. if (!file_exists(APP_PATH . 'config' . DS . 'core.php')) {
  248. include_once CORE_PATH . 'cake' . DS . 'console' . DS . 'templates' . DS . 'skel' . DS . 'config' . DS . 'core.php';
  249. App::build();
  250. }
  251. Configure::write('debug', 1);
  252. return true;
  253. }
  254. /**
  255. * Clear the console
  256. *
  257. * @return void
  258. * @access public
  259. */
  260. function clear() {
  261. if (empty($this->params['noclear'])) {
  262. if ( DS === '/') {
  263. passthru('clear');
  264. } else {
  265. passthru('cls');
  266. }
  267. }
  268. }
  269. /**
  270. * Dispatches a CLI request
  271. *
  272. * @return boolean
  273. * @access public
  274. */
  275. function dispatch() {
  276. $arg = $this->shiftArgs();
  277. if (!$arg) {
  278. $this->help();
  279. return false;
  280. }
  281. if ($arg == 'help') {
  282. $this->help();
  283. return true;
  284. }
  285. list($plugin, $shell) = pluginSplit($arg);
  286. $this->shell = $shell;
  287. $this->shellName = Inflector::camelize($shell);
  288. $this->shellClass = $this->shellName . 'Shell';
  289. $arg = null;
  290. if (isset($this->args[0])) {
  291. $arg = $this->args[0];
  292. $this->shellCommand = Inflector::variable($arg);
  293. }
  294. $Shell = $this->_getShell($plugin);
  295. if (!$Shell) {
  296. $title = sprintf(__('Error: Class %s could not be loaded.', true), $this->shellClass);
  297. $this->stderr($title . "\n");
  298. return false;
  299. }
  300. $methods = array();
  301. if (is_a($Shell, 'Shell')) {
  302. $Shell->initialize();
  303. $Shell->loadTasks();
  304. foreach ($Shell->tasks() as $task) {
  305. if (is_a($Shell->{$task}, 'Shell')) {
  306. $Shell->{$task}->initialize();
  307. $Shell->{$task}->loadTasks();
  308. }
  309. }
  310. $task = Inflector::camelize($arg);
  311. if (in_array($task, $Shell->tasks())) {
  312. $this->shiftArgs();
  313. $Shell->{$task}->startup();
  314. if (isset($this->args[0]) && $this->args[0] == 'help') {
  315. if (method_exists($Shell->{$task}, 'help')) {
  316. $Shell->{$task}->help();
  317. } else {
  318. $this->help();
  319. }
  320. return true;
  321. }
  322. return $Shell->{$task}->execute();
  323. }
  324. $methods = array_diff(get_class_methods('Shell'), array('help'));
  325. }
  326. $methods = array_diff(get_class_methods($Shell), $methods);
  327. $added = in_array(strtolower($arg), array_map('strtolower', $methods));
  328. $private = $arg[0] == '_' && method_exists($Shell, $arg);
  329. if (!$private) {
  330. if ($added) {
  331. $this->shiftArgs();
  332. $Shell->startup();
  333. return $Shell->{$arg}();
  334. }
  335. if (method_exists($Shell, 'main')) {
  336. $Shell->startup();
  337. return $Shell->main();
  338. }
  339. }
  340. $title = sprintf(__('Error: Unknown %1$s command %2$s.', true), $this->shellName, $arg);
  341. $message = sprintf(__('For usage try `cake %s help`', true), $this->shell);
  342. $this->stderr($title . "\n" . $message . "\n");
  343. return false;
  344. }
  345. /**
  346. * Get shell to use, either plugin shell or application shell
  347. *
  348. * All paths in the shellPaths property are searched.
  349. * shell, shellPath and shellClass properties are taken into account.
  350. *
  351. * @param string $plugin Optionally the name of a plugin
  352. * @return mixed False if no shell could be found or an object on success
  353. * @access protected
  354. */
  355. function _getShell($plugin = null) {
  356. foreach ($this->shellPaths as $path) {
  357. $this->shellPath = $path . $this->shell . '.php';
  358. $pluginShellPath = DS . $plugin . DS . 'vendors' . DS . 'shells' . DS;
  359. if ((strpos($path, $pluginShellPath) !== false || !$plugin) && file_exists($this->shellPath)) {
  360. $loaded = true;
  361. break;
  362. }
  363. }
  364. if (!isset($loaded)) {
  365. return false;
  366. }
  367. if (!class_exists('Shell')) {
  368. require CONSOLE_LIBS . 'shell.php';
  369. }
  370. if (!class_exists($this->shellClass)) {
  371. require $this->shellPath;
  372. }
  373. if (!class_exists($this->shellClass)) {
  374. return false;
  375. }
  376. $Shell = new $this->shellClass($this);
  377. return $Shell;
  378. }
  379. /**
  380. * Prompts the user for input, and returns it.
  381. *
  382. * @param string $prompt Prompt text.
  383. * @param mixed $options Array or string of options.
  384. * @param string $default Default input value.
  385. * @return Either the default value, or the user-provided input.
  386. * @access public
  387. */
  388. function getInput($prompt, $options = null, $default = null) {
  389. if (!is_array($options)) {
  390. $printOptions = '';
  391. } else {
  392. $printOptions = '(' . implode('/', $options) . ')';
  393. }
  394. if ($default == null) {
  395. $this->stdout($prompt . " $printOptions \n" . '> ', false);
  396. } else {
  397. $this->stdout($prompt . " $printOptions \n" . "[$default] > ", false);
  398. }
  399. $result = fgets($this->stdin);
  400. if ($result === false) {
  401. exit;
  402. }
  403. $result = trim($result);
  404. if ($default != null && empty($result)) {
  405. return $default;
  406. }
  407. return $result;
  408. }
  409. /**
  410. * Outputs to the stdout filehandle.
  411. *
  412. * @param string $string String to output.
  413. * @param boolean $newline If true, the outputs gets an added newline.
  414. * @return integer Returns the number of bytes output to stdout.
  415. * @access public
  416. */
  417. function stdout($string, $newline = true) {
  418. if ($newline) {
  419. return fwrite($this->stdout, $string . "\n");
  420. } else {
  421. return fwrite($this->stdout, $string);
  422. }
  423. }
  424. /**
  425. * Outputs to the stderr filehandle.
  426. *
  427. * @param string $string Error text to output.
  428. * @access public
  429. */
  430. function stderr($string) {
  431. fwrite($this->stderr, $string);
  432. }
  433. /**
  434. * Parses command line options
  435. *
  436. * @param array $params Parameters to parse
  437. * @access public
  438. */
  439. function parseParams($params) {
  440. $this->__parseParams($params);
  441. $defaults = array('app' => 'app', 'root' => dirname(dirname(dirname(__FILE__))), 'working' => null, 'webroot' => 'webroot');
  442. $params = array_merge($defaults, array_intersect_key($this->params, $defaults));
  443. $isWin = false;
  444. foreach ($defaults as $default => $value) {
  445. if (strpos($params[$default], '\\') !== false) {
  446. $isWin = true;
  447. break;
  448. }
  449. }
  450. $params = str_replace('\\', '/', $params);
  451. if (!empty($params['working']) && (!isset($this->args[0]) || isset($this->args[0]) && $this->args[0]{0} !== '.')) {
  452. if (empty($this->params['app']) && $params['working'] != $params['root']) {
  453. $params['root'] = dirname($params['working']);
  454. $params['app'] = basename($params['working']);
  455. } else {
  456. $params['root'] = $params['working'];
  457. }
  458. }
  459. if ($params['app'][0] == '/' || preg_match('/([a-z])(:)/i', $params['app'], $matches)) {
  460. $params['root'] = dirname($params['app']);
  461. } elseif (strpos($params['app'], '/')) {
  462. $params['root'] .= '/' . dirname($params['app']);
  463. }
  464. $params['app'] = basename($params['app']);
  465. $params['working'] = rtrim($params['root'], '/') . '/' . $params['app'];
  466. if (!empty($matches[0]) || !empty($isWin)) {
  467. $params = str_replace('/', '\\', $params);
  468. }
  469. $this->params = array_merge($this->params, $params);
  470. }
  471. /**
  472. * Helper for recursively parsing params
  473. *
  474. * @return array params
  475. * @access private
  476. */
  477. function __parseParams($params) {
  478. $count = count($params);
  479. for ($i = 0; $i < $count; $i++) {
  480. if (isset($params[$i])) {
  481. if ($params[$i]{0} === '-') {
  482. $key = substr($params[$i], 1);
  483. $this->params[$key] = true;
  484. unset($params[$i]);
  485. if (isset($params[++$i])) {
  486. if ($params[$i]{0} !== '-') {
  487. $this->params[$key] = str_replace('"', '', $params[$i]);
  488. unset($params[$i]);
  489. } else {
  490. $i--;
  491. $this->__parseParams($params);
  492. }
  493. }
  494. } else {
  495. $this->args[] = $params[$i];
  496. unset($params[$i]);
  497. }
  498. }
  499. }
  500. }
  501. /**
  502. * Removes first argument and shifts other arguments up
  503. *
  504. * @return mixed Null if there are no arguments otherwise the shifted argument
  505. * @access public
  506. */
  507. function shiftArgs() {
  508. return array_shift($this->args);
  509. }
  510. /**
  511. * Shows console help
  512. *
  513. * @access public
  514. */
  515. function help() {
  516. $this->clear();
  517. $this->stdout("\nWelcome to CakePHP v" . Configure::version() . " Console");
  518. $this->stdout("---------------------------------------------------------------");
  519. $this->stdout("Current Paths:");
  520. $this->stdout(" -app: ". $this->params['app']);
  521. $this->stdout(" -working: " . rtrim($this->params['working'], DS));
  522. $this->stdout(" -root: " . rtrim($this->params['root'], DS));
  523. $this->stdout(" -core: " . rtrim(CORE_PATH, DS));
  524. $this->stdout("");
  525. $this->stdout("Changing Paths:");
  526. $this->stdout("your working path should be the same as your application path");
  527. $this->stdout("to change your path use the '-app' param.");
  528. $this->stdout("Example: -app relative/path/to/myapp or -app /absolute/path/to/myapp");
  529. $this->stdout("\nAvailable Shells:");
  530. $shellList = array();
  531. foreach ($this->shellPaths as $path) {
  532. if (!is_dir($path)) {
  533. continue;
  534. }
  535. $shells = App::objects('file', $path);
  536. if (empty($shells)) {
  537. continue;
  538. }
  539. if (preg_match('@plugins[\\\/]([^\\\/]*)@', $path, $matches)) {
  540. $type = Inflector::camelize($matches[1]);
  541. } elseif (preg_match('@([^\\\/]*)[\\\/]vendors[\\\/]@', $path, $matches)) {
  542. $type = $matches[1];
  543. } elseif (strpos($path, CAKE_CORE_INCLUDE_PATH . DS . 'cake') === 0) {
  544. $type = 'CORE';
  545. } else {
  546. $type = 'app';
  547. }
  548. foreach ($shells as $shell) {
  549. if ($shell !== 'shell.php') {
  550. $shell = str_replace('.php', '', $shell);
  551. $shellList[$shell][$type] = $type;
  552. }
  553. }
  554. }
  555. if ($shellList) {
  556. ksort($shellList);
  557. if (DS === '/') {
  558. $width = exec('tput cols') - 2;
  559. }
  560. if (empty($width)) {
  561. $width = 80;
  562. }
  563. $columns = max(1, floor($width / 30));
  564. $rows = ceil(count($shellList) / $columns);
  565. foreach($shellList as $shell => $types) {
  566. sort($types);
  567. $shellList[$shell] = str_pad($shell . ' [' . implode ($types, ', ') . ']', $width / $columns);
  568. }
  569. $out = array_chunk($shellList, $rows);
  570. for($i = 0; $i < $rows; $i++) {
  571. $row = '';
  572. for($j = 0; $j < $columns; $j++) {
  573. if (!isset($out[$j][$i])) {
  574. continue;
  575. }
  576. $row .= $out[$j][$i];
  577. }
  578. $this->stdout(" " . $row);
  579. }
  580. }
  581. $this->stdout("\nTo run a command, type 'cake shell_name [args]'");
  582. $this->stdout("To get help on a specific command, type 'cake shell_name help'");
  583. }
  584. /**
  585. * Stop execution of the current script
  586. *
  587. * @param $status see http://php.net/exit for values
  588. * @return void
  589. * @access protected
  590. */
  591. function _stop($status = 0) {
  592. exit($status);
  593. }
  594. }
  595. if (!defined('DISABLE_AUTO_DISPATCH')) {
  596. $dispatcher = new ShellDispatcher($argv);
  597. }
  598. ?>