@param Request $request
@param Response $response
@param string $type

@return File
13713
private function parseBinaryResponseBody(Request $request, Response $response, $type)
    {
        $body = $response->getBody();

        return new File($type, (string) $body, $body->getSize());
    }
28354
public function createAction(Request $request, $type = 0)
    {
        /** @var ContentManager $manager */
        $manager = $this->get('opifer.content.content_manager');

        if ($type) {
            $contentType = $this->get('opifer.content.content_type_manager')->getRepository()->find($type);
            $content = $this->get('opifer.eav.eav_manager')->initializeEntity($contentType->getSchema());
            $content->setContentType($contentType);
        } else {
            $content = $manager->initialize();
        }

        $form = $this->createForm(ContentType::class, $content);
        $form->handleRequest($request);

        if ($form->isValid()) {
            // Create a new document
            $blockManager = $this->get('opifer.content.block_manager');
            $document = new DocumentBlock();
            $document->setPublish(true);
            $blockManager->save($document);

            $content->setBlock($document);
            $manager->save($content);

            return $this->redirectToRoute('opifer_content_contenteditor_design', [
                'type'    => 'content',
                'id'      => $content->getId(),
                'rootVersion' => 0,
            ]);
        }

        return $this->render($this->getParameter('opifer_content.content_new_view'), [
            'form' => $form->createView(),
        ]);
    }
1147742
private function getRemuxStream(Request $request, Response $response)
    {
        if (!$this->config->remux) {
            throw new Exception(_('You need to enable remux mode to merge two formats.'));
        }
        $stream = $this->video->getRemuxStream();
        $response = $response->withHeader('Content-Type', 'video/x-matroska');
        if ($request->isGet()) {
            $response = $response->withBody(new Stream($stream));
        }

        return $response->withHeader(
            'Content-Disposition',
            'attachment; filename="'.$this->video->getFileNameWithExtension('mkv')
        );
    }
195081
public function setResponse(string $type, $response)
    {
        $this->response = new Response($type, $response);
        $this->initialized['response'] = true;

        return $this;
    }
1266001
public function handle(Request $request, $type = HttpKernelInterface::MASTER_REQUEST, $catch = true)
	{
		$response = $this->app->handle($request, $type, $catch);

		foreach ($this->cookies->getQueuedCookies() as $cookie)
		{
			$response->headers->setCookie($cookie);
		}

		return $response;
	}
551119
private function addCommonHeaders(Request $request, Response $response)
    {
        // replace content-type if a schema was requested
        if ($request->attributes->get('schemaRequest')) {
            $response->headers->set('Content-Type', 'application/schema+json');
        }

        if ($request->attributes->has('recordCount')) {
            $response->headers->set(
                'X-Record-Count',
                (string) $request->attributes->get('recordCount')
            );
        }

        // search source header?
        if ($request->attributes->has('X-Search-Source')) {
            $response->headers->set(
                'X-Search-Source',
                (string) $request->attributes->get('X-Search-Source')
            );
        }
    }
852045
public function createAction(Request $request, $type = 0)
    {
        /** @var ContentManager $manager */
        $manager = $this->get('opifer.content.content_manager');

        if ($type) {
            $contentType = $this->get('opifer.content.content_type_manager')->getRepository()->find($type);
            $content = $this->get('opifer.eav.eav_manager')->initializeEntity($contentType->getSchema());
            $content->setContentType($contentType);
        } else {
            $content = $manager->initialize();
        }

        $form = $this->createForm(LayoutType::class, $content);
        $form->handleRequest($request);

        if ($form->isValid()) {
            //setSlug because slugListener will create one based on title
            $content->setSlug(sha1(date('y-m-d h:i:s')));
            $content->setAlias(sha1(date('y-m-d h:i:s')));

            $manager->save($content);

            return $this->redirectToRoute('opifer_content_contenteditor_design', [
                'owner' => 'content',
                'ownerId' => $content->getId(),
            ]);
        }

        return $this->render($this->getParameter('opifer_content.content_new_view'), [
            'form' => $form->createView(),
        ]);
    }
