PageRenderTime 56ms CodeModel.GetById 15ms app.highlight 33ms RepoModel.GetById 1ms app.codeStats 0ms

/cake/dispatcher.php

https://github.com/Forbin/cakephp2x
PHP | 713 lines | 490 code | 63 blank | 160 comment | 145 complexity | f9ccee19a03aa40439febf5efa6a9b4d 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 Version 5.x
  9 *
 10 * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
 11 * Copyright 2005-2009, 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-2009, Cake Software Foundation, Inc. (http://cakefoundation.org)
 17 * @link          http://cakephp.org CakePHP(tm) Project
 18 * @package       cake
 19 * @subpackage    cake.cake
 20 * @since         CakePHP(tm) v 0.2.9
 21 * @license       MIT License (http://www.opensource.org/licenses/mit-license.php)
 22 */
 23
 24/**
 25 * List of helpers to include
 26 */
 27App::import('Core', 'Router');
 28Router::init();
 29App::import('Controller', 'Controller', false);
 30
 31/**
 32 * Dispatcher translates URLs to controller-action-paramter triads.
 33 *
 34 * Dispatches the request, creating appropriate models and controllers.
 35 *
 36 * @package       cake
 37 * @subpackage    cake.cake
 38 */
 39class Dispatcher extends Object {
 40
 41/**
 42 * Base URL
 43 *
 44 * @var string
 45 * @access public
 46 */
 47	public $base = false;
 48
 49/**
 50 * webroot path
 51 *
 52 * @var string
 53 * @access public
 54 */
 55	public $webroot = '/';
 56
 57/**
 58 * Current URL
 59 *
 60 * @var string
 61 * @access public
 62 */
 63	public $here = false;
 64
 65/**
 66 * the params for this request
 67 *
 68 * @var string
 69 * @access public
 70 */
 71	public $params = null;
 72
 73/**
 74 * Constructor.
 75 */
 76	public function __construct($url = null, $base = false) {
 77		if ($base !== false) {
 78			Configure::write('App.base', $base);
 79		}
 80		if ($url !== null) {
 81			return $this->dispatch($url);
 82		}
 83	}
 84
 85/**
 86 * Dispatches and invokes given URL, handing over control to the involved controllers, and then renders the results (if autoRender is set).
 87 *
 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
 90 * Actions).
 91 *
 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
 95 * @access public
 96 */
 97	public function dispatch($url = null, $additionalParams = array()) {
 98		if ($this->base === false) {
 99			$this->base = $this->baseUrl();
100		}
101
102		if (is_array($url)) {
103			$url = $this->__extractParams($url, $additionalParams);
104		} else {
105			if ($url) {
106				$_GET['url'] = $url;
107			}
108			$url = $this->getUrl();
109			$this->params = array_merge($this->parseParams($url), $additionalParams);
110		}
111		$this->here = $this->base . '/' . $url;
112
113		if ($this->asset($url) || $this->cached($url)) {
114			$this->_stop();
115		}
116		$controller = $this->__getController();
117
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,
123				'url' => $url,
124				'base' => $this->base
125			)));
126		}
127		$privateAction = $this->params['action'][0] === '_';
128		$prefixes = Router::prefixes();
129
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);
136			}
137		}
138
139		Router::setRequestInfo(array(
140			$this->params, array('base' => $this->base, 'here' => $this->here, 'webroot' => $this->webroot)
141		));
142
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,
148				'url' => $url,
149				'base' => $this->base
150			)));
151		}
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']);
159
160		if (!empty($this->params['data'])) {
161			$controller->data =& $this->params['data'];
162		} else {
163			$controller->data = null;
164		}
165		if (array_key_exists('return', $this->params) && $this->params['return'] == 1) {
166			$controller->autoRender = false;
167		}
168		if (!empty($this->params['bare'])) {
169			$controller->autoLayout = false;
170		}
171		if (array_key_exists('layout', $this->params)) {
172			if (empty($this->params['layout'])) {
173				$controller->autoLayout = false;
174			} else {
175				$controller->layout = $this->params['layout'];
176			}
177		}
178		if (isset($this->params['viewPath'])) {
179			$controller->viewPath = $this->params['viewPath'];
180		}
181		return $this->_invoke($controller, $this->params);
182	}
183
184/**
185 * Invokes given controller's render action if autoRender option is set. Otherwise the
186 * contents of the operation are returned as a string.
187 *
188 * @param object $controller Controller to invoke
189 * @param array $params Parameters with at least the 'action' to invoke
190 * @param boolean $missingAction Set to true if missing action should be rendered, false otherwise
191 * @return string Output as sent by controller
192 * @access protected
193 */
194	protected function _invoke(&$controller, $params) {
195		$controller->constructClasses();
196		$controller->Component->initialize($controller);
197		$controller->beforeFilter();
198		$controller->Component->startup($controller);
199
200		$methods = array_flip($controller->methods);
201
202		if (!isset($methods[strtolower($params['action'])])) {
203			if ($controller->scaffold !== false) {
204				App::import('Controller', 'Scaffold', false);
205				return new Scaffold($controller, $params);
206			}
207			return $this->cakeError('missingAction', array(array(
208				'className' => Inflector::camelize($params['controller']."Controller"),
209				'action' => $params['action'],
210				'webroot' => $this->webroot,
211				'url' => $this->here,
212				'base' => $this->base
213			)));
214		}
215		$output = $controller->dispatchMethod($params['action'], $params['pass']);
216
217		if ($controller->autoRender) {
218			$controller->output = $controller->render();
219		} elseif (empty($controller->output)) {
220			$controller->output = $output;
221		}
222		$controller->Component->shutdown($controller);
223		$controller->afterFilter();
224
225		if (isset($params['return'])) {
226			return $controller->output;
227		}
228		echo($controller->output);
229	}
230
231/**
232 * Sets the params when $url is passed as an array to Object::requestAction();
233 *
234 * @param array $url
235 * @param array $additionalParams
236 * @return string $url
237 * @access private
238 */
239	private function __extractParams($url, $additionalParams = array()) {
240		$defaults = array('pass' => array(), 'named' => array(), 'form' => array());
241		$this->params = array_merge($defaults, $url, $additionalParams);
242		return Router::url($url);
243	}
244
245/**
246 * Returns array of GET and POST parameters. GET parameters are taken from given URL.
247 *
248 * @param string $fromUrl URL to mine for parameter information.
249 * @return array Parameters found in POST and GET.
250 * @access public
251 */
252	public function parseParams($fromUrl) {
253		$params = array();
254
255		if (isset($_POST)) {
256			$params['form'] = $_POST;
257			if (ini_get('magic_quotes_gpc') === '1') {
258				$params['form'] = stripslashes_deep($params['form']);
259			}
260			if (env('HTTP_X_HTTP_METHOD_OVERRIDE')) {
261				$params['form']['_method'] = env('HTTP_X_HTTP_METHOD_OVERRIDE');
262			}
263			if (isset($params['form']['_method'])) {
264				if (!empty($_SERVER)) {
265					$_SERVER['REQUEST_METHOD'] = $params['form']['_method'];
266				} else {
267					$_ENV['REQUEST_METHOD'] = $params['form']['_method'];
268				}
269				unset($params['form']['_method']);
270			}
271		}
272		$namedExpressions = Router::getNamedExpressions();
273		extract($namedExpressions);
274		include CONFIGS . 'routes.php';
275		$params = array_merge(Router::parse($fromUrl), $params);
276
277		if (strlen($params['action']) === 0) {
278			$params['action'] = 'index';
279		}
280		if (isset($params['form']['data'])) {
281			$params['data'] = $params['form']['data'];
282			unset($params['form']['data']);
283		}
284		if (isset($_GET)) {
285			if (ini_get('magic_quotes_gpc') === '1') {
286				$url = stripslashes_deep($_GET);
287			} else {
288				$url = $_GET;
289			}
290			if (isset($params['url'])) {
291				$params['url'] = array_merge($params['url'], $url);
292			} else {
293				$params['url'] = $url;
294			}
295		}
296
297		foreach ($_FILES as $name => $data) {
298			if ($name != 'data') {
299				$params['form'][$name] = $data;
300			}
301		}
302
303		if (isset($_FILES['data'])) {
304			foreach ($_FILES['data'] as $key => $data) {
305				foreach ($data as $model => $fields) {
306					if (is_array($fields)) {
307						foreach ($fields as $field => $value) {
308							if (is_array($value)) {
309								foreach ($value as $k => $v) {
310									$params['data'][$model][$field][$k][$key] = $v;
311								}
312							} else {
313								$params['data'][$model][$field][$key] = $value;
314							}
315						}
316					} else {
317						$params['data'][$model][$key] = $fields;
318					}
319				}
320			}
321		}
322		return $params;
323	}
324
325/**
326 * Returns a base URL and sets the proper webroot
327 *
328 * @return string Base URL
329 * @access public
330 */
331	public function baseUrl() {
332		$dir = $webroot = null;
333		$config = Configure::read('App');
334		extract($config);
335
336		if (!$base) {
337			$base = $this->base;
338		}
339		if ($base !== false) {
340			$this->webroot = $base . '/';
341			return $this->base = $base;
342		}
343		if (!$baseUrl) {
344			$replace = array('<', '>', '*', '\'', '"');
345			$base = str_replace($replace, '', dirname(env('PHP_SELF')));
346
347			if ($webroot === 'webroot' && $webroot === basename($base)) {
348				$base = dirname($base);
349			}
350			if ($dir === 'app' && $dir === basename($base)) {
351				$base = dirname($base);
352			}
353
354			if ($base === DS || $base === '.') {
355				$base = '';
356			}
357
358			$this->webroot = $base .'/';
359			return $base;
360		}
361		$file = '/' . basename($baseUrl);
362		$base = dirname($baseUrl);
363		
364		if ($base === DS || $base === '.') {
365			$base = '';
366		}
367		$this->webroot = $base .'/';
368
369		if (strpos($this->webroot, $dir) === false) {
370			$this->webroot .= $dir . '/' ;
371		}
372		if (strpos($this->webroot, $webroot) === false) {
373			$this->webroot .= $webroot . '/';
374		}
375		return $base . $file;
376	}
377
378/**
379 * Restructure params in case we're serving a plugin.
380 *
381 * @param array $params Array on where to re-set 'controller', 'action', and 'pass' indexes
382 * @param boolean $reverse
383 * @return array Restructured array
384 * @access protected
385 */
386	protected function _restructureParams($params, $reverse = false) {
387		if ($reverse === true) {
388			extract(Router::getArgs($params['action']));
389			$params = array_merge($params, array(
390				'controller' => $params['plugin'],
391				'action' => $params['controller'],
392				'pass' => array_merge($pass, $params['pass']),
393				'named' => array_merge($named, $params['named'])
394			));
395		} else {
396			$params['plugin'] = $params['controller'];
397		}
398		return $params;
399	}
400
401/**
402 * Get controller to use, either plugin controller or application controller
403 *
404 * @param array $params Array of parameters
405 * @return mixed name of controller if not loaded, or object if loaded
406 * @access private
407 */
408	private function __getController() {
409		$original = $params = $this->params;
410
411		$controller = false;
412		$ctrlClass = $this->__loadController($params);
413		if (!$ctrlClass) {
414			if (!isset($params['plugin'])) {
415				$params = $this->_restructureParams($params);
416			} else {
417				$params = $this->_restructureParams($params, true);
418			}
419			$ctrlClass = $this->__loadController($params);
420			if (!$ctrlClass) {
421				$this->params = $original;
422				return $controller;
423			}
424		}
425		$name = $ctrlClass;
426		$ctrlClass .= 'Controller';
427		if (class_exists($ctrlClass)) {
428			if (empty($params['plugin']) && strtolower(get_parent_class($ctrlClass)) === strtolower($name . 'AppController')) {
429				$params = $this->_restructureParams($params);
430			}
431			$this->params = $params;
432			$controller = new $ctrlClass();
433		}
434		return $controller;
435	}
436
437/**
438 * Load controller and return controller class
439 *
440 * @param array $params Array of parameters
441 * @return string|bool Name of controller class name
442 * @access private
443 */
444	private function __loadController($params) {
445		$pluginName = $pluginPath = $controller = null;
446		if (!empty($params['plugin'])) {
447			$pluginName = Inflector::camelize($params['plugin']);
448			$pluginPath = $pluginName . '.';
449			$this->params['controller'] = $params['plugin'];
450			$controller = $pluginName;
451		}
452		if (!empty($params['controller'])) {
453			$this->params['controller'] = $params['controller'];
454			$controller = Inflector::camelize($params['controller']);
455		}
456		if ($pluginPath . $controller) {
457			if (App::import('Controller', $pluginPath . $controller)) {
458				return $controller;
459			}
460		}
461		return false;
462	}
463
464/**
465 * Returns the REQUEST_URI from the server environment, or, failing that,
466 * constructs a new one, using the PHP_SELF constant and other variables.
467 *
468 * @return string URI
469 * @access public
470 */
471	public function uri() {
472		foreach (array('HTTP_X_REWRITE_URL', 'REQUEST_URI', 'argv') as $var) {
473			if ($uri = env($var)) {
474				if ($var == 'argv') {
475					$uri = $uri[0];
476				}
477				break;
478			}
479		}
480		$base = preg_replace('/^\//', '', '' . Configure::read('App.baseUrl'));
481
482		if ($base) {
483			$uri = preg_replace('/^(?:\/)?(?:' . preg_quote($base, '/') . ')?(?:url=)?/', '', $uri);
484		}
485		if (PHP_SAPI == 'isapi') {
486			$uri = preg_replace('/^(?:\/)?(?:\/)?(?:\?)?(?:url=)?/', '', $uri);
487		}
488		if (!empty($uri)) {
489			if (key($_GET) && strpos(key($_GET), '?') !== false) {
490				unset($_GET[key($_GET)]);
491			}
492			$uri = explode('?', $uri, 2);
493
494			if (isset($uri[1])) {
495				parse_str($uri[1], $_GET);
496			}
497			$uri = $uri[0];
498		} else {
499			$uri = env('QUERY_STRING');
500		}
501		if (is_string($uri) && strpos($uri, 'index.php') !== false) {
502			list(, $uri) = explode('index.php', $uri, 2);
503		}
504		if (empty($uri) || $uri == '/' || $uri == '//') {
505			return '';
506		}
507		return str_replace('//', '/', '/' . $uri);
508	}
509
510/**
511 * Returns and sets the $_GET[url] derived from the REQUEST_URI
512 *
513 * @param string $uri Request URI
514 * @param string $base Base path
515 * @return string URL
516 * @access public
517 */
518	public function getUrl($uri = null, $base = null) {
519		if (empty($_GET['url'])) {
520			if ($uri == null) {
521				$uri = $this->uri();
522			}
523			if ($base == null) {
524				$base = $this->base;
525			}
526			$url = null;
527			$tmpUri = preg_replace('/^(?:\?)?(?:\/)?/', '', $uri);
528			$baseDir = preg_replace('/^\//', '', dirname($base)) . '/';
529
530			if ($tmpUri === '/' || $tmpUri == $baseDir || $tmpUri == $base) {
531				$url = $_GET['url'] = '/';
532			} else {
533				if ($base && strpos($uri, $base) !== false) {
534					$elements = explode($base, $uri);
535				} elseif (preg_match('/^[\/\?\/|\/\?|\?\/]/', $uri)) {
536					$elements = array(1 => preg_replace('/^[\/\?\/|\/\?|\?\/]/', '', $uri));
537				} else {
538					$elements = array();
539				}
540
541				if (!empty($elements[1])) {
542					$_GET['url'] = $elements[1];
543					$url = $elements[1];
544				} else {
545					$url = $_GET['url'] = '/';
546				}
547
548				if (strpos($url, '/') === 0 && $url != '/') {
549					$url = $_GET['url'] = substr($url, 1);
550				}
551			}
552		} else {
553			$url = $_GET['url'];
554		}
555		if ($url{0} == '/') {
556			$url = substr($url, 1);
557		}
558		return $url;
559	}
560
561/**
562 * Outputs cached dispatch view cache
563 *
564 * @param string $url Requested URL
565 * @access public
566 */
567	function cached($url) {
568		if (Configure::read('Cache.check') === true) {
569			$path = $this->here;
570			if ($this->here == '/') {
571				$path = 'home';
572			}
573			$path = strtolower(Inflector::slug($path));
574
575			$filename = CACHE . 'views' . DS . $path . '.php';
576
577			if (!file_exists($filename)) {
578				$filename = CACHE . 'views' . DS . $path . '_index.php';
579			}
580
581			if (file_exists($filename)) {
582				if (!class_exists('View')) {
583					App::import('View', 'View', false);
584				}
585				$controller = null;
586				$view = new View($controller);
587				$return = $view->renderCache($filename, getMicrotime());
588				if (!$return) {
589					ClassRegistry::removeObject('view');
590				}
591				return $return;
592			}
593		}
594
595		return false;
596	}
597
598/**
599 * Checks if a requested asset exists and sends it to the browser
600 *
601 * @param $url string $url Requested URL
602 * @return boolean True on success if the asset file was found and sent
603 * @access public
604 */
605	function asset($url) {
606		if (strpos($url, '..') !== false || strpos($url, '.') === false) {
607			return false;
608		}
609
610		if (strpos($url, 'ccss/') === 0) {
611			include WWW_ROOT . DS . Configure::read('Asset.filter.css');
612			$this->_stop();
613		} elseif (strpos($url, 'cjs/') === 0) {
614			include WWW_ROOT . DS . Configure::read('Asset.filter.js');
615			$this->_stop();
616		}
617		$controller = null;
618		$ext = array_pop(explode('.', $url));
619		$pos = 0;
620		$parts = explode('/', $url);
621
622		if ($parts[0] === 'theme') {
623			$pos = strlen($parts[0] . $parts[1]) + 1;
624		} elseif (count($parts) > 2) {
625			$pos = strlen($parts[0]);
626		}
627		$assetFile = null;
628		$paths = array();
629		$matched = false;
630
631		if ($pos > 0) {
632			$plugin = substr($url, 0, $pos);
633			$url = preg_replace('/^' . preg_quote($plugin, '/') . '\//i', '', $url);
634
635			if (strpos($plugin, '/') !== false) {
636				list($plugin, $theme) = explode('/', $plugin);
637				$themePaths = App::path('views');
638
639				foreach ($themePaths as $viewPath) {
640					$path = $viewPath . 'themed' . DS . $theme . DS . 'webroot' . DS;
641					if ($plugin === 'theme' && (is_file($path . $url) && file_exists($path . $url))) {
642						$assetFile = $path . $url;
643						break;
644					}
645				}
646			}
647
648			if ($matched === false) {
649				$paths[] = App::pluginPath($plugin) . 'webroot' . DS;
650			}
651		}
652
653		if ($matched === false) {
654			foreach ($paths as $path) {
655				if (is_file($path . $url) && file_exists($path . $url)) {
656					$assetFile = $path . $url;
657					break;
658				}
659			}
660		}
661
662		if ($assetFile !== null) {
663			$this->_deliverAsset($assetFile, $ext);
664			return true;
665		}
666		return false;
667	}
668
669/**
670 * Sends an asset file to the client
671 *
672 * @param string $assetFile Path to the asset file in the file system
673 * @param string $ext The extension of the file to determine its mime type
674 * @return void
675 * @access protected
676 */
677	function _deliverAsset($assetFile, $ext) {
678		$ob = @ini_get("zlib.output_compression") !== '1' && extension_loaded("zlib") && (strpos(env('HTTP_ACCEPT_ENCODING'), 'gzip') !== false);
679		if ($ob && Configure::read('Asset.compress')) {
680			ob_start();
681			ob_start('ob_gzhandler');
682		}
683
684		App::import('View', 'Media', false);
685		$Media = new MediaView($controller);
686		if (isset($Media->mimeType[$ext])) {
687			$contentType = $Media->mimeType[$ext];
688		} else {
689			$contentType = 'application/octet-stream';
690			$agent = env('HTTP_USER_AGENT');
691			if (preg_match('%Opera(/| )([0-9].[0-9]{1,2})%', $agent) || preg_match('/MSIE ([0-9].[0-9]{1,2})/', $agent)) {
692				$contentType = 'application/octetstream';
693			}
694		}
695
696		header("Date: " . date("D, j M Y G:i:s ", filemtime($assetFile)) . 'GMT');
697		header('Content-type: ' . $contentType);
698		header("Expires: " . gmdate("D, j M Y H:i:s", time() + DAY) . " GMT");
699		header("Cache-Control: cache");
700		header("Pragma: cache");
701
702		if ($ext === 'css' || $ext === 'js') {
703			include($assetFile);
704		} else {
705			readfile($assetFile);
706		}
707
708		if (Configure::read('Asset.compress')) {
709			ob_end_flush();
710		}
711	}
712}
713?>