public function register() { $user = new Users(); $user->attributes = $this->attributes; $salt = md5(uniqid() . time()); $user->email = $this->email; $user->salt = $salt; $user->pass = crypt(trim($this->pass) . $salt); if ($user->validate() && $user->save()) { if (!Settings::model()->getValue('mail_confirm')) { $user->status = 1; $user->save(); return 1; } Yii::import('ext.YiiMailer.YiiMailer'); $code = md5(md5($user->pass . $user->email)); $mail = new YiiMailer(); $mail->setFrom(Settings::model()->getValue('register')); $mail->setTo($user->email); $mail->setSubject(Yii::t('register', 'Account activation')); $mail->setBody(Yii::t('register', "Hello {nick},<br/><br/>Your activation code: {code}<br/>{link}", array('{nick}' => $user->nick, '{code}' => $code, '{link}' => Yii::app()->createAbsoluteUrl('site/confirm', array('user' => $user->nick, 'code' => $code))))); $mail->send(); return 1; } }
/** * Creates a new model. * If creation is successful, the browser will be redirected to the 'view' page. */ public function actionCreate() { if (Yii::app()->user->checkAccess('createUsers')) { $model = new Users(); $address = new Address(); if (isset($_POST['Users']) && isset($_POST['Address'])) { $model->attributes = $_POST['Users']; $address->attributes = $_POST['Address']; $model->account_id = Users::model()->findByPk(Yii::app()->user->id)->account_id; $valid = $address->validate(); $valid = $model->validate() && $valid; if ($valid) { $address->save(false); $model->address_id = $address->primaryKey; $passBeforeMD5 = $model->user_password; $model->user_password = md5($model->user_password); if ($model->save(false)) { // Guardar log $attributes = array('log_date' => date("Y-m-d G:i:s"), 'log_activity' => 'UserCreated', 'log_resourceid' => $model->primaryKey, 'log_type' => 'created', 'user_id' => Yii::app()->user->id, 'module_id' => Yii::app()->controller->id); Logs::model()->saveLog($attributes); $str = $this->renderPartial('//templates/users/invitation', array('userCreateInvitation' => Yii::app()->user->CompleteName, 'user_email' => $model->user_email, 'user_password' => $passBeforeMD5, 'userInvited' => $model->CompleteName, 'applicationName' => Yii::app()->name, 'applicationUrl' => "http://" . $_SERVER['SERVER_NAME'] . Yii::app()->request->baseUrl), true); $subject = Yii::t('email', 'UserInvitation'); Yii::import('application.extensions.phpMailer.yiiPhpMailer'); $mailer = new yiiPhpMailer(); //$mailer->Ready($subject, $str, array('email'=>$model->user_email, 'name'=>$model->CompleteName)); $mailer->pushMail($subject, $str, array('email' => $model->user_email, 'name' => $model->CompleteName), Emails::PRIORITY_NORMAL); $this->redirect(array('view', 'id' => $model->user_id)); } } } $this->render('create', array('model' => $model, 'allowEdit' => true, 'userManager' => true, 'address' => $address)); } else { throw new CHttpException(403, Yii::t('site', '403_Error')); } }
/** * This function performs the validation work for complex object models. * * In addition to checking the current object, all related objects will * also be validated. If all pass then <code>true</code> is returned; otherwise * an aggreagated array of ValidationFailed objects will be returned. * * @param array $columns Array of column names to validate. * @return mixed <code>true</code> if all validations pass; array of <code>ValidationFailed</code> objets otherwise. */ protected function doValidate($columns = null) { if (!$this->alreadyInValidation) { $this->alreadyInValidation = true; $retval = null; $failureMap = array(); // We call the validate method on the following object(s) if they // were passed to this object by their coresponding set // method. This object relates to these object(s) by a // foreign key reference. if ($this->aUsers !== null) { if (!$this->aUsers->validate($columns)) { $failureMap = array_merge($failureMap, $this->aUsers->getValidationFailures()); } } if ($this->aUserBikes !== null) { if (!$this->aUserBikes->validate($columns)) { $failureMap = array_merge($failureMap, $this->aUserBikes->getValidationFailures()); } } if (($retval = UserEquipementPeer::doValidate($this, $columns)) !== true) { $failureMap = array_merge($failureMap, $retval); } if ($this->collUserStatEquips !== null) { foreach ($this->collUserStatEquips as $referrerFK) { if (!$referrerFK->validate($columns)) { $failureMap = array_merge($failureMap, $referrerFK->getValidationFailures()); } } } $this->alreadyInValidation = false; } return !empty($failureMap) ? $failureMap : true; }
/** * Creates a new model. * If creation is successful, the browser will be redirected to the 'index' page. */ public function actionCreateUser() { Yii::log("actionCreate called", "trace", self::LOG_CAT); $cancelLink = $this->createUrl('site/login'); $model = new Users(); if (isset($_POST['Users'])) { $model->attributes = $_POST['Users']; $model->roles = $_POST['Users']['roles']; if ($model->validate("insert")) { if ($model->save() && $model->saveRoles($model->userId, "create")) { // send the user the email link: $toMailName = $model->userName; $email = $model->email; // construct data and set expiry to 24 hrs $resetEncrypt = base64_encode($email . ",resetTrue," . (strtotime(date("H:i:s")) + 86400)); $passwordUrl = "http://" . $_SERVER["HTTP_HOST"] . Yii::app()->request->baseUrl . "/index.php/site/changepassword?data={$resetEncrypt}" . "&redirect_uri=" . $cancelLink; $mail = new TTMailer(); $subject = Yii::t('translation', 'User created'); $altBody = Yii::t('translation', 'To view the message, please use an HTML compatible email viewer!'); $message = Yii::t('translation', 'Dear ') . $toMailName . ',<br /><br />' . Yii::t('translation', 'your user account has been created, please visit '); $message .= '<a href="' . $passwordUrl . '">' . $passwordUrl . '</a>' . Yii::t('translation', ' to activate it and set a new password. ') . '<p></p>' . Yii::t('translation', 'This message was automatically generated.') . '<br />' . Yii::t('translation', ' If you think it was sent incorrectly, ') . Yii::t('translation', 'please contact your administrator.'); //if mail is not sent successfully issue appropriate message if (!$mail->ttSendMail($subject, $altBody, $message, $email, $toMailName)) { Yii::log("Error in sending the password to the user", "error", self::LOG_CAT); $msg = Yii::t('translation', "Error in sending the password to the user"); return $msg; } Yii::app()->user->setFlash('success', "User successfully created."); $this->redirect(array('users/index')); } } } $this->render('create', array('model' => $model)); }
/** * Logs in the user using the given username and password in the model. * @return boolean whether login is successful */ public function save() { $user = new Users(); $user->setAttributes($this->attributes); $user->setAttribute("password", BaseTool::ENPWD($this->password)); if ($user->validate() && $user->save()) { $accountarray = array('user_id' => Yii::app()->db->getLastInsertID(), 'total' => 0, 'use_money' => 0, 'no_use_money' => 0, 'newworth' => 0); $newAccount = new Account(); $newAccount->setAttributes($accountarray); $newAccount->save(); //发送邮件 $activecode = BaseTool::getActiveMailCode($this->username); $message = MailTemplet::getActiveEmail($this->username, $activecode); $mail = Yii::app()->Smtpmail; $mail->SetFrom(Yii::app()->params['adminEmail']); $mail->Subject = "好帮贷测试邮件"; $mail->MsgHTML($message); $mail->AddAddress($this->email); if ($mail->Send()) { $user->updateAll(array("regtaken" => $activecode, "regativetime" => time() + 60 * 60), "username=:username", array(":username" => $this->username)); } Yii::import("application.models.form.LoginForm", true); $loginform = new LoginForm(); $loginarray = array('rememberMe' => false, 'username' => $this->username, 'password' => $this->password); $loginform->setAttributes($loginarray); if ($loginform->validate() && $loginform->login()) { } return true; } else { $usererror = $user->errors; $this->addError("username", current(current($usererror))); return false; } }
public function actionStep2() { $model = new Users('step2'); /*if(isset($_POST['ajax']) && $_POST['ajax']==='users-form') //тут ajax-валидация { $model->setScenario('active'); $model->verifyCode = $_POST['Users']['verifyCode']; echo CActiveForm::validate($model); Yii::app()->end(); }*/ if (isset($_POST['Users'])) { //print_r($_POST); exit(); $model->name = $_POST['Users']['name']; //$model->login = $_POST['Users']['login']; $model->email = $_POST['Users']['email']; $model->password = $_POST['Users']['password']; $model->member = $_POST['Users']['member']; //$model->verifyCode = $_POST['Users']['verifyCode']; $model->tos = $_POST['Users']['tos']; if ($_POST['Users']['member'] == 0) { $model->member_type = 'client'; } //$model->scenario = 'registerwcaptcha'; if ($model->validate()) { // and here is the actual HACKY part $model->scenario = 'step2'; if ($model->save()) { if (!is_dir($_SERVER['DOCUMENT_ROOT'] . '/users/' . $model->id)) { mkdir($_SERVER['DOCUMENT_ROOT'] . '/users/' . $model->id); } $key = ''; $key = hash('md5', 'uid=' . $model->id . '&activate=1'); $name = '=?UTF-8?B?' . base64_encode($model->name) . '?='; $subject = '=?UTF-8?B?' . base64_encode('Регистрация на НМ') . '?='; $headers = "MIME-Version: 1.0\r\n" . "Content-Type: text/plain; charset=UTF-8"; $msg = "Подтвердите регистрацию! Ссылка - <a href='" . $this->createUrl('/register/confirm', array('uid' => $model->id, 'key' => $key)) . "'>подтвердить</a>\n <br />Если Ваш браузер не открывает ссылку, скопируйте ее адрес в браузер - " . $this->createUrl('/register/confirm', array('uid' => $model->id, 'key' => $key)); //if(mail($model->email,$subject,$msg,$headers)) { if (Users::mailsend($model->email, '*****@*****.**', $subject, $msg)) { Yii::app()->user->setFlash('create', 'На Ваш email отправлено письмо для подтверждения регистрации.'); //$this->render('activate',array('model'=>$model)); //sleep(100); //$this->redirect(array('/profile/view','id'=>$model->id)); } else { throw new CHttpException(500, 'Error send mail().'); } $this->render('activate', array('model' => $model)); } } else { /*echo "not valid"; echo CActiveForm::validate($model); Yii::app()->end();*/ $this->render('step2', array('model' => $model)); } } else { $this->render('step2', array('model' => $model)); } }
/** * login method * * Uses the reference {@link User} class to handle * user validation. * * @see User * @todo Decide which validate method to user instead of both * @access public * @param string $user account user name * @param string $password account password * @return boolean */ public function login($user, $password) { if (empty($user) || empty($password)) { return false; } else { // Проверяем через два метода валидации. Должны работать оба. // Статический метод класса User для валидации аккаунта $firstValidation = Users::validate($user, $password); // 'волшебный' метод класса User validate<username>($password) $userLoginFunction = 'validate' . $user; $secondValidation = $this->users->{$userLoginFunction}($password); return $firstValidation && $secondValidation; } }
public function register() { $user = new Users(); $user->attributes = $this->attributes; $salt = md5(uniqid() . time()); $user->email = $this->email; $user->salt = $salt; if (Yii::app()->user->permissions == 3) { $user->status = $this->rang; } else { $user->status = 1; } $user->pass = crypt(trim($this->pass) . $salt); if ($user->validate() && $user->save()) { return 1; } }
/** * Creates a new model. * If creation is successful, the browser will be redirected to the 'view' page. */ public function actionCreate() { $model = new TransaksiRegistrasi(); $model_user = new Users(); // Uncomment the following line if AJAX validation is needed // $this->performAjaxValidation($model,$model_user); if (isset($_POST['TransaksiRegistrasi'])) { // if($model->validate() && $model_user->validate()){ // echo "oke"; // }else{ // echo "ga oke"; // } // die(); $model->attributes = $_POST['TransaksiRegistrasi']; $model_user->attributes = $_POST['Users']; $cek = $model->validate(); $cek = $model_user->validate() && $cek; if ($cek) { // if($model->save()){ $number = ''; for ($i = 0; $i < 16; $i++) { $number .= rand(0, 9); } $model->ID_FANBASE = 1; $model->NO_SAKTI = $number; $model->VAD = '-'; $model->STATUS_REKONSILIASI = 'N'; $model->STATUS_RELEASE = 'N'; $tgl = explode('/', $_POST['TransaksiRegistrasi']['TANGGAL']); $model->TANGGAL = $tgl[2] . '-' . $tgl[0] . '-' . $tgl[1]; // print_r($model); die(); $model->save(false); $model_user->PASSWORD = md5($_POST['Users']['PASSWORD']); $model_user->ID_FANBASE = $model->ID_FANBASE; $model_user->ID_REGISTRASI = $model->ID_REGISTRASI; $model_user->ID_JENIS = 4; $model_user->VAS = '-'; $model_user->STATUS = 'N'; $model_user->save(false); $this->redirect(array('site/login', 'id' => $model->ID_REGISTRASI)); } } $this->render('create', array('model' => $model, 'model_user' => $model_user)); }
/** * Creates a new model. * If creation is successful, the browser will be redirected to the 'view' page. */ public function actionCreate() { $model = new Users('createSubAdmin'); if (isset($_POST['Users'])) { $model->attributes = $_POST['Users']; $model->status = $_POST['Users']['status']; if ($model->validate()) { $model->temp_password = $model->password_hash; $model->created_date = date("Y-m-d H:i:s"); $model->application_id = BE; //save user for back end $model->save(); $model->password_hash = md5($model->password_hash); $model->update(); $this->redirect(array('view', 'id' => $model->id)); } } $this->render('create', array('model' => $model, 'actions' => $this->listActionsCanAccess)); }
public function actionLogin() { if (Yii::app()->user->isGuest) { $model = new Users('login'); if (Yii::app()->request->isPostRequest) { $user = Yii::app()->request->getParam('Users'); $model->setAttributes($user); $user_identity = new UserIdentity($model->username, md5($model->password)); if ($model->validate() && $user_identity->authenticate()) { Yii::app()->user->login($user_identity, 60 * 60 * 24 * 7); // sign-in for week $this->redirect($this->createUrl(Yii::app()->user->returnUrl && Yii::app()->user->returnUrl != '/' ? Yii::app()->user->returnUrl : 'site/index')); } else { $this->render('login', ['model' => $model, 'error' => $user_identity->errorCode]); } } else { $this->render('login', ['model' => $model]); } } else { throw new CHttpException(403); } }
private function registerUserAction() { $newuser = new Users(); $name = $this->getParam('name'); //se ejecutó la opcion para obtener ususrio y contraseña $username = $this->getParam('username'); $password = $this->getParam('password'); //se ejecutó la opcion para obtener ususrio y contraseña $rpassword = $this->getParam('rpassword'); $email = $this->getParam('email'); if ($rpassword == $password) { if ($newuser->adduser($name, $username, $password, $email)) { $id = $newuser->validate($username, $password); $newuser->adduserstats($id); $this->dataview['msgerror'] = "Successful sign Up!!"; } else { $this->dataview['msgerror'] = "Couldn't write in Database!!"; } } else { $this->dataview['msgerror'] = "Passwords do not match!!"; } $this->registerAction(); }
public function actionCreate() { try { $model = new Users('create_register'); if (isset($_POST['Users'])) { $model->attributes = $_POST['Users']; $model->role_id = ROLE_REGISTER_MEMBER; $model->temp_password = $_POST['Users']['password_hash']; $model->application_id = FE; $model->validate(); if (!$model->hasErrors()) { $model->scenario = NULL; $model->password_hash = md5($_POST['Users']['password_hash']); $model->save(); $this->redirect(array('view', 'id' => $model->id)); } } $this->render('create', array('model' => $model, 'actions' => $this->listActionsCanAccess)); } catch (Exception $e) { Yii::log("Exception " . print_r($e, true), 'error'); throw new CHttpException("Exception " . print_r($e, true)); } }
public function renderContent() { // Форма регистрации $form = new Users(); $login = new LoginForm(); // Проверка если пришли данные из формы if (!empty($_POST['User'])) { $form->attributes = $_POST['User']; // Валидация формы if ($form->validate()) { if ($form->model()->count('username = :username', array(':username' => strtolower($form->username)))) { $form->addError('username', 'Такое имя пользователя уже зарегистрировано!'); $this->render('userauth', array( 'form' => $form, 'login' => $login )); } else { $form->save(); Yii::app()->user->setFlash('register', 'Вы подписаны на рассылку новостей'); } } else { $this->render('userauth', array( 'form' => $form, 'login' => $login )); } } else { $this->render('userauth', array( 'form' => $form, 'login' => $login )); } }
public static function addUser($weixinUser) { #注册新用户 $newuser = new Users(); $newuser->setAttribute('username', $weixinUser); $newuser->setAttribute('password', 'ooxxooxx'); $newuser->setAttribute('wangwang', $weixinUser); $newuser->setAttribute('privacy', uniqid()); if ($newuser->validate() && $newuser->save()) { $accountarray = array('user_id' => Yii::app()->db->getLastInsertID(), 'total' => 0, 'use_money' => 0, 'no_use_money' => 0, 'newworth' => 0); $newAccount = new Account(); $newAccount->setAttributes($accountarray); $newAccount->save(); } $user = Users::model()->find("username=:username", array(":username", $weixinUser)); return $user; }
public function saveMemberInfo($data) { $user_info = new Users(); $user_info = Users::model()->findByPk($data->getProperty('id')); if ($user_info == null) { $user_info = new Users(); $user_info->id = $data->getProperty('id'); $user_info->email = $data->getProperty('id') . '@qea.it'; $user_info->nickname = $data->getProperty('id'); $user_info->validate(); $user_info->save(); } $user_info->usersPersonalInfo = UserPersonalInfo::model()->findByPk($data->getProperty('id')); if ($user_info->usersPersonalInfo == null) { $user_info->usersPersonalInfo = new UserPersonalInfo(); } $user_info->usersPersonalInfo->user_id = $data->getProperty('id'); $names = str_word_count($data->getProperty('name'), 1); if (count($names) > 2) { $user_info->usersPersonalInfo->first_name = $names[0] . ' ' . $names[1]; $user_info->usersPersonalInfo->last_name = $names[2]; } else { if (isset($names[0])) { $user_info->usersPersonalInfo->first_name = $names[0]; } if (isset($names[1])) { $user_info->usersPersonalInfo->last_name = $names[1]; } } $user_info->usersPersonalInfo->validate(); $user_info->usersPersonalInfo->save(); }
protected function Int_register($params) { $mob = $params['mobile']; $pwd = $params['password']; //注册开始 $reg_ok = false; $notify_msg = ''; if ($mob && $pwd) { //预先验证使用的用户名本店范围内不重复 $testUser = UsersPassword::model()->find("username='******' and shop_id=0"); if (!$testUser) { //开启事务 $this->doTransaction('db', 'start'); //写入用户基本信息 $userMod = new Users(); $userMod->attributes = array('shop_id' => 0, 'dis_name' => $mob, 'real_name' => $mob, 'status' => 1, 'create_time' => time()); if (!($userMod->validate() && $userMod->save())) { $this->doTransaction('db', 'rollback'); $notify_msg = 'user-save-error'; } else { //保存用户组信息 $uGroup = new UserGroup(); $uGroup->attributes = array('user_id' => $userMod->user_id, 'group_id' => USER_GROUP_GUEST, 'status' => 'enabled'); if (!($uGroup->validate() && $uGroup->save())) { $this->doTransaction('db', 'rollback'); $notify_msg = 'user-group-save-error'; } else { //进一步处理用户登录授权方式 $grant_type_id = DEFAULT_GUEST_LOGIN_TYPE; //找到模块信息 $gtInfo = LoginGrantTypes::model()->findByPk($grant_type_id); if (!$gtInfo) { $this->doTransaction('db', 'rollback'); $notify_msg = 'user-grant-error'; } else { $userLoginGrantMod = new UsersLoginGrant(); $userLoginGrantMod->attributes = array('user_id' => $userMod->user_id, 'grant_type_id' => $grant_type_id, 'grant_type_name' => $gtInfo->grant_name, 'grantModelClass' => $gtInfo->grantModelClass, 'status' => 1); if (!($userLoginGrantMod->validate() && $userLoginGrantMod->save())) { $this->doTransaction('db', 'rollback'); $notify_msg = 'user-grent-save-error'; } else { //保存用户密码 $rndCode = rand(1000, 9999); $newpass = md5(md5($pwd) . $rndCode); $userPassMod = new UsersPassword(); $userPassMod->attributes = array('user_id' => $userMod->user_id, 'shop_id' => 0, 'username' => $mob, 'password' => $newpass, 'rndCode' => $rndCode); if (!($userPassMod->validate() && $userPassMod->save())) { $this->doTransaction('db', 'rollback'); $notify_msg = 'user-password-save-error'; } else { $this->doTransaction('db', 'commit'); $notify_msg = 'user-created'; $reg_ok = true; } } } } } } else { $notify_msg = 'user-exists'; } } return $this->_output(array('message' => $notify_msg, 'token' => !$reg_ok ? '' : $this->_grentAccessTokenForUser($userMod->user_id)), $reg_ok); }
/** * Regsiter FB user * * @author Kuldeep Dangi <*****@*****.**> */ public function actionFB() { $model = new Users(); if (isset($_GET['username'])) { $userModel = $model->findByUsername($_GET['username']); if ($userModel) { if (!empty($_GET['deviceType']) && $_GET['deviceToken']) { $userModel->deviceType = $_GET['deviceType']; $userModel->deviceToken = $_GET['deviceToken']; $userModel->save(); } $this->result['success'] = true; $this->result['message'] = 'User logged in successfully.'; $this->result['data'] = $userModel; } else { if (!empty($_GET['facebookAccount'])) { $_GET['password'] = md5($_GET['facebookAccount']); } else { $_GET['password'] = isset($_GET['password']) ? md5($_GET['password']) : ''; } $model->attributes = $_GET; $model->slugname = $_GET['username']; $model->active = 1; // $model->rewardpoints = self::REWARD_ON_REGSITER; if ($model->validate() && $model->save()) { $notficationModel = new Notifications(); $notficationModel->sendPushNotification(array('deviceToken' => $model->deviceToken, 'deviceType' => $model->deviceType, 'message' => 1)); $userObj = $model->findByUsername($_GET['username']); $nCash = new Ncash(); $nCash->addAmount($userObj->user_id, self::REWARD_ON_REGSITER, 4); $this->result['data'] = $userObj; $this->result['success'] = true; $this->result['message'] = 'User regsitered successfully.'; } else { $this->result['message'] = 'Invalid Data.'; } } } else { $this->result['message'] = 'No data to save.'; } $this->sendResponse($this->result); }
* @Param: $nameField field file in model user */ public static function removeFile($modelDel, $nameField, $pathUpload) { if (trim($modelDel->{$nameField}) == '') { return; } $ImageProcessing = new ImageProcessing(); $ImageProcessing->folder = '/' . $pathUpload . '/' . $modelDel->id; $ImageProcessing->delete($ImageProcessing->folder . '/' . $modelDel->{$nameField}); } public function getInforUser($id = null, $name = null) { /** * Get information user */ $id = (int) $id; $name = trim($name); if (empty($id)) {
public function actionRegistration() { if (!Yii::app()->user->isGuest) { throw new CException('Вы уже зарегистрированы!'); } else { $form = new Users(); if (!empty($_POST['Users'])) { $form->attributes = $_POST['Users']; if ($form->validate('registration')) { if ($form->model()->count('login=:login', array(':login' => $form->login))) { $form->addError('Такой логин уже занят!'); $this->render('registration', array('model' => $form)); } else { $form->save(); $this->render('registered'); $user = Users::model()->find(array('select' => 'id', 'condition' => 'login=:login', 'params' => array(':login' => $form->login))); mkdir('images/' . $user->id, 0644); } } else { $this->render('registration', array('model' => $form)); } } else { $this->render('registration', array('model' => $form)); } } }
/** * Creates a new model. * @return create view */ public function actionCreate() { // check if user has permissions to createClients if (Yii::app()->user->checkAccess('createClients')) { // create Users object model $modelUsers = new Users(); // create Address object model $address = new Address(); // if Users and Address form exist and was sent if (isset($_POST['Users']) && isset($_POST['Address'])) { // set form elements to Users model attributes $modelUsers->attributes = $_POST['Users']; // set form elements to Address model attributes $address->attributes = $_POST['Address']; $modelUsers->user_admin = 0; $modelUsers->account_id = Yii::app()->user->Accountid; // validate both models $valid = $address->validate(); $valid = $modelUsers->validate() && $valid; if ($valid) { // save address $address->save(false); $modelUsers->address_id = $address->primaryKey; // temporary variable with user password $passBeforeMD5 = $modelUsers->user_password; // hashed user password $modelUsers->user_password = md5($modelUsers->user_password); // save user if ($modelUsers->save(false)) { // create clients object $model = new Clients(); $model->user_id = $modelUsers->user_id; // validate and save if ($model->save()) { // save log $attributes = array('log_date' => date("Y-m-d G:i:s"), 'log_activity' => 'ClientCreated', 'log_resourceid' => $model->primaryKey, 'log_type' => Logs::LOG_CREATED, 'user_id' => Yii::app()->user->id, 'module_id' => Yii::app()->controller->id); Logs::model()->saveLog($attributes); // prepare to send email template to new user $str = $this->renderPartial('//templates/users/invitation', array('userCreateInvitation' => Yii::app()->user->CompleteName, 'user_email' => $modelUsers->user_email, 'user_password' => $passBeforeMD5, 'userInvited' => $modelUsers->CompleteName, 'applicationName' => Yii::app()->name, 'applicationUrl' => "http://" . $_SERVER['SERVER_NAME'] . Yii::app()->request->baseUrl), true); $subject = Yii::t('email', 'UserInvitation'); Yii::import('application.extensions.phpMailer.yiiPhpMailer'); $mailer = new yiiPhpMailer(); $mailer->pushMail($subject, $str, array('email' => $modelUsers->user_email, 'name' => $modelUsers->CompleteName), Emails::PRIORITY_NORMAL); // to prevent F5 keypress, redirect to view detail page $this->redirect(array('view', 'id' => $model->client_id)); } } } } $this->render('create', array('model' => $modelUsers, 'address' => $address)); } else { throw new CHttpException(403, Yii::t('site', '403_Error')); } }
public function actionSignup() { // Создать модель и указать ей, что используется сценарий регистрации $user = new Users(Users::SCENARIO_SIGNUP); // Если пришли данные для сохранения if(isset($_POST['Users'])) { // Безопасное присваивание значений атрибутам $user->attributes = $_POST['Users']; // Проверка данных if($user->validate()) { // Сохранить полученные данные // false нужен для того, чтобы не производить повторную проверку $user->save(false); } } $this->redirect(Yii::app()->homeUrl); }
load_skin('users'); // the path to this page $context['path_bar'] = array('users/' => i18n::s('People')); // the title of the page $context['page_title'] = i18n::s('Validate your e-mail address'); // stop crawlers if (Surfer::is_crawler()) { Safe::header('Status: 401 Unauthorized', TRUE, 401); Logger::error(i18n::s('You are not allowed to perform this operation.')); // not found } elseif (!isset($item['id'])) { include '../error.php'; // bad handle } elseif ($id != $item['handle']) { include '../error.php'; } elseif (Users::validate($item['id'])) { // congratulations $context['text'] .= sprintf(i18n::s('<p>%s,</p><p>Your e-mail address has been validated, and you are now an active member of this community.</p>'), ucfirst($item['nick_name'])); // set permanent name shown from top level Safe::setcookie('surfer_name', $item['nick_name'], time() + 60 * 60 * 24 * 500, '/'); // save surfer profile in session context Surfer::set($item); // follow-up commands $follow_up = i18n::s('Where do you want to go now?'); $menu = array(); $menu = array_merge($menu, array(Users::get_permalink($item) => i18n::s('My profile'))); $menu = array_merge($menu, array($context['url_to_root'] => i18n::s('Front page'))); $follow_up .= Skin::build_list($menu, 'menu_bar'); $context['text'] .= Skin::build_block($follow_up, 'bottom'); // failed operation } else {
/** * Register a new user */ public function actionSignin() { $output = array('errno' => 0, 'message' => '', 'html' => null, 'params' => null); //CHECK INPUT $user = new Users(); $user->attributes = array('id' => null, 'email' => $_POST['email'], 'password_md5' => hash(Yii::app()->params['security']['password_md5_algo'], $_POST['password']), 'password_sha512' => hash(Yii::app()->params['security']['password_sha512_algo'], $_POST['password']), 'status' => Users::STATUS_PENDING_ACTIVATION, 'suscribe_date' => date('Y-m-d H:i:s')); //Validate user data if ($user->validate()) { //CHECK email is in use $userSearch = Users::model()->find(array('select' => '*', 'condition' => 'email=:email', 'params' => array(':email' => $_POST['email']))); if ($userSearch) { //el email está siendo utilizado $output['message'] = 'El email está siendo utilizado. Si quieres recuperar la cuenta, ponte en contacto con nosotros.'; $output['errno'] = 1; } } else { //El email no es correcto. $output['message'] = 'El email está siendo utilizado.'; $output['errno'] = 1; } //Seach name of knight $knight = Knights::model()->find(array('select' => '*', 'condition' => 'name=:name', 'params' => array(':name' => ucfirst(strtolower($_POST['name']))))); if ($knight) { //caballero con nombre en uso $message = 'El nombre del caballero está en uso. Elige otro.'; $output['errno'] = 1; if ($output['errno'] === 0) { $output['message'] = $message; } else { $output['message'] .= $message; } } //INSERT USER AND KNIGHT INTO DATA BASE IF IS FREE ERROR if ($output['errno'] == 0) { if ($user->save(false)) { //Set attribute knight $knight = new Knights(); $knight->attributes = array('users_id' => $user->id, 'suscribe_date' => date('Y-m-d H:i:s'), 'name' => ucfirst(strtolower($_POST['name'])), 'status' => Knights::STATUS_PENDING_VALIDATION, 'level' => Yii::app()->params['knight_default']['level'], 'endurance' => 1, 'life' => 1, 'experiencie_earned' => Yii::app()->params['knight_default']['experiencie_earned'], 'experiencie_used' => Yii::app()->params['knight_default']['experiencie_used']); //Comprobamos si valida. if ($knight->validate()) { //Insertamos el caballero. if ($knight->save()) { //ENVIAMOS EMAIL //creamos el codigo de activacion. Va ser el md5 de email, nombre del caballero, password y la fecha en la que se da de alta $codigo_activacion = md5($_POST['email'] . $knight->name . hash('md5', $_POST['password']) . $user->suscribe_date); //cargamos la plantilla $message = Yii::app()->controller->renderFile(Yii::app()->basePath . Yii::app()->params['email_templates_path'] . 'sigin.tpl', array('enlace_activacion' => Yii::app()->params->url_domain . '/site/AccountActivation/email/' . $user->email . '/code/' . $codigo_activacion, 'knights_name' => $_POST['name']), true); //echo $message; // To send HTML mail, the Content-type header must be set $headers = 'MIME-Version: 1.0' . "\r\n"; $headers .= 'Content-type: text/html; charset=utf-8' . "\r\n"; // Additional headers $headers .= 'To: ' . $_POST['email'] . "\r\n"; $headers .= 'From: <' . Yii::app()->params['adminEmail'] . '>' . "\r\n"; $headers = array($headers); if (!Yii::app()->email->send(Yii::app()->params['adminEmail'], $_POST['email'], Yii::app()->name . ': ¡ya eres parte de nuestra historia!', $message, $headers)) { $output['message'] = '<p>Se ha producido un error al enviar el correo electrónico. Contacta con nosotros para solucionar la incidencia.</p><p>¡Lo sentimos!</p>' . Yii::app()->email->getErrors(); $output['errno'] = 1; } } else { //Usuario encontrado $output['message'] = 'Se ha producido un error al dar de alta el caballero.'; $output['errno'] = 1; } } else { //Usuario encontrado $output['message'] = 'Se ha producido un error en la validación del caballero.'; $output['errno'] = 1; } } else { //No se ha podido dar de alta el usuario $output['message'] = 'Se ha producido un error al dar de alta un usuario.'; $output['errno'] = 1; } } //echo "NOBORRAR"; if ($output['errno'] == 0) { $output['message'] = $this->renderPartial('signin', null, true); } //SHOW OUTPUT echo CJSON::encode($output); }
public function actionSigninPlatform() { if (!Yii::app()->user->isGuest) { $this->redirect('/'); } $user = new Users('signin'); if (isset($_POST['Users'])) { $user->attributes = $_POST['Users']; } $user->role = Users::ROLE_PLATFORM; $user->status = Users::STATUS_MODERATION; $platform = new Platforms('signin'); if (isset($_POST['Platforms'])) { $platform->attributes = $_POST['Platforms']; } $platform->is_active = 0; if (isset($_POST['Users']) && isset($_POST['Platforms'])) { $user->validate(); $platform->validate(); if (!$user->hasErrors() && !$platform->hasErrors()) { $transaction = $user->getDbConnection()->beginTransaction(); if ($user->save(false)) { $platform->user_id = $user->id; if ($platform->save(false)) { SMail::sendMail(Yii::app()->params['registrationEmail'], 'Регистрация пользователя ' . $user->email, 'SignInRequest', array('user' => $user)); $transaction->commit(); $this->redirect(array('users/signinSuccess')); } } $transaction->rollback(); } } $this->render('signin_platform', array('user' => $user, 'platform' => $platform)); }
public function actionRegistration() { $model = new Users(); $useInvitations = AuthCommon::getParam('useInvitations'); if ($useInvitations) { if (Yii::app()->user->hasState('invitationGuid')) { $invitationGuid = Yii::app()->user->getState('invitationGuid'); } else { $invitationGuid = null; } if (empty($invitationGuid)) { //invitation is empty so we neet to show invitation enter page $this->redirect(array('invitations/index')); } $model->invitationGuid = $invitationGuid; } if (isset($_POST['Users'])) { //this is a second call this action but with form data, //so we need to update and save User model $model->attributes = $_POST['Users']; if ($model->termsSigned > 0) { $model->terms_version = 1; } if (!$model->validate()) { //have not pass validators Yii::app()->user->setFlash('error', Yii::t('AuthModule.main', 'Incorrect form data')); $this->render('change', array('model' => $model)); return; } $model->created_manually = true; if (!$model->saveModel()) { $this->render('change', array('model' => $model)); return; } if ($useInvitations) { //mark invintation used if (!Invitations::setUsed($model->invitationGuid, $model->username)) { Yii::app()->user->setFlash('error', Yii::t('AuthModule.main', 'Invitation occupy error')); $this->redirect(array('invitations/index')); } Yii::app()->user->setState('invitationGuid', null); } $email = $model->email; $user_id = $model->id; Yii::app()->user->setState('formUsername', $model->username); $guid = AuthCommon::getGUID(); $validations = new Validations(); $validations->guid = $guid; $validations->user_id = $user_id; $validations->email = $email; $validations->type = self::VALIDATOR_ACTIVATE; $date = new DateTime(); $date->modify("+24 hours"); $exp_time = $date->format(AuthCommon::getParam('dateFormat')); $validations->exp_datetime = $exp_time; $validations->comments = 'Activate new user'; if (!$validations->validate() || !$validations->save()) { Yii::app()->user->setFlash('error', Yii::t('AuthModule.main', 'Form validation error')); $this->redirect(array('user/registration')); } if (AuthCommon::sendActivationtEmail($model->email, $guid, $model->username)) { Yii::app()->user->setFlash('success', sprintf(Yii::t('AuthModule.main', 'Activation email has been sent to address'), $email)); $this->redirect(array('user/activation')); } else { Yii::app()->user->setFlash('error', sprintf(Yii::t('AuthModule.main', 'Error sending email'), $email)); Helpers::showError('Ошибка отправки письма', 'Регистрация пользователя', true); } } else { $this->render('change', array('model' => $model)); } }
public function actionCreate() { $this->hasPrivilege(Acl::ACTION_CREATE); $this->pageTitle = Lang::t('New ' . $this->resourceAddLabel); // User information $user_model = new Users(ActiveRecord::SCENARIO_CREATE); $user_model->status = Users::STATUS_ACTIVE; $user_model_class_name = $user_model->getClassName(); //personal information $person_model = new Person(); $person_model_class_name = $person_model->getClassName(); //staff information $staff_model = new Staff(ActiveRecord::SCENARIO_CREATE); $staff_model->status = Staff::STATUS_ACTIVE; $staff_model_class_name = $staff_model->getClassName(); if (Yii::app()->request->isPostRequest) { $user_model->attributes = $_POST[$user_model_class_name]; $person_model->attributes = $_POST[$person_model_class_name]; $staff_model->attributes = $_POST[$staff_model_class_name]; $person_model->validate(); $staff_model->validate(); $user_model->validate(); if (!$user_model->hasErrors() && !$staff_model->hasErrors() && !$person_model->hasErrors()) { if ($user_model->save(FALSE)) { $person_model->id = $user_model->id; if ($person_model->save(FALSE)) { $staff_model->person_id = $person_model->id; $staff_model->save(FALSE); Yii::app()->user->setFlash('success', Lang::t('Staff added successfully.')); $this->redirect(Controller::getReturnUrl($this->createUrl('view', array('id' => $staff_model->id)))); } } } } $this->render('create', array('staff_model' => $staff_model, 'user_model' => $user_model, 'model' => $person_model)); }
/** * Creates a new model. * If creation is successful, the browser will be redirected to the 'view' page. */ public function actionCreate($dept_id = NULL, $user_level = NULL) { $this->hasPrivilege(Acl::ACTION_CREATE); $this->pageTitle = Lang::t('Add ' . $this->resourceLabel); //account information $user_model = new Users(ActiveRecord::SCENARIO_CREATE); $user_model->status = Users::STATUS_ACTIVE; $user_model_class_name = $user_model->getClassName(); //personal information $person_model = new Person(); $person_model_class_name = $person_model->getClassName(); if (Yii::app()->request->isPostRequest) { $user_model->attributes = $_POST[$user_model_class_name]; $person_model->attributes = $_POST[$person_model_class_name]; $user_model->validate(); $person_model->validate(); if (!$user_model->hasErrors() && !$person_model->hasErrors()) { if ($user_model->save(FALSE)) { $person_model->id = $user_model->id; $person_model->save(FALSE); $user_model->updateDeptUser(); if (!empty($user_model->dept_id)) { Dept::model()->updateContactPerson($user_model->dept_id, $person_model->id); } Yii::app()->user->setFlash('success', Lang::t('SUCCESS_MESSAGE')); $this->redirect(Controller::getReturnUrl($this->createUrl('view', array('id' => $user_model->id)))); } } } $user_model->timezone = Yii::app()->settings->get(Constants::CATEGORY_GENERAL, Constants::KEY_DEFAULT_TIMEZONE, SettingsTimezone::DEFAULT_TIME_ZONE); if (!empty($dept_id)) { $user_model->dept_id = $dept_id; } if (!empty($user_level)) { $user_model->user_level = $user_level; } $this->render('create', array('user_model' => $user_model, 'person_model' => $person_model)); }
/** * Регистрациия пользователя */ public function actionRegistration() { $this->layout = 'start_page'; if (isset($_GET['idUser'])) { $model = Users::model()->findByPk($_GET['idUser']); $model->setScenario('edit'); } else { $model = new Users('create'); } if (isset($_POST['Users'])) { $model->attributes = $_POST['Users']; $model->idRole = 2; if ($model->validate()) { if ($model->save()) { $this->_loginModel = new LoginForm(); $this->_loginModel->login = $model->login; $this->_loginModel->password = $_POST['Users']['password']; if ($this->_loginModel->login()) { $this->redirect(Yii::app()->homeUrl); } } } } $this->render('registration', array('model' => $model)); }
/** * Метод создания пользователя, путешествия, покупки * возвращает массив JSON с ошибками */ public function actionaddPurchase() { if (empty(Yii::app()->request->csrfToken)) { throw new CHttpException('403', 'Ошибочный запрос, отказано в доступе.'); } $params = CJSON::decode(file_get_contents('php://input'), true); $errors = array(); $user = new Users(); $user->username = $params['data']['userfullname']; $user->password = $params['data']['password']; $user->email = $params['data']['email']; $user->first_name = strpos($params['data']['userfullname'], ' ') === false ? $params['data']['userfullname'] : substr($params['data']['userfullname'], 0, strpos($params['data']['userfullname'], ' ')); $user->last_name = strpos($params['data']['userfullname'], ' ') === false ? $params['data']['userfullname'] : substr($params['data']['userfullname'], strpos($params['data']['userfullname'], ' ')); if ($user->validate()) { if (!$user->save()) { throw new CHttpException('403', 'Ошибочный запрос, не удалось обновить user'); } } else { throw new CHttpException('403', 'Ошибочный запрос, не удалось обновить user'); } $trip = new Trip(); $trip->users__id = $user->id; $trip->departure = $params['data']['departure']; $trip->destination = $params['data']['destination']; $trip->date_start = date("Y-m-d", strtotime($params['data']['date_start'])); $trip->date_end = date("Y-m-d", strtotime($params['data']['date_end'])); if ($trip->validate()) { if (!$trip->save()) { throw new CHttpException('403', 'Ошибочный запрос, не удалось обновить trip'); } } else { throw new CHttpException('403', 'Ошибочный запрос, не удалось обновить trip'); } $purchase = new Purchases(); $purchase->users__id = $user->id; $purchase->trip__id = $trip->id; $purchase->name = $params['data']['name']; $purchase->price = $params['data']['price']; if ($purchase->validate()) { if (!$purchase->save()) { throw new CHttpException('403', 'Ошибочный запрос, не удалось обновить purchase'); } } else { throw new CHttpException('403', 'Ошибочный запрос, не удалось обновить purchase validate'); } $errors['customer'] = array_merge($user->getErrors(), $trip->getErrors()); echo CJSON::encode($errors); }