RequestHandlerComponent.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644
  1. <?php
  2. /**
  3. * Request object for handling alternative HTTP requests
  4. *
  5. * Alternative HTTP requests can come from wireless units like mobile phones, palmtop computers,
  6. * and the like. These units have no use for Ajax requests, and this Component can tell how Cake
  7. * should respond to the different needs of a handheld computer and a desktop machine.
  8. *
  9. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  10. * Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
  11. *
  12. * Licensed under The MIT License
  13. * Redistributions of files must retain the above copyright notice.
  14. *
  15. * @copyright Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
  16. * @link http://cakephp.org CakePHP(tm) Project
  17. * @package cake.libs.controller.components
  18. * @since CakePHP(tm) v 0.10.4.1076
  19. * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
  20. */
  21. App::uses('Xml', 'Utility');
  22. /**
  23. * Request object for handling HTTP requests
  24. *
  25. * @package cake.libs.controller.components
  26. * @link http://book.cakephp.org/view/1291/Request-Handling
  27. *
  28. */
  29. class RequestHandlerComponent extends Component {
  30. /**
  31. * The layout that will be switched to for Ajax requests
  32. *
  33. * @var string
  34. * @access public
  35. * @see RequestHandler::setAjax()
  36. */
  37. public $ajaxLayout = 'ajax';
  38. /**
  39. * Determines whether or not callbacks will be fired on this component
  40. *
  41. * @var boolean
  42. * @access public
  43. */
  44. public $enabled = true;
  45. /**
  46. * Holds the reference to Controller::$request
  47. *
  48. * @var CakeRequest
  49. * @access public
  50. */
  51. public $request;
  52. /**
  53. * Holds the reference to Controller::$response
  54. *
  55. * @var CakeResponse
  56. * @access public
  57. */
  58. public $response;
  59. /**
  60. * The template to use when rendering the given content type.
  61. *
  62. * @var string
  63. * @access private
  64. */
  65. private $__renderType = null;
  66. /**
  67. * Contains the file extension parsed out by the Router
  68. *
  69. * @var string
  70. * @access public
  71. * @see Router::parseExtensions()
  72. */
  73. public $ext = null;
  74. /**
  75. * Flag set when MIME types have been initialized
  76. *
  77. * @var boolean
  78. * @access private
  79. * @see RequestHandler::__initializeTypes()
  80. */
  81. private $__typesInitialized = false;
  82. /**
  83. * Constructor. Parses the accepted content types accepted by the client using HTTP_ACCEPT
  84. *
  85. * @param ComponentCollection $collection ComponentCollection object.
  86. * @param array $settings Array of settings.
  87. */
  88. function __construct(ComponentCollection $collection, $settings = array()) {
  89. $this->__acceptTypes = explode(',', env('HTTP_ACCEPT'));
  90. foreach ($this->__acceptTypes as $i => $type) {
  91. if (strpos($type, ';')) {
  92. $type = explode(';', $type);
  93. $this->__acceptTypes[$i] = $type[0];
  94. }
  95. }
  96. parent::__construct($collection, $settings);
  97. }
  98. /**
  99. * Initializes the component, gets a reference to Controller::$parameters, and
  100. * checks to see if a file extension has been parsed by the Router. Or if the
  101. * HTTP_ACCEPT_TYPE is set to a single value that is a supported extension and mapped type.
  102. * If yes, RequestHandler::$ext is set to that value
  103. *
  104. * @param object $controller A reference to the controller
  105. * @param array $settings Array of settings to _set().
  106. * @return void
  107. * @see Router::parseExtensions()
  108. */
  109. public function initialize($controller, $settings = array()) {
  110. $this->request = $controller->request;
  111. $this->response = $controller->response;
  112. if (isset($this->request->params['url']['ext'])) {
  113. $this->ext = $this->request->params['url']['ext'];
  114. }
  115. if (empty($this->ext)) {
  116. $accepts = $this->request->accepts();
  117. $extensions = Router::extensions();
  118. if (count($accepts) == 1) {
  119. $mapped = $this->mapType($accepts[0]);
  120. if (in_array($mapped, $extensions)) {
  121. $this->ext = $mapped;
  122. }
  123. }
  124. }
  125. $this->params = $controller->params;
  126. $this->_set($settings);
  127. }
  128. /**
  129. * The startup method of the RequestHandler enables several automatic behaviors
  130. * related to the detection of certain properties of the HTTP request, including:
  131. *
  132. * - Disabling layout rendering for Ajax requests (based on the HTTP_X_REQUESTED_WITH header)
  133. * - If Router::parseExtensions() is enabled, the layout and template type are
  134. * switched based on the parsed extension or Accept-Type header. For example, if `controller/action.xml`
  135. * is requested, the view path becomes `app/views/controller/xml/action.ctp`. Also if
  136. * `controller/action` is requested with `Accept-Type: application/xml` in the headers
  137. * the view path will become `app/views/controller/xml/action.ctp`.
  138. * - If a helper with the same name as the extension exists, it is added to the controller.
  139. * - If the extension is of a type that RequestHandler understands, it will set that
  140. * Content-type in the response header.
  141. * - If the XML data is POSTed, the data is parsed into an XML object, which is assigned
  142. * to the $data property of the controller, which can then be saved to a model object.
  143. *
  144. * @param object $controller A reference to the controller
  145. * @return void
  146. */
  147. public function startup($controller) {
  148. $controller->request->params['isAjax'] = $this->request->is('ajax');
  149. $isRecognized = (
  150. !in_array($this->ext, array('html', 'htm')) &&
  151. $this->response->getMimeType($this->ext)
  152. );
  153. if (!empty($this->ext) && $isRecognized) {
  154. $this->renderAs($controller, $this->ext);
  155. } elseif ($this->request->is('ajax')) {
  156. $this->renderAs($controller, 'ajax');
  157. } elseif (empty($this->ext) || in_array($this->ext, array('html', 'htm'))) {
  158. $this->respondAs('html', array('charset' => Configure::read('App.encoding')));
  159. }
  160. if ($this->requestedWith('xml')) {
  161. try {
  162. $xml = $controller->request->input('Xml::build');
  163. if (isset($xml->data)) {
  164. $controller->data = Xml::toArray($xml->data);
  165. } else {
  166. $controller->data = Xml::toArray($xml);
  167. }
  168. } catch (Exception $e) {}
  169. }
  170. }
  171. /**
  172. * Handles (fakes) redirects for Ajax requests using requestAction()
  173. *
  174. * @param object $controller A reference to the controller
  175. * @param mixed $url A string or array containing the redirect location
  176. * @param mixed HTTP Status for redirect
  177. */
  178. public function beforeRedirect($controller, $url, $status = null, $exit = true) {
  179. if (!$this->request->is('ajax')) {
  180. return;
  181. }
  182. foreach ($_POST as $key => $val) {
  183. unset($_POST[$key]);
  184. }
  185. if (is_array($url)) {
  186. $url = Router::url($url + array('base' => false));
  187. }
  188. if (!empty($status)) {
  189. $statusCode = $this->response->httpCodes($status);
  190. $code = key($statusCode);
  191. $this->response->statusCode($code);
  192. }
  193. $this->response->body($this->requestAction($url, array('return', 'bare' => false)));
  194. $this->response->send();
  195. $this->_stop();
  196. }
  197. /**
  198. * Returns true if the current HTTP request is Ajax, false otherwise
  199. *
  200. * @return boolean True if call is Ajax
  201. */
  202. public function isAjax() {
  203. return $this->request->is('ajax');
  204. }
  205. /**
  206. * Returns true if the current HTTP request is coming from a Flash-based client
  207. *
  208. * @return boolean True if call is from Flash
  209. */
  210. public function isFlash() {
  211. return $this->request->is('flash');
  212. }
  213. /**
  214. * Returns true if the current request is over HTTPS, false otherwise.
  215. *
  216. * @return bool True if call is over HTTPS
  217. */
  218. public function isSSL() {
  219. return $this->request->is('ssl');
  220. }
  221. /**
  222. * Returns true if the current call accepts an XML response, false otherwise
  223. *
  224. * @return boolean True if client accepts an XML response
  225. */
  226. public function isXml() {
  227. return $this->prefers('xml');
  228. }
  229. /**
  230. * Returns true if the current call accepts an RSS response, false otherwise
  231. *
  232. * @return boolean True if client accepts an RSS response
  233. */
  234. public function isRss() {
  235. return $this->prefers('rss');
  236. }
  237. /**
  238. * Returns true if the current call accepts an Atom response, false otherwise
  239. *
  240. * @return boolean True if client accepts an RSS response
  241. */
  242. public function isAtom() {
  243. return $this->prefers('atom');
  244. }
  245. /**
  246. * Returns true if user agent string matches a mobile web browser, or if the
  247. * client accepts WAP content.
  248. *
  249. * @return boolean True if user agent is a mobile web browser
  250. */
  251. function isMobile() {
  252. return $this->request->is('mobile') || $this->accepts('wap');
  253. }
  254. /**
  255. * Returns true if the client accepts WAP content
  256. *
  257. * @return bool
  258. */
  259. public function isWap() {
  260. return $this->prefers('wap');
  261. }
  262. /**
  263. * Returns true if the current call a POST request
  264. *
  265. * @return boolean True if call is a POST
  266. * @deprecated Use $this->request->is('post'); from your controller.
  267. */
  268. public function isPost() {
  269. return $this->request->is('post');
  270. }
  271. /**
  272. * Returns true if the current call a PUT request
  273. *
  274. * @return boolean True if call is a PUT
  275. * @deprecated Use $this->request->is('put'); from your controller.
  276. */
  277. public function isPut() {
  278. return $this->request->is('put');
  279. }
  280. /**
  281. * Returns true if the current call a GET request
  282. *
  283. * @return boolean True if call is a GET
  284. * @deprecated Use $this->request->is('get'); from your controller.
  285. */
  286. public function isGet() {
  287. return $this->request->is('get');
  288. }
  289. /**
  290. * Returns true if the current call a DELETE request
  291. *
  292. * @return boolean True if call is a DELETE
  293. * @deprecated Use $this->request->is('delete'); from your controller.
  294. */
  295. public function isDelete() {
  296. return $this->request->is('delete');
  297. }
  298. /**
  299. * Gets Prototype version if call is Ajax, otherwise empty string.
  300. * The Prototype library sets a special "Prototype version" HTTP header.
  301. *
  302. * @return string Prototype version of component making Ajax call
  303. */
  304. public function getAjaxVersion() {
  305. if (env('HTTP_X_PROTOTYPE_VERSION') != null) {
  306. return env('HTTP_X_PROTOTYPE_VERSION');
  307. }
  308. return false;
  309. }
  310. /**
  311. * Adds/sets the Content-type(s) for the given name. This method allows
  312. * content-types to be mapped to friendly aliases (or extensions), which allows
  313. * RequestHandler to automatically respond to requests of that type in the
  314. * startup method.
  315. *
  316. * @param string $name The name of the Content-type, i.e. "html", "xml", "css"
  317. * @param mixed $type The Content-type or array of Content-types assigned to the name,
  318. * i.e. "text/html", or "application/xml"
  319. * @return void
  320. */
  321. public function setContent($name, $type = null) {
  322. $this->response->type(array($name => $type));
  323. }
  324. /**
  325. * Gets the server name from which this request was referred
  326. *
  327. * @return string Server address
  328. * @deprecated use $this->request->referer() from your controller instead
  329. */
  330. public function getReferer() {
  331. return $this->request->referer(false);
  332. }
  333. /**
  334. * Gets remote client IP
  335. *
  336. * @return string Client IP address
  337. * @deprecated use $this->request->clientIp() from your controller instead.
  338. */
  339. public function getClientIP($safe = true) {
  340. return $this->request->clientIp($safe);
  341. }
  342. /**
  343. * Determines which content types the client accepts. Acceptance is based on
  344. * the file extension parsed by the Router (if present), and by the HTTP_ACCEPT
  345. * header. Unlike CakeRequest::accepts() this method deals entirely with mapped content types.
  346. *
  347. * Usage:
  348. *
  349. * `$this->RequestHandler->accepts(array('xml', 'html', 'json'));`
  350. *
  351. * Returns true if the client accepts any of the supplied types.
  352. *
  353. * `$this->RequestHandler->accepts('xml');`
  354. *
  355. * Returns true if the client accepts xml.
  356. *
  357. * @param mixed $type Can be null (or no parameter), a string type name, or an
  358. * array of types
  359. * @return mixed If null or no parameter is passed, returns an array of content
  360. * types the client accepts. If a string is passed, returns true
  361. * if the client accepts it. If an array is passed, returns true
  362. * if the client accepts one or more elements in the array.
  363. * @see RequestHandlerComponent::setContent()
  364. */
  365. public function accepts($type = null) {
  366. $accepted = $this->request->accepts();
  367. if ($type == null) {
  368. return $this->mapType($accepted);
  369. } elseif (is_array($type)) {
  370. foreach ($type as $t) {
  371. $t = $this->mapAlias($t);
  372. if (in_array($t, $accepted)) {
  373. return true;
  374. }
  375. }
  376. return false;
  377. } elseif (is_string($type)) {
  378. $type = $this->mapAlias($type);
  379. return in_array($type, $accepted);
  380. }
  381. return false;
  382. }
  383. /**
  384. * Determines the content type of the data the client has sent (i.e. in a POST request)
  385. *
  386. * @param mixed $type Can be null (or no parameter), a string type name, or an array of types
  387. * @return mixed If a single type is supplied a boolean will be returned. If no type is provided
  388. * The mapped value of CONTENT_TYPE will be returned. If an array is supplied the first type
  389. * in the request content type will be returned.
  390. */
  391. public function requestedWith($type = null) {
  392. if (!$this->request->is('post') && !$this->request->is('put')) {
  393. return null;
  394. }
  395. list($contentType) = explode(';', env('CONTENT_TYPE'));
  396. if ($type == null) {
  397. return $this->mapType($contentType);
  398. } elseif (is_array($type)) {
  399. foreach ($type as $t) {
  400. if ($this->requestedWith($t)) {
  401. return $t;
  402. }
  403. }
  404. return false;
  405. } elseif (is_string($type)) {
  406. return ($type == $this->mapType($contentType));
  407. }
  408. }
  409. /**
  410. * Determines which content-types the client prefers. If no parameters are given,
  411. * the content-type that the client most likely prefers is returned. If $type is
  412. * an array, the first item in the array that the client accepts is returned.
  413. * Preference is determined primarily by the file extension parsed by the Router
  414. * if provided, and secondarily by the list of content-types provided in
  415. * HTTP_ACCEPT.
  416. *
  417. * @param mixed $type An optional array of 'friendly' content-type names, i.e.
  418. * 'html', 'xml', 'js', etc.
  419. * @return mixed If $type is null or not provided, the first content-type in the
  420. * list, based on preference, is returned.
  421. * @see RequestHandlerComponent::setContent()
  422. */
  423. public function prefers($type = null) {
  424. $accepts = $this->accepts();
  425. if ($type == null) {
  426. if (empty($this->ext)) {
  427. if (is_array($accepts)) {
  428. return $accepts[0];
  429. }
  430. return $accepts;
  431. }
  432. return $this->ext;
  433. }
  434. $types = (array)$type;
  435. if (count($types) === 1) {
  436. if (!empty($this->ext)) {
  437. return ($types[0] == $this->ext);
  438. }
  439. return ($types[0] == $accepts[0]);
  440. }
  441. $intersect = array_values(array_intersect($accepts, $types));
  442. if (empty($intersect)) {
  443. return false;
  444. }
  445. return $intersect[0];
  446. }
  447. /**
  448. * Sets the layout and template paths for the content type defined by $type.
  449. *
  450. * ### Usage:
  451. *
  452. * Render the response as an 'ajax' response.
  453. *
  454. * `$this->RequestHandler->renderAs($this, 'ajax');`
  455. *
  456. * Render the response as an xml file and force the result as a file download.
  457. *
  458. * `$this->RequestHandler->renderAs($this, 'xml', array('attachment' => 'myfile.xml');`
  459. *
  460. * @param object $controller A reference to a controller object
  461. * @param string $type Type of response to send (e.g: 'ajax')
  462. * @param array $options Array of options to use
  463. * @return void
  464. * @see RequestHandlerComponent::setContent()
  465. * @see RequestHandlerComponent::respondAs()
  466. */
  467. public function renderAs($controller, $type, $options = array()) {
  468. $defaults = array('charset' => 'UTF-8');
  469. if (Configure::read('App.encoding') !== null) {
  470. $defaults['charset'] = Configure::read('App.encoding');
  471. }
  472. $options = array_merge($defaults, $options);
  473. if ($type == 'ajax') {
  474. $controller->layout = $this->ajaxLayout;
  475. return $this->respondAs('html', $options);
  476. }
  477. $controller->ext = '.ctp';
  478. if (empty($this->__renderType)) {
  479. $controller->viewPath .= DS . $type;
  480. } else {
  481. $remove = preg_replace("/([\/\\\\]{$this->__renderType})$/", DS . $type, $controller->viewPath);
  482. $controller->viewPath = $remove;
  483. }
  484. $this->__renderType = $type;
  485. $controller->layoutPath = $type;
  486. if ($this->response->getMimeType($type)) {
  487. $this->respondAs($type, $options);
  488. }
  489. $helper = ucfirst($type);
  490. $isAdded = (
  491. in_array($helper, $controller->helpers) ||
  492. array_key_exists($helper, $controller->helpers)
  493. );
  494. if (!$isAdded) {
  495. App::uses($helper . 'Helper', 'View/Helper');
  496. if (class_exists($helper . 'Helper')) {
  497. $controller->helpers[] = $helper;
  498. }
  499. }
  500. }
  501. /**
  502. * Sets the response header based on type map index name. This wraps several methods
  503. * available on CakeResponse. It also allows you to use Content-Type aliases.
  504. *
  505. * @param mixed $type Friendly type name, i.e. 'html' or 'xml', or a full content-type,
  506. * like 'application/x-shockwave'.
  507. * @param array $options If $type is a friendly type name that is associated with
  508. * more than one type of content, $index is used to select which content-type to use.
  509. * @return boolean Returns false if the friendly type name given in $type does
  510. * not exist in the type map, or if the Content-type header has
  511. * already been set by this method.
  512. * @see RequestHandlerComponent::setContent()
  513. */
  514. public function respondAs($type, $options = array()) {
  515. $defaults = array('index' => null, 'charset' => null, 'attachment' => false);
  516. $options = $options + $defaults;
  517. if (strpos($type, '/') === false) {
  518. $cType = $this->response->getMimeType($type);
  519. if ($cType === false) {
  520. return false;
  521. }
  522. if (is_array($cType) && isset($cType[$options['index']])) {
  523. $cType = $cType[$options['index']];
  524. }
  525. if (is_array($cType)) {
  526. if ($this->prefers($cType)) {
  527. $cType = $this->prefers($cType);
  528. } else {
  529. $cType = $cType[0];
  530. }
  531. }
  532. } else {
  533. $cType = $type;
  534. }
  535. if ($cType != null) {
  536. if (empty($this->request->params['requested'])) {
  537. $this->response->type($cType);
  538. }
  539. if (!empty($options['charset'])) {
  540. $this->response->charset($options['charset']);
  541. }
  542. if (!empty($options['attachment'])) {
  543. $this->response->download($options['attachment']);
  544. }
  545. return true;
  546. }
  547. return false;
  548. }
  549. /**
  550. * Returns the current response type (Content-type header), or null if not alias exists
  551. *
  552. * @return mixed A string content type alias, or raw content type if no alias map exists,
  553. * otherwise null
  554. */
  555. public function responseType() {
  556. return $this->mapType($this->response->type());
  557. }
  558. /**
  559. * Maps a content-type back to an alias
  560. *
  561. * @param mixed $cType Either a string content type to map, or an array of types.
  562. * @return mixed Aliases for the types provided.
  563. * @deprecated Use $this->response->mapType() in your controller instead.
  564. */
  565. public function mapType($cType) {
  566. return $this->response->mapType($cType);
  567. }
  568. /**
  569. * Maps a content type alias back to its mime-type(s)
  570. *
  571. * @param mixed $alias String alias to convert back into a content type. Or an array of aliases to map.
  572. * @return mixed Null on an undefined alias. String value of the mapped alias type. If an
  573. * alias maps to more than one content type, the first one will be returned.
  574. */
  575. public function mapAlias($alias) {
  576. if (is_array($alias)) {
  577. return array_map(array($this, 'mapAlias'), $alias);
  578. }
  579. $type = $this->response->getMimeType($alias);
  580. if ($type) {
  581. if (is_array($type)) {
  582. return $type[0];
  583. }
  584. return $type;
  585. }
  586. return null;
  587. }
  588. }