CakePHP
  • Documentation
    • Book
    • API
    • Videos
    • Reporting Security Issues
    • Privacy Policy
    • Logos & Trademarks
  • Business Solutions
  • Swag
  • Road Trip
  • Team
  • Community
    • Community
    • Get Involved
    • Issues (GitHub)
    • Bakery
    • Featured Resources
    • Training
    • Meetups
    • My CakePHP
    • CakeFest
    • Newsletter
    • Linkedin
    • YouTube
    • Facebook
    • Twitter
    • Mastodon
    • Help & Support
    • Forum
    • Stack Overflow
    • Slack
    • Paid Support
CakePHP

C CakePHP 2.0 API

  • Overview
  • Tree
  • Deprecated
  • Version:
    • 2.0
      • 4.2
      • 4.1
      • 4.0
      • 3.9
      • 3.8
      • 3.7
      • 3.6
      • 3.5
      • 3.4
      • 3.3
      • 3.2
      • 3.1
      • 3.0
      • 2.10
      • 2.9
      • 2.8
      • 2.7
      • 2.6
      • 2.5
      • 2.4
      • 2.3
      • 2.2
      • 2.1
      • 2.0
      • 1.3
      • 1.2

Packages

  • Cake
    • Cache
      • Engine
    • Configure
    • Console
      • Command
        • Task
    • Controller
      • Component
        • Auth
    • Core
    • Error
    • I18n
    • Log
      • Engine
    • Model
      • Behavior
      • Datasource
        • Database
        • Session
    • Network
      • Email
      • Http
    • Routing
      • Route
    • TestSuite
      • Coverage
      • Fixture
      • Reporter
    • Utility
    • View
      • Helper

