PageRenderTime 56ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 0ms

/cake/dispatcher.php

https://bitbucket.org/webpolis/hurli
PHP | 659 lines | 447 code | 57 blank | 155 comment | 134 complexity | 7a9a4e55f9ba3cb86e994b007495ffda 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 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(Router::parse($fromUrl), $params);
  244. if (strlen($params['action']) === 0) {
  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. if (!empty($base)) {
  328. if (strpos($this->webroot, $dir) === false) {
  329. $this->webroot .= $dir . '/' ;
  330. }
  331. if (strpos($this->webroot, $webroot) === false) {
  332. $this->webroot .= $webroot . '/';
  333. }
  334. }
  335. return $base . $file;
  336. }
  337. /**
  338. * Get controller to use, either plugin controller or application controller
  339. *
  340. * @param array $params Array of parameters
  341. * @return mixed name of controller if not loaded, or object if loaded
  342. * @access private
  343. */
  344. function &__getController() {
  345. $controller = false;
  346. $ctrlClass = $this->__loadController($this->params);
  347. if (!$ctrlClass) {
  348. return $controller;
  349. }
  350. $ctrlClass .= 'Controller';
  351. if (class_exists($ctrlClass)) {
  352. $controller =& new $ctrlClass();
  353. }
  354. return $controller;
  355. }
  356. /**
  357. * Load controller and return controller classname
  358. *
  359. * @param array $params Array of parameters
  360. * @return string|bool Name of controller class name
  361. * @access private
  362. */
  363. function __loadController($params) {
  364. $pluginName = $pluginPath = $controller = null;
  365. if (!empty($params['plugin'])) {
  366. $pluginName = $controller = Inflector::camelize($params['plugin']);
  367. $pluginPath = $pluginName . '.';
  368. }
  369. if (!empty($params['controller'])) {
  370. $controller = Inflector::camelize($params['controller']);
  371. }
  372. if ($pluginPath . $controller) {
  373. if (App::import('Controller', $pluginPath . $controller)) {
  374. return $controller;
  375. }
  376. }
  377. return false;
  378. }
  379. /**
  380. * Returns the REQUEST_URI from the server environment, or, failing that,
  381. * constructs a new one, using the PHP_SELF constant and other variables.
  382. *
  383. * @return string URI
  384. * @access public
  385. */
  386. function uri() {
  387. foreach (array('HTTP_X_REWRITE_URL', 'REQUEST_URI', 'argv') as $var) {
  388. if ($uri = env($var)) {
  389. if ($var == 'argv') {
  390. $uri = $uri[0];
  391. }
  392. break;
  393. }
  394. }
  395. $base = preg_replace('/^\//', '', '' . Configure::read('App.baseUrl'));
  396. if ($base) {
  397. $uri = preg_replace('/^(?:\/)?(?:' . preg_quote($base, '/') . ')?(?:url=)?/', '', $uri);
  398. }
  399. if (PHP_SAPI == 'isapi') {
  400. $uri = preg_replace('/^(?:\/)?(?:\/)?(?:\?)?(?:url=)?/', '', $uri);
  401. }
  402. if (!empty($uri)) {
  403. if (key($_GET) && strpos(key($_GET), '?') !== false) {
  404. unset($_GET[key($_GET)]);
  405. }
  406. $uri = explode('?', $uri, 2);
  407. if (isset($uri[1])) {
  408. parse_str($uri[1], $_GET);
  409. }
  410. $uri = $uri[0];
  411. } else {
  412. $uri = env('QUERY_STRING');
  413. }
  414. if (is_string($uri) && strpos($uri, 'index.php') !== false) {
  415. list(, $uri) = explode('index.php', $uri, 2);
  416. }
  417. if (empty($uri) || $uri == '/' || $uri == '//') {
  418. return '';
  419. }
  420. return str_replace('//', '/', '/' . $uri);
  421. }
  422. /**
  423. * Returns and sets the $_GET[url] derived from the REQUEST_URI
  424. *
  425. * @param string $uri Request URI
  426. * @param string $base Base path
  427. * @return string URL
  428. * @access public
  429. */
  430. function getUrl($uri = null, $base = null) {
  431. if (empty($_GET['url'])) {
  432. if ($uri == null) {
  433. $uri = $this->uri();
  434. }
  435. if ($base == null) {
  436. $base = $this->base;
  437. }
  438. $url = null;
  439. $tmpUri = preg_replace('/^(?:\?)?(?:\/)?/', '', $uri);
  440. $baseDir = preg_replace('/^\//', '', dirname($base)) . '/';
  441. if ($tmpUri === '/' || $tmpUri == $baseDir || $tmpUri == $base) {
  442. $url = $_GET['url'] = '/';
  443. } else {
  444. if ($base && strpos($uri, $base) !== false) {
  445. $elements = explode($base, $uri);
  446. } elseif (preg_match('/^[\/\?\/|\/\?|\?\/]/', $uri)) {
  447. $elements = array(1 => preg_replace('/^[\/\?\/|\/\?|\?\/]/', '', $uri));
  448. } else {
  449. $elements = array();
  450. }
  451. if (!empty($elements[1])) {
  452. $_GET['url'] = $elements[1];
  453. $url = $elements[1];
  454. } else {
  455. $url = $_GET['url'] = '/';
  456. }
  457. if (strpos($url, '/') === 0 && $url != '/') {
  458. $url = $_GET['url'] = substr($url, 1);
  459. }
  460. }
  461. } else {
  462. $url = $_GET['url'];
  463. }
  464. if ($url{0} == '/') {
  465. $url = substr($url, 1);
  466. }
  467. return $url;
  468. }
  469. /**
  470. * Outputs cached dispatch view cache
  471. *
  472. * @param string $url Requested URL
  473. * @access public
  474. */
  475. function cached($url) {
  476. if (Configure::read('Cache.check') === true) {
  477. $path = $this->here;
  478. if ($this->here == '/') {
  479. $path = 'home';
  480. }
  481. $path = strtolower(Inflector::slug($path));
  482. $filename = CACHE . 'views' . DS . $path . '.php';
  483. if (!file_exists($filename)) {
  484. $filename = CACHE . 'views' . DS . $path . '_index.php';
  485. }
  486. if (file_exists($filename)) {
  487. if (!class_exists('View')) {
  488. App::import('View', 'View', false);
  489. }
  490. $controller = null;
  491. $view =& new View($controller);
  492. $return = $view->renderCache($filename, getMicrotime());
  493. if (!$return) {
  494. ClassRegistry::removeObject('view');
  495. }
  496. return $return;
  497. }
  498. }
  499. return false;
  500. }
  501. /**
  502. * Checks if a requested asset exists and sends it to the browser
  503. *
  504. * @param $url string $url Requested URL
  505. * @return boolean True on success if the asset file was found and sent
  506. * @access public
  507. */
  508. function asset($url) {
  509. if (strpos($url, '..') !== false || strpos($url, '.') === false) {
  510. return false;
  511. }
  512. $filters = Configure::read('Asset.filter');
  513. $isCss = (
  514. strpos($url, 'ccss/') === 0 ||
  515. preg_match('#^(theme/([^/]+)/ccss/)|(([^/]+)(?<!css)/ccss)/#i', $url)
  516. );
  517. $isJs = (
  518. strpos($url, 'cjs/') === 0 ||
  519. preg_match('#^/((theme/[^/]+)/cjs/)|(([^/]+)(?<!js)/cjs)/#i', $url)
  520. );
  521. if (($isCss && empty($filters['css'])) || ($isJs && empty($filters['js']))) {
  522. header('HTTP/1.1 404 Not Found');
  523. return $this->_stop();
  524. } elseif ($isCss) {
  525. include WWW_ROOT . DS . $filters['css'];
  526. $this->_stop();
  527. } elseif ($isJs) {
  528. include WWW_ROOT . DS . $filters['js'];
  529. $this->_stop();
  530. }
  531. $controller = null;
  532. $ext = array_pop(explode('.', $url));
  533. $parts = explode('/', $url);
  534. $assetFile = null;
  535. if ($parts[0] === 'theme') {
  536. $themeName = $parts[1];
  537. unset($parts[0], $parts[1]);
  538. $fileFragment = implode(DS, $parts);
  539. $path = App::themePath($themeName) . 'webroot' . DS;
  540. if (file_exists($path . $fileFragment)) {
  541. $assetFile = $path . $fileFragment;
  542. }
  543. } else {
  544. $plugin = $parts[0];
  545. unset($parts[0]);
  546. $fileFragment = implode(DS, $parts);
  547. $pluginWebroot = App::pluginPath($plugin) . 'webroot' . DS;
  548. if (file_exists($pluginWebroot . $fileFragment)) {
  549. $assetFile = $pluginWebroot . $fileFragment;
  550. }
  551. }
  552. if ($assetFile !== null) {
  553. $this->_deliverAsset($assetFile, $ext);
  554. return true;
  555. }
  556. return false;
  557. }
  558. /**
  559. * Sends an asset file to the client
  560. *
  561. * @param string $assetFile Path to the asset file in the file system
  562. * @param string $ext The extension of the file to determine its mime type
  563. * @return void
  564. * @access protected
  565. */
  566. function _deliverAsset($assetFile, $ext) {
  567. $ob = @ini_get("zlib.output_compression") !== '1' && extension_loaded("zlib") && (strpos(env('HTTP_ACCEPT_ENCODING'), 'gzip') !== false);
  568. $compressionEnabled = $ob && Configure::read('Asset.compress');
  569. if ($compressionEnabled) {
  570. ob_start();
  571. ob_start('ob_gzhandler');
  572. }
  573. App::import('View', 'Media', false);
  574. $controller = null;
  575. $Media = new MediaView($controller);
  576. if (isset($Media->mimeType[$ext])) {
  577. $contentType = $Media->mimeType[$ext];
  578. } else {
  579. $contentType = 'application/octet-stream';
  580. $agent = env('HTTP_USER_AGENT');
  581. if (preg_match('%Opera(/| )([0-9].[0-9]{1,2})%', $agent) || preg_match('/MSIE ([0-9].[0-9]{1,2})/', $agent)) {
  582. $contentType = 'application/octetstream';
  583. }
  584. }
  585. header("Date: " . date("D, j M Y G:i:s ", filemtime($assetFile)) . 'GMT');
  586. header('Content-type: ' . $contentType);
  587. header("Expires: " . gmdate("D, j M Y H:i:s", time() + DAY) . " GMT");
  588. header("Cache-Control: cache");
  589. header("Pragma: cache");
  590. if ($ext === 'css' || $ext === 'js') {
  591. include($assetFile);
  592. } else {
  593. if ($compressionEnabled) {
  594. ob_clean();
  595. }
  596. readfile($assetFile);
  597. }
  598. if ($compressionEnabled) {
  599. ob_end_flush();
  600. }
  601. }
  602. }