Validates file size
@param Entity\File $file
778160
public function validateFile(Entity\File $file, $sourceFilePath = null)
	{
		$size = $file->getSize();
		
		if ($size > $this->maxSize) {
			$message = 'File size is bigger than "' . $this->maxSize . '"';
			
			throw new Exception\UploadFilterException(self::EXCEPTION_MESSAGE_KEY, $message);
		}
	}
646936
protected function validateUpload(UploadedFileInterface $file): void
    {
        // Handle bad filenames.
        $filename = $file->getClientFilename();

        if (!Utils::checkFilename($filename)) {
            $grav = Grav::instance();
            throw new \RuntimeException(
                sprintf($grav['language']->translate('PLUGIN_FORM.FILEUPLOAD_UNABLE_TO_UPLOAD', null, true), $filename, 'Bad filename')
            );
        }
    }
125309
protected function recreateImageSizes(Image $file)
	{
		if ( ! $file instanceof Image) {
			throw new Exception\RuntimeException('Image entity expected');
		}

		$sizes = $file->getImageSizeCollection();
		if ( ! $sizes->isEmpty()) {
			foreach ($sizes as $size) {
				$sizeName = $size->getName();
				$filePath = $this->getImagePath($file, $sizeName);

				if (file_exists($filePath)) {
					
					$result = unlink($filePath);

					if ( ! $result) {
						throw new Exception\RuntimeException("Could not delete '$filePath' from file storage");
					}
				}

				$this->createResizedImage($file, $size->getTargetWidth(), $size->getTargetHeight(), $size->getCropMode(), $size->getQuality(), true);
			}
		}
	}
982880
public function setFile(\BiberLtd\Bundle\FileManagementBundle\Entity\File $file) {
        if($this->setModified('file', $file)->isModified()) {
            $this->file = $file;
        }

        return $this;
    }
424496
private function checkFile(string &$file): bool
    {
        $file = "{$this->directory}/{$file}";

        return file_exists($file) || (touch($file) && chmod($file, 0600));
    }
1292197
protected function validateCoversTagsNotEmpty(File $file, array $tags)
    {
        foreach ($tags as $index => $value) {
            if (empty($value)) {
                $file->addError(
                    'Covers tag must not be empty',
                    $index,
                    'CoversTagEmpty'
                );
            }
        }
    }
858510
private function verifyFileSize($size)
    {
        $max = $this->config['max_size'];
        if ($max > 0 && $size > $max) {
            throw FileSizeException::fileIsTooBig($size, $max);
        }

        return $size;
    }
1320124
protected function validate($file)
    {
        // Check if file is valid
        if ( ! $file->isValid()) {
            return false;
        }

        $inputFile = [$this->field => $file];
        $rules     = [$this->field => $this->validationRules];

        // Validate
        $validator = Validator::make($inputFile, $rules);
        if ($validator->fails()) {
            $this->errors = $validator;

            return false;
        }

        return true;
    }
23633
protected function validate(UploadFile $file)
    {
        if (parent::validate($file)) {

            $info = getimagesize($file->getFileTemp());
            $width = $info[ 0 ];
            $height = $info[ 1 ];

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

            /* Validate width max size */
            if ($this->allowedImageSize[ 'width' ][ 'max' ] > 0) {
                if ($width > $this->allowedImageSize[ 'width' ][ 'max' ]) {
                    $this->errors[] = language()->getLine(
                        'IMAGE_E_ALLOWED_MAX_WIDTH_SIZE',
                        [$this->allowedFileSize[ 'max' ], $width]
                    );
                }
            }

            /* Validate height min size */
            if ($this->allowedImageSize[ 'height' ][ 'min' ] > 0) {
                if ($height < $this->allowedImageSize[ 'width' ][ 'min' ]) {
                    $this->errors[] = language()->getLine(
                        'IMAGE_E_ALLOWED_MIN_HEIGHT_SIZE',
                        [$this->allowedFileSize[ 'min' ], $height]
                    );
                }
            }

            /* Validate height max size */
            if ($this->allowedImageSize[ 'height' ][ 'max' ] > 0) {
                if ($height > $this->allowedImageSize[ 'width' ][ 'max' ]) {
                    $this->errors[] = language()->getLine(
                        'IMAGE_E_ALLOWED_MAX_HEIGHT_SIZE',
                        [$this->allowedFileSize[ 'max' ], $height]
                    );
                }
            }
        }

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

        return false;
    }
