Daniel@0: parameters = $parameters; Daniel@0: } Daniel@0: public function all() Daniel@0: { Daniel@0: return $this->parameters; Daniel@0: } Daniel@0: public function keys() Daniel@0: { Daniel@0: return array_keys($this->parameters); Daniel@0: } Daniel@0: public function replace(array $parameters = array()) Daniel@0: { Daniel@0: $this->parameters = $parameters; Daniel@0: } Daniel@0: public function add(array $parameters = array()) Daniel@0: { Daniel@0: $this->parameters = array_replace($this->parameters, $parameters); Daniel@0: } Daniel@0: public function get($path, $default = null, $deep = false) Daniel@0: { Daniel@0: if (!$deep || false === $pos = strpos($path,'[')) { Daniel@0: return array_key_exists($path, $this->parameters) ? $this->parameters[$path] : $default; Daniel@0: } Daniel@0: $root = substr($path, 0, $pos); Daniel@0: if (!array_key_exists($root, $this->parameters)) { Daniel@0: return $default; Daniel@0: } Daniel@0: $value = $this->parameters[$root]; Daniel@0: $currentKey = null; Daniel@0: for ($i = $pos, $c = strlen($path); $i < $c; $i++) { Daniel@0: $char = $path[$i]; Daniel@0: if ('['=== $char) { Daniel@0: if (null !== $currentKey) { Daniel@0: throw new \InvalidArgumentException(sprintf('Malformed path. Unexpected "[" at position %d.', $i)); Daniel@0: } Daniel@0: $currentKey =''; Daniel@0: } elseif (']'=== $char) { Daniel@0: if (null === $currentKey) { Daniel@0: throw new \InvalidArgumentException(sprintf('Malformed path. Unexpected "]" at position %d.', $i)); Daniel@0: } Daniel@0: if (!is_array($value) || !array_key_exists($currentKey, $value)) { Daniel@0: return $default; Daniel@0: } Daniel@0: $value = $value[$currentKey]; Daniel@0: $currentKey = null; Daniel@0: } else { Daniel@0: if (null === $currentKey) { Daniel@0: throw new \InvalidArgumentException(sprintf('Malformed path. Unexpected "%s" at position %d.', $char, $i)); Daniel@0: } Daniel@0: $currentKey .= $char; Daniel@0: } Daniel@0: } Daniel@0: if (null !== $currentKey) { Daniel@0: throw new \InvalidArgumentException(sprintf('Malformed path. Path must end with "]".')); Daniel@0: } Daniel@0: return $value; Daniel@0: } Daniel@0: public function set($key, $value) Daniel@0: { Daniel@0: $this->parameters[$key] = $value; Daniel@0: } Daniel@0: public function has($key) Daniel@0: { Daniel@0: return array_key_exists($key, $this->parameters); Daniel@0: } Daniel@0: public function remove($key) Daniel@0: { Daniel@0: unset($this->parameters[$key]); Daniel@0: } Daniel@0: public function getAlpha($key, $default ='', $deep = false) Daniel@0: { Daniel@0: return preg_replace('/[^[:alpha:]]/','', $this->get($key, $default, $deep)); Daniel@0: } Daniel@0: public function getAlnum($key, $default ='', $deep = false) Daniel@0: { Daniel@0: return preg_replace('/[^[:alnum:]]/','', $this->get($key, $default, $deep)); Daniel@0: } Daniel@0: public function getDigits($key, $default ='', $deep = false) Daniel@0: { Daniel@0: return str_replace(array('-','+'),'', $this->filter($key, $default, $deep, FILTER_SANITIZE_NUMBER_INT)); Daniel@0: } Daniel@0: public function getInt($key, $default = 0, $deep = false) Daniel@0: { Daniel@0: return (int) $this->get($key, $default, $deep); Daniel@0: } Daniel@0: public function filter($key, $default = null, $deep = false, $filter = FILTER_DEFAULT, $options = array()) Daniel@0: { Daniel@0: $value = $this->get($key, $default, $deep); Daniel@0: if (!is_array($options) && $options) { Daniel@0: $options = array('flags'=> $options); Daniel@0: } Daniel@0: if (is_array($value) && !isset($options['flags'])) { Daniel@0: $options['flags'] = FILTER_REQUIRE_ARRAY; Daniel@0: } Daniel@0: return filter_var($value, $filter, $options); Daniel@0: } Daniel@0: public function getIterator() Daniel@0: { Daniel@0: return new \ArrayIterator($this->parameters); Daniel@0: } Daniel@0: public function count() Daniel@0: { Daniel@0: return count($this->parameters); Daniel@0: } Daniel@0: } Daniel@0: } Daniel@0: namespace Symfony\Component\HttpFoundation Daniel@0: { Daniel@0: class HeaderBag implements \IteratorAggregate, \Countable Daniel@0: { Daniel@0: protected $headers = array(); Daniel@0: protected $cacheControl = array(); Daniel@0: public function __construct(array $headers = array()) Daniel@0: { Daniel@0: foreach ($headers as $key => $values) { Daniel@0: $this->set($key, $values); Daniel@0: } Daniel@0: } Daniel@0: public function __toString() Daniel@0: { Daniel@0: if (!$this->headers) { Daniel@0: return''; Daniel@0: } Daniel@0: $max = max(array_map('strlen', array_keys($this->headers))) + 1; Daniel@0: $content =''; Daniel@0: ksort($this->headers); Daniel@0: foreach ($this->headers as $name => $values) { Daniel@0: $name = implode('-', array_map('ucfirst', explode('-', $name))); Daniel@0: foreach ($values as $value) { Daniel@0: $content .= sprintf("%-{$max}s %s\r\n", $name.':', $value); Daniel@0: } Daniel@0: } Daniel@0: return $content; Daniel@0: } Daniel@0: public function all() Daniel@0: { Daniel@0: return $this->headers; Daniel@0: } Daniel@0: public function keys() Daniel@0: { Daniel@0: return array_keys($this->headers); Daniel@0: } Daniel@0: public function replace(array $headers = array()) Daniel@0: { Daniel@0: $this->headers = array(); Daniel@0: $this->add($headers); Daniel@0: } Daniel@0: public function add(array $headers) Daniel@0: { Daniel@0: foreach ($headers as $key => $values) { Daniel@0: $this->set($key, $values); Daniel@0: } Daniel@0: } Daniel@0: public function get($key, $default = null, $first = true) Daniel@0: { Daniel@0: $key = strtr(strtolower($key),'_','-'); Daniel@0: if (!array_key_exists($key, $this->headers)) { Daniel@0: if (null === $default) { Daniel@0: return $first ? null : array(); Daniel@0: } Daniel@0: return $first ? $default : array($default); Daniel@0: } Daniel@0: if ($first) { Daniel@0: return count($this->headers[$key]) ? $this->headers[$key][0] : $default; Daniel@0: } Daniel@0: return $this->headers[$key]; Daniel@0: } Daniel@0: public function set($key, $values, $replace = true) Daniel@0: { Daniel@0: $key = strtr(strtolower($key),'_','-'); Daniel@0: $values = array_values((array) $values); Daniel@0: if (true === $replace || !isset($this->headers[$key])) { Daniel@0: $this->headers[$key] = $values; Daniel@0: } else { Daniel@0: $this->headers[$key] = array_merge($this->headers[$key], $values); Daniel@0: } Daniel@0: if ('cache-control'=== $key) { Daniel@0: $this->cacheControl = $this->parseCacheControl($values[0]); Daniel@0: } Daniel@0: } Daniel@0: public function has($key) Daniel@0: { Daniel@0: return array_key_exists(strtr(strtolower($key),'_','-'), $this->headers); Daniel@0: } Daniel@0: public function contains($key, $value) Daniel@0: { Daniel@0: return in_array($value, $this->get($key, null, false)); Daniel@0: } Daniel@0: public function remove($key) Daniel@0: { Daniel@0: $key = strtr(strtolower($key),'_','-'); Daniel@0: unset($this->headers[$key]); Daniel@0: if ('cache-control'=== $key) { Daniel@0: $this->cacheControl = array(); Daniel@0: } Daniel@0: } Daniel@0: public function getDate($key, \DateTime $default = null) Daniel@0: { Daniel@0: if (null === $value = $this->get($key)) { Daniel@0: return $default; Daniel@0: } Daniel@0: if (false === $date = \DateTime::createFromFormat(DATE_RFC2822, $value)) { Daniel@0: throw new \RuntimeException(sprintf('The %s HTTP header is not parseable (%s).', $key, $value)); Daniel@0: } Daniel@0: return $date; Daniel@0: } Daniel@0: public function addCacheControlDirective($key, $value = true) Daniel@0: { Daniel@0: $this->cacheControl[$key] = $value; Daniel@0: $this->set('Cache-Control', $this->getCacheControlHeader()); Daniel@0: } Daniel@0: public function hasCacheControlDirective($key) Daniel@0: { Daniel@0: return array_key_exists($key, $this->cacheControl); Daniel@0: } Daniel@0: public function getCacheControlDirective($key) Daniel@0: { Daniel@0: return array_key_exists($key, $this->cacheControl) ? $this->cacheControl[$key] : null; Daniel@0: } Daniel@0: public function removeCacheControlDirective($key) Daniel@0: { Daniel@0: unset($this->cacheControl[$key]); Daniel@0: $this->set('Cache-Control', $this->getCacheControlHeader()); Daniel@0: } Daniel@0: public function getIterator() Daniel@0: { Daniel@0: return new \ArrayIterator($this->headers); Daniel@0: } Daniel@0: public function count() Daniel@0: { Daniel@0: return count($this->headers); Daniel@0: } Daniel@0: protected function getCacheControlHeader() Daniel@0: { Daniel@0: $parts = array(); Daniel@0: ksort($this->cacheControl); Daniel@0: foreach ($this->cacheControl as $key => $value) { Daniel@0: if (true === $value) { Daniel@0: $parts[] = $key; Daniel@0: } else { Daniel@0: if (preg_match('#[^a-zA-Z0-9._-]#', $value)) { Daniel@0: $value ='"'.$value.'"'; Daniel@0: } Daniel@0: $parts[] = "$key=$value"; Daniel@0: } Daniel@0: } Daniel@0: return implode(', ', $parts); Daniel@0: } Daniel@0: protected function parseCacheControl($header) Daniel@0: { Daniel@0: $cacheControl = array(); Daniel@0: preg_match_all('#([a-zA-Z][a-zA-Z_-]*)\s*(?:=(?:"([^"]*)"|([^ \t",;]*)))?#', $header, $matches, PREG_SET_ORDER); Daniel@0: foreach ($matches as $match) { Daniel@0: $cacheControl[strtolower($match[1])] = isset($match[3]) ? $match[3] : (isset($match[2]) ? $match[2] : true); Daniel@0: } Daniel@0: return $cacheControl; Daniel@0: } Daniel@0: } Daniel@0: } Daniel@0: namespace Symfony\Component\HttpFoundation Daniel@0: { Daniel@0: use Symfony\Component\HttpFoundation\File\UploadedFile; Daniel@0: class FileBag extends ParameterBag Daniel@0: { Daniel@0: private static $fileKeys = array('error','name','size','tmp_name','type'); Daniel@0: public function __construct(array $parameters = array()) Daniel@0: { Daniel@0: $this->replace($parameters); Daniel@0: } Daniel@0: public function replace(array $files = array()) Daniel@0: { Daniel@0: $this->parameters = array(); Daniel@0: $this->add($files); Daniel@0: } Daniel@0: public function set($key, $value) Daniel@0: { Daniel@0: if (!is_array($value) && !$value instanceof UploadedFile) { Daniel@0: throw new \InvalidArgumentException('An uploaded file must be an array or an instance of UploadedFile.'); Daniel@0: } Daniel@0: parent::set($key, $this->convertFileInformation($value)); Daniel@0: } Daniel@0: public function add(array $files = array()) Daniel@0: { Daniel@0: foreach ($files as $key => $file) { Daniel@0: $this->set($key, $file); Daniel@0: } Daniel@0: } Daniel@0: protected function convertFileInformation($file) Daniel@0: { Daniel@0: if ($file instanceof UploadedFile) { Daniel@0: return $file; Daniel@0: } Daniel@0: $file = $this->fixPhpFilesArray($file); Daniel@0: if (is_array($file)) { Daniel@0: $keys = array_keys($file); Daniel@0: sort($keys); Daniel@0: if ($keys == self::$fileKeys) { Daniel@0: if (UPLOAD_ERR_NO_FILE == $file['error']) { Daniel@0: $file = null; Daniel@0: } else { Daniel@0: $file = new UploadedFile($file['tmp_name'], $file['name'], $file['type'], $file['size'], $file['error']); Daniel@0: } Daniel@0: } else { Daniel@0: $file = array_map(array($this,'convertFileInformation'), $file); Daniel@0: } Daniel@0: } Daniel@0: return $file; Daniel@0: } Daniel@0: protected function fixPhpFilesArray($data) Daniel@0: { Daniel@0: if (!is_array($data)) { Daniel@0: return $data; Daniel@0: } Daniel@0: $keys = array_keys($data); Daniel@0: sort($keys); Daniel@0: if (self::$fileKeys != $keys || !isset($data['name']) || !is_array($data['name'])) { Daniel@0: return $data; Daniel@0: } Daniel@0: $files = $data; Daniel@0: foreach (self::$fileKeys as $k) { Daniel@0: unset($files[$k]); Daniel@0: } Daniel@0: foreach (array_keys($data['name']) as $key) { Daniel@0: $files[$key] = $this->fixPhpFilesArray(array('error'=> $data['error'][$key],'name'=> $data['name'][$key],'type'=> $data['type'][$key],'tmp_name'=> $data['tmp_name'][$key],'size'=> $data['size'][$key], Daniel@0: )); Daniel@0: } Daniel@0: return $files; Daniel@0: } Daniel@0: } Daniel@0: } Daniel@0: namespace Symfony\Component\HttpFoundation Daniel@0: { Daniel@0: class ServerBag extends ParameterBag Daniel@0: { Daniel@0: public function getHeaders() Daniel@0: { Daniel@0: $headers = array(); Daniel@0: $contentHeaders = array('CONTENT_LENGTH'=> true,'CONTENT_MD5'=> true,'CONTENT_TYPE'=> true); Daniel@0: foreach ($this->parameters as $key => $value) { Daniel@0: if (0 === strpos($key,'HTTP_')) { Daniel@0: $headers[substr($key, 5)] = $value; Daniel@0: } Daniel@0: elseif (isset($contentHeaders[$key])) { Daniel@0: $headers[$key] = $value; Daniel@0: } Daniel@0: } Daniel@0: if (isset($this->parameters['PHP_AUTH_USER'])) { Daniel@0: $headers['PHP_AUTH_USER'] = $this->parameters['PHP_AUTH_USER']; Daniel@0: $headers['PHP_AUTH_PW'] = isset($this->parameters['PHP_AUTH_PW']) ? $this->parameters['PHP_AUTH_PW'] :''; Daniel@0: } else { Daniel@0: $authorizationHeader = null; Daniel@0: if (isset($this->parameters['HTTP_AUTHORIZATION'])) { Daniel@0: $authorizationHeader = $this->parameters['HTTP_AUTHORIZATION']; Daniel@0: } elseif (isset($this->parameters['REDIRECT_HTTP_AUTHORIZATION'])) { Daniel@0: $authorizationHeader = $this->parameters['REDIRECT_HTTP_AUTHORIZATION']; Daniel@0: } Daniel@0: if (null !== $authorizationHeader) { Daniel@0: if (0 === stripos($authorizationHeader,'basic ')) { Daniel@0: $exploded = explode(':', base64_decode(substr($authorizationHeader, 6)), 2); Daniel@0: if (count($exploded) == 2) { Daniel@0: list($headers['PHP_AUTH_USER'], $headers['PHP_AUTH_PW']) = $exploded; Daniel@0: } Daniel@0: } elseif (empty($this->parameters['PHP_AUTH_DIGEST']) && (0 === stripos($authorizationHeader,'digest '))) { Daniel@0: $headers['PHP_AUTH_DIGEST'] = $authorizationHeader; Daniel@0: $this->parameters['PHP_AUTH_DIGEST'] = $authorizationHeader; Daniel@0: } Daniel@0: } Daniel@0: } Daniel@0: if (isset($headers['PHP_AUTH_USER'])) { Daniel@0: $headers['AUTHORIZATION'] ='Basic '.base64_encode($headers['PHP_AUTH_USER'].':'.$headers['PHP_AUTH_PW']); Daniel@0: } elseif (isset($headers['PHP_AUTH_DIGEST'])) { Daniel@0: $headers['AUTHORIZATION'] = $headers['PHP_AUTH_DIGEST']; Daniel@0: } Daniel@0: return $headers; Daniel@0: } Daniel@0: } Daniel@0: } Daniel@0: namespace Symfony\Component\HttpFoundation Daniel@0: { Daniel@0: use Symfony\Component\HttpFoundation\Session\SessionInterface; Daniel@0: class Request Daniel@0: { Daniel@0: const HEADER_CLIENT_IP ='client_ip'; Daniel@0: const HEADER_CLIENT_HOST ='client_host'; Daniel@0: const HEADER_CLIENT_PROTO ='client_proto'; Daniel@0: const HEADER_CLIENT_PORT ='client_port'; Daniel@0: protected static $trustedProxies = array(); Daniel@0: protected static $trustedHostPatterns = array(); Daniel@0: protected static $trustedHosts = array(); Daniel@0: protected static $trustedHeaders = array( Daniel@0: self::HEADER_CLIENT_IP =>'X_FORWARDED_FOR', Daniel@0: self::HEADER_CLIENT_HOST =>'X_FORWARDED_HOST', Daniel@0: self::HEADER_CLIENT_PROTO =>'X_FORWARDED_PROTO', Daniel@0: self::HEADER_CLIENT_PORT =>'X_FORWARDED_PORT', Daniel@0: ); Daniel@0: protected static $httpMethodParameterOverride = false; Daniel@0: public $attributes; Daniel@0: public $request; Daniel@0: public $query; Daniel@0: public $server; Daniel@0: public $files; Daniel@0: public $cookies; Daniel@0: public $headers; Daniel@0: protected $content; Daniel@0: protected $languages; Daniel@0: protected $charsets; Daniel@0: protected $encodings; Daniel@0: protected $acceptableContentTypes; Daniel@0: protected $pathInfo; Daniel@0: protected $requestUri; Daniel@0: protected $baseUrl; Daniel@0: protected $basePath; Daniel@0: protected $method; Daniel@0: protected $format; Daniel@0: protected $session; Daniel@0: protected $locale; Daniel@0: protected $defaultLocale ='en'; Daniel@0: protected static $formats; Daniel@0: protected static $requestFactory; Daniel@0: public function __construct(array $query = array(), array $request = array(), array $attributes = array(), array $cookies = array(), array $files = array(), array $server = array(), $content = null) Daniel@0: { Daniel@0: $this->initialize($query, $request, $attributes, $cookies, $files, $server, $content); Daniel@0: } Daniel@0: public function initialize(array $query = array(), array $request = array(), array $attributes = array(), array $cookies = array(), array $files = array(), array $server = array(), $content = null) Daniel@0: { Daniel@0: $this->request = new ParameterBag($request); Daniel@0: $this->query = new ParameterBag($query); Daniel@0: $this->attributes = new ParameterBag($attributes); Daniel@0: $this->cookies = new ParameterBag($cookies); Daniel@0: $this->files = new FileBag($files); Daniel@0: $this->server = new ServerBag($server); Daniel@0: $this->headers = new HeaderBag($this->server->getHeaders()); Daniel@0: $this->content = $content; Daniel@0: $this->languages = null; Daniel@0: $this->charsets = null; Daniel@0: $this->encodings = null; Daniel@0: $this->acceptableContentTypes = null; Daniel@0: $this->pathInfo = null; Daniel@0: $this->requestUri = null; Daniel@0: $this->baseUrl = null; Daniel@0: $this->basePath = null; Daniel@0: $this->method = null; Daniel@0: $this->format = null; Daniel@0: } Daniel@0: public static function createFromGlobals() Daniel@0: { Daniel@0: $server = $_SERVER; Daniel@0: if ('cli-server'=== php_sapi_name()) { Daniel@0: if (array_key_exists('HTTP_CONTENT_LENGTH', $_SERVER)) { Daniel@0: $server['CONTENT_LENGTH'] = $_SERVER['HTTP_CONTENT_LENGTH']; Daniel@0: } Daniel@0: if (array_key_exists('HTTP_CONTENT_TYPE', $_SERVER)) { Daniel@0: $server['CONTENT_TYPE'] = $_SERVER['HTTP_CONTENT_TYPE']; Daniel@0: } Daniel@0: } Daniel@0: $request = self::createRequestFromFactory($_GET, $_POST, array(), $_COOKIE, $_FILES, $server); Daniel@0: if (0 === strpos($request->headers->get('CONTENT_TYPE'),'application/x-www-form-urlencoded') Daniel@0: && in_array(strtoupper($request->server->get('REQUEST_METHOD','GET')), array('PUT','DELETE','PATCH')) Daniel@0: ) { Daniel@0: parse_str($request->getContent(), $data); Daniel@0: $request->request = new ParameterBag($data); Daniel@0: } Daniel@0: return $request; Daniel@0: } Daniel@0: public static function create($uri, $method ='GET', $parameters = array(), $cookies = array(), $files = array(), $server = array(), $content = null) Daniel@0: { Daniel@0: $server = array_replace(array('SERVER_NAME'=>'localhost','SERVER_PORT'=> 80,'HTTP_HOST'=>'localhost','HTTP_USER_AGENT'=>'Symfony/2.X','HTTP_ACCEPT'=>'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8','HTTP_ACCEPT_LANGUAGE'=>'en-us,en;q=0.5','HTTP_ACCEPT_CHARSET'=>'ISO-8859-1,utf-8;q=0.7,*;q=0.7','REMOTE_ADDR'=>'127.0.0.1','SCRIPT_NAME'=>'','SCRIPT_FILENAME'=>'','SERVER_PROTOCOL'=>'HTTP/1.1','REQUEST_TIME'=> time(), Daniel@0: ), $server); Daniel@0: $server['PATH_INFO'] =''; Daniel@0: $server['REQUEST_METHOD'] = strtoupper($method); Daniel@0: $components = parse_url($uri); Daniel@0: if (isset($components['host'])) { Daniel@0: $server['SERVER_NAME'] = $components['host']; Daniel@0: $server['HTTP_HOST'] = $components['host']; Daniel@0: } Daniel@0: if (isset($components['scheme'])) { Daniel@0: if ('https'=== $components['scheme']) { Daniel@0: $server['HTTPS'] ='on'; Daniel@0: $server['SERVER_PORT'] = 443; Daniel@0: } else { Daniel@0: unset($server['HTTPS']); Daniel@0: $server['SERVER_PORT'] = 80; Daniel@0: } Daniel@0: } Daniel@0: if (isset($components['port'])) { Daniel@0: $server['SERVER_PORT'] = $components['port']; Daniel@0: $server['HTTP_HOST'] = $server['HTTP_HOST'].':'.$components['port']; Daniel@0: } Daniel@0: if (isset($components['user'])) { Daniel@0: $server['PHP_AUTH_USER'] = $components['user']; Daniel@0: } Daniel@0: if (isset($components['pass'])) { Daniel@0: $server['PHP_AUTH_PW'] = $components['pass']; Daniel@0: } Daniel@0: if (!isset($components['path'])) { Daniel@0: $components['path'] ='/'; Daniel@0: } Daniel@0: switch (strtoupper($method)) { Daniel@0: case'POST': Daniel@0: case'PUT': Daniel@0: case'DELETE': Daniel@0: if (!isset($server['CONTENT_TYPE'])) { Daniel@0: $server['CONTENT_TYPE'] ='application/x-www-form-urlencoded'; Daniel@0: } Daniel@0: case'PATCH': Daniel@0: $request = $parameters; Daniel@0: $query = array(); Daniel@0: break; Daniel@0: default: Daniel@0: $request = array(); Daniel@0: $query = $parameters; Daniel@0: break; Daniel@0: } Daniel@0: $queryString =''; Daniel@0: if (isset($components['query'])) { Daniel@0: parse_str(html_entity_decode($components['query']), $qs); Daniel@0: if ($query) { Daniel@0: $query = array_replace($qs, $query); Daniel@0: $queryString = http_build_query($query,'','&'); Daniel@0: } else { Daniel@0: $query = $qs; Daniel@0: $queryString = $components['query']; Daniel@0: } Daniel@0: } elseif ($query) { Daniel@0: $queryString = http_build_query($query,'','&'); Daniel@0: } Daniel@0: $server['REQUEST_URI'] = $components['path'].(''!== $queryString ?'?'.$queryString :''); Daniel@0: $server['QUERY_STRING'] = $queryString; Daniel@0: return self::createRequestFromFactory($query, $request, array(), $cookies, $files, $server, $content); Daniel@0: } Daniel@0: public static function setFactory($callable) Daniel@0: { Daniel@0: self::$requestFactory = $callable; Daniel@0: } Daniel@0: public function duplicate(array $query = null, array $request = null, array $attributes = null, array $cookies = null, array $files = null, array $server = null) Daniel@0: { Daniel@0: $dup = clone $this; Daniel@0: if ($query !== null) { Daniel@0: $dup->query = new ParameterBag($query); Daniel@0: } Daniel@0: if ($request !== null) { Daniel@0: $dup->request = new ParameterBag($request); Daniel@0: } Daniel@0: if ($attributes !== null) { Daniel@0: $dup->attributes = new ParameterBag($attributes); Daniel@0: } Daniel@0: if ($cookies !== null) { Daniel@0: $dup->cookies = new ParameterBag($cookies); Daniel@0: } Daniel@0: if ($files !== null) { Daniel@0: $dup->files = new FileBag($files); Daniel@0: } Daniel@0: if ($server !== null) { Daniel@0: $dup->server = new ServerBag($server); Daniel@0: $dup->headers = new HeaderBag($dup->server->getHeaders()); Daniel@0: } Daniel@0: $dup->languages = null; Daniel@0: $dup->charsets = null; Daniel@0: $dup->encodings = null; Daniel@0: $dup->acceptableContentTypes = null; Daniel@0: $dup->pathInfo = null; Daniel@0: $dup->requestUri = null; Daniel@0: $dup->baseUrl = null; Daniel@0: $dup->basePath = null; Daniel@0: $dup->method = null; Daniel@0: $dup->format = null; Daniel@0: if (!$dup->get('_format') && $this->get('_format')) { Daniel@0: $dup->attributes->set('_format', $this->get('_format')); Daniel@0: } Daniel@0: if (!$dup->getRequestFormat(null)) { Daniel@0: $dup->setRequestFormat($this->getRequestFormat(null)); Daniel@0: } Daniel@0: return $dup; Daniel@0: } Daniel@0: public function __clone() Daniel@0: { Daniel@0: $this->query = clone $this->query; Daniel@0: $this->request = clone $this->request; Daniel@0: $this->attributes = clone $this->attributes; Daniel@0: $this->cookies = clone $this->cookies; Daniel@0: $this->files = clone $this->files; Daniel@0: $this->server = clone $this->server; Daniel@0: $this->headers = clone $this->headers; Daniel@0: } Daniel@0: public function __toString() Daniel@0: { Daniel@0: return Daniel@0: sprintf('%s %s %s', $this->getMethod(), $this->getRequestUri(), $this->server->get('SERVER_PROTOCOL'))."\r\n". Daniel@0: $this->headers."\r\n". Daniel@0: $this->getContent(); Daniel@0: } Daniel@0: public function overrideGlobals() Daniel@0: { Daniel@0: $this->server->set('QUERY_STRING', static::normalizeQueryString(http_build_query($this->query->all(), null,'&'))); Daniel@0: $_GET = $this->query->all(); Daniel@0: $_POST = $this->request->all(); Daniel@0: $_SERVER = $this->server->all(); Daniel@0: $_COOKIE = $this->cookies->all(); Daniel@0: foreach ($this->headers->all() as $key => $value) { Daniel@0: $key = strtoupper(str_replace('-','_', $key)); Daniel@0: if (in_array($key, array('CONTENT_TYPE','CONTENT_LENGTH'))) { Daniel@0: $_SERVER[$key] = implode(', ', $value); Daniel@0: } else { Daniel@0: $_SERVER['HTTP_'.$key] = implode(', ', $value); Daniel@0: } Daniel@0: } Daniel@0: $request = array('g'=> $_GET,'p'=> $_POST,'c'=> $_COOKIE); Daniel@0: $requestOrder = ini_get('request_order') ?: ini_get('variables_order'); Daniel@0: $requestOrder = preg_replace('#[^cgp]#','', strtolower($requestOrder)) ?:'gp'; Daniel@0: $_REQUEST = array(); Daniel@0: foreach (str_split($requestOrder) as $order) { Daniel@0: $_REQUEST = array_merge($_REQUEST, $request[$order]); Daniel@0: } Daniel@0: } Daniel@0: public static function setTrustedProxies(array $proxies) Daniel@0: { Daniel@0: self::$trustedProxies = $proxies; Daniel@0: } Daniel@0: public static function getTrustedProxies() Daniel@0: { Daniel@0: return self::$trustedProxies; Daniel@0: } Daniel@0: public static function setTrustedHosts(array $hostPatterns) Daniel@0: { Daniel@0: self::$trustedHostPatterns = array_map(function ($hostPattern) { Daniel@0: return sprintf('{%s}i', str_replace('}','\\}', $hostPattern)); Daniel@0: }, $hostPatterns); Daniel@0: self::$trustedHosts = array(); Daniel@0: } Daniel@0: public static function getTrustedHosts() Daniel@0: { Daniel@0: return self::$trustedHostPatterns; Daniel@0: } Daniel@0: public static function setTrustedHeaderName($key, $value) Daniel@0: { Daniel@0: if (!array_key_exists($key, self::$trustedHeaders)) { Daniel@0: throw new \InvalidArgumentException(sprintf('Unable to set the trusted header name for key "%s".', $key)); Daniel@0: } Daniel@0: self::$trustedHeaders[$key] = $value; Daniel@0: } Daniel@0: public static function getTrustedHeaderName($key) Daniel@0: { Daniel@0: if (!array_key_exists($key, self::$trustedHeaders)) { Daniel@0: throw new \InvalidArgumentException(sprintf('Unable to get the trusted header name for key "%s".', $key)); Daniel@0: } Daniel@0: return self::$trustedHeaders[$key]; Daniel@0: } Daniel@0: public static function normalizeQueryString($qs) Daniel@0: { Daniel@0: if (''== $qs) { Daniel@0: return''; Daniel@0: } Daniel@0: $parts = array(); Daniel@0: $order = array(); Daniel@0: foreach (explode('&', $qs) as $param) { Daniel@0: if (''=== $param ||'='=== $param[0]) { Daniel@0: continue; Daniel@0: } Daniel@0: $keyValuePair = explode('=', $param, 2); Daniel@0: $parts[] = isset($keyValuePair[1]) ? Daniel@0: rawurlencode(urldecode($keyValuePair[0])).'='.rawurlencode(urldecode($keyValuePair[1])) : Daniel@0: rawurlencode(urldecode($keyValuePair[0])); Daniel@0: $order[] = urldecode($keyValuePair[0]); Daniel@0: } Daniel@0: array_multisort($order, SORT_ASC, $parts); Daniel@0: return implode('&', $parts); Daniel@0: } Daniel@0: public static function enableHttpMethodParameterOverride() Daniel@0: { Daniel@0: self::$httpMethodParameterOverride = true; Daniel@0: } Daniel@0: public static function getHttpMethodParameterOverride() Daniel@0: { Daniel@0: return self::$httpMethodParameterOverride; Daniel@0: } Daniel@0: public function get($key, $default = null, $deep = false) Daniel@0: { Daniel@0: if ($this !== $result = $this->query->get($key, $this, $deep)) { Daniel@0: return $result; Daniel@0: } Daniel@0: if ($this !== $result = $this->attributes->get($key, $this, $deep)) { Daniel@0: return $result; Daniel@0: } Daniel@0: if ($this !== $result = $this->request->get($key, $this, $deep)) { Daniel@0: return $result; Daniel@0: } Daniel@0: return $default; Daniel@0: } Daniel@0: public function getSession() Daniel@0: { Daniel@0: return $this->session; Daniel@0: } Daniel@0: public function hasPreviousSession() Daniel@0: { Daniel@0: return $this->hasSession() && $this->cookies->has($this->session->getName()); Daniel@0: } Daniel@0: public function hasSession() Daniel@0: { Daniel@0: return null !== $this->session; Daniel@0: } Daniel@0: public function setSession(SessionInterface $session) Daniel@0: { Daniel@0: $this->session = $session; Daniel@0: } Daniel@0: public function getClientIps() Daniel@0: { Daniel@0: $ip = $this->server->get('REMOTE_ADDR'); Daniel@0: if (!self::$trustedProxies) { Daniel@0: return array($ip); Daniel@0: } Daniel@0: if (!self::$trustedHeaders[self::HEADER_CLIENT_IP] || !$this->headers->has(self::$trustedHeaders[self::HEADER_CLIENT_IP])) { Daniel@0: return array($ip); Daniel@0: } Daniel@0: $clientIps = array_map('trim', explode(',', $this->headers->get(self::$trustedHeaders[self::HEADER_CLIENT_IP]))); Daniel@0: $clientIps[] = $ip; Daniel@0: $ip = $clientIps[0]; Daniel@0: foreach ($clientIps as $key => $clientIp) { Daniel@0: if (preg_match('{((?:\d+\.){3}\d+)\:\d+}', $clientIp, $match)) { Daniel@0: $clientIps[$key] = $clientIp = $match[1]; Daniel@0: } Daniel@0: if (IpUtils::checkIp($clientIp, self::$trustedProxies)) { Daniel@0: unset($clientIps[$key]); Daniel@0: } Daniel@0: } Daniel@0: return $clientIps ? array_reverse($clientIps) : array($ip); Daniel@0: } Daniel@0: public function getClientIp() Daniel@0: { Daniel@0: $ipAddresses = $this->getClientIps(); Daniel@0: return $ipAddresses[0]; Daniel@0: } Daniel@0: public function getScriptName() Daniel@0: { Daniel@0: return $this->server->get('SCRIPT_NAME', $this->server->get('ORIG_SCRIPT_NAME','')); Daniel@0: } Daniel@0: public function getPathInfo() Daniel@0: { Daniel@0: if (null === $this->pathInfo) { Daniel@0: $this->pathInfo = $this->preparePathInfo(); Daniel@0: } Daniel@0: return $this->pathInfo; Daniel@0: } Daniel@0: public function getBasePath() Daniel@0: { Daniel@0: if (null === $this->basePath) { Daniel@0: $this->basePath = $this->prepareBasePath(); Daniel@0: } Daniel@0: return $this->basePath; Daniel@0: } Daniel@0: public function getBaseUrl() Daniel@0: { Daniel@0: if (null === $this->baseUrl) { Daniel@0: $this->baseUrl = $this->prepareBaseUrl(); Daniel@0: } Daniel@0: return $this->baseUrl; Daniel@0: } Daniel@0: public function getScheme() Daniel@0: { Daniel@0: return $this->isSecure() ?'https':'http'; Daniel@0: } Daniel@0: public function getPort() Daniel@0: { Daniel@0: if (self::$trustedProxies) { Daniel@0: if (self::$trustedHeaders[self::HEADER_CLIENT_PORT] && $port = $this->headers->get(self::$trustedHeaders[self::HEADER_CLIENT_PORT])) { Daniel@0: return $port; Daniel@0: } Daniel@0: if (self::$trustedHeaders[self::HEADER_CLIENT_PROTO] &&'https'=== $this->headers->get(self::$trustedHeaders[self::HEADER_CLIENT_PROTO],'http')) { Daniel@0: return 443; Daniel@0: } Daniel@0: } Daniel@0: if ($host = $this->headers->get('HOST')) { Daniel@0: if ($host[0] ==='[') { Daniel@0: $pos = strpos($host,':', strrpos($host,']')); Daniel@0: } else { Daniel@0: $pos = strrpos($host,':'); Daniel@0: } Daniel@0: if (false !== $pos) { Daniel@0: return intval(substr($host, $pos + 1)); Daniel@0: } Daniel@0: return'https'=== $this->getScheme() ? 443 : 80; Daniel@0: } Daniel@0: return $this->server->get('SERVER_PORT'); Daniel@0: } Daniel@0: public function getUser() Daniel@0: { Daniel@0: return $this->headers->get('PHP_AUTH_USER'); Daniel@0: } Daniel@0: public function getPassword() Daniel@0: { Daniel@0: return $this->headers->get('PHP_AUTH_PW'); Daniel@0: } Daniel@0: public function getUserInfo() Daniel@0: { Daniel@0: $userinfo = $this->getUser(); Daniel@0: $pass = $this->getPassword(); Daniel@0: if (''!= $pass) { Daniel@0: $userinfo .= ":$pass"; Daniel@0: } Daniel@0: return $userinfo; Daniel@0: } Daniel@0: public function getHttpHost() Daniel@0: { Daniel@0: $scheme = $this->getScheme(); Daniel@0: $port = $this->getPort(); Daniel@0: if (('http'== $scheme && $port == 80) || ('https'== $scheme && $port == 443)) { Daniel@0: return $this->getHost(); Daniel@0: } Daniel@0: return $this->getHost().':'.$port; Daniel@0: } Daniel@0: public function getRequestUri() Daniel@0: { Daniel@0: if (null === $this->requestUri) { Daniel@0: $this->requestUri = $this->prepareRequestUri(); Daniel@0: } Daniel@0: return $this->requestUri; Daniel@0: } Daniel@0: public function getSchemeAndHttpHost() Daniel@0: { Daniel@0: return $this->getScheme().'://'.$this->getHttpHost(); Daniel@0: } Daniel@0: public function getUri() Daniel@0: { Daniel@0: if (null !== $qs = $this->getQueryString()) { Daniel@0: $qs ='?'.$qs; Daniel@0: } Daniel@0: return $this->getSchemeAndHttpHost().$this->getBaseUrl().$this->getPathInfo().$qs; Daniel@0: } Daniel@0: public function getUriForPath($path) Daniel@0: { Daniel@0: return $this->getSchemeAndHttpHost().$this->getBaseUrl().$path; Daniel@0: } Daniel@0: public function getQueryString() Daniel@0: { Daniel@0: $qs = static::normalizeQueryString($this->server->get('QUERY_STRING')); Daniel@0: return''=== $qs ? null : $qs; Daniel@0: } Daniel@0: public function isSecure() Daniel@0: { Daniel@0: if (self::$trustedProxies && self::$trustedHeaders[self::HEADER_CLIENT_PROTO] && $proto = $this->headers->get(self::$trustedHeaders[self::HEADER_CLIENT_PROTO])) { Daniel@0: return in_array(strtolower(current(explode(',', $proto))), array('https','on','ssl','1')); Daniel@0: } Daniel@0: $https = $this->server->get('HTTPS'); Daniel@0: return !empty($https) &&'off'!== strtolower($https); Daniel@0: } Daniel@0: public function getHost() Daniel@0: { Daniel@0: if (self::$trustedProxies && self::$trustedHeaders[self::HEADER_CLIENT_HOST] && $host = $this->headers->get(self::$trustedHeaders[self::HEADER_CLIENT_HOST])) { Daniel@0: $elements = explode(',', $host); Daniel@0: $host = $elements[count($elements) - 1]; Daniel@0: } elseif (!$host = $this->headers->get('HOST')) { Daniel@0: if (!$host = $this->server->get('SERVER_NAME')) { Daniel@0: $host = $this->server->get('SERVER_ADDR',''); Daniel@0: } Daniel@0: } Daniel@0: $host = strtolower(preg_replace('/:\d+$/','', trim($host))); Daniel@0: if ($host &&''!== preg_replace('/(?:^\[)?[a-zA-Z0-9-:\]_]+\.?/','', $host)) { Daniel@0: throw new \UnexpectedValueException(sprintf('Invalid Host "%s"', $host)); Daniel@0: } Daniel@0: if (count(self::$trustedHostPatterns) > 0) { Daniel@0: if (in_array($host, self::$trustedHosts)) { Daniel@0: return $host; Daniel@0: } Daniel@0: foreach (self::$trustedHostPatterns as $pattern) { Daniel@0: if (preg_match($pattern, $host)) { Daniel@0: self::$trustedHosts[] = $host; Daniel@0: return $host; Daniel@0: } Daniel@0: } Daniel@0: throw new \UnexpectedValueException(sprintf('Untrusted Host "%s"', $host)); Daniel@0: } Daniel@0: return $host; Daniel@0: } Daniel@0: public function setMethod($method) Daniel@0: { Daniel@0: $this->method = null; Daniel@0: $this->server->set('REQUEST_METHOD', $method); Daniel@0: } Daniel@0: public function getMethod() Daniel@0: { Daniel@0: if (null === $this->method) { Daniel@0: $this->method = strtoupper($this->server->get('REQUEST_METHOD','GET')); Daniel@0: if ('POST'=== $this->method) { Daniel@0: if ($method = $this->headers->get('X-HTTP-METHOD-OVERRIDE')) { Daniel@0: $this->method = strtoupper($method); Daniel@0: } elseif (self::$httpMethodParameterOverride) { Daniel@0: $this->method = strtoupper($this->request->get('_method', $this->query->get('_method','POST'))); Daniel@0: } Daniel@0: } Daniel@0: } Daniel@0: return $this->method; Daniel@0: } Daniel@0: public function getRealMethod() Daniel@0: { Daniel@0: return strtoupper($this->server->get('REQUEST_METHOD','GET')); Daniel@0: } Daniel@0: public function getMimeType($format) Daniel@0: { Daniel@0: if (null === static::$formats) { Daniel@0: static::initializeFormats(); Daniel@0: } Daniel@0: return isset(static::$formats[$format]) ? static::$formats[$format][0] : null; Daniel@0: } Daniel@0: public function getFormat($mimeType) Daniel@0: { Daniel@0: if (false !== $pos = strpos($mimeType,';')) { Daniel@0: $mimeType = substr($mimeType, 0, $pos); Daniel@0: } Daniel@0: if (null === static::$formats) { Daniel@0: static::initializeFormats(); Daniel@0: } Daniel@0: foreach (static::$formats as $format => $mimeTypes) { Daniel@0: if (in_array($mimeType, (array) $mimeTypes)) { Daniel@0: return $format; Daniel@0: } Daniel@0: } Daniel@0: } Daniel@0: public function setFormat($format, $mimeTypes) Daniel@0: { Daniel@0: if (null === static::$formats) { Daniel@0: static::initializeFormats(); Daniel@0: } Daniel@0: static::$formats[$format] = is_array($mimeTypes) ? $mimeTypes : array($mimeTypes); Daniel@0: } Daniel@0: public function getRequestFormat($default ='html') Daniel@0: { Daniel@0: if (null === $this->format) { Daniel@0: $this->format = $this->get('_format', $default); Daniel@0: } Daniel@0: return $this->format; Daniel@0: } Daniel@0: public function setRequestFormat($format) Daniel@0: { Daniel@0: $this->format = $format; Daniel@0: } Daniel@0: public function getContentType() Daniel@0: { Daniel@0: return $this->getFormat($this->headers->get('CONTENT_TYPE')); Daniel@0: } Daniel@0: public function setDefaultLocale($locale) Daniel@0: { Daniel@0: $this->defaultLocale = $locale; Daniel@0: if (null === $this->locale) { Daniel@0: $this->setPhpDefaultLocale($locale); Daniel@0: } Daniel@0: } Daniel@0: public function getDefaultLocale() Daniel@0: { Daniel@0: return $this->defaultLocale; Daniel@0: } Daniel@0: public function setLocale($locale) Daniel@0: { Daniel@0: $this->setPhpDefaultLocale($this->locale = $locale); Daniel@0: } Daniel@0: public function getLocale() Daniel@0: { Daniel@0: return null === $this->locale ? $this->defaultLocale : $this->locale; Daniel@0: } Daniel@0: public function isMethod($method) Daniel@0: { Daniel@0: return $this->getMethod() === strtoupper($method); Daniel@0: } Daniel@0: public function isMethodSafe() Daniel@0: { Daniel@0: return in_array($this->getMethod(), array('GET','HEAD')); Daniel@0: } Daniel@0: public function getContent($asResource = false) Daniel@0: { Daniel@0: if (false === $this->content || (true === $asResource && null !== $this->content)) { Daniel@0: throw new \LogicException('getContent() can only be called once when using the resource return type.'); Daniel@0: } Daniel@0: if (true === $asResource) { Daniel@0: $this->content = false; Daniel@0: return fopen('php://input','rb'); Daniel@0: } Daniel@0: if (null === $this->content) { Daniel@0: $this->content = file_get_contents('php://input'); Daniel@0: } Daniel@0: return $this->content; Daniel@0: } Daniel@0: public function getETags() Daniel@0: { Daniel@0: return preg_split('/\s*,\s*/', $this->headers->get('if_none_match'), null, PREG_SPLIT_NO_EMPTY); Daniel@0: } Daniel@0: public function isNoCache() Daniel@0: { Daniel@0: return $this->headers->hasCacheControlDirective('no-cache') ||'no-cache'== $this->headers->get('Pragma'); Daniel@0: } Daniel@0: public function getPreferredLanguage(array $locales = null) Daniel@0: { Daniel@0: $preferredLanguages = $this->getLanguages(); Daniel@0: if (empty($locales)) { Daniel@0: return isset($preferredLanguages[0]) ? $preferredLanguages[0] : null; Daniel@0: } Daniel@0: if (!$preferredLanguages) { Daniel@0: return $locales[0]; Daniel@0: } Daniel@0: $extendedPreferredLanguages = array(); Daniel@0: foreach ($preferredLanguages as $language) { Daniel@0: $extendedPreferredLanguages[] = $language; Daniel@0: if (false !== $position = strpos($language,'_')) { Daniel@0: $superLanguage = substr($language, 0, $position); Daniel@0: if (!in_array($superLanguage, $preferredLanguages)) { Daniel@0: $extendedPreferredLanguages[] = $superLanguage; Daniel@0: } Daniel@0: } Daniel@0: } Daniel@0: $preferredLanguages = array_values(array_intersect($extendedPreferredLanguages, $locales)); Daniel@0: return isset($preferredLanguages[0]) ? $preferredLanguages[0] : $locales[0]; Daniel@0: } Daniel@0: public function getLanguages() Daniel@0: { Daniel@0: if (null !== $this->languages) { Daniel@0: return $this->languages; Daniel@0: } Daniel@0: $languages = AcceptHeader::fromString($this->headers->get('Accept-Language'))->all(); Daniel@0: $this->languages = array(); Daniel@0: foreach (array_keys($languages) as $lang) { Daniel@0: if (strstr($lang,'-')) { Daniel@0: $codes = explode('-', $lang); Daniel@0: if ($codes[0] =='i') { Daniel@0: if (count($codes) > 1) { Daniel@0: $lang = $codes[1]; Daniel@0: } Daniel@0: } else { Daniel@0: for ($i = 0, $max = count($codes); $i < $max; $i++) { Daniel@0: if ($i == 0) { Daniel@0: $lang = strtolower($codes[0]); Daniel@0: } else { Daniel@0: $lang .='_'.strtoupper($codes[$i]); Daniel@0: } Daniel@0: } Daniel@0: } Daniel@0: } Daniel@0: $this->languages[] = $lang; Daniel@0: } Daniel@0: return $this->languages; Daniel@0: } Daniel@0: public function getCharsets() Daniel@0: { Daniel@0: if (null !== $this->charsets) { Daniel@0: return $this->charsets; Daniel@0: } Daniel@0: return $this->charsets = array_keys(AcceptHeader::fromString($this->headers->get('Accept-Charset'))->all()); Daniel@0: } Daniel@0: public function getEncodings() Daniel@0: { Daniel@0: if (null !== $this->encodings) { Daniel@0: return $this->encodings; Daniel@0: } Daniel@0: return $this->encodings = array_keys(AcceptHeader::fromString($this->headers->get('Accept-Encoding'))->all()); Daniel@0: } Daniel@0: public function getAcceptableContentTypes() Daniel@0: { Daniel@0: if (null !== $this->acceptableContentTypes) { Daniel@0: return $this->acceptableContentTypes; Daniel@0: } Daniel@0: return $this->acceptableContentTypes = array_keys(AcceptHeader::fromString($this->headers->get('Accept'))->all()); Daniel@0: } Daniel@0: public function isXmlHttpRequest() Daniel@0: { Daniel@0: return'XMLHttpRequest'== $this->headers->get('X-Requested-With'); Daniel@0: } Daniel@0: protected function prepareRequestUri() Daniel@0: { Daniel@0: $requestUri =''; Daniel@0: if ($this->headers->has('X_ORIGINAL_URL')) { Daniel@0: $requestUri = $this->headers->get('X_ORIGINAL_URL'); Daniel@0: $this->headers->remove('X_ORIGINAL_URL'); Daniel@0: $this->server->remove('HTTP_X_ORIGINAL_URL'); Daniel@0: $this->server->remove('UNENCODED_URL'); Daniel@0: $this->server->remove('IIS_WasUrlRewritten'); Daniel@0: } elseif ($this->headers->has('X_REWRITE_URL')) { Daniel@0: $requestUri = $this->headers->get('X_REWRITE_URL'); Daniel@0: $this->headers->remove('X_REWRITE_URL'); Daniel@0: } elseif ($this->server->get('IIS_WasUrlRewritten') =='1'&& $this->server->get('UNENCODED_URL') !='') { Daniel@0: $requestUri = $this->server->get('UNENCODED_URL'); Daniel@0: $this->server->remove('UNENCODED_URL'); Daniel@0: $this->server->remove('IIS_WasUrlRewritten'); Daniel@0: } elseif ($this->server->has('REQUEST_URI')) { Daniel@0: $requestUri = $this->server->get('REQUEST_URI'); Daniel@0: $schemeAndHttpHost = $this->getSchemeAndHttpHost(); Daniel@0: if (strpos($requestUri, $schemeAndHttpHost) === 0) { Daniel@0: $requestUri = substr($requestUri, strlen($schemeAndHttpHost)); Daniel@0: } Daniel@0: } elseif ($this->server->has('ORIG_PATH_INFO')) { Daniel@0: $requestUri = $this->server->get('ORIG_PATH_INFO'); Daniel@0: if (''!= $this->server->get('QUERY_STRING')) { Daniel@0: $requestUri .='?'.$this->server->get('QUERY_STRING'); Daniel@0: } Daniel@0: $this->server->remove('ORIG_PATH_INFO'); Daniel@0: } Daniel@0: $this->server->set('REQUEST_URI', $requestUri); Daniel@0: return $requestUri; Daniel@0: } Daniel@0: protected function prepareBaseUrl() Daniel@0: { Daniel@0: $filename = basename($this->server->get('SCRIPT_FILENAME')); Daniel@0: if (basename($this->server->get('SCRIPT_NAME')) === $filename) { Daniel@0: $baseUrl = $this->server->get('SCRIPT_NAME'); Daniel@0: } elseif (basename($this->server->get('PHP_SELF')) === $filename) { Daniel@0: $baseUrl = $this->server->get('PHP_SELF'); Daniel@0: } elseif (basename($this->server->get('ORIG_SCRIPT_NAME')) === $filename) { Daniel@0: $baseUrl = $this->server->get('ORIG_SCRIPT_NAME'); } else { Daniel@0: $path = $this->server->get('PHP_SELF',''); Daniel@0: $file = $this->server->get('SCRIPT_FILENAME',''); Daniel@0: $segs = explode('/', trim($file,'/')); Daniel@0: $segs = array_reverse($segs); Daniel@0: $index = 0; Daniel@0: $last = count($segs); Daniel@0: $baseUrl =''; Daniel@0: do { Daniel@0: $seg = $segs[$index]; Daniel@0: $baseUrl ='/'.$seg.$baseUrl; Daniel@0: ++$index; Daniel@0: } while ($last > $index && (false !== $pos = strpos($path, $baseUrl)) && 0 != $pos); Daniel@0: } Daniel@0: $requestUri = $this->getRequestUri(); Daniel@0: if ($baseUrl && false !== $prefix = $this->getUrlencodedPrefix($requestUri, $baseUrl)) { Daniel@0: return $prefix; Daniel@0: } Daniel@0: if ($baseUrl && false !== $prefix = $this->getUrlencodedPrefix($requestUri, dirname($baseUrl).'/')) { Daniel@0: return rtrim($prefix,'/'); Daniel@0: } Daniel@0: $truncatedRequestUri = $requestUri; Daniel@0: if (false !== $pos = strpos($requestUri,'?')) { Daniel@0: $truncatedRequestUri = substr($requestUri, 0, $pos); Daniel@0: } Daniel@0: $basename = basename($baseUrl); Daniel@0: if (empty($basename) || !strpos(rawurldecode($truncatedRequestUri), $basename)) { Daniel@0: return''; Daniel@0: } Daniel@0: if (strlen($requestUri) >= strlen($baseUrl) && (false !== $pos = strpos($requestUri, $baseUrl)) && $pos !== 0) { Daniel@0: $baseUrl = substr($requestUri, 0, $pos + strlen($baseUrl)); Daniel@0: } Daniel@0: return rtrim($baseUrl,'/'); Daniel@0: } Daniel@0: protected function prepareBasePath() Daniel@0: { Daniel@0: $filename = basename($this->server->get('SCRIPT_FILENAME')); Daniel@0: $baseUrl = $this->getBaseUrl(); Daniel@0: if (empty($baseUrl)) { Daniel@0: return''; Daniel@0: } Daniel@0: if (basename($baseUrl) === $filename) { Daniel@0: $basePath = dirname($baseUrl); Daniel@0: } else { Daniel@0: $basePath = $baseUrl; Daniel@0: } Daniel@0: if ('\\'=== DIRECTORY_SEPARATOR) { Daniel@0: $basePath = str_replace('\\','/', $basePath); Daniel@0: } Daniel@0: return rtrim($basePath,'/'); Daniel@0: } Daniel@0: protected function preparePathInfo() Daniel@0: { Daniel@0: $baseUrl = $this->getBaseUrl(); Daniel@0: if (null === ($requestUri = $this->getRequestUri())) { Daniel@0: return'/'; Daniel@0: } Daniel@0: $pathInfo ='/'; Daniel@0: if ($pos = strpos($requestUri,'?')) { Daniel@0: $requestUri = substr($requestUri, 0, $pos); Daniel@0: } Daniel@0: if (null !== $baseUrl && false === $pathInfo = substr($requestUri, strlen($baseUrl))) { Daniel@0: return'/'; Daniel@0: } elseif (null === $baseUrl) { Daniel@0: return $requestUri; Daniel@0: } Daniel@0: return (string) $pathInfo; Daniel@0: } Daniel@0: protected static function initializeFormats() Daniel@0: { Daniel@0: static::$formats = array('html'=> array('text/html','application/xhtml+xml'),'txt'=> array('text/plain'),'js'=> array('application/javascript','application/x-javascript','text/javascript'),'css'=> array('text/css'),'json'=> array('application/json','application/x-json'),'xml'=> array('text/xml','application/xml','application/x-xml'),'rdf'=> array('application/rdf+xml'),'atom'=> array('application/atom+xml'),'rss'=> array('application/rss+xml'), Daniel@0: ); Daniel@0: } Daniel@0: private function setPhpDefaultLocale($locale) Daniel@0: { Daniel@0: try { Daniel@0: if (class_exists('Locale', false)) { Daniel@0: \Locale::setDefault($locale); Daniel@0: } Daniel@0: } catch (\Exception $e) { Daniel@0: } Daniel@0: } Daniel@0: private function getUrlencodedPrefix($string, $prefix) Daniel@0: { Daniel@0: if (0 !== strpos(rawurldecode($string), $prefix)) { Daniel@0: return false; Daniel@0: } Daniel@0: $len = strlen($prefix); Daniel@0: if (preg_match("#^(%[[:xdigit:]]{2}|.){{$len}}#", $string, $match)) { Daniel@0: return $match[0]; Daniel@0: } Daniel@0: return false; Daniel@0: } Daniel@0: private static function createRequestFromFactory(array $query = array(), array $request = array(), array $attributes = array(), array $cookies = array(), array $files = array(), array $server = array(), $content = null) Daniel@0: { Daniel@0: if (self::$requestFactory) { Daniel@0: $request = call_user_func(self::$requestFactory, $query, $request, $attributes, $cookies, $files, $server, $content); Daniel@0: if (!$request instanceof Request) { Daniel@0: throw new \LogicException('The Request factory must return an instance of Symfony\Component\HttpFoundation\Request.'); Daniel@0: } Daniel@0: return $request; Daniel@0: } Daniel@0: return new static($query, $request, $attributes, $cookies, $files, $server, $content); Daniel@0: } Daniel@0: } Daniel@0: } Daniel@0: namespace Symfony\Component\HttpFoundation Daniel@0: { Daniel@0: class Response Daniel@0: { Daniel@0: const HTTP_CONTINUE = 100; Daniel@0: const HTTP_SWITCHING_PROTOCOLS = 101; Daniel@0: const HTTP_PROCESSING = 102; const HTTP_OK = 200; Daniel@0: const HTTP_CREATED = 201; Daniel@0: const HTTP_ACCEPTED = 202; Daniel@0: const HTTP_NON_AUTHORITATIVE_INFORMATION = 203; Daniel@0: const HTTP_NO_CONTENT = 204; Daniel@0: const HTTP_RESET_CONTENT = 205; Daniel@0: const HTTP_PARTIAL_CONTENT = 206; Daniel@0: const HTTP_MULTI_STATUS = 207; const HTTP_ALREADY_REPORTED = 208; const HTTP_IM_USED = 226; const HTTP_MULTIPLE_CHOICES = 300; Daniel@0: const HTTP_MOVED_PERMANENTLY = 301; Daniel@0: const HTTP_FOUND = 302; Daniel@0: const HTTP_SEE_OTHER = 303; Daniel@0: const HTTP_NOT_MODIFIED = 304; Daniel@0: const HTTP_USE_PROXY = 305; Daniel@0: const HTTP_RESERVED = 306; Daniel@0: const HTTP_TEMPORARY_REDIRECT = 307; Daniel@0: const HTTP_PERMANENTLY_REDIRECT = 308; const HTTP_BAD_REQUEST = 400; Daniel@0: const HTTP_UNAUTHORIZED = 401; Daniel@0: const HTTP_PAYMENT_REQUIRED = 402; Daniel@0: const HTTP_FORBIDDEN = 403; Daniel@0: const HTTP_NOT_FOUND = 404; Daniel@0: const HTTP_METHOD_NOT_ALLOWED = 405; Daniel@0: const HTTP_NOT_ACCEPTABLE = 406; Daniel@0: const HTTP_PROXY_AUTHENTICATION_REQUIRED = 407; Daniel@0: const HTTP_REQUEST_TIMEOUT = 408; Daniel@0: const HTTP_CONFLICT = 409; Daniel@0: const HTTP_GONE = 410; Daniel@0: const HTTP_LENGTH_REQUIRED = 411; Daniel@0: const HTTP_PRECONDITION_FAILED = 412; Daniel@0: const HTTP_REQUEST_ENTITY_TOO_LARGE = 413; Daniel@0: const HTTP_REQUEST_URI_TOO_LONG = 414; Daniel@0: const HTTP_UNSUPPORTED_MEDIA_TYPE = 415; Daniel@0: const HTTP_REQUESTED_RANGE_NOT_SATISFIABLE = 416; Daniel@0: const HTTP_EXPECTATION_FAILED = 417; Daniel@0: const HTTP_I_AM_A_TEAPOT = 418; const HTTP_UNPROCESSABLE_ENTITY = 422; const HTTP_LOCKED = 423; const HTTP_FAILED_DEPENDENCY = 424; const HTTP_RESERVED_FOR_WEBDAV_ADVANCED_COLLECTIONS_EXPIRED_PROPOSAL = 425; const HTTP_UPGRADE_REQUIRED = 426; const HTTP_PRECONDITION_REQUIRED = 428; const HTTP_TOO_MANY_REQUESTS = 429; const HTTP_REQUEST_HEADER_FIELDS_TOO_LARGE = 431; const HTTP_INTERNAL_SERVER_ERROR = 500; Daniel@0: const HTTP_NOT_IMPLEMENTED = 501; Daniel@0: const HTTP_BAD_GATEWAY = 502; Daniel@0: const HTTP_SERVICE_UNAVAILABLE = 503; Daniel@0: const HTTP_GATEWAY_TIMEOUT = 504; Daniel@0: const HTTP_VERSION_NOT_SUPPORTED = 505; Daniel@0: const HTTP_VARIANT_ALSO_NEGOTIATES_EXPERIMENTAL = 506; const HTTP_INSUFFICIENT_STORAGE = 507; const HTTP_LOOP_DETECTED = 508; const HTTP_NOT_EXTENDED = 510; const HTTP_NETWORK_AUTHENTICATION_REQUIRED = 511; Daniel@0: public $headers; Daniel@0: protected $content; Daniel@0: protected $version; Daniel@0: protected $statusCode; Daniel@0: protected $statusText; Daniel@0: protected $charset; Daniel@0: public static $statusTexts = array( Daniel@0: 100 =>'Continue', Daniel@0: 101 =>'Switching Protocols', Daniel@0: 102 =>'Processing', 200 =>'OK', Daniel@0: 201 =>'Created', Daniel@0: 202 =>'Accepted', Daniel@0: 203 =>'Non-Authoritative Information', Daniel@0: 204 =>'No Content', Daniel@0: 205 =>'Reset Content', Daniel@0: 206 =>'Partial Content', Daniel@0: 207 =>'Multi-Status', 208 =>'Already Reported', 226 =>'IM Used', 300 =>'Multiple Choices', Daniel@0: 301 =>'Moved Permanently', Daniel@0: 302 =>'Found', Daniel@0: 303 =>'See Other', Daniel@0: 304 =>'Not Modified', Daniel@0: 305 =>'Use Proxy', Daniel@0: 306 =>'Reserved', Daniel@0: 307 =>'Temporary Redirect', Daniel@0: 308 =>'Permanent Redirect', 400 =>'Bad Request', Daniel@0: 401 =>'Unauthorized', Daniel@0: 402 =>'Payment Required', Daniel@0: 403 =>'Forbidden', Daniel@0: 404 =>'Not Found', Daniel@0: 405 =>'Method Not Allowed', Daniel@0: 406 =>'Not Acceptable', Daniel@0: 407 =>'Proxy Authentication Required', Daniel@0: 408 =>'Request Timeout', Daniel@0: 409 =>'Conflict', Daniel@0: 410 =>'Gone', Daniel@0: 411 =>'Length Required', Daniel@0: 412 =>'Precondition Failed', Daniel@0: 413 =>'Request Entity Too Large', Daniel@0: 414 =>'Request-URI Too Long', Daniel@0: 415 =>'Unsupported Media Type', Daniel@0: 416 =>'Requested Range Not Satisfiable', Daniel@0: 417 =>'Expectation Failed', Daniel@0: 418 =>'I\'m a teapot', 422 =>'Unprocessable Entity', 423 =>'Locked', 424 =>'Failed Dependency', 425 =>'Reserved for WebDAV advanced collections expired proposal', 426 =>'Upgrade Required', 428 =>'Precondition Required', 429 =>'Too Many Requests', 431 =>'Request Header Fields Too Large', 500 =>'Internal Server Error', Daniel@0: 501 =>'Not Implemented', Daniel@0: 502 =>'Bad Gateway', Daniel@0: 503 =>'Service Unavailable', Daniel@0: 504 =>'Gateway Timeout', Daniel@0: 505 =>'HTTP Version Not Supported', Daniel@0: 506 =>'Variant Also Negotiates (Experimental)', 507 =>'Insufficient Storage', 508 =>'Loop Detected', 510 =>'Not Extended', 511 =>'Network Authentication Required', ); Daniel@0: public function __construct($content ='', $status = 200, $headers = array()) Daniel@0: { Daniel@0: $this->headers = new ResponseHeaderBag($headers); Daniel@0: $this->setContent($content); Daniel@0: $this->setStatusCode($status); Daniel@0: $this->setProtocolVersion('1.0'); Daniel@0: if (!$this->headers->has('Date')) { Daniel@0: $this->setDate(new \DateTime(null, new \DateTimeZone('UTC'))); Daniel@0: } Daniel@0: } Daniel@0: public static function create($content ='', $status = 200, $headers = array()) Daniel@0: { Daniel@0: return new static($content, $status, $headers); Daniel@0: } Daniel@0: public function __toString() Daniel@0: { Daniel@0: return Daniel@0: sprintf('HTTP/%s %s %s', $this->version, $this->statusCode, $this->statusText)."\r\n". Daniel@0: $this->headers."\r\n". Daniel@0: $this->getContent(); Daniel@0: } Daniel@0: public function __clone() Daniel@0: { Daniel@0: $this->headers = clone $this->headers; Daniel@0: } Daniel@0: public function prepare(Request $request) Daniel@0: { Daniel@0: $headers = $this->headers; Daniel@0: if ($this->isInformational() || $this->isEmpty()) { Daniel@0: $this->setContent(null); Daniel@0: $headers->remove('Content-Type'); Daniel@0: $headers->remove('Content-Length'); Daniel@0: } else { Daniel@0: if (!$headers->has('Content-Type')) { Daniel@0: $format = $request->getRequestFormat(); Daniel@0: if (null !== $format && $mimeType = $request->getMimeType($format)) { Daniel@0: $headers->set('Content-Type', $mimeType); Daniel@0: } Daniel@0: } Daniel@0: $charset = $this->charset ?:'UTF-8'; Daniel@0: if (!$headers->has('Content-Type')) { Daniel@0: $headers->set('Content-Type','text/html; charset='.$charset); Daniel@0: } elseif (0 === stripos($headers->get('Content-Type'),'text/') && false === stripos($headers->get('Content-Type'),'charset')) { Daniel@0: $headers->set('Content-Type', $headers->get('Content-Type').'; charset='.$charset); Daniel@0: } Daniel@0: if ($headers->has('Transfer-Encoding')) { Daniel@0: $headers->remove('Content-Length'); Daniel@0: } Daniel@0: if ($request->isMethod('HEAD')) { Daniel@0: $length = $headers->get('Content-Length'); Daniel@0: $this->setContent(null); Daniel@0: if ($length) { Daniel@0: $headers->set('Content-Length', $length); Daniel@0: } Daniel@0: } Daniel@0: } Daniel@0: if ('HTTP/1.0'!= $request->server->get('SERVER_PROTOCOL')) { Daniel@0: $this->setProtocolVersion('1.1'); Daniel@0: } Daniel@0: if ('1.0'== $this->getProtocolVersion() &&'no-cache'== $this->headers->get('Cache-Control')) { Daniel@0: $this->headers->set('pragma','no-cache'); Daniel@0: $this->headers->set('expires', -1); Daniel@0: } Daniel@0: $this->ensureIEOverSSLCompatibility($request); Daniel@0: return $this; Daniel@0: } Daniel@0: public function sendHeaders() Daniel@0: { Daniel@0: if (headers_sent()) { Daniel@0: return $this; Daniel@0: } Daniel@0: header(sprintf('HTTP/%s %s %s', $this->version, $this->statusCode, $this->statusText), true, $this->statusCode); Daniel@0: foreach ($this->headers->allPreserveCase() as $name => $values) { Daniel@0: foreach ($values as $value) { Daniel@0: header($name.': '.$value, false, $this->statusCode); Daniel@0: } Daniel@0: } Daniel@0: foreach ($this->headers->getCookies() as $cookie) { Daniel@0: setcookie($cookie->getName(), $cookie->getValue(), $cookie->getExpiresTime(), $cookie->getPath(), $cookie->getDomain(), $cookie->isSecure(), $cookie->isHttpOnly()); Daniel@0: } Daniel@0: return $this; Daniel@0: } Daniel@0: public function sendContent() Daniel@0: { Daniel@0: echo $this->content; Daniel@0: return $this; Daniel@0: } Daniel@0: public function send() Daniel@0: { Daniel@0: $this->sendHeaders(); Daniel@0: $this->sendContent(); Daniel@0: if (function_exists('fastcgi_finish_request')) { Daniel@0: fastcgi_finish_request(); Daniel@0: } elseif ('cli'!== PHP_SAPI) { Daniel@0: static::closeOutputBuffers(0, true); Daniel@0: } Daniel@0: return $this; Daniel@0: } Daniel@0: public function setContent($content) Daniel@0: { Daniel@0: if (null !== $content && !is_string($content) && !is_numeric($content) && !is_callable(array($content,'__toString'))) { Daniel@0: throw new \UnexpectedValueException(sprintf('The Response content must be a string or object implementing __toString(), "%s" given.', gettype($content))); Daniel@0: } Daniel@0: $this->content = (string) $content; Daniel@0: return $this; Daniel@0: } Daniel@0: public function getContent() Daniel@0: { Daniel@0: return $this->content; Daniel@0: } Daniel@0: public function setProtocolVersion($version) Daniel@0: { Daniel@0: $this->version = $version; Daniel@0: return $this; Daniel@0: } Daniel@0: public function getProtocolVersion() Daniel@0: { Daniel@0: return $this->version; Daniel@0: } Daniel@0: public function setStatusCode($code, $text = null) Daniel@0: { Daniel@0: $this->statusCode = $code = (int) $code; Daniel@0: if ($this->isInvalid()) { Daniel@0: throw new \InvalidArgumentException(sprintf('The HTTP status code "%s" is not valid.', $code)); Daniel@0: } Daniel@0: if (null === $text) { Daniel@0: $this->statusText = isset(self::$statusTexts[$code]) ? self::$statusTexts[$code] :''; Daniel@0: return $this; Daniel@0: } Daniel@0: if (false === $text) { Daniel@0: $this->statusText =''; Daniel@0: return $this; Daniel@0: } Daniel@0: $this->statusText = $text; Daniel@0: return $this; Daniel@0: } Daniel@0: public function getStatusCode() Daniel@0: { Daniel@0: return $this->statusCode; Daniel@0: } Daniel@0: public function setCharset($charset) Daniel@0: { Daniel@0: $this->charset = $charset; Daniel@0: return $this; Daniel@0: } Daniel@0: public function getCharset() Daniel@0: { Daniel@0: return $this->charset; Daniel@0: } Daniel@0: public function isCacheable() Daniel@0: { Daniel@0: if (!in_array($this->statusCode, array(200, 203, 300, 301, 302, 404, 410))) { Daniel@0: return false; Daniel@0: } Daniel@0: if ($this->headers->hasCacheControlDirective('no-store') || $this->headers->getCacheControlDirective('private')) { Daniel@0: return false; Daniel@0: } Daniel@0: return $this->isValidateable() || $this->isFresh(); Daniel@0: } Daniel@0: public function isFresh() Daniel@0: { Daniel@0: return $this->getTtl() > 0; Daniel@0: } Daniel@0: public function isValidateable() Daniel@0: { Daniel@0: return $this->headers->has('Last-Modified') || $this->headers->has('ETag'); Daniel@0: } Daniel@0: public function setPrivate() Daniel@0: { Daniel@0: $this->headers->removeCacheControlDirective('public'); Daniel@0: $this->headers->addCacheControlDirective('private'); Daniel@0: return $this; Daniel@0: } Daniel@0: public function setPublic() Daniel@0: { Daniel@0: $this->headers->addCacheControlDirective('public'); Daniel@0: $this->headers->removeCacheControlDirective('private'); Daniel@0: return $this; Daniel@0: } Daniel@0: public function mustRevalidate() Daniel@0: { Daniel@0: return $this->headers->hasCacheControlDirective('must-revalidate') || $this->headers->has('proxy-revalidate'); Daniel@0: } Daniel@0: public function getDate() Daniel@0: { Daniel@0: return $this->headers->getDate('Date', new \DateTime()); Daniel@0: } Daniel@0: public function setDate(\DateTime $date) Daniel@0: { Daniel@0: $date->setTimezone(new \DateTimeZone('UTC')); Daniel@0: $this->headers->set('Date', $date->format('D, d M Y H:i:s').' GMT'); Daniel@0: return $this; Daniel@0: } Daniel@0: public function getAge() Daniel@0: { Daniel@0: if (null !== $age = $this->headers->get('Age')) { Daniel@0: return (int) $age; Daniel@0: } Daniel@0: return max(time() - $this->getDate()->format('U'), 0); Daniel@0: } Daniel@0: public function expire() Daniel@0: { Daniel@0: if ($this->isFresh()) { Daniel@0: $this->headers->set('Age', $this->getMaxAge()); Daniel@0: } Daniel@0: return $this; Daniel@0: } Daniel@0: public function getExpires() Daniel@0: { Daniel@0: try { Daniel@0: return $this->headers->getDate('Expires'); Daniel@0: } catch (\RuntimeException $e) { Daniel@0: return \DateTime::createFromFormat(DATE_RFC2822,'Sat, 01 Jan 00 00:00:00 +0000'); Daniel@0: } Daniel@0: } Daniel@0: public function setExpires(\DateTime $date = null) Daniel@0: { Daniel@0: if (null === $date) { Daniel@0: $this->headers->remove('Expires'); Daniel@0: } else { Daniel@0: $date = clone $date; Daniel@0: $date->setTimezone(new \DateTimeZone('UTC')); Daniel@0: $this->headers->set('Expires', $date->format('D, d M Y H:i:s').' GMT'); Daniel@0: } Daniel@0: return $this; Daniel@0: } Daniel@0: public function getMaxAge() Daniel@0: { Daniel@0: if ($this->headers->hasCacheControlDirective('s-maxage')) { Daniel@0: return (int) $this->headers->getCacheControlDirective('s-maxage'); Daniel@0: } Daniel@0: if ($this->headers->hasCacheControlDirective('max-age')) { Daniel@0: return (int) $this->headers->getCacheControlDirective('max-age'); Daniel@0: } Daniel@0: if (null !== $this->getExpires()) { Daniel@0: return $this->getExpires()->format('U') - $this->getDate()->format('U'); Daniel@0: } Daniel@0: } Daniel@0: public function setMaxAge($value) Daniel@0: { Daniel@0: $this->headers->addCacheControlDirective('max-age', $value); Daniel@0: return $this; Daniel@0: } Daniel@0: public function setSharedMaxAge($value) Daniel@0: { Daniel@0: $this->setPublic(); Daniel@0: $this->headers->addCacheControlDirective('s-maxage', $value); Daniel@0: return $this; Daniel@0: } Daniel@0: public function getTtl() Daniel@0: { Daniel@0: if (null !== $maxAge = $this->getMaxAge()) { Daniel@0: return $maxAge - $this->getAge(); Daniel@0: } Daniel@0: } Daniel@0: public function setTtl($seconds) Daniel@0: { Daniel@0: $this->setSharedMaxAge($this->getAge() + $seconds); Daniel@0: return $this; Daniel@0: } Daniel@0: public function setClientTtl($seconds) Daniel@0: { Daniel@0: $this->setMaxAge($this->getAge() + $seconds); Daniel@0: return $this; Daniel@0: } Daniel@0: public function getLastModified() Daniel@0: { Daniel@0: return $this->headers->getDate('Last-Modified'); Daniel@0: } Daniel@0: public function setLastModified(\DateTime $date = null) Daniel@0: { Daniel@0: if (null === $date) { Daniel@0: $this->headers->remove('Last-Modified'); Daniel@0: } else { Daniel@0: $date = clone $date; Daniel@0: $date->setTimezone(new \DateTimeZone('UTC')); Daniel@0: $this->headers->set('Last-Modified', $date->format('D, d M Y H:i:s').' GMT'); Daniel@0: } Daniel@0: return $this; Daniel@0: } Daniel@0: public function getEtag() Daniel@0: { Daniel@0: return $this->headers->get('ETag'); Daniel@0: } Daniel@0: public function setEtag($etag = null, $weak = false) Daniel@0: { Daniel@0: if (null === $etag) { Daniel@0: $this->headers->remove('Etag'); Daniel@0: } else { Daniel@0: if (0 !== strpos($etag,'"')) { Daniel@0: $etag ='"'.$etag.'"'; Daniel@0: } Daniel@0: $this->headers->set('ETag', (true === $weak ?'W/':'').$etag); Daniel@0: } Daniel@0: return $this; Daniel@0: } Daniel@0: public function setCache(array $options) Daniel@0: { Daniel@0: if ($diff = array_diff(array_keys($options), array('etag','last_modified','max_age','s_maxage','private','public'))) { Daniel@0: throw new \InvalidArgumentException(sprintf('Response does not support the following options: "%s".', implode('", "', array_values($diff)))); Daniel@0: } Daniel@0: if (isset($options['etag'])) { Daniel@0: $this->setEtag($options['etag']); Daniel@0: } Daniel@0: if (isset($options['last_modified'])) { Daniel@0: $this->setLastModified($options['last_modified']); Daniel@0: } Daniel@0: if (isset($options['max_age'])) { Daniel@0: $this->setMaxAge($options['max_age']); Daniel@0: } Daniel@0: if (isset($options['s_maxage'])) { Daniel@0: $this->setSharedMaxAge($options['s_maxage']); Daniel@0: } Daniel@0: if (isset($options['public'])) { Daniel@0: if ($options['public']) { Daniel@0: $this->setPublic(); Daniel@0: } else { Daniel@0: $this->setPrivate(); Daniel@0: } Daniel@0: } Daniel@0: if (isset($options['private'])) { Daniel@0: if ($options['private']) { Daniel@0: $this->setPrivate(); Daniel@0: } else { Daniel@0: $this->setPublic(); Daniel@0: } Daniel@0: } Daniel@0: return $this; Daniel@0: } Daniel@0: public function setNotModified() Daniel@0: { Daniel@0: $this->setStatusCode(304); Daniel@0: $this->setContent(null); Daniel@0: foreach (array('Allow','Content-Encoding','Content-Language','Content-Length','Content-MD5','Content-Type','Last-Modified') as $header) { Daniel@0: $this->headers->remove($header); Daniel@0: } Daniel@0: return $this; Daniel@0: } Daniel@0: public function hasVary() Daniel@0: { Daniel@0: return null !== $this->headers->get('Vary'); Daniel@0: } Daniel@0: public function getVary() Daniel@0: { Daniel@0: if (!$vary = $this->headers->get('Vary', null, false)) { Daniel@0: return array(); Daniel@0: } Daniel@0: $ret = array(); Daniel@0: foreach ($vary as $item) { Daniel@0: $ret = array_merge($ret, preg_split('/[\s,]+/', $item)); Daniel@0: } Daniel@0: return $ret; Daniel@0: } Daniel@0: public function setVary($headers, $replace = true) Daniel@0: { Daniel@0: $this->headers->set('Vary', $headers, $replace); Daniel@0: return $this; Daniel@0: } Daniel@0: public function isNotModified(Request $request) Daniel@0: { Daniel@0: if (!$request->isMethodSafe()) { Daniel@0: return false; Daniel@0: } Daniel@0: $notModified = false; Daniel@0: $lastModified = $this->headers->get('Last-Modified'); Daniel@0: $modifiedSince = $request->headers->get('If-Modified-Since'); Daniel@0: if ($etags = $request->getEtags()) { Daniel@0: $notModified = in_array($this->getEtag(), $etags) || in_array('*', $etags); Daniel@0: } Daniel@0: if ($modifiedSince && $lastModified) { Daniel@0: $notModified = strtotime($modifiedSince) >= strtotime($lastModified) && (!$etags || $notModified); Daniel@0: } Daniel@0: if ($notModified) { Daniel@0: $this->setNotModified(); Daniel@0: } Daniel@0: return $notModified; Daniel@0: } Daniel@0: public function isInvalid() Daniel@0: { Daniel@0: return $this->statusCode < 100 || $this->statusCode >= 600; Daniel@0: } Daniel@0: public function isInformational() Daniel@0: { Daniel@0: return $this->statusCode >= 100 && $this->statusCode < 200; Daniel@0: } Daniel@0: public function isSuccessful() Daniel@0: { Daniel@0: return $this->statusCode >= 200 && $this->statusCode < 300; Daniel@0: } Daniel@0: public function isRedirection() Daniel@0: { Daniel@0: return $this->statusCode >= 300 && $this->statusCode < 400; Daniel@0: } Daniel@0: public function isClientError() Daniel@0: { Daniel@0: return $this->statusCode >= 400 && $this->statusCode < 500; Daniel@0: } Daniel@0: public function isServerError() Daniel@0: { Daniel@0: return $this->statusCode >= 500 && $this->statusCode < 600; Daniel@0: } Daniel@0: public function isOk() Daniel@0: { Daniel@0: return 200 === $this->statusCode; Daniel@0: } Daniel@0: public function isForbidden() Daniel@0: { Daniel@0: return 403 === $this->statusCode; Daniel@0: } Daniel@0: public function isNotFound() Daniel@0: { Daniel@0: return 404 === $this->statusCode; Daniel@0: } Daniel@0: public function isRedirect($location = null) Daniel@0: { Daniel@0: return in_array($this->statusCode, array(201, 301, 302, 303, 307, 308)) && (null === $location ?: $location == $this->headers->get('Location')); Daniel@0: } Daniel@0: public function isEmpty() Daniel@0: { Daniel@0: return in_array($this->statusCode, array(204, 304)); Daniel@0: } Daniel@0: public static function closeOutputBuffers($targetLevel, $flush) Daniel@0: { Daniel@0: $status = ob_get_status(true); Daniel@0: $level = count($status); Daniel@0: while ($level-- > $targetLevel Daniel@0: && (!empty($status[$level]['del']) Daniel@0: || (isset($status[$level]['flags']) Daniel@0: && ($status[$level]['flags'] & PHP_OUTPUT_HANDLER_REMOVABLE) Daniel@0: && ($status[$level]['flags'] & ($flush ? PHP_OUTPUT_HANDLER_FLUSHABLE : PHP_OUTPUT_HANDLER_CLEANABLE)) Daniel@0: ) Daniel@0: ) Daniel@0: ) { Daniel@0: if ($flush) { Daniel@0: ob_end_flush(); Daniel@0: } else { Daniel@0: ob_end_clean(); Daniel@0: } Daniel@0: } Daniel@0: } Daniel@0: protected function ensureIEOverSSLCompatibility(Request $request) Daniel@0: { Daniel@0: if (false !== stripos($this->headers->get('Content-Disposition'),'attachment') && preg_match('/MSIE (.*?);/i', $request->server->get('HTTP_USER_AGENT'), $match) == 1 && true === $request->isSecure()) { Daniel@0: if (intval(preg_replace("/(MSIE )(.*?);/","$2", $match[0])) < 9) { Daniel@0: $this->headers->remove('Cache-Control'); Daniel@0: } Daniel@0: } Daniel@0: } Daniel@0: } Daniel@0: } Daniel@0: namespace Symfony\Component\HttpFoundation Daniel@0: { Daniel@0: class ResponseHeaderBag extends HeaderBag Daniel@0: { Daniel@0: const COOKIES_FLAT ='flat'; Daniel@0: const COOKIES_ARRAY ='array'; Daniel@0: const DISPOSITION_ATTACHMENT ='attachment'; Daniel@0: const DISPOSITION_INLINE ='inline'; Daniel@0: protected $computedCacheControl = array(); Daniel@0: protected $cookies = array(); Daniel@0: protected $headerNames = array(); Daniel@0: public function __construct(array $headers = array()) Daniel@0: { Daniel@0: parent::__construct($headers); Daniel@0: if (!isset($this->headers['cache-control'])) { Daniel@0: $this->set('Cache-Control',''); Daniel@0: } Daniel@0: } Daniel@0: public function __toString() Daniel@0: { Daniel@0: $cookies =''; Daniel@0: foreach ($this->getCookies() as $cookie) { Daniel@0: $cookies .='Set-Cookie: '.$cookie."\r\n"; Daniel@0: } Daniel@0: ksort($this->headerNames); Daniel@0: return parent::__toString().$cookies; Daniel@0: } Daniel@0: public function allPreserveCase() Daniel@0: { Daniel@0: return array_combine($this->headerNames, $this->headers); Daniel@0: } Daniel@0: public function replace(array $headers = array()) Daniel@0: { Daniel@0: $this->headerNames = array(); Daniel@0: parent::replace($headers); Daniel@0: if (!isset($this->headers['cache-control'])) { Daniel@0: $this->set('Cache-Control',''); Daniel@0: } Daniel@0: } Daniel@0: public function set($key, $values, $replace = true) Daniel@0: { Daniel@0: parent::set($key, $values, $replace); Daniel@0: $uniqueKey = strtr(strtolower($key),'_','-'); Daniel@0: $this->headerNames[$uniqueKey] = $key; Daniel@0: if (in_array($uniqueKey, array('cache-control','etag','last-modified','expires'))) { Daniel@0: $computed = $this->computeCacheControlValue(); Daniel@0: $this->headers['cache-control'] = array($computed); Daniel@0: $this->headerNames['cache-control'] ='Cache-Control'; Daniel@0: $this->computedCacheControl = $this->parseCacheControl($computed); Daniel@0: } Daniel@0: } Daniel@0: public function remove($key) Daniel@0: { Daniel@0: parent::remove($key); Daniel@0: $uniqueKey = strtr(strtolower($key),'_','-'); Daniel@0: unset($this->headerNames[$uniqueKey]); Daniel@0: if ('cache-control'=== $uniqueKey) { Daniel@0: $this->computedCacheControl = array(); Daniel@0: } Daniel@0: } Daniel@0: public function hasCacheControlDirective($key) Daniel@0: { Daniel@0: return array_key_exists($key, $this->computedCacheControl); Daniel@0: } Daniel@0: public function getCacheControlDirective($key) Daniel@0: { Daniel@0: return array_key_exists($key, $this->computedCacheControl) ? $this->computedCacheControl[$key] : null; Daniel@0: } Daniel@0: public function setCookie(Cookie $cookie) Daniel@0: { Daniel@0: $this->cookies[$cookie->getDomain()][$cookie->getPath()][$cookie->getName()] = $cookie; Daniel@0: } Daniel@0: public function removeCookie($name, $path ='/', $domain = null) Daniel@0: { Daniel@0: if (null === $path) { Daniel@0: $path ='/'; Daniel@0: } Daniel@0: unset($this->cookies[$domain][$path][$name]); Daniel@0: if (empty($this->cookies[$domain][$path])) { Daniel@0: unset($this->cookies[$domain][$path]); Daniel@0: if (empty($this->cookies[$domain])) { Daniel@0: unset($this->cookies[$domain]); Daniel@0: } Daniel@0: } Daniel@0: } Daniel@0: public function getCookies($format = self::COOKIES_FLAT) Daniel@0: { Daniel@0: if (!in_array($format, array(self::COOKIES_FLAT, self::COOKIES_ARRAY))) { Daniel@0: throw new \InvalidArgumentException(sprintf('Format "%s" invalid (%s).', $format, implode(', ', array(self::COOKIES_FLAT, self::COOKIES_ARRAY)))); Daniel@0: } Daniel@0: if (self::COOKIES_ARRAY === $format) { Daniel@0: return $this->cookies; Daniel@0: } Daniel@0: $flattenedCookies = array(); Daniel@0: foreach ($this->cookies as $path) { Daniel@0: foreach ($path as $cookies) { Daniel@0: foreach ($cookies as $cookie) { Daniel@0: $flattenedCookies[] = $cookie; Daniel@0: } Daniel@0: } Daniel@0: } Daniel@0: return $flattenedCookies; Daniel@0: } Daniel@0: public function clearCookie($name, $path ='/', $domain = null) Daniel@0: { Daniel@0: $this->setCookie(new Cookie($name, null, 1, $path, $domain)); Daniel@0: } Daniel@0: public function makeDisposition($disposition, $filename, $filenameFallback ='') Daniel@0: { Daniel@0: if (!in_array($disposition, array(self::DISPOSITION_ATTACHMENT, self::DISPOSITION_INLINE))) { Daniel@0: throw new \InvalidArgumentException(sprintf('The disposition must be either "%s" or "%s".', self::DISPOSITION_ATTACHMENT, self::DISPOSITION_INLINE)); Daniel@0: } Daniel@0: if (''== $filenameFallback) { Daniel@0: $filenameFallback = $filename; Daniel@0: } Daniel@0: if (!preg_match('/^[\x20-\x7e]*$/', $filenameFallback)) { Daniel@0: throw new \InvalidArgumentException('The filename fallback must only contain ASCII characters.'); Daniel@0: } Daniel@0: if (false !== strpos($filenameFallback,'%')) { Daniel@0: throw new \InvalidArgumentException('The filename fallback cannot contain the "%" character.'); Daniel@0: } Daniel@0: if (false !== strpos($filename,'/') || false !== strpos($filename,'\\') || false !== strpos($filenameFallback,'/') || false !== strpos($filenameFallback,'\\')) { Daniel@0: throw new \InvalidArgumentException('The filename and the fallback cannot contain the "/" and "\\" characters.'); Daniel@0: } Daniel@0: $output = sprintf('%s; filename="%s"', $disposition, str_replace('"','\\"', $filenameFallback)); Daniel@0: if ($filename !== $filenameFallback) { Daniel@0: $output .= sprintf("; filename*=utf-8''%s", rawurlencode($filename)); Daniel@0: } Daniel@0: return $output; Daniel@0: } Daniel@0: protected function computeCacheControlValue() Daniel@0: { Daniel@0: if (!$this->cacheControl && !$this->has('ETag') && !$this->has('Last-Modified') && !$this->has('Expires')) { Daniel@0: return'no-cache'; Daniel@0: } Daniel@0: if (!$this->cacheControl) { Daniel@0: return'private, must-revalidate'; Daniel@0: } Daniel@0: $header = $this->getCacheControlHeader(); Daniel@0: if (isset($this->cacheControl['public']) || isset($this->cacheControl['private'])) { Daniel@0: return $header; Daniel@0: } Daniel@0: if (!isset($this->cacheControl['s-maxage'])) { Daniel@0: return $header.', private'; Daniel@0: } Daniel@0: return $header; Daniel@0: } Daniel@0: } Daniel@0: } Daniel@0: namespace Symfony\Component\DependencyInjection Daniel@0: { Daniel@0: interface ContainerAwareInterface Daniel@0: { Daniel@0: public function setContainer(ContainerInterface $container = null); Daniel@0: } Daniel@0: } Daniel@0: namespace Symfony\Component\DependencyInjection Daniel@0: { Daniel@0: use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException; Daniel@0: use Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException; Daniel@0: use Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException; Daniel@0: interface ContainerInterface Daniel@0: { Daniel@0: const EXCEPTION_ON_INVALID_REFERENCE = 1; Daniel@0: const NULL_ON_INVALID_REFERENCE = 2; Daniel@0: const IGNORE_ON_INVALID_REFERENCE = 3; Daniel@0: const SCOPE_CONTAINER ='container'; Daniel@0: const SCOPE_PROTOTYPE ='prototype'; Daniel@0: public function set($id, $service, $scope = self::SCOPE_CONTAINER); Daniel@0: public function get($id, $invalidBehavior = self::EXCEPTION_ON_INVALID_REFERENCE); Daniel@0: public function has($id); Daniel@0: public function getParameter($name); Daniel@0: public function hasParameter($name); Daniel@0: public function setParameter($name, $value); Daniel@0: public function enterScope($name); Daniel@0: public function leaveScope($name); Daniel@0: public function addScope(ScopeInterface $scope); Daniel@0: public function hasScope($name); Daniel@0: public function isScopeActive($name); Daniel@0: } Daniel@0: } Daniel@0: namespace Symfony\Component\DependencyInjection Daniel@0: { Daniel@0: interface IntrospectableContainerInterface extends ContainerInterface Daniel@0: { Daniel@0: public function initialized($id); Daniel@0: } Daniel@0: } Daniel@0: namespace Symfony\Component\DependencyInjection Daniel@0: { Daniel@0: use Symfony\Component\DependencyInjection\Exception\InactiveScopeException; Daniel@0: use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException; Daniel@0: use Symfony\Component\DependencyInjection\Exception\RuntimeException; Daniel@0: use Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException; Daniel@0: use Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException; Daniel@0: use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface; Daniel@0: use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag; Daniel@0: use Symfony\Component\DependencyInjection\ParameterBag\FrozenParameterBag; Daniel@0: class Container implements IntrospectableContainerInterface Daniel@0: { Daniel@0: protected $parameterBag; Daniel@0: protected $services = array(); Daniel@0: protected $methodMap = array(); Daniel@0: protected $aliases = array(); Daniel@0: protected $scopes = array(); Daniel@0: protected $scopeChildren = array(); Daniel@0: protected $scopedServices = array(); Daniel@0: protected $scopeStacks = array(); Daniel@0: protected $loading = array(); Daniel@0: public function __construct(ParameterBagInterface $parameterBag = null) Daniel@0: { Daniel@0: $this->parameterBag = $parameterBag ?: new ParameterBag(); Daniel@0: $this->set('service_container', $this); Daniel@0: } Daniel@0: public function compile() Daniel@0: { Daniel@0: $this->parameterBag->resolve(); Daniel@0: $this->parameterBag = new FrozenParameterBag($this->parameterBag->all()); Daniel@0: } Daniel@0: public function isFrozen() Daniel@0: { Daniel@0: return $this->parameterBag instanceof FrozenParameterBag; Daniel@0: } Daniel@0: public function getParameterBag() Daniel@0: { Daniel@0: return $this->parameterBag; Daniel@0: } Daniel@0: public function getParameter($name) Daniel@0: { Daniel@0: return $this->parameterBag->get($name); Daniel@0: } Daniel@0: public function hasParameter($name) Daniel@0: { Daniel@0: return $this->parameterBag->has($name); Daniel@0: } Daniel@0: public function setParameter($name, $value) Daniel@0: { Daniel@0: $this->parameterBag->set($name, $value); Daniel@0: } Daniel@0: public function set($id, $service, $scope = self::SCOPE_CONTAINER) Daniel@0: { Daniel@0: if (self::SCOPE_PROTOTYPE === $scope) { Daniel@0: throw new InvalidArgumentException(sprintf('You cannot set service "%s" of scope "prototype".', $id)); Daniel@0: } Daniel@0: $id = strtolower($id); Daniel@0: if ('service_container'=== $id) { Daniel@0: return; Daniel@0: } Daniel@0: if (self::SCOPE_CONTAINER !== $scope) { Daniel@0: if (!isset($this->scopedServices[$scope])) { Daniel@0: throw new RuntimeException(sprintf('You cannot set service "%s" of inactive scope.', $id)); Daniel@0: } Daniel@0: $this->scopedServices[$scope][$id] = $service; Daniel@0: } Daniel@0: $this->services[$id] = $service; Daniel@0: if (method_exists($this, $method ='synchronize'.strtr($id, array('_'=>'','.'=>'_','\\'=>'_')).'Service')) { Daniel@0: $this->$method(); Daniel@0: } Daniel@0: if (self::SCOPE_CONTAINER !== $scope && null === $service) { Daniel@0: unset($this->scopedServices[$scope][$id]); Daniel@0: } Daniel@0: if (null === $service) { Daniel@0: unset($this->services[$id]); Daniel@0: } Daniel@0: } Daniel@0: public function has($id) Daniel@0: { Daniel@0: $id = strtolower($id); Daniel@0: if ('service_container'=== $id) { Daniel@0: return true; Daniel@0: } Daniel@0: return isset($this->services[$id]) Daniel@0: || array_key_exists($id, $this->services) Daniel@0: || isset($this->aliases[$id]) Daniel@0: || method_exists($this,'get'.strtr($id, array('_'=>'','.'=>'_','\\'=>'_')).'Service') Daniel@0: ; Daniel@0: } Daniel@0: public function get($id, $invalidBehavior = self::EXCEPTION_ON_INVALID_REFERENCE) Daniel@0: { Daniel@0: foreach (array(false, true) as $strtolower) { Daniel@0: if ($strtolower) { Daniel@0: $id = strtolower($id); Daniel@0: } Daniel@0: if ('service_container'=== $id) { Daniel@0: return $this; Daniel@0: } Daniel@0: if (isset($this->aliases[$id])) { Daniel@0: $id = $this->aliases[$id]; Daniel@0: } Daniel@0: if (isset($this->services[$id]) || array_key_exists($id, $this->services)) { Daniel@0: return $this->services[$id]; Daniel@0: } Daniel@0: } Daniel@0: if (isset($this->loading[$id])) { Daniel@0: throw new ServiceCircularReferenceException($id, array_keys($this->loading)); Daniel@0: } Daniel@0: if (isset($this->methodMap[$id])) { Daniel@0: $method = $this->methodMap[$id]; Daniel@0: } elseif (method_exists($this, $method ='get'.strtr($id, array('_'=>'','.'=>'_','\\'=>'_')).'Service')) { Daniel@0: } else { Daniel@0: if (self::EXCEPTION_ON_INVALID_REFERENCE === $invalidBehavior) { Daniel@0: if (!$id) { Daniel@0: throw new ServiceNotFoundException($id); Daniel@0: } Daniel@0: $alternatives = array(); Daniel@0: foreach (array_keys($this->services) as $key) { Daniel@0: $lev = levenshtein($id, $key); Daniel@0: if ($lev <= strlen($id) / 3 || false !== strpos($key, $id)) { Daniel@0: $alternatives[] = $key; Daniel@0: } Daniel@0: } Daniel@0: throw new ServiceNotFoundException($id, null, null, $alternatives); Daniel@0: } Daniel@0: return; Daniel@0: } Daniel@0: $this->loading[$id] = true; Daniel@0: try { Daniel@0: $service = $this->$method(); Daniel@0: } catch (\Exception $e) { Daniel@0: unset($this->loading[$id]); Daniel@0: if (array_key_exists($id, $this->services)) { Daniel@0: unset($this->services[$id]); Daniel@0: } Daniel@0: if ($e instanceof InactiveScopeException && self::EXCEPTION_ON_INVALID_REFERENCE !== $invalidBehavior) { Daniel@0: return; Daniel@0: } Daniel@0: throw $e; Daniel@0: } Daniel@0: unset($this->loading[$id]); Daniel@0: return $service; Daniel@0: } Daniel@0: public function initialized($id) Daniel@0: { Daniel@0: $id = strtolower($id); Daniel@0: if ('service_container'=== $id) { Daniel@0: return true; Daniel@0: } Daniel@0: if (isset($this->aliases[$id])) { Daniel@0: $id = $this->aliases[$id]; Daniel@0: } Daniel@0: return isset($this->services[$id]) || array_key_exists($id, $this->services); Daniel@0: } Daniel@0: public function getServiceIds() Daniel@0: { Daniel@0: $ids = array(); Daniel@0: $r = new \ReflectionClass($this); Daniel@0: foreach ($r->getMethods() as $method) { Daniel@0: if (preg_match('/^get(.+)Service$/', $method->name, $match)) { Daniel@0: $ids[] = self::underscore($match[1]); Daniel@0: } Daniel@0: } Daniel@0: $ids[] ='service_container'; Daniel@0: return array_unique(array_merge($ids, array_keys($this->services))); Daniel@0: } Daniel@0: public function enterScope($name) Daniel@0: { Daniel@0: if (!isset($this->scopes[$name])) { Daniel@0: throw new InvalidArgumentException(sprintf('The scope "%s" does not exist.', $name)); Daniel@0: } Daniel@0: if (self::SCOPE_CONTAINER !== $this->scopes[$name] && !isset($this->scopedServices[$this->scopes[$name]])) { Daniel@0: throw new RuntimeException(sprintf('The parent scope "%s" must be active when entering this scope.', $this->scopes[$name])); Daniel@0: } Daniel@0: if (isset($this->scopedServices[$name])) { Daniel@0: $services = array($this->services, $name => $this->scopedServices[$name]); Daniel@0: unset($this->scopedServices[$name]); Daniel@0: foreach ($this->scopeChildren[$name] as $child) { Daniel@0: if (isset($this->scopedServices[$child])) { Daniel@0: $services[$child] = $this->scopedServices[$child]; Daniel@0: unset($this->scopedServices[$child]); Daniel@0: } Daniel@0: } Daniel@0: $this->services = call_user_func_array('array_diff_key', $services); Daniel@0: array_shift($services); Daniel@0: if (!isset($this->scopeStacks[$name])) { Daniel@0: $this->scopeStacks[$name] = new \SplStack(); Daniel@0: } Daniel@0: $this->scopeStacks[$name]->push($services); Daniel@0: } Daniel@0: $this->scopedServices[$name] = array(); Daniel@0: } Daniel@0: public function leaveScope($name) Daniel@0: { Daniel@0: if (!isset($this->scopedServices[$name])) { Daniel@0: throw new InvalidArgumentException(sprintf('The scope "%s" is not active.', $name)); Daniel@0: } Daniel@0: $services = array($this->services, $this->scopedServices[$name]); Daniel@0: unset($this->scopedServices[$name]); Daniel@0: foreach ($this->scopeChildren[$name] as $child) { Daniel@0: if (!isset($this->scopedServices[$child])) { Daniel@0: continue; Daniel@0: } Daniel@0: $services[] = $this->scopedServices[$child]; Daniel@0: unset($this->scopedServices[$child]); Daniel@0: } Daniel@0: $this->services = call_user_func_array('array_diff_key', $services); Daniel@0: if (isset($this->scopeStacks[$name]) && count($this->scopeStacks[$name]) > 0) { Daniel@0: $services = $this->scopeStacks[$name]->pop(); Daniel@0: $this->scopedServices += $services; Daniel@0: foreach ($services as $array) { Daniel@0: foreach ($array as $id => $service) { Daniel@0: $this->set($id, $service, $name); Daniel@0: } Daniel@0: } Daniel@0: } Daniel@0: } Daniel@0: public function addScope(ScopeInterface $scope) Daniel@0: { Daniel@0: $name = $scope->getName(); Daniel@0: $parentScope = $scope->getParentName(); Daniel@0: if (self::SCOPE_CONTAINER === $name || self::SCOPE_PROTOTYPE === $name) { Daniel@0: throw new InvalidArgumentException(sprintf('The scope "%s" is reserved.', $name)); Daniel@0: } Daniel@0: if (isset($this->scopes[$name])) { Daniel@0: throw new InvalidArgumentException(sprintf('A scope with name "%s" already exists.', $name)); Daniel@0: } Daniel@0: if (self::SCOPE_CONTAINER !== $parentScope && !isset($this->scopes[$parentScope])) { Daniel@0: throw new InvalidArgumentException(sprintf('The parent scope "%s" does not exist, or is invalid.', $parentScope)); Daniel@0: } Daniel@0: $this->scopes[$name] = $parentScope; Daniel@0: $this->scopeChildren[$name] = array(); Daniel@0: while ($parentScope !== self::SCOPE_CONTAINER) { Daniel@0: $this->scopeChildren[$parentScope][] = $name; Daniel@0: $parentScope = $this->scopes[$parentScope]; Daniel@0: } Daniel@0: } Daniel@0: public function hasScope($name) Daniel@0: { Daniel@0: return isset($this->scopes[$name]); Daniel@0: } Daniel@0: public function isScopeActive($name) Daniel@0: { Daniel@0: return isset($this->scopedServices[$name]); Daniel@0: } Daniel@0: public static function camelize($id) Daniel@0: { Daniel@0: return strtr(ucwords(strtr($id, array('_'=>' ','.'=>'_ ','\\'=>'_ '))), array(' '=>'')); Daniel@0: } Daniel@0: public static function underscore($id) Daniel@0: { Daniel@0: return strtolower(preg_replace(array('/([A-Z]+)([A-Z][a-z])/','/([a-z\d])([A-Z])/'), array('\\1_\\2','\\1_\\2'), strtr($id,'_','.'))); Daniel@0: } Daniel@0: } Daniel@0: } Daniel@0: namespace Symfony\Component\HttpKernel Daniel@0: { Daniel@0: use Symfony\Component\HttpFoundation\Request; Daniel@0: use Symfony\Component\HttpFoundation\Response; Daniel@0: interface HttpKernelInterface Daniel@0: { Daniel@0: const MASTER_REQUEST = 1; Daniel@0: const SUB_REQUEST = 2; Daniel@0: public function handle(Request $request, $type = self::MASTER_REQUEST, $catch = true); Daniel@0: } Daniel@0: } Daniel@0: namespace Symfony\Component\HttpKernel Daniel@0: { Daniel@0: use Symfony\Component\DependencyInjection\ContainerInterface; Daniel@0: use Symfony\Component\HttpKernel\Bundle\BundleInterface; Daniel@0: use Symfony\Component\Config\Loader\LoaderInterface; Daniel@0: interface KernelInterface extends HttpKernelInterface, \Serializable Daniel@0: { Daniel@0: public function registerBundles(); Daniel@0: public function registerContainerConfiguration(LoaderInterface $loader); Daniel@0: public function boot(); Daniel@0: public function shutdown(); Daniel@0: public function getBundles(); Daniel@0: public function isClassInActiveBundle($class); Daniel@0: public function getBundle($name, $first = true); Daniel@0: public function locateResource($name, $dir = null, $first = true); Daniel@0: public function getName(); Daniel@0: public function getEnvironment(); Daniel@0: public function isDebug(); Daniel@0: public function getRootDir(); Daniel@0: public function getContainer(); Daniel@0: public function getStartTime(); Daniel@0: public function getCacheDir(); Daniel@0: public function getLogDir(); Daniel@0: public function getCharset(); Daniel@0: } Daniel@0: } Daniel@0: namespace Symfony\Component\HttpKernel Daniel@0: { Daniel@0: use Symfony\Component\HttpFoundation\Request; Daniel@0: use Symfony\Component\HttpFoundation\Response; Daniel@0: interface TerminableInterface Daniel@0: { Daniel@0: public function terminate(Request $request, Response $response); Daniel@0: } Daniel@0: } Daniel@0: namespace Symfony\Component\HttpKernel Daniel@0: { Daniel@0: use Symfony\Bridge\ProxyManager\LazyProxy\Instantiator\RuntimeInstantiator; Daniel@0: use Symfony\Bridge\ProxyManager\LazyProxy\PhpDumper\ProxyDumper; Daniel@0: use Symfony\Component\DependencyInjection\ContainerInterface; Daniel@0: use Symfony\Component\DependencyInjection\ContainerBuilder; Daniel@0: use Symfony\Component\DependencyInjection\Dumper\PhpDumper; Daniel@0: use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag; Daniel@0: use Symfony\Component\DependencyInjection\Loader\XmlFileLoader; Daniel@0: use Symfony\Component\DependencyInjection\Loader\YamlFileLoader; Daniel@0: use Symfony\Component\DependencyInjection\Loader\IniFileLoader; Daniel@0: use Symfony\Component\DependencyInjection\Loader\PhpFileLoader; Daniel@0: use Symfony\Component\DependencyInjection\Loader\ClosureLoader; Daniel@0: use Symfony\Component\HttpFoundation\Request; Daniel@0: use Symfony\Component\HttpFoundation\Response; Daniel@0: use Symfony\Component\HttpKernel\Bundle\BundleInterface; Daniel@0: use Symfony\Component\HttpKernel\Config\EnvParametersResource; Daniel@0: use Symfony\Component\HttpKernel\Config\FileLocator; Daniel@0: use Symfony\Component\HttpKernel\DependencyInjection\MergeExtensionConfigurationPass; Daniel@0: use Symfony\Component\HttpKernel\DependencyInjection\AddClassesToCachePass; Daniel@0: use Symfony\Component\Config\Loader\LoaderResolver; Daniel@0: use Symfony\Component\Config\Loader\DelegatingLoader; Daniel@0: use Symfony\Component\Config\ConfigCache; Daniel@0: use Symfony\Component\ClassLoader\ClassCollectionLoader; Daniel@0: abstract class Kernel implements KernelInterface, TerminableInterface Daniel@0: { Daniel@0: protected $bundles = array(); Daniel@0: protected $bundleMap; Daniel@0: protected $container; Daniel@0: protected $rootDir; Daniel@0: protected $environment; Daniel@0: protected $debug; Daniel@0: protected $booted = false; Daniel@0: protected $name; Daniel@0: protected $startTime; Daniel@0: protected $loadClassCache; Daniel@0: const VERSION ='2.5.10'; Daniel@0: const VERSION_ID ='20510'; Daniel@0: const MAJOR_VERSION ='2'; Daniel@0: const MINOR_VERSION ='5'; Daniel@0: const RELEASE_VERSION ='10'; Daniel@0: const EXTRA_VERSION =''; Daniel@0: public function __construct($environment, $debug) Daniel@0: { Daniel@0: $this->environment = $environment; Daniel@0: $this->debug = (bool) $debug; Daniel@0: $this->rootDir = $this->getRootDir(); Daniel@0: $this->name = $this->getName(); Daniel@0: if ($this->debug) { Daniel@0: $this->startTime = microtime(true); Daniel@0: } Daniel@0: $this->init(); Daniel@0: } Daniel@0: public function init() Daniel@0: { Daniel@0: } Daniel@0: public function __clone() Daniel@0: { Daniel@0: if ($this->debug) { Daniel@0: $this->startTime = microtime(true); Daniel@0: } Daniel@0: $this->booted = false; Daniel@0: $this->container = null; Daniel@0: } Daniel@0: public function boot() Daniel@0: { Daniel@0: if (true === $this->booted) { Daniel@0: return; Daniel@0: } Daniel@0: if ($this->loadClassCache) { Daniel@0: $this->doLoadClassCache($this->loadClassCache[0], $this->loadClassCache[1]); Daniel@0: } Daniel@0: $this->initializeBundles(); Daniel@0: $this->initializeContainer(); Daniel@0: foreach ($this->getBundles() as $bundle) { Daniel@0: $bundle->setContainer($this->container); Daniel@0: $bundle->boot(); Daniel@0: } Daniel@0: $this->booted = true; Daniel@0: } Daniel@0: public function terminate(Request $request, Response $response) Daniel@0: { Daniel@0: if (false === $this->booted) { Daniel@0: return; Daniel@0: } Daniel@0: if ($this->getHttpKernel() instanceof TerminableInterface) { Daniel@0: $this->getHttpKernel()->terminate($request, $response); Daniel@0: } Daniel@0: } Daniel@0: public function shutdown() Daniel@0: { Daniel@0: if (false === $this->booted) { Daniel@0: return; Daniel@0: } Daniel@0: $this->booted = false; Daniel@0: foreach ($this->getBundles() as $bundle) { Daniel@0: $bundle->shutdown(); Daniel@0: $bundle->setContainer(null); Daniel@0: } Daniel@0: $this->container = null; Daniel@0: } Daniel@0: public function handle(Request $request, $type = HttpKernelInterface::MASTER_REQUEST, $catch = true) Daniel@0: { Daniel@0: if (false === $this->booted) { Daniel@0: $this->boot(); Daniel@0: } Daniel@0: return $this->getHttpKernel()->handle($request, $type, $catch); Daniel@0: } Daniel@0: protected function getHttpKernel() Daniel@0: { Daniel@0: return $this->container->get('http_kernel'); Daniel@0: } Daniel@0: public function getBundles() Daniel@0: { Daniel@0: return $this->bundles; Daniel@0: } Daniel@0: public function isClassInActiveBundle($class) Daniel@0: { Daniel@0: foreach ($this->getBundles() as $bundle) { Daniel@0: if (0 === strpos($class, $bundle->getNamespace())) { Daniel@0: return true; Daniel@0: } Daniel@0: } Daniel@0: return false; Daniel@0: } Daniel@0: public function getBundle($name, $first = true) Daniel@0: { Daniel@0: if (!isset($this->bundleMap[$name])) { Daniel@0: throw new \InvalidArgumentException(sprintf('Bundle "%s" does not exist or it is not enabled. Maybe you forgot to add it in the registerBundles() method of your %s.php file?', $name, get_class($this))); Daniel@0: } Daniel@0: if (true === $first) { Daniel@0: return $this->bundleMap[$name][0]; Daniel@0: } Daniel@0: return $this->bundleMap[$name]; Daniel@0: } Daniel@0: public function locateResource($name, $dir = null, $first = true) Daniel@0: { Daniel@0: if ('@'!== $name[0]) { Daniel@0: throw new \InvalidArgumentException(sprintf('A resource name must start with @ ("%s" given).', $name)); Daniel@0: } Daniel@0: if (false !== strpos($name,'..')) { Daniel@0: throw new \RuntimeException(sprintf('File name "%s" contains invalid characters (..).', $name)); Daniel@0: } Daniel@0: $bundleName = substr($name, 1); Daniel@0: $path =''; Daniel@0: if (false !== strpos($bundleName,'/')) { Daniel@0: list($bundleName, $path) = explode('/', $bundleName, 2); Daniel@0: } Daniel@0: $isResource = 0 === strpos($path,'Resources') && null !== $dir; Daniel@0: $overridePath = substr($path, 9); Daniel@0: $resourceBundle = null; Daniel@0: $bundles = $this->getBundle($bundleName, false); Daniel@0: $files = array(); Daniel@0: foreach ($bundles as $bundle) { Daniel@0: if ($isResource && file_exists($file = $dir.'/'.$bundle->getName().$overridePath)) { Daniel@0: if (null !== $resourceBundle) { Daniel@0: throw new \RuntimeException(sprintf('"%s" resource is hidden by a resource from the "%s" derived bundle. Create a "%s" file to override the bundle resource.', Daniel@0: $file, Daniel@0: $resourceBundle, Daniel@0: $dir.'/'.$bundles[0]->getName().$overridePath Daniel@0: )); Daniel@0: } Daniel@0: if ($first) { Daniel@0: return $file; Daniel@0: } Daniel@0: $files[] = $file; Daniel@0: } Daniel@0: if (file_exists($file = $bundle->getPath().'/'.$path)) { Daniel@0: if ($first && !$isResource) { Daniel@0: return $file; Daniel@0: } Daniel@0: $files[] = $file; Daniel@0: $resourceBundle = $bundle->getName(); Daniel@0: } Daniel@0: } Daniel@0: if (count($files) > 0) { Daniel@0: return $first && $isResource ? $files[0] : $files; Daniel@0: } Daniel@0: throw new \InvalidArgumentException(sprintf('Unable to find file "%s".', $name)); Daniel@0: } Daniel@0: public function getName() Daniel@0: { Daniel@0: if (null === $this->name) { Daniel@0: $this->name = preg_replace('/[^a-zA-Z0-9_]+/','', basename($this->rootDir)); Daniel@0: } Daniel@0: return $this->name; Daniel@0: } Daniel@0: public function getEnvironment() Daniel@0: { Daniel@0: return $this->environment; Daniel@0: } Daniel@0: public function isDebug() Daniel@0: { Daniel@0: return $this->debug; Daniel@0: } Daniel@0: public function getRootDir() Daniel@0: { Daniel@0: if (null === $this->rootDir) { Daniel@0: $r = new \ReflectionObject($this); Daniel@0: $this->rootDir = str_replace('\\','/', dirname($r->getFileName())); Daniel@0: } Daniel@0: return $this->rootDir; Daniel@0: } Daniel@0: public function getContainer() Daniel@0: { Daniel@0: return $this->container; Daniel@0: } Daniel@0: public function loadClassCache($name ='classes', $extension ='.php') Daniel@0: { Daniel@0: $this->loadClassCache = array($name, $extension); Daniel@0: } Daniel@0: public function setClassCache(array $classes) Daniel@0: { Daniel@0: file_put_contents($this->getCacheDir().'/classes.map', sprintf('debug ? $this->startTime : -INF; Daniel@0: } Daniel@0: public function getCacheDir() Daniel@0: { Daniel@0: return $this->rootDir.'/cache/'.$this->environment; Daniel@0: } Daniel@0: public function getLogDir() Daniel@0: { Daniel@0: return $this->rootDir.'/logs'; Daniel@0: } Daniel@0: public function getCharset() Daniel@0: { Daniel@0: return'UTF-8'; Daniel@0: } Daniel@0: protected function doLoadClassCache($name, $extension) Daniel@0: { Daniel@0: if (!$this->booted && is_file($this->getCacheDir().'/classes.map')) { Daniel@0: ClassCollectionLoader::load(include($this->getCacheDir().'/classes.map'), $this->getCacheDir(), $name, $this->debug, false, $extension); Daniel@0: } Daniel@0: } Daniel@0: protected function initializeBundles() Daniel@0: { Daniel@0: $this->bundles = array(); Daniel@0: $topMostBundles = array(); Daniel@0: $directChildren = array(); Daniel@0: foreach ($this->registerBundles() as $bundle) { Daniel@0: $name = $bundle->getName(); Daniel@0: if (isset($this->bundles[$name])) { Daniel@0: throw new \LogicException(sprintf('Trying to register two bundles with the same name "%s"', $name)); Daniel@0: } Daniel@0: $this->bundles[$name] = $bundle; Daniel@0: if ($parentName = $bundle->getParent()) { Daniel@0: if (isset($directChildren[$parentName])) { Daniel@0: throw new \LogicException(sprintf('Bundle "%s" is directly extended by two bundles "%s" and "%s".', $parentName, $name, $directChildren[$parentName])); Daniel@0: } Daniel@0: if ($parentName == $name) { Daniel@0: throw new \LogicException(sprintf('Bundle "%s" can not extend itself.', $name)); Daniel@0: } Daniel@0: $directChildren[$parentName] = $name; Daniel@0: } else { Daniel@0: $topMostBundles[$name] = $bundle; Daniel@0: } Daniel@0: } Daniel@0: if (!empty($directChildren) && count($diff = array_diff_key($directChildren, $this->bundles))) { Daniel@0: $diff = array_keys($diff); Daniel@0: throw new \LogicException(sprintf('Bundle "%s" extends bundle "%s", which is not registered.', $directChildren[$diff[0]], $diff[0])); Daniel@0: } Daniel@0: $this->bundleMap = array(); Daniel@0: foreach ($topMostBundles as $name => $bundle) { Daniel@0: $bundleMap = array($bundle); Daniel@0: $hierarchy = array($name); Daniel@0: while (isset($directChildren[$name])) { Daniel@0: $name = $directChildren[$name]; Daniel@0: array_unshift($bundleMap, $this->bundles[$name]); Daniel@0: $hierarchy[] = $name; Daniel@0: } Daniel@0: foreach ($hierarchy as $bundle) { Daniel@0: $this->bundleMap[$bundle] = $bundleMap; Daniel@0: array_pop($bundleMap); Daniel@0: } Daniel@0: } Daniel@0: } Daniel@0: protected function getContainerClass() Daniel@0: { Daniel@0: return $this->name.ucfirst($this->environment).($this->debug ?'Debug':'').'ProjectContainer'; Daniel@0: } Daniel@0: protected function getContainerBaseClass() Daniel@0: { Daniel@0: return'Container'; Daniel@0: } Daniel@0: protected function initializeContainer() Daniel@0: { Daniel@0: $class = $this->getContainerClass(); Daniel@0: $cache = new ConfigCache($this->getCacheDir().'/'.$class.'.php', $this->debug); Daniel@0: $fresh = true; Daniel@0: if (!$cache->isFresh()) { Daniel@0: $container = $this->buildContainer(); Daniel@0: $container->compile(); Daniel@0: $this->dumpContainer($cache, $container, $class, $this->getContainerBaseClass()); Daniel@0: $fresh = false; Daniel@0: } Daniel@0: require_once $cache; Daniel@0: $this->container = new $class(); Daniel@0: $this->container->set('kernel', $this); Daniel@0: if (!$fresh && $this->container->has('cache_warmer')) { Daniel@0: $this->container->get('cache_warmer')->warmUp($this->container->getParameter('kernel.cache_dir')); Daniel@0: } Daniel@0: } Daniel@0: protected function getKernelParameters() Daniel@0: { Daniel@0: $bundles = array(); Daniel@0: foreach ($this->bundles as $name => $bundle) { Daniel@0: $bundles[$name] = get_class($bundle); Daniel@0: } Daniel@0: return array_merge( Daniel@0: array('kernel.root_dir'=> realpath($this->rootDir) ?: $this->rootDir,'kernel.environment'=> $this->environment,'kernel.debug'=> $this->debug,'kernel.name'=> $this->name,'kernel.cache_dir'=> realpath($this->getCacheDir()) ?: $this->getCacheDir(),'kernel.logs_dir'=> realpath($this->getLogDir()) ?: $this->getLogDir(),'kernel.bundles'=> $bundles,'kernel.charset'=> $this->getCharset(),'kernel.container_class'=> $this->getContainerClass(), Daniel@0: ), Daniel@0: $this->getEnvParameters() Daniel@0: ); Daniel@0: } Daniel@0: protected function getEnvParameters() Daniel@0: { Daniel@0: $parameters = array(); Daniel@0: foreach ($_SERVER as $key => $value) { Daniel@0: if (0 === strpos($key,'SYMFONY__')) { Daniel@0: $parameters[strtolower(str_replace('__','.', substr($key, 9)))] = $value; Daniel@0: } Daniel@0: } Daniel@0: return $parameters; Daniel@0: } Daniel@0: protected function buildContainer() Daniel@0: { Daniel@0: foreach (array('cache'=> $this->getCacheDir(),'logs'=> $this->getLogDir()) as $name => $dir) { Daniel@0: if (!is_dir($dir)) { Daniel@0: if (false === @mkdir($dir, 0777, true)) { Daniel@0: throw new \RuntimeException(sprintf("Unable to create the %s directory (%s)\n", $name, $dir)); Daniel@0: } Daniel@0: } elseif (!is_writable($dir)) { Daniel@0: throw new \RuntimeException(sprintf("Unable to write in the %s directory (%s)\n", $name, $dir)); Daniel@0: } Daniel@0: } Daniel@0: $container = $this->getContainerBuilder(); Daniel@0: $container->addObjectResource($this); Daniel@0: $this->prepareContainer($container); Daniel@0: if (null !== $cont = $this->registerContainerConfiguration($this->getContainerLoader($container))) { Daniel@0: $container->merge($cont); Daniel@0: } Daniel@0: $container->addCompilerPass(new AddClassesToCachePass($this)); Daniel@0: $container->addResource(new EnvParametersResource('SYMFONY__')); Daniel@0: return $container; Daniel@0: } Daniel@0: protected function prepareContainer(ContainerBuilder $container) Daniel@0: { Daniel@0: $extensions = array(); Daniel@0: foreach ($this->bundles as $bundle) { Daniel@0: if ($extension = $bundle->getContainerExtension()) { Daniel@0: $container->registerExtension($extension); Daniel@0: $extensions[] = $extension->getAlias(); Daniel@0: } Daniel@0: if ($this->debug) { Daniel@0: $container->addObjectResource($bundle); Daniel@0: } Daniel@0: } Daniel@0: foreach ($this->bundles as $bundle) { Daniel@0: $bundle->build($container); Daniel@0: } Daniel@0: $container->getCompilerPassConfig()->setMergePass(new MergeExtensionConfigurationPass($extensions)); Daniel@0: } Daniel@0: protected function getContainerBuilder() Daniel@0: { Daniel@0: $container = new ContainerBuilder(new ParameterBag($this->getKernelParameters())); Daniel@0: if (class_exists('ProxyManager\Configuration')) { Daniel@0: $container->setProxyInstantiator(new RuntimeInstantiator()); Daniel@0: } Daniel@0: return $container; Daniel@0: } Daniel@0: protected function dumpContainer(ConfigCache $cache, ContainerBuilder $container, $class, $baseClass) Daniel@0: { Daniel@0: $dumper = new PhpDumper($container); Daniel@0: if (class_exists('ProxyManager\Configuration')) { Daniel@0: $dumper->setProxyDumper(new ProxyDumper()); Daniel@0: } Daniel@0: $content = $dumper->dump(array('class'=> $class,'base_class'=> $baseClass,'file'=> (string) $cache)); Daniel@0: if (!$this->debug) { Daniel@0: $content = static::stripComments($content); Daniel@0: } Daniel@0: $cache->write($content, $container->getResources()); Daniel@0: } Daniel@0: protected function getContainerLoader(ContainerInterface $container) Daniel@0: { Daniel@0: $locator = new FileLocator($this); Daniel@0: $resolver = new LoaderResolver(array( Daniel@0: new XmlFileLoader($container, $locator), Daniel@0: new YamlFileLoader($container, $locator), Daniel@0: new IniFileLoader($container, $locator), Daniel@0: new PhpFileLoader($container, $locator), Daniel@0: new ClosureLoader($container), Daniel@0: )); Daniel@0: return new DelegatingLoader($resolver); Daniel@0: } Daniel@0: public static function stripComments($source) Daniel@0: { Daniel@0: if (!function_exists('token_get_all')) { Daniel@0: return $source; Daniel@0: } Daniel@0: $rawChunk =''; Daniel@0: $output =''; Daniel@0: $tokens = token_get_all($source); Daniel@0: $ignoreSpace = false; Daniel@0: for (reset($tokens); false !== $token = current($tokens); next($tokens)) { Daniel@0: if (is_string($token)) { Daniel@0: $rawChunk .= $token; Daniel@0: } elseif (T_START_HEREDOC === $token[0]) { Daniel@0: $output .= $rawChunk.$token[1]; Daniel@0: do { Daniel@0: $token = next($tokens); Daniel@0: $output .= $token[1]; Daniel@0: } while ($token[0] !== T_END_HEREDOC); Daniel@0: $rawChunk =''; Daniel@0: } elseif (T_WHITESPACE === $token[0]) { Daniel@0: if ($ignoreSpace) { Daniel@0: $ignoreSpace = false; Daniel@0: continue; Daniel@0: } Daniel@0: $rawChunk .= preg_replace(array('/\n{2,}/S'),"\n", $token[1]); Daniel@0: } elseif (in_array($token[0], array(T_COMMENT, T_DOC_COMMENT))) { Daniel@0: $ignoreSpace = true; Daniel@0: } else { Daniel@0: $rawChunk .= $token[1]; Daniel@0: if (T_OPEN_TAG === $token[0]) { Daniel@0: $ignoreSpace = true; Daniel@0: } Daniel@0: } Daniel@0: } Daniel@0: $output .= $rawChunk; Daniel@0: return $output; Daniel@0: } Daniel@0: public function serialize() Daniel@0: { Daniel@0: return serialize(array($this->environment, $this->debug)); Daniel@0: } Daniel@0: public function unserialize($data) Daniel@0: { Daniel@0: list($environment, $debug) = unserialize($data); Daniel@0: $this->__construct($environment, $debug); Daniel@0: } Daniel@0: } Daniel@0: } Daniel@0: namespace Symfony\Component\ClassLoader Daniel@0: { Daniel@0: class ApcClassLoader Daniel@0: { Daniel@0: private $prefix; Daniel@0: protected $decorated; Daniel@0: public function __construct($prefix, $decorated) Daniel@0: { Daniel@0: if (!extension_loaded('apc')) { Daniel@0: throw new \RuntimeException('Unable to use ApcClassLoader as APC is not enabled.'); Daniel@0: } Daniel@0: if (!method_exists($decorated,'findFile')) { Daniel@0: throw new \InvalidArgumentException('The class finder must implement a "findFile" method.'); Daniel@0: } Daniel@0: $this->prefix = $prefix; Daniel@0: $this->decorated = $decorated; Daniel@0: } Daniel@0: public function register($prepend = false) Daniel@0: { Daniel@0: spl_autoload_register(array($this,'loadClass'), true, $prepend); Daniel@0: } Daniel@0: public function unregister() Daniel@0: { Daniel@0: spl_autoload_unregister(array($this,'loadClass')); Daniel@0: } Daniel@0: public function loadClass($class) Daniel@0: { Daniel@0: if ($file = $this->findFile($class)) { Daniel@0: require $file; Daniel@0: return true; Daniel@0: } Daniel@0: } Daniel@0: public function findFile($class) Daniel@0: { Daniel@0: if (false === $file = apc_fetch($this->prefix.$class)) { Daniel@0: apc_store($this->prefix.$class, $file = $this->decorated->findFile($class)); Daniel@0: } Daniel@0: return $file; Daniel@0: } Daniel@0: public function __call($method, $args) Daniel@0: { Daniel@0: return call_user_func_array(array($this->decorated, $method), $args); Daniel@0: } Daniel@0: } Daniel@0: } Daniel@0: namespace Symfony\Component\HttpKernel\Bundle Daniel@0: { Daniel@0: use Symfony\Component\DependencyInjection\ContainerAwareInterface; Daniel@0: use Symfony\Component\DependencyInjection\ContainerBuilder; Daniel@0: use Symfony\Component\DependencyInjection\Extension\ExtensionInterface; Daniel@0: interface BundleInterface extends ContainerAwareInterface Daniel@0: { Daniel@0: public function boot(); Daniel@0: public function shutdown(); Daniel@0: public function build(ContainerBuilder $container); Daniel@0: public function getContainerExtension(); Daniel@0: public function getParent(); Daniel@0: public function getName(); Daniel@0: public function getNamespace(); Daniel@0: public function getPath(); Daniel@0: } Daniel@0: } Daniel@0: namespace Symfony\Component\DependencyInjection Daniel@0: { Daniel@0: abstract class ContainerAware implements ContainerAwareInterface Daniel@0: { Daniel@0: protected $container; Daniel@0: public function setContainer(ContainerInterface $container = null) Daniel@0: { Daniel@0: $this->container = $container; Daniel@0: } Daniel@0: } Daniel@0: } Daniel@0: namespace Symfony\Component\HttpKernel\Bundle Daniel@0: { Daniel@0: use Symfony\Component\DependencyInjection\ContainerAware; Daniel@0: use Symfony\Component\DependencyInjection\ContainerBuilder; Daniel@0: use Symfony\Component\DependencyInjection\Container; Daniel@0: use Symfony\Component\Console\Application; Daniel@0: use Symfony\Component\Finder\Finder; Daniel@0: use Symfony\Component\DependencyInjection\Extension\ExtensionInterface; Daniel@0: abstract class Bundle extends ContainerAware implements BundleInterface Daniel@0: { Daniel@0: protected $name; Daniel@0: protected $extension; Daniel@0: protected $path; Daniel@0: public function boot() Daniel@0: { Daniel@0: } Daniel@0: public function shutdown() Daniel@0: { Daniel@0: } Daniel@0: public function build(ContainerBuilder $container) Daniel@0: { Daniel@0: } Daniel@0: public function getContainerExtension() Daniel@0: { Daniel@0: if (null === $this->extension) { Daniel@0: $basename = preg_replace('/Bundle$/','', $this->getName()); Daniel@0: $class = $this->getNamespace().'\\DependencyInjection\\'.$basename.'Extension'; Daniel@0: if (class_exists($class)) { Daniel@0: $extension = new $class(); Daniel@0: $expectedAlias = Container::underscore($basename); Daniel@0: if ($expectedAlias != $extension->getAlias()) { Daniel@0: throw new \LogicException(sprintf('The extension alias for the default extension of a '.'bundle must be the underscored version of the '.'bundle name ("%s" instead of "%s")', Daniel@0: $expectedAlias, $extension->getAlias() Daniel@0: )); Daniel@0: } Daniel@0: $this->extension = $extension; Daniel@0: } else { Daniel@0: $this->extension = false; Daniel@0: } Daniel@0: } Daniel@0: if ($this->extension) { Daniel@0: return $this->extension; Daniel@0: } Daniel@0: } Daniel@0: public function getNamespace() Daniel@0: { Daniel@0: $class = get_class($this); Daniel@0: return substr($class, 0, strrpos($class,'\\')); Daniel@0: } Daniel@0: public function getPath() Daniel@0: { Daniel@0: if (null === $this->path) { Daniel@0: $reflected = new \ReflectionObject($this); Daniel@0: $this->path = dirname($reflected->getFileName()); Daniel@0: } Daniel@0: return $this->path; Daniel@0: } Daniel@0: public function getParent() Daniel@0: { Daniel@0: } Daniel@0: final public function getName() Daniel@0: { Daniel@0: if (null !== $this->name) { Daniel@0: return $this->name; Daniel@0: } Daniel@0: $name = get_class($this); Daniel@0: $pos = strrpos($name,'\\'); Daniel@0: return $this->name = false === $pos ? $name : substr($name, $pos + 1); Daniel@0: } Daniel@0: public function registerCommands(Application $application) Daniel@0: { Daniel@0: if (!is_dir($dir = $this->getPath().'/Command')) { Daniel@0: return; Daniel@0: } Daniel@0: $finder = new Finder(); Daniel@0: $finder->files()->name('*Command.php')->in($dir); Daniel@0: $prefix = $this->getNamespace().'\\Command'; Daniel@0: foreach ($finder as $file) { Daniel@0: $ns = $prefix; Daniel@0: if ($relativePath = $file->getRelativePath()) { Daniel@0: $ns .='\\'.strtr($relativePath,'/','\\'); Daniel@0: } Daniel@0: $class = $ns.'\\'.$file->getBasename('.php'); Daniel@0: if ($this->container) { Daniel@0: $alias ='console.command.'.strtolower(str_replace('\\','_', $class)); Daniel@0: if ($this->container->has($alias)) { Daniel@0: continue; Daniel@0: } Daniel@0: } Daniel@0: $r = new \ReflectionClass($class); Daniel@0: if ($r->isSubclassOf('Symfony\\Component\\Console\\Command\\Command') && !$r->isAbstract() && !$r->getConstructor()->getNumberOfRequiredParameters()) { Daniel@0: $application->add($r->newInstance()); Daniel@0: } Daniel@0: } Daniel@0: } Daniel@0: } Daniel@0: } Daniel@0: namespace Symfony\Component\Config Daniel@0: { Daniel@0: use Symfony\Component\Config\Resource\ResourceInterface; Daniel@0: use Symfony\Component\Filesystem\Exception\IOException; Daniel@0: use Symfony\Component\Filesystem\Filesystem; Daniel@0: class ConfigCache Daniel@0: { Daniel@0: private $debug; Daniel@0: private $file; Daniel@0: public function __construct($file, $debug) Daniel@0: { Daniel@0: $this->file = $file; Daniel@0: $this->debug = (bool) $debug; Daniel@0: } Daniel@0: public function __toString() Daniel@0: { Daniel@0: return $this->file; Daniel@0: } Daniel@0: public function isFresh() Daniel@0: { Daniel@0: if (!is_file($this->file)) { Daniel@0: return false; Daniel@0: } Daniel@0: if (!$this->debug) { Daniel@0: return true; Daniel@0: } Daniel@0: $metadata = $this->getMetaFile(); Daniel@0: if (!is_file($metadata)) { Daniel@0: return false; Daniel@0: } Daniel@0: $time = filemtime($this->file); Daniel@0: $meta = unserialize(file_get_contents($metadata)); Daniel@0: foreach ($meta as $resource) { Daniel@0: if (!$resource->isFresh($time)) { Daniel@0: return false; Daniel@0: } Daniel@0: } Daniel@0: return true; Daniel@0: } Daniel@0: public function write($content, array $metadata = null) Daniel@0: { Daniel@0: $mode = 0666; Daniel@0: $umask = umask(); Daniel@0: $filesystem = new Filesystem(); Daniel@0: $filesystem->dumpFile($this->file, $content, null); Daniel@0: try { Daniel@0: $filesystem->chmod($this->file, $mode, $umask); Daniel@0: } catch (IOException $e) { Daniel@0: } Daniel@0: if (null !== $metadata && true === $this->debug) { Daniel@0: $filesystem->dumpFile($this->getMetaFile(), serialize($metadata), null); Daniel@0: try { Daniel@0: $filesystem->chmod($this->getMetaFile(), $mode, $umask); Daniel@0: } catch (IOException $e) { Daniel@0: } Daniel@0: } Daniel@0: } Daniel@0: private function getMetaFile() Daniel@0: { Daniel@0: return $this->file.'.meta'; Daniel@0: } Daniel@0: } Daniel@0: } Daniel@0: namespace Symfony\Component\HttpKernel Daniel@0: { Daniel@0: use Symfony\Component\HttpKernel\Controller\ControllerResolverInterface; Daniel@0: use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; Daniel@0: use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface; Daniel@0: use Symfony\Component\HttpKernel\Event\FilterControllerEvent; Daniel@0: use Symfony\Component\HttpKernel\Event\FilterResponseEvent; Daniel@0: use Symfony\Component\HttpKernel\Event\FinishRequestEvent; Daniel@0: use Symfony\Component\HttpKernel\Event\GetResponseEvent; Daniel@0: use Symfony\Component\HttpKernel\Event\GetResponseForControllerResultEvent; Daniel@0: use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent; Daniel@0: use Symfony\Component\HttpKernel\Event\PostResponseEvent; Daniel@0: use Symfony\Component\HttpFoundation\Request; Daniel@0: use Symfony\Component\HttpFoundation\RequestStack; Daniel@0: use Symfony\Component\HttpFoundation\Response; Daniel@0: use Symfony\Component\EventDispatcher\EventDispatcherInterface; Daniel@0: class HttpKernel implements HttpKernelInterface, TerminableInterface Daniel@0: { Daniel@0: protected $dispatcher; Daniel@0: protected $resolver; Daniel@0: protected $requestStack; Daniel@0: public function __construct(EventDispatcherInterface $dispatcher, ControllerResolverInterface $resolver, RequestStack $requestStack = null) Daniel@0: { Daniel@0: $this->dispatcher = $dispatcher; Daniel@0: $this->resolver = $resolver; Daniel@0: $this->requestStack = $requestStack ?: new RequestStack(); Daniel@0: } Daniel@0: public function handle(Request $request, $type = HttpKernelInterface::MASTER_REQUEST, $catch = true) Daniel@0: { Daniel@0: try { Daniel@0: return $this->handleRaw($request, $type); Daniel@0: } catch (\Exception $e) { Daniel@0: if (false === $catch) { Daniel@0: $this->finishRequest($request, $type); Daniel@0: throw $e; Daniel@0: } Daniel@0: return $this->handleException($e, $request, $type); Daniel@0: } Daniel@0: } Daniel@0: public function terminate(Request $request, Response $response) Daniel@0: { Daniel@0: $this->dispatcher->dispatch(KernelEvents::TERMINATE, new PostResponseEvent($this, $request, $response)); Daniel@0: } Daniel@0: public function terminateWithException(\Exception $exception) Daniel@0: { Daniel@0: if (!$request = $this->requestStack->getMasterRequest()) { Daniel@0: throw new \LogicException('Request stack is empty', 0, $exception); Daniel@0: } Daniel@0: $response = $this->handleException($exception, $request, self::MASTER_REQUEST); Daniel@0: $response->sendHeaders(); Daniel@0: $response->sendContent(); Daniel@0: $this->terminate($request, $response); Daniel@0: } Daniel@0: private function handleRaw(Request $request, $type = self::MASTER_REQUEST) Daniel@0: { Daniel@0: $this->requestStack->push($request); Daniel@0: $event = new GetResponseEvent($this, $request, $type); Daniel@0: $this->dispatcher->dispatch(KernelEvents::REQUEST, $event); Daniel@0: if ($event->hasResponse()) { Daniel@0: return $this->filterResponse($event->getResponse(), $request, $type); Daniel@0: } Daniel@0: if (false === $controller = $this->resolver->getController($request)) { Daniel@0: throw new NotFoundHttpException(sprintf('Unable to find the controller for path "%s". Maybe you forgot to add the matching route in your routing configuration?', $request->getPathInfo())); Daniel@0: } Daniel@0: $event = new FilterControllerEvent($this, $controller, $request, $type); Daniel@0: $this->dispatcher->dispatch(KernelEvents::CONTROLLER, $event); Daniel@0: $controller = $event->getController(); Daniel@0: $arguments = $this->resolver->getArguments($request, $controller); Daniel@0: $response = call_user_func_array($controller, $arguments); Daniel@0: if (!$response instanceof Response) { Daniel@0: $event = new GetResponseForControllerResultEvent($this, $request, $type, $response); Daniel@0: $this->dispatcher->dispatch(KernelEvents::VIEW, $event); Daniel@0: if ($event->hasResponse()) { Daniel@0: $response = $event->getResponse(); Daniel@0: } Daniel@0: if (!$response instanceof Response) { Daniel@0: $msg = sprintf('The controller must return a response (%s given).', $this->varToString($response)); Daniel@0: if (null === $response) { Daniel@0: $msg .=' Did you forget to add a return statement somewhere in your controller?'; Daniel@0: } Daniel@0: throw new \LogicException($msg); Daniel@0: } Daniel@0: } Daniel@0: return $this->filterResponse($response, $request, $type); Daniel@0: } Daniel@0: private function filterResponse(Response $response, Request $request, $type) Daniel@0: { Daniel@0: $event = new FilterResponseEvent($this, $request, $type, $response); Daniel@0: $this->dispatcher->dispatch(KernelEvents::RESPONSE, $event); Daniel@0: $this->finishRequest($request, $type); Daniel@0: return $event->getResponse(); Daniel@0: } Daniel@0: private function finishRequest(Request $request, $type) Daniel@0: { Daniel@0: $this->dispatcher->dispatch(KernelEvents::FINISH_REQUEST, new FinishRequestEvent($this, $request, $type)); Daniel@0: $this->requestStack->pop(); Daniel@0: } Daniel@0: private function handleException(\Exception $e, $request, $type) Daniel@0: { Daniel@0: $event = new GetResponseForExceptionEvent($this, $request, $type, $e); Daniel@0: $this->dispatcher->dispatch(KernelEvents::EXCEPTION, $event); Daniel@0: $e = $event->getException(); Daniel@0: if (!$event->hasResponse()) { Daniel@0: $this->finishRequest($request, $type); Daniel@0: throw $e; Daniel@0: } Daniel@0: $response = $event->getResponse(); Daniel@0: if ($response->headers->has('X-Status-Code')) { Daniel@0: $response->setStatusCode($response->headers->get('X-Status-Code')); Daniel@0: $response->headers->remove('X-Status-Code'); Daniel@0: } elseif (!$response->isClientError() && !$response->isServerError() && !$response->isRedirect()) { Daniel@0: if ($e instanceof HttpExceptionInterface) { Daniel@0: $response->setStatusCode($e->getStatusCode()); Daniel@0: $response->headers->add($e->getHeaders()); Daniel@0: } else { Daniel@0: $response->setStatusCode(500); Daniel@0: } Daniel@0: } Daniel@0: try { Daniel@0: return $this->filterResponse($response, $request, $type); Daniel@0: } catch (\Exception $e) { Daniel@0: return $response; Daniel@0: } Daniel@0: } Daniel@0: private function varToString($var) Daniel@0: { Daniel@0: if (is_object($var)) { Daniel@0: return sprintf('Object(%s)', get_class($var)); Daniel@0: } Daniel@0: if (is_array($var)) { Daniel@0: $a = array(); Daniel@0: foreach ($var as $k => $v) { Daniel@0: $a[] = sprintf('%s => %s', $k, $this->varToString($v)); Daniel@0: } Daniel@0: return sprintf("Array(%s)", implode(', ', $a)); Daniel@0: } Daniel@0: if (is_resource($var)) { Daniel@0: return sprintf('Resource(%s)', get_resource_type($var)); Daniel@0: } Daniel@0: if (null === $var) { Daniel@0: return'null'; Daniel@0: } Daniel@0: if (false === $var) { Daniel@0: return'false'; Daniel@0: } Daniel@0: if (true === $var) { Daniel@0: return'true'; Daniel@0: } Daniel@0: return (string) $var; Daniel@0: } Daniel@0: } Daniel@0: } Daniel@0: namespace Symfony\Component\HttpKernel\DependencyInjection Daniel@0: { Daniel@0: use Symfony\Component\HttpFoundation\Request; Daniel@0: use Symfony\Component\HttpFoundation\RequestStack; Daniel@0: use Symfony\Component\HttpKernel\HttpKernelInterface; Daniel@0: use Symfony\Component\HttpKernel\HttpKernel; Daniel@0: use Symfony\Component\HttpKernel\Controller\ControllerResolverInterface; Daniel@0: use Symfony\Component\EventDispatcher\EventDispatcherInterface; Daniel@0: use Symfony\Component\DependencyInjection\ContainerInterface; Daniel@0: use Symfony\Component\DependencyInjection\Scope; Daniel@0: class ContainerAwareHttpKernel extends HttpKernel Daniel@0: { Daniel@0: protected $container; Daniel@0: public function __construct(EventDispatcherInterface $dispatcher, ContainerInterface $container, ControllerResolverInterface $controllerResolver, RequestStack $requestStack = null) Daniel@0: { Daniel@0: parent::__construct($dispatcher, $controllerResolver, $requestStack); Daniel@0: $this->container = $container; Daniel@0: if (!$container->hasScope('request')) { Daniel@0: $container->addScope(new Scope('request')); Daniel@0: } Daniel@0: } Daniel@0: public function handle(Request $request, $type = HttpKernelInterface::MASTER_REQUEST, $catch = true) Daniel@0: { Daniel@0: $request->headers->set('X-Php-Ob-Level', ob_get_level()); Daniel@0: $this->container->enterScope('request'); Daniel@0: $this->container->set('request', $request,'request'); Daniel@0: try { Daniel@0: $response = parent::handle($request, $type, $catch); Daniel@0: } catch (\Exception $e) { Daniel@0: $this->container->set('request', null,'request'); Daniel@0: $this->container->leaveScope('request'); Daniel@0: throw $e; Daniel@0: } Daniel@0: $this->container->set('request', null,'request'); Daniel@0: $this->container->leaveScope('request'); Daniel@0: return $response; Daniel@0: } Daniel@0: } Daniel@0: } Daniel@0: Daniel@0: namespace { return $loader; } Daniel@0: