Validate the form field from profile page

@param stdClass $usernew
@return  string  contains error message otherwise null
199505
public function edit_validate_field($usernew) {
        global $DB;

        $errors = array();
        // Get input value.
        if (isset($usernew->{$this->inputname})) {
            if (is_array($usernew->{$this->inputname}) && isset($usernew->{$this->inputname}['text'])) {
                $value = $usernew->{$this->inputname}['text'];
            } else {
                $value = $usernew->{$this->inputname};
            }
        } else {
            $value = '';
        }

        // Check for uniqueness of data if required.
        if ($this->is_unique() && (($value !== '') || $this->is_required())) {
            $data = $DB->get_records_sql('
                    SELECT id, userid
                      FROM {user_info_data}
                     WHERE fieldid = ?
                       AND ' . $DB->sql_compare_text('data', 255) . ' = ' . $DB->sql_compare_text('?', 255),
                    array($this->field->id, $value));
            if ($data) {
                $existing = false;
                foreach ($data as $v) {
                    if ($v->userid == $usernew->id) {
                        $existing = true;
                        break;
                    }
                }
                if (!$existing) {
                    $errors[$this->inputname] = get_string('valuealreadyused');
                }
            }
        }
        return $errors;
    }
1194967
public function findActiveValidationByUser(User $user, $sort = null)
    {
        $dql = 'SELECT b
            FROM Phraseanet:Basket b
            JOIN b.elements e
            JOIN e.validation_datas v
            JOIN b.validation s
            JOIN s.participants p
            WHERE b.user != ?1 AND p.user = ?2
             AND (s.expires IS NULL OR s.expires > CURRENT_TIMESTAMP()) ';

        if ($sort == 'date') {
            $dql .= ' ORDER BY b.created DESC';
        } elseif ($sort == 'name') {
            $dql .= ' ORDER BY b.name ASC';
        }

        $query = $this->_em->createQuery($dql);
        $query->setParameters([1 => $user->getId(), 2 => $user->getId()]);

        return $query->getResult();
    }
732303
protected function validateData(Framework $framework, User $user, $oldPassword, $newPassword, $newPasswordConfirmed)
    {
        // Old password
        if (!$user->comparePasswords($oldPassword)) {
            return $this->translate('The old password is not valid.', '\\Zepi\\Web\\AccessControl');
        }
        
        // New password
        if (strlen($newPassword) < 8) {
            return $this->translate('The new password needs at least 8 characters.', '\\Zepi\\Web\\AccessControl');
        }
        
        if ($newPassword != $newPasswordConfirmed) {
            return $this->translate('The new password are not equal.', '\\Zepi\\Web\\AccessControl');
        }

        return true;
    }
817176
protected function validateEditUser()
    {
        $this->setSubmitted('user');
        $this->setSubmittedBool('status');
        $this->setSubmitted('update', $this->data_user);

        $this->validateComponent('user', array('admin' => $this->access('user_edit')));

        return !$this->hasErrors();
    }
1096046
public static function create_contact_request(int $userid, int $requesteduserid) : \stdClass {
        global $DB, $PAGE;

        $request = new \stdClass();
        $request->userid = $userid;
        $request->requesteduserid = $requesteduserid;
        $request->timecreated = time();

        $request->id = $DB->insert_record('message_contact_requests', $request);

        // Send a notification.
        $userfrom = \core_user::get_user($userid);
        $userfromfullname = fullname($userfrom);
        $userto = \core_user::get_user($requesteduserid);
        $url = new \moodle_url('/message/pendingcontactrequests.php');

        $subject = get_string('messagecontactrequestsnotificationsubject', 'core_message', $userfromfullname);
        $fullmessage = get_string('messagecontactrequestsnotification', 'core_message', $userfromfullname);

        $message = new \core\message\message();
        $message->courseid = SITEID;
        $message->component = 'moodle';
        $message->name = 'messagecontactrequests';
        $message->notification = 1;
        $message->userfrom = $userfrom;
        $message->userto = $userto;
        $message->subject = $subject;
        $message->fullmessage = text_to_html($fullmessage);
        $message->fullmessageformat = FORMAT_HTML;
        $message->fullmessagehtml = $fullmessage;
        $message->smallmessage = '';
        $message->contexturl = $url->out(false);
        $userpicture = new \user_picture($userfrom);
        $userpicture->includetoken = $userto->id; // Generate an out-of-session token for the user receiving the message.
        $message->customdata = [
            'notificationiconurl' => $userpicture->get_url($PAGE)->out(false),
            'actionbuttons' => [
                'accept' => get_string_manager()->get_string('accept', 'moodle', null, $userto->lang),
                'reject' => get_string_manager()->get_string('reject', 'moodle', null, $userto->lang),
            ],
        ];

        message_send($message);

        return $request;
    }
