/** * Получение модели пользователя * @return bool|null|static */ public function getUser() { if ($this->_user === false) { $this->_user = User::findOne(['email' => $this->email]); } return $this->_user; }
/** * Отправка письма согласно шаблону "confirmEmail" * после регистрации * @param bool $insert * @param array $changedAttributes */ public function afterSave($insert, $changedAttributes) { parent::afterSave($insert, $changedAttributes); $view = '@lowbase/user/mail/confirmEmail'; if (method_exists(\Yii::$app->controller->module, 'getCustomMailView')) { $view = \Yii::$app->controller->module->getCustomMailView('confirmEmail', $view); } Yii::$app->mailer->compose($view, ['model' => $this])->setFrom([Yii::$app->params['adminEmail']])->setTo($this->email)->setSubject(Yii::t('user', 'Подтверждение регистрации на сайте'))->send(); }
/** * @param string $token - токен * @param array $config - параметры * @throws \yii\base\InvalidParamException - при пустом или неправильном токене */ public function __construct($token, $config = []) { if (empty($token) || !is_string($token)) { throw new InvalidParamException(Yii::t('user', 'Отсутствует код подтверждения.')); } $this->_user = User::findByEmailConfirmToken($token); if (!$this->_user) { throw new InvalidParamException(Yii::t('user', 'Неверный токен.')); } parent::__construct($config); }
/** * Создает DataProvider на основе переданных данных * @param $params - параметры * @return ActiveDataProvider */ public function search($params) { $query = User::find(); $dataProvider = new ActiveDataProvider(['query' => $query, 'pagination' => ['pageSize' => $this::COUNT], 'sort' => array('defaultOrder' => ['created_at' => SORT_DESC])]); $this->load($params); // Если валидация не пройдена, то ничего не выводить if (!$this->validate()) { $query->where('0=1'); return $dataProvider; } // Фильтр данных $query->andFilterWhere(['id' => $this->id, 'sex' => $this->sex, 'birthday' => $this->birthday, 'country_id' => $this->country_id, 'city_id' => $this->city_id, 'status' => $this->status, 'updated_at' => $this->updated_at, 'login_at' => $this->login_at]); if ($this->created_at) { $date = new \DateTime($this->created_at); $this->created_at = $date->format('Y-m-d'); } $query->andFilterWhere(['like', 'first_name', $this->first_name])->andFilterWhere(['like', 'last_name', $this->last_name])->andFilterWhere(['like', 'auth_key', $this->auth_key])->andFilterWhere(['like', 'password_hash', $this->password_hash])->andFilterWhere(['like', 'password_reset_token', $this->password_reset_token])->andFilterWhere(['like', 'email_confirm_token', $this->email_confirm_token])->andFilterWhere(['like', 'email', $this->email])->andFilterWhere(['like', 'image', $this->image])->andFilterWhere(['like', 'phone', $this->phone])->andFilterWhere(['like', 'created_at', $this->created_at])->andFilterWhere(['like', 'address', $this->address]); if ($this->id_from) { $query->andFilterWhere(['>=', 'id', $this->id_from]); } if ($this->id_till) { $query->andFilterWhere(['<=', 'id', $this->id_till]); } if ($this->created_at_from) { $date_from = new \DateTime($this->created_at_from); $query->andFilterWhere(['>=', 'created_at', $date_from->format('Y-m-d')]); } if ($this->created_at_till) { $date_till = new \DateTime($this->created_at_till); $query->andFilterWhere(['<=', 'created_at', $date_till->format('Y-m-d')]); } if ($this->login_at_from) { $date_from = new \DateTime($this->login_at_from); $query->andFilterWhere(['>=', 'login_at', $date_from->format('Y-m-d')]); } if ($this->login_at_till) { $date_till = new \DateTime($this->login_at_till); $query->andFilterWhere(['<=', 'login_at', $date_till->format('Y-m-d')]); } if ($this->birthday_from) { $birthday_from = new \DateTime($this->birthday_from); $query->andFilterWhere(['>=', 'birthday', $birthday_from->format('Y-m-d')]); } if ($this->birthday_till) { $birthday_till = new \DateTime($this->birthday_till); $query->andFilterWhere(['<=', 'birthday', $birthday_till->format('Y-m-d')]); } return $dataProvider; }
/** * @param array $token - токен * @param $password - пароль * @param array $config - праметры */ public function __construct($token, $password, $config = []) { if (empty($token) || !is_string($token)) { throw new InvalidParamException(Yii::t('user', 'Ключ для восстановления пароля не найден.')); } if (empty($password) || !is_string($password)) { throw new InvalidParamException(Yii::t('user', 'Пароль не задан.')); } $this->_user = User::findByPasswordResetToken($token); $this->password = $password; if (!$this->_user) { throw new InvalidParamException(Yii::t('user', 'Неправильный ключ для восстановления пароля.')); } parent::__construct($config); }
/** * Генерация пароля и ключа авторизации, * преобразование дня рождения в необходимый * формат перед сохранением * * @param bool $insert * @return bool */ public function beforeSave($insert) { if (parent::beforeSave($insert)) { // Если указан новый пароль if ($this->password) { $this->setPassword($this->password); $this->generateAuthKey(); } // Преобразование дня рождения if ($this->birthday) { $date = new \DateTime($this->birthday); $this->birthday = $date->format('Y-m-d'); } return true; } return false; }
/** * Отправка сообщения с подтверждением * нового пароля * @return bool */ public function sendEmail() { /* @var $user User */ $user = User::findByEmail($this->email); if ($user) { if (!User::isPasswordResetTokenValid($user->password_reset_token)) { $user->generatePasswordResetToken(); } if ($user->save()) { // Отправка по шаблону письма "passwordResetToken" $view = '@lowbase/user/mail/passwordResetToken'; if (method_exists(\Yii::$app->controller->module, 'getCustomMailView')) { $view = \Yii::$app->controller->module->getCustomMailView('passwordResetToken', $view); } return \Yii::$app->mailer->compose($view, ['model' => $user, 'password' => $this->password])->setFrom(\Yii::$app->params['adminEmail'])->setTo($this->email)->setSubject(\Yii::t('user', 'Сброс пароля на сайте'))->send(); } } return false; }
/** * Пользователи из города * @return \yii\db\ActiveQuery */ public function getUsers() { return $this->hasMany(User::className(), ['city_id' => 'id']); }
<div class="col-lg-6"> <?php echo $form->field($model, 'image'); ?> </div> </div> <div class="row"> <div class="col-lg-6"> <?php echo $form->field($model, 'created_by')->widget(Select2::classname(), ['data' => User::getAll(true), 'options' => ['placeholder' => '', 'id' => 'created'], 'pluginOptions' => ['allowClear' => true]]); ?> </div> <div class="col-lg-6"> <?php echo $form->field($model, 'updated_by')->widget(Select2::classname(), ['data' => User::getAll(true), 'options' => ['placeholder' => '', 'id' => 'updated'], 'pluginOptions' => ['allowClear' => true]]); ?> </div> </div> <div class="row"> <div class="col-lg-6"> <?php echo $form->field($model, 'created_at_from')->widget(DatePicker::classname(), ['options' => ['placeholder' => ''], 'type' => DatePicker::TYPE_COMPONENT_APPEND, 'pluginOptions' => ['autoclose' => true, 'format' => 'dd.mm.yyyy']]); ?> </div> <div class="col-lg-6"> <?php echo $form->field($model, 'created_at_till')->widget(DatePicker::classname(), ['options' => ['placeholder' => ''], 'type' => DatePicker::TYPE_COMPONENT_APPEND, 'pluginOptions' => ['autoclose' => true, 'format' => 'dd.mm.yyyy']]); ?> </div>
/** * Поиск пользователя по ID * @param $id - ID пользователя * @return null|static * @throws NotFoundHttpException */ protected function findModel($id) { if (($model = User::findOne($id)) !== null) { return $model; } else { throw new NotFoundHttpException(Yii::t('user', 'Пользователь не найден.')); } }
if ($model->image) { echo "<img src='/" . $model->image . "' class='thumbnail'>"; echo "<p>" . Html::a(Yii::t('user', 'Удалить фото'), ['rmv', 'id' => $model->id]) . "</p>"; } else { if ($model->sex === User::SEX_FEMALE) { echo "<img src='" . $assets->baseUrl . "/image/female.png' class='thumbnail'>"; } else { echo "<img src='" . $assets->baseUrl . "/image/male.png' class='thumbnail'>"; } } ?> <?php echo $form->field($model, 'photo')->fileInput(['maxlength' => true, 'placeholder' => $model->getAttributeLabel('photo')]); ?> </div> </div> <div class="col-lg-6"> <?php echo $form->field($model, 'sex')->radioList([null => Yii::t('user', 'Не указан')] + User::getSexArray()); ?> </div> </div> <?php ActiveForm::end(); ?> </div> </div>
</div> <div class="col-lg-6"> </div> </div> <div class="row"> <div class="col-lg-6"> <?php echo '<label class="control-label">' . Yii::t('user', 'Обладает допусками') . '</label>'; ?> <?php echo Select2::widget(['name' => 'AuthItem[children_array]', 'value' => array_keys($model->children_array), 'data' => AuthItem::getAll(), 'options' => ['multiple' => true], 'pluginOptions' => ['tags' => true]]); ?> </div> <div class="col-lg-6"> <?php echo '<label class="control-label">' . Yii::t('user', 'Обладают пользователи') . '</label>'; ?> <?php echo Select2::widget(['name' => 'AuthItem[user_array]', 'value' => array_keys($model->user_array), 'data' => User::getAll(), 'options' => ['multiple' => true], 'pluginOptions' => ['tags' => true]]); ?> </div> </div> <?php ActiveForm::end(); ?> </div>
/** * Пользователи, обладающие текущей ролью или допуском * @return $this */ public function getUsers() { return $this->hasMany(User::className(), ['id' => 'user_id'])->viaTable('lb_auth_assignment', ['item_name' => 'name']); }
switch ($model->status) { case User::STATUS_BLOCKED: return '<span class="label label-danger"> <i class="glyphicon glyphicon-lock"></i> ' . User::getStatusArray()[User::STATUS_BLOCKED] . '</span>'; break; case User::STATUS_WAIT: return '<span class="label label-warning"> <i class="glyphicon glyphicon-hourglass"></i> ' . User::getStatusArray()[User::STATUS_WAIT] . '</span>'; break; case User::STATUS_ACTIVE: return '<span class="label label-success"> <i class="glyphicon glyphicon-ok"></i> ' . User::getStatusArray()[User::STATUS_ACTIVE] . '</span>'; break; } return false; }, 'filter' => User::getStatusArray()], ['template' => '{view} {update} {delete}', 'class' => 'kartik\\grid\\ActionColumn'], ['class' => 'kartik\\grid\\CheckboxColumn', 'headerOptions' => ['class' => 'kartik-sheet-style']]]; echo GridView::widget(['layout' => "{items}\n{summary}\n{pager}", 'dataProvider' => $dataProvider, 'filterModel' => $searchModel, 'columns' => $gridColumns, 'containerOptions' => ['style' => 'overflow: auto'], 'headerRowOptions' => ['class' => 'kartik-sheet-style'], 'filterRowOptions' => ['class' => 'kartik-sheet-style'], 'pjax' => false, 'panel' => ['heading' => '<i class="glyphicon glyphicon-user"></i> ' . Yii::t('user', 'Пользователи'), 'type' => GridView::TYPE_PRIMARY, 'before' => Html::button('<span class="glyphicon glyphicon-search"></span> ' . Yii::t('user', 'Поиск'), ['class' => 'filter btn btn-default', 'data-toggle' => 'modal', 'data-target' => '#filter']), 'after' => "<div class='text-right'><b>" . Yii::t('user', 'Выбранные') . ":</b> " . Html::button('<span class="glyphicon glyphicon-eye-open"></span> ' . Yii::t('user', 'Активировать'), ['class' => 'btn btn-default open-all']) . " " . Html::button('<span class="glyphicon glyphicon-eye-close"></span> ' . Yii::t('user', 'Заблокировать'), ['class' => 'btn btn-default close-all']) . " " . Html::button('<span class="glyphicon glyphicon-trash"></span> ' . Yii::t('user', 'Удалить'), ['class' => 'btn btn-danger delete-all']) . "</div>"], 'export' => ['fontAwesome' => true], 'bordered' => true, 'striped' => true, 'condensed' => true, 'persistResize' => false, 'hover' => true, 'responsive' => true]); ?> </div> <?php $this->registerJs(' $(".delete-all").click(function(){ var keys = $(".grid-view").yiiGridView("getSelectedRows"); $.ajax({ url: "' . Url::to(['user/multidelete']) . '", type:"POST", data:{keys: keys}, success: function(data){ location.reload();
$icon = $model->is_folder ? 'glyphicon glyphicon-folder-open' : 'glyphicon glyphicon-file'; return "<span class='" . $icon . "'></span> " . $model->id; }], 'name', ['attribute' => 'parent_id', 'vAlign' => 'middle', 'format' => 'raw', 'width' => '150px', 'value' => function ($model) { return $model->parent_id && $model->parent ? $model->parent->name : null; }, 'filter' => Document::getAll(), 'filterType' => GridView::FILTER_SELECT2, 'filterWidgetOptions' => ['pluginOptions' => ['allowClear' => true]], 'filterInputOptions' => ['placeholder' => ' ', 'class' => 'form-control']], ['attribute' => 'template_id', 'vAlign' => 'middle', 'format' => 'raw', 'width' => '150px', 'value' => function ($model) { return $model->template_id && $model->template ? $model->template->name : null; }, 'filter' => Template::getAll(), 'filterType' => GridView::FILTER_SELECT2, 'filterWidgetOptions' => ['pluginOptions' => ['allowClear' => true]], 'filterInputOptions' => ['placeholder' => ' ', 'class' => 'form-control']], ['attribute' => 'created_at', 'vAlign' => 'middle', 'format' => ['date', 'dd.MM.Y HH:mm:ss'], 'width' => '200px', 'filter' => DatePicker::widget(['value' => isset($_GET['DocumentSearch']['created_at']) ? $_GET['DocumentSearch']['created_at'] : '', 'name' => 'DocumentSearch[created_at]', 'type' => DatePicker::TYPE_COMPONENT_APPEND, 'pluginOptions' => ['format' => 'dd.mm.yyyy', 'todayHighlight' => true]])], ['attribute' => 'created_by', 'vAlign' => 'middle', 'format' => 'raw', 'width' => '200px;', 'value' => function ($model) { $value = ''; if (isset($model->created)) { $value .= $model->created->first_name; if ($model->created->last_name) { $value .= ' ' . $model->created->last_name; } } return $value . ' (' . $model->created_by . ')'; }, 'filter' => User::getAll(true), 'filterType' => GridView::FILTER_SELECT2, 'filterWidgetOptions' => ['pluginOptions' => ['allowClear' => true]], 'filterInputOptions' => ['placeholder' => ' ', 'class' => 'form-control', 'id' => 'created_by']], ['attribute' => 'status', 'vAlign' => 'middle', 'format' => 'raw', 'value' => function ($model) { switch ($model->status) { case Document::STATUS_BLOCKED: return '<span class="label label-danger"> <i class="glyphicon glyphicon-lock"></i> ' . Document::getStatusArray()[Document::STATUS_BLOCKED] . '</span>'; break; case Document::STATUS_WAIT: return '<span class="label label-warning"> <i class="glyphicon glyphicon-hourglass"></i> ' . Document::getStatusArray()[Document::STATUS_WAIT] . '</span>'; break; case Document::STATUS_ACTIVE: return '<span class="label label-success"> <i class="glyphicon glyphicon-ok"></i> ' . Document::getStatusArray()[Document::STATUS_ACTIVE] . '</span>'; break; } return false;
/** * Удлаение ключа авторизации соц. сети (отвзяывание) * @param $id - ID ключа авторизации * @return \yii\web\Response */ public function actionUnbind($id) { /** @var \lowbase\user\models\UserOauthKey $key */ $key = UserOauthKey::findOne(['user_id' => Yii::$app->user->id, 'provider_id' => UserOauthKey::getAvailableClients()[$id]]); if (!$key) { Yii::$app->session->setFlash('error', Yii::t('user', 'Ключ не найден')); } else { /** @var \lowbase\user\models\User $user */ $user = User::findOne($key->user_id); if ($user) { if (UserOauthKey::isOAuth($user->id) <= 1 && $user->email === null) { Yii::$app->session->setFlash('error', Yii::t('user', 'Нельзя отвязать единственную соц. сеть, не заполнив Email')); } elseif (UserOauthKey::isOAuth($user->id) <= 1 && $user->password_hash === null) { Yii::$app->session->setFlash('error', Yii::t('user', 'Нельзя отвязать единственную соц. сеть, не заполнив пароль')); } else { $key->delete(); Yii::$app->session->setFlash('success', Yii::t('user', 'Ключ входа удален')); } } } return $this->redirect(Yii::$app->request->referrer); }
?> <?php echo Html::a('<i class="glyphicon glyphicon-menu-left"></i> ' . Yii::t('user', 'Отмена'), ['index'], ['class' => 'btn btn-default']); ?> </p> <?php $keys = ''; if ($model->keys) { $keys .= "<div class='row'>"; foreach ($model->keys as $key) { $services = array_flip(UserOauthKey::getAvailableClients()); $keys .= "<div class='col-xs-1'><a href='" . UserOauthKey::getSites()[$key->provider_id] . $key->page . "'><span class='auth-icon " . $services[$key->provider_id] . "'></span></a></div>"; } $keys .= "</div>"; } $roles = ''; if ($model->authAssignments) { foreach ($model->authAssignments as $role) { $type = $role->itemName->type == 1 ? 'label-primary' : 'label-success'; $roles .= Html::a('<span class="label ' . $type . '">' . $role->itemName->description . '</span>', ['auth-item/view', 'id' => $role->itemName->name]) . " "; } } ?> <?php echo DetailView::widget(['model' => $model, 'attributes' => ['id', 'first_name', 'last_name', 'email:email', ['attribute' => 'sex', 'value' => $model->sex ? User::getSexArray()[$model->sex] : null], ['attribute' => 'birthday', 'format' => ['date', 'dd.MM.Y']], 'phone', ['attribute' => 'country_id', 'value' => isset($model->country) ? $model->country->name : null], ['attribute' => 'city_id', 'value' => isset($model->city) ? $model->city->city . " (" . $model->city->state . " " . $model->city->region . ")" : null], 'address', ['attribute' => 'status', 'value' => User::getStatusArray()[$model->status]], 'ip', ['attribute' => 'created_at', 'format' => ['date', 'dd.MM.Y HH:mm:ss']], ['attribute' => 'updated_at', 'format' => ['date', 'dd.MM.Y HH:mm:ss']], ['attribute' => 'login_at', 'format' => ['date', 'dd.MM.Y HH:mm:ss']], ['attribute' => 'image', 'format' => 'raw', 'value' => $model->image ? '<img src="/' . $model->image . '" class="thumbnail">' : null], ['attribute' => Yii::t('user', 'Социальные сети'), 'format' => 'raw', 'value' => $keys ? $keys : null], ['attribute' => Yii::t('user', 'Обладает ролями и допусками'), 'format' => 'raw', 'value' => $roles ? $roles : null]]]); ?> </div>
/** * Пользователь, которому принадлежит ключ * @return \yii\db\ActiveQuery */ public function getUser() { return $this->hasOne(User::className(), ['id' => 'user_id']); }
<?php echo $form->field($model, 'country_id')->widget(Select2::classname(), ['data' => Country::getAll(), 'options' => ['placeholder' => '', 'id' => 'country_id'], 'pluginOptions' => ['allowClear' => true]]); ?> </div> <div class="col-lg-6"> <?php echo $form->field($model, 'city_id')->widget(Select2::classname(), ['initValueText' => $model->city_id && $model->city ? $model->city->city . ' (' . $model->city->state . ", " . $model->city->region . ")" : '', 'options' => ['placeholder' => ''], 'pluginOptions' => ['allowClear' => true, 'minimumInputLength' => 3, 'ajax' => ['url' => Url::to(['city/find']), 'dataType' => 'json', 'data' => new JsExpression('function(params) { return {q:params.term}; }')], 'escapeMarkup' => new JsExpression('function (markup) { return markup; }'), 'templateResult' => new JsExpression('function(city) { return city.text; }'), 'templateSelection' => new JsExpression('function (city) { return city.text; }')]]); ?> </div> </div> <div class="row"> <div class="col-lg-6"> <?php echo $form->field($model, 'status')->dropDownList(['' => ''] + User::getStatusArray()); ?> </div> <div class="col-lg-6"> <?php echo $form->field($model, 'address'); ?> </div> </div> <div class="row"> <div class="col-lg-6"> <?php echo $form->field($model, 'created_at_from')->widget(DatePicker::classname(), ['options' => ['placeholder' => ''], 'type' => DatePicker::TYPE_COMPONENT_APPEND, 'pluginOptions' => ['autoclose' => true, 'format' => 'dd.mm.yyyy']]); ?> </div>
public function getUpdated() { return $this->hasOne(User::className(), ['id' => 'updated_by']); }