Fix checkRpItemsPosition
[ryzomcore.git] / web / public_php / webtt / cake / dispatcher.php
blobd1e79c4d3c33713897ee128074b856db1a0ff2a1
1 <?php
2 /**
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.
8 * PHP versions 4 and 5
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
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)
24 /**
25 * List of helpers to include
27 App::import('Core', 'Router');
28 App::import('Controller', 'Controller', false);
30 /**
31 * Dispatcher translates URLs to controller-action-paramter triads.
33 * Dispatches the request, creating appropriate models and controllers.
35 * @package cake
36 * @subpackage cake.cake
38 class Dispatcher extends Object {
40 /**
41 * Base URL
43 * @var string
44 * @access public
46 var $base = false;
48 /**
49 * webroot path
51 * @var string
52 * @access public
54 var $webroot = '/';
56 /**
57 * Current URL
59 * @var string
60 * @access public
62 var $here = false;
64 /**
65 * the params for this request
67 * @var string
68 * @access public
70 var $params = null;
72 /**
73 * Constructor.
75 function __construct($url = null, $base = false) {
76 if ($base !== false) {
77 Configure::write('App.base', $base);
79 if ($url !== null) {
80 return $this->dispatch($url);
84 /**
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
90 * Actions).
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
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);
104 } else {
105 if ($url) {
106 $_GET['url'] = $url;
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)) {
114 return;
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,
123 'url' => $url,
124 'base' => $this->base
125 )));
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,
148 'url' => $url,
149 'base' => $this->base
150 )));
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'];
162 } else {
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
183 * @access protected
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
202 )));
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.
226 * @access private
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.
242 * @access public
244 function parseParams($fromUrl) {
245 $params = array();
247 if (isset($_POST)) {
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'];
258 } else {
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']);
276 if (isset($_GET)) {
277 if (ini_get('magic_quotes_gpc') === '1') {
278 $url = stripslashes_deep($_GET);
279 } else {
280 $url = $_GET;
282 if (isset($params['url'])) {
283 $params['url'] = array_merge($params['url'], $url);
284 } else {
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;
304 } else {
305 $params['data'][$model][$field][$key] = $value;
308 } else {
309 $params['data'][$model][$key] = $fields;
314 return $params;
318 * Returns a base URL and sets the proper webroot
320 * @return string Base URL
321 * @access public
323 function baseUrl() {
324 $dir = $webroot = null;
325 $config = Configure::read('App');
326 extract($config);
328 if (!$base) {
329 $base = $this->base;
331 if ($base !== false) {
332 $this->webroot = $base . '/';
333 return $this->base = $base;
335 if (!$baseUrl) {
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 === '.') {
347 $base = '';
350 $this->webroot = $base .'/';
351 return $base;
354 $file = '/' . basename($baseUrl);
355 $base = dirname($baseUrl);
357 if ($base === DS || $base === '.') {
358 $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
381 * @access private
383 function &__getController() {
384 $controller = false;
385 $ctrlClass = $this->__loadController($this->params);
386 if (!$ctrlClass) {
387 return $controller;
389 $ctrlClass .= 'Controller';
390 if (class_exists($ctrlClass)) {
391 $controller =& new $ctrlClass();
393 return $controller;
397 * Load controller and return controller classname
399 * @param array $params Array of parameters
400 * @return string|bool Name of controller class name
401 * @access private
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)) {
414 return $controller;
417 return false;
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.
424 * @return string URI
425 * @access public
427 function uri() {
428 foreach (array('HTTP_X_REWRITE_URL', 'REQUEST_URI', 'argv') as $var) {
429 if ($uri = env($var)) {
430 if ($var == 'argv') {
431 $uri = $uri[0];
433 break;
436 $base = preg_replace('/^\//', '', '' . Configure::read('App.baseUrl'));
438 if ($base) {
439 $uri = preg_replace('/^(?:\/)?(?:' . preg_quote($base, '/') . ')?(?:url=)?/', '', $uri);
441 if (PHP_SAPI == 'isapi') {
442 $uri = preg_replace('/^(?:\/)?(?:\/)?(?:\?)?(?:url=)?/', '', $uri);
444 if (!empty($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);
453 $uri = $uri[0];
454 } else {
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 == '//') {
461 return '';
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
471 * @return string URL
472 * @access public
474 function getUrl($uri = null, $base = null) {
475 if (empty($_GET['url'])) {
476 if ($uri == null) {
477 $uri = $this->uri();
479 if ($base == null) {
480 $base = $this->base;
482 $url = null;
483 $tmpUri = preg_replace('/^(?:\?)?(?:\/)?/', '', $uri);
484 $baseDir = preg_replace('/^\//', '', dirname($base)) . '/';
486 if ($tmpUri === '/' || $tmpUri == $baseDir || $tmpUri == $base) {
487 $url = $_GET['url'] = '/';
488 } else {
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));
493 } else {
494 $elements = array();
497 if (!empty($elements[1])) {
498 $_GET['url'] = $elements[1];
499 $url = $elements[1];
500 } else {
501 $url = $_GET['url'] = '/';
504 if (strpos($url, '/') === 0 && $url != '/') {
505 $url = $_GET['url'] = substr($url, 1);
508 } else {
509 $url = $_GET['url'];
512 if ($url{0} == '/') {
513 $url = substr($url, 1);
515 return $url;
519 * Outputs cached dispatch view cache
521 * @param string $url Requested URL
522 * @access public
524 function cached($url) {
525 if (Configure::read('Cache.check') === true) {
526 $path = $this->here;
527 if ($this->here == '/') {
528 $path = 'home';
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);
542 $controller = null;
543 $view =& new View($controller);
544 $return = $view->renderCache($filename, getMicrotime());
545 if (!$return) {
546 ClassRegistry::removeObject('view');
548 return $return;
551 return false;
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
559 * @access public
561 function asset($url) {
562 if (strpos($url, '..') !== false || strpos($url, '.') === false) {
563 return false;
565 $filters = Configure::read('Asset.filter');
566 $isCss = (
567 strpos($url, 'ccss/') === 0 ||
568 preg_match('#^(theme/([^/]+)/ccss/)|(([^/]+)(?<!css)/ccss)/#i', $url)
570 $isJs = (
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();
578 } elseif ($isCss) {
579 include WWW_ROOT . DS . $filters['css'];
580 $this->_stop();
581 } elseif ($isJs) {
582 include WWW_ROOT . DS . $filters['js'];
583 $this->_stop();
585 $controller = null;
586 $ext = array_pop(explode('.', $url));
587 $parts = explode('/', $url);
588 $assetFile = null;
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;
598 } else {
599 $plugin = $parts[0];
600 unset($parts[0]);
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);
610 return true;
612 return false;
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
620 * @return void
621 * @access protected
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) {
627 ob_start();
628 ob_start('ob_gzhandler');
631 App::import('View', 'Media');
632 $controller = null;
633 $Media = new MediaView($controller);
634 if (isset($Media->mimeType[$ext])) {
635 $contentType = $Media->mimeType[$ext];
636 } else {
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') {
651 include($assetFile);
652 } else {
653 if ($compressionEnabled) {
654 ob_clean();
656 readfile($assetFile);
659 if ($compressionEnabled) {
660 ob_end_flush();