Completed
Push — master ( 7d7e50...55e0f0 )
by Alexey
11:27
created

DefaultController::processRemoveAvatar()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 13
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 13
rs 9.2
cc 4
eloc 9
nc 3
nop 2
1
<?php
2
3
namespace modules\users\controllers\backend;
4
5
use Yii;
6
use yii\helpers\Url;
7
use modules\users\models\LoginForm;
8
use modules\users\models\backend\User;
9
use modules\users\models\backend\UserSearch;
10
use modules\users\models\UploadForm;
11
use yii\web\UploadedFile;
12
use yii\web\Controller;
13
use yii\web\NotFoundHttpException;
14
use yii\filters\VerbFilter;
15
use yii\filters\AccessControl;
16
use modules\rbac\models\Permission;
17
use modules\users\Module;
18
19
/**
20
 * Class DefaultController
21
 * @package modules\users\controllers\backend
22
 */
23
class DefaultController extends Controller
24
{
25
    protected $jsFile;
26
27
    /**
28
     * @inheritdoc
29
     */
30
    public function behaviors()
31
    {
32
        return [
33
            'verbs' => [
34
                'class' => VerbFilter::className(),
35
                'actions' => [
36
                    'delete' => ['POST'],
37
                    'logout' => ['POST'],
38
                ],
39
            ],
40
            'access' => [
41
                'class' => AccessControl::className(),
42
                'rules' => [
43
                    [
44
                        'actions' => ['login'],
45
                        'allow' => true,
46
                        'roles' => ['?']
47
                    ],
48
                    [
49
                        'actions' => ['logout'],
50
                        'allow' => true,
51
                        'roles' => ['@']
52
                    ],
53
                    [
54
                        'allow' => true,
55
                        'roles' => [Permission::PERMISSION_MANAGER_USERS]
56
                    ],
57
                ],
58
            ],
59
        ];
60
    }
61
62
    public function init()
63
    {
64
        parent::init();
65
66
        $this->jsFile = '@modules/users/views/ajax/ajax.js';
67
68
        // Publish and register the required JS file
69
        Yii::$app->assetManager->publish($this->jsFile);
70
        $this->getView()->registerJsFile(
71
            Yii::$app->assetManager->getPublishedUrl($this->jsFile),
72
            ['depends' => 'yii\web\JqueryAsset',] // depends
73
        );
74
    }
75
76
    /**
77
     * Lists all User models.
78
     * @return mixed
79
     */
80
    public function actionIndex()
81
    {
82
        $searchModel = new UserSearch();
83
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
84
85
        return $this->render('index', [
86
            'searchModel' => $searchModel,
87
            'dataProvider' => $dataProvider,
88
        ]);
89
    }
90
91
    /**
92
     * Displays a single User model.
93
     * @param integer $id
94
     * @return mixed
95
     */
96
    public function actionView($id)
97
    {
98
        if ($model = $this->findModel($id)) {
99
            return $this->render('view', [
100
                'model' => $model,
101
            ]);
102
        }
103
        return $this->redirect(['index']);
104
    }
105
106
    /**
107
     * Creates a new User model.
108
     * If creation is successful, the browser will be redirected to the 'view' page.
109
     * @return mixed
110
     */
111
    public function actionCreate()
112
    {
113
        $model = new User();
114
115
        $uploadModel = new UploadForm();
116
117
        $model->role = $model::RBAC_DEFAULT_ROLE;
118
        $model->status = $model::STATUS_WAIT;
119
        $model->registration_type = Yii::$app->user->identity->getId();
120
121
        if ($model->load(Yii::$app->request->post())) {
122
            $uploadModel->imageFile = UploadedFile::getInstance($model, 'imageFile');
123
            if ($model->save()) {
124
                $authManager = Yii::$app->getAuthManager();
125
                $role = $authManager->getRole($model->role);
126
                $authManager->assign($role, $model->id);
127
128
                $uploadModel->upload($model->id);
129
                return $this->redirect(['view', 'id' => $model->id]);
130
            }
131
        }
132
        $model->scenario = $model::SCENARIO_ADMIN_CREATE;
133
        return $this->render('create', [
134
            'model' => $model,
135
        ]);
136
    }
137
138
    /**
139
     * Updates an existing User model.
140
     * If update is successful, the browser will be redirected to the 'view' page.
141
     * @param integer $id
142
     * @return mixed
143
     */
144
    public function actionUpdate($id)
145
    {
146
        if ($model = $this->findModel($id)) {
147
            $user_role = $model->getUserRoleValue();
148
            $model->role = $user_role ? $user_role : $model::RBAC_DEFAULT_ROLE;
149
150
            return $this->render('update', [
151
                'model' => $model,
152
            ]);
153
        }
154
        return $this->redirect(['index']);
155
    }
156
157
    /**
158
     * @param $id
159
     * @return array|\yii\web\Response
160
     * @throws NotFoundHttpException
161
     */
162
    public function actionStatus($id)
163
    {
164
        if (Yii::$app->request->isAjax) {
165
            if ($model = $this->findModel($id)) {
166
                Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
167
                // Запрещаем менять статус у себя и админа
168
                if ($model->id !== Yii::$app->user->identity->getId()) {
169
                    if ($model->status == $model::STATUS_ACTIVE) {
170
                        $model->status = $model::STATUS_BLOCKED;
171
                    } else if ($model->status == $model::STATUS_BLOCKED) {
172
                        $model->status = $model::STATUS_ACTIVE;
173
                    } else if ($model->status == $model::STATUS_WAIT) {
174
                        $model->status = $model::STATUS_ACTIVE;
175
                    } else if ($model->status == $model::STATUS_DELETED) {
176
                        $model->status = $model::STATUS_WAIT;
177
                    }
178
                    if ($model->save()) {
179
                        return [
180
                            'body' => $model->statusLabelName,
0 ignored issues
show
Bug introduced by
The property statusLabelName does not seem to exist. Did you mean status?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
181
                            'success' => true,
182
                        ];
183
                    }
184
                }
185
            }
186
        }
187
        return $this->redirect(['index']);
188
    }
189
190
    /**
191
     * @param $id
192
     * @return \yii\web\Response
193
     * @throws NotFoundHttpException
194
     */
195
    public function actionUpdateProfile($id)
196
    {
197
        if ($model = $this->findModel($id)) {
198
            $model->scenario = $model::SCENARIO_ADMIN_UPDATE;
199
200
            $user_role = $model->getUserRoleValue();
201
            $model->role = $user_role ? $user_role : $model::RBAC_DEFAULT_ROLE;
202
            $_role = $model->role;
203
204
            if ($model->load(Yii::$app->request->post())) {
205
                // Если изменена роль
206
                if ($_role != $model->role) {
207
                    $authManager = Yii::$app->getAuthManager();
208
                    // Отвязываем старую роль если она существует
209
                    if ($role = $authManager->getRole($_role))
210
                        $authManager->revoke($role, $model->id);
211
                    // Привязываем новую
212
                    $role = $authManager->getRole($model->role);
213
                    $authManager->assign($role, $model->id);
214
                }
215
                if ($model->save())
216
                    Yii::$app->session->setFlash('success', Module::t('module', 'Profile successfully changed.'));
217
            }
218
        }
219
        return $this->redirect(['update', 'id' => $model->id, 'tab' => 'profile']);
220
    }
221
222
    /**
223
     * @param $id
224
     * @return \yii\web\Response
225
     * @throws NotFoundHttpException
226
     */
227
    public function actionUpdatePassword($id)
228
    {
229
        if ($model = $this->findModel($id)) {
230
            $model->scenario = $model::SCENARIO_PASSWORD_UPDATE;
231
            if ($model->load(Yii::$app->request->post()) && $model->save()) {
232
                Yii::$app->session->setFlash('success', Module::t('module', 'Password changed successfully.'));
233
            }
234
        }
235
        return $this->redirect(['update', 'id' => $model->id, 'tab' => 'password']);
236
    }
237
238
    /**
239
     * @param $id
240
     * @return \yii\web\Response
241
     * @throws NotFoundHttpException
242
     */
243
    public function actionUpdateAvatar($id)
244
    {
245
        if ($model = $this->findModel($id)) {
246
            $model->scenario = $model::SCENARIO_AVATAR_UPDATE;
247
            $oldAvatar = $model->avatar;
248
            if ($model->load(Yii::$app->request->post()) && ($model->scenario === $model::SCENARIO_AVATAR_UPDATE)) {
249
                if ($model->isDel) {
250
                    $this->processRemoveAvatar($model, $oldAvatar);
251
                }
252
                $uploadModel = new UploadForm();
253
                if ($uploadModel->imageFile = UploadedFile::getInstance($model, 'imageFile'))
254
                    $uploadModel->upload($model->id);
255
            }
256
        }
257
        return $this->redirect(['update', 'id' => $model->id, 'tab' => 'avatar']);
258
    }
259
260
    /**
261
     * Remove Avatar
262
     * @param \modules\users\models\backend\User $model
263
     * @param string $oldAvatar
264
     */
265
    public function processRemoveAvatar($model = null, $oldAvatar = '')
266
    {
267
        if ($model && $oldAvatar) {
268
            $upload = Yii::$app->getModule('users')->uploads;
269
            $path = str_replace('\\', '/', Url::to('@upload') . DIRECTORY_SEPARATOR . $upload . DIRECTORY_SEPARATOR . $model->id);
270
            $avatar = $path . '/' . $oldAvatar;
271
            if (file_exists($avatar)) {
272
                unlink($avatar);
273
            }
274
            $model->avatar = null;
275
            $model->save();
276
        }
277
    }
278
279
    /**
280
     * Deletes an existing User model.
281
     * If deletion is successful, the browser will be redirected to the 'index' page.
282
     * @param integer $id
283
     * @return mixed
284
     */
285
    public function actionDelete($id)
286
    {
287
        $model = $this->findModel($id);
288
        // Запрещаем удалять самого себя
289
        if ($model->id !== Yii::$app->user->identity->getId()) {
290
            if ($model->isDeleted()) {
291
                if ($model->delete()) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $model->delete() of type false|integer is loosely compared to true; this is ambiguous if the integer can be zero. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
292
                    Yii::$app->session->setFlash('success', Module::t('module', 'The user "{:name}" have been successfully deleted.', [':name' => $model->username]));
293
                }
294
            } else {
295
                $model->scenario = $model::SCENARIO_PROFILE_DELETE;
296
                $model->status = $model::STATUS_DELETED;
297
                if ($model->save()) {
298
                    Yii::$app->session->setFlash('success', Module::t('module', 'The user "{:name}" are marked as deleted.', [':name' => $model->username]));
299
                }
300
            }
301
        } else {
302
            Yii::$app->session->setFlash('warning', Module::t('module', 'You can not remove yourself.'));
303
        }
304
        return $this->redirect(['index']);
305
    }
