RequestHandlerComponent.php 20 KB

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