190391
public function createNewPageFromTemplate($user, $data)
    {
        if (empty($user)) {
            throw new TrackingException('A valid user is required in ' . get_class($this));
        }
        $validatedData = $data;
        /** @var \Rcm\Entity\Page $page */
        $page = $this->pageRepo->findOneBy(
            [
                'pageId' => $validatedData['page-template'],
                'pageType' => 't'
            ]
        );

        if (empty($page)) {
            throw new PageNotFoundException(
                'No template found for page id: '
                . $validatedData['page-template']
            );
        }

        $pageData = [
            'name' => $validatedData['name'],
            'pageTitle' => $validatedData['pageTitle'],
            'pageType' => 'n', // "n" means "normal"
            'createdByUserId' => $user->getId(),
            'createdReason' => 'New page from template in ' . get_class($this),
            'author' => $user->getName(),
        ];

        $createdPage = $resultRevisionId = $this->pageRepo->copyPage(
            $this->currentSite,
            $page,
            $pageData
        );

        $this->immuteblePageVersionRepo->createUnpublished(
            new PageLocator(
                $this->currentSite->getSiteId(),
                $this->rcmPageNameToPathname->__invoke($createdPage->getName(), $createdPage->getPageType())
            ),
            $this->immutablePageContentFactory->__invoke(
                $createdPage->getPageTitle(),
                $createdPage->getDescription(),
                $createdPage->getKeywords(),
                $this->revisionRepo->find($resultRevisionId)->getPluginWrappers()->toArray()
            ),
            $user->getId(),
            __CLASS__ . '::' . __FUNCTION__
        );
    }
886724
private function getCurrentUser($required)
    {
        $result = null;
        $id = $this->getCurrentUserID($required);
        if ($id !== null) {
            $result = $this->getEntityManager()->find(UserEntity::class, $id);
        }

        if ($result === null && $required) {
            throw new UserMessageException(t('No logged in user'));
        }

        return $result;
    }
131009
protected function validateUserForgot()
    {
        $this->setSubmitted('user', null, false);
        $this->filterSubmitted(array('email', 'password'));

        $this->setSubmitted('user', $this->data_user);
        $this->validateComponent('user_reset_password');

        return !$this->hasErrors();
    }
53715
public function validateFinal(array &$form, FormStateInterface $form_state) {
    $flood_config = $this->config('user.flood');
    if (!$form_state->get('uid')) {
      // Set general error message to not leak privacy information.
      $this->setGeneralErrorMessage($form, $form_state);

      // Always register an IP-based failed login event.
      $this->flood->register('user.failed_login_ip', $flood_config->get('ip_window'));
      // Register a per-user failed login event.
      if ($flood_control_user_identifier = $form_state->get('flood_control_user_identifier')) {
        $this->flood->register('user.failed_login_user', $flood_config->get('user_window'), $flood_control_user_identifier);
      }
      $flood_control_triggered = $form_state->get('flood_control_triggered');
      if (!$flood_control_triggered) {
        $name = $form_state->getValue('name_or_mail');
        $accounts = $this->userStorage->loadByProperties(['mail' => $form_state->getValue('name_or_mail'), 'status' => 1]);
        $account = reset($accounts);
        if ($account) {
          $name = $account->getAccountName();
        }
        $accounts = $this->userStorage->loadByProperties(['name' => $name]);
        if (!empty($accounts)) {
          $this->logger('user')->notice('Login attempt failed for %user.', ['%user' => $name]);
        }
        else {
          // If the username entered is not a valid user,
          // only store the IP address.
          $this->logger('user')->notice('Login attempt failed from %ip.', ['%ip' => $this->getRequest()->getClientIp()]);
        }
      }
    }
    elseif ($flood_control_user_identifier = $form_state->get('flood_control_user_identifier')) {
      // Clear past failures for this user so as not to block a user who might
      // log in and out more than once in an hour.
      $this->flood->clear('user.failed_login_user', $flood_control_user_identifier);
    }
  }
1029560
public static function user_match($newuser, $olduser) {
        if ($newuser->firstname != $olduser->firstname) {
            return false;
        }
        if ($newuser->lastname != $olduser->lastname) {
            return false;
        }
        if ($newuser->email != $olduser->email) {
            return false;
        }
        if ($newuser->city != $olduser->city) {
            return false;
        }
        if ($newuser->country != $olduser->country) {
            return false;
        }
        if ($newuser->institution != $olduser->institution) {
            return false;
        }
        if ($newuser->timezone != $olduser->timezone) {
            return false;
        }
        if ($newuser->maildisplay != $olduser->maildisplay) {
            return false;
        }
        if ($newuser->mnethostid != $olduser->mnethostid) {
            return false;
        }
        if ($newuser->confirmed != $olduser->confirmed) {
            return false;
        }
        if ($newuser->lang != $olduser->lang) {
            return false;
        }

        return true;
    }