247756
protected function _triggerErrors($file)
    {
        if (!empty($file['error'])) {
            switch ((int)$file['error']) {
                case UPLOAD_ERR_INI_SIZE:
                    $message = __('The uploaded file exceeds the upload_max_filesize directive in php.ini : {0}', ini_get('upload_max_filesize'));
                    break;

                case UPLOAD_ERR_FORM_SIZE:
                    $message = __('The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.');
                    break;

                case UPLOAD_ERR_NO_FILE:
                    $message = false;
                    break;

                case UPLOAD_ERR_PARTIAL:
                    $message = __('The uploaded file was only partially uploaded.');
                    break;

                case UPLOAD_ERR_NO_TMP_DIR:
                    $message = __('Missing a temporary folder.');
                    break;

                case UPLOAD_ERR_CANT_WRITE:
                    $message = __('Failed to write file to disk.');
                    break;

                case UPLOAD_ERR_EXTENSION:
                    $message = __('A PHP extension stopped the file upload.');
                    break;

                default:
                    $message = __('Unknown upload error.');
            }

            return $message;
        }
    }
1225663
public function validatePhpFile($file)
    {
        if (!$this->canValidatePhpCode()) {
            return null;
        }

        $output = shell_exec('php -l ' . escapeshellarg($file));

        $count = 0;
        $error = preg_replace('/Errors parsing.*$/', '', $output, -1, $count);
        return $count > 0 ? trim("$error") : true;
    }
140026
private function imageAndFileOutput(File $file, $localeId = null)
	{
		$request = $this->container->getRequest();
		$postInput = $request->isMethod('POST') ? $request->request : $request->query;
		$requestedSizes = $postInput->get('sizes', array());
		$requestedSizeNames = array();
		$isBroken = false;
		$thumbSize = null;
		$previewSize = null;

		try {
			if ($file instanceof Image && $this->getFileStorage()->fileExists($file)) {

				$thumbSize = $this->getFileStorage()->createResizedImage($file, 30, 30, true);
				$previewSize = $this->getFileStorage()->createResizedImage($file, 200, 200);

				foreach ($requestedSizes as $size) {
					$width = filter_var($size['width'], FILTER_VALIDATE_INT);
					$height = filter_var($size['height'], FILTER_VALIDATE_INT);
					$crop = filter_var($size['crop'], FILTER_VALIDATE_BOOLEAN);

					$requestedSizeNames[] = $this->getFileStorage()->createResizedImage($file, $width, $height, $crop);
				}
			}
		} catch (\Exception $e) {
			$isBroken = true;
		}

		$output = $this->getFileStorage()->getFileInfo($file, $localeId);

		// Return only requested sizes
		if ( ! empty($requestedSizeNames)) {
			foreach ($output['sizes'] as $sizeName => $size) {

				if ($sizeName == 'original') {
					continue;
				}

				if ( ! in_array($sizeName, $requestedSizeNames, true)) {
					unset($output['sizes'][$sizeName]);
				}
			}
		}

		// Create thumbnail&preview
		try {
			if ($file instanceof Image && $this->getFileStorage()->fileExists($file)) {
				if ($file->isPublic()) {
					$output['preview'] = $this->getFileStorage()->getWebPath($file, $previewSize);
					$output['thumbnail'] = $this->getFileStorage()->getWebPath($file, $thumbSize);
				} else {
					$output['thumbnail'] = $this->getPrivateImageWebPath($file, $thumbSize);
					$output['file_web_path'] = $output['preview'] = $this->getPrivateImageWebPath($file);

					if ( ! empty($output['sizes'])) {
						foreach ($output['sizes'] as $sizeName => &$size) {
							$sizePath = null;

							if ($sizeName == 'original') {
								$sizePath = $output['file_web_path'];
							} else {
								$sizePath = $this->getPrivateImageWebPath($file, $sizeName);
							}

							$size['external_path'] = $sizePath;
						}
					}
				}
			}
		} catch (\Exception $e) {
			$output['broken'] = true;
			return $output;
		}

		$extension = mb_strtolower($file->getExtension());
		$knownExtensions = $this->container->getParameter('cms.media_library_known_file_extensions');
		if (in_array($extension, $knownExtensions)) {
			$output['known_extension'] = $extension;
		}

		$checkExistance = $this->container->getParameter('cms.media_library_check_file_existence');

		if ($isBroken) {
			$output['broken'] = true;
		} elseif ($checkExistance == self::CHECK_FULL
			|| $checkExistance == self::CHECK_PARTIAL) {

			$output['broken'] = ( ! $this->isAvailable($file));
		}

		$output['timestamp'] = $file->getModificationTime()->getTimestamp();

		// Custom Properties
		$propertyConfigurations = $this->getFileStorage()->getCustomPropertyConfigurations();
		$propertyData = array();
		foreach ($propertyConfigurations as $configuration) {
			/* @var $configuration PropertyConfiguration */
			$propertyName = $configuration->name;
			$propertyData[$propertyName] = $this->getFileStorage()->getFileCustomPropertyValue($file, $propertyName);
		}

		$output['metaData'] = $propertyData;

		return $output;
	}
