@param string|resource $file
@param integer $size
@param integer $error
@param string $clientFilename
@param string $clientMediaType

@return UploadedFileInterface
775468
public static function createUploadedFile(
        $file,
        $size = null,
        $error = UPLOAD_ERR_OK,
        $clientFilename = null,
        $clientMediaType = null
    ) {
        if (! static::$uploadedFileFactory) {
            static::$uploadedFileFactory = new UploadedFileFactory();
        }

        return static::$uploadedFileFactory->createUploadedFile(
            $file,
            $size,
            $error,
            $clientFilename,
            $clientMediaType
        );
    }
459086
public function processPhpFile($event, $request, $response, $file)
    {
        if(!$this->php_engine){
            $response->statusCode = 403;
            $response->body = "php engine disabled";
            return ;
        }
        
        if(!$response->headers->has('Content-type')) {
            if($response->charset === null && $this->default_charset){
                $response->charset = $this->default_charset;
            }
            
            $response->mimeType = $this->default_content_type;
        }
        
        $_POST = $request->_POST;
        $_GET = $request->_GET;
        $_FILES = $request->_FILES;
        $_COOKIE = $request->_COOKIE;
        $_SERVER = $request->_SERVER;
        
        ob_start();        
        include $file;
        
        if($response->gzip && $request->gzipSupport()){
            $response->headers->set('Content-Encoding', 'gzip');
            $response->body = gzencode(ob_get_clean());
        }else{
            $response->body = ob_get_clean();
        }
        
        return ;
    }
549386
public static function error($number, $string, $file, $line)
    {
        throw new \ErrorException($string, 0, $number, $file, $line);
    }
319655
protected function validateFile($file, FormEvent $event)
    {
        if ($file instanceof File) {

            $isValidFile  = true;

            //check if the file is allowed by the MIME-types constraint given
            if (!empty($this->allowedFileTypes) && null !== $mime = $file->getMimeType()) {
                if (!in_array($mime, $this->allowedFileTypes)) {
                    $isValidFile = false;
                    $message = $this->translator->trans(
                        'zicht_filemanager.wrong_type',
                        array(
                            '%this_type%'     => $mime,
                            '%allowed_types%' => implode(', ', $this->allowedFileTypes)
                        ),
                        $event->getForm()->getConfig()->getOption('translation_domain')
                    );

                    $event->getForm()->addError(new FormError($message));
                    /** Set back data to old so we don`t see new file */
                    $event->setData(array(FileType::UPLOAD_FIELDNAME => $event->getForm()->getData()));
                }
            }

            if ($isValidFile) {
                $purgatoryFileManager = $this->getPurgatoryFileManager();
                $entity = $event->getForm()->getParent()->getConfig()->getDataClass();

                $data = $event->getData();
                $replaceFile = isset($data[FileType::KEEP_PREVIOUS_FILENAME]) && $data[FileType::KEEP_PREVIOUS_FILENAME] === '1';
                $forceFilename = $replaceFile ? $event->getForm()->getData() : '';

                $path = $purgatoryFileManager->prepare($file, $entity, $this->field, true, $forceFilename);
                $purgatoryFileManager->save($file, $path);
                $this->prepareData($data, $path, $event->getForm()->getPropertyPath());
                $event->setData($data);
            }
        }
    }
710382
public function createForFormType($formType, array &$resources = [])
    {
        $resources[] = new FileResource(__FILE__);

        $form = $this->formFactory->create(FormUtil::formTypeToString($formType));

        $actualFormType = $form->getConfig()->getType()->getInnerType();
        $reflection = new \ReflectionObject($actualFormType);
        $resources[] = new FileResource($reflection->getFileName());

        $inputDefinition = new InputDefinition();

        foreach ($form->all() as $name => $field) {
            if (!$this->isFormFieldSupported($field)) {
                continue;
            }

            $type = InputOption::VALUE_REQUIRED;
            $default = $field->getConfig()->getOption('data', null);
            $description = FormUtil::label($field);

            $inputDefinition->addOption(new InputOption($name, null, $type, $description, $default));
        }

        return $inputDefinition;
    }
