Esempio n. 1
0
 protected function getDestinationPath(Uri $baseUri, HttpRequest $request)
 {
     if (!$request->hasHeader('Destination')) {
         throw new BadRequestException();
     }
     $dest = $request->getHeader('Destination');
     if (preg_match("'^(?:https?:)?//'i", $dest)) {
         try {
             $uri = new Uri($dest);
         } catch (\Exception $e) {
             throw new BadRequestException($e);
         }
         if (0 !== strpos((string) $uri, rtrim($baseUri, '/') . '/')) {
             throw new WebDavException(WebDav::CODE_BAD_GATEWAY);
         }
         return Uri::decode(substr($uri->getPath(), strlen(rtrim($baseUri->getPath(), '/') . '/')));
     }
     if (preg_match("'^/.*'", $dest)) {
         $path = '/' . trim($dest, '/');
         $base = rtrim('/' . $baseUri->getPath(), '/') . '/';
         if (0 !== strpos($path, $base)) {
             throw new WebDavException(WebDav::CODE_BAD_GATEWAY);
         }
         return Uri::decode(substr($path, strlen($base)));
     }
     throw new BadRequestException();
 }
Esempio n. 2
0
 public function interceptRequest(HttpRequest $request)
 {
     if ($this->secure && !$request->isSecure()) {
         $response = new HttpResponse(Http::REDIRECT_IDENTICAL);
         $response->setHeader('Location', $request->getUri()->setScheme('https'));
         return $response;
     }
     if (!$this->secure && $request->isSecure()) {
         $response = new HttpResponse(Http::REDIRECT_IDENTICAL);
         $response->setHeader('Location', $request->getUri()->setScheme('http'));
         return $response;
     }
 }
Esempio n. 3
0
 /**
  * Dispatch the given request and return the generated HTTP response.
  * 
  * HINT: This method will transform the response entity into a StringEntity populated with the contents of
  * the original entity, HTTP headers of the original entity will be preserved.
  * 
  * NOTE: If you do not specify a host in the URL it will be set to test.me!
  * 
  * @param HttpRequest $request
  * @return HttpResponse
  * 
  * @throws \RuntimeException When the dispatcher did not return an HTTP response and no other exception was thrown.
  */
 public function dispatch(HttpRequest $request)
 {
     $uri = $request->getUri();
     if (NULL === $uri->getHost()) {
         $request->setUri($uri->setHost('test.me')->setPort(Http::PORT));
     }
     $dispatcher = $this->container->get(DispatcherInterface::class);
     $chain = $this->container->get(MiddlewareChain::class);
     $response = $dispatcher->handleRequest($request, $chain, true);
     if (!$response instanceof HttpResponse) {
         $type = is_object($response) ? get_class($response) : gettype($response);
         throw new \RuntimeException(sprintf('Expecting an HttpResponse object, given %s', $type));
     }
     return $response;
 }
 public function __construct(HttpRequest $request, SignatureProviderInterface $signature = NULL)
 {
     $this->signature = $signature;
     $tmp = trim($request->getCookie(self::COOKIE_NAME, ''));
     if ($tmp !== '') {
         $this->messages = [];
         $input = base64_decode($tmp);
         if ($this->signature !== NULL) {
             $input = $this->signature->verify($input);
         }
         foreach ((array) json_decode($input, true) as $message) {
             $this->messages[] = new FlashMessage($message['type'], $message['message']);
         }
         $this->modified = true;
     }
 }
