RequestHandlerComponent.php 21 KB

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