1350419
public function validateFile(Entity\File $file, $sourceFilePath = null)
	{
		if ( ! $file instanceof Entity\Image) {
			return;
		}

		if (is_null($sourceFilePath)) {
			return;
		}

		$info = new ImageInfo($sourceFilePath);
		if($info->hasError()) {
			throw new Exception\RuntimeException($info->getError());
		}

		// Assumes memory_limit is in MB
		// "-1" means no limit
		$memoryLimit = (int) ini_get('memory_limit');
		if ($memoryLimit < 0) {
			return;
		}
		
		$memoryLeft = (int) $memoryLimit * 1024 * 1024 - memory_get_usage(); // Should use real usage or not?
		// Read data from image info, default bitsPerChannel to 8, channel count to 4
		$memoryRequired = ($info->getWidth() * $info->getHeight() * ($info->getBits() ?: 8) * ($info->getChannels() ?: 4)) * 2;

		if ($memoryRequired > $memoryLeft) {
			$message = "Not enough memory [{$memoryLeft} bytes] to resize the image, required amount [{$memoryRequired} bytes]";

			throw new Exception\InsufficientSystemResources(self::EXCEPTION_MESSAGE_KEY, $message);
		}
	}
271380
public function validate(File $file, $typeName, $sourceFilePath = null)
	{
		$name = $file->getFileName();
		$fileNameHelper = new Helpers\FileNameValidationHelper();
		$result = $fileNameHelper->validate($name);
		
		if( ! $result) {
			$message = $fileNameHelper->getErrorMessage();
			
			throw new Exception\UploadFilterException(self::EXCEPTION_MESSAGE_KEY, $message);
		}
	}
161781
static function getUploadError($iErrorNumber)
    {
        //  Upload was aborted, I wonder why?
        switch ($iErrorNumber) {

            case UPLOAD_ERR_INI_SIZE:

                $iMaxFileSize = function_exists('ini_get') ? ini_get('upload_max_filesize') : null;

                if (!is_null($iMaxFileSize)) {

                    $iMaxFileSize = static::returnBytes($iMaxFileSize);
                    $iMaxFileSize = static::formatBytes($iMaxFileSize);
                    $sError       = sprintf(
                        'The file exceeds the maximum size accepted by this server (which is %s).',
                        $iMaxFileSize
                    );

                } else {
                    $sError = 'The file exceeds the maximum size accepted by this server.';
                }
                break;

            case UPLOAD_ERR_FORM_SIZE:
                $sError = 'The file exceeds the maximum size accepted by this server.';
                break;

            case UPLOAD_ERR_PARTIAL:
                $sError = 'The file was only partially uploaded.';
                break;

            case UPLOAD_ERR_NO_FILE:
                $sError = 'No file was uploaded.';
                break;

            case UPLOAD_ERR_NO_TMP_DIR:
                $sError = 'This server cannot accept uploads at this time.';
                break;

            case UPLOAD_ERR_CANT_WRITE:
                $sError = 'Failed to write uploaded file to disk, you can try again.';
                break;

            case UPLOAD_ERR_EXTENSION:
                $sError = 'The file failed to upload due to a server configuration.';
                break;

            default:
                $sError = 'The file failed to upload.';
                break;
        }

        return $sError;
    }
