#1092 - Все пользователи

parent 057adeea
......@@ -37,6 +37,7 @@ class Module extends \common\components\WebModule
public static function adminMenu()
{
return array(
'Все пользователи' => '/school/user-admin/manage',
'Список курсов' => '/school/courses-admin/manage',
'Список уроков' => '/school/lessons-admin/manage',
);
......
<?php
namespace common\modules\school\controllers;
use Yii;
use yii\filters\VerbFilter;
use yii\helpers\Url;
use yii\web\NotFoundHttpException;
use yii\filters\AccessControl;
use himiklab\sortablegrid\SortableGridAction;
use common\modules\users\models\User;
use common\models\LoginForm;
use common\modules\users\forms\UserForm;
use common\modules\rbac\models\AuthAssignment;
class UserAdminController extends \common\components\AdminController
{
public static function actionsTitles()
{
return array(
"Manage" => !empty($_GET['is_deleted'])?"Удаленные пользователи":"Все пользователи",
"View" => "Просмотр пользователя",
"Create" => "Добавление пользователя",
"Update" => "Редактирование пользователя",
"Delete" => "Безвозвратное удаление пользователя",
"SendNewPassword" => "Безвозвратное удаление пользователя",
"SetDeletedFlag" => "Удаление и восстановление пользователя",
"Sort" => "",
"Block" => "",
);
}
public function actions()
{
return [
'sort' => [
'class' => \himiklab\sortablegrid\SortableGridAction::className(),
'modelName' => \common\modules\users\models\User::className(),
],
];
}
/**
* @inheritdoc
*/
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'rules' => [
[
'actions' => ['login', 'error'],
'allow' => true,
],
[
'actions' => ['logout', 'index'],
'allow' => true,
'roles' => ['@'],
],
],
],
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'logout' => ['post'],
],
],
];
}
public function actionBlock($id) {
$model = User::find()->where(['id'=>$id])->one();
if(empty($model)) $error;
$model->status = 'blocked';
$model->save(false);
$this->redirect(['/rbac/role-admin/manage']);
}
public function actionSendNewPassword($id)
{
$model = $this->loadModel($id);
$model->scenario = User::SCENARIO_SEND_NEW_PASSWORD;
$form = new BaseForm('users.SendNewPasswordForm', $model);
if(isset($_POST['User'])) {
if (isset($_POST['User']['password']) && isset($_POST['User']['password_c'])) {
$model->password = $_POST['User']['password'];
$model->password_c = $_POST['User']['password_c'];
} else {
$model->password = 123;
$model->password_c = 123;
}
if ($model->validate()) {
if ($_POST['User']['generate_new'] == 1) {
$password = PasswordGenerator::generate(7);
} else {
$password = $_POST['User']['password'];
}
$model->password = md5($password);
$model->password_c = md5($password);
if ($model->save()) {
Yii::app()->user->setFlash('flash','Пароль для пользователя <b>'.$model->name.'</b> был изменён.');
$email = Yii::app()->email;
$email->to = $user;
$email->from = Setting::getValue('support_email');
$email->subject = 'Hello';
$email->message = Yii::app()->controller->renderInternal(Yii::getPathOfAlias('application.views.yii-mail.pass').'.php', array('password' => $password), true);
$email->send();
$this->redirect('/users/userAdmin/manage');
}
}
}
$this->render('sendNewPassword', array('form' => $form));
}
public function actionManage($is_deleted = 0)
{
//$is_deleted = $this->getRequest()->getQueryParam('is_deleted') ? $this->getRequest()->getQueryParam('is_deleted') : 0;
$model = new \common\modules\users\models\User(/*User::SCENARIO_SEARCH*/);
$model->scenario = User::SCENARIO_SEARCH;
$model->is_deleted = $is_deleted;
$model->attributes = $this->getRequest()->getQueryParams();
\yii::$app->controller->breadcrumbs = [
$is_deleted == 0 ? 'Все пользователи':'Удаленные пользователи',
];
return $this->render('manage', array(
'is_deleted' => $is_deleted,
'model' => $model,
));
}
public function actionView($id)
{
$this->render('view', array(
'model'=> $this->loadModel($id),
));
}
private function saveEmailToNewUser($user, $password)
{
$body = Setting::getValue('email_to_new_user');
$subject = Setting::getValue('email_to_new_user_subject');
$mailer_letter = MailerLetter::model();
$body = $mailer_letter->compileText($body, array(
'gender' => 'Уважаемый(ая)',
'user' => $user,
'password' => $password
));
MailerModule::sendMail($user->email, $subject, $body);
}
public function actionCreate()
{
$model = new User;
$model->scenario = User::SCENARIO_CREATE;
$model->status = "active";
if (!isset($_POST['User']))
{
$model->send_email = true;
}
\Yii::$app->controller->page_title = 'Добавить пользователя';
\Yii::$app->controller->tabs = array(
"управление пользователями" => Url::toRoute("manage"),
);
\yii::$app->controller->breadcrumbs = [
['Все пользователи' => '/users/user-admin/manage'],
'Новый пользователь',
];
if (isset($_POST['User']))
{
$model->attributes = $_POST['User'];
if ($model->validate())
{
$password = $model->password;
$model->password = \Yii::$app->security->generatePasswordHash($model->password);
$model->activate_code=\Yii::$app->security->generatePasswordHash($model->password.'xdf5sf');
if(!$model->save(false)) die(print_r($model->error));
$this->redirect(array(
'/rbac/role-admin/manage',
'id' => $model->id,
'is_created'=>1
));
}
}
$form = new \common\components\BaseForm('/common/modules/users/forms/UserForm', $model);
return $this->render('create', [
'form' => $form->out,
'model' => $model
]);
}
public function actionUpdate($id)
{
$model = $this->loadModel($id);
$old_password = $model->password;
$model->password_c = $model->password = null;
$model->scenario = User::SCENARIO_UPDATE;
\yii::$app->controller->page_title = 'Редактирование пользователя <small>' . $model->name.'</small>';
\yii::$app->controller->tabs = [
"управление пользователями" => \yii\helpers\Url::toRoute("manage"),
];
\yii::$app->controller->breadcrumbs = [
['Все пользователи' => '/users/user-admin/manage'],
$model->name,
];
if($model->load(Yii::$app->request->post()))
{
if($model->password)
{
$model->password = $model->password_c = \Yii::$app->security->generatePasswordHash($model->password);
}
else
{
$model->password = $model->password_c = $old_password;
}
if($model->save())
{
AuthAssignment::updateUserRole($model->id, $_POST['User']['role']);
return $this->redirect(array(
'/rbac/role-admin/manage',
'id'=> $model->id
));
}
}
$form = new \common\components\BaseForm('/common/modules/users/forms/UserForm', $model);
return $this->render('update', array(
'form' => $form->out,
'model' => $model,
));
}
public function actionDelete($id)
{
$this->findModel($id)->delete();
return $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : ['/rbac/role-admin/manage']);
}
public function actionSetDeletedFlag($id, $is_deleted)
{
$model = $this->loadModel($id);
$model->scenario = User::SCENARIO_DELETE;
$model->is_deleted = $is_deleted;
$model->date_delete = new CDbExpression('NOW()');
$model->save(false);
return $this->redirect($this->createUrl('manage'));
}
/**
* Finds the Faq model based on its primary key value.
* If the model is not found, a 404 HTTP exception will be thrown.
* @param integer $id
* @return Faq the loaded model
* @throws NotFoundHttpException if the model cannot be found
*/
protected function findModel($id)
{
if (($model = User::findOne($id)) !== null) {
return $model;
} else {
throw new NotFoundHttpException('The requested page does not exist.');
}
}
}
\ No newline at end of file
<style>
#user-password + a{
display: none !important;
}
#user-password_c + a{
display: none !important;
}
</style>
<?php
echo $form;
$url_block = \yii\helpers\Url::toRoute(['/users/user-admin/block', 'id'=>$model->id]);
$url_delete = \yii\helpers\Url::toRoute(['/users/user-admin/delete', 'id'=>$model->id]);
$script = <<< JS
$('#block').on('click', function(e) {
document.location.href = "$url_block";
});
$('#delete').on('click', function(e) {
if(prompt('Вы действительно хотите удалить пользователя\\nНАВСЕГДА и все его данные из системы?\\nВведите пароль на удаление: ') == '25350')
document.location.href = "$url_delete";
else alert('Неверный пароль');
});
JS;
$this->registerJs($script);
$status = \yii::t('users',$model->status);
$active = \yii::t('users','active');
$block = \yii::t('users','blocked');
$script = <<< JS
"use strict";
$("#user-phone").mask("8(999) 999-9999");
$("#user-mobile_phone").mask("8(999) 999-9999");
$('#user-password').passwordStrength({targetDiv: '#passwordStrengthDiv'});
$('#user-password_c').passwordStrength({targetDiv: '#passwordStrengthDiv2'});
$('[data-id="switchery-state-text"]').text('$active');
$('[data-change="check-switchery-state-text"]').live('change', function() {
if($(this).prop('checked'))
$('[data-id="switchery-state-text"]').text('$active');
else
$('[data-id="switchery-state-text"]').text('$block');
});
$('#block').hide();
$('#delete').hide();
$('#delete').parent().next().hide();
JS;
$this->registerJs($script);
?>
<?php $this->registerJsFile('/plugins/masked-input/masked-input.min.js', ['position' => \yii\web\View::POS_END]);?>
<?php $this->registerJsFile('/js/form-plugins.demo.min.js', ['position' => \yii\web\View::POS_HEAD]);?>
<?php $this->registerCssFile('/plugins/password-indicator/css/password-indicator.css', ['position' => \yii\web\View::POS_HEAD]);?>
\ No newline at end of file
<script type="text/javascript">
$(function()
{
$('.recover_u, .delete_u').live('click', function()
{
var msg = $(this).attr('class') == 'recover_u' ? 'Восстановить пользователя?' : 'Удалить пользователя безвозвратно?';
if (confirm(msg))
{
var url = $(this).attr('href');
$.fn.yiiGridView.update('user-grid',
{
type:'POST',
url:url,
success:function(data)
{
$.fn.yiiGridView.update('user-grid');
}
});
}
return false;
});
});
</script>
<?php
use yii\helpers\Url;
use yii\helpers\ArrayHelper;
use yii\helpers\Html;
use common\components\zii\AdminGrid;
use yii\grid\GridView;
?>
<?php if (\Yii::$app->session->hasFlash('flash')) : ?>
<div class="message"><span><?php echo Yii::app()->session->getFlash('flash'); ?></span></div>
<?php endif; ?>
В этом разделе представлен полный список пользователей зарегистрированных на сайте. <br><br>
<?php
if ($is_deleted)
{
\Yii::$app->controller->tabs = array(
"Все пользователи" => Url::toRoute("manage")
);
$buttons = [
'class' => 'common\components\ColorActionColumn',
'options' => ['width' => '75'],
'template' => '{revert}&nbsp;{view}&nbsp;{remove}',
'buttons' => [
'remove' => function($url, $data) {
$url = Url::toRoute(["/users/userAdmin/delete", 'id'=>$data->id, 'ajax'=>'user-grid']);
$imageUrl = '/img/icons/remove.png';
$options = [
'title' => 'удалить окончательно',
'class' => 'delete_u',
];
return \yii\helpers\Html::a('<span class="glyphicon"><img src="'.$imageUrl.'"></span>', $url, $options);
},
'revert' => function($url, $data) {
$url = Url::toRoute(["/users/userAdmin/SetDeletedFlag", 'id'=>$data->id, 'is_deleted'=>0]);
$imageUrl = '/img/icons/revert.png';
$options = [
'title' => 'Восстановить пользователя',
'class' => 'recover_u',
];
return \yii\helpers\Html::a('<span class="glyphicon"><img src="'.$imageUrl.'"></span>', $url, $options);
}
]
];
}
else
{
\Yii::$app->controller->tabs = array(
"Удаленные пользователи" => Url::toRoute(["manage", "is_deleted" => 1]),
);
$buttons = [
'class' => 'common\components\ColorActionColumn',
'options' => ['width' => '75'],
'template' => '{sendEmail}&nbsp;{sendNewPassword}<br>{view}&nbsp;{update}&nbsp;{delete}',
'buttons' => [
'sendNewPassword' => function($url, $data) {
$url = Url::toRoute("/users/userAdmin/sendNewPassword/id/$data->id");
$imageUrl = '/img/icons/mail.png';
$title = 'Отправить новый пароль';
return \yii\helpers\Html::a('<span class="glyphicon"><img src="'.$imageUrl.'"></span>', $url, ['title' => $title]);
},
'sendEmail' => function($url, $data) {
$url = '"mailto:".$data->email';
$imageUrl = '/img/icons/email.png';
$title = 'Отправить сообщение на email';
return \yii\helpers\Html::a('<span class="glyphicon"><img src="'.$imageUrl.'"></span>', $url, ['title' => $title]);
},
]
];
}
\yii\widgets\Pjax::begin(['id' => 'demo']);
echo AdminGrid::widget([
'id' => 'user-grid',
'dataProvider' => $model->search(Yii::$app->request->queryParams),
'filterModel' => $model,
'class' => 'table table-striped table-bordered nowrap',
'columns' => [
['class'=>'yii\grid\SerialColumn'],
'name',
'email',
'date_create',
$buttons
],
]);
yii\widgets\Pjax::end();
?>
<style>
#user-password + a, #user-password_c + a{
display: none;
}
</style>
<?php
echo $form;
$url_block = \yii\helpers\Url::toRoute(['/users/user-admin/block', 'id'=>$model->id]);
$url_delete = \yii\helpers\Url::toRoute(['/users/user-admin/delete', 'id'=>$model->id]);
$script = <<< JS
$('#block').on('click', function(e) {
document.location.href = "$url_block";
});
$('#delete').on('click', function(e) {
if(prompt('Вы действительно хотите удалить пользователя\\nНАВСЕГДА и все его данные из системы?\\nВведите пароль на удаление: ') == '25350')
document.location.href = "$url_delete";
else alert('Неверный пароль');
});
JS;
$this->registerJs($script);
$status = \yii::t('users',$model->status);
$active = \yii::t('users','active');
$block = \yii::t('users','blocked');
$script = <<< JS
"use strict";
$("#user-phone").mask("8(999) 999-9999");
$("#user-mobile_phone").mask("8(999) 999-9999");
$('#user-password').passwordStrength({targetDiv: '#passwordStrengthDiv'});
$('#user-password_c').passwordStrength({targetDiv: '#passwordStrengthDiv2'});
$('[data-id="switchery-state-text"]').text('$status');
$('[data-change="check-switchery-state-text"]').live('change', function() {
if($(this).prop('checked'))
$('[data-id="switchery-state-text"]').text('$active');
else
$('[data-id="switchery-state-text"]').text('$block');
});
JS;
$this->registerJs($script);
?>
<?php $this->registerJsFile('/plugins/masked-input/masked-input.min.js', ['position' => \yii\web\View::POS_END]);?>
<?php $this->registerJsFile('/js/form-plugins.demo.min.js', ['position' => \yii\web\View::POS_HEAD]);?>
<?php $this->registerCssFile('/plugins/password-indicator/css/password-indicator.css', ['position' => \yii\web\View::POS_HEAD]);?>
\ No newline at end of file
<?php
$this->page_title = "Просмотр Пользователя: {$model->name}";
$this->tabs = array(
"управление пользователями" => $this->createUrl("manage"),
"редактировать" => $this->createUrl("update", array("id" => $model->id))
);
if(!empty($_GET['is_created'])) {
echo '<span style="font-weight: bold; font-size: 10px; display: inline-block; margin-bottom: 4px;">
Пользователь был успешно создан. Для подтверждения e-mail адреса, вы должны перейдя по ссылке указанной в письме, которое было отправлено Вам на почтовый адрес.
<br />Если письмо вам не пришло, то проверьте его в СПАМе или вышлите повторно.
</span>';
}
$this->widget('application.components.DetailView', array(
'data' => $model,
'attributes' => array(
'fio',
'email',
'phone',
array(
'name' => 'role',
'value' => $model->role->description
),
array(
'name' => 'status',
'value' => User::$status_list[$model->status]
),
'date_create'
),
));
?>
......@@ -42,7 +42,6 @@ class users extends \common\components\WebModule
public static function adminMenu()
{
return array(
'Зарегистрированные' => '/users/user-admin/manage',
// 'Добавить пользователя' => '/users/user-admin/create',
);
}
......
......@@ -39,8 +39,6 @@ use yii\grid\GridView;
<?php
if ($is_deleted)
{
//$this->page_title = 'Удаленные пользователи';
\Yii::$app->controller->tabs = array(
"Все пользователи" => Url::toRoute("manage")
);
......@@ -73,8 +71,6 @@ if ($is_deleted)
}
else
{
//$this->page_title = 'Управление пользователями';
\Yii::$app->controller->tabs = array(
"Удаленные пользователи" => Url::toRoute(["manage", "is_deleted" => 1]),
);
......@@ -82,17 +78,8 @@ else
$buttons = [
'class' => 'common\components\ColorActionColumn',
'options' => ['width' => '75'],
//'template' => '{sendNewPassword} {view} {update} {delete}',
'template' => '{sendEmail}&nbsp;{sendNewPassword}<br>{view}&nbsp;{update}&nbsp;{delete}',
//'deleteButtonUrl' => 'Url::toRoute("/users/userAdmin/SetDeletedFlag/id/$data->id/is_deleted/1")',
'buttons' => [
/*'sendNewPassword' => array(
'url' => 'Url::toRoute("/users/userAdmin/sendNewPassword/id/$data->id")',
'imageUrl' => '/images/icons/mail.png',
'options' => array(
'title' => 'Отправить новый пароль',
),
),*/
'sendNewPassword' => function($url, $data) {
$url = Url::toRoute("/users/userAdmin/sendNewPassword/id/$data->id");
$imageUrl = '/img/icons/mail.png';
......@@ -109,55 +96,17 @@ else
];
}
\Yii::$app->controller->tabs["добавить"] = Url::toRoute("create");
\Yii::$app->controller->tabs["импорт из CSV-файла"] = Url::toRoute("importCSV");
//die(print_r(\Yii::$app->authManager));
$roles = ArrayHelper::map(\Yii::$app->authManager->getRoles(), 'name', 'description');
//die(print_r(\Yii::$app->authManager->getRoles()));
$filter_hint = '<div class="search-info">
<strong>Правила поиска</strong>
<ul>
<li>*контактор* - по слову или его части. В результате поиска отображаются даже те слова, которые начинались с
буквы «К» (то есть поиск по данному запросу осуществляется как запрос «*контактор*» и как «контактор*»)
</li>
<li>конта* - только по началу слова</li>
<li>*актор - по окончанию слова</li>
<li>*автомат*выкл* - по двум словам (автоматические выключатели)</li>
</ul>
</div>';
//use \yii\helpers\Html;
\yii\widgets\Pjax::begin(['id' => 'demo']);
echo AdminGrid::widget([
//echo \yii\grid\GridView::widget(array(
'id' => 'user-grid',
// 'ajaxUpdate' => true,
'dataProvider' => $model->search(Yii::$app->request->queryParams),
'filterModel' => $model,
'class' => 'table table-striped table-bordered nowrap',
// 'filter_hint' => $filter_hint,
'columns' => [
['class'=>'yii\grid\SerialColumn'],
'name',
'email',
'date_create',
[
'header' => '',
'attribute' => 'email',
// 'value' => (function ($model, $key, $index, $column){ return Html::mailto("email", $column, ["title"=>$column]);}),
'format' => 'raw',
'filter' => false
], /**/
/*array(
'name' => 'status',
'value' => 'User::$status_list[$data->status]',
'filter' => false
),
[
'header' => 'Группа пользователей',
'value' => 'roleName',
'filter' => Html::dropDownList('role', '', $roles, ['empty'=> 'Все', 'class'=>'form-control']),
], */
$buttons
],
]);
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment