public function actionRegister() { $mediabroker = new Mediabroker(); $user = new User(); if (isset($_POST['User'])) { // populate input data to $a and $b $user->attributes = $_POST['User']; $mediabroker->wlabel_id = Yii::app()->user->getWhiteLabelId(); $user->wlabel_id = Yii::app()->user->getWhiteLabelId(); $user->type = UserType::TYPE_MEDIABROKER; $user->date_created = date("Y-m-d h:i:s"); $user->status = $this->getStatusAccordingToWLModeration(); //print_r("STATE: ".$user->status); $valid = true; $mediabroker->promocode = $this->generateUniquePromocode($user->first_name, $user->last_name); //print_r("PROMOCODE: ".$mediabroker->promocode); // validate BOTH $a and $b $valid = $mediabroker->validate() && $valid; $valid = $user->validate() && $valid; if ($user->password != '' && $user->password != $user->confirm_password) { $user->addError('password', 'You have to use the same password!'); $valid = false; } if ($valid) { $user->save(false); $mediabroker->user_id = $user->user_id; $mediabroker->save(false); $this->redirect(array('mediabroker/regsuccessful')); } } $this->render('register', array('user' => $user)); }
public function actionRegister() { $advertiser = new Advertiser(); $user = new User(); if (isset($_POST['User'])) { // populate input data to $a and $b $user->attributes = $_POST['User']; $advertiser->wlabel_id = Yii::app()->user->getWhiteLabelId(); $user->wlabel_id = Yii::app()->user->getWhiteLabelId(); $user->type = UserType::TYPE_ADVERTISER; $user->date_created = date("Y-m-d h:i:s"); $user->status = $this->getStatusAccordingToWLModeration(); $valid = true; // validate BOTH $a and $b $valid = $advertiser->validate() && $valid; $valid = $user->validate() && $valid; if ($user->password != '' && $user->password != $user->confirm_password) { $user->addError('password', 'You have to use the same password!'); $valid = false; } if ($valid) { $user->save(false); $advertiser->user_id = $user->user_id; $advertiser->mbroker_id = Utils::getReferingMediabroker(); $advertiser->save(false); $this->redirect(array('advertiser/regsuccessful')); } } $this->render('register', array('user' => $user)); }
/** * Creates a new model. * If creation is successful, the browser will be redirected to the 'view' page. */ public function actionCreate() { $model = new User(); // Uncomment the following line if AJAX validation is needed // $this->performAjaxValidation($model); if (isset($_POST['User'])) { $model->attributes = $_POST['User']; $model->id = $_POST['User']['kode_guru']; $model->password = md5('isims' . $_POST['User']['password']); try { if ($valid) { $model->save(); Yii::app()->user->setFlash('success', 'Data <strong>berhasil</strong> ditambahkan. Terima kasih'); $this->redirect(array('view', 'id' => $model->id)); } } catch (CDbException $e) { $model->addError(null, $e->getMessage()); } } $this->render('create', array('model' => $model)); }
/** * This is the default 'index' action that is invoked * when an action is not explicitly requested by users. */ public function actionIndex() { $form = new User(); $form->scenario = 'modify'; if (!empty($_POST['user'])) { $attributes = $_POST['user']; $form->attributes = $attributes; $form->validate(); $uid = Yii::app()->user->id; $user = User::model()->findByPk($uid); if (md5($attributes['oldpassword']) != $user->password) { $form->addError('oldpassword', '旧密码错误'); } else { $user->password = $attributes['password']; $user->save(); $this->refresh(); //弹出提示框 } } $data = array('form' => $form); $this->render('index', $data); }
public function actionCreate() { $model = new User(); if (isset($_POST['User'])) { $model->setAttributes($_POST['User']); $obj = Yii::app()->db->createCommand('SELECT count(*) FROM user where username=:iduser'); $obj->bindParam(":iduser", $_POST['User']['username'], PDO::PARAM_STR); $check = $obj->queryScalar(); if ($check == 0) { if ($model->save()) { if (Yii::app()->getRequest()->getIsAjaxRequest()) { Yii::app()->end(); } else { $this->redirect(array('subscription', 'create' => 2)); } } } else { $model->addError('', '<h4>Iri zina <u>' . $_POST['User']['username'] . '</u> ryarafashwe.Mushobora gukoresha irindi.</h4>'); } } $this->render('create', array('model' => $model)); }
/** * password change */ public function actionPasschange($code) { $model = User::findByRecoveryCode($code); if ($model === null) { $model = new User('passrecovery'); $model->addError('passrecovery_code', Yii::t('app', 'correct code required.')); } else { if (isset($_POST['User'])) { $password = $_POST['User']['password']; $model->password = $model->hashPassword($password); if ($model->save()) { Yii::app()->user->setFlash('info', Yii::t('app', "You successfully changed password.")); $this->redirect(Yii::app()->user->loginUrl); } } $model->password = null; } // display the passrecovery form $this->render('passchange', array('model' => $model)); }
/** * 会员登录 */ public function actionLogin() { $this->layout = " "; Yii::app()->clientScript->registerScriptFile(Yii::app()->theme->baseUrl . '/js/jquery-1.9.1.js'); Yii::app()->clientScript->registerCssFile(Yii::app()->theme->baseUrl . '/css/login.css'); $original = Yii::app()->request->getQuery('original'); $model = new User('login'); if (XUtils::method() == 'POST') { $model->attributes = $_POST['User']; $data = $model->find('username=:username OR email=:email', array(':username' => $model->username, ':email' => $model->username)); if ($data === null) { $model->addError('username', '用户不存在'); } elseif (!$model->validatePassword($data->password)) { $model->addError('password', '密码不正确'); } else { $userInfo = UserInfo::model()->find('userId=:userId', array(':userId' => $data->id)); parent::_stateWrite(array('userId' => $data->id, 'userName' => $data->username, 'nickname' => $userInfo->nickname), array('prefix' => '_account')); $data->last_login_ip = XUtils::getClientIP(); $data->last_login_time = time(); $data->login_count = $data->login_count + 1; $data->save(); if ($_REQUEST["houseid"] == "") { //判断登陆是否从预约看房那边进来的 if (!empty($original)) { $this->redirect($original); } else { $this->redirect(array('site/index')); } } else { $this->redirect(array('house/view&id=' . $_REQUEST[houseid] . '')); } } } $this->render('login', array('model' => $model)); }
public function actionEmailreg($email) { $model = new User(); $emailRecord = User::model()->findByAttributes(array('email' => $email)); if (!$emailRecord) { $model->addError('email', 'email不存在'); } else { if (!$emailRecord->password == '') { $model->addError('email', 'email已注册'); } else { // $this->redirect(array('update',array('id'=>1)); } } //$this->render('emailreg',$model); $this->redirect(array('update', 'id' => 1)); }
/** * Confirm email address. */ public function actionConfirmEmail() { $done = false; if (isset($_GET['email'], $_GET['key']) && !isset($_POST['User'])) { // scenario 1: confirm using url $model = new User('confirmEmailUrl'); // parse url parameters (from the link in the 'welcome' email) if (isset($_GET['email'])) { $model->email = $_GET['email']; } if (isset($_GET['key'])) { $model->emailConfirmationKey = $_GET['key']; } } else { // scenario 2: confirm using form $model = new User($this->action->id); if (isset($_POST['User'])) { // collect user input data $model->attributes = $_POST['User']; } } // attempt to confirm email if ((isset($_POST['User']) || isset($_GET['email'], $_GET['key'])) && $model->validate()) { // find user by email if (($user = User::model()->with('details')->findByAttributes(array('email' => $model->email))) !== null) { if (is_object($user->details)) { // explicitly set model scenario to be current action $user->details->setScenario($this->action->id); if ($user->details->isEmailConfirmed === UserDetails::EMAIL_IS_CONFIRMED) { // was confirmed earlier MUserFlash::setTopInfo(Yii::t('hint', 'Email address {email} was confirmed earlier.', array('{email}' => MHtml::wrapInTag($user->email, 'strong')))); } else { if ($user->details->emailConfirmationKey !== $model->emailConfirmationKey) { // wrong key MUserFlash::setTopError(Yii::t('hint', 'We are sorry, but email address {email} has a different confirmation key. You provided: {emailConfirmationKey}.', array('{email}' => MHtml::wrapInTag($user->email, 'strong'), '{emailConfirmationKey}' => MHtml::wrapInTag($model->emailConfirmationKey, 'strong')))); } else { // confirm email if ($user->details->saveAttributes(array('isEmailConfirmed' => UserDetails::EMAIL_IS_CONFIRMED))) { // set success message MUserFlash::setTopSuccess(Yii::t('hint', 'Email address {email} has been successfully confirmed.', array('{email}' => MHtml::wrapInTag($user->email, 'strong')))); // renew key in db $user->details->saveAttributes(array('emailConfirmationKey' => $user->details->generateConfirmationKey())); // clear form values $model = new User($this->action->id); // variable for view $done = true; } else { // set error message MUserFlash::setTopError(Yii::t('hint', 'Error! Email address {email} could not be confirmed.', array('{email}' => MHtml::wrapInTag($user->email, 'strong')))); Yii::log(W3::t('system', 'Could not save attributes of the {model} model. Model ID: {modelId}. Method called: {method}.', array('{model}' => get_class($user->details), '{modelId}' => $user->details->userId, '{method}' => __METHOD__ . '()')), 'error', 'w3'); } } } } else { // hmmm, user details does not exists MUserFlash::setTopError(Yii::t('hint', 'System failure! Please accept our apologies...')); Yii::log(W3::t('system', 'Member with ID {userId} has no UserDetails record associated. Method called: {method}.', array('{userId}' => $user->id, '{method}' => __METHOD__ . '()')), 'error', 'w3'); } } else { // email is not registered? MUserFlash::setTopInfo(Yii::t('hint', 'A member account with email address {email} could not be found.', array('{email}' => MHtml::wrapInTag($model->email, 'strong')))); // pay visitor attention to the 'email' field $model->addError('email', ''); } } // display the confirm email form $this->render($this->action->id, array('model' => $model, 'done' => $done)); }
/** * Метод регистрации * * Выводим форму для регистрации пользователя и проверяем * данные которые придут от неё. */ public function actionRegistration() { // тут думаю все понятно $form = new User(); // Проверяем являеться ли пользователь гостем // ведь если он уже зарегистрирован - формы он не должен увидеть. if (!Yii::app()->user->isGuest) { throw new CException('Вы уже зарегистрированны!'); } else { // Если $_POST['User'] не пустой массив - значит была отправлена форма // следовательно нам надо заполнить $form этими данными // и провести валидацию. Если валидация пройдет успешно - пользователь // будет зарегистрирован, не успешно - покажем ошибку на экран if (!empty($_POST['User'])) { // Заполняем $form данными которые пришли с формы $form->attributes = $_POST['User']; // Запоминаем данные которые пользователь ввёл в капче $form->verifyCode = $_POST['User']['verifyCode']; // В validate мы передаем название сценария. Оно нам может понадобиться // когда будем заниматься созданием правил валидации [читайте дальше] if ($form->validate('registration')) { // Если валидация прошла успешно... // Тогда проверяем свободен ли указанный логин.. if ($form->model()->count("username = :username", array(':username' => $form->username))) { // Указанный логин уже занят. Создаем ошибку и передаем в форму $form->addError('username', 'Логин уже занят'); $this->render("registration", array('form' => $form)); } else { // Выводим страницу что "все окей" $form->save(); $this->render("registration_ok"); } } else { // Если введенные данные противоречат // правилам валидации (указаны в rules) тогда // выводим форму и ошибки. // [Внимание!] Нам ненадо передавать ошибку в отображение, // Она автоматически после валидации цепляеться за // $form и будет [автоматически] показана на странице с // формой! Так что мы тут делаем простой рэндер. $this->render("registration", array('form' => $form)); } } else { // Если $_POST['User'] пустой массив - значит форму некто не отправлял. // Это значит что пользователь просто вошел на страницу регистрации // и ему мы должны просто показать форму. $this->render("registration", array('form' => $form)); } } }
public function actionAdd() { $model = new User(); $store = Store::model()->findAll('i_account_manager = 0'); $typeAccount = Yii::app()->user->hasState('typeAccountCurrent') ? Yii::app()->user->getState('typeAccountCurrent') : null; $this->pageTitle = $typeAccount != null ? 'Add Account Of ' . $typeAccount : 'Add Account'; if (isset(Yii::app()->user->storeID)) { $model->s_store_id = Yii::app()->user->storeID; $store = null; } if (isset($_POST['User'])) { $flagSave = false; $pk_s_id = 0; $s_image_server = ''; $password = ''; $model->attributes = $_POST['User']; $model->pk_s_id = '-1'; $levelAccount = Yii::app()->user->level; $role = Roles::model()->findByPk($model->i_user_role); $checkStore = Store::model()->find('pk_s_id = :pk_s_id', array(':pk_s_id' => $model->s_store_id)); //var_dump($checkStore);exit; $model->i_manager = 0; $model->i_device_max = intval($model->i_device_max); $model->s_code_active = $model->randomString(time() . 'ABCDEFGHIJKLM' . time() . time(), 8); $model->s_token = sha1(base64_encode($model->s_code_active) . time()); $model->i_time_send_code_active = time() + 86400; $model->s_secret_code = $model->secretCode(); $model->i_active = 0; $model->i_lock = 0; $model->i_flag_sync = 1; $model->i_flag_deleted = 0; $model->i_disable = 0; if ($model->i_user_role == 3) { $model->i_manager = 1; } if ($checkStore == null) { $model->s_store_id = null; } else { $storeManager = $checkStore->userManager(); if ($storeManager != null) { $model->addError('i_user_role', 'The store has managed. Please select user type other or stores other'); } } if ($role == null) { $model->addError('i_user_role', 'Type not exist'); } elseif ($levelAccount < $role->level) { $model->addError('i_user_role', 'Your are not authorized to make this type of account'); } $image = CUploadedFile::getInstance($model, 's_image_server'); if ($image != null) { $model->s_image_server = $model->s_username . date("dmHi") . '.' . $image->extensionName; if ($image->saveAs(Yii::app()->basePath . '/../data/users/' . $model->s_image_server)) { $imgthumb = Yii::app()->phpThumb->create(Yii::app()->basePath . '/../data/users/' . $model->s_image_server); $imgthumb->resize(240, 240); $imgthumb->save(Yii::app()->basePath . '/../data/users/240x240_' . $model->s_image_server); $imgthumb->resize(120, 120); $imgthumb->save(Yii::app()->basePath . '/../data/users/120x120_' . $model->s_image_server); $model->i_sync_image = 1; } else { $model->addError('s_image_server', 'Upload image fail'); } } if (count($model->errors) == 0) { if ($model->save()) { $flagSave = true; $pk_s_id = 'SV' . $model->id; $password = sha1($model->s_secret_code . sha1($model->s_password . $model->s_secret_code)); $model->pk_s_id = $pk_s_id; $model->s_password = $password; if ($model->save()) { $flagSave = true; } else { $flagSave = false; @unlink(Yii::app()->basePath . '/../data/users/' . $model->s_image_server); @unlink(Yii::app()->basePath . '/../data/users/240x240_' . $model->s_image_server); @unlink(Yii::app()->basePath . '/../data/users/120x120_' . $model->s_image_server); $model->delete(); } } if ($flagSave == true) { $this->redirect(array('index')); } } } $this->render('create', array('model' => $model, 'store' => $store, 'typeAccount' => $typeAccount)); }
/** * Allows password reset */ public function actionResetPassword() { $this->layout = '//layouts/accession'; $this->pageTitle = 'Reset Password | ' . Yii::app()->name; if (!Yii::app()->user->isGuest) { // can't be here $this->redirect(array('site/dashboard')); } $PasswordResetForm = new PasswordResetForm(); $User = new User(); $User->scenario = 'resetPassword'; if ($_GET['hash']) { $User = User::model()->findByAttributes(array('reset_hash' => $_GET['hash'])); if (!is_null($User)) { if ($_POST['PasswordResetForm']) { $PasswordResetForm->attributes = $_POST['PasswordResetForm']; if ($PasswordResetForm->validate()) { // submitting updated password $User->password1 = $_POST['PasswordResetForm']['password']; $User->password2 = $_POST['PasswordResetForm']['password_repeat']; $User->reset_hash = ''; $User->verified = 1; if ($User->save(true, array('password', 'reset_hash', 'verified'))) { Yii::app()->user->setFlash('success', 'We\'ve saved your new password. Please log in below'); $this->redirect(array('site/login')); } } } $User->password2 = ''; $User->password1 = ''; } else { // Check for a contact user $Store = $this->getContactStoreByHash($_GET['hash']); $Accession = $Store->store2contact->accession; if (!is_null($Store)) { $PasswordResetForm = new PasswordResetForm(); if ($_POST['PasswordResetForm']) { $PasswordResetForm->attributes = $_POST['PasswordResetForm']; if ($PasswordResetForm->validate()) { $Accession->password = hash('sha256', $_POST['PasswordResetForm']['password'] . SHASALT); $Accession->reset_hash = ''; $Accession->save(true, array('password', 'reset_hash')); Yii::app()->user->setFlash('success', 'We\'ve saved your new password. Please log in below'); $this->redirect(array('site/login')); } } } else { $User = new User(); $User->addError('email', 'That hash is expired or has been used. Please generate a new one below.'); unset($_GET['hash']); } } } elseif ($_POST['PasswordResetForm']['email']) { if (!strlen(trim($_POST['PasswordResetForm']['email']))) { $User->addError('email', 'A valid email address is required.'); } else { // trying to reset an email address // Check admin users first $User = User::model()->findByAttributes(array('email' => $_POST['PasswordResetForm']['email'])); if (!is_null($User)) { // Admin user found. Send email $User->sendPasswordResetEmail(); } else { $Store = new Store(); // Check for a contact user $Store = $this->getContactStore($Store->encryptEmail($_POST['PasswordResetForm']['email'])); if (!is_null($Store)) { $Store->sendPasswordResetEmail(); } else { $User = new User(); } } } } $this->render('resetPassword', array('User' => $User, 'PasswordResetForm' => $PasswordResetForm)); }
private function checkPassTwo() { $pass_two = $this->pass_two; if (strlen($pass_two) === 0 && strlen($this->pass) >= 6) { User::addError('password_two', 'Please confirm your password'); } elseif ($pass_two !== $this->pass && strlen($this->pass) >= 6) { User::addError('password_two', 'Passwords do not match'); } }
/** * 修改密码 * * @param $id */ public function actionUpdate() { $this->layout = ' '; Yii::app()->clientScript->registerCssFile(Yii::app()->theme->baseUrl . '/css/login.css'); Yii::app()->clientScript->registerScriptFile(Yii::app()->theme->baseUrl . '/js/jquery-1.9.1.js'); $email = Yii::app()->request->getQuery('email'); $email = base64_decode($email); $model = new User(); $link_list = Link::model()->findAll(); if (isset($_POST['User'])) { $email = $_POST['User']['email']; $password = $_POST['User']['password']; $password_repeat = $_POST['User']['password_repeat']; if (!empty($password)) { if ($password == $password_repeat) { $user = User::model()->find('email = :email', array(':email' => $email)); $user->password = md5($password); if ($user->save()) { $this->redirect(array('changeSuccess')); } else { $this->redirect(array('changeFailed')); } } else { $model->addError('password_repeat', '密码确认有误'); } } else { $model->addError('password', '密码不可为空'); } } $data = array('model' => $model, 'email' => $email, 'link_list' => $link_list); $this->render('update', $data); }
/** * Creates a new model. * If creation is successful, the browser will be redirected to the 'view' page. */ public function actionCreate() { if ($this->CanAccess('create')) { $model = new User(); $profile = new Profile(); $schoolMentor = new SchoolMentor(); if (isset($_POST['User'])) { $model->attributes = $_POST['User']; $model->activkey = $this->encrypting(microtime() . $model->password); $profile->attributes = $_POST['Profile']; $profile->user_id = 0; $profile->timezone = 'Europe/Ljubljana'; $profile->user_role = 5; $model->country_id = $profile->country_id; $custom_error = false; $modelValidate = $model->validate(); if ($model->password == '') { $model->addError('password', Yii::t('app', 'Password can not be empty!')); $custom_error = true; } $schoolMentorPost = Yii::app()->getRequest()->getPost('SchoolMentor', array()); if (!isset($schoolMentorPost['school_id']) || isset($schoolMentorPost['school_id']) && $schoolMentorPost['school_id'] == '') { $schoolMentor->addError('school_id', Yii::t('app', 'School must be choosen!')); $custom_error = true; } if ($modelValidate && $profile->validate() && !$custom_error) { $model->password = $this->encrypting($model->password); if ($model->save()) { $profile->user_id = $model->id; if ($profile->save()) { $schoolMentor->user_id = $model->id; $schoolMentor->school_id = isset($schoolMentorPost['school_id']) ? $schoolMentorPost['school_id'] : null; $schoolMentor->coordinator = isset($schoolMentorPost['coordinator']) ? $schoolMentorPost['coordinator'] : 0; $schoolMentor->active = 0; $schoolMentor->save(); $activation_url = $this->createAbsoluteUrl('/user/activation/activation', array("activkey" => $model->activkey, "email" => $model->email)); UserModule::sendMail($model->email, UserModule::t("You registered from {site_name}", array('{site_name}' => Yii::app()->name)), UserModule::t("Please activate you account go to {activation_url}", array('{activation_url}' => $activation_url))); } } $this->redirect(array('view', 'id' => $model->id)); } else { $profile->validate(); } } else { $model->country_id = 0; $profile->country_id = 0; } if (!Yii::app()->request->isAjaxRequest) { $this->render('create', array('model' => $model, 'profile' => $profile, 'school_mentor' => $schoolMentor)); // IF YOU NEED DIFFERENT RENDERING FOR AJAX AND NON-AJAX CALLS, // USE THIS LINE AND DELETE THE LINE ABOVE // $this->render('create', array('model' => $model, 'ajaxRendering' => false)); } else { throw new CHttpException(400, Yii::t('app', 'Bad request. The request cannot be fulfilled.')); // IF YOU NEED DIFFERENT RENDERING FOR AJAX AND NON-AJAX CALLS, // USE THIS LINE AND DELETE THE LINE ABOVE // $this->renderPartial('create', array('model' => $model, 'ajaxRendering' => true)); } } else { throw new CHttpException(405, Yii::t('app', 'You do not have permissions to access this page.')); } }