Internal method. Validates filepicker and filemanager files if they are
set as required fields. Also, sets the error message if encountered one.

@return bool|array with errors
976606
protected function validate_draft_files() {
        global $USER;
        $mform =& $this->_form;

        $errors = array();
        //Go through all the required elements and make sure you hit filepicker or
        //filemanager element.
        foreach ($mform->_rules as $elementname => $rules) {
            $elementtype = $mform->getElementType($elementname);
            //If element is of type filepicker then do validation
            if (($elementtype == 'filepicker') || ($elementtype == 'filemanager')){
                //Check if rule defined is required rule
                foreach ($rules as $rule) {
                    if ($rule['type'] == 'required') {
                        $draftid = (int)$mform->getSubmitValue($elementname);
                        $fs = get_file_storage();
                        $context = context_user::instance($USER->id);
                        if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
                            $errors[$elementname] = $rule['message'];
                        }
                    }
                }
            }
        }
        // Check all the filemanager elements to make sure they do not have too many
        // files in them.
        foreach ($mform->_elements as $element) {
            if ($element->_type == 'filemanager') {
                $maxfiles = $element->getMaxfiles();
                if ($maxfiles > 0) {
                    $draftid = (int)$element->getValue();
                    $fs = get_file_storage();
                    $context = context_user::instance($USER->id);
                    $files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, '', false);
                    if (count($files) > $maxfiles) {
                        $errors[$element->getName()] = get_string('err_maxfiles', 'form', $maxfiles);
                    }
                }
            }
        }
        if (empty($errors)) {
            return true;
        } else {
            return $errors;
        }
    }
494507
public function isValid()
    {
        foreach ($this->objects as $fileInfo) {
            // Before validation callback
            $this->applyCallback('beforeValidation', $fileInfo);

            // Check is uploaded file
            if ($fileInfo->isUploadedFile() === false) {
                $this->errors[] = sprintf(
                    '%s: %s',
                    $fileInfo->getNameWithExtension(),
                    'Is not an uploaded file'
                );
                continue;
            }

            // Apply user validations
            foreach ($this->validations as $validation) {
                try {
                    $validation->validate($fileInfo);
                } catch (\Upload\Exception $e) {
                    $this->errors[] = sprintf(
                        '%s: %s',
                        $fileInfo->getNameWithExtension(),
                        $e->getMessage()
                    );
                }
            }

            // After validation callback
            $this->applyCallback('afterValidation', $fileInfo);
        }

        return empty($this->errors);
    }
1243908
public function isValid()
    {
        $isOk = $this->error === UPLOAD_ERR_OK;

        return $this->test ? $isOk : $isOk && is_uploaded_file($this->getPathname());
    }
858519
public final function validation($data, $files) {
        $errors = parent::validation($data, $files);
        $data = $this->get_submitted_data();

        // Only validate compatible fields.
        $persistentdata = $this->filter_data_for_persistent($data);
        $persistent = $this->get_persistent();
        $persistent->from_record((object) $persistentdata);
        $errors = array_merge($errors, $persistent->get_errors());

        // Apply extra validation.
        $extraerrors = $this->extra_validation($data, $files, $errors);
        $errors = array_merge($errors, (array) $extraerrors);

        return $errors;
    }
191157
public function validation($data, $files) {
        $errors = parent::validation($data, $files);

        if ($files = $this->get_draft_files('rolepreset')) {
            /** @var stored_file $file */
            $file = reset($files);
            $xml = $file->get_content();
            if (!core_role_preset::is_valid_preset($xml)) {
                $errors['rolepreset'] = get_string('invalidpresetfile', 'core_role');
            }
        }

        return $errors;
    }
435976
public function valid()
    {
        if ($this->fileSize == 0) {
            return false;
        }

        if (feof($this->handle)) {
            return false;
        }

        $current = fgets($this->handle);

        if (trim($current) === '' && feof($this->handle)) {
            return false;
        } else {
            fseek($this->handle, $this->offset);
        }

        return true;
    }
