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