Esempio n. 5
0
 /**
  * {@inheritdoc}
  */
 public function updateCredentials(HttpRequest $request)
 {
     $this->setStatus(self::AUTHENTICATION_NEEDED);
     $path = trim($request->getUri()->getPath(false), '/');
     $logoutPath = trim((new Uri($this->auth->getLogoutUri()))->getPath(false), '/');
     if ($path === $logoutPath) {
         return;
     }
     $session = $this->securityContext->getSession();
     if ($session->isInitialized()) {
         $data = (array) $session->get($this->auth->getKey(), NULL);
         $identity = NULL;
         if (isset($data[FormAuthenticationProvider::SESSION_IDENTITY])) {
             $identity = (string) $data[FormAuthenticationProvider::SESSION_IDENTITY];
         }
         if ($identity !== NULL) {
             $principal = $this->auth->getPrincipalProvider()->findPrincipal($identity);
             if ($principal !== NULL) {
                 $this->setPrincipal($principal);
                 return $this->setStatus(self::AUTHENTICATION_SUCCESSFUL);
             }
         }
     }
     if ($request->isPost(false) && $request->getMediaType()->is(Http::FORM_ENCODED)) {
         $fields = $request->getEntity()->getFields();
         $data = isset($fields['auth']) ? (array) $fields['auth'] : [];
         $data = isset($data[$this->auth->getKey()]) ? (array) $data[$this->auth->getKey()] : [];
         if (array_key_exists(FormAuthenticationProvider::FIELD_USERNAME, $data)) {
             $this->username = (string) $data[FormAuthenticationProvider::FIELD_USERNAME];
         }
         if (array_key_exists(FormAuthenticationProvider::FIELD_PASSWORD, $data)) {
             $this->password = (string) $data[FormAuthenticationProvider::FIELD_PASSWORD];
         }
         if (array_key_exists(FormAuthenticationProvider::FIELD_GUARD, $data)) {
             $guard = (string) $data[FormAuthenticationProvider::FIELD_GUARD];
             $data = (array) $session->get($this->auth->getKey(), NULL);
             if (array_key_exists(FormAuthenticationProvider::SESSION_GUARD, $data)) {
                 if ((string) $data[FormAuthenticationProvider::SESSION_GUARD] == $guard) {
                     $this->guarded = true;
                 }
             }
         }
         return $this->setStatus(self::AUTHENTICATION_NEEDED);
     }
 }
Esempio n. 6
0
 public function invokeHandlers($pathInfo, Uri $baseUri, HttpRequest $request)
 {
     if ($request->isOptions()) {
         $response = new HttpResponse(Http::CODE_NO_CONTENT);
         $response->setHeader('MS-Author-Via', 'DAV');
         try {
             $event = new PopulateOptionsEvent($this->storage->findResource($pathInfo));
         } catch (\OutOfBoundsException $e) {
             return new HttpResponse(WebDav::CODE_NOT_FOUND);
         }
         $this->dispatcher->notify($event);
         $response->setHeader('DAV', implode(', ', $event->features));
         $response->setHeader('Allow', implode(', ', $event->allow));
         $response->setHeader('Cache-Control', 'no-cache, no-store, must-revalidate, proxy-revalidate, max-age=0');
         return $response;
     }
     foreach ($this->handlers as $handler) {
         try {
             $response = $handler->handle($pathInfo, $baseUri, $request, $this->storage);
         } catch (MethodNotAllowedException $e) {
             break;
         } catch (\OutOfBoundsException $e) {
             return new HttpResponse(WebDav::CODE_NOT_FOUND);
         }
         if ($response !== NULL) {
             if (!$response->hasHeader('Cache-Control')) {
                 $response->setHeader('Cache-Control', 'no-cache, no-store, must-revalidate, proxy-revalidate, max-age=0');
             }
             return $response;
         }
     }
     try {
         $resource = $this->storage->findResource($pathInfo);
     } catch (\OutOfBoundsException $e) {
         return new HttpResponse(WebDav::CODE_NOT_FOUND);
     }
     $event = new PopulateOptionsEvent($resource);
     $this->dispatcher->notify($event);
     $response = new HttpResponse(Http::CODE_METHOD_NOT_ALLOWED);
     $response->setHeader('MS-Author-Via', 'DAV');
     $response->setHeader('DAV', implode(', ', $event->features));
     $response->setHeader('Allow', implode(', ', $event->allow));
     $response->setHeader('Cache-Control', 'no-cache, no-store, must-revalidate, proxy-revalidate, max-age=0');
     return $response;
 }
Esempio n. 7
0
 /**
  * {@inheritdoc}
  */
 public function startAuthentication(TokenInterface $token, HttpRequest $request, HttpResponse $response)
 {
     if (!$token instanceof FormAuthToken) {
         throw new SecurityException(sprintf('Invalid token %s passed to %s', get_class($token), get_class($this)));
     }
     $loginUri = new Uri($this->auth->getLoginUri());
     $path = trim($request->getUri()->getPath(false), '/');
     $loginPath = trim($loginUri->getPath(false), '/');
     $session = $this->securityContext->getSession();
     $data = (array) $session->get($this->auth->getKey(), NULL);
     // Save the current URI when it is not the login URI.
     if ($path !== $loginPath && !array_key_exists(FormAuthenticationProvider::SESSION_URI, $data)) {
         $data[FormAuthenticationProvider::SESSION_URI] = (string) $request->getUri();
     }
     $session->set($this->auth->getKey(), $data);
     $response->setStatus(Http::REDIRECT_TEMPORARY);
     $response->setReason(Http::getReason(Http::REDIRECT_TEMPORARY));
     $response->setHeader('Location', $loginUri);
 }
