Completed
Push — master ( 5b5792...2b84bd )
by Schlaefer
03:33 queued 11s
created

UsersController::initialize()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 0
dl 0
loc 5
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * Saito - The Threaded Web Forum
4
 *
5
 * @copyright Copyright (c) the Saito Project Developers 2015
6
 * @link https://github.com/Schlaefer/Saito
7
 * @license http://opensource.org/licenses/MIT
8
 */
9
10
namespace App\Controller;
11
12
use App\Controller\Component\RefererComponent;
13
use App\Controller\Component\ThemesComponent;
14
use App\Form\BlockForm;
15
use App\Model\Entity\User;
16
use App\Model\Table\UsersTable;
17
use Cake\Core\Configure;
18
use Cake\Event\Event;
19
use Cake\Http\Exception\BadRequestException;
20
use Cake\Http\Exception\NotFoundException;
21
use Cake\Http\Response;
22
use Cake\I18n\Time;
23
use Saito\Exception\Logger\ExceptionLogger;
24
use Saito\Exception\Logger\ForbiddenLogger;
25
use Saito\Exception\SaitoForbiddenException;
26
use Saito\User\Blocker\ManualBlocker;
27
use Saito\User\ForumsUserInterface;
28
use Saito\User\SaitoUser;
29
use Siezi\SimpleCaptcha\Model\Validation\SimpleCaptchaValidator;
30
use Stopwatch\Lib\Stopwatch;
31
32
/**
33
 * User controller
34
 *
35
 * @property RefererComponent $Referer
36
 * @property UsersTable $Users
37
 */
