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: * Modifies the $_POST and $_SERVER['REQUEST_METHOD'] to simulate a new GET request.
221: *
222: * @param Controller $controller A reference to the controller
223: * @param string|array $url A string or array containing the redirect location
224: * @param integer|array $status HTTP Status for redirect
225: * @param boolean $exit
226: * @return void
227: */
228: public function beforeRedirect(Controller $controller, $url, $status = null, $exit = true) {
229: if (!$this->request->is('ajax')) {
230: return;
231: }
232: $_SERVER['REQUEST_METHOD'] = 'GET';
233: foreach ($_POST as $key => $val) {
234: unset($_POST[$key]);
235: }
236: if (is_array($url)) {
237: $url = Router::url($url + array('base' => false));
238: }
239: if (!empty($status)) {
240: $statusCode = $this->response->httpCodes($status);
241: $code = key($statusCode);
242: $this->response->statusCode($code);
243: }
244: $this->response->body($this->requestAction($url, array('return', 'bare' => false)));
245: $this->response->send();
246: $this->_stop();
247: }
248:
249: /**
250: * Checks if the response can be considered different according to the request
251: * headers, and the caching response headers. If it was not modified, then the
252: * render process is skipped. And the client will get a blank response with a
253: * "304 Not Modified" header.
254: *
255: * @params Controller $controller
256: * @return boolean false if the render process should be aborted
257: **/
258: public function beforeRender(Controller $controller) {
259: $shouldCheck = $this->settings['checkHttpCache'];
260: if ($shouldCheck && $this->response->checkNotModified($this->request)) {
261: return false;
262: }
263: }
264:
265: /**
266: * Returns true if the current HTTP request is Ajax, false otherwise
267: *
268: * @return boolean True if call is Ajax
269: * @deprecated use `$this->request->is('ajax')` instead.
270: */
271: public function isAjax() {
272: return $this->request->is('ajax');
273: }
274:
275: /**
276: * Returns true if the current HTTP request is coming from a Flash-based client
277: *
278: * @return boolean True if call is from Flash
279: * @deprecated use `$this->request->is('flash')` instead.
280: */
281: public function isFlash() {
282: return $this->request->is('flash');
283: }
284:
285: /**
286: * Returns true if the current request is over HTTPS, false otherwise.
287: *
288: * @return boolean True if call is over HTTPS
289: * @deprecated use `$this->request->is('ssl')` instead.
290: */
291: public function isSSL() {
292: return $this->request->is('ssl');
293: }
294:
295: /**
296: * Returns true if the current call accepts an XML response, false otherwise
297: *
298: * @return boolean True if client accepts an XML response
299: */
300: public function isXml() {
301: return $this->prefers('xml');
302: }
303:
304: /**
305: * Returns true if the current call accepts an RSS response, false otherwise
306: *
307: * @return boolean True if client accepts an RSS response
308: */
309: public function isRss() {
310: return $this->prefers('rss');
311: }
312:
313: /**
314: * Returns true if the current call accepts an Atom response, false otherwise
315: *
316: * @return boolean True if client accepts an RSS response
317: */
318: public function isAtom() {
319: return $this->prefers('atom');
320: }
321:
322: /**
323: * Returns true if user agent string matches a mobile web browser, or if the
324: * client accepts WAP content.
325: *
326: * @return boolean True if user agent is a mobile web browser
327: */
328: public function isMobile() {
329: return $this->request->is('mobile') || $this->accepts('wap');
330: }
331:
332: /**
333: * Returns true if the client accepts WAP content
334: *
335: * @return boolean
336: */
337: public function isWap() {
338: return $this->prefers('wap');
339: }
340:
341: /**
342: * Returns true if the current call a POST request
343: *
344: * @return boolean True if call is a POST
345: * @deprecated Use $this->request->is('post'); from your controller.
346: */
347: public function isPost() {
348: return $this->request->is('post');
349: }
350:
351: /**
352: * Returns true if the current call a PUT request
353: *
354: * @return boolean True if call is a PUT
355: * @deprecated Use $this->request->is('put'); from your controller.
356: */
357: public function isPut() {
358: return $this->request->is('put');
359: }
360:
361: /**
362: * Returns true if the current call a GET request
363: *
364: * @return boolean True if call is a GET
365: * @deprecated Use $this->request->is('get'); from your controller.
366: */
367: public function isGet() {
368: return $this->request->is('get');
369: }
370:
371: /**
372: * Returns true if the current call a DELETE request
373: *
374: * @return boolean True if call is a DELETE
375: * @deprecated Use $this->request->is('delete'); from your controller.
376: */
377: public function isDelete() {
378: return $this->request->is('delete');
379: }
380:
381: /**
382: * Gets Prototype version if call is Ajax, otherwise empty string.
383: * The Prototype library sets a special "Prototype version" HTTP header.
384: *
385: * @return string Prototype version of component making Ajax call
386: */
387: public function getAjaxVersion() {
388: if (env('HTTP_X_PROTOTYPE_VERSION') != null) {
389: return env('HTTP_X_PROTOTYPE_VERSION');
390: }
391: return false;
392: }
393:
394: /**
395: * Adds/sets the Content-type(s) for the given name. This method allows
396: * content-types to be mapped to friendly aliases (or extensions), which allows
397: * RequestHandler to automatically respond to requests of that type in the
398: * startup method.
399: *
400: * @param string $name The name of the Content-type, i.e. "html", "xml", "css"
401: * @param string|array $type The Content-type or array of Content-types assigned to the name,
402: * i.e. "text/html", or "application/xml"
403: * @return void
404: * @deprecated use `$this->response->type()` instead.
405: */
406: public function setContent($name, $type = null) {
407: $this->response->type(array($name => $type));
408: }
409:
410: /**
411: * Gets the server name from which this request was referred
412: *
413: * @return string Server address
414: * @deprecated use $this->request->referer() from your controller instead
415: */
416: public function getReferer() {
417: return $this->request->referer(false);
418: }
419:
420: /**
421: * Gets remote client IP
422: *
423: * @param boolean $safe
424: * @return string Client IP address
425: * @deprecated use $this->request->clientIp() from your, controller instead.
426: */
427: public function getClientIP($safe = true) {
428: return $this->request->clientIp($safe);
429: }
430:
431: /**
432: * Determines which content types the client accepts. Acceptance is based on
433: * the file extension parsed by the Router (if present), and by the HTTP_ACCEPT
434: * header. Unlike CakeRequest::accepts() this method deals entirely with mapped content types.
435: *
436: * Usage:
437: *
438: * `$this->RequestHandler->accepts(array('xml', 'html', 'json'));`
439: *
440: * Returns true if the client accepts any of the supplied types.
441: *
442: * `$this->RequestHandler->accepts('xml');`
443: *
444: * Returns true if the client accepts xml.
445: *
446: * @param string|array $type Can be null (or no parameter), a string type name, or an
447: * array of types
448: * @return mixed If null or no parameter is passed, returns an array of content
449: * types the client accepts. If a string is passed, returns true
450: * if the client accepts it. If an array is passed, returns true
451: * if the client accepts one or more elements in the array.
452: * @see RequestHandlerComponent::setContent()
453: */
454: public function accepts($type = null) {
455: $accepted = $this->request->accepts();
456:
457: if ($type == null) {
458: return $this->mapType($accepted);
459: } elseif (is_array($type)) {
460: foreach ($type as $t) {
461: $t = $this->mapAlias($t);
462: if (in_array($t, $accepted)) {
463: return true;
464: }
465: }
466: return false;
467: } elseif (is_string($type)) {
468: $type = $this->mapAlias($type);
469: return in_array($type, $accepted);
470: }
471: return false;
472: }
473:
474: /**
475: * Determines the content type of the data the client has sent (i.e. in a POST request)
476: *
477: * @param string|array $type Can be null (or no parameter), a string type name, or an array of types
478: * @return mixed If a single type is supplied a boolean will be returned. If no type is provided
479: * The mapped value of CONTENT_TYPE will be returned. If an array is supplied the first type
480: * in the request content type will be returned.
481: */
482: public function requestedWith($type = null) {
483: if (!$this->request->is('post') && !$this->request->is('put')) {
484: return null;
485: }
486:
487: list($contentType) = explode(';', env('CONTENT_TYPE'));
488: if ($type == null) {
489: return $this->mapType($contentType);
490: } elseif (is_array($type)) {
491: foreach ($type as $t) {
492: if ($this->requestedWith($t)) {
493: return $t;
494: }
495: }
496: return false;
497: } elseif (is_string($type)) {
498: return ($type == $this->mapType($contentType));
499: }
500: }
501:
502: /**
503: * Determines which content-types the client prefers. If no parameters are given,
504: * the single content-type that the client most likely prefers is returned. If $type is
505: * an array, the first item in the array that the client accepts is returned.
506: * Preference is determined primarily by the file extension parsed by the Router
507: * if provided, and secondarily by the list of content-types provided in
508: * HTTP_ACCEPT.
509: *
510: * @param string|array $type An optional array of 'friendly' content-type names, i.e.
511: * 'html', 'xml', 'js', etc.
512: * @return mixed If $type is null or not provided, the first content-type in the
513: * list, based on preference, is returned. If a single type is provided
514: * a boolean will be returned if that type is preferred.
515: * If an array of types are provided then the first preferred type is returned.
516: * If no type is provided the first preferred type is returned.
517: * @see RequestHandlerComponent::setContent()
518: */
519: public function prefers($type = null) {
520: $acceptRaw = $this->request->parseAccept();
521:
522: if (empty($acceptRaw)) {
523: return $this->ext;
524: }
525: $accepts = array_shift($acceptRaw);
526: $accepts = $this->mapType($accepts);
527:
528: if ($type == null) {
529: if (empty($this->ext) && !empty($accepts)) {
530: return $accepts[0];
531: }
532: return $this->ext;
533: }
534:
535: $types = (array)$type;
536:
537: if (count($types) === 1) {
538: if (!empty($this->ext)) {
539: return in_array($this->ext, $types);
540: }
541: return in_array($types[0], $accepts);
542: }
543:
544: $intersect = array_values(array_intersect($accepts, $types));
545: if (empty($intersect)) {
546: return false;
547: }
548: return $intersect[0];
549: }
550:
551: /**
552: * Sets the layout and template paths for the content type defined by $type.
553: *
554: * ### Usage:
555: *
556: * Render the response as an 'ajax' response.
557: *
558: * `$this->RequestHandler->renderAs($this, 'ajax');`
559: *
560: * Render the response as an xml file and force the result as a file download.
561: *
562: * `$this->RequestHandler->renderAs($this, 'xml', array('attachment' => 'myfile.xml');`
563: *
564: * @param Controller $controller A reference to a controller object
565: * @param string $type Type of response to send (e.g: 'ajax')
566: * @param array $options Array of options to use
567: * @return void
568: * @see RequestHandlerComponent::setContent()
569: * @see RequestHandlerComponent::respondAs()
570: */
571: public function renderAs(Controller $controller, $type, $options = array()) {
572: $defaults = array('charset' => 'UTF-8');
573:
574: if (Configure::read('App.encoding') !== null) {
575: $defaults['charset'] = Configure::read('App.encoding');
576: }
577: $options = array_merge($defaults, $options);
578:
579: if ($type == 'ajax') {
580: $controller->layout = $this->ajaxLayout;
581: return $this->respondAs('html', $options);
582: }
583: $controller->ext = '.ctp';
584:
585: $viewClass = Inflector::classify($type);
586: $viewName = $viewClass . 'View';
587: if (!class_exists($viewName)) {
588: App::uses($viewName, 'View');
589: }
590: if (class_exists($viewName)) {
591: $controller->viewClass = $viewClass;
592: } elseif (empty($this->_renderType)) {
593: $controller->viewPath .= DS . $type;
594: } else {
595: $remove = preg_replace("/([\/\\\\]{$this->_renderType})$/", DS . $type, $controller->viewPath);
596: $controller->viewPath = $remove;
597: }
598: $this->_renderType = $type;
599: $controller->layoutPath = $type;
600:
601: if ($this->response->getMimeType($type)) {
602: $this->respondAs($type, $options);
603: }
604:
605: $helper = ucfirst($type);
606: $isAdded = (
607: in_array($helper, $controller->helpers) ||
608: array_key_exists($helper, $controller->helpers)
609: );
610:
611: if (!$isAdded) {
612: App::uses('AppHelper', 'View/Helper');
613: App::uses($helper . 'Helper', 'View/Helper');
614: if (class_exists($helper . 'Helper')) {
615: $controller->helpers[] = $helper;
616: }
617: }
618: }
619:
620: /**
621: * Sets the response header based on type map index name. This wraps several methods
622: * available on CakeResponse. It also allows you to use Content-Type aliases.
623: *
624: * @param string|array $type Friendly type name, i.e. 'html' or 'xml', or a full content-type,
625: * like 'application/x-shockwave'.
626: * @param array $options If $type is a friendly type name that is associated with
627: * more than one type of content, $index is used to select which content-type to use.
628: * @return boolean Returns false if the friendly type name given in $type does
629: * not exist in the type map, or if the Content-type header has
630: * already been set by this method.
631: * @see RequestHandlerComponent::setContent()
632: */
633: public function respondAs($type, $options = array()) {
634: $defaults = array('index' => null, 'charset' => null, 'attachment' => false);
635: $options = $options + $defaults;
636:
637: if (strpos($type, '/') === false) {
638: $cType = $this->response->getMimeType($type);
639: if ($cType === false) {
640: return false;
641: }
642: if (is_array($cType) && isset($cType[$options['index']])) {
643: $cType = $cType[$options['index']];
644: }
645: if (is_array($cType)) {
646: if ($this->prefers($cType)) {
647: $cType = $this->prefers($cType);
648: } else {
649: $cType = $cType[0];
650: }
651: }
652: } else {
653: $cType = $type;
654: }
655:
656: if ($cType != null) {
657: if (empty($this->request->params['requested'])) {
658: $this->response->type($cType);
659: }
660:
661: if (!empty($options['charset'])) {
662: $this->response->charset($options['charset']);
663: }
664: if (!empty($options['attachment'])) {
665: $this->response->download($options['attachment']);
666: }
667: return true;
668: }
669: return false;
670: }
671:
672: /**
673: * Returns the current response type (Content-type header), or null if not alias exists
674: *
675: * @return mixed A string content type alias, or raw content type if no alias map exists,
676: * otherwise null
677: */
678: public function responseType() {
679: return $this->mapType($this->response->type());
680: }
681:
682: /**
683: * Maps a content-type back to an alias
684: *
685: * @param string|array $cType Either a string content type to map, or an array of types.
686: * @return string|array Aliases for the types provided.
687: * @deprecated Use $this->response->mapType() in your controller instead.
688: */
689: public function mapType($cType) {
690: return $this->response->mapType($cType);
691: }
692:
693: /**
694: * Maps a content type alias back to its mime-type(s)
695: *
696: * @param string|array $alias String alias to convert back into a content type. Or an array of aliases to map.
697: * @return string Null on an undefined alias. String value of the mapped alias type. If an
698: * alias maps to more than one content type, the first one will be returned.
699: */
700: public function mapAlias($alias) {
701: if (is_array($alias)) {
702: return array_map(array($this, 'mapAlias'), $alias);
703: }
704: $type = $this->response->getMimeType($alias);
705: if ($type) {
706: if (is_array($type)) {
707: return $type[0];
708: }
709: return $type;
710: }
711: return null;
712: }
713:
714: /**
715: * Add a new mapped input type. Mapped input types are automatically
716: * converted by RequestHandlerComponent during the startup() callback.
717: *
718: * @param string $type The type alias being converted, ie. json
719: * @param array $handler The handler array for the type. The first index should
720: * be the handling callback, all other arguments should be additional parameters
721: * for the handler.
722: * @return void
723: * @throws CakeException
724: */
725: public function addInputType($type, $handler) {
726: if (!is_array($handler) || !isset($handler[0]) || !is_callable($handler[0])) {
727: throw new CakeException(__d('cake_dev', 'You must give a handler callback.'));
728: }
729: $this->_inputTypeMap[$type] = $handler;
730: }
731:
732: }
733: