UserModel::save PHP Method

save() public method

Generic save procedure.
public save ( array $FormPostValues, array $Settings = [] )
$FormPostValues array The user to save.
$Settings array Controls certain save functionality. - SaveRoles - Save 'RoleID' field as user's roles. Default false. - HashPassword - Hash the provided password on update. Default true. - FixUnique - Try to resolve conflicts with unique constraints on Name and Email. Default false. - ValidateEmail - Make sure the provided email addresses is formatted properly. Default true. - NoConfirmEmail - Disable email confirmation. Default false.
    public function save($FormPostValues, $Settings = [])
    {
        // See if the user's related roles should be saved or not.
        $SaveRoles = val('SaveRoles', $Settings);
        // Define the primary key in this model's table.
        $this->defineSchema();
        // Custom Rule: This will make sure that at least one role was selected if saving roles for this user.
        if ($SaveRoles) {
            $this->Validation->addRule('OneOrMoreArrayItemRequired', 'function:ValidateOneOrMoreArrayItemRequired');
            $this->Validation->applyRule('RoleID', 'OneOrMoreArrayItemRequired');
        } else {
            $this->Validation->unapplyRule('RoleID', 'OneOrMoreArrayItemRequired');
        }
        // Make sure that checkbox values are saved as the appropriate value.
        if (array_key_exists('ShowEmail', $FormPostValues)) {
            $FormPostValues['ShowEmail'] = forceBool($FormPostValues['ShowEmail'], '0', '1', '0');
        }
        if (array_key_exists('Banned', $FormPostValues)) {
            $FormPostValues['Banned'] = intval($FormPostValues['Banned']);
        }
        if (array_key_exists('Confirmed', $FormPostValues)) {
            $FormPostValues['Confirmed'] = forceBool($FormPostValues['Confirmed'], '0', '1', '0');
        }
        if (array_key_exists('Verified', $FormPostValues)) {
            $FormPostValues['Verified'] = forceBool($FormPostValues['Verified'], '0', '1', '0');
        }
        // Do not allowing setting this via general save.
        unset($FormPostValues['Admin']);
        // This field is deprecated but included on user objects for backwards compatibility.
        // It will absolutely break if you try to save it back to the database.
        unset($FormPostValues['AllIPAddresses']);
        if (array_key_exists('Gender', $FormPostValues)) {
            $FormPostValues['Gender'] = self::fixGender($FormPostValues['Gender']);
        }
        if (array_key_exists('DateOfBirth', $FormPostValues) && $FormPostValues['DateOfBirth'] == '0-00-00') {
            $FormPostValues['DateOfBirth'] = null;
        }
        $UserID = val('UserID', $FormPostValues);
        $User = [];
        $Insert = $UserID > 0 ? false : true;
        if ($Insert) {
            $this->addInsertFields($FormPostValues);
        } else {
            $this->addUpdateFields($FormPostValues);
            $User = $this->getID($UserID, DATASET_TYPE_ARRAY);
            if (!$User) {
                $User = [];
            }
            // Block banning the superadmin or System accounts
            if (val('Admin', $User) == 2 && val('Banned', $FormPostValues)) {
                $this->Validation->addValidationResult('Banned', 'You may not ban a System user.');
            } elseif (val('Admin', $User) && val('Banned', $FormPostValues)) {
                $this->Validation->addValidationResult('Banned', 'You may not ban a user with the Admin flag set.');
            }
        }
        $this->EventArguments['FormPostValues'] = $FormPostValues;
        $this->fireEvent('BeforeSaveValidation');
        $RecordRoleChange = true;
        if ($UserID && val('FixUnique', $Settings)) {
            $UniqueValid = $this->validateUniqueFields(val('Name', $FormPostValues), val('Email', $FormPostValues), $UserID, true);
            if (!$UniqueValid['Name']) {
                unset($FormPostValues['Name']);
            }
            if (!$UniqueValid['Email']) {
                unset($FormPostValues['Email']);
            }
            $UniqueValid = true;
        } else {
            $UniqueValid = $this->validateUniqueFields(val('Name', $FormPostValues), val('Email', $FormPostValues), $UserID);
        }
        // Add & apply any extra validation rules:
        if (array_key_exists('Email', $FormPostValues) && val('ValidateEmail', $Settings, true)) {
            $this->Validation->applyRule('Email', 'Email');
        }
        if ($this->validate($FormPostValues, $Insert) && $UniqueValid) {
            // All fields on the form that need to be validated (including non-schema field rules defined above)
            $Fields = $this->Validation->validationFields();
            $RoleIDs = val('RoleID', $Fields, 0);
            $Username = val('Name', $Fields);
            $Email = val('Email', $Fields);
            // Only fields that are present in the schema
            $Fields = $this->Validation->schemaValidationFields();
            // Remove the primary key from the fields collection before saving.
            unset($Fields[$this->PrimaryKey]);
            if (!$Insert && array_key_exists('Password', $Fields) && val('HashPassword', $Settings, true)) {
                // Encrypt the password for saving only if it won't be hashed in _Insert()
                $PasswordHash = new Gdn_PasswordHash();
                $Fields['Password'] = $PasswordHash->hashPassword($Fields['Password']);
                $Fields['HashMethod'] = 'Vanilla';
            }
            // Check for email confirmation.
            if (self::requireConfirmEmail() && !val('NoConfirmEmail', $Settings)) {
                // Email address has changed
                if (isset($Fields['Email']) && (array_key_exists('Confirmed', $Fields) && $Fields['Confirmed'] == 0 || $UserID == Gdn::session()->UserID && $Fields['Email'] != Gdn::session()->User->Email && !Gdn::session()->checkPermission('Garden.Users.Edit'))) {
                    $Attributes = val('Attributes', Gdn::session()->User);
                    if (is_string($Attributes)) {
                        $Attributes = dbdecode($Attributes);
                    }
                    $ConfirmEmailRoleID = RoleModel::getDefaultRoles(RoleModel::TYPE_UNCONFIRMED);
                    if (!empty($ConfirmEmailRoleID)) {
                        // The confirm email role is set and it exists so go ahead with the email confirmation.
                        $NewKey = randomString(8);
                        $EmailKey = touchValue('EmailKey', $Attributes, $NewKey);
                        $Fields['Attributes'] = dbencode($Attributes);
                        $Fields['Confirmed'] = 0;
                    }
                }
            }
            $this->EventArguments['SaveRoles'] =& $SaveRoles;
            $this->EventArguments['RoleIDs'] =& $RoleIDs;
            $this->EventArguments['Fields'] =& $Fields;
            $this->fireEvent('BeforeSave');
            $User = array_merge($User, $Fields);
            // Check the validation results again in case something was added during the BeforeSave event.
            if (count($this->Validation->results()) == 0) {
                // Encode any IP fields that aren't already encoded.
                $ipCols = ['InsertIPAddress', 'LastIPAddress', 'UpdateIPAddress'];
                foreach ($ipCols as $col) {
                    if (isset($Fields[$col]) && filter_var($Fields[$col], FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 | FILTER_FLAG_IPV6)) {
                        $Fields[$col] = ipEncode($Fields[$col]);
                    }
                }
                unset($col);
                // If the primary key exists in the validated fields and it is a
                // numeric value greater than zero, update the related database row.
                if ($UserID > 0) {
                    // If they are changing the username & email, make sure they aren't
                    // already being used (by someone other than this user)
                    if (val('Name', $Fields, '') != '' || val('Email', $Fields, '') != '') {
                        if (!$this->validateUniqueFields($Username, $Email, $UserID)) {
                            return false;
                        }
                    }
                    if (array_key_exists('Attributes', $Fields) && !is_string($Fields['Attributes'])) {
                        $Fields['Attributes'] = dbencode($Fields['Attributes']);
                    }
                    // Perform save DB operation
                    $this->SQL->put($this->Name, $Fields, [$this->PrimaryKey => $UserID]);
                    // Record activity if the person changed his/her photo.
                    $Photo = val('Photo', $FormPostValues);
                    if ($Photo !== false) {
                        if (val('CheckExisting', $Settings)) {
                            $User = $this->getID($UserID);
                            $OldPhoto = val('Photo', $User);
                        }
                        if (isset($OldPhoto) && $OldPhoto != $Photo) {
                            if (isUrl($Photo)) {
                                $PhotoUrl = $Photo;
                            } else {
                                $PhotoUrl = Gdn_Upload::url(changeBasename($Photo, 'n%s'));
                            }
                            $ActivityModel = new ActivityModel();
                            if ($UserID == Gdn::session()->UserID) {
                                $HeadlineFormat = t('HeadlineFormat.PictureChange', '{RegardingUserID,You} changed {ActivityUserID,your} profile picture.');
                            } else {
                                $HeadlineFormat = t('HeadlineFormat.PictureChange.ForUser', '{RegardingUserID,You} changed the profile picture for {ActivityUserID,user}.');
                            }
                            $ActivityModel->save(['ActivityUserID' => $UserID, 'RegardingUserID' => Gdn::session()->UserID, 'ActivityType' => 'PictureChange', 'HeadlineFormat' => $HeadlineFormat, 'Story' => img($PhotoUrl, ['alt' => t('Thumbnail')])]);
                        }
                    }
                } else {
                    $RecordRoleChange = false;
                    if (!$this->validateUniqueFields($Username, $Email)) {
                        return false;
                    }
                    // Define the other required fields:
                    $Fields['Email'] = $Email;
                    $Fields['Roles'] = $RoleIDs;
                    // Make sure that the user is assigned to one or more roles:
                    $SaveRoles = false;
                    // And insert the new user.
                    $UserID = $this->insertInternal($Fields, $Settings);
                    if ($UserID > 0) {
                        // Report that the user was created.
                        $ActivityModel = new ActivityModel();
                        $ActivityModel->save(['ActivityType' => 'Registration', 'ActivityUserID' => $UserID, 'HeadlineFormat' => t('HeadlineFormat.Registration', '{ActivityUserID,You} joined.'), 'Story' => t('Welcome Aboard!')], false, ['GroupBy' => 'ActivityTypeID']);
                        // Report the creation for mods.
                        $ActivityModel->save(['ActivityType' => 'Registration', 'ActivityUserID' => Gdn::session()->UserID, 'RegardingUserID' => $UserID, 'NotifyUserID' => ActivityModel::NOTIFY_MODS, 'HeadlineFormat' => t('HeadlineFormat.AddUser', '{ActivityUserID,user} added an account for {RegardingUserID,user}.')]);
                    }
                }
                // Now update the role settings if necessary.
                if ($SaveRoles) {
                    // If no RoleIDs were provided, use the system defaults
                    if (!is_array($RoleIDs)) {
                        $RoleIDs = RoleModel::getDefaultRoles(RoleModel::TYPE_MEMBER);
                    }
                    $this->saveRoles($UserID, $RoleIDs, $RecordRoleChange);
                }
                // Send the confirmation email.
                if (isset($EmailKey)) {
                    if (!is_array($User)) {
                        $User = $this->getID($UserID, DATASET_TYPE_ARRAY);
                    }
                    $this->sendEmailConfirmationEmail($User, true);
                }
                $this->EventArguments['UserID'] = $UserID;
                $this->fireEvent('AfterSave');
            } else {
                $UserID = false;
            }
        } else {
            $UserID = false;
        }
        // Clear cached user data
        if (!$Insert && $UserID) {
            $this->clearCache($UserID, ['user']);
        }
        return $UserID;
    }

Usage Example

Example #1
0
 function create($name)
 {
     $this->user->setName($name);
     $this->user->set('role', 'user');
     $this->user->set('email', $name . '@service.com');
     $this->user->save();
     return true;
 }
All Usage Examples Of UserModel::save
UserModel