/** * Saves a user, or registers a new one. * * @param UserModel $user * @throws Exception * @return bool */ public function saveUser(UserModel $user) { if (($isNewUser = !$user->id) == false) { $userRecord = $this->_getUserRecordById($user->id); if (!$userRecord) { throw new Exception(Craft::t('No user exists with the ID “{id}”', array('id' => $user->id))); } $oldUsername = $userRecord->username; } else { $userRecord = new UserRecord(); } // Set the user record attributes $userRecord->username = $user->username; $userRecord->firstName = $user->firstName; $userRecord->lastName = $user->lastName; $userRecord->email = $user->email; $userRecord->admin = $user->admin; $userRecord->passwordResetRequired = $user->passwordResetRequired; $userRecord->preferredLocale = $user->preferredLocale; $userRecord->validate(); $user->addErrors($userRecord->getErrors()); // If newPassword is set at all, even to an empty string, validate & set it. if ($user->newPassword !== null) { $this->_setPasswordOnUserRecord($user, $userRecord); } if (!$user->hasErrors()) { if ($user->verificationRequired) { $userRecord->status = $user->status = UserStatus::Pending; $unhashedVerificationCode = $this->_setVerificationCodeOnUserRecord($userRecord); } // Fire an 'onBeforeSaveUser' event $this->onBeforeSaveUser(new Event($this, array('user' => $user, 'isNewUser' => $isNewUser))); if ($isNewUser) { // Create the entry record $elementRecord = new ElementRecord(); $elementRecord->type = ElementType::User; $elementRecord->save(); // Now that we have the entry ID, save it on everything else $user->id = $elementRecord->id; $userRecord->id = $elementRecord->id; } $userRecord->save(false); if (!$isNewUser) { // Has the username changed? if ($user->username != $oldUsername) { // Rename the user's photo directory $oldFolder = craft()->path->getUserPhotosPath() . $oldUsername; $newFolder = craft()->path->getUserPhotosPath() . $user->username; if (IOHelper::folderExists($newFolder)) { IOHelper::deleteFolder($newFolder); } if (IOHelper::folderExists($oldFolder)) { IOHelper::rename($oldFolder, $newFolder); } } } // Update the search index craft()->search->indexElementAttributes($user); if ($isNewUser && $user->verificationRequired) { craft()->templates->registerTwigAutoloader(); craft()->email->sendEmailByKey($user, 'account_activation', array('link' => new \Twig_Markup(craft()->config->getActivateAccountPath($unhashedVerificationCode, $userRecord->uid), craft()->templates->getTwig()->getCharset()))); } // Fire an 'onSaveUser' event $this->onSaveUser(new Event($this, array('user' => $user, 'isNewUser' => $isNewUser))); return true; } else { return false; } }
/** * Saves a new or existing user. * * ```php * $user = new UserModel(); * $user->username = '******'; * $user->firstName = 'Tom'; * $user->lastName = 'Foolery'; * $user->email = '*****@*****.**'; * * $user->getContent()->birthYear = 1812; * * $success = craft()->users->saveUser($user); * * if (!$success) * { * Craft::log('Couldn’t save the user "'.$user->username.'"', LogLevel::Error); * } * ``` * * @param UserModel $user The user to be saved. * * @throws \Exception * @return bool Whether the user was saved successfully. */ public function saveUser(UserModel $user) { $isNewUser = !$user->id; if (!$isNewUser) { $userRecord = $this->_getUserRecordById($user->id); if (!$userRecord) { throw new Exception(Craft::t('No user exists with the ID “{id}”.', array('id' => $user->id))); } $oldUsername = $userRecord->username; } else { $userRecord = new UserRecord(); $userRecord->pending = true; } // Set the user record attributes $userRecord->username = $user->username; $userRecord->firstName = $user->firstName; $userRecord->lastName = $user->lastName; $userRecord->photo = $user->photo; $userRecord->email = $user->email; $userRecord->admin = $user->admin; $userRecord->client = $user->client; $userRecord->passwordResetRequired = $user->passwordResetRequired; $userRecord->preferredLocale = $user->preferredLocale; $userRecord->weekStartDay = $user->weekStartDay; $userRecord->unverifiedEmail = $user->unverifiedEmail; $userRecord->validate(); $user->addErrors($userRecord->getErrors()); if (craft()->getEdition() == Craft::Pro) { // Validate any content. if (!craft()->content->validateContent($user)) { $user->addErrors($user->getContent()->getErrors()); } } // If newPassword is set at all, even to an empty string, validate & set it. if ($user->newPassword !== null) { $this->_setPasswordOnUserRecord($user, $userRecord); } if ($user->hasErrors()) { return false; } $transaction = craft()->db->getCurrentTransaction() === null ? craft()->db->beginTransaction() : null; try { // Fire an 'onBeforeSaveUser' event $event = new Event($this, array('user' => $user, 'isNewUser' => $isNewUser)); $this->onBeforeSaveUser($event); // Is the event is giving us the go-ahead? if ($event->performAction) { // Save the element $success = craft()->elements->saveElement($user, false); // If it didn't work, rollback the transaction in case something changed in onBeforeSaveUser if (!$success) { if ($transaction !== null) { $transaction->rollback(); } return false; } // Now that we have an element ID, save it on the other stuff if ($isNewUser) { $userRecord->id = $user->id; } $userRecord->save(false); if (!$isNewUser) { // Has the username changed? if ($user->username != $oldUsername) { // Rename the user's photo directory $oldFolder = craft()->path->getUserPhotosPath() . $oldUsername; $newFolder = craft()->path->getUserPhotosPath() . $user->username; if (IOHelper::folderExists($newFolder)) { IOHelper::deleteFolder($newFolder); } if (IOHelper::folderExists($oldFolder)) { IOHelper::rename($oldFolder, $newFolder); } } } } else { $success = false; } // Commit the transaction regardless of whether we saved the user, in case something changed // in onBeforeSaveUser if ($transaction !== null) { $transaction->commit(); } } catch (\Exception $e) { if ($transaction !== null) { $transaction->rollback(); } throw $e; } if ($success) { // Fire an 'onSaveUser' event $this->onSaveUser(new Event($this, array('user' => $user, 'isNewUser' => $isNewUser))); if ($this->hasEventHandler('onSaveProfile')) { // Fire an 'onSaveProfile' event (deprecated) $this->onSaveProfile(new Event($this, array('user' => $user))); } // They got unsuspended if ($userRecord->suspended == true && $user->suspended == false) { $this->unsuspendUser($user); } else { if ($userRecord->suspended == false && $user->suspended == true) { $this->suspendUser($user); } } // They got activated if ($userRecord->pending == true && $user->pending == false) { $this->activateUser($user); } } return $success; }
/** * Saves a new or existing user. * * ```php * $user = new UserModel(); * $user->username = '******'; * $user->firstName = 'Tom'; * $user->lastName = 'Foolery'; * $user->email = '*****@*****.**'; * * $user->getContent()->birthYear = 1812; * * $success = craft()->users->saveUser($user); * * if (!$success) * { * Craft::log('Couldn’t save the user "'.$user->username.'"', LogLevel::Error); * } * ``` * * @param UserModel $user The user to be saved. * * @throws \Exception * @return bool Whether the user was saved successfully. */ public function saveUser(UserModel $user) { $isNewUser = !$user->id; if (!$isNewUser) { $userRecord = $this->_getUserRecordById($user->id); if (!$userRecord) { throw new Exception(Craft::t('No user exists with the ID “{id}”', array('id' => $user->id))); } $oldUsername = $userRecord->username; } else { $userRecord = new UserRecord(); } // Set the user record attributes $userRecord->username = $user->username; $userRecord->firstName = $user->firstName; $userRecord->lastName = $user->lastName; $userRecord->photo = $user->photo; $userRecord->email = $user->email; $userRecord->admin = $user->admin; $userRecord->client = $user->client; $userRecord->passwordResetRequired = $user->passwordResetRequired; $userRecord->preferredLocale = $user->preferredLocale; $userRecord->status = $user->status; $userRecord->unverifiedEmail = $user->unverifiedEmail; $userRecord->validate(); $user->addErrors($userRecord->getErrors()); if (craft()->getEdition() == Craft::Pro) { // Validate any content. if (!craft()->content->validateContent($user)) { $user->addErrors($user->getContent()->getErrors()); } } // If newPassword is set at all, even to an empty string, validate & set it. if ($user->newPassword !== null) { $this->_setPasswordOnUserRecord($user, $userRecord, false); } if ($user->hasErrors()) { return false; } $transaction = craft()->db->getCurrentTransaction() === null ? craft()->db->beginTransaction() : null; try { // If we're going through account verification, in whatever form if ($user->unverifiedEmail) { $unhashedVerificationCode = $this->_setVerificationCodeOnUserRecord($userRecord); } // Set a default status of pending, if one wasn't supplied. if (!$user->status) { $user->status = UserStatus::Pending; } // Fire an 'onBeforeSaveUser' event $this->onBeforeSaveUser(new Event($this, array('user' => $user, 'isNewUser' => $isNewUser))); if (craft()->elements->saveElement($user, false)) { // Now that we have an element ID, save it on the other stuff if ($isNewUser) { $userRecord->id = $user->id; } $userRecord->save(false); if ($user->unverifiedEmail) { // Temporarily set the unverified email on the UserModel so the verification email goes to the // right place $originalEmail = $user->email; $user->email = $user->unverifiedEmail; try { craft()->email->sendEmailByKey($user, $isNewUser ? 'account_activation' : 'verify_new_email', array('link' => TemplateHelper::getRaw(craft()->config->getActivateAccountPath($unhashedVerificationCode, $userRecord->uid)))); } catch (\phpmailerException $e) { craft()->userSession->setError(Craft::t('User saved, but couldn’t send verification email. Check your email settings.')); } $user->email = $originalEmail; } if (!$isNewUser) { // Has the username changed? if ($user->username != $oldUsername) { // Rename the user's photo directory $oldFolder = craft()->path->getUserPhotosPath() . $oldUsername; $newFolder = craft()->path->getUserPhotosPath() . $user->username; if (IOHelper::folderExists($newFolder)) { IOHelper::deleteFolder($newFolder); } if (IOHelper::folderExists($oldFolder)) { IOHelper::rename($oldFolder, $newFolder); } } } if ($transaction !== null) { $transaction->commit(); } } else { return false; } } catch (\Exception $e) { if ($transaction !== null) { $transaction->rollback(); } throw $e; } // If we've made it here, everything has been successful so far. // Fire an 'onSaveUser' event $this->onSaveUser(new Event($this, array('user' => $user, 'isNewUser' => $isNewUser))); if ($this->hasEventHandler('onSaveProfile')) { // Fire an 'onSaveProfile' event (deprecated) $this->onSaveProfile(new Event($this, array('user' => $user))); } return true; }