/** * 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(); } }
/** * 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); } }
/** * 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(); } }
/** * @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()); }
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]); }
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 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)); }
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)); }
/** * 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()))); }
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)); }
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 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)); } }