Esempio n. 8
0
 public function handle($path, Uri $baseUri, HttpRequest $request, StorageInterface $storage)
 {
     if (!$request->isPut()) {
         return;
     }
     if ($request->hasHeader('Content-Range')) {
         throw new BadRequestException();
     }
     $stream = $request->hasEntity() ? $request->getEntity()->getInputStream() : new StringStream();
     $created = false;
     $storage->beginTransaction();
     try {
         try {
             $resource = $storage->findResource($path);
             if ($resource->isCollection()) {
                 throw new MethodNotAllowedException();
             }
             $resource = $storage->updateResource($resource, $stream);
         } catch (\OutOfBoundsException $e) {
             $parts = explode('/', $path);
             $name = array_pop($parts);
             try {
                 $parent = $storage->findResource(implode('/', $parts));
             } catch (\OutOfBoundsException $ex) {
                 throw new WebDavException(WebDav::CODE_CONFLICT, $ex);
             }
             if (!$parent->isCollection()) {
                 throw new WebDavException(WebDav::CODE_CONFLICT);
             }
             $resource = $storage->createResource($parent, $name, $stream);
             $created = true;
         }
     } catch (\Exception $e) {
         $storage->rollBack();
         throw $e;
     }
     $storage->commit();
     $response = new HttpResponse(empty($created) ? WebDav::CODE_NO_CONTENT : WebDav::CODE_CREATED);
     $response->setHeader('ETag', $resource->getEtag());
     return $response;
 }
Esempio n. 9
0
 public function handle($path, Uri $baseUri, HttpRequest $request, StorageInterface $storage)
 {
     if (!$request->isGet() && !$request->isHead()) {
         return;
     }
     try {
         $resource = $storage->findResource($path);
     } catch (\OutOfBoundsException $e) {
         return new HttpResponse(WebDav::CODE_NOT_FOUND);
     }
     if ($resource->isCollection()) {
         return new HttpResponse(WebDav::CODE_NO_CONTENT);
     }
     $cacheControl = new CacheControlHeader();
     $cacheControl->setPrivate(true)->setMustRevalidate(true)->setMaxAge(7200);
     if ($request->isGet() && ($response = $request->evaluatePreconditions($resource->getEtag()))) {
         return $response->setHeader($cacheControl);
     }
     $response = new HttpResponse();
     $response->setHeader($cacheControl);
     $response->setHeader('Content-Type', $resource->getMediaType());
     $response->setHeader('ETag', $resource->getEtag());
     if ($request->isGet()) {
         $response->setEntity($resource->getInputStream());
     }
     return $response;
 }
Esempio n. 10
0
 public function handle($path, Uri $baseUri, HttpRequest $request, StorageInterface $storage)
 {
     if (!$request->isDelete()) {
         return;
     }
     $resource = $storage->findResource($path);
     if ($resource->isCollection() && $request->hasHeader('Depth')) {
         $depth = $request->getHeader('Depth', 'infinity');
         if ($depth != 'infinity') {
             throw new BadRequestException();
         }
     }
     $storage->beginTransaction();
     try {
         $storage->deleteResource($resource);
     } catch (\Exception $e) {
         $storage->rollBack();
         throw $e;
     }
     $storage->commit();
     return new HttpResponse(WebDav::CODE_NO_CONTENT);
 }