38
class UsersController extends AppController
39
{
40
    public $helpers = [
41
        'SpectrumColorpicker.SpectrumColorpicker',
42
        'Posting',
43
        'Siezi/SimpleCaptcha.SimpleCaptcha',
44
        'Text'
45
    ];
46
47
    /**
48
     * Are moderators allowed to bloack users
49
     *
50
     * @var bool
51
     */
52
    protected $modLocking = false;
53
54
    /**
55
     * {@inheritDoc}
56
     */
57
    public function initialize()
58
    {
59
        parent::initialize();
60
        $this->loadComponent('Referer');
61
    }
62
63
    /**
64
     * Login user.
65
     *
66
     * @return void|\Cake\Network\Response
67
     */
68
    public function login()
69
    {
70
        $data = $this->request->getData();
71
        //= just show form
72
        if (empty($data['username'])) {
73
            return;
74
        }
75
76
        //= successful login with request data
77
        if ($this->CurrentUser->login()) {
78
            if ($this->Referer->wasAction('login')) {
79
                return $this->redirect($this->Auth->redirectUrl());
80
            } else {
81
                return $this->redirect($this->referer());
82
            }
83
        }
84
85
        //= error on login
86
        $username = $this->request->getData('username');
87
        $readUser = $this->Users->findByUsername($username)->first();
0 ignored issues
show
Documentation Bug introduced by
The method findByUsername does not exist on object<App\Model\Table\UsersTable>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
88
89
        $message = __('auth_loginerror');
90
91
        if (!empty($readUser)) {
92
            $User = new SaitoUser($readUser);
93
94
            if (!$User->isActivated()) {
95
                $message = __('user.actv.ny');
96
            } elseif ($User->isLocked()) {
97
                $ends = $this->Users->UserBlocks
98
                    ->getBlockEndsForUser($User->getId());
99
                if ($ends) {
100
                    $time = new Time($ends);
101
                    $data = [
102
                        $username,
103
                        $time->timeAgoInWords(['accuracy' => 'hour'])
104
                    ];
105
                    $message = __('user.block.pubExpEnds', $data);
106
                } else {
107
                    $message = __('user.block.pubExp', $username);
108
                }
109
            }
110
        }
111
112
        // don't autofill password
113
        $this->setRequest($this->getRequest()->withData('password', ''));
114
115
        $Logger = new ForbiddenLogger;
116
        $Logger->write(
117
            "Unsuccessful login for user: $username",
118
            ['msgs' => [$message]]
119
        );
120
121
        $this->Flash->set($message, ['key' => 'auth']);
122
    }
123
124
    /**
125
     * Logout user.
126
     *
127
     * @return void
128
     */
129
    public function logout()
130
    {
131
        $cookies = $this->request->getCookieCollection();
132
        foreach ($cookies as $cookie) {
133
            $cookie = $cookie->withPath($this->request->getAttribute('webroot'));
134
            $this->response = $this->response->withExpiredCookie($cookie);
135
        }
136
137
        $this->CurrentUser->logout();
138
        $this->redirect('/');
139
    }
140
141
    /**
142
     * Register new user.
143
     *
144
     * @return void
145
     */
146
    public function register()
147
    {
148
        $this->set('status', 'view');
149
150
        $this->CurrentUser->logout();
151
152
        $tosRequired = Configure::read('Saito.Settings.tos_enabled');
153
        $this->set(compact('tosRequired'));
154
155
        $user = $this->Users->newEntity();
156
        $this->set('user', $user);
157
158
        if (!$this->request->is('post')) {
159
            return;
160
        }
161
162
        $data = $this->request->getData();
163
164
        if (!$tosRequired) {
165
            $data['tos_confirm'] = true;
166
        }
167
        $tosConfirmed = $data['tos_confirm'];
168
        if (!$tosConfirmed) {
169
            return;
170
        }
171
172
        $validator = new SimpleCaptchaValidator();
173
        $errors = $validator->errors($this->request->getData());
0 ignored issues
show
Bug introduced by
It seems like $this->request->getData() targeting Cake\Http\ServerRequest::getData() can also be of type null or string; however, Cake\Validation\Validator::errors() does only seem to accept array, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
174
175
        $user = $this->Users->register($data);
0 ignored issues
show
Bug introduced by
It seems like $data defined by $this->request->getData() on line 162 can also be of type string; however, App\Model\Table\UsersTable::register() does only seem to accept array, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
176
        $user->setErrors($errors);
177
178
        $errors = $user->getErrors();
179
        if (!empty($errors)) {
180
            // registering failed, show form again
181
            if (isset($errors['password'])) {
182
                $user->setErrors($errors);
183
            }
184
            $user->set('tos_confirm', false);
185
            $this->set('user', $user);
186
187
            return;
188
        }
189
190
        // registered successfully
191
        try {
192
            $forumName = Configure::read('Saito.Settings.forum_name');
193
            $subject = __('register_email_subject', $forumName);
194
            $this->SaitoEmail->email(
195
                [
196
                    'recipient' => $user,
197
                    'subject' => $subject,
198
                    'sender' => 'register',
199
                    'template' => 'user_register',
200
                    'viewVars' => ['user' => $user]
201
                ]
202
            );
203
        } catch (\Exception $e) {
204
            $Logger = new ExceptionLogger();
205
            $Logger->write(
206
                'Registering email confirmation failed',
207
                ['e' => $e]
208
            );
209
            $this->set('status', 'fail: email');
210
211
            return;
212
        }
213
214
        $this->set('status', 'success');
215
    }
216
217
    /**
218
     * register success (user clicked link in confirm mail)
219
     *
220
     * @param string $id user-ID
221
     * @return void
222
     * @throws BadRequestException
223
     */
224
    public function rs($id = null)
225
    {
226
        if (!$id) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $id of type string|null is loosely compared to false; this is ambiguous if the string can be empty. 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 string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
227
            throw new BadRequestException();
228
        }
229
        $code = $this->request->getQuery('c');
230
        try {
231
            $activated = $this->Users->activate((int)$id, $code);
0 ignored issues
show
Bug introduced by
It seems like $code defined by $this->request->getQuery('c') on line 229 can also be of type array or null; however, App\Model\Table\UsersTable::activate() does only seem to accept string, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
232
        } catch (\Exception $e) {
233
            $activated = false;
234
        }
235
        if (!$activated) {
236
            $activated = ['status' => 'fail'];
237
        }
238
        $this->set('status', $activated['status']);
239
    }
240
241
    /**
242
     * Show list of all users.
243
     *
244
     * @return void
245
     */
246
    public function index()
247
    {
248
        $menuItems = [
249
            'username' => [__('username_marking'), []],
250
            'user_type' => [__('user_type'), []],
251
            'UserOnline.logged_in' => [
252
                __('userlist_online'),
253
                ['direction' => 'desc']
254
            ],
255
            'registered' => [__('registered'), ['direction' => 'desc']]
256
        ];
257
        $showBlocked = Configure::read('Saito.Settings.block_user_ui');
258
        if ($showBlocked) {
259
            $menuItems['user_lock'] = [
260
                __('user.set.lock.t'),
261
                ['direction' => 'desc']
262
            ];
263
        }
264
265
        $this->paginate = $options = [
0 ignored issues
show
Unused Code introduced by
$options is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
266
            'contain' => ['UserOnline'],
267
            'sortWhitelist' => array_keys($menuItems),
268
            'finder' => 'paginated',
269
            'limit' => 400,
270
            'order' => [
271
                'UserOnline.logged_in' => 'desc',
272
            ]
273
        ];
274
        $users = $this->paginate($this->Users);
275
276
        $showBottomNavigation = true;
277
278
        $this->set(compact('menuItems', 'showBottomNavigation', 'users'));
279
    }
