Base for a static organization website

ShellDispatcher.php 10.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  1. <?php
  2. /**
  3. * ShellDispatcher file
  4. *
  5. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  6. * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  7. *
  8. * Licensed under The MIT License
  9. * For full copyright and license information, please see the LICENSE.txt
  10. * Redistributions of files must retain the above copyright notice.
  11. *
  12. * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  13. * @link http://cakephp.org CakePHP(tm) Project
  14. * @since CakePHP(tm) v 2.0
  15. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  16. */
  17. /**
  18. * Shell dispatcher handles dispatching cli commands.
  19. *
  20. * @package Cake.Console
  21. */
  22. class ShellDispatcher {
  23. /**
  24. * Contains command switches parsed from the command line.
  25. *
  26. * @var array
  27. */
  28. public $params = array();
  29. /**
  30. * Contains arguments parsed from the command line.
  31. *
  32. * @var array
  33. */
  34. public $args = array();
  35. /**
  36. * Constructor
  37. *
  38. * The execution of the script is stopped after dispatching the request with
  39. * a status code of either 0 or 1 according to the result of the dispatch.
  40. *
  41. * @param array $args the argv from PHP
  42. * @param bool $bootstrap Should the environment be bootstrapped.
  43. */
  44. public function __construct($args = array(), $bootstrap = true) {
  45. set_time_limit(0);
  46. $this->parseParams($args);
  47. if ($bootstrap) {
  48. $this->_initConstants();
  49. $this->_initEnvironment();
  50. }
  51. }
  52. /**
  53. * Run the dispatcher
  54. *
  55. * @param array $argv The argv from PHP
  56. * @return void
  57. */
  58. public static function run($argv) {
  59. $dispatcher = new ShellDispatcher($argv);
  60. return $dispatcher->_stop($dispatcher->dispatch() === false ? 1 : 0);
  61. }
  62. /**
  63. * Defines core configuration.
  64. *
  65. * @return void
  66. */
  67. protected function _initConstants() {
  68. if (function_exists('ini_set')) {
  69. ini_set('html_errors', false);
  70. ini_set('implicit_flush', true);
  71. ini_set('max_execution_time', 0);
  72. }
  73. if (!defined('CAKE_CORE_INCLUDE_PATH')) {
  74. define('CAKE_CORE_INCLUDE_PATH', dirname(dirname(dirname(__FILE__))));
  75. define('CAKEPHP_SHELL', true);
  76. if (!defined('DS')) {
  77. define('DS', DIRECTORY_SEPARATOR);
  78. }
  79. if (!defined('CORE_PATH')) {
  80. define('CORE_PATH', CAKE_CORE_INCLUDE_PATH . DS);
  81. }
  82. }
  83. }
  84. /**
  85. * Defines current working environment.
  86. *
  87. * @return void
  88. * @throws CakeException
  89. */
  90. protected function _initEnvironment() {
  91. if (!$this->_bootstrap()) {
  92. $message = "Unable to load CakePHP core.\nMake sure " . DS . 'lib' . DS . 'Cake exists in ' . CAKE_CORE_INCLUDE_PATH;
  93. throw new CakeException($message);
  94. }
  95. if (!isset($this->args[0]) || !isset($this->params['working'])) {
  96. $message = "This file has been loaded incorrectly and cannot continue.\n" .
  97. "Please make sure that " . DS . 'lib' . DS . 'Cake' . DS . "Console is in your system path,\n" .
  98. "and check the cookbook for the correct usage of this command.\n" .
  99. "(http://book.cakephp.org/)";
  100. throw new CakeException($message);
  101. }
  102. $this->shiftArgs();
  103. }
  104. /**
  105. * Initializes the environment and loads the CakePHP core.
  106. *
  107. * @return bool Success.
  108. */
  109. protected function _bootstrap() {
  110. if (!defined('ROOT')) {
  111. define('ROOT', $this->params['root']);
  112. }
  113. if (!defined('APP_DIR')) {
  114. define('APP_DIR', $this->params['app']);
  115. }
  116. if (!defined('APP')) {
  117. define('APP', $this->params['working'] . DS);
  118. }
  119. if (!defined('WWW_ROOT')) {
  120. define('WWW_ROOT', APP . $this->params['webroot'] . DS);
  121. }
  122. if (!defined('TMP') && !is_dir(APP . 'tmp')) {
  123. define('TMP', CAKE_CORE_INCLUDE_PATH . DS . 'Cake' . DS . 'Console' . DS . 'Templates' . DS . 'skel' . DS . 'tmp' . DS);
  124. }
  125. $boot = file_exists(ROOT . DS . APP_DIR . DS . 'Config' . DS . 'bootstrap.php');
  126. require CORE_PATH . 'Cake' . DS . 'bootstrap.php';
  127. if (!file_exists(APP . 'Config' . DS . 'core.php')) {
  128. include_once CAKE_CORE_INCLUDE_PATH . DS . 'Cake' . DS . 'Console' . DS . 'Templates' . DS . 'skel' . DS . 'Config' . DS . 'core.php';
  129. App::build();
  130. }
  131. $this->setErrorHandlers();
  132. if (!defined('FULL_BASE_URL')) {
  133. $url = Configure::read('App.fullBaseUrl');
  134. define('FULL_BASE_URL', $url ? $url : 'http://localhost');
  135. Configure::write('App.fullBaseUrl', FULL_BASE_URL);
  136. }
  137. return true;
  138. }
  139. /**
  140. * Set the error/exception handlers for the console
  141. * based on the `Error.consoleHandler`, and `Exception.consoleHandler` values
  142. * if they are set. If they are not set, the default ConsoleErrorHandler will be
  143. * used.
  144. *
  145. * @return void
  146. */
  147. public function setErrorHandlers() {
  148. App::uses('ConsoleErrorHandler', 'Console');
  149. $error = Configure::read('Error');
  150. $exception = Configure::read('Exception');
  151. $errorHandler = new ConsoleErrorHandler();
  152. if (empty($error['consoleHandler'])) {
  153. $error['consoleHandler'] = array($errorHandler, 'handleError');
  154. Configure::write('Error', $error);
  155. }
  156. if (empty($exception['consoleHandler'])) {
  157. $exception['consoleHandler'] = array($errorHandler, 'handleException');
  158. Configure::write('Exception', $exception);
  159. }
  160. set_exception_handler($exception['consoleHandler']);
  161. set_error_handler($error['consoleHandler'], Configure::read('Error.level'));
  162. App::uses('Debugger', 'Utility');
  163. Debugger::getInstance()->output('txt');
  164. }
  165. /**
  166. * Dispatches a CLI request
  167. *
  168. * @return bool
  169. * @throws MissingShellMethodException
  170. */
  171. public function dispatch() {
  172. $shell = $this->shiftArgs();
  173. if (!$shell) {
  174. $this->help();
  175. return false;
  176. }
  177. if (in_array($shell, array('help', '--help', '-h'))) {
  178. $this->help();
  179. return true;
  180. }
  181. $Shell = $this->_getShell($shell);
  182. $command = null;
  183. if (isset($this->args[0])) {
  184. $command = $this->args[0];
  185. }
  186. if ($Shell instanceof Shell) {
  187. $Shell->initialize();
  188. return $Shell->runCommand($command, $this->args);
  189. }
  190. $methods = array_diff(get_class_methods($Shell), get_class_methods('Shell'));
  191. $added = in_array($command, $methods);
  192. $private = $command[0] === '_' && method_exists($Shell, $command);
  193. if (!$private) {
  194. if ($added) {
  195. $this->shiftArgs();
  196. $Shell->startup();
  197. return $Shell->{$command}();
  198. }
  199. if (method_exists($Shell, 'main')) {
  200. $Shell->startup();
  201. return $Shell->main();
  202. }
  203. }
  204. throw new MissingShellMethodException(array('shell' => $shell, 'method' => $command));
  205. }
  206. /**
  207. * Get shell to use, either plugin shell or application shell
  208. *
  209. * All paths in the loaded shell paths are searched.
  210. *
  211. * @param string $shell Optionally the name of a plugin
  212. * @return mixed An object
  213. * @throws MissingShellException when errors are encountered.
  214. */
  215. protected function _getShell($shell) {
  216. list($plugin, $shell) = pluginSplit($shell, true);
  217. $plugin = Inflector::camelize($plugin);
  218. $class = Inflector::camelize($shell) . 'Shell';
  219. App::uses('Shell', 'Console');
  220. App::uses('AppShell', 'Console/Command');
  221. App::uses($class, $plugin . 'Console/Command');
  222. if (!class_exists($class)) {
  223. $plugin = Inflector::camelize($shell) . '.';
  224. App::uses($class, $plugin . 'Console/Command');
  225. }
  226. if (!class_exists($class)) {
  227. throw new MissingShellException(array(
  228. 'class' => $class
  229. ));
  230. }
  231. $Shell = new $class();
  232. $Shell->plugin = trim($plugin, '.');
  233. return $Shell;
  234. }
  235. /**
  236. * Parses command line options and extracts the directory paths from $params
  237. *
  238. * @param array $args Parameters to parse
  239. * @return void
  240. */
  241. public function parseParams($args) {
  242. $this->_parsePaths($args);
  243. $defaults = array(
  244. 'app' => 'app',
  245. 'root' => dirname(dirname(dirname(dirname(__FILE__)))),
  246. 'working' => null,
  247. 'webroot' => 'webroot'
  248. );
  249. $params = array_merge($defaults, array_intersect_key($this->params, $defaults));
  250. $isWin = false;
  251. foreach ($defaults as $default => $value) {
  252. if (strpos($params[$default], '\\') !== false) {
  253. $isWin = true;
  254. break;
  255. }
  256. }
  257. $params = str_replace('\\', '/', $params);
  258. if (isset($params['working'])) {
  259. $params['working'] = trim($params['working']);
  260. }
  261. if (!empty($params['working']) && (!isset($this->args[0]) || isset($this->args[0]) && $this->args[0][0] !== '.')) {
  262. if ($params['working'][0] === '.') {
  263. $params['working'] = realpath($params['working']);
  264. }
  265. if (empty($this->params['app']) && $params['working'] != $params['root']) {
  266. $params['root'] = dirname($params['working']);
  267. $params['app'] = basename($params['working']);
  268. } else {
  269. $params['root'] = $params['working'];
  270. }
  271. }
  272. if ($params['app'][0] === '/' || preg_match('/([a-z])(:)/i', $params['app'], $matches)) {
  273. $params['root'] = dirname($params['app']);
  274. } elseif (strpos($params['app'], '/')) {
  275. $params['root'] .= '/' . dirname($params['app']);
  276. }
  277. $params['app'] = basename($params['app']);
  278. $params['working'] = rtrim($params['root'], '/');
  279. if (!$isWin || !preg_match('/^[A-Z]:$/i', $params['app'])) {
  280. $params['working'] .= '/' . $params['app'];
  281. }
  282. if (!empty($matches[0]) || !empty($isWin)) {
  283. $params = str_replace('/', '\\', $params);
  284. }
  285. $this->params = $params + $this->params;
  286. }
  287. /**
  288. * Parses out the paths from from the argv
  289. *
  290. * @param array $args The argv to parse.
  291. * @return void
  292. */
  293. protected function _parsePaths($args) {
  294. $parsed = array();
  295. $keys = array('-working', '--working', '-app', '--app', '-root', '--root');
  296. $args = (array)$args;
  297. foreach ($keys as $key) {
  298. while (($index = array_search($key, $args)) !== false) {
  299. $keyname = str_replace('-', '', $key);
  300. $valueIndex = $index + 1;
  301. $parsed[$keyname] = $args[$valueIndex];
  302. array_splice($args, $index, 2);
  303. }
  304. }
  305. $this->args = $args;
  306. $this->params = $parsed;
  307. }
  308. /**
  309. * Removes first argument and shifts other arguments up
  310. *
  311. * @return mixed Null if there are no arguments otherwise the shifted argument
  312. */
  313. public function shiftArgs() {
  314. return array_shift($this->args);
  315. }
  316. /**
  317. * Shows console help. Performs an internal dispatch to the CommandList Shell
  318. *
  319. * @return void
  320. */
  321. public function help() {
  322. $this->args = array_merge(array('command_list'), $this->args);
  323. $this->dispatch();
  324. }
  325. /**
  326. * Stop execution of the current script
  327. *
  328. * @param int|string $status see http://php.net/exit for values
  329. * @return void
  330. */
  331. protected function _stop($status = 0) {
  332. exit($status);
  333. }
  334. }