347775
public function set($file)
    {
        //Resets `$error`
        unset($this->error);

        $this->file = (object)$file;

        //Errors messages
        $errors = [
            UPLOAD_ERR_INI_SIZE => 'The uploaded file exceeds the maximum size that was specified in php.ini',
            UPLOAD_ERR_FORM_SIZE => 'The uploaded file exceeds the maximum size that was specified in the HTML form',
            UPLOAD_ERR_PARTIAL => 'The uploaded file was partially uploaded',
            UPLOAD_ERR_NO_FILE => 'No file was uploaded',
            UPLOAD_ERR_NO_TMP_DIR => 'Missing a temporary folder',
            UPLOAD_ERR_CANT_WRITE => 'Failed to write file to disk',
            UPLOAD_ERR_EXTENSION => 'File upload stopped by extension',
            'default' => 'Unknown upload error',
        ];

        //Checks errors during upload
        if (!isset($file['error']) || $file['error'] !== UPLOAD_ERR_OK) {
            //Gets the default error message, if the error can not be
            //  identified or if the key is not present
            if (!isset($file['error']) || !array_key_exists($file['error'], $errors)) {
                $file['error'] = 'default';
            }

            $this->setError($errors[$file['error']]);
        }

        return $this;
    }
861868
async function validateFile (file, options) {
  if (file instanceof File === false) {
    return null
  }

  await file.setOptions(Object.assign(file.validationOptions, options)).runValidations()
  return _.size(file.error()) ? file.error().message : null
}
871692
public function validateFileUpload(File $file, $sourceFilePath = null)
	{
		// file validation
		foreach ($this->fileUploadFilters as $filter) {
			/* @var $filter Validation\FileValidationInterface */
			$filter->validateFile($file, $sourceFilePath);
		}
	}
441159
public static function size(String $file, String $type = 'b', Int $decimal = 2) : Float
    {
        $file = self::rpath($file);

        if( ! file_exists($file) )
        {
            throw new Exception\FileNotFoundException(NULL, $file);
        }

        $size      = 0;
        $fileSize  = filesize($file);

        if( is_file($file) )
        {
            $size += $fileSize;
        }
        else
        {
            $folderFiles = FileList::files($file);

            if( $folderFiles )
            {
                foreach( $folderFiles as $val )
                {
                    $size += self::size($file."/".$val);
                }

                $size += $fileSize;
            }
            else
            {
                $size += $fileSize;
            }
        }

        // BYTES
        if( $type === "b" )
        {
            return  $size;
        }
        // KILO BYTES
        if( $type === "kb" )
        {
            return round($size / 1024, $decimal);
        }
        // MEGA BYTES
        if( $type === "mb" )
        {
            return round($size / (1024 * 1024), $decimal);
        }
        // GIGA BYTES
        if( $type === "gb" )
        {
            return round($size / (1024 * 1024 * 1024), $decimal);
        }
    }
1083932
public function size($file, int $size): bool
    {
        if (empty($filename = $this->resolveFilename($file))) {
            return false;
        }

        return $this->files->size($filename) <= ($size * 1024);
    }