Completed
Push — master ( 196a6a...314b46 )
by Stone
12s
created

Home::checkForm()   A

Complexity

Conditions 4
Paths 8

Size

Total Lines 18
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 11
nc 8
nop 0
dl 0
loc 18
rs 9.9
c 0
b 0
f 0
1
<?php
2
3
namespace App\Controllers\Admin;
4
5
6
use App\Models\CommentModel;
7
use App\Models\RoleModel;
8
use App\Models\UserModel;
9
use Core\Constant;
10
use Core\Container;
11
use Core\Traits\PasswordFunctions;
12
use Core\Traits\StringFunctions;
13
14
class Home extends \Core\AdminController
15
{
16
    use StringFunctions;
17
    use PasswordFunctions;
18
    protected $siteConfig;
19
    protected $pagination;
20
21
    private $userModel;
22
    private $roleModel;
23
    private $commentModel;
24
25
    private $user;
26
    private $registerErrors;
27
28
    public function __construct(Container $container)
29
    {
30
        $this->loadModules[] = 'SiteConfig';
31
        $this->loadModules[] = 'pagination';
32
        parent::__construct($container);
33
        $this->userModel = new UserModel($this->container);
34
        $this->roleModel = new RoleModel($this->container);
35
        $this->commentModel = new CommentModel($container);
36
37
        $this->registerErrors = new \stdClass();
38
        $this->user = new \stdClass();
39
40
        $this->data['configs'] = $this->siteConfig->getSiteConfig();
41
        $this->data["pendingCommentsCount"] = $this->commentModel->countPendingComments();
42
    }
43
44
    /**
45
     * check if the set user is the original admin
46
     * @return bool
47
     */
48
    private function checkOriginalAdmin(): bool
49
    {
50
        $userId = (int)$this->user->userId;
51
        //The admin selector should be disables and not sent so forcing default role
52
        $userLockedOut = $this->user->userLockedOut ?? 0;
53
        $userRoleSelector = $this->user->userRoleSelector ?? 2;
54
        $error = false;
55
        //doing a quick check to send back error message
56
        if ($userId === 1 && $userLockedOut == 1) {
57
            $error = true;
58
            $this->alertBox->setAlert("Original admin may not be deactivated", "error");
59
        }
60
61
        if ($userId === 1 && $userRoleSelector != 2) {
62
            $error = true;
63
            $this->alertBox->setAlert("Original admin must stay admin", "error");
64
        }
65
66
        //forcing the default values
67
        if($userId === 1){
68
            $this->user->userRoleSelector = 2;
69
            $this->user->userLockedOut = 0;
70
        }
71
72
        return $error;
73
    }
74
75
    /**
76
     * check if the set data is valid
77
     * @return bool
78
     */
79
    private function checkForm(): bool
80
    {
81
        $error = false;
82
83
        if ($this->user->userName == "") {
84
            $error = true;
85
            $this->registerErrors->userName = "name must not be empty";
86
        }
87
        if ($this->user->userSurname == "") {
88
            $error = true;
89
            $this->registerErrors->userSurname = "surname must not be empty";
90
        }
91
        if ($this->user->userUsername == "") {
92
            $error = true;
93
            $this->registerErrors->userUsername = "username must not be empty";
94
        }
95
96
        return $error;
97
    }
98
99
    /**
100
     * The front page of the admin section. We display the user info
101
     * @throws \ReflectionException
102
     * @throws \Twig_Error_Loader
103
     * @throws \Twig_Error_Runtime
104
     * @throws \Twig_Error_Syntax
105
     */
106
    public function index()
107
    {
108
        $this->onlyUser();
109
110
        //check if have prefilled form data and error mesages
111
        $this->data["registrationInfo"] = $this->session->get("registrationInfo");
112
        $this->data["registrationErrors"] = $this->session->get("registrationErrors");
113
114
        //remove the set data as it is now sent to the template
115
        $this->session->remove("registrationInfo");
116
        $this->session->remove("registrationErrors");
117
118
        $userId = $this->session->get("userId");
119
        if ($userId === null) {
120
            //this should never happen but scrutinizer throws an alert
121
            throw new \Exception("Session error, no ID");
122
        }
123
124
        $userDetails = $this->userModel->getUserDetailsById($userId);
125
126
        if ($userDetails === false) {
127
            //the user is still logged in to his session but deleted from the DB.
128
            $this->cookie->deleteCookie("rememberMe");
129
            $this->session->destroySession();
130
            $this->alertBox->setAlert('your user no longer exists, please contact the admin');
131
            $this->response->redirect();
132
        }
133
134
        $this->data["user"] = $userDetails;
135
136
        $this->data["roles"] = $this->roleModel->getRoleList();
137
138
        $this->renderView('Admin/Home');
139
    }
140
141
    /**
142
     * Administrate a user as an admin
143
     * @param int $userId
144
     * @throws \ReflectionException
145
     * @throws \Twig_Error_Loader
146
     * @throws \Twig_Error_Runtime
147
     * @throws \Twig_Error_Syntax
148
     */
149
    public function viewUser(int $userId)
150
    {
151
        $this->onlyAdmin();
152
        if (!$this->isInt($userId)) {
153
            throw new \Exception("Error in passed ID");
154
        }
155
156
        //check if have prefilled form data and error messages
157
        $this->data["registrationInfo"] = $this->session->get("registrationInfo");
158
        $this->data["registrationErrors"] = $this->session->get("registrationErrors");
159
160
        //remove the set data as it is now sent to the template
161
        $this->session->remove("registrationInfo");
162
        $this->session->remove("registrationErrors");
163
164
        $this->data["user"] = $this->userModel->getUserDetailsById($userId);
165
166
        $this->data["roles"] = $this->roleModel->getRoleList();
167
168
        $this->renderView('Admin/Home');
169
    }
170
171
    /**
172
     * Update the user info via post
173
     * @throws \Exception
174
     */
175
    public function updateUser()
176
    {
177
        $this->onlyUser();
178
        $this->onlyPost();
179
180
        $this->user = (object)$this->request->getDataFull();
181
        $redirectUrl = "/admin";
182
183
        if ($this->user->userId !== $this->session->get("userId") || isset($this->user->userRoleSelector) || isset($this->user->locked_out)) {
184
            //an admin is trying to update a user or form tampered with
185
            $this->onlyAdmin();
186
            $redirectUrl = "/admin/home/view-user/" . $this->user->userId;
187
        } else {
188
            //set the role to the original state for update
189
            $beforeUser = $this->userModel->getUserDetailsById($this->user->userId);
190
            $this->user->userRoleSelector = $beforeUser->roles_idroles;
191
            $this->user->userLockedOut = $beforeUser->locked_out;
192
        }
193
194
        $userId = $this->user->userId;
195
        $password = $this->user->forgotPassword ?? "";
196
        $confirm = $this->user->forgotConfirm ?? "";
197
        $resetPassword = false;
198
        $error = false;
199
200
201
202
        if ($this->checkOriginalAdmin()) {
203
            $error = true;
204
        }
205
206
        if ($password !== "" || $confirm !== "") {
207
            //we are resetting the password
208
            $resetPassword = true;
209
            if ($password !== $confirm) {
210
                $error = true;
211
                $this->registerErrors->forgotPassword = "password and confirmation do not match";
212
                $this->registerErrors->forgotConfirm = "password and confirmation do not match";
213
            }
214
215
            $passwordError = $this->isPasswordComplex($password);
216
            if (!$passwordError["success"]) {
217
                $error = true;
218
                $this->registerErrors->forgotPassword = $passwordError["message"];
219
            }
220
        }
221
222
        if ($this->checkForm()) {
223
            $error = true;
224
        }
225
226
        if ($error) {
227
            $this->session->set("registrationErrors", $this->registerErrors);
228
            $this->response->redirect($redirectUrl);
229
        }
230
231
        if ($resetPassword) {
232
            $this->userModel->resetPassword($userId, $password);
233
        }
234
235
        $this->userModel->updateUser($this->user);
236
237
        $this->alertBox->setAlert('User details updated');
238
        $this->response->redirect($redirectUrl);
239
    }
240
241
    /**
242
     * List all the users
243
     * @param string $page
244
     * @param int $linesPerPage
245
     * @throws \ReflectionException
246
     * @throws \Twig_Error_Loader
247
     * @throws \Twig_Error_Runtime
248
     * @throws \Twig_Error_Syntax
249
     */
250
    public function listUsers(string $page = "page-1", int $linesPerPage = Constant::LIST_PER_PAGE)
251
    {
252
        $this->onlyAdmin();
253
254
        $totalUsers = $this->userModel->countUsers();
255
        $pagination = $this->pagination->getPagination($page, $totalUsers, $linesPerPage);
256
257
        if ($linesPerPage !== Constant::LIST_PER_PAGE) {
258
            $this->data['paginationPostsPerPage'] = $linesPerPage;
259
        }
260
261
        $this->data["posts"] = $this->userModel->getUserList($pagination["offset"], $linesPerPage);
262
        $this->data['pagination'] = $pagination;
263
        $this->renderView("Admin/ListUser");
264
    }
265
266
    /**
267
     * permanantly delete a user
268
     * @param int $userId
269
     * @throws \Exception
270
     */
271
    public function deleteUser(int $userId)
272
    {
273
        $this->onlyAdmin();
274
        if (!$this->isInt($userId)) {
275
            throw new \Exception("Error in passed ID");
276
        }
277
278
        if ($userId === 1) {
279
            $this->alertBox->setAlert('Original Admin can not be deleted', "error");
280
            $this->response->redirect("/admin/home/list-users");
281
        }
282
283
        $this->userModel->deleteUser($userId);
284
        $this->alertBox->setAlert('User deleted');
285
        $this->response->redirect("/admin/home/list-users");
286
    }
287
}