1232210
public function verifyFile()
	{
		if (!$this->file)
            return array('error' => Yii::t('ciims.misc', 'No files were uploaded.'));
        
        $size = $this->file->size;

        if ($size == 0) 
            return array('error' => Yii::t('ciims.misc', 'File is empty'));
        
        if ($size > $this->sizeLimit) 
            return array('error' => Yii::t('ciims.misc', 'File is too large'));
        
        $pathinfo = pathinfo($this->file->name);
        $filename = $pathinfo['filename'];

        //$filename = md5(uniqid());
        $ext = $pathinfo['extension'];

        if(!in_array(strtolower($ext), $this->allowedExtensions))
        {
            $these = implode(', ', $this->allowedExtensions);
            return array('error' => Yii::t('ciims.misc', "File has an invalid extension, it should be one of {{these}}.", array('{{these}}' => $these)));
        }

        return array('success' => $filename);
	}
742702
function _validate_files(&$files) {
        global $CFG, $COURSE;

        $files = array();

        if (empty($_FILES)) {
            // we do not need to do any checks because no files were submitted
            // note: server side rules do not work for files - use custom verification in validate() instead
            return true;
        }

        $errors = array();
        $filenames = array();

        // now check that we really want each file
        foreach ($_FILES as $elname=>$file) {
            $required = $this->_form->isElementRequired($elname);

            if ($file['error'] == 4 and $file['size'] == 0) {
                if ($required) {
                    $errors[$elname] = get_string('required');
                }
                unset($_FILES[$elname]);
                continue;
            }

            if (!empty($file['error'])) {
                $errors[$elname] = file_get_upload_error($file['error']);
                unset($_FILES[$elname]);
                continue;
            }

            if (!is_uploaded_file($file['tmp_name'])) {
                // TODO: improve error message
                $errors[$elname] = get_string('error');
                unset($_FILES[$elname]);
                continue;
            }

            if (!$this->_form->elementExists($elname) or !$this->_form->getElementType($elname)=='file') {
                // hmm, this file was not requested
                unset($_FILES[$elname]);
                continue;
            }

            // NOTE: the viruses are scanned in file picker, no need to deal with them here.

            $filename = clean_param($_FILES[$elname]['name'], PARAM_FILE);
            if ($filename === '') {
                // TODO: improve error message - wrong chars
                $errors[$elname] = get_string('error');
                unset($_FILES[$elname]);
                continue;
            }
            if (in_array($filename, $filenames)) {
                // TODO: improve error message - duplicate name
                $errors[$elname] = get_string('error');
                unset($_FILES[$elname]);
                continue;
            }
            $filenames[] = $filename;
            $_FILES[$elname]['name'] = $filename;

            $files[$elname] = $_FILES[$elname]['tmp_name'];
        }

        // return errors if found
        if (count($errors) == 0){
            return true;

        } else {
            $files = array();
            return $errors;
        }
    }
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;
    }
719671
protected function validate_uploaded_file($data, $errors) {
        if (empty($data['newfile'])) {
            $errors['newfile'] = get_string('required');
            return $errors;
        }

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

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

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

        require_once($formatfile);

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

        $file = reset($files);
        if (!$qformat->can_import_file($file)) {
            $a = new stdClass();
            $a->actualtype = $file->get_mimetype();
            $a->expectedtype = $qformat->mime_type();
            $errors['newfile'] = get_string('importwrongfiletype', 'question', $a);
        }

        return $errors;
    }
