File upload callback
Resizes the image according to validation constraints

@param string                                             $field Field name
@param Symfony\Component\HttpFoundation\File\UploadedFile $file  File to process

@return void
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);
                }
            }
        }
    }
1015881
protected function prepareForeach(UploadedFile $file = null)
    {
        $self       = clone $this;
        $self->name = $self->getStoreName($file);

        return tap($self->upload($file), function () use ($self) {
            $self->name = null;
        });
    }
1348543
public function saveFile(UploadedFile $file)
    {
        Validator::validate(
            [$this->getName() => $file],
            $this->getUploadValidationRules(),
            $this->getUploadValidationMessages(),
            $this->getUploadValidationTitles()
        );

        $path = $file->storeAs(
            $this->getUploadPath($file),
            $this->getUploadFileName($file),
            $this->getDisk()
        );

        return $this->getFileInfo($path);
    }
884793
protected function handleFile($field, $options)
    {
        $file = $this->form->data($field);

        if (!is_array($file) || !isset($file['error']) || intval($file['error']) !== UPLOAD_ERR_OK) {
            // If this is an array, kirby-form already recognized and validated the
            // uploaded file. If the file is required, this should have been checked
            // during validation.
            return;
        }

        if (!array_key_exists('target', $options)) {
            // No translation because this is a developer error.
            $this->fail("The target directory is missing for field {$field}.");
        }

        $target = $options['target'];

        if (!is_dir($target)) {
            if (@mkdir($target, 0755)) {
                $this->createdDirectories[] = $target;
            } else {
                $this->fail(I18n::translate('uniform-upload-mkdir-fail'), $field);
            }
        }

        $name = $file['name'];
        $prefix = A::get($options, 'prefix');

        if (is_null($prefix)) {
            $name = $this->getRandomPrefix($name);
        } elseif ($prefix !== false) {
            $name = $prefix.$name;
        }

        $path = $target.DIRECTORY_SEPARATOR.$name;
        if (is_file($path)) {
            $this->fail(I18n::translate('uniform-upload-exists'), $field);
        }

        $success = $this->moveFile($file['tmp_name'], $path);

        if ($success) {
            $this->createdFiles[] = $path;
        } else {
            $this->fail(I18n::translate('uniform-upload-failed'), $field);
        }
    }
124798
public function upload($file, $key)
    {
        if (! $file || ! $this->isValidKey($key))
            return;

        $fileName = $file->getClientOriginalName();
        $pathinfo = pathinfo($fileName);

        $this->deleteStored($key);

        Storage::putFileAs($this->getStoragePath(), $file, $key . '.' . $pathinfo['extension']);
    }
665896
protected function updateFormField($field)
    {
        parent::updateFormField($field);

        if ($this->MinValue) {
            $field->setAttribute('data-rule-min', $this->MinValue);
        }

        if ($this->MaxValue) {
            $field->setAttribute('data-rule-max', $this->MaxValue);
        }
    }
341081
private function setByTypeFileField(CsvField $field) : void
    {
        if (! in_array($field->getType(), ['files', 'images'])) {
            return;
        }

        $this->setAssociation(
            'hasMany',
            static::generateAssociationName(FileUpload::FILE_STORAGE_TABLE_NAME, $field->getName()),
            [
                'className' => FileUpload::FILE_STORAGE_TABLE_NAME,
                'foreignKey' => 'foreign_key',
                'conditions' => ['model' => $this->getTable(), 'model_field' => $field->getName()]
            ]
        );
    }
270050
private function validateExtension(UploadedFile $uploadedFile) {
        $pathInfo = pathinfo($uploadedFile->getName());
        if(!isset($pathInfo['extension'])) {
            throw new Exception('No Extension Found(' . $uploadedFile->getName() . ')', 401);
        }
        $extension = strtolower($pathInfo['extension']);
        if(!in_array($extension, $this->getAllowedExtensions())) {
            throw new Exception('Invalid Type of File Uploaded, valid types: ' . implode(', ', $this->getAllowedExtensions()), 401);
        }
    }
109963
private function validateError(UploadedFile $uploadedFile) {
        switch($uploadedFile->getError()) {
            case UPLOAD_ERR_OK:
                //Do Nothing
                break;
            case UPLOAD_ERR_INI_SIZE:
                throw new Exception('File too large, must not be greater than ' . ini_get('upload_max_filesize'), 401);
                break;
            case UPLOAD_ERR_NO_FILE:
                throw new Exception('No File Uploaded', 401);
                break;
            default:
                throw new Exception($uploadedFile->getError(), 401);
                break;
        }
    }