168503
public function actionUpload($type)
    {
        /** @var $loadFile \Symfony\Component\HttpFoundation\File\UploadedFile */
        $loadFile = App::$Request->files->get('upload');
        if ($loadFile === null || $loadFile->getError() !== 0)
            return $this->errorResponse(__('File upload failed'));

        // get file extension
        $fileExt = '.' . $loadFile->guessExtension();
        // check if this request type is allowed
        if ($this->allowedExt[$type] === null || !Any::isArray($this->allowedExt[$type]))
            throw new NativeException('Hack attempt');

        // check if this file extension is allowed to upload
        if (!Arr::in($fileExt, $this->allowedExt[$type])) {
            return $this->errorResponse(__('This file type is not allowed to upload'));
        }

        $date = Date::convertToDatetime(time(), 'd-m-Y');

        // create file hash based on name-size
        $fileNewName = App::$Security->simpleHash($loadFile->getFilename() . $loadFile->getSize()) . $fileExt;
        $savePath = Normalize::diskFullPath('/upload/' . $type . '/' . $date);
        // save file from tmp to regular
        $loadFile->move($savePath, $fileNewName);

        // generate URI of uploaded file
        $url = '/upload/' . $type . '/' . $date . '/' . $fileNewName;

        return App::$View->render('editor/load_success',
            [
                'callbackId' => (int)App::$Request->query->get('CKEditorFuncNum'),
                'url' => $url
            ],
            __DIR__);
    }
340188
private function executeInterceptor($type, Request $request, Response $response) {
		foreach ($this->interceptor[$type] as $it) {
			if (isset($it['all'])) {
				if ($it['handler']->{$type}($request, $response) !== null) {
					return true;
				}
			} elseif (isset($it['uri'])) {
				if ($request->uri === $it['uri']) {
					if ($it['handler']->{$type}($request, $response) !== null) {
						return true;
					}
				}
			} else {
				if (preg_match($it['regex'], $request->uri)) {
					if ($it['handler']->{$type}($request, $response) !== null) {
						return true;
					}
				}
			}
		}
		return null;
	}
1259883
public function request(TypeInfo $resultTypeInfo, Request $apiRequest)
    {
        $headers = $apiRequest->getHeaders();

        $headers['Accept'] = JsonRequest::CONTENT_TYPE;

        if ($this->bearerToken !== null) {
            $headers['Authorization'] = 'Bearer ' . $this->bearerToken;
        }

        $request = new Psr7\Request(
            $apiRequest->method,
            $apiRequest->getUrl($this->baseUrl),
            $headers,
            $apiRequest->getBody()
        );

        $options = $apiRequest->getOptions();
        $options['query'] = $apiRequest->getQuery();

        $response = $this->httpClient->send($request, $options);

        $responseBody = $response->getBody();
        $contents = $responseBody->getContents();
        $rawResult = Common::decode($contents);

        return $resultTypeInfo->deserialize($rawResult);
    }
1000761
public function index(Request $request, $type = 'default')
    {
        // Get the configuration
        $config = Config::get('media-upload');

        $configType = Config::get('media-upload.types.'.$type);

        if ( ! $configType )
        {
            return [ 'error' => 'type-not-found' ];
        }

        // Check if file is uploaded
        if ( ! \Input::hasFile('file') )
        {
            return [ 'error' => 'file-not-found' ];
        }

        $file  = \Input::file('file');

        // get file size in Bytes
        $file_size = $file->getSize();

        // Check the file size
        if ( $file_size > $config['max_size'] * 1024 || ( isset($configType['max_size']) && $file_size > $configType['max_size'] * 1024 ) )
        {
            return [ 'error' => 'limit-size' ];
        }

        // get the extension
        $ext = strtolower( $file->getClientOriginalExtension() );

        // checking file format
        $format = $this->getFileFormat($ext);

        // TODO: check file format
        if( isset($configType['format']) && ! in_array($format, explode('|', $configType['format'])) )
        {
            return [ 'error' => 'invalid-format' ];
        }

        // saving file
        $filename = date('U').str_random(10);
        $file->move(public_path().'/'.$config['dir'].'/'.$type, $filename.'.'.$ext);

        $file_path = $config['dir'].'/'.$type.'/'.$filename.'.'.$ext;

        if ( $format == 'image' && isset($config['types'][$type]['image']) && count($config['types'][$type]['image']) )
        {

            $img = Image::make(public_path().'/'.$file_path);

            foreach($config['types'][$type]['image'] as $task => $params)
            {
                switch($task) {
                    case 'resize':
                        $img->resize($params[0], $params[1]);
                        break;
                    case 'fit':
                        $img->fit($params[0], $params[1]);
                        break;
                    case 'crop':
                        $img->crop($params[0], $params[1]);
                        break;
                    case 'thumbs':
                        $img->save();

                        foreach($params as $name => $sizes) {
                            
                            $img->backup();

                            $thumb_path = $config['dir'].'/'.$filename.'-'.$name.'.'.$ext;

                            $img->fit($sizes[0], $sizes[1])->save($thumb_path);

                            $img->reset();
                        }
                        break;
                }
            }

            $img->save();
        }

        return [
            'original' => [
                'name' => $file->getClientOriginalName(),
                'size' => $file_size,
            ],
            'ext' => $ext,
            'format' => $format,
            // 'image' => [
            //     'size' =>$img->getSize(),
            // ],
            'name' => $filename,
            'path' => $file_path,
        ];

    }
