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