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