Form validation

@param array $data
@param array $files
@return array $errors An array of errors
344344
function validation($data, $files) {
        global $COURSE, $DB, $CFG;

        $errors = parent::validation($data, $files);

        $name = trim($data['name']);
        if (isset($data['idnumber'])) {
            $idnumber = trim($data['idnumber']);
        } else {
            $idnumber = '';
        }
        if ($data['id'] and $group = $DB->get_record('groups', array('id'=>$data['id']))) {
            if (core_text::strtolower($group->name) != core_text::strtolower($name)) {
                if (groups_get_group_by_name($COURSE->id,  $name)) {
                    $errors['name'] = get_string('groupnameexists', 'group', $name);
                }
            }
            if (!empty($idnumber) && $group->idnumber != $idnumber) {
                if (groups_get_group_by_idnumber($COURSE->id, $idnumber)) {
                    $errors['idnumber']= get_string('idnumbertaken');
                }
            }

            if ($data['enrolmentkey'] != '') {
                $errmsg = '';
                if (!empty($CFG->groupenrolmentkeypolicy) && $group->enrolmentkey !== $data['enrolmentkey']
                        && !check_password_policy($data['enrolmentkey'], $errmsg)) {
                    // Enforce password policy when the password is changed.
                    $errors['enrolmentkey'] = $errmsg;
                } else {
                    // Prevent twice the same enrolment key in course groups.
                    $sql = "SELECT id FROM {groups} WHERE id <> :groupid AND courseid = :courseid AND enrolmentkey = :key";
                    $params = array('groupid' => $data['id'], 'courseid' => $COURSE->id, 'key' => $data['enrolmentkey']);
                    if ($DB->record_exists_sql($sql, $params)) {
                        $errors['enrolmentkey'] = get_string('enrolmentkeyalreadyinuse', 'group');
                    }
                }
            }

        } else if (groups_get_group_by_name($COURSE->id, $name)) {
            $errors['name'] = get_string('groupnameexists', 'group', $name);
        } else if (!empty($idnumber) && groups_get_group_by_idnumber($COURSE->id, $idnumber)) {
            $errors['idnumber']= get_string('idnumbertaken');
        } else if ($data['enrolmentkey'] != '') {
            $errmsg = '';
            if (!empty($CFG->groupenrolmentkeypolicy) && !check_password_policy($data['enrolmentkey'], $errmsg)) {
                // Enforce password policy.
                $errors['enrolmentkey'] = $errmsg;
            } else if ($DB->record_exists('groups', array('courseid' => $COURSE->id, 'enrolmentkey' => $data['enrolmentkey']))) {
                // Prevent the same enrolment key from being used multiple times in course groups.
                $errors['enrolmentkey'] = get_string('enrolmentkeyalreadyinuse', 'group');
            }
        }

        return $errors;
    }
695265
public function validation($data, $files) {
        $errors = [];
        if (isset($data['purgeselectedcaches']) && empty(array_filter($data['purgeselectedoptions']))) {
            $errors['purgeselectedoptions'] = get_string('purgecachesnoneselected', 'admin');
        }
        return $errors;
    }
347858
public function validation($data, $files) {
        $errors = parent::validation($data, $files);

        if (isset($data['rawname'])) {
            $newname = core_text::strtolower($data['rawname']);
            $tag = $this->_customdata['tag'];
            if ($tag->name != $newname) {
                // The name has changed, let's make sure it's not another existing tag.
                if (core_tag_tag::get_by_name($tag->tagcollid, $newname)) {
                    // Something exists already, so flag an error.
                    $errors['rawname'] = get_string('namesalreadybeeingused', 'tag');
                }
            }
        }

        return $errors;
    }
1154441
public function validation($data, $files) {
        global $USER;

        if ($errors = parent::validation($data, $files)) {
            return $errors;
        }

        $usercontext = context_user::instance($USER->id);
        $fs = get_file_storage();

        if (!$files = $fs->get_area_files($usercontext->id, 'user', 'draft', $data['package'], 'id', false)) {
            if (!$this->current->instance) {
                $errors['package'] = get_string('required');
                return $errors;
            }
        } else {
            $file = reset($files);
            if ($file->get_mimetype() != 'application/zip') {
                $errors['package'] = get_string('invalidfiletype', 'error', '', $file);
                // Better delete current file, it is not usable anyway.
                $fs->delete_area_files($usercontext->id, 'user', 'draft', $data['package']);
            }
        }

        return $errors;
    }
