Validate upload image.

@param UploadedFile $uploadedImage
@param array $config

@return array
185274
private function validateUploadImage(UploadedFile $uploadedImage, array $config)
    {
        $errors = array();

        foreach ($this->validator->validateValue($uploadedImage, $this->getConstraint($config)) as $error) {
            $errors[] = $error->getMessage();
        }

        return $errors;
    }
821922
public function validatesUploadedFile($validate = null)
    {
        if (func_num_args() === 0)
        {
            return $this->validatesUploadedFile;
        }

        return $this->validatesUploadedFile = (bool)$validate;
    }
430369
protected function validate(UploadFile $file)
    {
        /* Validate extension */
        if (is_array($this->allowedExtensions) && count($this->allowedExtensions)) {
            if ( ! in_array('.' . $file->getExtension(), $this->allowedExtensions)) {
                $this->errors[] = language()->getLine(
                    'UPLOADER_E_ALLOWED_EXTENSIONS',
                    [implode(',', $this->allowedExtensions), $file->getExtension()]
                );
            }
        }

        /* Validate mime */
        if (is_array($this->allowedMimes) && count($this->allowedExtensions)) {
            if ( ! in_array($file->getFileMime(), $this->allowedMimes)) {
                $this->errors[] = language()->getLine(
                    'UPLOADER_E_ALLOWED_MIMES',
                    [implode(',', $this->allowedMimes), $file->getFileMime()]
                );
            }
        }

        /* Validate min size */
        if ($this->allowedFileSize[ 'min' ] > 0) {
            if ($file->getSize() < $this->allowedFileSize[ 'min' ]) {
                $this->errors[] = language()->getLine(
                    'UPLOADER_E_ALLOWED_MIN_FILESIZE',
                    [$this->allowedFileSize[ 'min' ], $file->getSize()]
                );
            }
        }

        /* Validate max size */
        if ($this->allowedFileSize[ 'min' ] > 0) {
            if ($file->getSize() > $this->allowedFileSize[ 'max' ]) {
                $this->errors[] = language()->getLine(
                    'UPLOADER_E_ALLOWED_MAX_FILESIZE',
                    [$this->allowedFileSize[ 'max' ], $file->getSize()]
                );
            }
        }

        if (count($this->errors) == 0) {
            return true;
        }

        return false;
    }
