RequestHandlerComponent.php 23 KB

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