3 * Dispatcher takes the URL information, parses it for paramters and
4 * tells the involved controllers what to do.
6 * This is the heart of Cake's operation.
10 * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
11 * Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
13 * Licensed under The MIT License
14 * Redistributions of files must retain the above copyright notice.
16 * @copyright Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
17 * @link http://cakephp.org CakePHP(tm) Project
19 * @subpackage cake.cake
20 * @since CakePHP(tm) v 0.2.9
21 * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
25 * List of helpers to include
27 App
::import('Core', 'Router');
28 App
::import('Controller', 'Controller', false);
31 * Dispatcher translates URLs to controller-action-paramter triads.
33 * Dispatches the request, creating appropriate models and controllers.
36 * @subpackage cake.cake
38 class Dispatcher
extends Object {
65 * the params for this request
75 function __construct($url = null, $base = false) {
76 if ($base !== false) {
77 Configure
::write('App.base', $base);
80 return $this->dispatch($url);
85 * Dispatches and invokes given URL, handing over control to the involved controllers, and then renders the
86 * results (if autoRender is set).
88 * If no controller of given name can be found, invoke() shows error messages in
89 * the form of Missing Controllers information. It does the same with Actions (methods of Controllers are called
92 * @param string $url URL information to work on
93 * @param array $additionalParams Settings array ("bare", "return") which is melded with the GET and POST params
94 * @return boolean Success
97 function dispatch($url = null, $additionalParams = array()) {
98 if ($this->base
=== false) {
99 $this->base
= $this->baseUrl();
102 if (is_array($url)) {
103 $url = $this->__extractParams($url, $additionalParams);
108 $url = $this->getUrl();
109 $this->params
= array_merge($this->parseParams($url), $additionalParams);
111 $this->here
= $this->base
. '/' . $url;
113 if ($this->asset($url) ||
$this->cached($url)) {
116 $controller =& $this->__getController();
118 if (!is_object($controller)) {
119 Router
::setRequestInfo(array($this->params
, array('base' => $this->base
, 'webroot' => $this->webroot
)));
120 return $this->cakeError('missingController', array(array(
121 'className' => Inflector
::camelize($this->params
['controller']) . 'Controller',
122 'webroot' => $this->webroot
,
124 'base' => $this->base
127 $privateAction = $this->params
['action'][0] === '_';
128 $prefixes = Router
::prefixes();
130 if (!empty($prefixes)) {
131 if (isset($this->params
['prefix'])) {
132 $this->params
['action'] = $this->params
['prefix'] . '_' . $this->params
['action'];
133 } elseif (strpos($this->params
['action'], '_') > 0) {
134 list($prefix, $action) = explode('_', $this->params
['action']);
135 $privateAction = in_array($prefix, $prefixes);
139 Router
::setRequestInfo(array(
140 $this->params
, array('base' => $this->base
, 'here' => $this->here
, 'webroot' => $this->webroot
)
143 if ($privateAction) {
144 return $this->cakeError('privateAction', array(array(
145 'className' => Inflector
::camelize($this->params
['controller'] . "Controller"),
146 'action' => $this->params
['action'],
147 'webroot' => $this->webroot
,
149 'base' => $this->base
152 $controller->base
= $this->base
;
153 $controller->here
= $this->here
;
154 $controller->webroot
= $this->webroot
;
155 $controller->plugin
= isset($this->params
['plugin']) ?
$this->params
['plugin'] : null;
156 $controller->params
=& $this->params
;
157 $controller->action
=& $this->params
['action'];
158 $controller->passedArgs
= array_merge($this->params
['pass'], $this->params
['named']);
160 if (!empty($this->params
['data'])) {
161 $controller->data
=& $this->params
['data'];
163 $controller->data
= null;
165 if (isset($this->params
['return']) && $this->params
['return'] == 1) {
166 $controller->autoRender
= false;
168 if (!empty($this->params
['bare'])) {
169 $controller->autoLayout
= false;
171 return $this->_invoke($controller, $this->params
);
175 * Initializes the components and models a controller will be using.
176 * Triggers the controller action, and invokes the rendering if Controller::$autoRender is true and echo's the output.
177 * Otherwise the return value of the controller action are returned.
179 * @param object $controller Controller to invoke
180 * @param array $params Parameters with at least the 'action' to invoke
181 * @param boolean $missingAction Set to true if missing action should be rendered, false otherwise
182 * @return string Output as sent by controller
185 function _invoke(&$controller, $params) {
186 $controller->constructClasses();
187 $controller->startupProcess();
189 $methods = array_flip($controller->methods
);
191 if (!isset($methods[strtolower($params['action'])])) {
192 if ($controller->scaffold
!== false) {
193 App
::import('Controller', 'Scaffold', false);
194 return new Scaffold($controller, $params);
196 return $this->cakeError('missingAction', array(array(
197 'className' => Inflector
::camelize($params['controller']."Controller"),
198 'action' => $params['action'],
199 'webroot' => $this->webroot
,
200 'url' => $this->here
,
201 'base' => $this->base
204 $output = call_user_func_array(array(&$controller, $params['action']), $params['pass']);
206 if ($controller->autoRender
) {
207 $controller->output
= $controller->render();
208 } elseif (empty($controller->output
)) {
209 $controller->output
= $output;
211 $controller->shutdownProcess();
213 if (isset($params['return'])) {
214 return $controller->output
;
216 echo($controller->output
);
220 * Sets the params when $url is passed as an array to Object::requestAction();
221 * Merges the $url and $additionalParams and creates a string url.
223 * @param array $url Array or request parameters
224 * @param array $additionalParams Array of additional parameters.
225 * @return string $url The generated url string.
228 function __extractParams($url, $additionalParams = array()) {
229 $defaults = array('pass' => array(), 'named' => array(), 'form' => array());
230 $params = array_merge($defaults, $url, $additionalParams);
231 $this->params
= $params;
233 $params +
= array('base' => false, 'url' => array());
234 return ltrim(Router
::reverse($params), '/');
238 * Returns array of GET and POST parameters. GET parameters are taken from given URL.
240 * @param string $fromUrl URL to mine for parameter information.
241 * @return array Parameters found in POST and GET.
244 function parseParams($fromUrl) {
248 $params['form'] = $_POST;
249 if (ini_get('magic_quotes_gpc') === '1') {
250 $params['form'] = stripslashes_deep($params['form']);
252 if (env('HTTP_X_HTTP_METHOD_OVERRIDE')) {
253 $params['form']['_method'] = env('HTTP_X_HTTP_METHOD_OVERRIDE');
255 if (isset($params['form']['_method'])) {
256 if (!empty($_SERVER)) {
257 $_SERVER['REQUEST_METHOD'] = $params['form']['_method'];
259 $_ENV['REQUEST_METHOD'] = $params['form']['_method'];
261 unset($params['form']['_method']);
264 $namedExpressions = Router
::getNamedExpressions();
265 extract($namedExpressions);
266 include CONFIGS
. 'routes.php';
267 $params = array_merge(array('controller' => '', 'action' => ''), Router
::parse($fromUrl), $params);
269 if (empty($params['action'])) {
270 $params['action'] = 'index';
272 if (isset($params['form']['data'])) {
273 $params['data'] = $params['form']['data'];
274 unset($params['form']['data']);
277 if (ini_get('magic_quotes_gpc') === '1') {
278 $url = stripslashes_deep($_GET);
282 if (isset($params['url'])) {
283 $params['url'] = array_merge($params['url'], $url);
285 $params['url'] = $url;
289 foreach ($_FILES as $name => $data) {
290 if ($name != 'data') {
291 $params['form'][$name] = $data;
295 if (isset($_FILES['data'])) {
296 foreach ($_FILES['data'] as $key => $data) {
297 foreach ($data as $model => $fields) {
298 if (is_array($fields)) {
299 foreach ($fields as $field => $value) {
300 if (is_array($value)) {
301 foreach ($value as $k => $v) {
302 $params['data'][$model][$field][$k][$key] = $v;
305 $params['data'][$model][$field][$key] = $value;
309 $params['data'][$model][$key] = $fields;
318 * Returns a base URL and sets the proper webroot
320 * @return string Base URL
324 $dir = $webroot = null;
325 $config = Configure
::read('App');
331 if ($base !== false) {
332 $this->webroot
= $base . '/';
333 return $this->base
= $base;
336 $replace = array('<', '>', '*', '\'', '"');
337 $base = str_replace($replace, '', dirname(env('PHP_SELF')));
339 if ($webroot === 'webroot' && $webroot === basename($base)) {
340 $base = dirname($base);
342 if ($dir === 'app' && $dir === basename($base)) {
343 $base = dirname($base);
346 if ($base === DS ||
$base === '.') {
350 $this->webroot
= $base .'/';
354 $file = '/' . basename($baseUrl);
355 $base = dirname($baseUrl);
357 if ($base === DS ||
$base === '.') {
360 $this->webroot
= $base . '/';
362 $docRoot = realpath(env('DOCUMENT_ROOT'));
363 $docRootContainsWebroot = strpos($docRoot, $dir . '/' . $webroot);
365 if (!empty($base) ||
!$docRootContainsWebroot) {
366 if (strpos($this->webroot
, $dir) === false) {
367 $this->webroot
.= $dir . '/' ;
369 if (strpos($this->webroot
, $webroot) === false) {
370 $this->webroot
.= $webroot . '/';
373 return $base . $file;
377 * Get controller to use, either plugin controller or application controller
379 * @param array $params Array of parameters
380 * @return mixed name of controller if not loaded, or object if loaded
383 function &__getController() {
385 $ctrlClass = $this->__loadController($this->params
);
389 $ctrlClass .= 'Controller';
390 if (class_exists($ctrlClass)) {
391 $controller =& new $ctrlClass();
397 * Load controller and return controller classname
399 * @param array $params Array of parameters
400 * @return string|bool Name of controller class name
403 function __loadController($params) {
404 $pluginName = $pluginPath = $controller = null;
405 if (!empty($params['plugin'])) {
406 $pluginName = $controller = Inflector
::camelize($params['plugin']);
407 $pluginPath = $pluginName . '.';
409 if (!empty($params['controller'])) {
410 $controller = Inflector
::camelize($params['controller']);
412 if ($pluginPath . $controller) {
413 if (App
::import('Controller', $pluginPath . $controller)) {
421 * Returns the REQUEST_URI from the server environment, or, failing that,
422 * constructs a new one, using the PHP_SELF constant and other variables.
428 foreach (array('HTTP_X_REWRITE_URL', 'REQUEST_URI', 'argv') as $var) {
429 if ($uri = env($var)) {
430 if ($var == 'argv') {
436 $base = preg_replace('/^\//', '', '' . Configure
::read('App.baseUrl'));
439 $uri = preg_replace('/^(?:\/)?(?:' . preg_quote($base, '/') . ')?(?:url=)?/', '', $uri);
441 if (PHP_SAPI
== 'isapi') {
442 $uri = preg_replace('/^(?:\/)?(?:\/)?(?:\?)?(?:url=)?/', '', $uri);
445 if (key($_GET) && strpos(key($_GET), '?') !== false) {
446 unset($_GET[key($_GET)]);
448 $uri = explode('?', $uri, 2);
450 if (isset($uri[1])) {
451 parse_str($uri[1], $_GET);
455 $uri = env('QUERY_STRING');
457 if (is_string($uri) && strpos($uri, 'index.php') !== false) {
458 list(, $uri) = explode('index.php', $uri, 2);
460 if (empty($uri) ||
$uri == '/' ||
$uri == '//') {
463 return str_replace('//', '/', '/' . $uri);
467 * Returns and sets the $_GET[url] derived from the REQUEST_URI
469 * @param string $uri Request URI
470 * @param string $base Base path
474 function getUrl($uri = null, $base = null) {
475 if (empty($_GET['url'])) {
483 $tmpUri = preg_replace('/^(?:\?)?(?:\/)?/', '', $uri);
484 $baseDir = preg_replace('/^\//', '', dirname($base)) . '/';
486 if ($tmpUri === '/' ||
$tmpUri == $baseDir ||
$tmpUri == $base) {
487 $url = $_GET['url'] = '/';
489 if ($base && strpos($uri, $base) === 0) {
490 $elements = explode($base, $uri, 2);
491 } elseif (preg_match('/^[\/\?\/|\/\?|\?\/]/', $uri)) {
492 $elements = array(1 => preg_replace('/^[\/\?\/|\/\?|\?\/]/', '', $uri));
497 if (!empty($elements[1])) {
498 $_GET['url'] = $elements[1];
501 $url = $_GET['url'] = '/';
504 if (strpos($url, '/') === 0 && $url != '/') {
505 $url = $_GET['url'] = substr($url, 1);
512 if ($url{0} == '/') {
513 $url = substr($url, 1);
519 * Outputs cached dispatch view cache
521 * @param string $url Requested URL
524 function cached($url) {
525 if (Configure
::read('Cache.check') === true) {
527 if ($this->here
== '/') {
530 $path = strtolower(Inflector
::slug($path));
532 $filename = CACHE
. 'views' . DS
. $path . '.php';
534 if (!file_exists($filename)) {
535 $filename = CACHE
. 'views' . DS
. $path . '_index.php';
538 if (file_exists($filename)) {
539 if (!class_exists('View')) {
540 App
::import('View', 'View', false);
543 $view =& new View($controller);
544 $return = $view->renderCache($filename, getMicrotime());
546 ClassRegistry
::removeObject('view');
555 * Checks if a requested asset exists and sends it to the browser
557 * @param $url string $url Requested URL
558 * @return boolean True on success if the asset file was found and sent
561 function asset($url) {
562 if (strpos($url, '..') !== false ||
strpos($url, '.') === false) {
565 $filters = Configure
::read('Asset.filter');
567 strpos($url, 'ccss/') === 0 ||
568 preg_match('#^(theme/([^/]+)/ccss/)|(([^/]+)(?<!css)/ccss)/#i', $url)
571 strpos($url, 'cjs/') === 0 ||
572 preg_match('#^/((theme/[^/]+)/cjs/)|(([^/]+)(?<!js)/cjs)/#i', $url)
575 if (($isCss && empty($filters['css'])) ||
($isJs && empty($filters['js']))) {
576 header('HTTP/1.1 404 Not Found');
577 return $this->_stop();
579 include WWW_ROOT
. DS
. $filters['css'];
582 include WWW_ROOT
. DS
. $filters['js'];
586 $ext = array_pop(explode('.', $url));
587 $parts = explode('/', $url);
590 if ($parts[0] === 'theme') {
591 $themeName = $parts[1];
592 unset($parts[0], $parts[1]);
593 $fileFragment = implode(DS
, $parts);
594 $path = App
::themePath($themeName) . 'webroot' . DS
;
595 if (file_exists($path . $fileFragment)) {
596 $assetFile = $path . $fileFragment;
601 $fileFragment = implode(DS
, $parts);
602 $pluginWebroot = App
::pluginPath($plugin) . 'webroot' . DS
;
603 if (file_exists($pluginWebroot . $fileFragment)) {
604 $assetFile = $pluginWebroot . $fileFragment;
608 if ($assetFile !== null) {
609 $this->_deliverAsset($assetFile, $ext);
616 * Sends an asset file to the client
618 * @param string $assetFile Path to the asset file in the file system
619 * @param string $ext The extension of the file to determine its mime type
623 function _deliverAsset($assetFile, $ext) {
624 $ob = @ini_get
("zlib.output_compression") !== '1' && extension_loaded("zlib") && (strpos(env('HTTP_ACCEPT_ENCODING'), 'gzip') !== false);
625 $compressionEnabled = $ob && Configure
::read('Asset.compress');
626 if ($compressionEnabled) {
628 ob_start('ob_gzhandler');
631 App
::import('View', 'Media');
633 $Media = new MediaView($controller);
634 if (isset($Media->mimeType
[$ext])) {
635 $contentType = $Media->mimeType
[$ext];
637 $contentType = 'application/octet-stream';
638 $agent = env('HTTP_USER_AGENT');
639 if (preg_match('%Opera(/| )([0-9].[0-9]{1,2})%', $agent) ||
preg_match('/MSIE ([0-9].[0-9]{1,2})/', $agent)) {
640 $contentType = 'application/octetstream';
644 header("Date: " . date("D, j M Y G:i:s ", filemtime($assetFile)) . 'GMT');
645 header('Content-type: ' . $contentType);
646 header("Expires: " . gmdate("D, j M Y H:i:s", time() + DAY
) . " GMT");
647 header("Cache-Control: cache");
648 header("Pragma: cache");
650 if ($ext === 'css' ||
$ext === 'js') {
653 if ($compressionEnabled) {
656 readfile($assetFile);
659 if ($compressionEnabled) {