Creates a middleware that updates a command with the content and tree
hash headers for upload operations.

@return callable
@throws CouldNotCreateChecksumException if the body is not seekable.
344865
private function getChecksumsMiddleware()
    {
        return function (callable $handler) {
            return function (
                CommandInterface $command,
                RequestInterface $request = null
            ) use ($handler) {
                // Accept "ContentSHA256" with a lowercase "c" to match other Glacier params.
                if (!$command['ContentSHA256'] && $command['contentSHA256']) {
                    $command['ContentSHA256'] = $command['contentSHA256'];
                    unset($command['contentSHA256']);
                }

                // If uploading, then make sure checksums are added.
                $name = $command->getName();
                if (($name === 'UploadArchive' || $name === 'UploadMultipartPart')
                    && (!$command['checksum'] || !$command['ContentSHA256'])
                ) {
                    $body = $request->getBody();
                    if (!$body->isSeekable()) {
                        throw new CouldNotCreateChecksumException('sha256');
                    }

                    // Add a tree hash if not provided.
                    if (!$command['checksum']) {
                        $body = new HashingStream(
                            $body, new TreeHash(),
                            function ($result) use ($command, &$request) {
                                $request = $request->withHeader(
                                    'x-amz-sha256-tree-hash',
                                    bin2hex($result)
                                );
                            }
                        );
                    }

                    // Add a linear content hash if not provided.
                    if (!$command['ContentSHA256']) {
                        $body = new HashingStream(
                            $body, new PhpHash('sha256'),
                            function ($result) use ($command) {
                                $command['ContentSHA256'] = bin2hex($result);
                            }
                        );
                    }

                    // Read the stream in order to calculate the hashes.
                    while (!$body->eof()) {
                        $body->read(1048576);
                    }
                    $body->seek(0);
                }

                // Set the content hash header if a value is in the command.
                if ($command['ContentSHA256']) {
                    $request = $request->withHeader(
                        'x-amz-content-sha256',
                        $command['ContentSHA256']
                    );
                }

                return $handler($command, $request);
            };
        };
    }
457326
protected function createChunksFolderIfNeeded()
    {
        $path = $this->getChunkDirectory(true);

        // creates the chunks dir
        if (!file_exists($path)) {
            mkdir($path, 0777, true);
        }
    }
237553
final protected function CanCreateIn()
    {
        return $this->AllowChildren() && 
            BackendModule::Guard()->Allow(BackendAction::Create(), $this->content);
    }
860933
public function build(): SetExtraHTTPHeadersRequest
	{
		$instance = new SetExtraHTTPHeadersRequest();
		if ($this->headers === null) {
			throw new BuilderException('Property [headers] is required.');
		}
		$instance->headers = $this->headers;
		return $instance;
	}
1138912
function canCreate( )
    {
        if ( !isset( $this->Permissions["can_create"] ) )
        {
            $this->Permissions["can_create"] = $this->checkAccess( 'create' );
        }
        return ( $this->Permissions["can_create"] == 1 );
    }
789434
public function create()
	{
		try
		{
			$this->client->send(new Request($this->uri->withPath($this->uri->getPath().'resources')
				->withQuery(http_build_query([
					'path' => $this->getPath()
				], null, '&')), 'PUT'));
			$this->setContents([]);
		}
		catch (\Exception $exc)
		{
			throw $exc;
		}

		return $this;
	}
797873
private HttpRequest buildHttpRequest(boolean usingHead) throws IOException {
    Preconditions.checkArgument(uploader == null);
    Preconditions.checkArgument(!usingHead || requestMethod.equals(HttpMethods.GET));
    String requestMethodToUse = usingHead ? HttpMethods.HEAD : requestMethod;
    final HttpRequest httpRequest = getAbstractGoogleClient()
        .getRequestFactory().buildRequest(requestMethodToUse, buildHttpRequestUrl(), httpContent);
    new MethodOverride().intercept(httpRequest);
    httpRequest.setParser(getAbstractGoogleClient().getObjectParser());
    // custom methods may use POST with no content but require a Content-Length header
    if (httpContent == null && (requestMethod.equals(HttpMethods.POST)
        || requestMethod.equals(HttpMethods.PUT) || requestMethod.equals(HttpMethods.PATCH))) {
      httpRequest.setContent(new EmptyContent());
    }
    httpRequest.getHeaders().putAll(requestHeaders);
    if (!disableGZipContent) {
      httpRequest.setEncoding(new GZipEncoding());
    }
    final HttpResponseInterceptor responseInterceptor = httpRequest.getResponseInterceptor();
    httpRequest.setResponseInterceptor(new HttpResponseInterceptor() {

      public void interceptResponse(HttpResponse response) throws IOException {
        if (responseInterceptor != null) {
          responseInterceptor.interceptResponse(response);
        }
        if (!response.isSuccessStatusCode() && httpRequest.getThrowExceptionOnExecuteError()) {
          throw newExceptionOnError(response);
        }
      }
    });
    return httpRequest;
  }