552999
public function process($field = null)
    {
        $uploadFiles = input()->files($field);

        if ( ! is_array($uploadFiles)) {
            $uploadFiles = [$uploadFiles];
        }

        if (count($uploadFiles)) {
            foreach ($uploadFiles as $file) {
                if ($file instanceof UploadFile) {
                    if (defined('PATH_STORAGE')) {
                        if ($this->path === PATH_STORAGE) {
                            if (strpos($file->getClientMediaType(), 'image') !== false) {
                                $this->path = $this->path . 'images' . DIRECTORY_SEPARATOR;
                            } else {
                                $this->path = $this->path . 'files' . DIRECTORY_SEPARATOR;
                            }
                        }
                    }

                    $targetPath = $this->path;

                    if (empty($this->targetFilename)) {
                        $this->setTargetFilename($file->getClientFilename());
                    }

                    $filename = $this->targetFilename;

                    if ($this->validate($file)) {
                        if ( ! is_file($filePath = $targetPath . $filename . '.' . $file->getExtension())) {
                            $this->move($file, $filePath);
                        } elseif ( ! is_file($filePath = $targetPath . $filename . '-1' . '.' . $file->getExtension())) {
                            $this->move($file, $filePath);
                        } else {
                            $existingFiles = glob($targetPath . $filename . '*.' . $file->getExtension());
                            if (count($existingFiles)) {
                                $increment = count($existingFiles) - 1;
                            }

                            foreach (range($increment + 1, $increment + 3, 1) as $increment) {
                                if ($increment > $this->maxIncrementFilename) {
                                    $this->errors[] = language()->getLine(
                                        'UPLOADER_E_MAXIMUM_INCREMENT_FILENAME',
                                        [$file->getClientFilename()]
                                    );
                                }

                                if ( ! is_file($filePath = $targetPath . $filename . '-' . $increment . '.' . $file->getExtension())) {
                                    $this->move($file, $filePath);
                                    break;
                                }
                            }
                        }
                    }
                }
            }

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

        return false;
    }
611596
function processFile($token, $file)
	{
		// Why not in one condition?
		// @see http://forum.nettephp.com/cs/viewtopic.php?pid=29556#p29556
		if (!$file instanceof FileUpload) {
			return false;
		}

		/* @var $validateCallback Callback */
		$validateCallback = MultipleFileUpload::$validateFileCallback;

		/* @var $isValid bool */
		$isValid = $validateCallback->invoke($file);

		if ($isValid) {
			MultipleFileUpload::getQueuesModel()
				->getQueue($token)
				->addFile($file);
		}
		return $isValid;
	}
1327651
public function uploadedFile(
        $file,
        $clientFilename = null,
        $clientMediaType = null,
        $size = null,
        $error = UPLOAD_ERR_OK
    ) {
        return new Messages\UploadedFile\Implementation(
            $this,
            $file,
            $clientFilename,
            $clientMediaType,
            $size,
            $error
        );
    }
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())
            );
        }
    }
157812
public function createUploadedFile(
        $file,
        $size = null,
        $error = \UPLOAD_ERR_OK,
        $clientFilename = null,
        $clientMediaType = null
    )
    {
        if ($size === null)
        {
            if (\is_string($file))
            {
                $size = (int)filesize($file);
            }
            else
            {
                $stats = \fstat($file);
                $size  = $stats['size'];
            }
        }

        return new UploadedFile($file, $size, $error, $clientFilename, $clientMediaType);
    }
1056402
public function setFile(UploadedFile $file)
    {
        $this->file = $file;
        $this->name = $file->name;

        if ($this->unique === true && $file->extension) {
            $this->setUriName(uniqid() . '.' . $file->extension);
        } else {
            $this->setUriName($this->name);
        }

        if (file_exists($this->filePath)) {
            $this->setUriName($file->baseName . uniqid() . '.' . $file->extension);
        }

        $this->mime = FileHelper::getMimeTypeByExtension($this->name);
        $this->size = $file->size;

        return $this;
    }
1019637
public static function createFromUploadedFile(UploadedFile $file = null)
    {
        if (!$file instanceof UploadedFile) {
            return;
        }

        $instance = new static();

        self::$generic_file->moveUploadedFile(new File($file,
            $file->getClientOriginalName()), null, $instance);

        return $instance;
    }
873399
private function scaleUploadedImage($file)
    {
        $backend = $file->getImageBackend();

        // temporary location for image manipulation
        $tmp_image = TEMP_FOLDER . '/resampled-' . mt_rand(100000, 999999) . '.' . $file->getExtension();

        $tmp_contents = $file->getString();

        // write to tmp file
        @file_put_contents($tmp_image, $tmp_contents);

        $backend->loadFrom($tmp_image);

        if ($backend->getImageResource()) {
            $modified = false;

            // clone original
            $transformed = $backend;

            /* If rotation allowed & JPG, test to see if orientation needs switching */
            if ($this->config_auto_rotate && preg_match('/jpe?g/i', $file->getExtension())) {
                $switch_orientation = $this->exifRotation($tmp_image);
                if ($switch_orientation) {
                    $modified = true;
                    $transformed->setImageResource($transformed->getImageResource()->orientate());
                }
            }

            // resize to max values
            if ($transformed &&
                (
                    ($this->config_max_width && $transformed->getWidth() > $this->config_max_width) ||
                    ($this->config_max_height && $transformed->getHeight() > $this->config_max_height)
                )
            ) {
                if ($this->config_max_width && $this->config_max_height) {
                    $transformed = $transformed->resizeRatio($this->config_max_width, $this->config_max_height);
                } elseif ($this->config_max_width) {
                    $transformed = $transformed->resizeByWidth($this->config_max_width);
                } else {
                    $transformed = $transformed->resizeByHeight($this->config_max_height);
                }
                $modified = true;
            } elseif ($transformed && $this->config_force_resampling) {
                $modified = true;
            }

            // write to tmp file and then overwrite original
            if ($transformed && $modified) {
                $transformed->writeTo($tmp_image);
                // if !legacy_filenames then delete original, else rogue copies are left on filesystem
                if (!Config::inst()->get(FlysystemAssetStore::class, 'legacy_filenames')) {
                    $file->File->deleteFile();
                }
                $file->setFromLocalFile($tmp_image, $file->FileName); // set new image
                $file->write();
            }
        }

        @unlink($tmp_image); // delete tmp file
    }