RequestHandlerComponent.php 20 KB

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