593735
public function createRequest()
    {
        if ($this->request == null){
            $this->request = Request::fromPhpContext($this);
        }

        return $this->request;
    }
629844
public function actionFileUpload() {

		$source = $this->config->getCompatibleSource($this->request->source);

		$root = $source->getRoot();
		$path = $source->getPath();

		$this->accessControl->checkPermission($this->getUserRole(), $this->action, $path);

		$messages = [];

		$files = $this->move($source);

		$isImages = [];
		$files = array_map(function (File $file) use ($source, $root, &$isImages) {
			$messages[] = 'File ' . $file->getName() . ' was uploaded';
			$isImages[] = $file->isImage();
			return str_replace($root, '', $file->getPath());
		}, $files);

		if (!count($files)) {
			throw new \Exception('No files have been uploaded', Consts::ERROR_CODE_NO_FILES_UPLOADED);
		}

		return [
			'baseurl' => $source->baseurl,
			'messages' => $messages,
			'files' => $files,
			'isImages' => $isImages
		];
	}
1039714
public function upload()
    {
        try {
            $templatecontent = $this->getBase64Contents();
            $filename        = basename($this->getName());
        } catch ( FileExistException $ex ) {
            throw new FileExistException('Template file does not exist or is not readable' , $ex);
        }

        try {
            $this->getSoapClient()->UploadTemplate([
                'template' => $templatecontent ,
                'filename' => $filename ,
            ]);

            $remoteTemplate = new Remote($this->getSoapClient());
            $remoteTemplate->setName($this->getName());

            return $remoteTemplate;
        } catch ( SoapException $ex ) {
            throw new UploadException('Error while uploading the template' , $ex);
        }
    }
290732
protected function make()
  {
    if ( !$this->file && strpos($this->path,'http://') === 0 ){
      $d = getcwd();
      chdir(__DIR__);
      chdir('../tmp');
      $f = tempnam('.','image');
      try{
        $c = file_get_contents($this->path.$this->name);
        if ( file_put_contents($f, $c) ){
          if ( substr($this->name,-1) == '/' ){
            $this->name = substr($this->name,0,-1);
          }
          chmod($f, 0644);
          $this->file = $f;
          $this->path = getcwd();
        }
        else{
          $this->error = 'Impossible to get the file '.$this->path.$this->name;
        }
      }
      catch ( Error $e )
        { $this->error = 'Impossible to get the file '.$this->path.$this->name; }
      chdir($d);
    }
    return $this;
  }
1199176
public function create()
    {
        $type = NodeType::getByHandle('file');
        if (!is_object($type)) {
            NodeType::add('file');
        }
        $type = NodeType::getByHandle('file_folder');
        if (!is_object($type)) {
            NodeType::add('file_folder');
        }
        $type = NodeType::getByHandle('search_preset');
        if (!is_object($type)) {
            NodeType::add('search_preset');
        }
        $type = TreeType::getByHandle('file_manager');
        if (!is_object($type)) {
            TreeType::add('file_manager');
        }

        $manager = FileManager::get();
        if (!is_object($manager)) {
            $manager = FileManager::add();
        }

        return $manager;
    }
