RequestHandlerComponent.php 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783
  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 bool
  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 XML string.
  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 int|array $status HTTP Status for redirect
  228. * @param bool $exit Whether to exit script, defaults to `true`.
  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. * @param Controller $controller Controller instance.
  261. * @return bool 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 bool 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 bool 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 bool 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 bool 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 bool 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 bool 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 bool 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 bool
  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 bool 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 bool 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 bool 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 bool 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|bool 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 bool $safe Use safe = false when you think the user might manipulate
  410. * their HTTP_CLIENT_IP header. Setting $safe = false will also look at HTTP_X_FORWARDED_FOR
  411. * @return string Client IP address
  412. * @deprecated use $this->request->clientIp() from your, controller instead.
  413. */
  414. public function getClientIP($safe = true) {
  415. return $this->request->clientIp($safe);
  416. }
  417. /**
  418. * Determines which content types the client accepts. Acceptance is based on
  419. * the file extension parsed by the Router (if present), and by the HTTP_ACCEPT
  420. * header. Unlike CakeRequest::accepts() this method deals entirely with mapped content types.
  421. *
  422. * Usage:
  423. *
  424. * `$this->RequestHandler->accepts(array('xml', 'html', 'json'));`
  425. *
  426. * Returns true if the client accepts any of the supplied types.
  427. *
  428. * `$this->RequestHandler->accepts('xml');`
  429. *
  430. * Returns true if the client accepts xml.
  431. *
  432. * @param string|array $type Can be null (or no parameter), a string type name, or an
  433. * array of types
  434. * @return mixed If null or no parameter is passed, returns an array of content
  435. * types the client accepts. If a string is passed, returns true
  436. * if the client accepts it. If an array is passed, returns true
  437. * if the client accepts one or more elements in the array.
  438. * @see RequestHandlerComponent::setContent()
  439. */
  440. public function accepts($type = null) {
  441. $accepted = $this->request->accepts();
  442. if (!$type) {
  443. return $this->mapType($accepted);
  444. }
  445. if (is_array($type)) {
  446. foreach ($type as $t) {
  447. $t = $this->mapAlias($t);
  448. if (in_array($t, $accepted)) {
  449. return true;
  450. }
  451. }
  452. return false;
  453. }
  454. if (is_string($type)) {
  455. return in_array($this->mapAlias($type), $accepted);
  456. }
  457. return false;
  458. }
  459. /**
  460. * Determines the content type of the data the client has sent (i.e. in a POST request)
  461. *
  462. * @param string|array $type Can be null (or no parameter), a string type name, or an array of types
  463. * @return mixed If a single type is supplied a boolean will be returned. If no type is provided
  464. * The mapped value of CONTENT_TYPE will be returned. If an array is supplied the first type
  465. * in the request content type will be returned.
  466. */
  467. public function requestedWith($type = null) {
  468. if (!$this->request->is('post') && !$this->request->is('put')) {
  469. return null;
  470. }
  471. if (is_array($type)) {
  472. foreach ($type as $t) {
  473. if ($this->requestedWith($t)) {
  474. return $t;
  475. }
  476. }
  477. return false;
  478. }
  479. list($contentType) = explode(';', env('CONTENT_TYPE'));
  480. if ($contentType === '') {
  481. list($contentType) = explode(';', CakeRequest::header('CONTENT_TYPE'));
  482. }
  483. if (!$type) {
  484. return $this->mapType($contentType);
  485. }
  486. if (is_string($type)) {
  487. return ($type === $this->mapType($contentType));
  488. }
  489. }
  490. /**
  491. * Determines which content-types the client prefers. If no parameters are given,
  492. * the single content-type that the client most likely prefers is returned. If $type is
  493. * an array, the first item in the array that the client accepts is returned.
  494. * Preference is determined primarily by the file extension parsed by the Router
  495. * if provided, and secondarily by the list of content-types provided in
  496. * HTTP_ACCEPT.
  497. *
  498. * @param string|array $type An optional array of 'friendly' content-type names, i.e.
  499. * 'html', 'xml', 'js', etc.
  500. * @return mixed If $type is null or not provided, the first content-type in the
  501. * list, based on preference, is returned. If a single type is provided
  502. * a boolean will be returned if that type is preferred.
  503. * If an array of types are provided then the first preferred type is returned.
  504. * If no type is provided the first preferred type is returned.
  505. * @see RequestHandlerComponent::setContent()
  506. */
  507. public function prefers($type = null) {
  508. $acceptRaw = $this->request->parseAccept();
  509. if (empty($acceptRaw)) {
  510. return $this->ext;
  511. }
  512. $accepts = $this->mapType(array_shift($acceptRaw));
  513. if (!$type) {
  514. if (empty($this->ext) && !empty($accepts)) {
  515. return $accepts[0];
  516. }
  517. return $this->ext;
  518. }
  519. $types = (array)$type;
  520. if (count($types) === 1) {
  521. if (!empty($this->ext)) {
  522. return in_array($this->ext, $types);
  523. }
  524. return in_array($types[0], $accepts);
  525. }
  526. $intersect = array_values(array_intersect($accepts, $types));
  527. if (empty($intersect)) {
  528. return false;
  529. }
  530. return $intersect[0];
  531. }
  532. /**
  533. * Sets the layout and template paths for the content type defined by $type.
  534. *
  535. * ### Usage:
  536. *
  537. * Render the response as an 'ajax' response.
  538. *
  539. * `$this->RequestHandler->renderAs($this, 'ajax');`
  540. *
  541. * Render the response as an xml file and force the result as a file download.
  542. *
  543. * `$this->RequestHandler->renderAs($this, 'xml', array('attachment' => 'myfile.xml');`
  544. *
  545. * @param Controller $controller A reference to a controller object
  546. * @param string $type Type of response to send (e.g: 'ajax')
  547. * @param array $options Array of options to use
  548. * @return void
  549. * @see RequestHandlerComponent::setContent()
  550. * @see RequestHandlerComponent::respondAs()
  551. */
  552. public function renderAs(Controller $controller, $type, $options = array()) {
  553. $defaults = array('charset' => 'UTF-8');
  554. if (Configure::read('App.encoding') !== null) {
  555. $defaults['charset'] = Configure::read('App.encoding');
  556. }
  557. $options += $defaults;
  558. if ($type === 'ajax') {
  559. $controller->layout = $this->ajaxLayout;
  560. return $this->respondAs('html', $options);
  561. }
  562. $pluginDot = null;
  563. $viewClassMap = $this->viewClassMap();
  564. if (array_key_exists($type, $viewClassMap)) {
  565. list($pluginDot, $viewClass) = pluginSplit($viewClassMap[$type], true);
  566. } else {
  567. $viewClass = Inflector::classify($type);
  568. }
  569. $viewName = $viewClass . 'View';
  570. if (!class_exists($viewName)) {
  571. App::uses($viewName, $pluginDot . 'View');
  572. }
  573. if (class_exists($viewName)) {
  574. $controller->viewClass = $viewClass;
  575. } elseif (empty($this->_renderType)) {
  576. $controller->viewPath .= DS . $type;
  577. } else {
  578. $controller->viewPath = preg_replace(
  579. "/([\/\\\\]{$this->_renderType})$/",
  580. DS . $type,
  581. $controller->viewPath
  582. );
  583. }
  584. $this->_renderType = $type;
  585. $controller->layoutPath = $type;
  586. if ($this->response->getMimeType($type)) {
  587. $this->respondAs($type, $options);
  588. }
  589. $helper = ucfirst($type);
  590. if (!in_array($helper, $controller->helpers) && empty($controller->helpers[$helper])) {
  591. App::uses('AppHelper', 'View/Helper');
  592. App::uses($helper . 'Helper', 'View/Helper');
  593. if (class_exists($helper . 'Helper')) {
  594. $controller->helpers[] = $helper;
  595. }
  596. }
  597. }
  598. /**
  599. * Sets the response header based on type map index name. This wraps several methods
  600. * available on CakeResponse. It also allows you to use Content-Type aliases.
  601. *
  602. * @param string|array $type Friendly type name, i.e. 'html' or 'xml', or a full content-type,
  603. * like 'application/x-shockwave'.
  604. * @param array $options If $type is a friendly type name that is associated with
  605. * more than one type of content, $index is used to select which content-type to use.
  606. * @return bool Returns false if the friendly type name given in $type does
  607. * not exist in the type map, or if the Content-type header has
  608. * already been set by this method.
  609. * @see RequestHandlerComponent::setContent()
  610. */
  611. public function respondAs($type, $options = array()) {
  612. $defaults = array('index' => null, 'charset' => null, 'attachment' => false);
  613. $options = $options + $defaults;
  614. $cType = $type;
  615. if (strpos($type, '/') === false) {
  616. $cType = $this->response->getMimeType($type);
  617. }
  618. if (is_array($cType)) {
  619. if (isset($cType[$options['index']])) {
  620. $cType = $cType[$options['index']];
  621. }
  622. if ($this->prefers($cType)) {
  623. $cType = $this->prefers($cType);
  624. } else {
  625. $cType = $cType[0];
  626. }
  627. }
  628. if (!$type) {
  629. return false;
  630. }
  631. if (empty($this->request->params['requested'])) {
  632. $this->response->type($cType);
  633. }
  634. if (!empty($options['charset'])) {
  635. $this->response->charset($options['charset']);
  636. }
  637. if (!empty($options['attachment'])) {
  638. $this->response->download($options['attachment']);
  639. }
  640. return true;
  641. }
  642. /**
  643. * Returns the current response type (Content-type header), or null if not alias exists
  644. *
  645. * @return mixed A string content type alias, or raw content type if no alias map exists,
  646. * otherwise null
  647. */
  648. public function responseType() {
  649. return $this->mapType($this->response->type());
  650. }
  651. /**
  652. * Maps a content-type back to an alias
  653. *
  654. * @param string|array $cType Either a string content type to map, or an array of types.
  655. * @return string|array Aliases for the types provided.
  656. * @deprecated Use $this->response->mapType() in your controller instead.
  657. */
  658. public function mapType($cType) {
  659. return $this->response->mapType($cType);
  660. }
  661. /**
  662. * Maps a content type alias back to its mime-type(s)
  663. *
  664. * @param string|array $alias String alias to convert back into a content type. Or an array of aliases to map.
  665. * @return string Null on an undefined alias. String value of the mapped alias type. If an
  666. * alias maps to more than one content type, the first one will be returned.
  667. */
  668. public function mapAlias($alias) {
  669. if (is_array($alias)) {
  670. return array_map(array($this, 'mapAlias'), $alias);
  671. }
  672. $type = $this->response->getMimeType($alias);
  673. if ($type) {
  674. if (is_array($type)) {
  675. return $type[0];
  676. }
  677. return $type;
  678. }
  679. return null;
  680. }
  681. /**
  682. * Add a new mapped input type. Mapped input types are automatically
  683. * converted by RequestHandlerComponent during the startup() callback.
  684. *
  685. * @param string $type The type alias being converted, ie. json
  686. * @param array $handler The handler array for the type. The first index should
  687. * be the handling callback, all other arguments should be additional parameters
  688. * for the handler.
  689. * @return void
  690. * @throws CakeException
  691. */
  692. public function addInputType($type, $handler) {
  693. if (!is_array($handler) || !isset($handler[0]) || !is_callable($handler[0])) {
  694. throw new CakeException(__d('cake_dev', 'You must give a handler callback.'));
  695. }
  696. $this->_inputTypeMap[$type] = $handler;
  697. }
  698. /**
  699. * Getter/setter for viewClassMap
  700. *
  701. * @param array|string $type The type string or array with format `array('type' => 'viewClass')` to map one or more
  702. * @param array $viewClass The viewClass to be used for the type without `View` appended
  703. * @return array|string Returns viewClass when only string $type is set, else array with viewClassMap
  704. */
  705. public function viewClassMap($type = null, $viewClass = null) {
  706. if (!$viewClass && is_string($type) && isset($this->_viewClassMap[$type])) {
  707. return $this->_viewClassMap[$type];
  708. }
  709. if (is_string($type)) {
  710. $this->_viewClassMap[$type] = $viewClass;
  711. } elseif (is_array($type)) {
  712. foreach ($type as $key => $value) {
  713. $this->viewClassMap($key, $value);
  714. }
  715. }
  716. return $this->_viewClassMap;
  717. }
  718. }