RequestHandlerComponent.php 20 KB

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