417920
public function validateUpload()
    {
        \Message::reset();
        $strTempName = $this->strName . '_fineuploader';
        $objUploader = new \Haste\Util\FileUpload($this->strName);
        $blnIsChunk = isset($_POST['qqpartindex']);

        // Convert the $_FILES array to Contao format
        if (!empty($_FILES[$strTempName])) {
            $arrFile = array
            (
                'name' => array($_FILES[$strTempName]['name']),
                'type' => array($_FILES[$strTempName]['type']),
                'tmp_name' => array($_FILES[$strTempName]['tmp_name']),
                'error' => array($_FILES[$strTempName]['error']),
                'size' => array($_FILES[$strTempName]['size']),
            );

            // Replace the comma character (#22)
            $arrFile['name'] = str_replace(',', '_', $arrFile['name']);

            // Set the UUID as the filename
            if ($blnIsChunk) {
                $arrFile['name'][0] = \Input::post('qquuid') . '.chunk';
            }

            // Check if the file exists
            if (file_exists(TL_ROOT . '/' . $this->strTemporaryPath . '/' . $arrFile['name'][0])) {
                $arrFile['name'][0] = $this->getFileName($arrFile['name'][0], $this->strTemporaryPath);
            }

            $_FILES[$this->strName] = $arrFile;
            unset($_FILES[$strTempName]); // Unset the temporary file
        }

        $varInput = '';

        // Add the "chunk" extension to upload types
        if ($blnIsChunk) {
            $extensions   = trimsplit(',', $GLOBALS['TL_CONFIG']['uploadTypes']);
            $extensions[] = 'chunk';

            $objUploader->setExtensions($extensions);
        }

        // Validate the minlength
        if ($this->arrConfiguration['minlength'] > 0 && !$blnIsChunk) {
            $objUploader->setMinFileSize($this->arrConfiguration['minlength']);
        }

        // Validate the maxlength
        if ($this->arrConfiguration['maxlength'] > 0 || $blnIsChunk) {
            $objUploader->setMaxFileSize($blnIsChunk ? $this->arrConfiguration['chunkSize'] : $this->arrConfiguration['maxlength']);
        }

        // Set the maximum width
        if ($this->arrConfiguration['maxWidth']) {
            $objUploader->setImageWidth($this->arrConfiguration['maxWidth']);
        }

        // Set the maximum height
        if ($this->arrConfiguration['maxHeight']) {
            $objUploader->setImageHeight($this->arrConfiguration['maxHeight']);
        }

        try {
            $varInput = $objUploader->uploadTo($this->strTemporaryPath);

            if ($objUploader->hasError()) {
                if (version_compare(VERSION, '4.2', '>=')) {
                    $session = \System::getContainer()->get('session');

                    foreach ($session->getFlashBag()->peek('contao.'.TL_MODE.'.error') as $strError) {
                        $this->addError($strError);
                    }
                } else {
                    foreach ((array) $_SESSION['TL_ERROR'] as $strError) {
                        $this->addError($strError);
                    }
                }
            }

            \Message::reset();
        } catch (\Exception $e) {
            $this->addError($e->getMessage());
        }

        if (!is_array($varInput) || empty($varInput)) {
            $this->addError($GLOBALS['TL_LANG']['MSC']['fineuploader_error']);
        }

        $varInput = $varInput[0];

        // Store the chunk in the session for further merge
        if ($blnIsChunk) {
            $_SESSION[$this->strName . '_FINEUPLOADER_CHUNKS'][\Input::post('qqfilename')][] = $varInput;

            // This is the last chunking request, merge the chunks and create the final file
            if (\Input::post('qqpartindex') == \Input::post('qqtotalparts') - 1) {
                $strFileName = \Input::post('qqfilename');

                // Get the new file name
                if (file_exists(TL_ROOT . '/' . $this->strTemporaryPath . '/' . $strFileName)) {
                    $strFileName = $this->getFileName($strFileName, $this->strTemporaryPath);
                }

                $objFile = new \File($this->strTemporaryPath . '/' . $strFileName);

                // Merge the chunks
                foreach ($_SESSION[$this->strName . '_FINEUPLOADER_CHUNKS'][\Input::post('qqfilename')] as $strChunk) {
                    $objFile->append(file_get_contents(TL_ROOT . '/' . $strChunk), '');

                    // Delete the file
                    \Files::getInstance()->delete($strChunk);
                }

                $objFile->close();
                $varInput = $objFile->path;

                // Validate the minlength
                if ($this->arrConfiguration['minlength'] > 0 && $objFile->size < $this->arrConfiguration['minlength']) {
                    $readableSize = \System::getReadableSize($this->arrConfiguration['minlength']);
                    $this->addError(sprintf($GLOBALS['TL_LANG']['ERR']['minFileSize'], $readableSize));
                    \System::log('File "'.$objFile->name.'" is smaller than the minimum file size of '.$readableSize, __METHOD__, TL_ERROR);
                }

                // Validate the maxlength
                if ($this->arrConfiguration['maxlength'] > 0 && $objFile->size > $this->arrConfiguration['maxlength']) {
                    $readableSize = \System::getReadableSize($this->arrConfiguration['maxlength']);
                    $this->addError(sprintf($GLOBALS['TL_LANG']['ERR']['maxFileSize'], $readableSize));
                    \System::log('File "'.$objFile->name.'" exceeds the maximum file size of '.$readableSize, __METHOD__, TL_ERROR);
                }

                // Reset the chunk flag
                $blnIsChunk = false;

                // Unset the file session after merging the chunks
                unset($_SESSION[$this->strName . '_FINEUPLOADER_CHUNKS'][\Input::post('qqfilename')]);
            }
        }

        // Validate and move the file immediately
        if ($this->arrConfiguration['directUpload'] && !$blnIsChunk) {
            $varInput = $this->validatorSingle($varInput, $this->getDestinationFolder());
        }

        return $varInput;
    }
44464
private function getUploadedOriginalFileProperties(UploadedFile $uploadedFile)
    {
        $this->results['original_filename'] = $uploadedFile->getClientOriginalName();
        $this->results['original_filepath'] = $this->getRelativePath($uploadedFile->getRealPath());
        $this->results['original_filedir'] = $uploadedFile->getRealPath();
        $this->results['original_extension'] = $uploadedFile->getClientOriginalExtension();
        $this->results['original_filesize'] = (int) $uploadedFile->getSize();
        $this->results['original_mime'] = $uploadedFile->getMimeType();

        return $this;
    }