Esempio n. 11
0
 protected function parseBody(HttpRequest $request)
 {
     $body = $request->getContents();
     if ($body === '') {
         return;
     }
     try {
         $xml = (new XmlDocumentBuilder())->buildFromSource($body);
     } catch (XmlParseException $e) {
         throw new BadRequestException($e);
     }
     $root = $xml->documentElement;
     if ($root->namespaceURI != WebDav::NS_DAV || $root->localName != 'mkcol') {
         throw new WebDavException(WebDav::CODE_UNPROCESSABLE_ENTITY);
     }
     $xpath = new \DOMXPath($xml);
     $xpath->registerNamespace('D', WebDav::NS_DAV);
     $proppatch = new ProppatchRequest();
     foreach ($xpath->query('/mkcol/*') as $el) {
         if ($el->namespaceURI != WebDav::NS_DAV) {
             throw new WebDavException(WebDav::CODE_UNPROCESSABLE_ENTITY);
         }
         if ($el->localName == 'set') {
             $nodes = $xpath->query('D:prop/*', $el);
             if ($nodes->length < 1) {
                 throw new WebDavException(WebDav::CODE_UNPROCESSABLE_ENTITY);
             }
             foreach ($nodes as $set) {
                 $proppatch->addOperation(new SetPropertyOperation(new XmlName($set), $set));
             }
         } else {
             throw new WebDavException(WebDav::CODE_UNPROCESSABLE_ENTITY);
         }
     }
     if ($proppatch->count() < 1) {
         throw new WebDavException(WebDav::CODE_UNPROCESSABLE_ENTITY);
     }
     return $proppatch;
 }
Esempio n. 12
0
 protected function parseBody(HttpRequest $request)
 {
     if (!$request->hasEntity()) {
         return new AllPropRequest();
     }
     $contents = trim($request->getContents());
     if ($contents == '') {
         return new AllPropRequest();
     }
     try {
         $xml = (new XmlDocumentBuilder())->buildFromSource($contents);
     } catch (XmlParseException $e) {
         throw new BadRequestException($e);
     }
     $root = $xml->documentElement;
     if ($root->namespaceURI != WebDav::NS_DAV || $root->localName != 'propfind') {
         throw new WebDavException(WebDav::CODE_UNPROCESSABLE_ENTITY);
     }
     $xpath = new \DOMXPath($xml);
     $xpath->registerNamespace('D', WebDav::NS_DAV);
     $nodes = $xpath->query('/D:propfind/D:*');
     if ($nodes->length == 0) {
         throw new WebDavException(WebDav::CODE_UNPROCESSABLE_ENTITY);
     }
     $nodes = $xpath->query('/D:propfind/D:propname');
     if ($nodes->length == 1) {
         return new PropNameRequest();
     }
     $nodes = $xpath->query('/D:propfind/D:allprop');
     if ($nodes->length == 1) {
         return $this->parseAllPropRequest($nodes->item(0)->parentNode, $xpath);
     }
     $nodes = $xpath->query('/D:propfind/D:prop');
     if ($nodes->length > 0) {
         return $this->parsePropfindRequest($nodes, $xpath);
     }
     throw new WebDavException(WebDav::CODE_UNPROCESSABLE_ENTITY);
 }
Esempio n. 13
0
 public function handle($path, Uri $baseUri, HttpRequest $request, StorageInterface $storage)
 {
     if ($request->getMethod() != WebDav::METHOD_REPORT) {
         return;
     }
     try {
         $resource = $storage->findResource($path);
     } catch (\OutOfBoundsException $e) {
         throw new NotFoundException($e);
     }
     try {
         $xml = (new XmlDocumentBuilder())->buildFromSource($request->getContents());
     } catch (XmlParseException $e) {
         throw new BadRequestException($e);
     }
     $name = new XmlName($xml->documentElement);
     foreach ($this->generators as $generator) {
         if ($generator->getReportName() == $name && $generator->isSupported($resource)) {
             return $generator->generateReport($xml->documentElement, $resource, $baseUri, $request, $this->dispatcher);
         }
     }
     throw new UnsupportedReportException();
 }
Esempio n. 14
0
 /**
  * {@inheritdoc}
  */
 public function updateCredentials(HttpRequest $request)
 {
     $this->setStatus(self::NO_CREDENTIALS);
     $this->username = NULL;
     $this->password = NULL;
     if ('' === ($auth = trim($request->getHeader('Authorization', '')))) {
         return;
     }
     $parts = preg_split("'\\s+'", $auth, 2);
     if (!is_array($parts) || count($parts) != 2 || strtolower($parts[0]) !== 'basic') {
         return;
     }
     $credentials = explode(':', (string) @base64_decode($parts[1]), 2);
     if (!is_array($credentials) || count($credentials) != 2) {
         return;
     }
     $username = $credentials[0];
     if (false !== ($index = strrpos($username, '\\\\'))) {
         $username = substr($username, $index + 1);
     }
     $this->username = trim($username);
     $this->password = trim($credentials[1]);
     $this->setStatus(self::AUTHENTICATION_NEEDED);
 }