1270163
public function uploadAction(Request $request, $type = 'image')
    {
        $this->checkIfMediaBundleIsLoaded();

        if (false === $this->admin->checkAccess('CREATE')) {
            throw new AccessDeniedException();
        }

	    /** @var $mediaAdmin \Sonata\MediaBundle\Admin\ORM\MediaAdmin */
	    $mediaAdmin = $this->container->get('sonata.media.admin.media');

	    $mediaAdmin->setRequest($request);

        $provider = $request->get('provider');
        $file = $request->files->get('upload');

	    $message = $this->admin->trans(
		    'The file is not readable.',[], 'validators'
	    );
	    $response = ['uploaded' => 0, 'error'  => ['message' =>  $message]];


        if (!$provider || null === $file) {
	        return new JsonResponse($response);
        }

        if ($file instanceof UploadedFile && $file->isValid()) {

            try {
                $context = $request->get('context', $this->get('sonata.media.pool')->getDefaultContext());

	            /** @var Media $media */
	            $media = $mediaAdmin->getNewInstance();
	            $media->setEnabled(true);
	            $media->setName($file->getClientOriginalName());
                $media->setBinaryContent($file);
                $media->setContext($context);
                $media->setProviderName($provider);


	            $provider = $mediaAdmin->getPool()->getProvider($provider);

	            $provider->transform($media);

	            $validator = $this->container->get('validator');

	            $errors = $validator->validate($media);

	            if ($errors->count() > 0) {
		            $duplicate = false;
		            foreach ($errors as $error) {
			            $errorMessages[] = $error->getMessage();

			            if ($error->getMessage() == 'File is duplicate') {
				            $duplicate = true;
			            }
		            }

		            if ($duplicate) {
			            $originalMedia = $mediaAdmin->checkForDuplicate($media);
			            $path = $provider->generatePublicUrl($originalMedia, 'reference');
			            $response = [
			            	'uploaded' => 1,
				            'fileName' => $originalMedia->getMetadataValue('filename'),
				            'url' => $path,
				            'error'  => ['message' => 'duplicate media']];
		            }else{
			            $response = ['uploaded' => 0, 'error'  => ['message' =>  implode(', ', $errorMessages)]];
		            }

		            return new JsonResponse($response);
	            }

	            try {
		            $mediaAdmin->create($media);
		            $path = $provider->generatePublicUrl($media, 'reference');
                    $response = ['uploaded' => 1, 'fileName' => $media->getMetadataValue('filename'), 'url' => $path ];
	            } catch (\Exception $e) {
		            $response = ['uploaded' => 0, 'error'  => ['message' => $e->getMessage()]];
	            }

            } catch (\Exception $e) {

	            $response = ['uploaded' => 0, 'error'  => ['message' => $e->getMessage()]];
            } catch (\Throwable $e) {
	            $response = ['uploaded' => 0, 'error'  => ['message' => $e->getMessage()]];
            }
        } elseif ($file instanceof UploadedFile && !$file->isValid()) {

	        $response = ['uploaded' => 0, 'error'  => ['message' =>  $file->getError()]];
        } else {
            $message = $this->admin->trans(
                'error.file_upload_size',
                ['%max_server_size%' => ini_get('upload_max_filesize')], 'media'
            );

	        $response = ['uploaded' => 0, 'error'  => ['message' =>  $message]];
        }

        return new JsonResponse($response);
    }
