PageRenderTime 50ms CodeModel.GetById 20ms RepoModel.GetById 1ms app.codeStats 0ms

/lib/Cake/Controller/Component/RequestHandlerComponent.php

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