RequestHandlerComponent.php 24 KB

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