RequestHandlerComponent.php 20 KB

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