PageRenderTime 48ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 1ms

/code/ryzom/tools/server/www/webtt/cake/dispatcher.php

https://bitbucket.org/mattraykowski/ryzomcore_demoshard
PHP | 663 lines | 449 code | 59 blank | 155 comment | 134 complexity | 2f16606dae99ab197781483bb2cc613d MD5 | raw file
Possible License(s): AGPL-3.0, GPL-3.0, LGPL-2.1
  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 versions 4 and 5
  9. *
  10. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  11. * Copyright 2005-2010, 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-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)
  22. */
  23. /**
  24. * List of helpers to include
  25. */
  26. App::import('Core', 'Router');
  27. App::import('Controller', 'Controller', false);
  28. /**
  29. * Dispatcher translates URLs to controller-action-paramter triads.
  30. *
  31. * Dispatches the request, creating appropriate models and controllers.
  32. *
  33. * @package cake
  34. * @subpackage cake.cake
  35. */
  36. class Dispatcher extends Object {
  37. /**
  38. * Base URL
  39. *
  40. * @var string
  41. * @access public
  42. */
  43. var $base = false;
  44. /**
  45. * webroot path
  46. *
  47. * @var string
  48. * @access public
  49. */
  50. var $webroot = '/';
  51. /**
  52. * Current URL
  53. *
  54. * @var string
  55. * @access public
  56. */
  57. var $here = false;
  58. /**
  59. * the params for this request
  60. *
  61. * @var string
  62. * @access public
  63. */
  64. var $params = null;
  65. /**
  66. * Constructor.
  67. */
  68. function __construct($url = null, $base = false) {
  69. if ($base !== false) {
  70. Configure::write('App.base', $base);
  71. }
  72. if ($url !== null) {
  73. return $this->dispatch($url);
  74. }
  75. }
  76. /**
  77. * Dispatches and invokes given URL, handing over control to the involved controllers, and then renders the
  78. * results (if autoRender is set).
  79. *
  80. * If no controller of given name can be found, invoke() shows error messages in
  81. * the form of Missing Controllers information. It does the same with Actions (methods of Controllers are called
  82. * Actions).
  83. *
  84. * @param string $url URL information to work on
  85. * @param array $additionalParams Settings array ("bare", "return") which is melded with the GET and POST params
  86. * @return boolean Success
  87. * @access public
  88. */
  89. function dispatch($url = null, $additionalParams = array()) {
  90. if ($this->base === false) {
  91. $this->base = $this->baseUrl();
  92. }
  93. if (is_array($url)) {
  94. $url = $this->__extractParams($url, $additionalParams);
  95. } else {
  96. if ($url) {
  97. $_GET['url'] = $url;
  98. }
  99. $url = $this->getUrl();
  100. $this->params = array_merge($this->parseParams($url), $additionalParams);
  101. }
  102. $this->here = $this->base . '/' . $url;
  103. if ($this->asset($url) || $this->cached($url)) {
  104. return;
  105. }
  106. $controller =& $this->__getController();
  107. if (!is_object($controller)) {
  108. Router::setRequestInfo(array($this->params, array('base' => $this->base, 'webroot' => $this->webroot)));
  109. return $this->cakeError('missingController', array(array(
  110. 'className' => Inflector::camelize($this->params['controller']) . 'Controller',
  111. 'webroot' => $this->webroot,
  112. 'url' => $url,
  113. 'base' => $this->base
  114. )));
  115. }
  116. $privateAction = $this->params['action'][0] === '_';
  117. $prefixes = Router::prefixes();
  118. if (!empty($prefixes)) {
  119. if (isset($this->params['prefix'])) {
  120. $this->params['action'] = $this->params['prefix'] . '_' . $this->params['action'];
  121. } elseif (strpos($this->params['action'], '_') > 0) {
  122. list($prefix, $action) = explode('_', $this->params['action']);
  123. $privateAction = in_array($prefix, $prefixes);
  124. }
  125. }
  126. Router::setRequestInfo(array(
  127. $this->params, array('base' => $this->base, 'here' => $this->here, 'webroot' => $this->webroot)
  128. ));
  129. if ($privateAction) {
  130. return $this->cakeError('privateAction', array(array(
  131. 'className' => Inflector::camelize($this->params['controller'] . "Controller"),
  132. 'action' => $this->params['action'],
  133. 'webroot' => $this->webroot,
  134. 'url' => $url,
  135. 'base' => $this->base
  136. )));
  137. }
  138. $controller->base = $this->base;
  139. $controller->here = $this->here;
  140. $controller->webroot = $this->webroot;
  141. $controller->plugin = isset($this->params['plugin']) ? $this->params['plugin'] : null;
  142. $controller->params =& $this->params;
  143. $controller->action =& $this->params['action'];
  144. $controller->passedArgs = array_merge($this->params['pass'], $this->params['named']);
  145. if (!empty($this->params['data'])) {
  146. $controller->data =& $this->params['data'];
  147. } else {
  148. $controller->data = null;
  149. }
  150. if (isset($this->params['return']) && $this->params['return'] == 1) {
  151. $controller->autoRender = false;
  152. }
  153. if (!empty($this->params['bare'])) {
  154. $controller->autoLayout = false;
  155. }
  156. return $this->_invoke($controller, $this->params);
  157. }
  158. /**
  159. * Initializes the components and models a controller will be using.
  160. * Triggers the controller action, and invokes the rendering if Controller::$autoRender is true and echo's the output.
  161. * Otherwise the return value of the controller action are returned.
  162. *
  163. * @param object $controller Controller to invoke
  164. * @param array $params Parameters with at least the 'action' to invoke
  165. * @param boolean $missingAction Set to true if missing action should be rendered, false otherwise
  166. * @return string Output as sent by controller
  167. * @access protected
  168. */
  169. function _invoke(&$controller, $params) {
  170. $controller->constructClasses();
  171. $controller->startupProcess();
  172. $methods = array_flip($controller->methods);
  173. if (!isset($methods[strtolower($params['action'])])) {
  174. if ($controller->scaffold !== false) {
  175. App::import('Controller', 'Scaffold', false);
  176. return new Scaffold($controller, $params);
  177. }
  178. return $this->cakeError('missingAction', array(array(
  179. 'className' => Inflector::camelize($params['controller']."Controller"),
  180. 'action' => $params['action'],
  181. 'webroot' => $this->webroot,
  182. 'url' => $this->here,
  183. 'base' => $this->base
  184. )));
  185. }
  186. $output = call_user_func_array(array(&$controller, $params['action']), $params['pass']);
  187. if ($controller->autoRender) {
  188. $controller->output = $controller->render();
  189. } elseif (empty($controller->output)) {
  190. $controller->output = $output;
  191. }
  192. $controller->shutdownProcess();
  193. if (isset($params['return'])) {
  194. return $controller->output;
  195. }
  196. echo($controller->output);
  197. }
  198. /**
  199. * Sets the params when $url is passed as an array to Object::requestAction();
  200. * Merges the $url and $additionalParams and creates a string url.
  201. *
  202. * @param array $url Array or request parameters
  203. * @param array $additionalParams Array of additional parameters.
  204. * @return string $url The generated url string.
  205. * @access private
  206. */
  207. function __extractParams($url, $additionalParams = array()) {
  208. $defaults = array('pass' => array(), 'named' => array(), 'form' => array());
  209. $params = array_merge($defaults, $url, $additionalParams);
  210. $this->params = $params;
  211. $params += array('base' => false, 'url' => array());
  212. return ltrim(Router::reverse($params), '/');
  213. }
  214. /**
  215. * Returns array of GET and POST parameters. GET parameters are taken from given URL.
  216. *
  217. * @param string $fromUrl URL to mine for parameter information.
  218. * @return array Parameters found in POST and GET.
  219. * @access public
  220. */
  221. function parseParams($fromUrl) {
  222. $params = array();
  223. if (isset($_POST)) {
  224. $params['form'] = $_POST;
  225. if (ini_get('magic_quotes_gpc') === '1') {
  226. $params['form'] = stripslashes_deep($params['form']);
  227. }
  228. if (env('HTTP_X_HTTP_METHOD_OVERRIDE')) {
  229. $params['form']['_method'] = env('HTTP_X_HTTP_METHOD_OVERRIDE');
  230. }
  231. if (isset($params['form']['_method'])) {
  232. if (!empty($_SERVER)) {
  233. $_SERVER['REQUEST_METHOD'] = $params['form']['_method'];
  234. } else {
  235. $_ENV['REQUEST_METHOD'] = $params['form']['_method'];
  236. }
  237. unset($params['form']['_method']);
  238. }
  239. }
  240. $namedExpressions = Router::getNamedExpressions();
  241. extract($namedExpressions);
  242. include CONFIGS . 'routes.php';
  243. $params = array_merge(array('controller' => '', 'action' => ''), Router::parse($fromUrl), $params);
  244. if (empty($params['action'])) {
  245. $params['action'] = 'index';
  246. }
  247. if (isset($params['form']['data'])) {
  248. $params['data'] = $params['form']['data'];
  249. unset($params['form']['data']);
  250. }
  251. if (isset($_GET)) {
  252. if (ini_get('magic_quotes_gpc') === '1') {
  253. $url = stripslashes_deep($_GET);
  254. } else {
  255. $url = $_GET;
  256. }
  257. if (isset($params['url'])) {
  258. $params['url'] = array_merge($params['url'], $url);
  259. } else {
  260. $params['url'] = $url;
  261. }
  262. }
  263. foreach ($_FILES as $name => $data) {
  264. if ($name != 'data') {
  265. $params['form'][$name] = $data;
  266. }
  267. }
  268. if (isset($_FILES['data'])) {
  269. foreach ($_FILES['data'] as $key => $data) {
  270. foreach ($data as $model => $fields) {
  271. if (is_array($fields)) {
  272. foreach ($fields as $field => $value) {
  273. if (is_array($value)) {
  274. foreach ($value as $k => $v) {
  275. $params['data'][$model][$field][$k][$key] = $v;
  276. }
  277. } else {
  278. $params['data'][$model][$field][$key] = $value;
  279. }
  280. }
  281. } else {
  282. $params['data'][$model][$key] = $fields;
  283. }
  284. }
  285. }
  286. }
  287. return $params;
  288. }
  289. /**
  290. * Returns a base URL and sets the proper webroot
  291. *
  292. * @return string Base URL
  293. * @access public
  294. */
  295. function baseUrl() {
  296. $dir = $webroot = null;
  297. $config = Configure::read('App');
  298. extract($config);
  299. if (!$base) {
  300. $base = $this->base;
  301. }
  302. if ($base !== false) {
  303. $this->webroot = $base . '/';
  304. return $this->base = $base;
  305. }
  306. if (!$baseUrl) {
  307. $replace = array('<', '>', '*', '\'', '"');
  308. $base = str_replace($replace, '', dirname(env('PHP_SELF')));
  309. if ($webroot === 'webroot' && $webroot === basename($base)) {
  310. $base = dirname($base);
  311. }
  312. if ($dir === 'app' && $dir === basename($base)) {
  313. $base = dirname($base);
  314. }
  315. if ($base === DS || $base === '.') {
  316. $base = '';
  317. }
  318. $this->webroot = $base .'/';
  319. return $base;
  320. }
  321. $file = '/' . basename($baseUrl);
  322. $base = dirname($baseUrl);
  323. if ($base === DS || $base === '.') {
  324. $base = '';
  325. }
  326. $this->webroot = $base . '/';
  327. $docRoot = realpath(env('DOCUMENT_ROOT'));
  328. $docRootContainsWebroot = strpos($docRoot, $dir . '/' . $webroot);
  329. if (!empty($base) || !$docRootContainsWebroot) {
  330. if (strpos($this->webroot, $dir) === false) {
  331. $this->webroot .= $dir . '/' ;
  332. }
  333. if (strpos($this->webroot, $webroot) === false) {
  334. $this->webroot .= $webroot . '/';
  335. }
  336. }
  337. return $base . $file;
  338. }
  339. /**
  340. * Get controller to use, either plugin controller or application controller
  341. *
  342. * @param array $params Array of parameters
  343. * @return mixed name of controller if not loaded, or object if loaded
  344. * @access private
  345. */
  346. function &__getController() {
  347. $controller = false;
  348. $ctrlClass = $this->__loadController($this->params);
  349. if (!$ctrlClass) {
  350. return $controller;
  351. }
  352. $ctrlClass .= 'Controller';
  353. if (class_exists($ctrlClass)) {
  354. $controller =& new $ctrlClass();
  355. }
  356. return $controller;
  357. }
  358. /**
  359. * Load controller and return controller classname
  360. *
  361. * @param array $params Array of parameters
  362. * @return string|bool Name of controller class name
  363. * @access private
  364. */
  365. function __loadController($params) {
  366. $pluginName = $pluginPath = $controller = null;
  367. if (!empty($params['plugin'])) {
  368. $pluginName = $controller = Inflector::camelize($params['plugin']);
  369. $pluginPath = $pluginName . '.';
  370. }
  371. if (!empty($params['controller'])) {
  372. $controller = Inflector::camelize($params['controller']);
  373. }
  374. if ($pluginPath . $controller) {
  375. if (App::import('Controller', $pluginPath . $controller)) {
  376. return $controller;
  377. }
  378. }
  379. return false;
  380. }
  381. /**
  382. * Returns the REQUEST_URI from the server environment, or, failing that,
  383. * constructs a new one, using the PHP_SELF constant and other variables.
  384. *
  385. * @return string URI
  386. * @access public
  387. */
  388. function uri() {
  389. foreach (array('HTTP_X_REWRITE_URL', 'REQUEST_URI', 'argv') as $var) {
  390. if ($uri = env($var)) {
  391. if ($var == 'argv') {
  392. $uri = $uri[0];
  393. }
  394. break;
  395. }
  396. }
  397. $base = preg_replace('/^\//', '', '' . Configure::read('App.baseUrl'));
  398. if ($base) {
  399. $uri = preg_replace('/^(?:\/)?(?:' . preg_quote($base, '/') . ')?(?:url=)?/', '', $uri);
  400. }
  401. if (PHP_SAPI == 'isapi') {
  402. $uri = preg_replace('/^(?:\/)?(?:\/)?(?:\?)?(?:url=)?/', '', $uri);
  403. }
  404. if (!empty($uri)) {
  405. if (key($_GET) && strpos(key($_GET), '?') !== false) {
  406. unset($_GET[key($_GET)]);
  407. }
  408. $uri = explode('?', $uri, 2);
  409. if (isset($uri[1])) {
  410. parse_str($uri[1], $_GET);
  411. }
  412. $uri = $uri[0];
  413. } else {
  414. $uri = env('QUERY_STRING');
  415. }
  416. if (is_string($uri) && strpos($uri, 'index.php') !== false) {
  417. list(, $uri) = explode('index.php', $uri, 2);
  418. }
  419. if (empty($uri) || $uri == '/' || $uri == '//') {
  420. return '';
  421. }
  422. return str_replace('//', '/', '/' . $uri);
  423. }
  424. /**
  425. * Returns and sets the $_GET[url] derived from the REQUEST_URI
  426. *
  427. * @param string $uri Request URI
  428. * @param string $base Base path
  429. * @return string URL
  430. * @access public
  431. */
  432. function getUrl($uri = null, $base = null) {
  433. if (empty($_GET['url'])) {
  434. if ($uri == null) {
  435. $uri = $this->uri();
  436. }
  437. if ($base == null) {
  438. $base = $this->base;
  439. }
  440. $url = null;
  441. $tmpUri = preg_replace('/^(?:\?)?(?:\/)?/', '', $uri);
  442. $baseDir = preg_replace('/^\//', '', dirname($base)) . '/';
  443. if ($tmpUri === '/' || $tmpUri == $baseDir || $tmpUri == $base) {
  444. $url = $_GET['url'] = '/';
  445. } else {
  446. if ($base && strpos($uri, $base) === 0) {
  447. $elements = explode($base, $uri, 2);
  448. } elseif (preg_match('/^[\/\?\/|\/\?|\?\/]/', $uri)) {
  449. $elements = array(1 => preg_replace('/^[\/\?\/|\/\?|\?\/]/', '', $uri));
  450. } else {
  451. $elements = array();
  452. }
  453. if (!empty($elements[1])) {
  454. $_GET['url'] = $elements[1];
  455. $url = $elements[1];
  456. } else {
  457. $url = $_GET['url'] = '/';
  458. }
  459. if (strpos($url, '/') === 0 && $url != '/') {
  460. $url = $_GET['url'] = substr($url, 1);
  461. }
  462. }
  463. } else {
  464. $url = $_GET['url'];
  465. }
  466. if ($url{0} == '/') {
  467. $url = substr($url, 1);
  468. }
  469. return $url;
  470. }
  471. /**
  472. * Outputs cached dispatch view cache
  473. *
  474. * @param string $url Requested URL
  475. * @access public
  476. */
  477. function cached($url) {
  478. if (Configure::read('Cache.check') === true) {
  479. $path = $this->here;
  480. if ($this->here == '/') {
  481. $path = 'home';
  482. }
  483. $path = strtolower(Inflector::slug($path));
  484. $filename = CACHE . 'views' . DS . $path . '.php';
  485. if (!file_exists($filename)) {
  486. $filename = CACHE . 'views' . DS . $path . '_index.php';
  487. }
  488. if (file_exists($filename)) {
  489. if (!class_exists('View')) {
  490. App::import('View', 'View', false);
  491. }
  492. $controller = null;
  493. $view =& new View($controller);
  494. $return = $view->renderCache($filename, getMicrotime());
  495. if (!$return) {
  496. ClassRegistry::removeObject('view');
  497. }
  498. return $return;
  499. }
  500. }
  501. return false;
  502. }
  503. /**
  504. * Checks if a requested asset exists and sends it to the browser
  505. *
  506. * @param $url string $url Requested URL
  507. * @return boolean True on success if the asset file was found and sent
  508. * @access public
  509. */
  510. function asset($url) {
  511. if (strpos($url, '..') !== false || strpos($url, '.') === false) {
  512. return false;
  513. }
  514. $filters = Configure::read('Asset.filter');
  515. $isCss = (
  516. strpos($url, 'ccss/') === 0 ||
  517. preg_match('#^(theme/([^/]+)/ccss/)|(([^/]+)(?<!css)/ccss)/#i', $url)
  518. );
  519. $isJs = (
  520. strpos($url, 'cjs/') === 0 ||
  521. preg_match('#^/((theme/[^/]+)/cjs/)|(([^/]+)(?<!js)/cjs)/#i', $url)
  522. );
  523. if (($isCss && empty($filters['css'])) || ($isJs && empty($filters['js']))) {
  524. header('HTTP/1.1 404 Not Found');
  525. return $this->_stop();
  526. } elseif ($isCss) {
  527. include WWW_ROOT . DS . $filters['css'];
  528. $this->_stop();
  529. } elseif ($isJs) {
  530. include WWW_ROOT . DS . $filters['js'];
  531. $this->_stop();
  532. }
  533. $controller = null;
  534. $ext = array_pop(explode('.', $url));
  535. $parts = explode('/', $url);
  536. $assetFile = null;
  537. if ($parts[0] === 'theme') {
  538. $themeName = $parts[1];
  539. unset($parts[0], $parts[1]);
  540. $fileFragment = implode(DS, $parts);
  541. $path = App::themePath($themeName) . 'webroot' . DS;
  542. if (file_exists($path . $fileFragment)) {
  543. $assetFile = $path . $fileFragment;
  544. }
  545. } else {
  546. $plugin = $parts[0];
  547. unset($parts[0]);
  548. $fileFragment = implode(DS, $parts);
  549. $pluginWebroot = App::pluginPath($plugin) . 'webroot' . DS;
  550. if (file_exists($pluginWebroot . $fileFragment)) {
  551. $assetFile = $pluginWebroot . $fileFragment;
  552. }
  553. }
  554. if ($assetFile !== null) {
  555. $this->_deliverAsset($assetFile, $ext);
  556. return true;
  557. }
  558. return false;
  559. }
  560. /**
  561. * Sends an asset file to the client
  562. *
  563. * @param string $assetFile Path to the asset file in the file system
  564. * @param string $ext The extension of the file to determine its mime type
  565. * @return void
  566. * @access protected
  567. */
  568. function _deliverAsset($assetFile, $ext) {
  569. $ob = @ini_get("zlib.output_compression") !== '1' && extension_loaded("zlib") && (strpos(env('HTTP_ACCEPT_ENCODING'), 'gzip') !== false);
  570. $compressionEnabled = $ob && Configure::read('Asset.compress');
  571. if ($compressionEnabled) {
  572. ob_start();
  573. ob_start('ob_gzhandler');
  574. }
  575. App::import('View', 'Media');
  576. $controller = null;
  577. $Media = new MediaView($controller);
  578. if (isset($Media->mimeType[$ext])) {
  579. $contentType = $Media->mimeType[$ext];
  580. } else {
  581. $contentType = 'application/octet-stream';
  582. $agent = env('HTTP_USER_AGENT');
  583. if (preg_match('%Opera(/| )([0-9].[0-9]{1,2})%', $agent) || preg_match('/MSIE ([0-9].[0-9]{1,2})/', $agent)) {
  584. $contentType = 'application/octetstream';
  585. }
  586. }
  587. header("Date: " . date("D, j M Y G:i:s ", filemtime($assetFile)) . 'GMT');
  588. header('Content-type: ' . $contentType);
  589. header("Expires: " . gmdate("D, j M Y H:i:s", time() + DAY) . " GMT");
  590. header("Cache-Control: cache");
  591. header("Pragma: cache");
  592. if ($ext === 'css' || $ext === 'js') {
  593. include($assetFile);
  594. } else {
  595. if ($compressionEnabled) {
  596. ob_clean();
  597. }
  598. readfile($assetFile);
  599. }
  600. if ($compressionEnabled) {
  601. ob_end_flush();
  602. }
  603. }
  604. }