955010
public org.biouno.figshare.v1.model.File uploadFile(long articleId, File file) {
        HttpClient httpClient = null;
        try {
            final String method = String.format("my_data/articles/%d/files", articleId);
            // create an HTTP request to a protected resource
            final String url = getURL(endpoint, version, method);
            // create an HTTP request to a protected resource
            final HttpPut request = new HttpPut(url);

            MultipartEntityBuilder builder  = MultipartEntityBuilder.create();
            ContentBody body = new FileBody(file);
            FormBodyPart part = FormBodyPartBuilder.create("filedata", body).build();
            builder.addPart(part);

            HttpEntity entity = builder.build();
            request.setEntity(entity);

            // sign the request
            consumer.sign(request);

            // send the request
            httpClient = HttpClientBuilder.create().build();
            HttpResponse response = httpClient.execute(request);
            HttpEntity responseEntity = response.getEntity();
            String json = EntityUtils.toString(responseEntity);
            org.biouno.figshare.v1.model.File uploadedFile = readFileFromJson(json);
            return uploadedFile;
        } catch (OAuthCommunicationException e) {
            throw new FigShareClientException("Failed to get articles: " + e.getMessage(), e);
        } catch (OAuthMessageSignerException e) {
            throw new FigShareClientException("Failed to get articles: " + e.getMessage(), e);
        } catch (OAuthExpectationFailedException e) {
            throw new FigShareClientException("Failed to get articles: " + e.getMessage(), e);
        } catch (ClientProtocolException e) {
            throw new FigShareClientException("Failed to get articles: " + e.getMessage(), e);
        } catch (IOException e) {
            throw new FigShareClientException("Failed to get articles: " + e.getMessage(), e);
        }
    }
775695
public function changeType($bucket, $key, $fileType)
    {
        $resource = \Qiniu\entry($bucket, $key);
        $path = '/chtype/' . $resource . '/type/' . $fileType;
        list(, $error) = $this->rsPost($path);
        return $error;
    }
1138892
public function maxFileSize($size, $unit = "B")
	{
		$unit = strtoupper($unit);
		if(! is_numeric($size))
		{
			throw new Exception("Invalid file size: expects integer");
		}
		if($unit === "B" || preg_match("/^BYTE(S)?$/", $unit))
		{
			$this->maxFileSize = $size;
		}
		elseif($unit === "KB" || preg_match("/^KILOBYTE(S)?$/", $unit))
		{
			$this->maxFileSize = ($size * 1000);
		}
		elseif($unit === "MB" || preg_match("/^MEGABYTE(S)?$/", $unit))
		{
			$this->maxFileSize = ($size * 1000000);
		}
		else
		{
			throw new Exception("Invalid unit in setMaxFileSize: Expects 'B', 'KB' or 'MB'.");
		}
		if($this->maxFileSize > UploadedFile::getMaxFilesize())
		{
			throw new Exception("Max file size cannot exceed upload_max_filesize in php.ini");
		}

		return $this;
	}
39973
public function processCrop($size, $upload_path, $file, $sizeMeta) {
		$upload_info = wp_upload_dir();
		$subdir = trim(str_replace($upload_info['basedir'], '', $upload_path), '/');
		$upload_path = rtrim(str_replace($subdir, '', $upload_path), '/');

		if($this->client && $this->client->enabled()) {
			$sizeMeta = $this->processFile($upload_path, $subdir.'/'.$file, $sizeMeta);
		}

		return $sizeMeta;
	}
1056963
protected function publishFile($sourceStream, $relativeTargetPathAndFilename, ResourceMetaDataInterface $metaData)
    {
        $objectName = $this->keyPrefix . $relativeTargetPathAndFilename;
        $options = array(
            'params' => array(
                'ContentLength' => $metaData->getFileSize(),
                'ContentType' => $metaData->getMediaType()
            )
        );

        try {
            $this->s3Client->upload($this->bucketName, $objectName, $sourceStream, 'public-read', $options);
            $this->systemLogger->log(sprintf('Successfully published resource as object "%s" in bucket "%s" with MD5 hash "%s"', $objectName, $this->bucketName, $metaData->getMd5() ?: 'unknown'), LOG_DEBUG);
        } catch (\Exception $e) {
            $this->systemLogger->log(sprintf('Failed publishing resource as object "%s" in bucket "%s" with MD5 hash "%s": %s', $objectName, $this->bucketName, $metaData->getMd5() ?: 'unknown', $e->getMessage()), LOG_DEBUG);
            if (is_resource($sourceStream)) {
                fclose($sourceStream);
            }
            throw $e;
        }
    }