280
281
    /**
282
     * Ignore user.
283
     *
284
     * @return void
285
     */
286
    public function ignore()
287
    {
288
        $this->request->allowMethod('POST');
289
        $blockedId = (int)$this->request->getData('id');
290
        $this->_ignore($blockedId, true);
291
    }
292
293
    /**
294
     * Unignore user.
295
     *
296
     * @return void
297
     */
298
    public function unignore()
299
    {
300
        $this->request->allowMethod('POST');
301
        $blockedId = (int)$this->request->getData('id');
302
        $this->_ignore($blockedId, false);
303
    }
304
305
    /**
306
     * Mark user as un-/ignored
307
     *
308
     * @param int $blockedId user to ignore
309
     * @param bool $set block or unblock
310
     * @return \Cake\Network\Response
311
     */
312
    protected function _ignore($blockedId, $set)
313
    {
314
        $userId = $this->CurrentUser->getId();
315
        if ((int)$userId === (int)$blockedId) {
316
            throw new BadRequestException();
317
        }
318
        if ($set) {
319
            $this->Users->UserIgnores->ignore($userId, $blockedId);
320
        } else {
321
            $this->Users->UserIgnores->unignore($userId, $blockedId);
322
        }
323
324
        return $this->redirect($this->referer());
325
    }
326
327
    /**
328
     * Show user with profile $name
329
     *
330
     * @param string $name username
331
     * @return void
332
     */
333
    public function name($name = null)
334
    {
335
        if (!empty($name)) {
336
            $viewedUser = $this->Users->find()
337
                ->select(['id'])
338
                ->where(['username' => $name])
339
                ->first();
340
            if (!empty($viewedUser)) {
341
                $this->redirect(
342
                    [
343
                        'controller' => 'users',
344
                        'action' => 'view',
345
                        $viewedUser->get('id')
346
                    ]
347
                );
348
349
                return;
350
            }
351
        }
352
        $this->Flash->set(__('Invalid user'), ['element' => 'error']);
353
        $this->redirect('/');
354
    }
355
356
    /**
357
     * View user profile.
358
     *
359
     * @param null $id user-ID
360
     * @return \Cake\Network\Response|void
361
     */
362
    public function view($id = null)
363
    {
364
        // redirect view/<username> to name/<username>
365
        if (!empty($id) && !is_numeric($id)) {
366
            $this->redirect(
367
                ['controller' => 'users', 'action' => 'name', $id]
368
            );
369
370
            return;
371
        }
372
373
        $user = $this->Users->find()
374
            ->contain(
375
                [
376
                    'UserBlocks' => function ($q) {
377
                        return $q->find('assocUsers');
378
                    },
379
                    'UserOnline'
380
                ]
381
            )
382
            ->where(['Users.id' => $id])
383
            ->first();
384
385 View Code Duplication
        if ($id === null || empty($user)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
386
            $this->Flash->set(__('Invalid user'), ['element' => 'error']);
387
388
            return $this->redirect('/');
389
        }
390
391
        $entriesShownOnPage = 20;
392
        $this->set(
393
            'lastEntries',
394
            $this->Users->Entries->getRecentEntries(
395
                $this->CurrentUser,
396
                ['user_id' => $id, 'limit' => $entriesShownOnPage]
397
            )
398
        );
399
400
        $this->set(
401
            'hasMoreEntriesThanShownOnPage',
402
            ($user->numberOfPostings() - $entriesShownOnPage) > 0
403
        );
404
405
        if ($this->CurrentUser->isUser($id)) {
406
            $ignores = $this->Users->UserIgnores->getAllIgnoredBy($id);
407
            $user->set('ignores', $ignores);
408
        }
409
410
        $isEditingAllowed = $this->_isEditingAllowed($this->CurrentUser, $id);
411
412
        $blockForm = new BlockForm();
413
        $solved = $this->Users->countSolved($id);
414
        $this->set(compact('blockForm', 'isEditingAllowed', 'solved', 'user'));
415
        $this->set('titleForLayout', $user->get('username'));
416
    }
