RequestHandlerComponent.php 20 KB

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