Classes

  • CakeRequest
  • CakeResponse
  • CakeSocket
  1: <?php
  2: /**
  3:  * CakeRequest
  4:  *
  5:  * PHP 5
  6:  *
  7:  * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  8:  * Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
  9:  *
 10:  * Licensed under The MIT License
 11:  * Redistributions of files must retain the above copyright notice.
 12:  *
 13:  * @copyright     Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
 14:  * @link          http://cakephp.org CakePHP(tm) Project
 15:  * @since         CakePHP(tm) v 2.0
 16:  * @license       MIT License (http://www.opensource.org/licenses/mit-license.php)
 17:  */
 18: 
 19: App::uses('Set', 'Utility');
 20: 
 21: /**
 22:  * A class that helps wrap Request information and particulars about a single request.
 23:  * Provides methods commonly used to introspect on the request headers and request body.
 24:  *
 25:  * Has both an Array and Object interface. You can access framework parameters using indexes:
 26:  *
 27:  * `$request['controller']` or `$request->controller`.
 28:  *
 29:  * @package       Cake.Network
 30:  */
 31: class CakeRequest implements ArrayAccess {
 32: /**
 33:  * Array of parameters parsed from the url.
 34:  *
 35:  * @var array
 36:  */
 37:     public $params = array(
 38:         'plugin' => null,
 39:         'controller' => null,
 40:         'action' => null,
 41:     );
 42: 
 43: /**
 44:  * Array of POST data.  Will contain form data as well as uploaded files.
 45:  * Inputs prefixed with 'data' will have the data prefix removed.  If there is
 46:  * overlap between an input prefixed with data and one without, the 'data' prefixed
 47:  * value will take precedence.
 48:  *
 49:  * @var array
 50:  */
 51:     public $data = array();
 52: 
 53: /**
 54:  * Array of querystring arguments
 55:  *
 56:  * @var array
 57:  */
 58:     public $query = array();
 59: 
 60: /**
 61:  * The url string used for the request.
 62:  *
 63:  * @var string
 64:  */
 65:     public $url;
 66: 
 67: /**
 68:  * Base url path.
 69:  *
 70:  * @var string
 71:  */
 72:     public $base = false;
 73: 
 74: /**
 75:  * webroot path segment for the request.
 76:  *
 77:  * @var string
 78:  */
 79:     public $webroot = '/';
 80: 
 81: /**
 82:  * The full address to the current request
 83:  *
 84:  * @var string
 85:  */
 86:     public $here = null;
 87: 
 88: /**
 89:  * The built in detectors used with `is()` can be modified with `addDetector()`.
 90:  *
 91:  * There are several ways to specify a detector, see CakeRequest::addDetector() for the
 92:  * various formats and ways to define detectors.
 93:  *
 94:  * @var array
 95:  */
 96:     protected $_detectors = array(
 97:         'get' => array('env' => 'REQUEST_METHOD', 'value' => 'GET'),
 98:         'post' => array('env' => 'REQUEST_METHOD', 'value' => 'POST'),
 99:         'put' => array('env' => 'REQUEST_METHOD', 'value' => 'PUT'),
100:         'delete' => array('env' => 'REQUEST_METHOD', 'value' => 'DELETE'),
101:         'head' => array('env' => 'REQUEST_METHOD', 'value' => 'HEAD'),
102:         'options' => array('env' => 'REQUEST_METHOD', 'value' => 'OPTIONS'),
103:         'ssl' => array('env' => 'HTTPS', 'value' => 1),
104:         'ajax' => array('env' => 'HTTP_X_REQUESTED_WITH', 'value' => 'XMLHttpRequest'),
105:         'flash' => array('env' => 'HTTP_USER_AGENT', 'pattern' => '/^(Shockwave|Adobe) Flash/'),
106:         'mobile' => array('env' => 'HTTP_USER_AGENT', 'options' => array(
107:             'Android', 'AvantGo', 'BlackBerry', 'DoCoMo', 'Fennec', 'iPod', 'iPhone', 'iPad',
108:             'J2ME', 'MIDP', 'NetFront', 'Nokia', 'Opera Mini', 'Opera Mobi', 'PalmOS', 'PalmSource',
109:             'portalmmm', 'Plucker', 'ReqwirelessWeb', 'SonyEricsson', 'Symbian', 'UP\\.Browser',
110:             'webOS', 'Windows CE', 'Windows Phone OS', 'Xiino'
111:         ))
112:     );
113: 
114: /**
115:  * Copy of php://input.  Since this stream can only be read once in most SAPI's
116:  * keep a copy of it so users don't need to know about that detail.
117:  *
118:  * @var string
119:  */
120:     protected $_input = '';
121: 
122: /**
123:  * Constructor
124:  *
125:  * @param string $url Trimmed url string to use.  Should not contain the application base path.
126:  * @param boolean $parseEnvironment Set to false to not auto parse the environment. ie. GET, POST and FILES.
127:  */
128:     public function __construct($url = null, $parseEnvironment = true) {
129:         $this->_base();
130:         if (empty($url)) {
131:             $url = $this->_url();
132:         }
133:         if ($url[0] == '/') {
134:             $url = substr($url, 1);
135:         }
136:         $this->url = $url;
137: 
138:         if ($parseEnvironment) {
139:             $this->_processPost();
140:             $this->_processGet();
141:             $this->_processFiles();
142:         }
143:         $this->here = $this->base . '/' . $this->url;
144:     }
145: 
146: /**
147:  * process the post data and set what is there into the object.
148:  * processed data is available at $this->data
149:  *
150:  * @return void
151:  */
152:     protected function _processPost() {
153:         $this->data = $_POST;
154:         if (ini_get('magic_quotes_gpc') === '1') {
155:             $this->data = stripslashes_deep($this->data);
156:         }
157:         if (env('HTTP_X_HTTP_METHOD_OVERRIDE')) {
158:             $this->data['_method'] = env('HTTP_X_HTTP_METHOD_OVERRIDE');
159:         }
160:         if (isset($this->data['_method'])) {
161:             if (!empty($_SERVER)) {
162:                 $_SERVER['REQUEST_METHOD'] = $this->data['_method'];
163:             } else {
164:                 $_ENV['REQUEST_METHOD'] = $this->data['_method'];
165:             }
166:             unset($this->data['_method']);
167:         }
168:         if (isset($this->data['data'])) {
169:             $data = $this->data['data'];
170:             unset($this->data['data']);
171:             $this->data = Set::merge($this->data, $data);
172:         }
173:     }
174: 
175: /**
176:  * Process the GET parameters and move things into the object.
177:  *
178:  * @return void
179:  */
180:     protected function _processGet() {
181:         if (ini_get('magic_quotes_gpc') === '1') {
182:             $query = stripslashes_deep($_GET);
183:         } else {
184:             $query = $_GET;
185:         }
186: 
187:         unset($query['/' . str_replace('.', '_', $this->url)]);
188:         if (strpos($this->url, '?') !== false) {
189:             list(, $querystr) = explode('?', $this->url);
190:             parse_str($querystr, $queryArgs);
191:             $query += $queryArgs;
192:         }
193:         if (isset($this->params['url'])) {
194:             $query = array_merge($this->params['url'], $query);
195:         }
196:         $this->query = $query;
197:     }
198: 
199: /**
200:  * Get the request uri.  Looks in PATH_INFO first, as this is the exact value we need prepared
201:  * by PHP.  Following that, REQUEST_URI, PHP_SELF, HTTP_X_REWRITE_URL and argv are checked in that order.
202:  * Each of these server variables have the base path, and query strings stripped off
203:  *
204:  * @return string URI The CakePHP request path that is being accessed.
205:  */
206:     protected function _url() {
207:         if (!empty($_SERVER['PATH_INFO'])) {
208:             return $_SERVER['PATH_INFO'];
209:         } elseif (isset($_SERVER['REQUEST_URI'])) {
210:             $uri = $_SERVER['REQUEST_URI'];
211:         } elseif (isset($_SERVER['PHP_SELF']) && isset($_SERVER['SCRIPT_NAME'])) {
212:             $uri = str_replace($_SERVER['SCRIPT_NAME'], '', $_SERVER['PHP_SELF']);
213:         } elseif (isset($_SERVER['HTTP_X_REWRITE_URL'])) {
214:             $uri = $_SERVER['HTTP_X_REWRITE_URL'];
215:         } elseif ($var = env('argv')) {
216:             $uri = $var[0];
217:         }
218: 
219:         $base = $this->base;
220: 
221:         if (strlen($base) > 0 && strpos($uri, $base) === 0) {
222:             $uri = substr($uri, strlen($base));
223:         }
224:         if (strpos($uri, '?') !== false) {
225:             list($uri) = explode('?', $uri, 2);
226:         }
227:         if (empty($uri) || $uri == '/' || $uri == '//') {
228:             return '/';
229:         }
230:         return $uri;
231:     }
232: 
233: /**
234:  * Returns a base URL and sets the proper webroot
235:  *
236:  * @return string Base URL
237:  */
238:     protected function _base() {
239:         $dir = $webroot = null;
240:         $config = Configure::read('App');
241:         extract($config);
242: 
243:         if (!isset($base)) {
244:             $base = $this->base;
245:         }
246:         if ($base !== false) {
247:             $this->webroot = $base . '/';
248:             return $this->base = $base;
249:         }
250: 
251:         if (!$baseUrl) {
252:             $base = dirname(env('PHP_SELF'));
253: 
254:             if ($webroot === 'webroot' && $webroot === basename($base)) {
255:                 $base = dirname($base);
256:             }
257:             if ($dir === 'app' && $dir === basename($base)) {
258:                 $base = dirname($base);
259:             }
260: 
261:             if ($base === DS || $base === '.') {
262:                 $base = '';
263:             }
264: 
265:             $this->webroot = $base .'/';
266:             return $this->base = $base;
267:         }
268: 
269:         $file = '/' . basename($baseUrl);
270:         $base = dirname($baseUrl);
271: 
272:         if ($base === DS || $base === '.') {
273:             $base = '';
274:         }
275:         $this->webroot = $base . '/';
276: 
277:         $docRoot = env('DOCUMENT_ROOT');
278:         $docRootContainsWebroot = strpos($docRoot, $dir . '/' . $webroot);
279: 
280:         if (!empty($base) || !$docRootContainsWebroot) {
281:             if (strpos($this->webroot, '/' . $dir . '/') === false) {
282:                 $this->webroot .= $dir . '/' ;
283:             }
284:             if (strpos($this->webroot, '/' . $webroot . '/') === false) {
285:                 $this->webroot .= $webroot . '/';
286:             }
287:         }
288:         return $this->base = $base . $file;
289:     }
290: 
291: /**
292:  * Process $_FILES and move things into the object.
293:  *
294:  * @return void
295:  */
296:     protected function _processFiles() {
297:         if (isset($_FILES) && is_array($_FILES)) {
298:             foreach ($_FILES as $name => $data) {
299:                 if ($name != 'data') {
300:                     $this->params['form'][$name] = $data;
301:                 }
302:             }
303:         }
304: 
305:         if (isset($_FILES['data'])) {
306:             foreach ($_FILES['data'] as $key => $data) {
307:                 foreach ($data as $model => $fields) {
308:                     if (is_array($fields)) {
309:                         foreach ($fields as $field => $value) {
310:                             if (is_array($value)) {
311:                                 foreach ($value as $k => $v) {
312:                                     $this->data[$model][$field][$k][$key] = $v;
313:                                 }
314:                             } else {
315:                                 $this->data[$model][$field][$key] = $value;
316:                             }
317:                         }
318:                     } else {
319:                         $this->data[$model][$key] = $fields;
320:                     }
321:                 }
322:             }
323:         }
324:     }
325: 
326: /**
327:  * Get the IP the client is using, or says they are using.
328:  *
329:  * @param boolean $safe Use safe = false when you think the user might manipulate their HTTP_CLIENT_IP
330:  *   header.  Setting $safe = false will will also look at HTTP_X_FORWARDED_FOR
331:  * @return string The client IP.
332:  */
333:     public function clientIp($safe = true) {
334:         if (!$safe && env('HTTP_X_FORWARDED_FOR') != null) {
335:             $ipaddr = preg_replace('/(?:,.*)/', '', env('HTTP_X_FORWARDED_FOR'));
336:         } else {
337:             if (env('HTTP_CLIENT_IP') != null) {
338:                 $ipaddr = env('HTTP_CLIENT_IP');
339:             } else {
340:                 $ipaddr = env('REMOTE_ADDR');
341:             }
342:         }
343: 
344:         if (env('HTTP_CLIENTADDRESS') != null) {
345:             $tmpipaddr = env('HTTP_CLIENTADDRESS');
346: 
347:             if (!empty($tmpipaddr)) {
348:                 $ipaddr = preg_replace('/(?:,.*)/', '', $tmpipaddr);
349:             }
350:         }
351:         return trim($ipaddr);
352:     }
353: 
354: /**
355:  * Returns the referer that referred this request.
356:  *
357:  * @param boolean $local Attempt to return a local address. Local addresses do not contain hostnames.
358:  * @return string The referring address for this request.
359:  */
360:     public function referer($local = false) {
361:         $ref = env('HTTP_REFERER');
362:         $forwarded = env('HTTP_X_FORWARDED_HOST');
363:         if ($forwarded) {
364:             $ref = $forwarded;
365:         }
366: 
367:         $base = '';
368:         if (defined('FULL_BASE_URL')) {
369:             $base = FULL_BASE_URL . $this->webroot;
370:         }
371:         if (!empty($ref) && !empty($base)) {
372:             if ($local && strpos($ref, $base) === 0) {
373:                 $ref = substr($ref, strlen($base));
374:                 if ($ref[0] != '/') {
375:                     $ref = '/' . $ref;
376:                 }
377:                 return $ref;
378:             } elseif (!$local) {
379:                 return $ref;
380:             }
381:         }
382:         return '/';
383:     }
384: 
385: /**
386:  * Missing method handler, handles wrapping older style isAjax() type methods
387:  *
388:  * @param string $name The method called
389:  * @param array $params Array of parameters for the method call
390:  * @return mixed
391:  * @throws CakeException when an invalid method is called.
392:  */
393:     public function __call($name, $params) {
394:         if (strpos($name, 'is') === 0) {
395:             $type = strtolower(substr($name, 2));
396:             return $this->is($type);
397:         }
398:         throw new CakeException(__d('cake_dev', 'Method %s does not exist', $name));
399:     }
400: 
401: /**
402:  * Magic get method allows access to parsed routing parameters directly on the object.
403:  *
404:  * Allows access to `$this->params['controller']` via `$this->controller`
405:  *
406:  * @param string $name The property being accessed.
407:  * @return mixed Either the value of the parameter or null.
408:  */
409:     public function __get($name) {
410:         if (isset($this->params[$name])) {
411:             return $this->params[$name];
412:         }
413:         return null;
414:     }
415: 
416: /**
417:  * Magic isset method allows isset/empty checks
418:  * on routing parameters.
419:  *
420:  * @param string $name The property being accessed.
421:  * @return bool Existence
422:  */
423:     public function __isset($name) {
424:         return isset($this->params[$name]);
425:     }
426: 
427: /**
428:  * Check whether or not a Request is a certain type.  Uses the built in detection rules
429:  * as well as additional rules defined with CakeRequest::addDetector().  Any detector can be called
430:  * as `is($type)` or `is$Type()`.
431:  *
432:  * @param string $type The type of request you want to check.
433:  * @return boolean Whether or not the request is the type you are checking.
434:  */
435:     public function is($type) {
436:         $type = strtolower($type);
437:         if (!isset($this->_detectors[$type])) {
438:             return false;
439:         }
440:         $detect = $this->_detectors[$type];
441:         if (isset($detect['env'])) {
442:             if (isset($detect['value'])) {
443:                 return env($detect['env']) == $detect['value'];
444:             }
445:             if (isset($detect['pattern'])) {
446:                 return (bool)preg_match($detect['pattern'], env($detect['env']));
447:             }
448:             if (isset($detect['options'])) {
449:                 $pattern = '/' . implode('|', $detect['options']) . '/i';
450:                 return (bool)preg_match($pattern, env($detect['env']));
451:             }
452:         }
453:         if (isset($detect['callback']) && is_callable($detect['callback'])) {
454:             return call_user_func($detect['callback'], $this);
455:         }
456:         return false;
457:     }
458: 
459: /**
460:  * Add a new detector to the list of detectors that a request can use.
461:  * There are several different formats and types of detectors that can be set.
462:  *
463:  * ### Environment value comparison
464:  *
465:  * An environment value comparison, compares a value fetched from `env()` to a known value
466:  * the environment value is equality checked against the provided value.
467:  *
468:  * e.g `addDetector('post', array('env' => 'REQUEST_METHOD', 'value' => 'POST'))`
469:  *
470:  * ### Pattern value comparison
471:  *
472:  * Pattern value comparison allows you to compare a value fetched from `env()` to a regular expression.
473:  *
474:  * e.g `addDetector('iphone', array('env' => 'HTTP_USER_AGENT', 'pattern' => '/iPhone/i'));`
475:  *
476:  * ### Option based comparison
477:  *
478:  * Option based comparisons use a list of options to create a regular expression.  Subsequent calls
479:  * to add an already defined options detector will merge the options.
480:  *
481:  * e.g `addDetector('mobile', array('env' => 'HTTP_USER_AGENT', 'options' => array('Fennec')));`
482:  *
483:  * ### Callback detectors
484:  *
485:  * Callback detectors allow you to provide a 'callback' type to handle the check.  The callback will
486:  * receive the request object as its only parameter.
487:  *
488:  * e.g `addDetector('custom', array('callback' => array('SomeClass', 'somemethod')));`
489:  *
490:  * @param string $name The name of the detector.
491:  * @param array $options  The options for the detector definition.  See above.
492:  * @return void
493:  */
494:     public function addDetector($name, $options) {
495:         if (isset($this->_detectors[$name]) && isset($options['options'])) {
496:             $options = Set::merge($this->_detectors[$name], $options);
497:         }
498:         $this->_detectors[$name] = $options;
499:     }
500: 
501: /**
502:  * Add parameters to the request's parsed parameter set. This will overwrite any existing parameters.
503:  * This modifies the parameters available through `$request->params`.
504:  *
505:  * @param array $params Array of parameters to merge in
506:  * @return The current object, you can chain this method.
507:  */
508:     public function addParams($params) {
509:         $this->params = array_merge($this->params, (array)$params);
510:         return $this;
511:     }
512: 
513: /**
514:  * Add paths to the requests' paths vars.  This will overwrite any existing paths.
515:  * Provides an easy way to modify, here, webroot and base.
516:  *
517:  * @param array $paths Array of paths to merge in
518:  * @return CakeRequest the current object, you can chain this method.
519:  */
520:     public function addPaths($paths) {
521:         foreach (array('webroot', 'here', 'base') as $element) {
522:             if (isset($paths[$element])) {
523:                 $this->{$element} = $paths[$element];
524:             }
525:         }
526:         return $this;
527:     }
528: 
529: /**
530:  * Get the value of the current requests url.  Will include named parameters and querystring arguments.
531:  *
532:  * @param boolean $base Include the base path, set to false to trim the base path off.
533:  * @return string the current request url including query string args.
534:  */
535:     public function here($base = true) {
536:         $url = $this->here;
537:         if (!empty($this->query)) {
538:             $url .= '?' . http_build_query($this->query);
539:         }
540:         if (!$base) {
541:             $url = preg_replace('/^' . preg_quote($this->base, '/') . '/', '', $url, 1);
542:         }
543:         return $url;
544:     }
545: 
546: /**
547:  * Read an HTTP header from the Request information.
548:  *
549:  * @param string $name Name of the header you want.
550:  * @return mixed Either false on no header being set or the value of the header.
551:  */
552:     public static function header($name) {
553:         $name = 'HTTP_' . strtoupper(str_replace('-', '_', $name));
554:         if (!empty($_SERVER[$name])) {
555:             return $_SERVER[$name];
556:         }
557:         return false;
558:     }
559: 
560: /**
561:  * Get the HTTP method used for this request.
562:  * There are a few ways to specify a method.
563:  *
564:  * - If your client supports it you can use native HTTP methods.
565:  * - You can set the HTTP-X-Method-Override header.
566:  * - You can submit an input with the name `_method`
567:  *
568:  * Any of these 3 approaches can be used to set the HTTP method used
569:  * by CakePHP internally, and will effect the result of this method.
570:  *
571:  * @return string The name of the HTTP method used.
572:  */
573:     public function method() {
574:         return env('REQUEST_METHOD');
575:     }
576: 
577: /**
578:  * Get the host that the request was handled on.
579:  *
580:  * @return void
581:  */
582:     public function host() {
583:         return env('HTTP_HOST');
584:     }
585: 
586: /**
587:  * Get the domain name and include $tldLength segments of the tld.
588:  *
589:  * @param integer $tldLength Number of segments your tld contains. For example: `example.com` contains 1 tld.
590:  *   While `example.co.uk` contains 2.
591:  * @return string Domain name without subdomains.
592:  */
593:     public function domain($tldLength = 1) {
594:         $segments = explode('.', $this->host());
595:         $domain = array_slice($segments, -1 * ($tldLength + 1));
596:         return implode('.', $domain);
597:     }
598: 
599: /**
600:  * Get the subdomains for a host.
601:  *
602:  * @param integer $tldLength Number of segments your tld contains. For example: `example.com` contains 1 tld.
603:  *   While `example.co.uk` contains 2.
604:  * @return array of subdomains.
605:  */
606:     public function subdomains($tldLength = 1) {
607:         $segments = explode('.', $this->host());
608:         return array_slice($segments, 0, -1 * ($tldLength + 1));
609:     }
610: 
611: /**
612:  * Find out which content types the client accepts or check if they accept a
613:  * particular type of content.
614:  *
615:  * #### Get all types:
616:  *
617:  * `$this->request->accepts();`
618:  *
619:  * #### Check for a single type:
620:  *
621:  * `$this->request->accepts('json');`
622:  *
623:  * This method will order the returned content types by the preference values indicated
624:  * by the client.
625:  *
626:  * @param string $type The content type to check for.  Leave null to get all types a client accepts.
627:  * @return mixed Either an array of all the types the client accepts or a boolean if they accept the
628:  *   provided type.
629:  */
630:     public function accepts($type = null) {
631:         $raw = $this->parseAccept();
632:         $accept = array();
633:         foreach ($raw as $value => $types) {
634:             $accept = array_merge($accept, $types);
635:         }
636:         if ($type === null) {
637:             return $accept;
638:         }
639:         return in_array($type, $accept);
640:     }
641: 
642: /**
643:  * Parse the HTTP_ACCEPT header and return a sorted array with content types
644:  * as the keys, and pref values as the values.
645:  *
646:  * Generally you want to use CakeRequest::accept() to get a simple list
647:  * of the accepted content types.
648:  *
649:  * @return array An array of prefValue => array(content/types)
650:  */
651:     public function parseAccept() {
652:         $accept = array();
653:         $header = explode(',', $this->header('accept'));
654:         foreach (array_filter($header) as $value) {
655:             $prefPos = strpos($value, ';');
656:             if ($prefPos !== false) {
657:                 $prefValue = substr($value, strpos($value, '=') + 1);
658:                 $value = trim(substr($value, 0, $prefPos));
659:             } else {
660:                 $prefValue = '1.0';
661:                 $value = trim($value);
662:             }
663:             if (!isset($accept[$prefValue])) {
664:                 $accept[$prefValue] = array();
665:             }
666:             if ($prefValue) {
667:                 $accept[$prefValue][] = $value;
668:             }
669:         }
670:         krsort($accept);
671:         return $accept;
672:     }
673: 
674: /**
675:  * Get the languages accepted by the client, or check if a specific language is accepted.
676:  *
677:  * Get the list of accepted languages:
678:  *
679:  * {{{ CakeRequest::acceptLanguage(); }}}
680:  *
681:  * Check if a specific language is accepted:
682:  *
683:  * {{{ CakeRequest::acceptLanguage('es-es'); }}}
684:  *
685:  * @param string $language The language to test.
686:  * @return If a $language is provided, a boolean. Otherwise the array of accepted languages.
687:  */
688:     public static function acceptLanguage($language = null) {
689:         $accepts = preg_split('/[;,]/', self::header('Accept-Language'));
690:         foreach ($accepts as &$accept) {
691:             $accept = strtolower($accept);
692:             if (strpos($accept, '_') !== false) {
693:                 $accept = str_replace('_', '-', $accept);
694:             }
695:         }
696:         if ($language === null) {
697:             return $accepts;
698:         }
699:         return in_array($language, $accepts);
700:     }
701: 
702: /**
703:  * Provides a read/write accessor for `$this->data`.  Allows you
704:  * to use a syntax similar to `CakeSession` for reading post data.
705:  *
706:  * ## Reading values.
707:  *
708:  * `$request->data('Post.title');`
709:  *
710:  * When reading values you will get `null` for keys/values that do not exist.
711:  *
712:  * ## Writing values
713:  *
714:  * `$request->data('Post.title', 'New post!');`
715:  *
716:  * You can write to any value, even paths/keys that do not exist, and the arrays
717:  * will be created for you.
718:  *
719:  * @param string $name,... Dot separated name of the value to read/write
720:  * @return mixed Either the value being read, or this so you can chain consecutive writes.
721:  */
722:     public function data($name) {
723:         $args = func_get_args();
724:         if (count($args) == 2) {
725:             $this->data = Set::insert($this->data, $name, $args[1]);
726:             return $this;
727:         }
728:         return Set::classicExtract($this->data, $name);
729:     }
730: 
731: /**
732:  * Read data from `php://input`. Useful when interacting with XML or JSON
733:  * request body content.
734:  *
735:  * Getting input with a decoding function:
736:  *
737:  * `$this->request->input('json_decode');`
738:  *
739:  * Getting input using a decoding function, and additional params:
740:  *
741:  * `$this->request->input('Xml::build', array('return' => 'DOMDocument'));`
742:  *
743:  * Any additional parameters are applied to the callback in the order they are given.
744:  *
745:  * @param string $callback A decoding callback that will convert the string data to another
746:  *     representation. Leave empty to access the raw input data. You can also
747:  *     supply additional parameters for the decoding callback using var args, see above.
748:  * @return The decoded/processed request data.
749:  */
750:     public function input($callback = null) {
751:         $input = $this->_readInput();
752:         $args = func_get_args();
753:         if (!empty($args)) {
754:             $callback = array_shift($args);
755:             array_unshift($args, $input);
756:             return call_user_func_array($callback, $args);
757:         }
758:         return $input;
759:     }
760: 
761: /**
762:  * Read data from php://input, mocked in tests.
763:  *
764:  * @return string contents of php://input
765:  */
766:     protected function _readInput() {
767:         if (empty($this->_input)) {
768:             $fh = fopen('php://input', 'r');
769:             $content = stream_get_contents($fh);
770:             fclose($fh);
771:             $this->_input = $content;
772:         }
773:         return $this->_input;
774:     }
775: 
776: /**
777:  * Array access read implementation
778:  *
779:  * @param string $name Name of the key being accessed.
780:  * @return mixed
781:  */
782:     public function offsetGet($name) {
783:         if (isset($this->params[$name])) {
784:             return $this->params[$name];
785:         }
786:         if ($name == 'url') {
787:             return $this->query;
788:         }
789:         if ($name == 'data') {
790:             return $this->data;
791:         }
792:         return null;
793:     }
794: 
795: /**
796:  * Array access write implementation
797:  *
798:  * @param string $name Name of the key being written
799:  * @param mixed $value The value being written.
800:  * @return void
801:  */
802:     public function offsetSet($name, $value) {
803:         $this->params[$name] = $value;
804:     }
805: 
806: /**
807:  * Array access isset() implementation
808:  *
809:  * @param string $name thing to check.
810:  * @return boolean
811:  */
812:     public function offsetExists($name) {
813:         return isset($this->params[$name]);
814:     }
815: 
816: /**
817:  * Array access unset() implementation
818:  *
819:  * @param string $name Name to unset.
820:  * @return void
821:  */
822:     public function offsetUnset($name) {
823:         unset($this->params[$name]);
824:     }
825: }
826: 
OpenHub
Rackspace
Rackspace
  • Business Solutions
  • Showcase
  • Documentation
  • Book
  • API
  • Videos
  • Reporting Security Issues
  • Privacy Policy
  • Logos & Trademarks
  • Community
  • Get Involved
  • Issues (GitHub)
  • Bakery
  • Featured Resources
  • Training
  • Meetups
  • My CakePHP
  • CakeFest
  • Newsletter
  • Linkedin
  • YouTube
  • Facebook
  • Twitter
  • Mastodon
  • Help & Support
  • Forum
  • Stack Overflow
  • Slack
  • Paid Support

Generated using CakePHP API Docs