586677
protected function validateUploads(array $files): void
    {
        foreach ($files as $file) {
            if (null === $file) {
                continue;
            }
            if ($file instanceof UploadedFileInterface) {
                $this->validateUpload($file);
            } else {
                $this->validateUploads($file);
            }
        }
    }
11760
function validation($data, $files) {
        $errors = parent::validation($data, $files);
        $columns = $this->_customdata['columns'];
        $optype  = $data['uutype'];
        $updatetype = $data['uuupdatetype'];

        // detect if password column needed in file
        if (!in_array('password', $columns)) {
            switch ($optype) {
                case UU_USER_UPDATE:
                    if (!empty($data['uupasswordold'])) {
                        $errors['uupasswordold'] = get_string('missingfield', 'error', 'password');
                    }
                    break;

                case UU_USER_ADD_UPDATE:
                    if (empty($data['uupasswordnew'])) {
                        $errors['uupasswordnew'] = get_string('missingfield', 'error', 'password');
                    }
                    if  (!empty($data['uupasswordold'])) {
                        $errors['uupasswordold'] = get_string('missingfield', 'error', 'password');
                    }
                    break;

                case UU_USER_ADDNEW:
                    if (empty($data['uupasswordnew'])) {
                        $errors['uupasswordnew'] = get_string('missingfield', 'error', 'password');
                    }
                    break;
                case UU_USER_ADDINC:
                    if (empty($data['uupasswordnew'])) {
                        $errors['uupasswordnew'] = get_string('missingfield', 'error', 'password');
                    }
                    break;
             }
        }

        // If the 'Existing user details' value is set we need to ensure that the
        // 'Upload type' is not set to something invalid.
        if (!empty($updatetype) && ($optype == UU_USER_ADDNEW || $optype == UU_USER_ADDINC)) {
            $errors['uuupdatetype'] = get_string('invalidupdatetype', 'tool_uploaduser');
        }

        // look for other required data
        if ($optype != UU_USER_UPDATE) {
            $requiredusernames = useredit_get_required_name_fields();
            $missing = array();
            foreach ($requiredusernames as $requiredusername) {
                if (!in_array($requiredusername, $columns)) {
                    $missing[] = get_string('missingfield', 'error', $requiredusername);;
                }
            }
            if ($missing) {
                $errors['uutype'] = implode('<br />',  $missing);
            }
            if (!in_array('email', $columns) and empty($data['email'])) {
                $errors['email'] = get_string('requiredtemplate', 'tool_uploaduser');
            }
        }
        return $errors;
    }
591504
function validation($data, $files) {
        global $DB, $CFG;

        $errors = parent::validation($data, $files);

        if ($data['courseid'] > 0) {
            if ($course = $DB->get_record('course', array('id'=>$data['courseid']))) {
                if ($data['timestart'] < $course->startdate) {
                    $errors['timestart'] = get_string('errorbeforecoursestart', 'calendar');
                }
            } else {
                $errors['courseid'] = get_string('invalidcourse', 'error');
            }

        }

        if ($data['duration'] == 1 && $data['timestart'] > $data['timedurationuntil']) {
            $errors['timedurationuntil'] = get_string('invalidtimedurationuntil', 'calendar');
        } else if ($data['duration'] == 2 && (trim($data['timedurationminutes']) == '' || $data['timedurationminutes'] < 1)) {
            $errors['timedurationminutes'] = get_string('invalidtimedurationminutes', 'calendar');
        }

        return $errors;
    }
