Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
tree: 93eb8c2c58
Fetching contributors…

Octocat-spinner-32-eaf2f5

Cannot retrieve contributors at this time

file 732 lines (670 sloc) 22.916 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731
<?php
/**
* Request object for handling alternative HTTP requests
*
* Alternative HTTP requests can come from wireless units like mobile phones, palmtop computers,
* and the like. These units have no use for Ajax requests, and this Component can tell how Cake
* should respond to the different needs of a handheld computer and a desktop machine.
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package Cake.Controller.Component
* @since CakePHP(tm) v 0.10.4.1076
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/

App::uses('Component', 'Controller');
App::uses('Xml', 'Utility');

/**
* Request object for handling alternative HTTP requests
*
* Alternative HTTP requests can come from wireless units like mobile phones, palmtop computers,
* and the like. These units have no use for Ajax requests, and this Component can tell how Cake
* should respond to the different needs of a handheld computer and a desktop machine.
*
* @package Cake.Controller.Component
* @link http://book.cakephp.org/2.0/en/core-libraries/components/request-handling.html
*
*/
class RequestHandlerComponent extends Component {

/**
* The layout that will be switched to for Ajax requests
*
* @var string
* @see RequestHandler::setAjax()
*/
public $ajaxLayout = 'ajax';

/**
* Determines whether or not callbacks will be fired on this component
*
* @var boolean
*/
public $enabled = true;

/**
* Holds the reference to Controller::$request
*
* @var CakeRequest
*/
public $request;

/**
* Holds the reference to Controller::$response
*
* @var CakeResponse
*/
public $response;

/**
* Contains the file extension parsed out by the Router
*
* @var string
* @see Router::parseExtensions()
*/
public $ext = null;

/**
* The template to use when rendering the given content type.
*
* @var string
*/
protected $_renderType = null;

/**
* A mapping between extensions and deserializers for request bodies of that type.
* By default only JSON and XML are mapped, use RequestHandlerComponent::addInputType()
*
* @var array
*/
protected $_inputTypeMap = array(
'json' => array('json_decode', true)
);

/**
* Constructor. Parses the accepted content types accepted by the client using HTTP_ACCEPT
*
* @param ComponentCollection $collection ComponentCollection object.
* @param array $settings Array of settings.
*/
public function __construct(ComponentCollection $collection, $settings = array()) {
$default = array('checkHttpCache' => true);
parent::__construct($collection, $settings + $default);
$this->addInputType('xml', array(array($this, 'convertXml')));

$Controller = $collection->getController();
$this->request = $Controller->request;
$this->response = $Controller->response;
}

/**
* Checks to see if a file extension has been parsed by the Router, or if the
* HTTP_ACCEPT_TYPE has matches only one content type with the supported extensions.
* If there is only one matching type between the supported content types & extensions,
* and the requested mime-types, RequestHandler::$ext is set to that value.
*
* @param Controller $controller A reference to the controller
* @param array $settings Array of settings to _set().
* @return void
* @see Router::parseExtensions()
*/
public function initialize(Controller $controller, $settings = array()) {
if (isset($this->request->params['ext'])) {
$this->ext = $this->request->params['ext'];
}
if (empty($this->ext) || $this->ext == 'html') {
$this->_setExtension();
}
$this->params = $controller->params;
$this->_set($settings);
}

/**
* Set the extension based on the accept headers.
* Compares the accepted types and configured extensions.
* If there is one common type, that is assigned as the ext/content type
* for the response.
*
* If html is one of the preferred types, no content type will be set, this
* is to avoid issues with browsers that prefer html and several other content types.
*
* @return void
*/
protected function _setExtension() {
$accept = $this->request->parseAccept();
if (empty($accept)) {
return;
}
$extensions = Router::extensions();
$preferred = array_shift($accept);
$preferredTypes = $this->response->mapType($preferred);
$similarTypes = array_intersect($extensions, $preferredTypes);
if (count($similarTypes) === 1 && !in_array('xhtml', $preferredTypes) && !in_array('html', $preferredTypes)) {
$this->ext = array_shift($similarTypes);
}
}

/**
* The startup method of the RequestHandler enables several automatic behaviors
* related to the detection of certain properties of the HTTP request, including:
*
* - Disabling layout rendering for Ajax requests (based on the HTTP_X_REQUESTED_WITH header)
* - If Router::parseExtensions() is enabled, the layout and template type are
* switched based on the parsed extension or Accept-Type header. For example, if `controller/action.xml`
* is requested, the view path becomes `app/View/Controller/xml/action.ctp`. Also if
* `controller/action` is requested with `Accept-Type: application/xml` in the headers
* the view path will become `app/View/Controller/xml/action.ctp`. Layout and template
* types will only switch to mime-types recognized by CakeResponse. If you need to declare
* additional mime-types, you can do so using CakeResponse::type() in your controllers beforeFilter()
* method.
* - If a helper with the same name as the extension exists, it is added to the controller.
* - If the extension is of a type that RequestHandler understands, it will set that
* Content-type in the response header.
* - If the XML data is POSTed, the data is parsed into an XML object, which is assigned
* to the $data property of the controller, which can then be saved to a model object.
*
* @param Controller $controller A reference to the controller
* @return void
*/
public function startup(Controller $controller) {
$controller->request->params['isAjax'] = $this->request->is('ajax');
$isRecognized = (
!in_array($this->ext, array('html', 'htm')) &&
$this->response->getMimeType($this->ext)
);

if (!empty($this->ext) && $isRecognized) {
$this->renderAs($controller, $this->ext);
} elseif ($this->request->is('ajax')) {
$this->renderAs($controller, 'ajax');
} elseif (empty($this->ext) || in_array($this->ext, array('html', 'htm'))) {
$this->respondAs('html', array('charset' => Configure::read('App.encoding')));
}

foreach ($this->_inputTypeMap as $type => $handler) {
if ($this->requestedWith($type)) {
$input = call_user_func_array(array($controller->request, 'input'), $handler);
$controller->request->data = $input;
}
}
}

/**
* Helper method to parse xml input data, due to lack of anonymous functions
* this lives here.
*
* @param string $xml
* @return array Xml array data
*/
public function convertXml($xml) {
try {
$xml = Xml::build($xml);
if (isset($xml->data)) {
return Xml::toArray($xml->data);
}
return Xml::toArray($xml);
} catch (XmlException $e) {
return array();
}
}

/**
* Handles (fakes) redirects for Ajax requests using requestAction()
*
* @param Controller $controller A reference to the controller
* @param string|array $url A string or array containing the redirect location
* @param integer|array $status HTTP Status for redirect
* @param boolean $exit
* @return void
*/
public function beforeRedirect(Controller $controller, $url, $status = null, $exit = true) {
if (!$this->request->is('ajax')) {
return;
}
foreach ($_POST as $key => $val) {
unset($_POST[$key]);
}
if (is_array($url)) {
$url = Router::url($url + array('base' => false));
}
if (!empty($status)) {
$statusCode = $this->response->httpCodes($status);
$code = key($statusCode);
$this->response->statusCode($code);
}
$this->response->body($this->requestAction($url, array('return', 'bare' => false)));
$this->response->send();
$this->_stop();
}

/**
* Checks if the response can be considered different according to the request
* headers, and the caching response headers. If it was not modified, then the
* render process is skipped. And the client will get a blank response with a
* "304 Not Modified" header.
*
* @params Controller $controller
* @return boolean false if the render process should be aborted
**/
public function beforeRender(Controller $controller) {
$shouldCheck = $this->settings['checkHttpCache'];
if ($shouldCheck && $this->response->checkNotModified($this->request)) {
return false;
}
}

/**
* Returns true if the current HTTP request is Ajax, false otherwise
*
* @return boolean True if call is Ajax
* @deprecated use `$this->request->is('ajax')` instead.
*/
public function isAjax() {
return $this->request->is('ajax');
}

/**
* Returns true if the current HTTP request is coming from a Flash-based client
*
* @return boolean True if call is from Flash
* @deprecated use `$this->request->is('flash')` instead.
*/
public function isFlash() {
return $this->request->is('flash');
}

/**
* Returns true if the current request is over HTTPS, false otherwise.
*
* @return boolean True if call is over HTTPS
* @deprecated use `$this->request->is('ssl')` instead.
*/
public function isSSL() {
return $this->request->is('ssl');
}

/**
* Returns true if the current call accepts an XML response, false otherwise
*
* @return boolean True if client accepts an XML response
*/
public function isXml() {
return $this->prefers('xml');
}

/**
* Returns true if the current call accepts an RSS response, false otherwise
*
* @return boolean True if client accepts an RSS response
*/
public function isRss() {
return $this->prefers('rss');
}

/**
* Returns true if the current call accepts an Atom response, false otherwise
*
* @return boolean True if client accepts an RSS response
*/
public function isAtom() {
return $this->prefers('atom');
}

/**
* Returns true if user agent string matches a mobile web browser, or if the
* client accepts WAP content.
*
* @return boolean True if user agent is a mobile web browser
*/
public function isMobile() {
return $this->request->is('mobile') || $this->accepts('wap');
}

/**
* Returns true if the client accepts WAP content
*
* @return boolean
*/
public function isWap() {
return $this->prefers('wap');
}

/**
* Returns true if the current call a POST request
*
* @return boolean True if call is a POST
* @deprecated Use $this->request->is('post'); from your controller.
*/
public function isPost() {
return $this->request->is('post');
}

/**
* Returns true if the current call a PUT request
*
* @return boolean True if call is a PUT
* @deprecated Use $this->request->is('put'); from your controller.
*/
public function isPut() {
return $this->request->is('put');
}

/**
* Returns true if the current call a GET request
*
* @return boolean True if call is a GET
* @deprecated Use $this->request->is('get'); from your controller.
*/
public function isGet() {
return $this->request->is('get');
}

/**
* Returns true if the current call a DELETE request
*
* @return boolean True if call is a DELETE
* @deprecated Use $this->request->is('delete'); from your controller.
*/
public function isDelete() {
return $this->request->is('delete');
}

/**
* Gets Prototype version if call is Ajax, otherwise empty string.
* The Prototype library sets a special "Prototype version" HTTP header.
*
* @return string Prototype version of component making Ajax call
*/
public function getAjaxVersion() {
if (env('HTTP_X_PROTOTYPE_VERSION') != null) {
return env('HTTP_X_PROTOTYPE_VERSION');
}
return false;
}

/**
* Adds/sets the Content-type(s) for the given name. This method allows
* content-types to be mapped to friendly aliases (or extensions), which allows
* RequestHandler to automatically respond to requests of that type in the
* startup method.
*
* @param string $name The name of the Content-type, i.e. "html", "xml", "css"
* @param string|array $type The Content-type or array of Content-types assigned to the name,
* i.e. "text/html", or "application/xml"
* @return void
* @deprecated use `$this->response->type()` instead.
*/
public function setContent($name, $type = null) {
$this->response->type(array($name => $type));
}

/**
* Gets the server name from which this request was referred
*
* @return string Server address
* @deprecated use $this->request->referer() from your controller instead
*/
public function getReferer() {
return $this->request->referer(false);
}

/**
* Gets remote client IP
*
* @param boolean $safe
* @return string Client IP address
* @deprecated use $this->request->clientIp() from your, controller instead.
*/
public function getClientIP($safe = true) {
return $this->request->clientIp($safe);
}

/**
* Determines which content types the client accepts. Acceptance is based on
* the file extension parsed by the Router (if present), and by the HTTP_ACCEPT
* header. Unlike CakeRequest::accepts() this method deals entirely with mapped content types.
*
* Usage:
*
* `$this->RequestHandler->accepts(array('xml', 'html', 'json'));`
*
* Returns true if the client accepts any of the supplied types.
*
* `$this->RequestHandler->accepts('xml');`
*
* Returns true if the client accepts xml.
*
* @param string|array $type Can be null (or no parameter), a string type name, or an
* array of types
* @return mixed If null or no parameter is passed, returns an array of content
* types the client accepts. If a string is passed, returns true
* if the client accepts it. If an array is passed, returns true
* if the client accepts one or more elements in the array.
* @see RequestHandlerComponent::setContent()
*/
public function accepts($type = null) {
$accepted = $this->request->accepts();

if ($type == null) {
return $this->mapType($accepted);
} elseif (is_array($type)) {
foreach ($type as $t) {
$t = $this->mapAlias($t);
if (in_array($t, $accepted)) {
return true;
}
}
return false;
} elseif (is_string($type)) {
$type = $this->mapAlias($type);
return in_array($type, $accepted);
}
return false;
}

/**
* Determines the content type of the data the client has sent (i.e. in a POST request)
*
* @param string|array $type Can be null (or no parameter), a string type name, or an array of types
* @return mixed If a single type is supplied a boolean will be returned. If no type is provided
* The mapped value of CONTENT_TYPE will be returned. If an array is supplied the first type
* in the request content type will be returned.
*/
public function requestedWith($type = null) {
if (!$this->request->is('post') && !$this->request->is('put')) {
return null;
}

list($contentType) = explode(';', env('CONTENT_TYPE'));
if ($type == null) {
return $this->mapType($contentType);
} elseif (is_array($type)) {
foreach ($type as $t) {
if ($this->requestedWith($t)) {
return $t;
}
}
return false;
} elseif (is_string($type)) {
return ($type == $this->mapType($contentType));
}
}

/**
* Determines which content-types the client prefers. If no parameters are given,
* the single content-type that the client most likely prefers is returned. If $type is
* an array, the first item in the array that the client accepts is returned.
* Preference is determined primarily by the file extension parsed by the Router
* if provided, and secondarily by the list of content-types provided in
* HTTP_ACCEPT.
*
* @param string|array $type An optional array of 'friendly' content-type names, i.e.
* 'html', 'xml', 'js', etc.
* @return mixed If $type is null or not provided, the first content-type in the
* list, based on preference, is returned. If a single type is provided
* a boolean will be returned if that type is preferred.
* If an array of types are provided then the first preferred type is returned.
* If no type is provided the first preferred type is returned.
* @see RequestHandlerComponent::setContent()
*/
public function prefers($type = null) {
$acceptRaw = $this->request->parseAccept();

if (empty($acceptRaw)) {
return $this->ext;
}
$accepts = array_shift($acceptRaw);
$accepts = $this->mapType($accepts);

if ($type == null) {
if (empty($this->ext) && !empty($accepts)) {
return $accepts[0];
}
return $this->ext;
}

$types = (array)$type;

if (count($types) === 1) {
if (!empty($this->ext)) {
return in_array($this->ext, $types);
}
return in_array($types[0], $accepts);
}

$intersect = array_values(array_intersect($accepts, $types));
if (empty($intersect)) {
return false;
}
return $intersect[0];
}

/**
* Sets the layout and template paths for the content type defined by $type.
*
* ### Usage:
*
* Render the response as an 'ajax' response.
*
* `$this->RequestHandler->renderAs($this, 'ajax');`
*
* Render the response as an xml file and force the result as a file download.
*
* `$this->RequestHandler->renderAs($this, 'xml', array('attachment' => 'myfile.xml');`
*
* @param Controller $controller A reference to a controller object
* @param string $type Type of response to send (e.g: 'ajax')
* @param array $options Array of options to use
* @return void
* @see RequestHandlerComponent::setContent()
* @see RequestHandlerComponent::respondAs()
*/
public function renderAs(Controller $controller, $type, $options = array()) {
$defaults = array('charset' => 'UTF-8');

if (Configure::read('App.encoding') !== null) {
$defaults['charset'] = Configure::read('App.encoding');
}
$options = array_merge($defaults, $options);

if ($type == 'ajax') {
$controller->layout = $this->ajaxLayout;
return $this->respondAs('html', $options);
}
$controller->ext = '.ctp';

$viewClass = Inflector::classify($type);
$viewName = $viewClass . 'View';
if (!class_exists($viewName)) {
App::uses($viewName, 'View');
}
if (class_exists($viewName)) {
$controller->viewClass = $viewClass;
} elseif (empty($this->_renderType)) {
$controller->viewPath .= DS . $type;
} else {
$remove = preg_replace("/([\/\\\\]{$this->_renderType})$/", DS . $type, $controller->viewPath);
$controller->viewPath = $remove;
}
$this->_renderType = $type;
$controller->layoutPath = $type;

if ($this->response->getMimeType($type)) {
$this->respondAs($type, $options);
}

$helper = ucfirst($type);
$isAdded = (
in_array($helper, $controller->helpers) ||
array_key_exists($helper, $controller->helpers)
);

if (!$isAdded) {
App::uses('AppHelper', 'View/Helper');
App::uses($helper . 'Helper', 'View/Helper');
if (class_exists($helper . 'Helper')) {
$controller->helpers[] = $helper;
}
}
}

/**
* Sets the response header based on type map index name. This wraps several methods
* available on CakeResponse. It also allows you to use Content-Type aliases.
*
* @param string|array $type Friendly type name, i.e. 'html' or 'xml', or a full content-type,
* like 'application/x-shockwave'.
* @param array $options If $type is a friendly type name that is associated with
* more than one type of content, $index is used to select which content-type to use.
* @return boolean Returns false if the friendly type name given in $type does
* not exist in the type map, or if the Content-type header has
* already been set by this method.
* @see RequestHandlerComponent::setContent()
*/
public function respondAs($type, $options = array()) {
$defaults = array('index' => null, 'charset' => null, 'attachment' => false);
$options = $options + $defaults;

if (strpos($type, '/') === false) {
$cType = $this->response->getMimeType($type);
if ($cType === false) {
return false;
}
if (is_array($cType) && isset($cType[$options['index']])) {
$cType = $cType[$options['index']];
}
if (is_array($cType)) {
if ($this->prefers($cType)) {
$cType = $this->prefers($cType);
} else {
$cType = $cType[0];
}
}
} else {
$cType = $type;
}

if ($cType != null) {
if (empty($this->request->params['requested'])) {
$this->response->type($cType);
}

if (!empty($options['charset'])) {
$this->response->charset($options['charset']);
}
if (!empty($options['attachment'])) {
$this->response->download($options['attachment']);
}
return true;
}
return false;
}

/**
* Returns the current response type (Content-type header), or null if not alias exists
*
* @return mixed A string content type alias, or raw content type if no alias map exists,
* otherwise null
*/
public function responseType() {
return $this->mapType($this->response->type());
}

/**
* Maps a content-type back to an alias
*
* @param string|array $cType Either a string content type to map, or an array of types.
* @return string|array Aliases for the types provided.
* @deprecated Use $this->response->mapType() in your controller instead.
*/
public function mapType($cType) {
return $this->response->mapType($cType);
}

/**
* Maps a content type alias back to its mime-type(s)
*
* @param string|array $alias String alias to convert back into a content type. Or an array of aliases to map.
* @return string Null on an undefined alias. String value of the mapped alias type. If an
* alias maps to more than one content type, the first one will be returned.
*/
public function mapAlias($alias) {
if (is_array($alias)) {
return array_map(array($this, 'mapAlias'), $alias);
}
$type = $this->response->getMimeType($alias);
if ($type) {
if (is_array($type)) {
return $type[0];
}
return $type;
}
return null;
}

/**
* Add a new mapped input type. Mapped input types are automatically
* converted by RequestHandlerComponent during the startup() callback.
*
* @param string $type The type alias being converted, ie. json
* @param array $handler The handler array for the type. The first index should
* be the handling callback, all other arguments should be additional parameters
* for the handler.
* @return void
* @throws CakeException
*/
public function addInputType($type, $handler) {
if (!is_array($handler) || !isset($handler[0]) || !is_callable($handler[0])) {
throw new CakeException(__d('cake_dev', 'You must give a handler callback.'));
}
$this->_inputTypeMap[$type] = $handler;
}

}
Something went wrong with that request. Please try again.