Dispatcher.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  1. <?php
  2. /**
  3. * Dispatcher takes the URL information, parses it for parameters and
  4. * tells the involved controllers what to do.
  5. *
  6. * This is the heart of Cake's operation.
  7. *
  8. * PHP 5
  9. *
  10. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  11. * Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
  12. *
  13. * Licensed under The MIT License
  14. * Redistributions of files must retain the above copyright notice.
  15. *
  16. * @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
  17. * @link http://cakephp.org CakePHP(tm) Project
  18. * @package Cake.Routing
  19. * @since CakePHP(tm) v 0.2.9
  20. * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
  21. */
  22. /**
  23. * List of helpers to include
  24. */
  25. App::uses('Router', 'Routing');
  26. App::uses('CakeRequest', 'Network');
  27. App::uses('CakeResponse', 'Network');
  28. App::uses('Controller', 'Controller');
  29. App::uses('Scaffold', 'Controller');
  30. App::uses('View', 'View');
  31. App::uses('Debugger', 'Utility');
  32. /**
  33. * Dispatcher converts Requests into controller actions. It uses the dispatched Request
  34. * to locate and load the correct controller. If found, the requested action is called on
  35. * the controller.
  36. *
  37. * @package Cake.Routing
  38. */
  39. class Dispatcher {
  40. /**
  41. * Constructor.
  42. *
  43. * @param string $base The base directory for the application. Writes `App.base` to Configure.
  44. */
  45. public function __construct($base = false) {
  46. if ($base !== false) {
  47. Configure::write('App.base', $base);
  48. }
  49. }
  50. /**
  51. * Dispatches and invokes given Request, handing over control to the involved controller. If the controller is set
  52. * to autoRender, via Controller::$autoRender, then Dispatcher will render the view.
  53. *
  54. * Actions in CakePHP can be any public method on a controller, that is not declared in Controller. If you
  55. * want controller methods to be public and in-accesible by URL, then prefix them with a `_`.
  56. * For example `public function _loadPosts() { }` would not be accessible via URL. Private and protected methods
  57. * are also not accessible via URL.
  58. *
  59. * If no controller of given name can be found, invoke() will throw an exception.
  60. * If the controller is found, and the action is not found an exception will be thrown.
  61. *
  62. * @param CakeRequest $request Request object to dispatch.
  63. * @param CakeResponse $response Response object to put the results of the dispatch into.
  64. * @param array $additionalParams Settings array ("bare", "return") which is melded with the GET and POST params
  65. * @return boolean Success
  66. * @throws MissingControllerException, MissingActionException, PrivateActionException if any of those error states
  67. * are encountered.
  68. */
  69. public function dispatch(CakeRequest $request, CakeResponse $response, $additionalParams = array()) {
  70. if ($this->asset($request->url, $response) || $this->cached($request->here)) {
  71. return;
  72. }
  73. Router::setRequestInfo($request);
  74. $request = $this->parseParams($request, $additionalParams);
  75. $controller = $this->_getController($request, $response);
  76. if (!($controller instanceof Controller)) {
  77. throw new MissingControllerException(array(
  78. 'class' => Inflector::camelize($request->params['controller']) . 'Controller',
  79. 'plugin' => empty($request->params['plugin']) ? null : Inflector::camelize($request->params['plugin'])
  80. ));
  81. }
  82. return $this->_invoke($controller, $request, $response);
  83. }
  84. /**
  85. * Initializes the components and models a controller will be using.
  86. * Triggers the controller action, and invokes the rendering if Controller::$autoRender is true and echo's the output.
  87. * Otherwise the return value of the controller action are returned.
  88. *
  89. * @param Controller $controller Controller to invoke
  90. * @param CakeRequest $request The request object to invoke the controller for.
  91. * @param CakeResponse $response The response object to receive the output
  92. * @return void
  93. */
  94. protected function _invoke(Controller $controller, CakeRequest $request, CakeResponse $response) {
  95. $controller->constructClasses();
  96. $controller->startupProcess();
  97. $render = true;
  98. $result = $controller->invokeAction($request);
  99. if ($result instanceof CakeResponse) {
  100. $render = false;
  101. $response = $result;
  102. }
  103. if ($render && $controller->autoRender) {
  104. $response = $controller->render();
  105. } elseif ($response->body() === null) {
  106. $response->body($result);
  107. }
  108. $controller->shutdownProcess();
  109. if (isset($request->params['return'])) {
  110. return $response->body();
  111. }
  112. $response->send();
  113. }
  114. /**
  115. * Applies Routing and additionalParameters to the request to be dispatched.
  116. * If Routes have not been loaded they will be loaded, and app/Config/routes.php will be run.
  117. *
  118. * @param CakeRequest $request CakeRequest object to mine for parameter information.
  119. * @param array $additionalParams An array of additional parameters to set to the request.
  120. * Useful when Object::requestAction() is involved
  121. * @return CakeRequest The request object with routing params set.
  122. */
  123. public function parseParams(CakeRequest $request, $additionalParams = array()) {
  124. if (count(Router::$routes) == 0) {
  125. $namedExpressions = Router::getNamedExpressions();
  126. extract($namedExpressions);
  127. $this->_loadRoutes();
  128. }
  129. $params = Router::parse($request->url);
  130. $request->addParams($params);
  131. if (!empty($additionalParams)) {
  132. $request->addParams($additionalParams);
  133. }
  134. return $request;
  135. }
  136. /**
  137. * Get controller to use, either plugin controller or application controller
  138. *
  139. * @param CakeRequest $request Request object
  140. * @param CakeResponse $response Response for the controller.
  141. * @return mixed name of controller if not loaded, or object if loaded
  142. */
  143. protected function _getController($request, $response) {
  144. $ctrlClass = $this->_loadController($request);
  145. if (!$ctrlClass) {
  146. return false;
  147. }
  148. $reflection = new ReflectionClass($ctrlClass);
  149. if ($reflection->isAbstract() || $reflection->isInterface()) {
  150. return false;
  151. }
  152. return $reflection->newInstance($request, $response);
  153. }
  154. /**
  155. * Load controller and return controller classname
  156. *
  157. * @param CakeRequest $request
  158. * @return string|bool Name of controller class name
  159. */
  160. protected function _loadController($request) {
  161. $pluginName = $pluginPath = $controller = null;
  162. if (!empty($request->params['plugin'])) {
  163. $pluginName = $controller = Inflector::camelize($request->params['plugin']);
  164. $pluginPath = $pluginName . '.';
  165. }
  166. if (!empty($request->params['controller'])) {
  167. $controller = Inflector::camelize($request->params['controller']);
  168. }
  169. if ($pluginPath . $controller) {
  170. $class = $controller . 'Controller';
  171. App::uses('AppController', 'Controller');
  172. App::uses($pluginName . 'AppController', $pluginPath . 'Controller');
  173. App::uses($class, $pluginPath . 'Controller');
  174. if (class_exists($class)) {
  175. return $class;
  176. }
  177. }
  178. return false;
  179. }
  180. /**
  181. * Loads route configuration
  182. *
  183. * @return void
  184. */
  185. protected function _loadRoutes() {
  186. include APP . 'Config' . DS . 'routes.php';
  187. }
  188. /**
  189. * Outputs cached dispatch view cache
  190. *
  191. * @param string $path Requested URL path
  192. * @return string|boolean False if is not cached or output
  193. */
  194. public function cached($path) {
  195. if (Configure::read('Cache.check') === true) {
  196. if ($path == '/') {
  197. $path = 'home';
  198. }
  199. $path = strtolower(Inflector::slug($path));
  200. $filename = CACHE . 'views' . DS . $path . '.php';
  201. if (!file_exists($filename)) {
  202. $filename = CACHE . 'views' . DS . $path . '_index.php';
  203. }
  204. if (file_exists($filename)) {
  205. App::uses('ThemeView', 'View');
  206. $controller = null;
  207. $view = new ThemeView($controller);
  208. return $view->renderCache($filename, microtime(true));
  209. }
  210. }
  211. return false;
  212. }
  213. /**
  214. * Checks if a requested asset exists and sends it to the browser
  215. *
  216. * @param string $url Requested URL
  217. * @param CakeResponse $response The response object to put the file contents in.
  218. * @return boolean True on success if the asset file was found and sent
  219. */
  220. public function asset($url, CakeResponse $response) {
  221. if (strpos($url, '..') !== false || strpos($url, '.') === false) {
  222. return false;
  223. }
  224. $filters = Configure::read('Asset.filter');
  225. $isCss = (
  226. strpos($url, 'ccss/') === 0 ||
  227. preg_match('#^(theme/([^/]+)/ccss/)|(([^/]+)(?<!css)/ccss)/#i', $url)
  228. );
  229. $isJs = (
  230. strpos($url, 'cjs/') === 0 ||
  231. preg_match('#^/((theme/[^/]+)/cjs/)|(([^/]+)(?<!js)/cjs)/#i', $url)
  232. );
  233. if (($isCss && empty($filters['css'])) || ($isJs && empty($filters['js']))) {
  234. $response->statusCode(404);
  235. $response->send();
  236. return true;
  237. } elseif ($isCss) {
  238. include WWW_ROOT . DS . $filters['css'];
  239. return true;
  240. } elseif ($isJs) {
  241. include WWW_ROOT . DS . $filters['js'];
  242. return true;
  243. }
  244. $pathSegments = explode('.', $url);
  245. $ext = array_pop($pathSegments);
  246. $parts = explode('/', $url);
  247. $assetFile = null;
  248. if ($parts[0] === 'theme') {
  249. $themeName = $parts[1];
  250. unset($parts[0], $parts[1]);
  251. $fileFragment = implode(DS, $parts);
  252. $path = App::themePath($themeName) . 'webroot' . DS;
  253. if (file_exists($path . $fileFragment)) {
  254. $assetFile = $path . $fileFragment;
  255. }
  256. } else {
  257. $plugin = Inflector::camelize($parts[0]);
  258. if (CakePlugin::loaded($plugin)) {
  259. unset($parts[0]);
  260. $fileFragment = implode(DS, $parts);
  261. $pluginWebroot = CakePlugin::path($plugin) . 'webroot' . DS;
  262. if (file_exists($pluginWebroot . $fileFragment)) {
  263. $assetFile = $pluginWebroot . $fileFragment;
  264. }
  265. }
  266. }
  267. if ($assetFile !== null) {
  268. $this->_deliverAsset($response, $assetFile, $ext);
  269. return true;
  270. }
  271. return false;
  272. }
  273. /**
  274. * Sends an asset file to the client
  275. *
  276. * @param CakeResponse $response The response object to use.
  277. * @param string $assetFile Path to the asset file in the file system
  278. * @param string $ext The extension of the file to determine its mime type
  279. * @return void
  280. */
  281. protected function _deliverAsset(CakeResponse $response, $assetFile, $ext) {
  282. ob_start();
  283. $compressionEnabled = Configure::read('Asset.compress') && $response->compress();
  284. if ($response->type($ext) == $ext) {
  285. $contentType = 'application/octet-stream';
  286. $agent = env('HTTP_USER_AGENT');
  287. if (preg_match('%Opera(/| )([0-9].[0-9]{1,2})%', $agent) || preg_match('/MSIE ([0-9].[0-9]{1,2})/', $agent)) {
  288. $contentType = 'application/octetstream';
  289. }
  290. $response->type($contentType);
  291. }
  292. $response->cache(filemtime($assetFile));
  293. $response->send();
  294. ob_clean();
  295. if ($ext === 'css' || $ext === 'js') {
  296. include($assetFile);
  297. } else {
  298. readfile($assetFile);
  299. }
  300. if ($compressionEnabled) {
  301. ob_end_flush();
  302. }
  303. }
  304. }