Esempio n. 15
0
 protected function sendChunkedEntity(StreamInterface $stream, HttpRequest $request, $compress)
 {
     $stream->write("\r\n");
     $body = new ChunkEncodedOutputStream($stream);
     $body->setCloseCascade(false);
     if ($compress) {
         $body = new DeflateOutputStream($body, DeflateOutputStream::GZIP);
     }
     try {
         $request->getEntity()->send($body);
     } finally {
         $body->close();
     }
 }
Esempio n. 16
0
 public function updateCredentials(HttpRequest $request)
 {
     $this->setStatus(self::NO_CREDENTIALS);
     $this->type = NULL;
     $this->username = NULL;
     $this->domain = NULL;
     $this->workstation = NULL;
     $this->clientBlob = NULL;
     $this->clientHash = NULL;
     $this->flags = NULL;
     $this->auth = NULL;
     if ('' === ($auth = trim($request->getHeader('Authorization', '')))) {
         return;
     }
     $parts = preg_split("'\\s+'", $auth, 2);
     if (!is_array($parts) || count($parts) != 2 || strtoupper($parts[0]) !== 'NTLM') {
         return;
     }
     $this->setStatus(self::AUTHENTICATION_NEEDED);
     $auth = @base64_decode($parts[1]);
     if (self::NTLM_HEADER !== substr($auth, 0, 8)) {
         return;
     }
     $this->auth = $auth;
     // Unpack the message type sent by the client, must be one of 1 or 3.
     $type = (int) $this->readUnsignedLong($this->auth, 8);
     if (1 == $type) {
         $this->type = 1;
         $this->flags = (int) $this->readUnsignedLong($this->auth, 12);
     } elseif (3 == $type) {
         $this->type = 3;
         $this->domain = $this->readSecurityBuffer($this->auth, 28);
         $this->username = $this->readSecurityBuffer($this->auth, 36);
         $this->workstation = $this->readSecurityBuffer($this->auth, 44);
         if (false !== strpos($this->username, '@')) {
             $tmp = explode('@', $this->username, 2);
             $this->username = trim($tmp[0]);
             $this->domain = trim($tmp[1]);
         }
         $ntlm = $this->readSecurityBuffer($this->auth, 20, false);
         $this->clientHash = (string) substr($ntlm, 0, 16);
         $this->clientBlob = (string) substr($ntlm, 16);
     }
 }
Esempio n. 17
0
 public function buildHttpRequest()
 {
     try {
         $method = $this->getRequestMethod();
         $request = new HttpRequest($this->getRequestUri(), $method, $this->getProtocol());
         $request->setRawUri($this->getRawRequestUri());
         $request->setPathBase(trim($this->getBaseUri()->getPath(false), '/'));
         $request->setCookies($this->getCookies());
         foreach ($this->getHeaders() as $name => $value) {
             $request->setHeader($name, $value);
             if ($name == 'content-type') {
                 $mediaType = $request->getMediaType();
                 if ($mediaType->is(Http::FORM_ENCODED)) {
                     if ($method != Http::METHOD_POST) {
                         $fields = Uri::parseQuery(file_get_contents($this->getInputUrl()));
                         $request->setEntity(new FormEntity($fields));
                     } else {
                         $request->setEntity(new FormEntity($this->getPostParams()));
                     }
                 } elseif ($mediaType->is(Http::FORM_MULTIPART_ENCODED)) {
                     if ($method != Http::METHOD_POST) {
                         throw new \RuntimeException('Multipart requests must be POST');
                     }
                     $request->setEntity(new MultipartFormEntity($this->getPostParams(), $this->getFiles()));
                 }
             }
         }
         if (!$request->hasEntity()) {
             $request->setEntity(new StreamEntity(ResourceInputStream::fromUrl($this->getInputUrl())));
         }
     } catch (BadRequestException $e) {
         throw $e;
     } catch (\Exception $e) {
         throw new BadRequestException($e);
     }
     return $request;
 }