520595
protected function validateEmailUniqueUser()
    {
        $field = 'email';
        $value = $this->getSubmitted($field);

        if ($this->isError($field) || !isset($value)) {
            return null;
        }

        $updating = $this->getUpdating();

        if (isset($updating['email']) && $updating['email'] === $value) {
            return true;
        }

        $user = $this->user->getByEmail($value);

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

        $this->setErrorExists($field, $this->translation->text('E-mail'));
        return false;
    }
604470
public function getFormToken($userId = null, $forceNew = false)
    {
        $userId = $userId ?: $this->userManager->getUser()->id;
        $userId = $userId ?: $this->session->getId();

        $config = $this->config;

        return md5($config['system.secret'] . $userId . $this->getToken($forceNew));
    }
316141
protected function validateFieldIdProductClassField()
    {
        $field = 'field_id';

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

        $value = $this->getSubmitted($field);

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

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

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

        $updating = $this->getUpdating();
        $product_class_id = $this->getSubmitted('product_class_id');

        if (!isset($product_class_id) && isset($updating['product_class_id'])) {
            $product_class_id = $updating['product_class_id'];
        }

        if (empty($product_class_id)) {
            $this->setErrorUnavailable($field, $this->translation->text('Unknown product class ID'));
        }

        $existing = $this->product_class_field->getList(array(
                'index' => 'field_id',
                'product_class_id' => $product_class_id)
        );

        $processed = array();

        foreach ((array) $value as $field_id) {

            if (empty($field_id) || !is_numeric($field_id)) {
                $this->setErrorInvalid($field, $label);
                return false;
            }

            if (in_array($field_id, $processed)) {
                $this->setErrorExists($field, $label);
                return false;
            }

            if (isset($existing[$field_id])) {
                $this->setErrorExists($field, $label);
                return false;
            }

            $data = $this->field->get($field_id);

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

            $processed[] = $field_id;
        }

        return true;
    }
475704
public function instance_form_save(\stdClass $datanew) {
        $elementname = $this->get_form_element_name();
        if (!property_exists($datanew, $elementname)) {
            return;
        }
        $value = $datanew->$elementname;
        $this->data->set($this->datafield(), $value);
        $this->data->set('value', $value);
        $this->save();
    }
1051800
public function validForCreation($first_name, $last_name, $email, $password)
	{
		return $this->validateUser($first_name, $last_name, $email, $password);
	}
1311682
public static function CheckUser($User, $Validation = NULL, $UpdateBlocks = FALSE, &$BansFound = NULL) {
      $Bans = self::AllBans();
      $Fields = array('Name' => 'Name', 'Email' => 'Email', 'IPAddress' => 'LastIPAddress');
      $Banned = array();
      
      if (!$BansFound)
         $BansFound = array();

      foreach ($Bans as $Ban) {
         // Convert ban to regex.
         $Parts = explode('*', str_replace('%', '*', $Ban['BanValue']));
         $Parts = array_map('preg_quote', $Parts);
         $Regex = '`^'.implode('.*', $Parts).'$`i';

         if (preg_match($Regex, GetValue($Fields[$Ban['BanType']], $User))) {
            $Banned[$Ban['BanType']] = TRUE;
            $BansFound[] = $Ban;

            if ($UpdateBlocks) {
               Gdn::SQL()
                  ->Update('Ban')
                  ->Set('CountBlockedRegistrations', 'CountBlockedRegistrations + 1', FALSE, FALSE)
                  ->Where('BanID', $Ban['BanID'])
                  ->Put();
            }
         }
      }

      // Add the validation results.
      if ($Validation) {
         foreach ($Banned as $BanType => $Value) {
            $Validation->AddValidationResult(Gdn_Form::LabelCode($BanType), 'ValidateBanned');
         }
      }
      return count($Banned) == 0;
   }
808325
public function validate(ValidatorInterface &$v = null)
    {
        $result = parent::validate($v);
        $objType = self::objType();
        $previousModel = $this->modelFactory()->create($objType)->load($this->id());

        $email = $this->email();
        if (empty($email)) {
            $this->validator()->error(
                'Email is required.',
                'email'
            );
        } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $this->validator()->error(
                'Email format is incorrect.',
                'email'
            );
        /** Check if updating/changing email. */
        } elseif ($previousModel->email() !== $email) {
            $existingModel = $this->modelFactory()->create($objType)->loadFrom('email', $email);
            /** Check for existing user with given email. */
            if (!empty($existingModel->id())) {
                $this->validator()->error(
                    'This email is not available.',
                    'email'
                );
            }
        }

        return count($this->validator()->errorResults()) === 0 && $result;
    }