PageRenderTime 50ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/Cake/Routing/Dispatcher.php

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