Esempio n. 18
0
 /**
  * @Route("POST /deployments/archive")
  */
 public function deployArchive(HttpRequest $request, $name = '', array $extensions = [])
 {
     if (!$request->hasEntity()) {
         throw new \RuntimeException('No file has been uploaded');
     }
     $builder = $this->repositoryService->createDeployment($name);
     $builder->addExtensions($extensions);
     $in = $request->getEntity()->getInputStream();
     $archive = tempnam(sys_get_temp_dir(), 'era');
     $fp = fopen($archive, 'wb');
     try {
         while (false !== ($chunk = $in->read())) {
             fwrite($fp, $chunk);
         }
     } finally {
         @fclose($fp);
     }
     $builder->addArchive($archive);
     $deployment = $this->repositoryService->deploy($builder);
     $definitions = $this->repositoryService->createProcessDefinitionQuery()->deploymentId($deployment->getId())->findAll();
     $response = new HttpResponse(Http::CODE_CREATED);
     $response->setHeader('Location', $this->uri->generate('../show-deployment', ['id' => $deployment->getId()]));
     $response->setEntity(new JsonEntity(['deployment' => $deployment, 'definitions' => $definitions, 'resources' => array_values($deployment->findResources()), '_links' => ['self' => $this->uri->generate('../show-deployment', ['id' => $deployment->getId()])]]));
     return $response;
 }
 /**
  * {@inheritdoc}
  */
 public function authenticate(SecurityContextInterface $context, TokenInterface $token, HttpRequest $request)
 {
     if (!$token instanceof FormAuthToken) {
         throw new SecurityException(sprintf('Token %s not supported by provider %s', get_class($token), get_class($this)));
     }
     $this->failedLogin = false;
     $this->username = $token->getUsername();
     $this->guard = bin2hex(random_bytes($this->guardByteCount));
     $path = trim($request->getUri()->getPath(false), '/');
     $loginPath = trim((new Uri($this->getLoginUri()))->getPath(false), '/');
     $logoutPath = trim((new Uri($this->getLogoutUri()))->getPath(false), '/');
     $isLogin = $path === $loginPath;
     $isLogout = $path === $logoutPath;
     $session = $context->getSession();
     if ($isLogout) {
         $session->remove($this->getKey());
         $token->setPrincipal(new AnonymousPrincipal());
         $token->setStatus(TokenInterface::AUTHENTICATION_SUCCESSFUL);
         return;
     }
     if ($isLogin) {
         try {
             if ($request->isPost(false)) {
                 $identity = $token->getUsername();
                 $password = $token->getPassword();
                 // Fetch user independent of guard in order to prevent leakage of timing information.
                 $principal = $this->getPrincipalProvider()->findPrincipalUsingPassword($identity, $password);
                 // Invalidate when guard fails.
                 if (!$token->isGuarded()) {
                     $principal = NULL;
                 }
                 if ($principal !== NULL) {
                     $session = $context->getSession();
                     $data = (array) $session->get($this->getKey(), NULL);
                     $data[self::SESSION_IDENTITY] = (string) $principal->getIdentity();
                     $session->set($this->getKey(), $data);
                     if (array_key_exists(self::SESSION_URI, $data)) {
                         $uri = $data[self::SESSION_URI];
                         unset($data[self::SESSION_URI]);
                         $session->set($this->getKey(), $data);
                         $response = new HttpResponse(Http::REDIRECT_TEMPORARY);
                         $response->setHeader('Location', $uri);
                         return $response;
                     }
                     $token->setPrincipal($principal);
                     $token->setStatus(TokenInterface::AUTHENTICATION_SUCCESSFUL);
                     return;
                 }
                 $this->failedLogin = true;
             }
             $token->setPrincipal(new AnonymousPrincipal());
             $token->setStatus(TokenInterface::AUTHENTICATION_SUCCESSFUL);
             return;
         } finally {
             $data = (array) $session->get($this->getKey(), []);
             $data[self::SESSION_GUARD] = $this->guard;
             $session->set($this->getKey(), $data);
         }
     }
 }