1338570
public function validation($data, $files = array()) {
        global $DB;

        $errors = array();
        /** @var field_controller $field */
        $field = $this->_customdata['field'];
        $handler = $field->get_handler();

        // Check the shortname is specified and is unique for this component-area-itemid combination.
        if (!preg_match('/^[a-z0-9_]+$/', $data['shortname'])) {
            // Check allowed pattern (numbers, letters and underscore).
            $errors['shortname'] = get_string('invalidshortnameerror', 'core_customfield');
        } else if ($DB->record_exists_sql('SELECT 1 FROM {customfield_field} f ' .
            'JOIN {customfield_category} c ON c.id = f.categoryid ' .
            'WHERE f.shortname = ? AND f.id <> ? AND c.component = ? AND c.area = ? AND c.itemid = ?',
            [$data['shortname'], $data['id'],
                $handler->get_component(), $handler->get_area(), $handler->get_itemid()])) {
            $errors['shortname'] = get_string('formfieldcheckshortname', 'core_customfield');
        }

        $errors = array_merge($errors, $field->config_form_validation($data, $files));

        return $errors;
    }
98012
public function validation($data, $files) {
        global $CFG;

        $errors = parent::validation($data, $files);

        require_once($CFG->libdir . '/simplepie/moodle_simplepie.php');

        $rss = new moodle_simplepie();
        $rssfile = $rss->registry->create('File', array($data['url']));
        $filetest = $rss->registry->create('Locator', array($rssfile));

        if (!$filetest->is_feed($rssfile)) {
            $errors['url'] = get_string('feedisinvalid', 'blog');
        } else {
            $rss->set_feed_url($data['url']);
            if (!$rss->init()) {
                $errors['url'] = get_string('emptyrssfeed', 'blog');
            }
        }

        return $errors;
    }
720995
public function configuration_validation($data, $files, array $errors) {
        if (empty($errors['prefix'])) {
            $factory = cache_factory::instance();
            $config = $factory->create_config_instance();
            foreach ($config->get_all_stores() as $store) {
                if ($store['plugin'] === 'apcu') {
                    if (isset($store['configuration']['prefix'])) {
                        if ($data['prefix'] === $store['configuration']['prefix']) {
                            // The new store has the same prefix as an existing store, thats a problem.
                            $errors['prefix'] = get_string('prefixnotunique', 'cachestore_apcu');
                            break;
                        }
                    } else if (empty($data['prefix'])) {
                        // The existing store hasn't got a prefix and neither does the new store, that's a problem.
                        $errors['prefix'] = get_string('prefixnotunique', 'cachestore_apcu');
                        break;
                    }
                }
            }
        }
        return $errors;
    }
39455
public function validation($data, $files) {
        global $DB;

        $course = get_course($data['id']);

        $errors = parent::validation($data, $files);

        // We check the values that would be used as start and end.
        if ($data['reset_start_date'] != 0) {
            $coursedata['startdate'] = $data['reset_start_date'];
        } else {
            $coursedata['startdate'] = $course->startdate;
        }

        if ($data['reset_end_date'] != 0) {
            // End date set by the user has preference.
            $coursedata['enddate'] = $data['reset_end_date'];
        } else if ($data['reset_start_date'] > 0 && $course->enddate != 0) {
            // Otherwise, if the current course enddate is set, reset_course_userdata will add the start date time shift to it.
            $timeshift = $data['reset_start_date'] - usergetmidnight($course->startdate);
            $coursedata['enddate'] = $course->enddate + $timeshift;
        } else {
            $coursedata['enddate'] = $course->enddate;
        }

        if ($errorcode = course_validate_dates($coursedata)) {
            $errors['reset_end_date'] = get_string($errorcode, 'error');
        }

        return $errors;
    }