417
418
    /**
419
     * Set user avatar.
420
     *
421
     * @param string $userId user-ID
422
     * @return void|\Cake\Network\Response
423
     */
424
    public function avatar(int $userId)
425
    {
426
        $data = [];
427
        if ($this->request->is('post') || $this->request->is('put')) {
428
            $data = [
429
                'avatar' => $this->request->getData('avatar'),
430
                'avatarDelete' => $this->request->getData('avatarDelete')
431
            ];
432
            if (!empty($data['avatarDelete'])) {
433
                $data = [
434
                    'avatar' => null,
435
                    'avatar_dir' => null
436
                ];
437
            }
438
        }
439
        $user = $this->_edit($userId, $data);
440
        if ($user === true) {
441
            return $this->redirect(['action' => 'edit', $userId]);
442
        }
443
444
        $this->set(
445
            'titleForPage',
446
            __('user.avatar.edit.t', [$user->get('username')])
447
        );
448
    }
449
450
    /**
451
     * Edit user.
452
     *
453
     * @param null $id user-ID
454
     *
455
     * @return \Cake\Network\Response|void
456
     */
457
    public function edit($id = null)
458
    {
459
        $data = [];
460
        if ($this->request->is('post') || $this->request->is('put')) {
461
            $data = $this->request->getData();
462
            unset($data['id']);
463
            //= make sure only admin can edit these fields
464
            if (!$this->CurrentUser->permission('saito.core.user.edit')) {
465
                // @td DRY: refactor this admin fields together with view
466
                unset($data['username'], $data['user_email'], $data['user_type']);
467
            }
468
        }
469
        $user = $this->_edit($id, $data);
0 ignored issues
show
Bug introduced by
It seems like $data defined by $this->request->getData() on line 461 can also be of type string; however, App\Controller\UsersController::_edit() does only seem to accept null|array, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
470
        if ($user === true) {
471
            return $this->redirect(['action' => 'view', $id]);
472
        }
473
474
        $this->set('user', $user);
475
        $this->set(
476
            'titleForPage',
477
            __('user.edit.t', [$user->get('username')])
478
        );
479
480
        $availableThemes = $this->Themes->getAvailable($this->CurrentUser);
481
        $availableThemes = array_combine($availableThemes, $availableThemes);
482
        $currentTheme = $this->Themes->getThemeForUser($this->CurrentUser);
483
        $this->set(compact('availableThemes', 'currentTheme'));
484
    }
485
486
    /**
487
     * Handle user edit core. Retrieve user or patch if data is passed.
488
     *
489
     * @param string $userId user-ID
490
     * @param array|null $data datat to update the user
491
     *
492
     * @return true|User true on successful save, patched user otherwise
493
     */
494
    protected function _edit($userId, array $data = null)
495
    {
496
        if (!$this->_isEditingAllowed($this->CurrentUser, $userId)) {
497
            throw new \Saito\Exception\SaitoForbiddenException(
498
                "Attempt to edit user $userId.",
499
                ['CurrentUser' => $this->CurrentUser]
500
            );
501
        }
502
        if (!$this->Users->exists($userId)) {
503
            throw new BadRequestException;
504
        }
505
        $user = $this->Users->get($userId);
506
507
        if ($data) {
508
            $user = $this->Users->patchEntity($user, $data);
509
            $errors = $user->getErrors();
510
            if (empty($errors) && $this->Users->save($user)) {
511
                return true;
512
            } else {
513
                $this->JsData->addMessage(
514
                    __('The user could not be saved. Please, try again.'),
515
                    ['type' => 'error']
516
                );
517
            }
518
        }
519
        $this->set('user', $user);
520
521
        return $user;
522
    }
523
524
    /**
525
     * Lock user.
526
     *
527
     * @return \Cake\Network\Response|void
528
     * @throws BadRequestException
529
     */
530
    public function lock()
