PageRenderTime 47ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/Cake/Routing/Dispatcher.php

https://github.com/gustavor/lore
PHP | 326 lines | 187 code | 27 blank | 112 comment | 42 complexity | 39c121563efe956ec3ed27eb62cddad7 MD5 | raw file
  1. <?php
  2. /**
  3. * Dispatcher takes the URL information, parses it for paramters 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. $request = $this->parseParams($request, $additionalParams);
  74. Router::setRequestInfo($request);
  75. $controller = $this->_getController($request, $response);
  76. if (!($controller instanceof Controller)) {
  77. throw new MissingControllerException(array(
  78. 'controller' => Inflector::camelize($request->params['controller']) . 'Controller'
  79. ));
  80. }
  81. return $this->_invoke($controller, $request, $response);
  82. }
  83. /**
  84. * Initializes the components and models a controller will be using.
  85. * Triggers the controller action, and invokes the rendering if Controller::$autoRender is true and echo's the output.
  86. * Otherwise the return value of the controller action are returned.
  87. *
  88. * @param Controller $controller Controller to invoke
  89. * @param CakeRequest $request The request object to invoke the controller for.
  90. * @param CakeResponse $response The response object to receive the output
  91. * @return void
  92. */
  93. protected function _invoke(Controller $controller, CakeRequest $request, CakeResponse $response) {
  94. $controller->constructClasses();
  95. $controller->startupProcess();
  96. $render = true;
  97. $result = $controller->invokeAction($request);
  98. if ($result instanceof CakeResponse) {
  99. $render = false;
  100. $response = $result;
  101. }
  102. if ($render && $controller->autoRender) {
  103. $response = $controller->render();
  104. } elseif ($response->body() === null) {
  105. $response->body($result);
  106. }
  107. $controller->shutdownProcess();
  108. if (isset($request->params['return'])) {
  109. return $response->body();
  110. }
  111. $response->send();
  112. }
  113. /**
  114. * Applies Routing and additionalParameters to the request to be dispatched.
  115. * If Routes have not been loaded they will be loaded, and app/Config/routes.php will be run.
  116. *
  117. * @param CakeRequest $request CakeRequest object to mine for parameter information.
  118. * @param array $additionalParams An array of additional parameters to set to the request.
  119. * Useful when Object::requestAction() is involved
  120. * @return CakeRequest The request object with routing params set.
  121. */
  122. public function parseParams(CakeRequest $request, $additionalParams = array()) {
  123. if (count(Router::$routes) == 0) {
  124. $namedExpressions = Router::getNamedExpressions();
  125. extract($namedExpressions);
  126. $this->_loadRoutes();
  127. }
  128. $params = Router::parse($request->url);
  129. $request->addParams($params);
  130. if (!empty($additionalParams)) {
  131. $request->addParams($additionalParams);
  132. }
  133. return $request;
  134. }
  135. /**
  136. * Get controller to use, either plugin controller or application controller
  137. *
  138. * @param CakeRequest $request Request object
  139. * @param CakeResponse $response Response for the controller.
  140. * @return mixed name of controller if not loaded, or object if loaded
  141. */
  142. protected function _getController($request, $response) {
  143. $ctrlClass = $this->_loadController($request);
  144. if (!$ctrlClass) {
  145. return false;
  146. }
  147. return new $ctrlClass($request, $response);
  148. }
  149. /**
  150. * Load controller and return controller classname
  151. *
  152. * @param CakeRequest $request
  153. * @return string|bool Name of controller class name
  154. */
  155. protected function _loadController($request) {
  156. $pluginName = $pluginPath = $controller = null;
  157. if (!empty($request->params['plugin'])) {
  158. $pluginName = $controller = Inflector::camelize($request->params['plugin']);
  159. $pluginPath = $pluginName . '.';
  160. }
  161. if (!empty($request->params['controller'])) {
  162. $controller = Inflector::camelize($request->params['controller']);
  163. }
  164. if ($pluginPath . $controller) {
  165. $class = $controller . 'Controller';
  166. App::uses('AppController', 'Controller');
  167. App::uses($pluginName . 'AppController', $pluginPath . 'Controller');
  168. App::uses($class, $pluginPath . 'Controller');
  169. if (class_exists($class)) {
  170. return $class;
  171. }
  172. }
  173. return false;
  174. }
  175. /**
  176. * Loads route configuration
  177. *
  178. * @return void
  179. */
  180. protected function _loadRoutes() {
  181. include APP . 'Config' . DS . 'routes.php';
  182. }
  183. /**
  184. * Outputs cached dispatch view cache
  185. *
  186. * @param string $path Requested URL path
  187. * @return string|boolean False if is not cached or output
  188. */
  189. public function cached($path) {
  190. if (Configure::read('Cache.check') === true) {
  191. if ($path == '/') {
  192. $path = 'home';
  193. }
  194. $path = strtolower(Inflector::slug($path));
  195. $filename = CACHE . 'views' . DS . $path . '.php';
  196. if (!file_exists($filename)) {
  197. $filename = CACHE . 'views' . DS . $path . '_index.php';
  198. }
  199. if (file_exists($filename)) {
  200. App::uses('ThemeView', 'View');
  201. $controller = null;
  202. $view = new ThemeView($controller);
  203. return $view->renderCache($filename, microtime(true));
  204. }
  205. }
  206. return false;
  207. }
  208. /**
  209. * Checks if a requested asset exists and sends it to the browser
  210. *
  211. * @param string $url Requested URL
  212. * @param CakeResponse $response The response object to put the file contents in.
  213. * @return boolean True on success if the asset file was found and sent
  214. */
  215. public function asset($url, CakeResponse $response) {
  216. if (strpos($url, '..') !== false || strpos($url, '.') === false) {
  217. return false;
  218. }
  219. $filters = Configure::read('Asset.filter');
  220. $isCss = (
  221. strpos($url, 'ccss/') === 0 ||
  222. preg_match('#^(theme/([^/]+)/ccss/)|(([^/]+)(?<!css)/ccss)/#i', $url)
  223. );
  224. $isJs = (
  225. strpos($url, 'cjs/') === 0 ||
  226. preg_match('#^/((theme/[^/]+)/cjs/)|(([^/]+)(?<!js)/cjs)/#i', $url)
  227. );
  228. if (($isCss && empty($filters['css'])) || ($isJs && empty($filters['js']))) {
  229. $response->statusCode(404);
  230. $response->send();
  231. return true;
  232. } elseif ($isCss) {
  233. include WWW_ROOT . DS . $filters['css'];
  234. return true;
  235. } elseif ($isJs) {
  236. include WWW_ROOT . DS . $filters['js'];
  237. return true;
  238. }
  239. $pathSegments = explode('.', $url);
  240. $ext = array_pop($pathSegments);
  241. $parts = explode('/', $url);
  242. $assetFile = null;
  243. if ($parts[0] === 'theme') {
  244. $themeName = $parts[1];
  245. unset($parts[0], $parts[1]);
  246. $fileFragment = implode(DS, $parts);
  247. $path = App::themePath($themeName) . 'webroot' . DS;
  248. if (file_exists($path . $fileFragment)) {
  249. $assetFile = $path . $fileFragment;
  250. }
  251. } else {
  252. $plugin = Inflector::camelize($parts[0]);
  253. if (CakePlugin::loaded($plugin)) {
  254. unset($parts[0]);
  255. $fileFragment = implode(DS, $parts);
  256. $pluginWebroot = CakePlugin::path($plugin) . 'webroot' . DS;
  257. if (file_exists($pluginWebroot . $fileFragment)) {
  258. $assetFile = $pluginWebroot . $fileFragment;
  259. }
  260. }
  261. }
  262. if ($assetFile !== null) {
  263. $this->_deliverAsset($response, $assetFile, $ext);
  264. return true;
  265. }
  266. return false;
  267. }
  268. /**
  269. * Sends an asset file to the client
  270. *
  271. * @param CakeResponse $response The response object to use.
  272. * @param string $assetFile Path to the asset file in the file system
  273. * @param string $ext The extension of the file to determine its mime type
  274. * @return void
  275. */
  276. protected function _deliverAsset(CakeResponse $response, $assetFile, $ext) {
  277. ob_start();
  278. $compressionEnabled = Configure::read('Asset.compress') && $response->compress();
  279. if ($response->type($ext) == $ext) {
  280. $contentType = 'application/octet-stream';
  281. $agent = env('HTTP_USER_AGENT');
  282. if (preg_match('%Opera(/| )([0-9].[0-9]{1,2})%', $agent) || preg_match('/MSIE ([0-9].[0-9]{1,2})/', $agent)) {
  283. $contentType = 'application/octetstream';
  284. }
  285. $response->type($contentType);
  286. }
  287. $response->cache(filemtime($assetFile));
  288. $response->send();
  289. ob_clean();
  290. if ($ext === 'css' || $ext === 'js') {
  291. include($assetFile);
  292. } else {
  293. readfile($assetFile);
  294. }
  295. if ($compressionEnabled) {
  296. ob_end_flush();
  297. }
  298. }
  299. }