47124
private function getDownloadResponse(Request $request, Response $response)
    {
        try {
            $videoUrls = $this->video->getUrl();
        } catch (EmptyUrlException $e) {
            /*
            If this happens it is probably a playlist
            so it will either be handled by getStream() or throw an exception anyway.
             */
            $videoUrls = [];
        }
        if (count($videoUrls) > 1) {
            return $this->getRemuxStream($request, $response);
        } elseif ($this->config->stream && (isset($this->video->entries) || $request->getQueryParam('stream'))) {
            return $this->getStream($request, $response);
        } else {
            if (empty($videoUrls[0])) {
                throw new Exception(_("Can't find URL of video."));
            }

            return $response->withRedirect($videoUrls[0]);
        }
    }
1235695
public function request($type, $file = null)
    {
        static $retries = [];

        // check if not checked
        $this->check();

        // check if is cached
        if(isset($this->cache[sha1($file)][$type]))
        {
            return $this->cache[sha1($file)][$type];
        }
        elseif(!isset($retries[sha1($file)]))
        {
            $retries[sha1($file)] = $this->retries;
        }

        // parameters for cURL request
        list($resource, $headers) = $this->getParameters($type, $file);

        // check the request
        $file = parent::checkRequest($type, $file);

        // cURL options
        $options = $this->getCurlOptions($type, $file);

        // sets headers
        foreach($headers as $header)
        {
            $options[CURLOPT_HTTPHEADER][] = $header;
        }

        // cURL init and options
        $options[CURLOPT_URL] = $this->getUrl() . "/$resource";

        // get the response and the HTTP status code
        list($response, $status) = $this->exec($options);

        // reduce memory usage closing cURL resource
        if(isset($options[CURLOPT_INFILE]) && is_resource($options[CURLOPT_INFILE]))
        {
            fclose($options[CURLOPT_INFILE]);
        }

        // request completed successfully
        if($status == 200)
        {
            if($type == 'meta')
            {
                $response = Metadata::make($response, $file);
            }

            // cache certain responses
            if(in_array($type, ['lang', 'meta']))
            {
                $this->cache[sha1($file)][$type] = $response;
            }
        }
        // request completed successfully but result is empty
        elseif($status == 204)
        {
            $response = null;
        }
        // retry on request failed with error 500
        elseif($status == 500 && $retries[sha1($file)]--)
        {
            $response = $this->request($type, $file);
        }
        // other status code is an error
        else
        {
            $this->error($status, $resource);
        }

        return $response;
    }
916029
private function parseJsonResponseBody(Request $request, Response $response, $type)
    {
        // Find resource type (URL) in response location or request url
        $location = $response->hasHeader('Location')
            ? $this->createUri($response->getHeaderLine('Location'))
            : $request->getUri();

        $uri = urldecode($location->getPath());

        // Remove version from URI
        $uri = preg_replace('#^/' . self::CURRENT_VERSION . '#', '', $uri);

        // Unserialize response body
        $content = json_decode((string) $response->getBody(), true) ?: [];

        // Build expected resource
        $resource = $this->factory->create($uri, []);

        if ($resource instanceof Rest\Collection) {
            $content = [
                'data' => $content,
                '_metadata' => [
                    'uri' => $uri,
                    'limit' => (int) $response->getHeaderLine('Pagination-Limit'),
                    'offset' => (int) $response->getHeaderLine('Pagination-Offset'),
                    'total' => (int) $response->getHeaderLine('Pagination-Total'),
                ],
            ];
        } else {
            $content['_metadata'] = [
                'uri' => $uri,
            ];
        }

        $resource->populate($content);

        return $resource;
    }
1300354
public function write($file, $content, $type='sandbox')
	{
		$url = 'https://api-content.dropbox.com/1/files_put/';
		$result = $this->doOAuthCall($url,'PUT',null,$type,$file,$content);
		$result_body = json_decode($result['body'],true);
		if (!array_key_exists('error', $result_body)) {
			return $result_body;
		} else {
			trigger_error(sprintf(self::E_APIERROR, $result_body['error']));
			return false;
		}
	}
585661
protected function deserialize(ResponseInterface $response, $type, ContextInterface $context = null)
    {
        return $this->serializer->deserialize((string) $response->getBody(), $type, $this->format, $context);
    }