531
    {
532
        $form = new BlockForm();
533
        if (!$this->modLocking || !$form->validate($this->request->getData())) {
0 ignored issues
show
Bug introduced by
It seems like $this->request->getData() targeting Cake\Http\ServerRequest::getData() can also be of type null or string; however, Cake\Form\Form::validate() does only seem to accept array, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
534
            throw new BadRequestException;
535
        }
536
537
        $id = (int)$this->request->getData('lockUserId');
538
        if (!$this->Users->exists($id)) {
539
            throw new NotFoundException('User does not exist.', 1524298280);
540
        }
541
        $readUser = $this->Users->get($id);
542
543
        if ($id === $this->CurrentUser->getId()) {
544
            $message = __('You can\'t lock yourself.');
545
            $this->Flash->set($message, ['element' => 'error']);
546
        } elseif ($readUser->getRole() === 'admin') {
547
            $message = __('You can\'t lock administrators.');
548
            $this->Flash->set($message, ['element' => 'error']);
549
        } else {
550
            try {
551
                $duration = (int)$this->request->getData('lockPeriod');
552
                $blocker = new ManualBlocker($this->CurrentUser->getId(), $duration);
553
                $status = $this->Users->UserBlocks->block($blocker, $id);
554
                if (!$status) {
555
                    throw new \Exception();
556
                }
557
                $message = __('User {0} is locked.', $readUser->get('username'));
558
                $this->Flash->set($message, ['element' => 'success']);
559
            } catch (\Exception $e) {
560
                $message = __('Error while locking.');
561
                $this->Flash->set($message, ['element' => 'error']);
562
            }
563
        }
564
        $this->redirect($this->referer());
565
    }
566
567
    /**
568
     * Unblock user.
569
     *
570
     * @param string $id user-ID
571
     * @return void
572
     */
573
    public function unlock($id)
574
    {
575
        $user = $this->Users->UserBlocks->findById($id)->contain(['Users'])->first();
0 ignored issues
show
Documentation Bug introduced by
The method findById does not exist on object<App\Model\Table\UserBlocksTable>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
576
577
        if (!$id || !$this->modLocking) {
578
            throw new BadRequestException;
579
        }
580
        if (!$this->Users->UserBlocks->unblock($id)) {
581
            $this->Flash->set(
582
                __('Error while unlocking.'),
583
                ['element' => 'error']
584
            );
585
        }
586
587
        $message = __('User {0} is unlocked.', $user->user->get('username'));
588
        $this->Flash->set($message, ['element' => 'success']);
589
        $this->redirect($this->referer());
590
    }
591
592
    /**
593
     * changes user password
594
     *
595
     * @param null $id user-ID
596
     * @return void
597
     * @throws \Saito\Exception\SaitoForbiddenException
598
     * @throws BadRequestException
599
     */
600
    public function changepassword($id = null)
601
    {
602
        if (!$id) {
603
            throw new BadRequestException();
604
        }
605
606
        $user = $this->Users->get($id);
607
        $allowed = $this->_isEditingAllowed($this->CurrentUser, $id);
608
        if (empty($user) || !$allowed) {
609
            throw new SaitoForbiddenException(
610
                "Attempt to change password for user $id.",
611
                ['CurrentUser' => $this->CurrentUser]
612
            );
613
        }
614
        $this->set('userId', $id);
615
        $this->set('username', $user->get('username'));
616
617
        //= just show empty form
618
        if (empty($this->request->getData())) {
619
            return;
620
        }
621
622
        $formFields = ['password', 'password_old', 'password_confirm'];
623
624
        //= process submitted form
625
        $data = [];
626
        foreach ($formFields as $field) {
627
            $data[$field] = $this->request->getData($field);
628
        }
629
        $this->Users->patchEntity($user, $data);
630
        $success = $this->Users->save($user);
631
632 View Code Duplication
        if ($success) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
633
            $this->Flash->set(
634
                __('change_password_success'),
635
                ['element' => 'success']
636
            );
637
            $this->redirect(['controller' => 'users', 'action' => 'edit', $id]);
638
639
            return;
640
        }
641
642
        $errors = $user->getErrors();
643 View Code Duplication
        if (!empty($errors)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
644
            $this->Flash->set(
645
                __d('nondynamic', current(array_pop($errors))),
646
                ['element' => 'error']
647
            );
648
        }
649
650
        //= unset all autofill form data
651
        foreach ($formFields as $field) {
652
            $this->request = $this->request->withoutData($field);
653
        }
654
    }
655
656
    /**
657
     * Directly set password for user
658
     *
659
     * @param string $id user-ID
660
     * @return Response|null
661
     */
662
    public function setpassword($id)
