public function up() { $data = (include Yii::getAlias('@common') . '/data/test-adverts.php'); $i = 0; while ($i++ !== 3) { foreach ($data as $one) { $advert = new Advert(); $advert->detachBehavior('timestamp'); $advert->setAttributes($one); $advert->user_id = rand(1, 50); $advert->created_at = time() - 3600 * 24 * rand(1, 31) - 3600 * rand(1, 24) + rand(1, 3600); $advert->updated_at = $advert->created_at; $advert->term_at = $advert->created_at + 3600 * 24 * rand(1, 31); if ($advert->save()) { echo "Advert for user №{$advert->user_id} created\n"; } else { print_r($advert->getErrors()); } } } foreach (User::find()->all() as $user) { $profile = new Profile(); $profile->user_id = $user->id; $profile->name = $user->username; if ($profile->save()) { echo "Profile of \"{$user->username}\" created\n"; } else { print_r($profile->getErrors()); } } }
/** * Signs user up. * * @return true|null the saved model or null if saving fails */ public function signup() { if ($this->validate()) { $user = new User(); $user->phone = $this->phone; $user->email = $this->email; $randLength = mt_rand(6, 9); $this->password = Yii::$app->security->generateRandomString($randLength); $user->setPassword($this->password); $user->generateAuthKey(); if ($user->save()) { $profile = new Profile(); $profile->user_id = $user->id; $profile->name = $this->name; //если в куках есть id аффилиата, сохраняем его $affiliateId = (int) Yii::$app->request->cookies['affiliate']; if ($affiliateId > 0 && User::findIdentity($affiliateId)) { $profile->user_affiliate_id = $affiliateId; } $profile->save(); return $this->sendRegistrationEmail(); } } return null; }
public function reg() { $user = new User(); $user->phone = $this->phone; $user->email = $this->email; $user->status = $this->status; $user->setPassword($this->password); $user->generateAuthKey(); if ($this->scenario === 'emailActivation') { $user->generateSecretKey(); } $transaction = Yii::$app->db->beginTransaction(); try { if ($user->save()) { $modelProfile = new Profile(); $modelProfile->user_id = $user->id; if ($modelProfile->save()) { $transaction->commit(); return RbacHelper::assignRole($user->getId()) ? $user : null; } } else { return false; } } catch (Exception $e) { $transaction->rollBack(); } }
/** * Create user profile after registration. */ public function createProfile($event) { $user = $this->owner; $profile = new Profile(); $profile->user_id = $user->id; $profile->save(); }
/** * Creates a new Profile model. * If creation is successful, the browser will be redirected to the 'view' page. * @return mixed */ public function actionCreate() { $model = new Profile(); if ($model->load(Yii::$app->request->post()) && $model->save()) { return $this->redirect(['view', 'id' => $model->user_id]); } else { return $this->render('create', ['model' => $model]); } }
public function actionForm() { //vd(1); $model = Profile::find()->where(['user_id' => Yii::$app->user->id])->one(); if (!$model) { $model = new Profile(); } if ($model->load(Yii::$app->request->post())) { //vd($_POST); if ($model->validate()) { $model->gender = $_POST['gender']; $model->user_id = Yii::$app->user->id; $model->login = User::getLoginById(Yii::$app->user->id); $model->save(); return $this->render('form', ['model' => $model]); } else { vd($model->getErrors()); } } return $this->render('form', ['model' => $model]); }
public function actionProfile() { $model = Profile::findOne(['user_id' => Yii::$app->user->id]); if (!$model) { $model = new Profile(); $model->user_id = Yii::$app->user->id; } if ($model->load(Yii::$app->request->post()) && $model->save()) { Yii::$app->getSession()->setFlash('success', Yii::t('app', 'New password was saved.')); return $this->goHome(); } return $this->render('profile', ['model' => $model]); }
/** * Save application form. * * @return Profile|null the saved model or null if saving fails */ public function save() { if ($this->validate()) { $person = Person::findById($this->id_person); if (empty($person)) { $person = new Person(); } if (trim($this->parent1_type) != '') { $parent1 = Person::findById($person->id_parent1); if (empty($parent1)) { $parent1 = new Person(); } $parent1->attributes = $this->getMyAttributes('parent1_'); $parent1->save(); $person->id_parent1 = $parent1->id; } else { $parent1 = Person::findById($person->id_parent1); if (!empty($parent1)) { $parent1->delete(); } $person->id_parent1 = null; } if (trim($this->parent2_type) != '') { $parent2 = Person::findById($person->id_parent2); if (empty($parent2)) { $parent2 = new Person(); } $parent2->attributes = $this->getMyAttributes('parent2_'); $parent2->save(); $person->id_parent2 = $parent2->id; } else { $parent2 = Person::findById($person->id_parent2); if (!empty($parent2)) { $parent2->delete(); } $person->id_parent2 = null; } $person->attributes = $this->attributes; if ($person->save()) { $this->id_person = $person->id; $profile = Profile::findById($this->id); if (empty($profile)) { $profile = new Profile(); } $profile->attributes = $this->attributes; $profile->id_person = $person->id; $profile->status = $this->status; if ($profile->validate()) { $profile->save(); $this->id = $profile->id; $specs = Yii::$app->request->post('spec'); $SpecArray = array(); $i = 0; if (!empty($specs)) { foreach ($specs as $id => $spec) { if ($spec != 'none') { $SpecArray[$i]['id_profile'] = $profile->id; $SpecArray[$i]['id_spec'] = $id; $spec == 'form_fulltime' ? $SpecArray[$i]['form_fulltime'] = 1 : ($SpecArray[$i]['form_fulltime'] = 0); $spec == 'form_extramural' ? $SpecArray[$i]['form_extramural'] = 1 : ($SpecArray[$i]['form_extramural'] = 0); $SpecArray[$i]['priority'] = $i + 1; $i++; } } } Yii::$app->db->createCommand()->delete('profile_spec', 'id_profile=:id', [':id' => $profile->id])->execute(); if (!empty($SpecArray)) { Yii::$app->db->createCommand()->batchInsert('profile_spec', ['id_profile', 'id_spec', 'form_fulltime', 'form_extramural', 'priority'], $SpecArray)->execute(); } return true; } else { return false; } } } return false; }
public function actionProfile() { $model = Profile::findOne(['user_id' => Yii::$app->user->id]); if (!$model) { $model = new Profile(); $model->user_id = Yii::$app->user->id; } if ($model->birthday) { $model->year = substr($model->birthday, 0, 4); $model->month = substr($model->birthday, 5, 2); $model->day = substr($model->birthday, 8, 2); } if ($model->load(Yii::$app->request->post())) { $model->year = intval(Yii::$app->request->post()['Profile']['year']); $model->month = intval(Yii::$app->request->post()['Profile']['month']); $model->day = intval(Yii::$app->request->post()['Profile']['day']); if ($model->year || $model->month || $model->day) { $model->birthday = date('Y-m-d H:i:s', mktime(0, 0, 0, $model->month, $model->day, $model->year)); } if ($model->save()) { Yii::$app->getSession()->setFlash('success', Yii::t('app', 'New profile was saved.')); } } return $this->render('profile', ['model' => $model]); }
public function onAuthSuccess($client) { /* @var $client \yii\authclient\OAuth2*/ /* @var $user \common\models\User */ $attributes = $client->getUserAttributes(); /* @var $auth Auth */ $auth = Auth::find()->where(['source' => $client->getId(), 'source_id' => $attributes['id']])->one(); if (Yii::$app->user->isGuest) { if ($auth) { // вход $user = $auth->user; if ($user->status == User::STATUS_NOT_ACTIVE && $user->email == '') { Yii::$app->getSession()->setFlash('success', [Yii::t('app', "Для завершения регистрации введите телефон и подтвердите адрес электронной почты.")]); return $this->redirectUser($url = Url::to(['/main/finish-reg', 'id' => $user->id])); } elseif ($user->status == User::STATUS_NOT_ACTIVE && $user->email != '') { Yii::$app->getSession()->setFlash('success', [Yii::t('app', "Для завершения регистрации введите номер телефона.")]); return $this->redirectUser($url = Url::to(['/main/finish-reg', 'id' => $user->id])); } elseif ($user->status == User::STATUS_DELETED) { Yii::$app->getSession()->setFlash('error', [Yii::t('app', "Данный пользователь заблокирован.")]); return $this->redirectUser($url = Url::to(['/main/index'])); } Yii::$app->user->login($user); } else { // регистрация if (isset($attributes['email']) && ($user = User::findOne(['email' => $attributes['email']]))) { // Если пользователь регитрировался ранее через форму регистации. if ($user->status == User::STATUS_ACTIVE) { Yii::$app->getSession()->setFlash('error', Yii::t('app', "Авторизация с использованием электронного адреса <strong>" . $user->email . "</strong> уже успешно прошла через форму регистрации.\n Воспользуйте ссылкой <strong>" . '"Забыли пароль?"' . "</strong> для востанновления пароля.")); return $this->redirectUser($url = Url::to(['/main/login'])); } else { Yii::$app->getSession()->setFlash('error', [Yii::t('app', "Авторизация с использованием электронного адреса <strong>" . $user->email . "</strong> уже происходила через аккунт <strong>" . $user->auths->source . "</strong>.\n Выполните вход используя аккаунт <strong>" . $user->auths->source . "</strong> или воспользуйте ссылкой <strong>" . '"Забыли пароль?"' . "</strong> для востанновления пароля для\n пользователя с емайл <strong>" . $user->email . "</strong>.", ['client' => $title = $client->getTitle()])]); return $this->redirectUser($url = Url::to(['/main/login'])); } } else { // Полученные данные заносим в переменные /* @var $email string */ /* @var $first_name string */ /* @var $second_name string */ if (Yii::$app->request->get('authclient') == 'google') { $first_name = $attributes['name']['givenName']; $second_name = $attributes['name']['familyName']; $email = $attributes['emails'][0]['value']; } elseif (Yii::$app->request->get('authclient') == 'yandex') { $first_name = $attributes['first_name']; $second_name = $attributes['last_name']; $email = $attributes['default_email']; } elseif (Yii::$app->request->get('authclient') == 'facebook') { $names = explode(' ', $attributes['name']); $first_name = $names[0]; $second_name = $names[1]; $email = $attributes['email']; } elseif (Yii::$app->request->get('authclient') == 'vkontakte') { $first_name = $attributes['first_name']; $second_name = $attributes['last_name']; $email = false; } elseif (Yii::$app->request->get('authclient') == 'twitter') { $names = $attributes['name']; $names = explode(' ', $names); $first_name = $names[0]; $second_name = $names[1]; $email = false; } elseif (Yii::$app->request->get('authclient') == 'linkedin') { $first_name = $attributes['first_name']; $second_name = $attributes['last_name']; $email = $attributes['email']; } $password = Yii::$app->security->generateRandomString(6); $user = new User(['email' => $email, 'password' => $password, 'status' => User::STATUS_NOT_ACTIVE]); $user->generateAuthKey(); $user->generateSecretKey(); $transaction = $user->getDb()->beginTransaction(); if ($user->save()) { $auth = new Auth(['user_id' => $user->id, 'source' => $client->getId(), 'source_id' => (string) $attributes['id']]); if ($auth->save()) { /* @var $modelProfile /common/models/Profile */ $modelProfile = new Profile(); $modelProfile->user_id = $user->id; $modelProfile->first_name = $first_name; $modelProfile->second_name = $second_name; if ($modelProfile->save()) { $transaction->commit(); // если нет емайл, делаем перенаправление на main/finish-reg if ($email == false) { Yii::$app->getSession()->setFlash('success', [Yii::t('app', "Для завершения регистрации введите телефон и подтвердите адрес электронной почты.")]); return $this->redirectUser($url = Url::to(['/main/finish-reg', 'id' => $user->id])); } Yii::$app->getSession()->setFlash('success', [Yii::t('app', "Для завершения регистрации введите номер телефона.")]); return $this->redirectUser($url = Url::to(['/main/finish-reg', 'id' => $user->id])); //Yii::$app->user->login($user); } } else { //dd($user->errors); print_r($auth->getErrors()); } } else { $user = User::findOne(['email' => $user->email]); // Если пользователь регитрировался ранее через форму регистации. if ($user->status == User::STATUS_ACTIVE) { Yii::$app->getSession()->setFlash('error', Yii::t('app', "Авторизация с использованием электронного адреса <strong>" . $user->email . "</strong> уже успешно прошла через форму регистрации.\n Воспользуйте ссылкой <strong>" . '"Забыли пароль?"' . "</strong> для востанновления пароля.")); return $this->redirectUser($url = Url::to(['/main/login'])); } else { Yii::$app->getSession()->setFlash('error', [Yii::t('app', "Авторизация с использованием электронного адреса <strong>" . $user->email . "</strong> уже происходила через аккунт <strong>" . $user->auths->source . "</strong>.\n Выполните вход используя аккаунт <strong>" . $user->auths->source . "</strong> или воспользуйте ссылкой <strong>" . '"Забыли пароль?"' . "</strong> для востанновления пароля для\n пользователя с емайл <strong>" . $user->email . "</strong>.", ['client' => $title = $client->getTitle()])]); return $this->redirectUser($url = Url::to(['/main/login'])); } } } } } else { // user already logged in if (!$auth) { // add auth provider $auth = new Auth(['user_id' => Yii::$app->user->id, 'source' => $client->getId(), 'source_id' => $attributes['id']]); $auth->save(); } } return true; }