RequestHandlerComponent.php 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782
  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 (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  11. *
  12. * Licensed under The MIT License
  13. * For full copyright and license information, please see the LICENSE.txt
  14. * Redistributions of files must retain the above copyright notice.
  15. *
  16. * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  17. * @link http://cakephp.org CakePHP(tm) Project
  18. * @package Cake.Controller.Component
  19. * @since CakePHP(tm) v 0.10.4.1076
  20. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  21. */
  22. App::uses('Component', 'Controller');
  23. App::uses('Xml', 'Utility');
  24. /**
  25. * Request object for handling alternative HTTP requests
  26. *
  27. * Alternative HTTP requests can come from wireless units like mobile phones, palmtop computers,
  28. * and the like. These units have no use for Ajax requests, and this Component can tell how Cake
  29. * should respond to the different needs of a handheld computer and a desktop machine.
  30. *
  31. * @package Cake.Controller.Component
  32. * @link http://book.cakephp.org/2.0/en/core-libraries/components/request-handling.html
  33. *
  34. */
  35. class RequestHandlerComponent extends Component {
  36. /**
  37. * The layout that will be switched to for Ajax requests
  38. *
  39. * @var string
  40. * @see RequestHandler::setAjax()
  41. */
  42. public $ajaxLayout = 'ajax';
  43. /**
  44. * Determines whether or not callbacks will be fired on this component
  45. *
  46. * @var boolean
  47. */
  48. public $enabled = true;
  49. /**
  50. * Holds the reference to Controller::$request
  51. *
  52. * @var CakeRequest
  53. */
  54. public $request;
  55. /**
  56. * Holds the reference to Controller::$response
  57. *
  58. * @var CakeResponse
  59. */
  60. public $response;
  61. /**
  62. * Contains the file extension parsed out by the Router
  63. *
  64. * @var string
  65. * @see Router::parseExtensions()
  66. */
  67. public $ext = null;
  68. /**
  69. * The template to use when rendering the given content type.
  70. *
  71. * @var string
  72. */
  73. protected $_renderType = null;
  74. /**
  75. * A mapping between extensions and deserializers for request bodies of that type.
  76. * By default only JSON and XML are mapped, use RequestHandlerComponent::addInputType()
  77. *
  78. * @var array
  79. */
  80. protected $_inputTypeMap = array(
  81. 'json' => array('json_decode', true)
  82. );
  83. /**
  84. * A mapping between type and viewClass
  85. * By default only JSON and XML are mapped, use RequestHandlerComponent::viewClassMap()
  86. *
  87. * @var array
  88. */
  89. protected $_viewClassMap = array(
  90. 'json' => 'Json',
  91. 'xml' => 'Xml'
  92. );
  93. /**
  94. * Constructor. Parses the accepted content types accepted by the client using HTTP_ACCEPT
  95. *
  96. * @param ComponentCollection $collection ComponentCollection object.
  97. * @param array $settings Array of settings.
  98. */
  99. public function __construct(ComponentCollection $collection, $settings = array()) {
  100. parent::__construct($collection, $settings + array('checkHttpCache' => true));
  101. $this->addInputType('xml', array(array($this, 'convertXml')));
  102. $Controller = $collection->getController();
  103. $this->request = $Controller->request;
  104. $this->response = $Controller->response;
  105. }
  106. /**
  107. * Checks to see if a file extension has been parsed by the Router, or if the
  108. * HTTP_ACCEPT_TYPE has matches only one content type with the supported extensions.
  109. * If there is only one matching type between the supported content types & extensions,
  110. * and the requested mime-types, RequestHandler::$ext is set to that value.
  111. *
  112. * @param Controller $controller A reference to the controller
  113. * @return void
  114. * @see Router::parseExtensions()
  115. */
  116. public function initialize(Controller $controller) {
  117. if (isset($this->request->params['ext'])) {
  118. $this->ext = $this->request->params['ext'];
  119. }
  120. if (empty($this->ext) || $this->ext === 'html') {
  121. $this->_setExtension();
  122. }
  123. $this->params = $controller->params;
  124. if (!empty($this->settings['viewClassMap'])) {
  125. $this->viewClassMap($this->settings['viewClassMap']);
  126. }
  127. }
  128. /**
  129. * Set the extension based on the accept headers.
  130. * Compares the accepted types and configured extensions.
  131. * If there is one common type, that is assigned as the ext/content type
  132. * for the response.
  133. * Type with the highest weight will be set. If the highest weight has more
  134. * then one type matching the extensions, the order in which extensions are specified
  135. * determines which type will be set.
  136. *
  137. * If html is one of the preferred types, no content type will be set, this
  138. * is to avoid issues with browsers that prefer html and several other content types.
  139. *
  140. * @return void
  141. */
  142. protected function _setExtension() {
  143. $accept = $this->request->parseAccept();
  144. if (empty($accept)) {
  145. return;
  146. }
  147. $accepts = $this->response->mapType($accept);
  148. $preferedTypes = current($accepts);
  149. if (array_intersect($preferedTypes, array('html', 'xhtml'))) {
  150. return null;
  151. }
  152. $extensions = Router::extensions();
  153. foreach ($accepts as $types) {
  154. $ext = array_intersect($extensions, $types);
  155. if ($ext) {
  156. $this->ext = current($ext);
  157. break;
  158. }
  159. }
  160. }
  161. /**
  162. * The startup method of the RequestHandler enables several automatic behaviors
  163. * related to the detection of certain properties of the HTTP request, including:
  164. *
  165. * - Disabling layout rendering for Ajax requests (based on the HTTP_X_REQUESTED_WITH header)
  166. * - If Router::parseExtensions() is enabled, the layout and template type are
  167. * switched based on the parsed extension or Accept-Type header. For example, if `controller/action.xml`
  168. * is requested, the view path becomes `app/View/Controller/xml/action.ctp`. Also if
  169. * `controller/action` is requested with `Accept-Type: application/xml` in the headers
  170. * the view path will become `app/View/Controller/xml/action.ctp`. Layout and template
  171. * types will only switch to mime-types recognized by CakeResponse. If you need to declare
  172. * additional mime-types, you can do so using CakeResponse::type() in your controllers beforeFilter()
  173. * method.
  174. * - If a helper with the same name as the extension exists, it is added to the controller.
  175. * - If the extension is of a type that RequestHandler understands, it will set that
  176. * Content-type in the response header.
  177. * - If the XML data is POSTed, the data is parsed into an XML object, which is assigned
  178. * to the $data property of the controller, which can then be saved to a model object.
  179. *
  180. * @param Controller $controller A reference to the controller
  181. * @return void
  182. */
  183. public function startup(Controller $controller) {
  184. $controller->request->params['isAjax'] = $this->request->is('ajax');
  185. $isRecognized = (
  186. !in_array($this->ext, array('html', 'htm')) &&
  187. $this->response->getMimeType($this->ext)
  188. );
  189. if (!empty($this->ext) && $isRecognized) {
  190. $this->renderAs($controller, $this->ext);
  191. } elseif ($this->request->is('ajax')) {
  192. $this->renderAs($controller, 'ajax');
  193. } elseif (empty($this->ext) || in_array($this->ext, array('html', 'htm'))) {
  194. $this->respondAs('html', array('charset' => Configure::read('App.encoding')));
  195. }
  196. foreach ($this->_inputTypeMap as $type => $handler) {
  197. if ($this->requestedWith($type)) {
  198. $input = call_user_func_array(array($controller->request, 'input'), $handler);
  199. $controller->request->data = $input;
  200. }
  201. }
  202. }
  203. /**
  204. * Helper method to parse xml input data, due to lack of anonymous functions
  205. * this lives here.
  206. *
  207. * @param string $xml
  208. * @return array Xml array data
  209. */
  210. public function convertXml($xml) {
  211. try {
  212. $xml = Xml::build($xml);
  213. if (isset($xml->data)) {
  214. return Xml::toArray($xml->data);
  215. }
  216. return Xml::toArray($xml);
  217. } catch (XmlException $e) {
  218. return array();
  219. }
  220. }
  221. /**
  222. * Handles (fakes) redirects for Ajax requests using requestAction()
  223. * Modifies the $_POST and $_SERVER['REQUEST_METHOD'] to simulate a new GET request.
  224. *
  225. * @param Controller $controller A reference to the controller
  226. * @param string|array $url A string or array containing the redirect location
  227. * @param integer|array $status HTTP Status for redirect
  228. * @param boolean $exit
  229. * @return void
  230. */
  231. public function beforeRedirect(Controller $controller, $url, $status = null, $exit = true) {
  232. if (!$this->request->is('ajax')) {
  233. return;
  234. }
  235. if (empty($url)) {
  236. return;
  237. }
  238. $_SERVER['REQUEST_METHOD'] = 'GET';
  239. foreach ($_POST as $key => $val) {
  240. unset($_POST[$key]);
  241. }
  242. if (is_array($url)) {
  243. $url = Router::url($url + array('base' => false));
  244. }
  245. if (!empty($status)) {
  246. $statusCode = $this->response->httpCodes($status);
  247. $code = key($statusCode);
  248. $this->response->statusCode($code);
  249. }
  250. $this->response->body($this->requestAction($url, array('return', 'bare' => false)));
  251. $this->response->send();
  252. $this->_stop();
  253. }
  254. /**
  255. * Checks if the response can be considered different according to the request
  256. * headers, and the caching response headers. If it was not modified, then the
  257. * render process is skipped. And the client will get a blank response with a
  258. * "304 Not Modified" header.
  259. *
  260. * @params Controller $controller
  261. * @return boolean false if the render process should be aborted
  262. */
  263. public function beforeRender(Controller $controller) {
  264. if ($this->settings['checkHttpCache'] && $this->response->checkNotModified($this->request)) {
  265. return false;
  266. }
  267. }
  268. /**
  269. * Returns true if the current HTTP request is Ajax, false otherwise
  270. *
  271. * @return boolean True if call is Ajax
  272. * @deprecated use `$this->request->is('ajax')` instead.
  273. */
  274. public function isAjax() {
  275. return $this->request->is('ajax');
  276. }
  277. /**
  278. * Returns true if the current HTTP request is coming from a Flash-based client
  279. *
  280. * @return boolean True if call is from Flash
  281. * @deprecated use `$this->request->is('flash')` instead.
  282. */
  283. public function isFlash() {
  284. return $this->request->is('flash');
  285. }
  286. /**
  287. * Returns true if the current request is over HTTPS, false otherwise.
  288. *
  289. * @return boolean True if call is over HTTPS
  290. * @deprecated use `$this->request->is('ssl')` instead.
  291. */
  292. public function isSSL() {
  293. return $this->request->is('ssl');
  294. }
  295. /**
  296. * Returns true if the current call accepts an XML response, false otherwise
  297. *
  298. * @return boolean True if client accepts an XML response
  299. */
  300. public function isXml() {
  301. return $this->prefers('xml');
  302. }
  303. /**
  304. * Returns true if the current call accepts an RSS response, false otherwise
  305. *
  306. * @return boolean True if client accepts an RSS response
  307. */
  308. public function isRss() {
  309. return $this->prefers('rss');
  310. }
  311. /**
  312. * Returns true if the current call accepts an Atom response, false otherwise
  313. *
  314. * @return boolean True if client accepts an RSS response
  315. */
  316. public function isAtom() {
  317. return $this->prefers('atom');
  318. }
  319. /**
  320. * Returns true if user agent string matches a mobile web browser, or if the
  321. * client accepts WAP content.
  322. *
  323. * @return boolean True if user agent is a mobile web browser
  324. */
  325. public function isMobile() {
  326. return $this->request->is('mobile') || $this->accepts('wap');
  327. }
  328. /**
  329. * Returns true if the client accepts WAP content
  330. *
  331. * @return boolean
  332. */
  333. public function isWap() {
  334. return $this->prefers('wap');
  335. }
  336. /**
  337. * Returns true if the current call a POST request
  338. *
  339. * @return boolean True if call is a POST
  340. * @deprecated Use $this->request->is('post'); from your controller.
  341. */
  342. public function isPost() {
  343. return $this->request->is('post');
  344. }
  345. /**
  346. * Returns true if the current call a PUT request
  347. *
  348. * @return boolean True if call is a PUT
  349. * @deprecated Use $this->request->is('put'); from your controller.
  350. */
  351. public function isPut() {
  352. return $this->request->is('put');
  353. }
  354. /**
  355. * Returns true if the current call a GET request
  356. *
  357. * @return boolean True if call is a GET
  358. * @deprecated Use $this->request->is('get'); from your controller.
  359. */
  360. public function isGet() {
  361. return $this->request->is('get');
  362. }
  363. /**
  364. * Returns true if the current call a DELETE request
  365. *
  366. * @return boolean True if call is a DELETE
  367. * @deprecated Use $this->request->is('delete'); from your controller.
  368. */
  369. public function isDelete() {
  370. return $this->request->is('delete');
  371. }
  372. /**
  373. * Gets Prototype version if call is Ajax, otherwise empty string.
  374. * The Prototype library sets a special "Prototype version" HTTP header.
  375. *
  376. * @return string|boolean When Ajax the prototype version of component making the call otherwise false
  377. */
  378. public function getAjaxVersion() {
  379. $httpX = env('HTTP_X_PROTOTYPE_VERSION');
  380. return ($httpX === null) ? false : $httpX;
  381. }
  382. /**
  383. * Adds/sets the Content-type(s) for the given name. This method allows
  384. * content-types to be mapped to friendly aliases (or extensions), which allows
  385. * RequestHandler to automatically respond to requests of that type in the
  386. * startup method.
  387. *
  388. * @param string $name The name of the Content-type, i.e. "html", "xml", "css"
  389. * @param string|array $type The Content-type or array of Content-types assigned to the name,
  390. * i.e. "text/html", or "application/xml"
  391. * @return void
  392. * @deprecated use `$this->response->type()` instead.
  393. */
  394. public function setContent($name, $type = null) {
  395. $this->response->type(array($name => $type));
  396. }
  397. /**
  398. * Gets the server name from which this request was referred
  399. *
  400. * @return string Server address
  401. * @deprecated use $this->request->referer() from your controller instead
  402. */
  403. public function getReferer() {
  404. return $this->request->referer(false);
  405. }
  406. /**
  407. * Gets remote client IP
  408. *
  409. * @param boolean $safe
  410. * @return string Client IP address
  411. * @deprecated use $this->request->clientIp() from your, controller instead.
  412. */
  413. public function getClientIP($safe = true) {
  414. return $this->request->clientIp($safe);
  415. }
  416. /**
  417. * Determines which content types the client accepts. Acceptance is based on
  418. * the file extension parsed by the Router (if present), and by the HTTP_ACCEPT
  419. * header. Unlike CakeRequest::accepts() this method deals entirely with mapped content types.
  420. *
  421. * Usage:
  422. *
  423. * `$this->RequestHandler->accepts(array('xml', 'html', 'json'));`
  424. *
  425. * Returns true if the client accepts any of the supplied types.
  426. *
  427. * `$this->RequestHandler->accepts('xml');`
  428. *
  429. * Returns true if the client accepts xml.
  430. *
  431. * @param string|array $type Can be null (or no parameter), a string type name, or an
  432. * array of types
  433. * @return mixed If null or no parameter is passed, returns an array of content
  434. * types the client accepts. If a string is passed, returns true
  435. * if the client accepts it. If an array is passed, returns true
  436. * if the client accepts one or more elements in the array.
  437. * @see RequestHandlerComponent::setContent()
  438. */
  439. public function accepts($type = null) {
  440. $accepted = $this->request->accepts();
  441. if (!$type) {
  442. return $this->mapType($accepted);
  443. }
  444. if (is_array($type)) {
  445. foreach ($type as $t) {
  446. $t = $this->mapAlias($t);
  447. if (in_array($t, $accepted)) {
  448. return true;
  449. }
  450. }
  451. return false;
  452. }
  453. if (is_string($type)) {
  454. return in_array($this->mapAlias($type), $accepted);
  455. }
  456. return false;
  457. }
  458. /**
  459. * Determines the content type of the data the client has sent (i.e. in a POST request)
  460. *
  461. * @param string|array $type Can be null (or no parameter), a string type name, or an array of types
  462. * @return mixed If a single type is supplied a boolean will be returned. If no type is provided
  463. * The mapped value of CONTENT_TYPE will be returned. If an array is supplied the first type
  464. * in the request content type will be returned.
  465. */
  466. public function requestedWith($type = null) {
  467. if (!$this->request->is('post') && !$this->request->is('put')) {
  468. return null;
  469. }
  470. if (is_array($type)) {
  471. foreach ($type as $t) {
  472. if ($this->requestedWith($t)) {
  473. return $t;
  474. }
  475. }
  476. return false;
  477. }
  478. list($contentType) = explode(';', env('CONTENT_TYPE'));
  479. if ($contentType === '') {
  480. list($contentType) = explode(';', CakeRequest::header('CONTENT_TYPE'));
  481. }
  482. if (!$type) {
  483. return $this->mapType($contentType);
  484. }
  485. if (is_string($type)) {
  486. return ($type == $this->mapType($contentType));
  487. }
  488. }
  489. /**
  490. * Determines which content-types the client prefers. If no parameters are given,
  491. * the single content-type that the client most likely prefers is returned. If $type is
  492. * an array, the first item in the array that the client accepts is returned.
  493. * Preference is determined primarily by the file extension parsed by the Router
  494. * if provided, and secondarily by the list of content-types provided in
  495. * HTTP_ACCEPT.
  496. *
  497. * @param string|array $type An optional array of 'friendly' content-type names, i.e.
  498. * 'html', 'xml', 'js', etc.
  499. * @return mixed If $type is null or not provided, the first content-type in the
  500. * list, based on preference, is returned. If a single type is provided
  501. * a boolean will be returned if that type is preferred.
  502. * If an array of types are provided then the first preferred type is returned.
  503. * If no type is provided the first preferred type is returned.
  504. * @see RequestHandlerComponent::setContent()
  505. */
  506. public function prefers($type = null) {
  507. $acceptRaw = $this->request->parseAccept();
  508. if (empty($acceptRaw)) {
  509. return $this->ext;
  510. }
  511. $accepts = $this->mapType(array_shift($acceptRaw));
  512. if (!$type) {
  513. if (empty($this->ext) && !empty($accepts)) {
  514. return $accepts[0];
  515. }
  516. return $this->ext;
  517. }
  518. $types = (array)$type;
  519. if (count($types) === 1) {
  520. if (!empty($this->ext)) {
  521. return in_array($this->ext, $types);
  522. }
  523. return in_array($types[0], $accepts);
  524. }
  525. $intersect = array_values(array_intersect($accepts, $types));
  526. if (empty($intersect)) {
  527. return false;
  528. }
  529. return $intersect[0];
  530. }
  531. /**
  532. * Sets the layout and template paths for the content type defined by $type.
  533. *
  534. * ### Usage:
  535. *
  536. * Render the response as an 'ajax' response.
  537. *
  538. * `$this->RequestHandler->renderAs($this, 'ajax');`
  539. *
  540. * Render the response as an xml file and force the result as a file download.
  541. *
  542. * `$this->RequestHandler->renderAs($this, 'xml', array('attachment' => 'myfile.xml');`
  543. *
  544. * @param Controller $controller A reference to a controller object
  545. * @param string $type Type of response to send (e.g: 'ajax')
  546. * @param array $options Array of options to use
  547. * @return void
  548. * @see RequestHandlerComponent::setContent()
  549. * @see RequestHandlerComponent::respondAs()
  550. */
  551. public function renderAs(Controller $controller, $type, $options = array()) {
  552. $defaults = array('charset' => 'UTF-8');
  553. if (Configure::read('App.encoding') !== null) {
  554. $defaults['charset'] = Configure::read('App.encoding');
  555. }
  556. $options = array_merge($defaults, $options);
  557. if ($type === 'ajax') {
  558. $controller->layout = $this->ajaxLayout;
  559. return $this->respondAs('html', $options);
  560. }
  561. $pluginDot = null;
  562. $viewClassMap = $this->viewClassMap();
  563. if (array_key_exists($type, $viewClassMap)) {
  564. list($pluginDot, $viewClass) = pluginSplit($viewClassMap[$type], true);
  565. } else {
  566. $viewClass = Inflector::classify($type);
  567. }
  568. $viewName = $viewClass . 'View';
  569. if (!class_exists($viewName)) {
  570. App::uses($viewName, $pluginDot . 'View');
  571. }
  572. if (class_exists($viewName)) {
  573. $controller->viewClass = $viewClass;
  574. } elseif (empty($this->_renderType)) {
  575. $controller->viewPath .= DS . $type;
  576. } else {
  577. $controller->viewPath = preg_replace(
  578. "/([\/\\\\]{$this->_renderType})$/",
  579. DS . $type,
  580. $controller->viewPath
  581. );
  582. }
  583. $this->_renderType = $type;
  584. $controller->layoutPath = $type;
  585. if ($this->response->getMimeType($type)) {
  586. $this->respondAs($type, $options);
  587. }
  588. $helper = ucfirst($type);
  589. if (!in_array($helper, $controller->helpers) && empty($controller->helpers[$helper])) {
  590. App::uses('AppHelper', 'View/Helper');
  591. App::uses($helper . 'Helper', 'View/Helper');
  592. if (class_exists($helper . 'Helper')) {
  593. $controller->helpers[] = $helper;
  594. }
  595. }
  596. }
  597. /**
  598. * Sets the response header based on type map index name. This wraps several methods
  599. * available on CakeResponse. It also allows you to use Content-Type aliases.
  600. *
  601. * @param string|array $type Friendly type name, i.e. 'html' or 'xml', or a full content-type,
  602. * like 'application/x-shockwave'.
  603. * @param array $options If $type is a friendly type name that is associated with
  604. * more than one type of content, $index is used to select which content-type to use.
  605. * @return boolean Returns false if the friendly type name given in $type does
  606. * not exist in the type map, or if the Content-type header has
  607. * already been set by this method.
  608. * @see RequestHandlerComponent::setContent()
  609. */
  610. public function respondAs($type, $options = array()) {
  611. $defaults = array('index' => null, 'charset' => null, 'attachment' => false);
  612. $options = $options + $defaults;
  613. $cType = $type;
  614. if (strpos($type, '/') === false) {
  615. $cType = $this->response->getMimeType($type);
  616. }
  617. if (is_array($cType)) {
  618. if (isset($cType[$options['index']])) {
  619. $cType = $cType[$options['index']];
  620. }
  621. if ($this->prefers($cType)) {
  622. $cType = $this->prefers($cType);
  623. } else {
  624. $cType = $cType[0];
  625. }
  626. }
  627. if (!$type) {
  628. return false;
  629. }
  630. if (empty($this->request->params['requested'])) {
  631. $this->response->type($cType);
  632. }
  633. if (!empty($options['charset'])) {
  634. $this->response->charset($options['charset']);
  635. }
  636. if (!empty($options['attachment'])) {
  637. $this->response->download($options['attachment']);
  638. }
  639. return true;
  640. }
  641. /**
  642. * Returns the current response type (Content-type header), or null if not alias exists
  643. *
  644. * @return mixed A string content type alias, or raw content type if no alias map exists,
  645. * otherwise null
  646. */
  647. public function responseType() {
  648. return $this->mapType($this->response->type());
  649. }
  650. /**
  651. * Maps a content-type back to an alias
  652. *
  653. * @param string|array $cType Either a string content type to map, or an array of types.
  654. * @return string|array Aliases for the types provided.
  655. * @deprecated Use $this->response->mapType() in your controller instead.
  656. */
  657. public function mapType($cType) {
  658. return $this->response->mapType($cType);
  659. }
  660. /**
  661. * Maps a content type alias back to its mime-type(s)
  662. *
  663. * @param string|array $alias String alias to convert back into a content type. Or an array of aliases to map.
  664. * @return string Null on an undefined alias. String value of the mapped alias type. If an
  665. * alias maps to more than one content type, the first one will be returned.
  666. */
  667. public function mapAlias($alias) {
  668. if (is_array($alias)) {
  669. return array_map(array($this, 'mapAlias'), $alias);
  670. }
  671. $type = $this->response->getMimeType($alias);
  672. if ($type) {
  673. if (is_array($type)) {
  674. return $type[0];
  675. }
  676. return $type;
  677. }
  678. return null;
  679. }
  680. /**
  681. * Add a new mapped input type. Mapped input types are automatically
  682. * converted by RequestHandlerComponent during the startup() callback.
  683. *
  684. * @param string $type The type alias being converted, ie. json
  685. * @param array $handler The handler array for the type. The first index should
  686. * be the handling callback, all other arguments should be additional parameters
  687. * for the handler.
  688. * @return void
  689. * @throws CakeException
  690. */
  691. public function addInputType($type, $handler) {
  692. if (!is_array($handler) || !isset($handler[0]) || !is_callable($handler[0])) {
  693. throw new CakeException(__d('cake_dev', 'You must give a handler callback.'));
  694. }
  695. $this->_inputTypeMap[$type] = $handler;
  696. }
  697. /**
  698. * Getter/setter for viewClassMap
  699. *
  700. * @param array|string $type The type string or array with format `array('type' => 'viewClass')` to map one or more
  701. * @param array $viewClass The viewClass to be used for the type without `View` appended
  702. * @return array|string Returns viewClass when only string $type is set, else array with viewClassMap
  703. */
  704. public function viewClassMap($type = null, $viewClass = null) {
  705. if (!$viewClass && is_string($type) && isset($this->_viewClassMap[$type])) {
  706. return $this->_viewClassMap[$type];
  707. }
  708. if (is_string($type)) {
  709. $this->_viewClassMap[$type] = $viewClass;
  710. } elseif (is_array($type)) {
  711. foreach ($type as $key => $value) {
  712. $this->viewClassMap($key, $value);
  713. }
  714. }
  715. return $this->_viewClassMap;
  716. }
  717. }