1142849
private function resize($file, $width = null, $height = null, $quality = 90)
    {
        if ($width || $height) {
            $finalWidth = $width;
            $finalHeight = $height;
            $crop = $width && $height;

            $iw = ImageWorkshop::initFromPath($file);

            if ($crop) {
                $originalRatio = $iw->getWidth() / $iw->getHeight();
                $finalRatio = $finalWidth / $finalHeight;

                if ($originalRatio > $finalRatio) {
                    $width = null;
                } else {
                    $height = null;
                }
            }

            $iw->resizeInPixel($width, $height, true, 0, 0, 'MM');
            $crop && $iw->cropInPixel($finalWidth, $finalHeight, 0, 0, 'MM');

            $iw->save(dirname($file), basename($file), false, null, $quality);
        }
    }
186409
protected function handleError($type, $message, $file, $line)
    {
        throw new ResourceException(sprintf(
            '%s: "%s" in %s on line %d',
            $type,
            $message,
            $file,
            $line
        ));
    }
798090
function insertHTTPFile( $object, $objectVersion, $objectLanguage,
                             $objectAttribute, $httpFile, $mimeData,
                             &$result )
    {
        $result = array( 'errors' => array(),
                         'require_storage' => false );
        $attributeID = $objectAttribute->attribute( 'id' );

        $media = eZMedia::fetch( $attributeID, $objectVersion );
        if ( $media === null )
            $media = eZMedia::create( $attributeID, $objectVersion );

        $httpFile->setMimeType( $mimeData['name'] );
        if ( !$httpFile->store( "original", false, false ) )
        {
            $result['errors'][] = array( 'description' => ezpI18n::tr( 'kernel/classes/datatypes/ezmedia',
                                                        'Failed to store media file %filename. Please contact the site administrator.', null,
                                                        array( '%filename' => $httpFile->attribute( "original_filename" ) ) ) );
            return false;
        }

        $classAttribute = $objectAttribute->contentClassAttribute();
        $player = $classAttribute->attribute( "data_text1" );
        $pluginPage = eZMediaType::pluginPage( $player );

        $media->setAttribute( "contentobject_attribute_id", $attributeID );
        $media->setAttribute( "version", $objectVersion );
        $media->setAttribute( "filename", basename( $httpFile->attribute( "filename" ) ) );
        $media->setAttribute( "original_filename", $httpFile->attribute( "original_filename" ) );
        $media->setAttribute( "mime_type", $mimeData['name'] );

        // Setting width and height to zero means that the browser/player must find the size itself.
        // In the future we will probably analyze the media file and find this information
        $width = $height = 0;
        // Quality is not known, so we don't set any
        $quality = false;
        // Not sure what this is for, set to false
        $controls = false;
        // We want to show controllers by default
        $hasController = true;
        // Don't play automatically
        $isAutoplay = false;
        // Don't loop movie
        $isLoop = false;

        $media->setAttribute( "width", $width );
        $media->setAttribute( "height", $height );
        $media->setAttribute( "quality", $quality );
        $media->setAttribute( "controls", $controls );
        $media->setAttribute( "pluginspage", $pluginPage );
        $media->setAttribute( "is_autoplay", $isAutoplay );
        $media->setAttribute( "has_controller", $hasController );
        $media->setAttribute( "is_loop", $isLoop );

        $filePath = $httpFile->attribute( 'filename' );
        $fileHandler = eZClusterFileHandler::instance();
        $fileHandler->fileStore( $filePath, 'mediafile', true, $mimeData['name'] );


        $media->store();

        $objectAttribute->setContent( $media );
        return true;
    }
592145
protected function _throw($file, $errorType)
    {
        $this->_value = $file['name'];
        switch($errorType) {
            case Zend_Validate_File_MimeType::FALSE_TYPE :
                $errorType = self::FALSE_TYPE;
                break;
            case Zend_Validate_File_MimeType::NOT_DETECTED :
                $errorType = self::NOT_DETECTED;
                break;
            case Zend_Validate_File_MimeType::NOT_READABLE :
                $errorType = self::NOT_READABLE;
                break;
        }

        $this->_error($errorType);
        return false;
    }