PageRenderTime 62ms CodeModel.GetById 33ms RepoModel.GetById 0ms app.codeStats 0ms

/trunk/lib/Cake/Routing/Dispatcher.php

https://github.com/Nervie/Beta
PHP | 331 lines | 190 code | 27 blank | 114 comment | 43 complexity | 26ecb4959b280d30a82bf0202802f89d 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. * Response object used for asset/cached responses.
  42. *
  43. * @var CakeResponse
  44. */
  45. public $response = null;
  46. /**
  47. * Constructor.
  48. */
  49. public function __construct($url = null, $base = false) {
  50. if ($base !== false) {
  51. Configure::write('App.base', $base);
  52. }
  53. if ($url !== null) {
  54. $this->dispatch($url);
  55. }
  56. }
  57. /**
  58. * Dispatches and invokes given Request, handing over control to the involved controller. If the controller is set
  59. * to autoRender, via Controller::$autoRender, then Dispatcher will render the view.
  60. *
  61. * Actions in CakePHP can be any public method on a controller, that is not declared in Controller. If you
  62. * want controller methods to be public and in-accesible by URL, then prefix them with a `_`.
  63. * For example `public function _loadPosts() { }` would not be accessible via URL. Private and protected methods
  64. * are also not accessible via URL.
  65. *
  66. * If no controller of given name can be found, invoke() will throw an exception.
  67. * If the controller is found, and the action is not found an exception will be thrown.
  68. *
  69. * @param CakeRequest $request Request object to dispatch.
  70. * @param CakeResponse $response Response object to put the results of the dispatch into.
  71. * @param array $additionalParams Settings array ("bare", "return") which is melded with the GET and POST params
  72. * @return boolean Success
  73. * @throws MissingControllerException, MissingActionException, PrivateActionException if any of those error states
  74. * are encountered.
  75. */
  76. public function dispatch(CakeRequest $request, CakeResponse $response, $additionalParams = array()) {
  77. if ($this->asset($request->url, $response) || $this->cached($request->here)) {
  78. return;
  79. }
  80. $request = $this->parseParams($request, $additionalParams);
  81. Router::setRequestInfo($request);
  82. $controller = $this->_getController($request, $response);
  83. if (!($controller instanceof Controller)) {
  84. throw new MissingControllerException(array(
  85. 'controller' => Inflector::camelize($request->params['controller']) . 'Controller'
  86. ));
  87. }
  88. return $this->_invoke($controller, $request, $response);
  89. }
  90. /**
  91. * Initializes the components and models a controller will be using.
  92. * Triggers the controller action, and invokes the rendering if Controller::$autoRender is true and echo's the output.
  93. * Otherwise the return value of the controller action are returned.
  94. *
  95. * @param Controller $controller Controller to invoke
  96. * @param CakeRequest $request The request object to invoke the controller for.
  97. * @return string Output as sent by controller
  98. * @throws MissingActionException when the action being called is missing.
  99. */
  100. protected function _invoke(Controller $controller, CakeRequest $request, CakeResponse $response) {
  101. $controller->constructClasses();
  102. $controller->startupProcess();
  103. $render = true;
  104. $result = $controller->invokeAction($request);
  105. if ($result instanceof CakeResponse) {
  106. $render = false;
  107. $response = $result;
  108. }
  109. if ($render && $controller->autoRender) {
  110. $response = $controller->render();
  111. } elseif ($response->body() === null) {
  112. $response->body($result);
  113. }
  114. $controller->shutdownProcess();
  115. if (isset($request->params['return'])) {
  116. return $response->body();
  117. }
  118. $response->send();
  119. }
  120. /**
  121. * Applies Routing and additionalParameters to the request to be dispatched.
  122. * If Routes have not been loaded they will be loaded, and app/Config/routes.php will be run.
  123. *
  124. * @param CakeRequest $request CakeRequest object to mine for parameter information.
  125. * @param array $additionalParams An array of additional parameters to set to the request.
  126. * Useful when Object::requestAction() is involved
  127. * @return CakeRequest The request object with routing params set.
  128. */
  129. public function parseParams(CakeRequest $request, $additionalParams = array()) {
  130. if (count(Router::$routes) == 0) {
  131. $namedExpressions = Router::getNamedExpressions();
  132. extract($namedExpressions);
  133. $this->_loadRoutes();
  134. }
  135. $params = Router::parse($request->url);
  136. $request->addParams($params);
  137. if (!empty($additionalParams)) {
  138. $request->addParams($additionalParams);
  139. }
  140. return $request;
  141. }
  142. /**
  143. * Get controller to use, either plugin controller or application controller
  144. *
  145. * @param CakeRequest $request Request object
  146. * @param CakeResponse $response Response for the controller.
  147. * @return mixed name of controller if not loaded, or object if loaded
  148. */
  149. protected function _getController($request, $response) {
  150. $ctrlClass = $this->_loadController($request);
  151. if (!$ctrlClass) {
  152. return false;
  153. }
  154. return new $ctrlClass($request, $response);
  155. }
  156. /**
  157. * Load controller and return controller classname
  158. *
  159. * @param array $params Array of parameters
  160. * @return string|bool Name of controller class name
  161. */
  162. protected function _loadController($request) {
  163. $pluginName = $pluginPath = $controller = null;
  164. if (!empty($request->params['plugin'])) {
  165. $pluginName = $controller = Inflector::camelize($request->params['plugin']);
  166. $pluginPath = $pluginName . '.';
  167. }
  168. if (!empty($request->params['controller'])) {
  169. $controller = Inflector::camelize($request->params['controller']);
  170. }
  171. if ($pluginPath . $controller) {
  172. $class = $controller . 'Controller';
  173. App::uses('AppController', 'Controller');
  174. App::uses($pluginName . 'AppController', $pluginPath . 'Controller');
  175. App::uses($class, $pluginPath . 'Controller');
  176. if (class_exists($class)) {
  177. return $class;
  178. }
  179. }
  180. return false;
  181. }
  182. /**
  183. * Loads route configuration
  184. *
  185. * @return void
  186. */
  187. protected function _loadRoutes() {
  188. include APP . 'Config' . DS . 'routes.php';
  189. }
  190. /**
  191. * Outputs cached dispatch view cache
  192. *
  193. * @param string $path Requested URL path
  194. */
  195. public function cached($path) {
  196. if (Configure::read('Cache.check') === true) {
  197. if ($path == '/') {
  198. $path = 'home';
  199. }
  200. $path = strtolower(Inflector::slug($path));
  201. $filename = CACHE . 'views' . DS . $path . '.php';
  202. if (!file_exists($filename)) {
  203. $filename = CACHE . 'views' . DS . $path . '_index.php';
  204. }
  205. if (file_exists($filename)) {
  206. $controller = null;
  207. $view = new View($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. }