Esempio n. 20
0
 protected function handleUnlock(ResourceInterface $resource, Uri $baseUri, HttpRequest $request, LockStorageInterface $storage)
 {
     if (!$resource instanceof LockableResourceInterface) {
         throw new MethodNotAllowedException();
     }
     if (!$resource->isLockSupported()) {
         throw new MethodNotAllowedException();
     }
     if (!$resource->isLocked()) {
         throw new LockTokenMatchesRequestUriException(WebDav::CODE_CONFLICT);
     }
     if (!$request->hasHeader('Lock-Token')) {
         throw new BadRequestException();
     }
     try {
         $tmp = $request->getHeader('Lock-Token', '');
         $m = NULL;
         if (!preg_match("'^<?urn:webdav:lock:([0-9a-f\\-]{36})>?\$'i", $tmp, $m)) {
             throw new BadRequestException();
         }
         $token = new UUID($m[1]);
     } catch (\InvalidArgumentException $e) {
         throw new BadRequestException($e);
     }
     $lockInfo = $resource->getLockInfo();
     if ($token != $lockInfo->getToken() || $lockInfo->getExpires() < new \DateTime()) {
         throw new LockTokenMatchesRequestUriException(WebDav::CODE_CONFLICT);
     }
     $storage->beginTransaction();
     try {
         $storage->removeLock($lockInfo);
     } catch (\Exception $e) {
         $storage->rollBack();
         throw $e;
     }
     $storage->commit();
     return new HttpResponse(Http::CODE_NO_CONTENT);
 }
Esempio n. 21
0
 /**
  * Compute the content MD5 hash of the request body (streams request body contents to a
  * temporary file and incrementaly computes the hash value replacing the requests input
  * URL with the URL of the created file).
  *
  * @param HttpRequest $request
  * @return string
  */
 protected function computeContentMd5(HttpRequest $request)
 {
     if (!$request->hasEntity()) {
         return md5('');
     }
     $hash = hash_init('md5');
     $in = $request->getEntity()->getInputStream();
     $tmp = new \SplTempFileObject();
     $fp = $tmp->openFile('wb', false);
     try {
         flock($fp, LOCK_EX);
         while (false !== ($chunk = $in->read())) {
             hash_update($hash, $chunk);
             fwrite($fp, $chunk);
         }
     } finally {
         @fclose($fp);
     }
     $request->setEntity(new StreamEntity($tmp->openFile('rb', false)));
     return hash_final($hash);
 }
Esempio n. 22
0
 /**
  * {@inheritDoc}
  */
 public function terminate(HttpRequest $request, HttpResponse $response)
 {
     $this->dispatcher->notify(new SendResponseEvent($request, self::MASTER_REQUEST, $response, $this));
     while (ob_get_level() > 1) {
         ob_end_flush();
     }
     $buffer = ob_get_level() ? ob_get_clean() : '';
     ini_set('default_mimetype', NULL);
     ini_set('default_charset', NULL);
     if ($response->hasEntity() && !$request->isHead()) {
         if ('gzip' == strtolower($response->getHeader('Content-Encoding', ''))) {
             ini_set('zlib.output_compression_level', 1);
             ini_set('zlib.output_compression', 4096);
         } else {
             ob_start(NULL, 4096);
         }
     }
     foreach ($response->getHeaders() as $n => $headers) {
         switch ($n) {
             case 'server':
             case 'connection':
             case 'content-length':
             case 'content-encoding':
             case 'transfer-encoding':
                 continue 2;
         }
         foreach ($headers as $index => $header) {
             header(sprintf('%s: %s', $header[0], $header[1]), $index == 0);
         }
     }
     $statusLine = sprintf('%s %u %s', $response->getProtocol(), $response->getStatus(), $response->getReason());
     header($statusLine, true, $response->getStatus());
     if ($response->hasEntity() && !$request->isHead()) {
         $stream = new UrlStream('php://output', 'wb');
         try {
             $response->getEntity()->send($stream);
         } finally {
             $stream->close();
         }
     }
     if (function_exists('fastcgi_finish_request')) {
         @fastcgi_finish_request();
     }
     $event = new TerminateEvent($request, self::MASTER_REQUEST, $response, $this);
     $event->bufferedContent = $buffer;
     $this->dispatcher->notify($event);
 }
Esempio n. 23
0
 protected function buildProppatchResponse(ProppatchRequest $proppatch, HttpRequest $request, StorageInterface $storage)
 {
     $builder = new PatchResponseBuilder($request->getUri(), $proppatch);
     return $builder->buildResponse(WebDav::CODE_MULTI_STATUS);
 }