663
    {
664
        if (!$this->CurrentUser->permission('saito.core.user.password.set')) {
665
            throw new SaitoForbiddenException(
666
                "Attempt to set password for user $id.",
667
                ['CurrentUser' => $this->CurrentUser]
668
            );
669
        }
670
671
        $user = $this->Users->get($id);
672
673
        if ($this->getRequest()->is('post')) {
674
            $this->Users->patchEntity($user, $this->getRequest()->getData(), ['fields' => 'password']);
0 ignored issues
show
Bug introduced by
It seems like $this->getRequest()->getData() targeting Cake\Http\ServerRequest::getData() can also be of type null or string; however, Cake\ORM\Table::patchEntity() does only seem to accept array, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
675
676 View Code Duplication
            if ($this->Users->save($user)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
677
                $this->Flash->set(
678
                    __('user.pw.set.s'),
679
                    ['element' => 'success']
680
                );
681
682
                return $this->redirect(['controller' => 'users', 'action' => 'edit', $id]);
683
            }
684
            $errors = $user->getErrors();
685 View Code Duplication
            if (!empty($errors)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
686
                $this->Flash->set(
687
                    __d('nondynamic', current(array_pop($errors))),
688
                    ['element' => 'error']
689
                );
690
            }
691
        }
692
693
        $this->set(compact('user'));
694
    }
695
696
    /**
697
     * Set slidetab-order.
698
     *
699
     * @return \Cake\Network\Response
700
     * @throws BadRequestException
701
     */
702
    public function slidetabOrder()
703
    {
704
        if (!$this->request->is('ajax')) {
705
            throw new BadRequestException;
706
        }
707
708
        $order = $this->request->getData('slidetabOrder');
709
        if (!$order) {
710
            throw new BadRequestException;
711
        }
712
713
        $allowed = $this->Slidetabs->getAvailable();
714
        $order = array_filter(
715
            $order,
716
            function ($item) use ($allowed) {
717
                return in_array($item, $allowed);
718
            }
719
        );
720
        $order = serialize($order);
721
722
        $userId = $this->CurrentUser->getId();
723
        $user = $this->Users->get($userId);
724
        $this->Users->patchEntity($user, ['slidetab_order' => $order]);
725
        $this->Users->save($user);
726
727
        $this->CurrentUser->set('slidetab_order', $order);
728
729
        $this->response = $this->response->withStringBody(true);
0 ignored issues
show
Documentation introduced by
true is of type boolean, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
730
731
        return $this->response;
732
    }
733
734
    /**
735
     * Shows user's uploads
736
     *
737
     * @return void
738
     */
739
    public function uploads()
740
    {
741
    }
742
743
    /**
744
     * Set category for user.
745
     *
746
     * @param null $id category-ID
747
     * @return \Cake\Network\Response
748
     * @throws ForbiddenException
749
     */
750
    public function setcategory($id = null)
751
    {
752
        $userId = $this->CurrentUser->getId();
753
        if ($id === 'all') {
754
            $this->Users->setCategory($userId, 'all');
755
        } elseif (!$id && $this->request->getData()) {
756
            $data = $this->request->getData('CatChooser');
757
            $this->Users->setCategory($userId, $data);
758
        } else {
759
            $this->Users->setCategory($userId, $id);
760
        }
761
762
        return $this->redirect($this->referer());
763
    }
764
765
    /**
766
     * {@inheritdoc}
767
     */
768
    public function beforeFilter(Event $event)
769
    {
770
        parent::beforeFilter($event);
771
        Stopwatch::start('Users->beforeFilter()');
772
773
        $unlocked = ['slidetabToggle', 'slidetabOrder'];
774
        $this->Security->setConfig('unlockedActions', $unlocked);
775
776
        $this->Auth->allow(['login', 'register', 'rs']);
777
        $this->modLocking = $this->CurrentUser
778
            ->permission('saito.core.user.block');
779
        $this->set('modLocking', $this->modLocking);
780
781
        Stopwatch::stop('Users->beforeFilter()');
782
    }
783
784
    /**
785
     * Checks if the current user is allowed to edit user $userId
786
     *
787
     * @param ForumsUserInterface $CurrentUser user
788
     * @param int $userId user-ID
789
     * @return bool
790
     */
791
    protected function _isEditingAllowed(ForumsUserInterface $CurrentUser, $userId)
792
    {
793
        if ($CurrentUser->permission('saito.core.user.edit')) {
794
            return true;
795
        }
796
797
        return $CurrentUser->isUser($userId);
798
    }
799
}
800