1281863
private function prepareUploadConfig(Config $config)
    {
        $options = [];

        if (isset($this->config['encrypt']) && $this->config['encrypt']) {
            $options['params']['ServerSideEncryption'] = 'AES256';
        }

        if ($config->has('params')) {
            $options['params'] = $config->get('params');
        }

        if ($config->has('visibility')) {
            $options['params']['ACL'] = $this->normalizeVisibility($config->get('visibility'));
        }

        return $options;
    }
454758
protected function validateUploadImages($entity)
    {
        $files = $this->request->file('files');

        if (empty($files['name'][0])) {
            return null;
        }

        $directory = $this->config->get("{$entity}_image_dirname", $entity);
        $results = $this->file_transfer->uploadMultiple($files, 'image', "image/upload/$directory");

        foreach ($results['transferred'] as $key => $path) {
            $this->setSubmitted("images.$key.path", $path);
        }

        if (!empty($results['errors'])) {
            $this->setError('images', implode('<br>', (array) $results['errors']));
            return false;
        }

        return true;
    }
192384
public static function process($config = array())
	{
		foreach (static::$upload->getAllFiles() as $file)
		{
			$file->setConfig($config);
			$file->validate();
		}
	}
346851
protected function imageUpload($field, UploadedFile $file)
    {
        if (UPLOAD_ERR_OK == $file->getError()) {
            $asserts = $this->getAsserts()[$field];

            foreach ($asserts as $assert) {
                // Detect image size constraints and resize accordingly
                if ($assert instanceof Image) {
                    $path = $file->getPathname();
                    $pathWithExtension = $path.'.'.$file->guessExtension();
                    rename($path, $pathWithExtension);

                    // ImageWorkshop relies on the file's extension for encoding
                    try {
                        $this->resize($pathWithExtension, $assert->maxWidth, $assert->maxHeight);
                    } catch (ImageWorkshopException $e) {
                    }

                    rename($pathWithExtension, $path);
                }
            }
        }
    }
836875
public static function upload($file_name, $saved_file_path, $uploaded_file_type_limit = null, $uploaded_file_size_limit = null, $uploaded_file_ext_limit = null)
    {
        $storage = new \Upload\Storage\FileSystem($saved_file_path);
        $file = new \Upload\File($file_name, $storage);

        // Optionally you can rename the file on upload
        /**
 * @var IdGenerator $idGenerator 
*/
        $idGenerator = IdGenerator::component();
        $new_filename = $idGenerator->generate();
        $file->setName($new_filename);

        // Validate file upload
        // MimeType List => http://www.iana.org/assignments/media-types/media-types.xhtml
        $validations = [];
        if ($uploaded_file_type_limit) {
            //You can also add multi mimetype validation
            $validations[] = new \Upload\Validation\Mimetype($uploaded_file_type_limit);
        }
        if ($uploaded_file_size_limit) {
            // Ensure file is no larger than 5M (use "B", "K", M", or "G")
            $validations[] = new \Upload\Validation\Size($uploaded_file_size_limit);
        }
        if ($uploaded_file_ext_limit) {
            $validations[] = new \Upload\Validation\Extension($uploaded_file_ext_limit);
        }
        if ($validations) {
            $file->addValidations($validations);
        }

        // Access data about the file that has been uploaded
        $data = array(
            'name'       => $file->getNameWithExtension(),
            'extension'  => $file->getExtension(),
            'mime'       => $file->getMimetype(),
            'size'       => $file->getSize(),
            'md5'        => $file->getMd5(),
            'dimensions' => $file->getDimensions()
        );

        // Try to upload file
        try {
            // Success!
            $file->upload();
            return ['result' => 'success', 'new_name' => $new_filename, 'data' => $data];
        } catch (\Throwable $e) {
            // Fail!
            $errors = $file->getErrors();
            return ['result' => 'failed', 'errors' => $errors];
        }
    }
1213518
protected function prepareUploadData(UploadedFile $uploadedFile)
    {
        return [
            'extension' => $uploadedFile->getClientOriginalExtension(),
            'mimetype'  => $uploadedFile->getMimeType(),
            'size'      => $uploadedFile->getSize(),
            'name'      => $uploadedFile->getClientOriginalName(),
        ];
    }