1008651
function validation($data, $files) {
        global $CFG, $COURSE;
        $errors = parent::validation($data, $files);

        if ($data['allocateby'] != 'no') {
            $source = array();
            if ($data['cohortid']) {
                $source['cohortid'] = $data['cohortid'];
            }
            if ($data['groupingid']) {
                $source['groupingid'] = $data['groupingid'];
            }
            if ($data['groupid']) {
                $source['groupid'] = $data['groupid'];
            }
            if (!$users = groups_get_potential_members($data['courseid'], $data['roleid'], $source)) {
                $errors['roleid'] = get_string('nousersinrole', 'group');
            }

           /// Check the number entered is sane
            if ($data['groupby'] == 'groups') {
                $usercnt = count($users);

                if ($data['number'] > $usercnt || $data['number'] < 1) {
                    $errors['number'] = get_string('toomanygroups', 'group', $usercnt);
                }
            }
        }

        //try to detect group name duplicates
        $name = groups_parse_name(trim($data['namingscheme']), 0);
        if (groups_get_group_by_name($COURSE->id, $name)) {
            $errors['namingscheme'] = get_string('groupnameexists', 'group', $name);
        }

        // check grouping name duplicates
        if ( isset($data['grouping']) && $data['grouping'] == '-1') {
            $name = trim($data['groupingname']);
            if (empty($name)) {
                $errors['groupingname'] = get_string('required');
            } else if (groups_get_grouping_by_name($COURSE->id, $name)) {
                $errors['groupingname'] = get_string('groupingnameexists', 'group', $name);
            }
        }

       /// Check the naming scheme
        if ($data['groupby'] == 'groups' and $data['number'] == 1) {
            // we can use the name as is because there will be only one group max
        } else {
            $matchcnt = preg_match_all('/[#@]{1,1}/', $data['namingscheme'], $matches);
            if ($matchcnt != 1) {
                $errors['namingscheme'] = get_string('badnamingscheme', 'group');
            }
        }

        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;
    }
1050485
public function config_form_validation(array $data, $files = array()) : array {
        global $CFG;
        $errors = parent::config_form_validation($data, $files);

        $maxlength = (int)$data['configdata']['maxlength'];
        if ($maxlength < 1 || $maxlength > 1333) {
            $errors['configdata[maxlength]'] = get_string('errorconfigmaxlen', 'customfield_text');
        }

        $displaysize = (int)$data['configdata']['displaysize'];
        if ($displaysize < 1 || $displaysize > 200) {
            $errors['configdata[displaysize]'] = get_string('errorconfigdisplaysize', 'customfield_text');
        }

        if (isset($data['configdata']['link'])) {
            $link = $data['configdata']['link'];
            if (strlen($link)) {
                require_once($CFG->dirroot . '/lib/validateurlsyntax.php');
                if (strpos($link, '$$') === false) {
                    $errors['configdata[link]'] = get_string('errorconfiglinkplaceholder', 'customfield_text');
                } else if (!validateUrlSyntax(str_replace('$$', 'XYZ', $link), 's+H?S?F-E-u-P-a?I?p?f?q?r?')) {
                    // This validation is more strict than PARAM_URL - it requires the protocol and it must be either http or https.
                    $errors['configdata[link]'] = get_string('errorconfigdisplaysize', 'customfield_text');
                }
            }
        }

        return $errors;
    }
238970
protected function validate(array &$data)
    {
        $messages = [];
        if (!empty($data['errors']) && !empty($data['activity']) && !empty($data['requests'])) {
            array_push($messages, ['warning', trans('It is recommended to periodically clean system logs.')]);
        }
        $data = array_merge($data, ['messages' => $messages]);
        return $data;
    }
1279901
public function validation($data, $files) {
        $user = $this->_customdata;

        $errors = parent::validation($data, $files);

        // Ignore submitted username.
        if ($data['password'] !== $data['password2']) {
            $errors['password'] = get_string('passwordsdiffer');
            $errors['password2'] = get_string('passwordsdiffer');
            return $errors;
        }

        $errmsg = ''; // Prevents eclipse warnings.
        if (!check_password_policy($data['password'], $errmsg)) {
            $errors['password'] = $errmsg;
            $errors['password2'] = $errmsg;
            return $errors;
        }

        if (user_is_previously_used_password($user->id, $data['password'])) {
            $errors['password'] = get_string('errorpasswordreused', 'core_auth');
            $errors['password2'] = get_string('errorpasswordreused', 'core_auth');
        }

        return $errors;
    }
275233
public function config_form_validation(array $data, $files = array()) : array {
        $options = preg_split("/\s*\n\s*/", trim($data['configdata']['options']));
        $errors = [];
        if (!$options || count($options) < 2) {
            $errors['configdata[options]'] = get_string('errornotenoughoptions', 'customfield_select');
        } else if (!empty($data['configdata']['defaultvalue'])) {
            $defaultkey = array_search($data['configdata']['defaultvalue'], $options);
            if ($defaultkey === false) {
                $errors['configdata[defaultvalue]'] = get_string('errordefaultvaluenotinlist', 'customfield_select');
            }
        }
        return $errors;
    }