112717
public function create()
	{
		// Set some options
		switch ($this->source)
		{
			case 'image':
				$extensions = \Config::get('validImageTypes');
				$orderField = $this->virtualFieldName('orderSRC');
				$isGallery = true;
				$isDownloads = false;
				break;
				
			case 'video':
				$extensions = \Config::get('validVideoTypes');
				$orderField = false;
				$isGallery = false;
				$isDownloads = true;
				break;
				
			case 'audio':
				$extensions = \Config::get('validAudioTypes');
				$orderField = false;
				$isGallery = false;
				$isDownloads = true;
				break;
				
			case 'custom':
				$extensions = $this->customExtension;
				$orderField = $this->virtualFieldName('orderSRC');
				$isGallery = false;
				$isDownloads = ($this->canSelectFolder) ? true : false;
				break;
				
			default:
				$extensions = \Config::get('allowedDownload');
				$orderField = $this->virtualFieldName('orderSRC');
				$isGallery = false;
				$isDownloads = true;
				break;				
		}

		if ($this->multiSource)
		{

			// The multiSRC field
			$this->generateDCA('multiSRC', array
			(
				'inputType' =>	'fileTree',
				'label'		=>	array($this->label, $this->description),
				'eval'     	=> 	array
				(
					'multiple'		=>	true,				
					'fieldType'		=>	'checkbox', 
					'orderField'	=>	$orderField,
					'files'			=>	true,
					'filesOnly'		=>	!$this->canSelectFolder,
					'extensions' 	=>	$extensions,
					'isGallery'		=>	$isGallery,
					'isDownloads'	=>	$isDownloads,
					'mandatory'		=>	($this->mandatory) ? true : false, 
					'tl_class'		=>	'clr',
				),
				'load_callback'		=> (!$orderField) ?: array
				(
					array('tl_content_elements', 'prepareOrderValue'),
				),
				'save_callback'		=> (!$orderField) ?: array
				(
					array('tl_content_elements', 'saveOrderValue'),
				),
			));

			// The orderSRC field
			if ($orderField)
			{
				$this->generateDCA('orderSRC', array(), false, false);
			}
		}
		else
		{
			// the singleSRC field
			$this->generateDCA('singleSRC', array
			(
				'inputType' =>	'fileTree',
				'label'		=>	array($this->label, $this->description),
				'eval'     	=> 	array
				(
					'fieldType'		=>	'radio', 
					'files'			=>	true, 
					'extensions' 	=>	$extensions,
					'mandatory'		=>	($this->mandatory) ? true : false, 
					'tl_class'		=>	'clr',
				),
			));
			
		}
		
		// The size field
		if ($this->source == 'image' && $this->canChangeSize)
		{
			$this->generateDCA('size', array
			(
				'inputType'			=> 'imageSize',
				'label'				=> &$GLOBALS['TL_LANG']['tl_content']['size'],
				'options'			=> $this->getImageSizeList(),
				'default'			=> $this->size,
				'reference'			=> &$GLOBALS['TL_LANG']['MSC'],
				'eval' =>	array
				(
					'rgxp' =>' natural', 
					'includeBlankOption' => false, 
					'nospace' => true, 
					'tl_class' => 'w50',
				),
				'load_callback'	=>	array
				(
					array('tl_content_elements','defaultValue')
				),
			));	
		}

		// The sortBy field
		if ($this->multiSource && $this->canChangeSortBy)
		{
			$this->generateDCA('sortBy', array
			(
				'inputType'               => 'select',
				'label'                   => &$GLOBALS['TL_LANG']['tl_content']['sortBy'],
				'options'                 => array('custom', 'name_asc', 'name_desc', 'date_asc', 'date_desc', 'random'),
				'reference'               => &$GLOBALS['TL_LANG']['tl_content'],
				'eval'                    => array
				(
					'tl_class'=>'w50'
				),
			));		
		}
	}
512324
public static function enable()
    {
        Builder::macro(self::MACRO_METHOD, function (Builder $builder) {
            return new static($builder->getClassMetadata());
        });

        UploadableFile::enable();
    }
763940
public function createBucket()
    {
        $client = $this->getClientInstance();
        $client->createBucket(['Bucket' => $this->getBucket()]);

        return $this->isBucketAvailable();
    }
511816
public function upload()
    {
        $multipartStream = new Psr7\MultipartStream([
            [
                'name' => 'metadata',
                'headers' => ['Content-Type' => 'application/json; charset=UTF-8'],
                'contents' => $this->jsonEncode($this->metadata)
            ],
            [
                'name' => 'data',
                'headers' => ['Content-Type' => $this->contentType],
                'contents' => $this->data
            ]
        ], 'boundary');

        $headers = [
            'Content-Type' => 'multipart/related; boundary=boundary',
            'Content-Length' => $multipartStream->getSize()
        ];

        return $this->jsonDecode(
            $this->requestWrapper->send(
                new Request(
                    'POST',
                    $this->uri,
                    $headers,
                    $multipartStream
                ),
                $this->requestOptions
            )->getBody(),
            true
        );
    }
1081302
public function createHeader() {
    if ($this->router->isTestRun()) {
      return;
    }

    http_response_code($this->getStatusCode());
    if ($this->response === null) {
      // exception was raised
      // FIXME ensure that a response is always given initialized with at least the content type header
      header(Header::CONTENT_TYPE . ":" . $this->getContentType());
    } else {
      foreach ($this->response->getHeaders() as $header => $value) {
        header($header . ":" . $value);
      }
    }
  }