939508
protected function validateLimitsUpload()
    {
        $files = $this->request->file('files');

        if (!gplcart_file_multi_upload($files)) {
            return false;
        }

        if ($this->user->isSuperadmin()) {
            return true;
        }

        $role_id = $this->user->getRoleId();
        $settings = $this->module->getSettings('file_manager');

        $maxfilesize = 0;
        $extensions = array();

        if (!empty($settings['filesize_limit'][$role_id])) {
            $maxfilesize = $settings['filesize_limit'][$role_id];
        }

        if (!empty($settings['extension_limit'][$role_id])) {
            $extensions = $settings['extension_limit'][$role_id];
        }

        $errors = array();
        foreach ($files as $file) {

            if ($maxfilesize && filesize($file['tmp_name']) > $maxfilesize) {
                unlink($file['tmp_name']);
                $errors[] = "{$file['name']}: " . $this->translation->text('File size exceeds %num bytes', array('%num' => $maxfilesize));
                continue;
            }

            if ($extensions && !in_array(pathinfo($file['name'], PATHINFO_EXTENSION), $extensions)) {
                unlink($file['tmp_name']);
                $errors[] = "{$file['name']}: " . $this->translation->text('Unsupported file extension');
            }
        }

        if (empty($errors)) {
            return true;
        }

        $this->setError('files', implode('<br>', $errors));
        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;
    }
874416
protected function validatePathFile()
    {
        $field = 'path';
        $value = $this->getSubmitted($field);

        if ($this->isExcluded($field) || $this->isError()) {
            return null;
        }

        if (!isset($value) && $this->isUpdating()) {
            return null;
        }

        $label = $this->translation->text('File');

        if (empty($value)) {
            $this->setErrorRequired($field, $label);
            return false;
        }

        if (!is_readable(gplcart_file_absolute($value))) {
            $this->setErrorUnavailable($field, $label);
            return false;
        }

        return true;
    }
1289978
public function validate()
    {
        if (($_FILES) && (isset($_FILES[$this->name]['name']))) {
            $value = $_FILES[$this->name]['name'];
            $size  = $_FILES[$this->name]['size'];
        } else {
            $value = null;
            $size  = null;
        }
        // Check if the element is required
        if (($this->required) && empty($value)) {
            $this->errors[] = 'This field is required.';
        }
        // Check field validators
        if (count($this->validators) > 0) {
            foreach ($this->validators as $validator) {
                if ($validator instanceof \Pop\Validator\ValidatorInterface) {
                    $class =  get_class($validator);
                    if ((null !== $size) &&
                        (('Pop\Validator\LessThanEqual' == $class) || ('Pop\Validator\GreaterThanEqual' == $class) ||
                         ('Pop\Validator\LessThan' == $class) || ('Pop\Validator\GreaterThan' == $class))) {
                        if (!$validator->evaluate($size)) {
                            $this->errors[] = $validator->getMessage();
                        }
                    } else {
                        if (!$validator->evaluate($value)) {
                            $this->errors[] = $validator->getMessage();
                        }
                    }
                } else if (is_callable($validator)) {
                    $result = call_user_func_array($validator, [$value]);
                    if (null !== $result) {
                        $this->errors[] = $result;
                    }
                }
            }
        }
        return (count($this->errors) == 0);
    }
1122500
public function validation($data, $files) {
        $errors = array();
        $draftitemid = $data['files_filemanager'];
        if (file_is_draft_area_limit_reached($draftitemid, $this->_customdata['options']['areamaxbytes'])) {
            $errors['files_filemanager'] = get_string('userquotalimit', 'error');
        }

        return $errors;
    }
1010344
protected function validateServiceCredential()
    {
        if (!$this->isPosted('save')) {
            return false;
        }

        $this->setSubmitted('credential');
        $this->validateElement(array('name' => $this->text('Name')), 'length', array(1, 255));
        $this->validateFileUploadCredential();

        return !$this->hasErrors();
    }
1312190
public function validate()
	{
		$this->errors = array();
		$value = $this->getRawValue();

		if ($this->required) {

			$passed = $this->validateRequired($value);

			// don't do anymore validation until it passes the required validation
			if (!$passed) return $this->errors;

			// validate by field type
			$this->validateType($value);

			// validate by pattern, if defined
			$this->validatePattern($value);

      // validate by maxlength, if defined
      $this->validateMaxLength($value);

			// hook for users?

		}

		return $this->errors;
	}