306
307
    /**
308
     * Finds the User model based on its primary key value.
309
     * If the model is not found, a 404 HTTP exception will be thrown.
310
     * @param integer $id
311
     * @return User the loaded model
312
     * @throws NotFoundHttpException if the model cannot be found
313
     */
314
    protected function findModel($id)
315
    {
316
        if (($model = User::findOne($id)) !== null) {
0 ignored issues
show
Bug Compatibility introduced by
The expression \modules\users\models\backend\User::findOne($id); of type yii\db\ActiveRecordInterface|array|null adds the type array to the return on line 317 which is incompatible with the return type documented by modules\users\controller...ltController::findModel of type modules\users\models\backend\User.
Loading history...
317
            return $model;
318
        } else {
319
            throw new NotFoundHttpException(Module::t('module', 'The requested page does not exist.'));
320
        }
321
    }
322
323
    /**
324
     * Login action.
325
     *
326
     * @return string
327
     */
328
    public function actionLogin()
329
    {
330
        if (!Yii::$app->user->isGuest) {
331
            return $this->goHome();
332
        }
333
        $this->layout = '//login';
334
335
        $model = new LoginForm();
336
        if ($model->load(Yii::$app->request->post()) && $model->login()) {
337
            // Если запрещен доступ к Backend сбрасываем авторизацию записываем сообщение в сессию
338
            // и перебрасываем на страницу входа
339
            if (!Yii::$app->user->can(\modules\rbac\models\Permission::PERMISSION_VIEW_ADMIN_PAGE)) {
340
                Yii::$app->user->logout();
341
                Yii::$app->session->setFlash('error', Module::t('module', 'You do not have rights, access is denied.'));
342
                return $this->goHome();
343
            }
344
            return $this->goBack();
345
        }
346
        return $this->render('login', [
347
            'model' => $model,
348
        ]);
349
    }
350
351
    /**
352
     * Logout action.
353
     *
354
     * @return string
355
     */
356
    public function actionLogout()
357
    {
358
        Yii::$app->user->logout();
359
        return $this->goHome();
360
    }
361
}
362