888853
private function moveAndCreatePhoto(
        UploadedFile $file,
        $size = ['l' => [1000, 1000], 's' => [300, 300]]
    ) {
        $extension = '.' . $file->extension();

        $name = token();
        $filename = $name . $extension;

        $path = upload_path_images();
        $imageTmp = Image::make($file->getRealPath());

        if (!$imageTmp) {
            return false;
        }

        $largeSize = $size['l'];
        $thumbSize = $size['s'];

        // save original
        $imageTmp->save($path . $name . ImageThumb::$originalAppend . $extension);

        // if width is the biggest - resize on max width
        if ($imageTmp->width() > $imageTmp->height()) {
            // resize the image to the large height and constrain aspect ratio (auto width)
            $imageTmp->resize(null, $largeSize[1], function ($constraint) {
                $constraint->aspectRatio();
            })->save($path . $filename);

            // resize the image to the thumb height and constrain aspect ratio (auto width)
            $imageTmp->resize(null, $thumbSize[1], function ($constraint) {
                $constraint->aspectRatio();
            })->save($path . $name . ImageThumb::$thumbAppend . $extension);
        }
        else {
            // resize the image to the large width and constrain aspect ratio (auto height)
            $imageTmp->resize($largeSize[0], null, function ($constraint) {
                $constraint->aspectRatio();
            })->save($path . $filename);

            // resize the image to the thumb width and constrain aspect ratio (auto width)
            $imageTmp->resize($thumbSize[0], null, function ($constraint) {
                $constraint->aspectRatio();
            })->save($path . $name . ImageThumb::$thumbAppend . $extension);
        }

        return $filename;
    }
35362
public static function uploadImage(UploadedFile $uploadedFile, $context, $storage = 'local', $fileName = null)
    {
        $file = Facades\File::get($uploadedFile);
        /** @var Processor $processor */
        $processor = app('icr.processor');
        return $processor->upload(
            $context,
            $file,
            $uploadedFile->getClientOriginalExtension(),
            Facades\Storage::disk($storage),
            $fileName
        );
    }
599710
protected function validate_uploaded_file($data, $errors) {
        global $CFG;

        if (empty($data['questionfile'])) {
            $errors['questionfile'] = get_string('required');
            return $errors;
        }

        $files = $this->get_draft_files('questionfile');
        if (count($files) < 1) {
            $errors['questionfile'] = get_string('required');
            return $errors;
        }

        $formatfile = $CFG->dirroot.'/question/format/'.$data['format'].'/format.php';
        if (!is_readable($formatfile)) {
            throw new moodle_exception('formatnotfound', 'lesson', '', $data['format']);
        }

        require_once($formatfile);

        $classname = 'qformat_' . $data['format'];
        $qformat = new $classname();

        return $errors;
    }
192801
public function upload($uploadedFile)
    {
        if ($uploadedFile->isValid()) {
            $this->getFilesystem()->putFileAs(
                dirname($this->getPath()),
                $uploadedFile,
                $this->getName()
            );

            return true;
        } else {
            $this->errors['upload'] = $uploadedFile->getErrorMessage();
        }

        return false;
    }
622878
private function buildData($uploadedFile, $data, $user)
    {
        if (!($uploadedFile instanceof UploadedFile)) {
            throw new InvalidFileException('Given uploaded file is not of instance UploadedFile');
        }

        $this->validator->validate($uploadedFile);

        $data['storageOptions'] = $this->storage->save(
            $uploadedFile->getPathname(),
            $this->getNormalizedFileName($uploadedFile->getClientOriginalName())
        );

        $data['name'] = $uploadedFile->getClientOriginalName();
        $data['size'] = $uploadedFile->getSize();
        $data['mimeType'] = $uploadedFile->getMimeType();
        $data['properties'] = $this->getProperties($uploadedFile);
        $data['type'] = [
            'id' => $this->typeManager->getMediaType($uploadedFile->getMimeType()),
        ];

        return $this->createMedia($data, $user);
    }
1246962
public function process(File &$file, UploadedFile &$upload)
    {
        $mimeType = $upload->getClientMimeType();
        if ($mimeType == 'image/jpeg' || $mimeType == 'image/png') {
            $image = (new ImageManager())->make($upload->getRealPath());

            if ($this->settings->get('mustResize')) {
                $this->resize($image);
            }

            if ($this->settings->get('addsWatermarks')) {
                $this->watermark($image);
            }

            @file_put_contents(
                $upload->getRealPath(),
                $image->encode($upload->getClientMimeType())
            );
        }
    }