public function editAction($uid) { $user = User::findUserByID($uid); if (!$user) { return $this->forward('errors/show404'); } if ($user->uid != $this->getAuth()["uid"]) { if (!Group::Permission_CanEditAll($this->getAuth()["groupid"])) { return $this->forward('errors/show401'); } } $form = new ProfileForm($user->usercard); if ($this->request->isPost()) { $data = $this->request->getPost(); if (!$form->isValid($data, $user->usercard)) { foreach ($form->getMessages() as $message) { $this->flash->error($message); } } else { if ($user->save() == false) { foreach ($user->getMessages() as $message) { $this->flash->error($message); } } else { $form->clear(); $this->flash->success("Profile was updated successfully"); return $this->forward("profile/view/{$uid}"); } } } $this->view->form = $form; $this->view->user = $user; }
public function testUserEmailChange() { $newEmail = '*****@*****.**'; $model = $this->user; $profileForm = new ProfileForm(); $this->assertTrue($model !== NULL); $profileForm->load($model->id, true); $profileForm->email = $newEmail; // Verify that the profile form saves $this->assertTrue($profileForm->save()); // Verify that the base user model didn't change $model = $this->getUserModel(); $this->assertTrue($model->email == '*****@*****.**'); $newEmailModel = UserMetadata::model()->findByAttributes(array('user_id' => $this->user->id, 'key' => 'newEmailAddress')); // Verify that the new email is stored in the database $this->assertTrue($newEmailModel !== NULL); $this->assertTrue($newEmailModel->value == $newEmail); $key = UserMetadata::model()->findByAttributes(array('user_id' => $this->user->id, 'key' => 'newEmailAddressChangeKey')); $this->assertTrue($key !== NULL); $emailChangeForm = new EmailChangeForm(); $emailChangeForm->setUser($this->getUserModel()); $emailChangeForm->verificationKey = $key->value; $emailChangeForm->password = '******'; // Verify that the verification key works $this->assertTrue($emailChangeForm->validateVerificationKey()); // Veirfy that the email address changes $this->assertTrue($emailChangeForm->validate()); $this->assertTrue($emailChangeForm->save()); // Verify that the email has changed for the model now $model = Users::model()->findByAttributes(array('email' => '*****@*****.**')); $this->assertTrue($model->email == $newEmail); }
public function executeProfile(sfWebRequest $request) { $user = $this->getUser(); $i18n = $this->getContext()->getI18N(); $form = new ProfileForm($user->getProfile(), array('user' => $user)); if ($request->isMethod('post')) { $config = $request->getParameter('config'); $form->bind($config); if ($form->isValid()) { $form->save(); $culture = $config['language']; if (isset($config['country'])) { $country = $config['country']; } else { $country = null; } if ($country) { $culture .= '_' . $country; } $user->setCulture($culture); $user->info($i18n->__('Your settings were successfully saved.')); $this->redirect('@profile'); } else { $user->error($i18n->__('Settings could not be saved. Please, check entered values and try to correct them.'), false); } } $this->form = $form; }
/** * @dataProvider invalidDataProvider */ public function testInvalid($scenario, $attributes, $errors) { $form = new ProfileForm($scenario); $form->userIdentityClass = 'UserIdentity'; $form->setAttributes($attributes); $this->assertFalse($form->validate()); $this->assertEquals($errors, $form->getErrors()); }
/** Edit the user details */ public function editAction() { $form = new ProfileForm(); $form->removeElement('password'); $this->view->form = $form; if ($this->getRequest()->isPost() && $form->isValid($this->_request->getPost())) { if ($form->isValid($form->getValues())) { $where = array(); $where[] = $users->getAdapter()->quoteInto('id = ?', $this->getIdentityForForms()); $this->_users->update($form->getValues(), $where); $this->_flashMessenger->addMessage('You updated your profile successfully.'); $this->_redirect('/users/account/'); } else { $form->populate($form->getValues()); $this->_flashMessenger->addMessage('You have some errors with your submission.'); } } else { $id = (int) $this->getIdentityForForms(); if ($id > 0) { $user = $this->_users->fetchRow('id =' . $this->getIdentityForForms())->toArray(); if ($user) { $form->populate($user); } else { throw new Exception('No user account found with that id'); } } } }
public function run() { $user = $this->getController()->user; $form = new ProfileForm(); $formAttributes = $form->getAttributes(); unset($formAttributes['avatar'], $formAttributes['verifyCode']); $form->setAttributes($user->getAttributes(array_keys($formAttributes))); // Если у нас есть данные из POST - получаем их: if (($data = Yii::app()->getRequest()->getPost('ProfileForm')) !== null) { $transaction = Yii::app()->getDb()->beginTransaction(); try { $form->setAttributes($data); if ($form->validate()) { // Удаляем ненужные данные: unset($data['avatar']); // Заполняем модель данными: $user->setAttributes($data); // Если есть ошибки в профиле - перекинем их в форму if ($user->hasErrors()) { $form->addErrors($user->getErrors()); } // Если у нас есть дополнительные профили - проверим их foreach ((array) $this->getController()->module->profiles as $p) { $p->validate() || $form->addErrors($p->getErrors()); } // Если нет ошибок валидации: if ($form->hasErrors() === false) { Yii::log(Yii::t('UserModule.user', 'Profile for #{id}-{nick_name} was changed', ['{id}' => $user->id, '{nick_name}' => $user->email]), CLogger::LEVEL_INFO, UserModule::$logCategory); Yii::app()->getUser()->setFlash(yupe\widgets\YFlashMessages::SUCCESS_MESSAGE, Yii::t('UserModule.user', 'Your profile was changed successfully')); if (($uploadedFile = CUploadedFile::getInstance($form, 'avatar')) !== null) { $user->changeAvatar($uploadedFile); } elseif ($form->use_gravatar) { $user->removeOldAvatar(); } $user->save(); // И дополнительные профили, если они есть if (is_array($this->getController()->module->profiles)) { foreach ($this->getController()->module->profiles as $k => $p) { $p->save(false); } } Yii::app()->getUser()->setFlash(yupe\widgets\YFlashMessages::SUCCESS_MESSAGE, Yii::t('UserModule.user', 'Profile was updated')); $transaction->commit(); $this->getController()->redirect(['/user/profile/profile']); } else { Yii::log(Yii::t('UserModule.user', 'Error when save profile! #{id}', ['{id}' => $user->id]), CLogger::LEVEL_ERROR, UserModule::$logCategory); } } } catch (Exception $e) { $transaction->rollback(); Yii::app()->getUser()->setFlash(yupe\widgets\YFlashMessages::ERROR_MESSAGE, $e->getMessage()); } } $this->getController()->render('profile', ['model' => $form, 'module' => Yii::app()->getModule('user'), 'user' => $user]); }
/** * Validate and save changes to user's profile. */ function saveProfile() { $this->validate(); $this->setupTemplate(); $dataModified = false; import('user.form.ProfileForm'); $profileForm = new ProfileForm(); $profileForm->readInputData(); if (Request::getUserVar('uploadProfileImage')) { if (!$profileForm->uploadProfileImage()) { $profileForm->addError('profileImage', Locale::translate('user.profile.form.profileImageInvalid')); } $dataModified = true; } else { if (Request::getUserVar('deleteProfileImage')) { $profileForm->deleteProfileImage(); $dataModified = true; } } if (!$dataModified && $profileForm->validate()) { $profileForm->execute(); Request::redirect(null, null, Request::getRequestedPage()); } else { $profileForm->display(); } }
/** * Validate and save changes to user's profile. * @param $args array * @param $request PKPRequest */ function saveProfile($args, &$request) { $this->validate(); $this->setupTemplate($request); $dataModified = false; import('classes.user.form.ProfileForm'); $profileForm = new ProfileForm(); $profileForm->readInputData(); if ($request->getUserVar('uploadProfileImage')) { if (!$profileForm->uploadProfileImage()) { $profileForm->addError('profileImage', __('user.profile.form.profileImageInvalid')); } $dataModified = true; } else { if ($request->getUserVar('deleteProfileImage')) { $profileForm->deleteProfileImage(); $dataModified = true; } } if (!$dataModified && $profileForm->validate()) { $profileForm->execute(); $request->redirect(null, $request->getRequestedPage()); } else { $profileForm->display(); } }
public function actionIndex() { $user = User::model()->findByPk(Yii::app()->user->id); $form = new ProfileForm(); if (isset($_POST['ProfileForm'])) { $form->attributes = $_POST['ProfileForm']; $form->newpassword_repeat = $_POST['ProfileForm']['newpassword_repeat']; if ($form->save()) { Yii::app()->user->setFlash('success', 'Your information has been successfully changed'); } else { Yii::app()->user->setFlash('danger', 'There was an error updating your information'); } } $this->render('index', array('user' => $user, 'profileform' => $form)); }
/** * Send a new verification email to the user */ public function actionResend() { $model = new ProfileForm(); $model->load(Yii::app()->user->id); // If we don't have one on file, then someone the user got to a page they shouldn't have gotten to // Seamlessly redirect them back if ($model->getNewEmail() == NULL) { $this->redirect(Yii::app()->user->returnUrl); } if ($model->sendVerificationEmail()) { Yii::app()->user->setFlash('success', Yii::t('ciims.controllers.Profile', 'A new verification email has been resent to {{user}}. Please check your email address.', array('{{user}}' => $model->getNewEmail()))); } else { Yii::app()->user->setFlash('error', Yii::t('ciims.controllers.Profile', 'There was an error resending the verification email. Please try again later.')); } $this->redirect($this->createUrl('profile/edit')); }
/** * Validate and save changes to user's profile. */ function saveProfile($args, $request) { $this->setupTemplate($request); $dataModified = false; $user = $request->getUser(); import('classes.user.form.ProfileForm'); $profileForm = new ProfileForm($user); $profileForm->readInputData(); if ($request->getUserVar('uploadProfileImage')) { if (!$profileForm->uploadProfileImage()) { $profileForm->addError('profileImage', __('user.profile.form.profileImageInvalid')); } $dataModified = true; } else { if ($request->getUserVar('deleteProfileImage')) { $profileForm->deleteProfileImage(); $dataModified = true; } } if (!$dataModified && $profileForm->validate()) { $profileForm->execute($request); $userGroupDao = DAORegistry::getDAO('UserGroupDAO'); $context = $request->getContext(); $userGroups = $userGroupDao->getByUserId($user->getId(), $context->getId()); while ($userGroup = $userGroups->next()) { if ($userGroup->getRoleId() != ROLE_ID_READER) { $request->redirect(null, 'dashboard'); } } $request->redirect(null, 'index'); } else { $profileForm->display($request); } }
public function actionProfile($id) { $model = new ProfileForm(); $model->setType($id); if (isset($_POST['ProfileForm'])) { $model->attributes = $_POST['ProfileForm']; if ($model->validate() && $model->change()) { if ($id == 'pass') { Yii::app()->user->setFlash('notify', array('type' => 'success', 'message' => Yii::t('user', 'Password successfully changed'))); } else { Yii::app()->user->setFlash('notifyTO', array('type' => 'success', 'message' => Yii::t('user', 'Time zone successfully changed'))); } $this->render('profile', array('model' => $model)); Yii::app()->end(); } } $this->render('profile', array('model' => $model)); }
public function actionUpdate() { $formModel = new ProfileForm(); if (isset($_POST['ProfileForm'])) { $allFieldTypes = $formModel->getAllFieldTypes(); foreach ($allFieldTypes as $fieldName => $fieldType) { $formModel->{$fieldName} = $_POST['ProfileForm'][$fieldName]; } if ($formModel->validate()) { $model = new Profile(); $data = array(); foreach ($allFieldTypes as $fieldName => $fieldType) { $data[$fieldName] = array('value' => $formModel->{$fieldName}); } $model->setProfileFields(CassandraUtil::import(Yii::app()->user->getId())->__toString(), User::PREFIX, $data); } } $this->render('update', array('model' => $formModel)); }
/** * Allows the users to update their profiles * * @access public * @return void */ public function editAction() { $this->title = 'Edit your profile'; $form = new ProfileForm(); $userModel = new BackofficeUser(); if ($this->getRequest()->isPost()) { if ($form->isValid($this->getRequest()->getPost())) { $userModel->updateProfile($form->getValues()); $this->_helper->FlashMessenger(array('msg-success' => 'Your profile was successfully updated.')); $this->_redirect('/profile/edit/'); } } else { $user = Zend_Auth::getInstance()->getIdentity(); $row = $userModel->findById($user->id); $form->populate($row->toArray()); $this->view->item = $row; } $this->view->form = $form; }
public function save($con = null) { $values = $this->getValues(); $presetList = opToolkit::getPresetProfileList(); $presetName = $values['preset']; $preset = $presetList[$presetName]; $values = $this->mergePresetAndValues($preset, $values); $values['name'] = 'op_preset_' . $values['name']; unset($values['preset'], $values['choices'], $values['caption']); $this->values = $values; parent::save($con); }
/** * * @param sfWebRequest $request * @param ProfileForm $form */ protected function processEdit(sfWebRequest $request, ProfileForm $form) { $form->bind($request->getParameter('profile')); if ($form->isValid()) { $values = $form->getValues(); $user = $this->getUser()->getGuardUser(); if ($user->checkPassword($values['current_password'])) { // Set new password into sfGuardUser table if (!empty($values['new_password']) && $values['new_password'] == $values['confirm_new_password']) { $user->setPassword($values['new_password']); } $user->setFirstName($values['first_name']); $user->setLastName($values['last_name']); $user->setEmailAddress($values['email']); $user->save(); // Set referer $this->getUser()->setReferer($request->getUri()); // Redirect to referer $this->redirect($this->getUser()->getReferer()); } } }
public function run() { if (Yii::app()->user->isAuthenticated() === false) { $this->controller->redirect(Yii::app()->user->loginUrl); } if (($user = Yii::app()->user->getProfile()) === null) { Yii::app()->user->setFlash(yupe\widgets\YFlashMessages::ERROR_MESSAGE, Yii::t('UserModule.user', 'User not found.')); Yii::app()->user->logout(); $this->controller->redirect((array) '/user/account/login'); } $profile = $user->profile; $profile->scenario = 'edit-profile'; $form = new ProfileForm(); $formAttributes = $form->getAttributes(); $form->setAttributes($profile->getAttributes(array_keys($formAttributes))); $module = Yii::app()->getModule('user'); // Если у нас есть данные из POST - получаем их: if (($data = Yii::app()->getRequest()->getPost('ProfileForm')) !== null) { $transaction = Yii::app()->db->beginTransaction(); try { $form->setAttributes($data); if ($form->validate()) { // Заполняем модель данными: $profile->setAttributes($data); // Если есть ошибки в профиле - перекинем их в форму if ($profile->hasErrors()) { $form->addErrors($profile->getErrors()); } // Если нет ошибок валидации: if ($form->hasErrors() === false) { // Сохраняем профиль $profile->save(); Yii::app()->user->setFlash(yupe\widgets\YFlashMessages::SUCCESS_MESSAGE, Yii::t('UserModule.user', 'Your profile was changed successfully')); $transaction->commit(); $this->controller->redirect(array('/user/account/profile')); } } } catch (Exception $e) { $transaction->rollback(); Yii::app()->user->setFlash(yupe\widgets\YFlashMessages::ERROR_MESSAGE, $e->getMessage()); } } $this->controller->render('profile', array('model' => $form, 'user' => $user)); }
/** * Edit action, Allow the User to update his profil * @author EL GUENNUNI Sohaib s.elguennuni@gmail.com * @param <empty> * @return <empty> */ public function editAction() { $this->title = 'Edit your account'; $form = new ProfileForm(); if ($this->getRequest()->isPost()) { if ($form->isValid($this->getRequest()->getPost())) { $data = $form->getValues(); $value_id = $this->_rvCityModel->searchCity($form->getValue('name')); if ($value_id) { $data['rv_city_id'] = $value_id; } else { $data['rv_city_id'] = $this->_rvCityModel->addCity($form->getValue('name')); } $this->_memberModel->updateMember($data); $this->_redirect($this->view->url(array('module' => 'frontend', 'controller' => 'account', 'action' => 'display'), 'default', true)); } } else { $row = $this->_memberModel->getMember($this->_idMember); $form->populate($row->toArray()); $this->view->item = $row; } $this->view->form = $form; }
$this->bio = new Phorm_Field_Textarea('Bio', 5, 40, array('required')); // Add some help text $this->email->help_text('We will never give out your email address.'); } protected function define_fieldsets() { $this->fieldsets = array(new Phorm_Fieldset('name', 'Name', array('user_id', 'first_name', 'last_name')), new Phorm_Fieldset('extra', 'Extra', array('email', 'url', 'bio'))); } public function report() { var_dump($this->cleaned_data()); } } // Set up the form $post_id = 42; $form = new ProfileForm('post', false, array('post_id' => $post_id)); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title>Profile Form example for Phorm</title> <link rel="stylesheet" href="assets/style.css" type="text/css" /> </head> <body> <?php echo $form->open(); ?> <h1>Profile Data</h1> <?php if ($form->has_errors()) {
protected function registerLocalProfile(ProfileForm $localProfile, HybridauthForm $remoteLogin) { if (isset($_POST['ProfileForm'])) { $localProfile->setAttributes($_POST['ProfileForm']); if ($localProfile->register()) { if ($this->module->requireVerifiedEmail) { if ($this->sendEmail($localProfile, 'verify')) { Yii::app()->user->setFlash('success', Yii::t('UsrModule.usr', 'An email containing further instructions has been sent to provided email address.')); } else { Yii::app()->user->setFlash('error', Yii::t('UsrModule.usr', 'Failed to send an email.') . ' ' . Yii::t('UsrModule.usr', 'Try again or contact the site administrator.')); } } // don't forget to associate the new profile with remote provider if (!$remoteLogin->associate($localProfile->getIdentity()->getId())) { Yii::app()->user->setFlash('error', Yii::t('UsrModule.usr', 'Failed to associate current user with {provider}.', array('{provider}' => $remoteLogin->provider))); $this->redirect('login'); } if ($localProfile->getIdentity()->isActive()) { // don't use the $localProfile->login() method because there is no password set so we can't authenticate this identity if (Yii::app()->user->login($localProfile->getIdentity(), 0)) { $this->afterLogin(); } else { Yii::app()->user->setFlash('error', Yii::t('UsrModule.usr', 'Failed to log in.') . ' ' . Yii::t('UsrModule.usr', 'Try again or contact the site administrator.')); } } else { if (!Yii::app()->user->hasFlash('success')) { Yii::app()->user->setFlash('success', Yii::t('UsrModule.usr', 'Please wait for the account to be activated. A notification will be send to provided email address.')); } $this->redirect(array('login')); } } } else { $profile = $remoteLogin->getHybridAuthAdapter()->getUserProfile(); $email = $profile->emailVerifier !== null ? $profile->emailVerifier : $profile->email; $localProfile->setAttributes(array('username' => $email, 'email' => $email, 'firstName' => $profile->firstName, 'lastName' => $profile->lastName)); } return $localProfile; }
public function actionProfile($update = false) { if (Yii::app()->user->isGuest) { $this->redirect(array('login')); } $model = new ProfileForm(); $model->setAttributes($model->getIdentity()->getAttributes()); $passwordForm = new PasswordForm(); if (isset($_POST['ajax']) && $_POST['ajax'] === 'profile-form') { $models = array($model); if (isset($_POST['PasswordForm']) && trim($_POST['PasswordForm']['newPassword']) !== '') { $models[] = $passwordForm; } echo CActiveForm::validate($models); Yii::app()->end(); } $flashes = array('success' => array(), 'error' => array()); if (isset($_POST['PasswordForm']) && trim($_POST['PasswordForm']['newPassword']) !== '') { $passwordForm->setAttributes($_POST['PasswordForm']); if ($passwordForm->validate()) { if ($passwordForm->resetPassword($model->getIdentity())) { $flashes['success'][] = Yii::t('UsrModule.usr', 'Changes have been saved successfully.'); } else { $flashes['error'][] = Yii::t('UsrModule.usr', 'Failed to change password.'); } } } if (isset($_POST['ProfileForm']) && empty($flashes['error'])) { $model->setAttributes($_POST['ProfileForm']); if ($model->validate()) { $oldEmail = $model->getIdentity()->getEmail(); if ($model->save()) { if ($this->module->requireVerifiedEmail && $oldEmail != $model->email) { if ($this->sendEmail($model, 'verify')) { $flashes['success'][] = Yii::t('UsrModule.usr', 'An email containing further instructions has been sent to provided email address.'); } else { $flashes['error'][] = Yii::t('UsrModule.usr', 'Failed to send an email.') . ' ' . Yii::t('UsrModule.usr', 'Try again or contact the site administrator.'); } } $flashes['success'][] = Yii::t('UsrModule.usr', 'Changes have been saved successfully.'); if (!empty($flashes['success'])) { Yii::app()->user->setFlash('success', implode('<br/>', $flashes['success'])); } if (!empty($flashes['error'])) { Yii::app()->user->setFlash('error', implode('<br/>', $flashes['error'])); } $this->redirect(array('profile')); } else { $flashes['error'][] = Yii::t('UsrModule.usr', 'Failed to update profile.') . ' ' . Yii::t('UsrModule.usr', 'Try again or contact the site administrator.'); } } } if (!empty($flashes['success'])) { Yii::app()->user->setFlash('success', implode('<br/>', $flashes['success'])); } if (!empty($flashes['error'])) { Yii::app()->user->setFlash('error', implode('<br/>', $flashes['error'])); } if ($update) { $this->render('updateProfile', array('model' => $model, 'passwordForm' => $passwordForm)); } else { $this->render('viewProfile', array('model' => $model)); } }
/** * Updates the user profile from a form */ public function actionProfile() { if (Pii::guest()) { $this->_redirectError('You must be logged in to change your profile.'); } $_model = new ProfileForm(); if (isset($_POST, $_POST['ProfileForm'])) { $_model->attributes = $_POST['ProfileForm']; if ($_model->validate()) { try { $_userId = Session::getCurrentUserId(); $_result = Profile::changeProfile($_userId, $_model->attributes); if (Option::getBool($_result, 'success')) { Yii::app()->user->setFlash('profile-form', 'Your profile has been successfully updated.'); } } catch (\Exception $_ex) { $_model->addError(null, $_ex->getMessage()); } } } else { $_userId = Session::getCurrentUserId(); $_model->attributes = Profile::getProfile($_userId); } $this->render('profile', array('model' => $_model, 'backUrl' => $this->_getRedirectUrl(), 'session' => Session::generateSessionDataFromUser(Session::getCurrentUserId()))); }
$this->bio = new LargeTextField('Bio', 5, 40, array('required')); // Add some help text $this->email->set_help_text('We will never give out your email address.'); } protected function define_fieldsets() { $this->fieldsets = array(new Fieldset('name', 'Name', array('user_id', 'first_name', 'last_name')), new Fieldset('extra', 'Extra', array('email', 'url', 'bio'))); } public function report() { var_dump($this->cleaned_data()); } } // Set up the form $post_id = 42; $form = new ProfileForm(Phorm::POST, false, array('post_id' => $post_id)); // Check form validity $valid = $form->is_valid(); ?> <html> <body> <style> table { border: 1px solid #ccc; padding: 2px 4px; } th { vertical-align: top; text-align: right; } td { vertical-align: top; } thead th { text-align: center; font-size: 16pt; background-color: #ccc; } .phorm_error { color: #bb0000; font-size: 10pt; text-align: left; font-style: oblique; } .phorm_help { margin: 0; padding: 2px; font-size: 10pt; font-style: oblique; color: #666; } </style> <?php
protected function registerLocalProfile(ProfileForm $localProfile, HybridauthForm $remoteLogin, $localIdentity = false) { if (!isset($_POST['ProfileForm']) && $localIdentity === false) { $userIdentityClass = $localProfile->userIdentityClass; $remoteProfile = $remoteLogin->getHybridAuthAdapter()->getUserProfile(); $localProfile->setAttributes($userIdentityClass::getRemoteAttributes($remoteProfile)); $localProfile->validate(); return $localProfile; } if ($localIdentity !== false) { $userIdentityClass = $localProfile->userIdentityClass; $remoteProfile = $remoteLogin->getHybridAuthAdapter()->getUserProfile(); $localProfile->setAttributes($userIdentityClass::getRemoteAttributes($remoteProfile)); } if (isset($_POST['ProfileForm']) && is_array($_POST['ProfileForm'])) { $localProfile->setAttributes($_POST['ProfileForm']); } if (!$localProfile->validate()) { return $localProfile; } $trx = Yii::app()->db->beginTransaction(); if (!$localProfile->save($this->module->requireVerifiedEmail)) { $trx->rollback(); Yii::app()->user->setFlash('error', Yii::t('UsrModule.usr', 'Failed to register a new user.') . ' ' . Yii::t('UsrModule.usr', 'Try again or contact the site administrator.')); return $localProfile; } $trx->commit(); if ($this->module->requireVerifiedEmail) { if ($this->sendEmail($localProfile, 'verify')) { Yii::app()->user->setFlash('success', Yii::t('UsrModule.usr', 'An email containing further instructions has been sent to the provided email address.')); } else { Yii::app()->user->setFlash('error', Yii::t('UsrModule.usr', 'Failed to send an email.') . ' ' . Yii::t('UsrModule.usr', 'Try again or contact the site administrator.')); } } // don't forget to associate the new profile with remote provider if (!$remoteLogin->associate($localProfile->getIdentity()->getId())) { Yii::app()->user->setFlash('error', Yii::t('UsrModule.usr', 'Failed to associate current user with {provider}.', array('{provider}' => $remoteLogin->provider))); $this->redirect(array('login', 'provider' => $remoteLogin->provider)); } if ($localProfile->getIdentity()->isActive()) { // don't use the $localProfile->login() method because there is no password set so we can't authenticate this identity if (Yii::app()->user->login($localProfile->getIdentity(), 0)) { $this->afterLogin(); } else { Yii::app()->user->setFlash('error', Yii::t('UsrModule.usr', 'Failed to log in.') . ' ' . Yii::t('UsrModule.usr', 'Try again or contact the site administrator.')); } } else { if (!Yii::app()->user->hasFlash('success')) { Yii::app()->user->setFlash('success', Yii::t('UsrModule.usr', 'Please wait for the account to be activated. A notification will be send to provided email address.')); } $this->redirect(array('login', 'provider' => $remoteLogin->provider)); } return $localProfile; }
public function run() { if (($user = Yii::app()->user->getProfile()) === null) { Yii::app()->user->setFlash(yupe\widgets\YFlashMessages::ERROR_MESSAGE, Yii::t('UserModule.user', 'User not found.')); Yii::app()->user->logout(); $this->controller->redirect(array('/user/account/login')); } $form = new ProfileForm(); $formAttributes = $form->getAttributes(); unset($formAttributes['avatar'], $formAttributes['verifyCode']); $form->setAttributes($user->getAttributes(array_keys($formAttributes))); // Очищаем необходимые поля: $form->password = $form->cPassword = null; $module = Yii::app()->getModule('user'); // Если у нас есть данные из POST - получаем их: if (($data = Yii::app()->getRequest()->getPost('ProfileForm')) !== null) { $transaction = Yii::app()->db->beginTransaction(); try { $form->setAttributes($data); if ($form->validate()) { // Новый пароль? - ок, запоминаем: $newPass = isset($data['password']) ? $data['password'] : null; // Удаляем ненужные данные: unset($data['password'], $data['avatar']); // Запоминаем старую почту, $oldEmail = $user->email; // Заполняем модель данными: $user->setAttributes($data); // Новый пароль? - Генерируем хеш: if ($newPass) { $user->hash = Yii::app()->userManager->hasher->hashPassword($newPass); } // Если есть ошибки в профиле - перекинем их в форму if ($user->hasErrors()) { $form->addErrors($user->getErrors()); } // Если у нас есть дополнительные профили - проверим их foreach ((array) $this->controller->module->profiles as $p) { $p->validate() || $form->addErrors($p->getErrors()); } // Если нет ошибок валидации: if ($form->hasErrors() === false) { Yii::log(Yii::t('UserModule.user', 'Profile for #{id}-{nick_name} was changed', array('{id}' => $user->id, '{nick_name}' => $user->nick_name)), CLogger::LEVEL_INFO, UserModule::$logCategory); Yii::app()->user->setFlash(yupe\widgets\YFlashMessages::SUCCESS_MESSAGE, Yii::t('UserModule.user', 'Your profile was changed successfully')); if ($form->use_gravatar) { $user->avatar = null; } elseif (($uploadedFile = CUploadedFile::getInstance($form, 'avatar')) !== null) { $user->changeAvatar($uploadedFile); } // Сохраняем профиль $user->save(); // И дополнительные профили, если они есть if (is_array($this->controller->module->profiles)) { foreach ($this->controller->module->profiles as $k => $p) { $p->save(false); } } Yii::app()->user->setFlash(yupe\widgets\YFlashMessages::SUCCESS_MESSAGE, Yii::t('UserModule.user', 'Profile was updated')); $transaction->commit(); // Если включена верификация при смене почты: if ($module->emailAccountVerification && $oldEmail != $form->email) { if (Yii::app()->userManager->changeUserEmail($user, $form->email)) { Yii::app()->user->setFlash(yupe\widgets\YFlashMessages::SUCCESS_MESSAGE, Yii::t('UserModule.user', 'You need to confirm your e-mail. Please check the mail!')); } } $this->controller->redirect(array('/user/account/profile')); } else { Yii::log(Yii::t('UserModule.user', 'Error when save profile! #{id}', array('{id}' => $user->id)), CLogger::LEVEL_ERROR, UserModule::$logCategory); } } } catch (Exception $e) { $transaction->rollback(); Yii::app()->user->setFlash(yupe\widgets\YFlashMessages::ERROR_MESSAGE, $e->getMessage()); } } $this->controller->render('profile', array('model' => $form, 'module' => $module, 'user' => $user)); }