Completed
Push — master ( 15a5bf...eb9630 )
by Joao
08:35
created

UsersController::postAdminEdit()   F

Complexity

Conditions 24
Paths 15937

Size

Total Lines 166
Code Lines 69

Duplication

Lines 22
Ratio 13.25 %

Importance

Changes 2
Bugs 0 Features 1
Metric Value
c 2
b 0
f 1
dl 22
loc 166
rs 2
cc 24
eloc 69
nc 15937
nop 1

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php namespace jlourenco\base\Controllers;
2
3
use App\Http\Controllers\Controller;
4
use Validator;
5
use App\Http\Requests;
6
use Sentinel;
7
use View;
8
use Input;
9
use File;
10
use Activation;
11
use Hash;
12
use Mail;
13
use URL;
14
use Illuminate\Support\Facades\Redirect;
15
use Base;
16
use DB;
17
use Lang;
18
19
class UsersController extends Controller
20
{
21
22
    /**
23
     * Declare the rules for the form validation
24
     *
25
     * @var array
26
     */
27
    protected $validationRules = array(
28
        'first_name'       => 'required|min:3',
29
        'last_name'        => 'required|min:3',
30
        'email'            => 'required|email|unique:User',
31
        'password'         => 'required|between:3,32',
32
        'password_confirm' => 'required|same:password',
33
        'pic'              => 'mimes:jpg,jpeg,bmp,png|max:10000'
34
    );
35
36
    protected $validationRulesAdmin = array(
37
        'gender'           =>  'required|digits_between:0,2',
38
        'first_name'       => 'required|min:3|max:25',
39
        'last_name'        => 'required|min:3|max:25',
40
        'password'         => 'required|between:3,32',
41
        'password_confirm' => 'required|same:password',
42
        'birthday'         =>  'date_format:d/m/Y|before:now',
43
    );
44
45
    protected $genders = [
46
        '0' => 'Male',
47
        '1' => 'Female',
48
        '2' => 'Other'
49
    ];
50
51
    protected $status = [
52
        '0' => 'Inactive',
53
        '1' => 'Active',
54
        '2' => 'Blocked',
55
        '3' => 'To create'
56
    ];
57
58
    /*
59
     * Public section
60
     */
61
62
    /**
63
     * Show a list of all the users.
64
     *
65
     * @return View
66
     */
67
    public function getIndex()
68
    {
69
        // Grab all the users
70
        $users = User::getAllStaff();
71
72
        // Show the page
73
        return View('collaborators', compact('users'));
74
    }
75
76
    /**
77
     * Display specified user profil.
78
     *
79
     * @param  int  $id
0 ignored issues
show
Bug introduced by
There is no parameter named $id. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
80
     * @return Response
81
     */
82
    public function show(User $user)
83
    {
84
        // Show the page
85
        return View('collaborator', compact('user'));
86
    }
87
88
    /**
89
     * get user details and display
90
     */
91
    public function myAccount()
92
    {
93
        $user = Sentinel::getUser();
94
95
        return View::make('public.users.edit', compact('user'));
96
    }
97
98
    /**
99
     * update user details and display
100
     */
101
    public function updateAccount()
102
    {
103
        $user = Sentinel::getUser();
104
105
        //validationRules are declared at beginning
106
        $this->validationRules['email'] = "required|email|unique:users,email,{$user->email},email";
107
108
        if (!$password = Input::get('password')) {
109
            unset($this->validationRules['password']);
110
            unset($this->validationRules['password_confirm']);
111
        }
112
113
        $this->validationRules['birthday'] = 'date_format:d/m/Y|before:now';
114
115
        // Create a new validator instance from our validation rules
116
        $validator = Validator::make(Input::all(), $this->validationRules);
117
118
        // If validation fails, we'll exit the operation now.
119
        if ($validator->fails()) {
120
            // Ooops.. something went wrong
121
            return Redirect::back()->withInput()->withErrors($validator);
122
        }
123
124
        $email = $user->email;
125
126
        // Update the user
127
        $user->first_name = Input::get('first_name');
128
        $user->last_name = Input::get('last_name');
129
        $user->email = Input::get('email');
130
        $user->gender = Input::get('gender');
131
        $user->description = Input::get('description');
132
133 View Code Duplication
        if (Input::get('birthday') != null)
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...
134
            $user->birthday = \Carbon\Carbon::createFromFormat('d/m/Y', Input::get('birthday'));
135
136
        $passwordChanged = false;
137
138
        // Do we want to update the user password?
139
        if ($password = Input::get('password'))
140
        {
141
            if (Sentinel::validateCredentials($user, [ 'email' => $email, 'password' => Input::get('old-password')]))
142
            {
143
                $passwordChanged = true;
144
                $user->password = Hash::make($password);
145
            }
146 View Code Duplication
            else
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...
147
            {
148
                $error = Lang::get('base.auth.wrong_password');
149
                $validator->messages()->add('old-password', Lang::get('base.auth.wrong_password'));
150
151
                // Redirect to the user page
152
                return Redirect::route('profile')->withInput()->withErrors($validator)->with('error', $error);
153
            }
154
        }
155
156
        // is new image uploaded?
157
        if ($file = Input::file('pic')) {
158
            $extension = $file->getClientOriginalExtension() ?: 'png';
159
            $folderName = '/uploads/users/';
160
            $destinationPath = public_path() . $folderName;
161
            $safeName = str_random(10) . '.' . $extension;
162
            $file->move($destinationPath, $safeName);
163
164
            //delete old pic if exists
165
            if (File::exists(public_path() . $folderName . $user->pic))
166
                File::delete(public_path() . $folderName . $user->pic);
167
168
            //save new file path into db
169
            $user->pic = $safeName;
170
171
            Base::Log($user->username . ' (' . $user->first_name . ' ' . $user->last_name . ') changed its profile photo. ');
172
        }
173
174
        // Was the user updated?
175
        if ($user->save()) {
176
            // Prepare the success message
177
            $success = Lang::get('base.auth.account.changed');
178
179
            if ($passwordChanged)
180
            {
181
                Base::Log($user->username . ' (' . $user->first_name . ' ' . $user->last_name . ') changed its password. ');
182
                Mail::queue('emails.account.password-changed', [ 'user' => $user ], function ($m) use ($user) {
183
                    $m->to($user->email, $user->first_name . ' ' . $user->last_name);
184
                    $m->subject(Lang::get('base.mails.password_changed'));
185
                });
186
            }
187
188
            Base::Log($user->username . ' (' . $user->first_name . ' ' . $user->last_name . ') updated the profile. ');
189
190
            // Redirect to the user page
191
            return Redirect::route('profile')->with('success', $success);
192
        }
193
194
        // Prepare the error message
195
        $error = Lang::get('base.base.error');
196
197
        // Redirect to the user page
198
        return Redirect::route('profile')->withInput()->with('error', $error);
199
    }
200
201
    /**
202
     * Show password change form
203
     */
204
    public function getChangePassword()
205
    {
206
        return View::make('public.users.change_password');
207
    }
208
209
    /**
210
     * Change password form processing page.
211
     *
212
     * @param  int      $id
0 ignored issues
show
Bug introduced by
There is no parameter named $id. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
213
     * @return Redirect
214
     */
215
    public function postChangePassword()
216
    {
217
        $user = Sentinel::getUser();
218
219
        $validation = array(
220
            'password'         => 'required|between:3,32',
221
            'password_confirm' => 'required|same:password',
222
        );
223
224
        // Create a new validator instance from our validation rules
225
        $validator = Validator::make(Input::all(), $validation);
226
227
        // If validation fails, we'll exit the operation now.
228
        if ($validator->fails()) {
229
            // Ooops.. something went wrong
230
            return Redirect::back()->withInput()->withErrors($validator);
231
        }
232
233
        try {
234
            // Do we want to update the user password?
235
            $password = Input::get('password');
236
237
            if (Sentinel::validateCredentials($user, [ 'email' => $user->email, 'password' => Input::get('old-password')]))
238
            {
239
                $user->password = Hash::make($password);
240
                $redirect = 'change-password';
241
242
                if ($user->force_new_password)
243
                {
244
                    $user->force_new_password = 0;
245
                    $redirect = 'home';
246
                }
247
248
                // Was the user updated?
249 View Code Duplication
                if ($user->save())
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...
250
                {
251
                    // Prepare the success message
252
                    $success = Lang::get('base.auth.account.changed');
253
254
                    Mail::queue('emails.account.password-changed', [ 'user' => $user ], function ($m) use ($user) {
255
                        $m->to($user->email, $user->first_name . ' ' . $user->last_name);
256
                        $m->subject(Lang::get('base.mails.password_changed'));
257
                    });
258
259
                    Base::Log($user->username . ' (' . $user->first_name . ' ' . $user->last_name . ') changed its password account. ');
260
261
                    // Redirect to the user page
262
                    return Redirect::route($redirect)->with('success', $success);
263
                }
264
            }
265 View Code Duplication
            else
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...
266
            {
267
                $error = Lang::get('base.auth.wrong_password');
268
                $validator->messages()->add('old-password', Lang::get('base.auth.wrong_password'));
269
270
                // Redirect to the user page
271
                return Redirect::route('change-password')->withInput()->withErrors($validator)->with('error', $error);
272
            }
273
274
            // Prepare the error message
275
        } catch (Exception $e) {
0 ignored issues
show
Bug introduced by
The class jlourenco\base\Controllers\Exception does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
276
        }
277
        $error = Lang::get('base.base.error');
278
279
280
        // Redirect to the user page
281
        return Redirect::route('change-password')->withInput()->with('error', $error);
282
    }
283
284
    /*
285
     * Admin section
286
     */
287 View Code Duplication
    public function getAdminIndex()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
288
    {
289
        // Grab all the users
290
        $users = Sentinel::createModel()->where('status', '=', '1')->Get();
291
292
        $possibleStatus = $this->status;
293
        $pending = false;
294
295
        // Show the page
296
        return View('admin.users.list', compact('users', 'possibleStatus', 'pending'));
297
    }
298
299 View Code Duplication
    public function getAdminPending()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
300
    {
301
        // Grab all the users
302
        $users = Sentinel::createModel()->where('last_login', '=', null)->where('status', '=', '0')->Get();
303
304
        $possibleStatus = $this->status;
305
        $pending = true;
306
307
        // Show the page
308
        return View('admin.users.list', compact('users', 'possibleStatus', 'pending'));
309
    }
310
311 View Code Duplication
    public function getAdminBlocked()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
312
    {
313
        // Grab all the users
314
        $users = Sentinel::createModel()->where('status', '=', '2')->Get();
315
316
        $possibleStatus = $this->status;
317
        $pending = true;
318
319
        // Show the page
320
        return View('admin.users.list', compact('users', 'possibleStatus', 'pending'));
321
    }
322
323
    /**
324
     * User update form processing page.
325
     *
326
     * @param  int      $id
327
     * @return Redirect
328
     */
329
    public function adminAccept($id = null)
330
    {
331
        // Get the user information
332
        $user = Sentinel::findById($id);
333
334 View Code Duplication
        if ($user == null || $user->last_login != null || $user->status != 0)
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...
335
        {
336
            // Prepare the error message
337
            $error = Lang::get('base.auth.not_found');
338
339
            // Redirect to the user management page
340
            return Redirect::route('users.pending')->with('error', $error);
341
        }
342
343
        $user->status = 1;
344
345
        if ($user->save())
346
        {
347
            $activation = Activation::exists($user);
348
349
            if (!$activation)
350
            {
351
                Activation::create($user);
352
353
                $activation = Activation::exists($user);
354
            }
355
356
            if($activation)
357
                Activation::complete($user, $activation->code);
358
359
            Base::TargettedLog($user->username . ' (' . $user->first_name . ' ' . $user->last_name . ') account was accepted. ', $user->id);
360
361
            Mail::queue('emails.account.accepted-by-admin', [ 'user' => $user ], function ($m) use ($user) {
362
                $m->to($user->email, $user->first_name . ' ' . $user->last_name);
363
                $m->subject(Lang::get('base.mails.account_accepted'));
364
            });
365
366
            $success = 'User registration was accepted.';
367
368
            // Redirect to the user page
369
            return Redirect::route('users.pending')->withInput()->with('success', $success);
370
        }
371
372
        $error = Lang::get('base.base.error');
373
374
        // Redirect to the user page
375
        return Redirect::route('users.pending')->withInput()->with('error', $error);
376
    }
377
378
    /**
379
     * User update form processing page.
380
     *
381
     * @param  int      $id
382
     * @return Redirect
383
     */
384
    public function adminRefuse($id = null)
385
    {
386
        // Get the user information
387
        $user = Sentinel::findById($id);
388
389 View Code Duplication
        if ($user == null || $user->last_login != null || $user->status != 0)
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...
390
        {
391
            // Prepare the error message
392
            $error = Lang::get('base.auth.not_found');
393
394
            // Redirect to the user management page
395
            return Redirect::route('users.pending')->with('error', $error);
396
        }
397
398
        $user->status = 2;
399
400 View Code Duplication
        if ($user->save())
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...
401
        {
402
            Base::TargettedLog($user->username . ' (' . $user->first_name . ' ' . $user->last_name . ') account was refused. ', $user->id);
403
404
            if (Base::getSetting('SEND_EMAIL_ON_REFUSE'))
405
                Mail::queue('emails.account.refused-by-admin', [ 'user' => $user ], function ($m) use ($user) {
406
                    $m->to($user->email, $user->first_name . ' ' . $user->last_name);
407
                    $m->subject(Lang::get('base.mails.account_accepted'));
408
                });
409
410
            $success = Lang::get('base.auth.account.rejected');
411
412
            // Redirect to the user page
413
            return Redirect::route('users.pending')->withInput()->with('success', $success);
414
        }
415
416
        $error = Lang::get('base.base.error');
417
418
        // Redirect to the user page
419
        return Redirect::route('users.pending')->withInput()->with('error', $error);
420
    }
421
422
    /**
423
     * Display specified user profile.
424
     *
425
     * @param  int  $id
426
     * @return Response
427
     */
428
    public function adminShow($id)
429
    {
430
        // Get the user information
431
        $user = Sentinel::findUserById($id);
432
433 View Code Duplication
        if ($user == null)
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...
434
        {
435
            // Prepare the error message
436
            $error = Lang::get('base.auth.not_found');
437
438
            // Redirect to the user management page
439
            return Redirect::route('users')->with('error', $error);
440
        }
441
442
        $possibleStatus = $this->status;
443
444
        $logs = Base::getLogsRepository()->where('created_by', $user->id)->orWhere('target', $user->id)->orderBy('created_at', 'desc')->take(300)->get(['ip', 'log', 'created_at', 'created_by', 'target']);
445
        $ips = Base::getLogsRepository()->where('created_by', $user->id)->where('log', 'LIKE', '%logged%')->orderBy('created_at', 'desc')->select('ip', DB::raw('count(*) as counter'), DB::raw('(SELECT created_at FROM Logs WHERE IP=ip ORDER BY created_at DESC LIMIT 1 ) as created_at'))->groupBy('ip')->take(300)->get();
446
447
        // Show the page
448
        return View('admin.users.show', compact('user', 'possibleStatus', 'logs', 'ips'));
0 ignored issues
show
Bug Best Practice introduced by
The return type of return View('admin.users...atus', 'logs', 'ips')); (Illuminate\View\View|Ill...\Contracts\View\Factory) is incompatible with the return type documented by jlourenco\base\Controlle...rsController::adminShow of type jlourenco\base\Controllers\Response.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
449
450
    }
451
452
    /**
453
     * Show a list of all the deleted users.
454
     *
455
     * @return View
456
     */
457
    public function getAdminDeletedUsers()
458
    {
459
        // Grab deleted users
460
        $users = Sentinel::createModel()->onlyTrashed()->get();
461
462
        // Show the page
463
        return View('admin.users.deleted', compact('users'));
464
    }
465
466
    /**
467
     * Delete Confirm
468
     *
469
     * @param   int   $id
470
     * @return  View
471
     */
472
    public function getAdminModalDelete($id = null)
473
    {
474
        $confirm_route = $error = null;
475
476
        // Get user information
477
        $user = Sentinel::findById($id);
478
479
        if ($user == null)
480
        {
481
            // Prepare the error message
482
            $error = Lang::get('base.auth.not_found');
483
            return View('layouts.modal_confirmation', compact('error', 'model', 'confirm_route'));
484
        }
485
486
        // Check if we are not trying to delete ourselves
487
        if ($user->id === Sentinel::getUser()->id)  {
488
            // Prepare the error message
489
            $error = Lang::get('base.base.error');
490
491
            return View('layouts.modal_confirmation', compact('error', 'model', 'confirm_route'));
492
        }
493
494
        $confirm_route = route('delete/user', ['id' => $user->id]);
495
        return View('layouts.modal_confirmation', compact('error', 'model', 'confirm_route'));
496
    }
497
498
    /**
499
     * Delete the given user.
500
     *
501
     * @param  int      $id
502
     * @return Redirect
503
     */
504
    public function getAdminDelete($id = null)
505
    {
506
        // Get user information
507
        $user = Sentinel::findById($id);
508
509 View Code Duplication
        if ($user == null)
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...
510
        {
511
            // Prepare the error message
512
            $error = Lang::get('base.auth.not_found');
513
514
            // Redirect to the user management page
515
            return Redirect::route('users')->with('error', $error);
516
        }
517
518
        // Check if we are not trying to delete ourselves
519
        if ($user->id === Sentinel::getUser()->id) {
520
            // Prepare the error message
521
            $error = Lang::get('base.base.error');
522
523
            // Redirect to the user management page
524
            return Redirect::route('users')->with('error', $error);
525
        }
526
527
        // Delete the user
528
        //to allow soft deleted, we are performing query on users model instead of Sentinel model
529
        //$user->delete();
0 ignored issues
show
Unused Code Comprehensibility introduced by
84% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
530
        Sentinel::createModel()->destroy($id);
531
532
        // Prepare the success message
533
        $success = Lang::get('base.auth.account.deleted');
534
535
        // Redirect to the user management page
536
        return Redirect::route('users')->with('success', $success);
537
    }
538
539
    /**
540
     * Restore a deleted user.
541
     *
542
     * @param  int      $id
543
     * @return Redirect
544
     */
545
    public function getAdminRestore($id = null)
546
    {
547
        // Get user information
548
        $user = Sentinel::createModel()->withTrashed()->find($id);
549
550
        if ($user == null)
551
        {
552
            // Prepare the error message
553
            $error = Lang::get('base.auth.not_found');
554
555
            // Redirect to the user management page
556
            return Redirect::route('users.deleted')->with('error', $error);
557
        }
558
559
        // Restore the user
560
        $user->restore();
561
562
        // Prepare the success message
563
        $success = Lang::get('base.auth.account.restored');
564
565
        // Redirect to the user management page
566
        return Redirect::route('users.deleted')->with('success', $success);
567
    }
568
569
    /**
570
     * User update.
571
     *
572
     * @param  int  $id
573
     * @return View
574
     */
575
    public function getAdminEdit($id = null)
576
    {
577
        // Get the user information
578
        if($user = Sentinel::findById($id))
579
        {
580
            // Get this user groups
581
            $userRoles = $user->getRoles()->lists('name', 'id')->all();
582
583
            // Get a list of all the available groups
584
            $roles = Sentinel::getRoleRepository()->all();
585
        }
586
        else
587
        {
588
            // Prepare the error message
589
            $error = Lang::get('base.auth.not_found');
590
591
            // Redirect to the user management page
592
            return Redirect::route('users')->with('error', $error);
593
        }
594
595
        $status = $user->status;
596
        $genders = $this->genders;
597
        $statusList = $this->status;
598
599
        // Show the page
600
        return View('admin/users/edit', compact('user', 'roles', 'userRoles', 'status', 'genders', 'statusList'));
0 ignored issues
show
Bug Best Practice introduced by
The return type of return View('admin/users...nders', 'statusList')); (Illuminate\View\View|Ill...\Contracts\View\Factory) is incompatible with the return type documented by jlourenco\base\Controlle...ontroller::getAdminEdit of type View.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
601
    }
602
603
    /**
604
     * User update form processing page.
605
     *
606
     * @param  int      $id
607
     * @return Redirect
608
     */
609
    public function postAdminEdit($id = null)
610
    {
611
        // Get the user information
612
        $user = Sentinel::findById($id);
613
614
        if ($user == null)
615
        {
616
            // Prepare the error message
617
            $error = Lang::get('base.auth.not_found');
618
619
            // Redirect to the user management page
620
            return Redirect::route('admin.users.show')->with('error', $error);
621
        }
622
623
        $this->validationRulesAdmin['email'] = "required|email|unique:User,email,{$user->email},email,status,3|max:255";
624
        $this->validationRulesAdmin['username'] = "required|min:3|unique:User,username,{$user->username},username|max:25";
625
626
        // Do we want to update the user password?
627
        if (!$password = Input::get('password')) {
628
            unset($this->validationRulesAdmin['password']);
629
            unset($this->validationRulesAdmin['password_confirm']);
630
        }
631
632
        // Create a new validator instance from our validation rules
633
        $validator = Validator::make(Input::all(), $this->validationRulesAdmin);
634
635
        // If validation fails, we'll exit the operation now.
636
        if ($validator->fails()) {
637
            // Ooops.. something went wrong
638
            return Redirect::back()->withInput()->withErrors($validator);
639
        }
640
641
        try {
642
            // Update the user
643
            $user->gender   = Input::get('gender');
644
            $user->first_name  = Input::get('first_name');
645
            $user->last_name   = Input::get('last_name');
646
            $user->username    = Input::get('username');
647
            $user->email       = Input::get('email');
648
            $user->description = Input::get('description');
649
650
            if (Input::get('force_new_password'))
651
                $user->force_new_password = 1;
652
            else
653
                $user->force_new_password = 0;
654
655 View Code Duplication
            if (Input::get('birthday') != null)
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...
656
                $user->birthday = \Carbon\Carbon::createFromFormat('d/m/Y', Input::get('birthday'));
657
658
            $password_changed = false;
659
660
            // Do we want to update the user password?
661
            if ($password)
662
            {
663
                $user->password = Hash::make($password);
664
                $password_changed = true;
665
            }
666
667
            // is new image uploaded?
668 View Code Duplication
            if ($file = Input::file('pic'))
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...
669
            {
670
                $fileName        = $file->getClientOriginalName();
0 ignored issues
show
Unused Code introduced by
$fileName 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...
671
                $extension       = $file->getClientOriginalExtension() ?: 'png';
672
673
                if ($extension == 'png' || $extension == 'PNG' || $extension == 'JGP' || $extension == 'jpg' || $extension == 'gif')
674
                {
675
                    $folderName      = '/uploads/users/';
676
                    $destinationPath = public_path() . $folderName;
677
                    $safeName        = str_random(10).'.'.$extension;
678
                    $file->move($destinationPath, $safeName);
679
680
                    //delete old pic if exists
681
                    if(File::exists(public_path() . $folderName . $user->pic))
682
                        File::delete(public_path() . $folderName . $user->pic);
683
684
                    //save new file path into db
685
                    $user->pic   = $safeName;
686
                }
687
            }
688
689
            /*
0 ignored issues
show
Unused Code Comprehensibility introduced by
38% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
690
            // Get the current user groups
691
            $userRoles = $user->roles()->lists('id')->all();
692
693
            // Get the selected groups
694
            $selectedRoles = Input::get('groups', array());
695
696
            // Groups comparison between the groups the user currently
697
            // have and the groups the user wish to have.
698
            $rolesToAdd    = array_diff($selectedRoles, $userRoles);
699
            $rolesToRemove = array_diff($userRoles, $selectedRoles);
700
701
            // Assign the user to groups
702
            foreach ($rolesToAdd as $roleId) {
703
                $role = Sentinel::findRoleById($roleId);
704
705
                $role->users()->attach($user);
706
            }
707
708
            // Remove the user from groups
709
            foreach ($rolesToRemove as $roleId) {
710
                $role = Sentinel::findRoleById($roleId);
711
712
                $role->users()->detach($user);
713
            }
714
            */
715
716
            // Activate / De-activate user
717
            $status = $activation = Activation::completed($user);
718
            $currentStatus = Input::get('status');
719
720
            if($currentStatus != $status)
721
            {
722
                if ($currentStatus == 0)
723
                    // Remove existing activation record
724
                    Activation::remove($user);
725
                else
726
                {
727
                    $activation = Activation::exists($user);
728
729
                    if (!$activation)
730
                    {
731
                        Activation::create($user);
732
733
                        $activation = Activation::exists($user);
734
                    }
735
736
                    if($activation)
737
                        Activation::complete($user, $activation->code);
738
                }
739
740
                $user->status = $currentStatus;
741
            }
742
            else
743
                $user->status = $currentStatus;
744
745
            // Was the user updated?
746
            if ($user->save())
747
            {
748
                if ($password_changed && Input::get('send_new_password_email'))
749
                {
750
                    Mail::queue('emails.account.password-changed-by-admin', [ 'user' => $user, 'new_password' => $password ], function ($m) use ($user) {
751
                        $m->to($user->email, $user->first_name . ' ' . $user->last_name);
752
                        $m->subject(Lang::get('base.mails.password_changed'));
753
                    });
754
                }
755
756
                if ($password_changed)
757
                    Base::TargettedLog($user->username . ' (' . $user->first_name . ' ' . $user->last_name . ') password was changed by an admin. ', $user->id);
758
759
                Base::TargettedLog($user->username . ' (' . $user->first_name . ' ' . $user->last_name . ') profile was changed by an admin. ', $user->id);
760
761
                // Prepare the success message
762
                $success = Lang::get('base.auth.user_changed');
763
764
                // Redirect to the user page
765
                return Redirect::route('users.update', $id)->with('success', $success);
766
            }
767
768
        } catch (Exception $e) {
0 ignored issues
show
Bug introduced by
The class jlourenco\base\Controllers\Exception does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
769
        }
770
        $error = Lang::get('base.base.error');
771
772
        // Redirect to the user page
773
        return Redirect::route('users.update', $id)->withInput()->with('error', $error);
774
    }
775
776
    /**
777
     * Create new user
778
     *
779
     * @return View
780
     */
781
    public function getAdminCreate()
782
    {
783
        // Get all the available groups
784
        $groups = Sentinel::getRoleRepository()->all();
785
786
        $genders = $this->genders;
787
        $statusList = $this->status;
788
        $user = null;
789
        $status = 0;
790
791
        // Show the page
792
        return View('admin.users.create', compact('groups', 'genders', 'statusList', 'user', 'status'));
793
    }
794
795
    /**
796
     * User create form processing.
797
     *
798
     * @return Redirect
799
     */
800
    public function postAdminCreate()
801
    {
802
        $this->validationRulesAdmin['email'] = "required|email|unique:User";
803
        $this->validationRulesAdmin['username'] = "required|min:3|unique:User|max:25";
804
        $this->validationRulesAdmin['birthday'] = "required|date_format:d/m/Y|before:now";
805
806
        // Create a new validator instance from our validation rules
807
        $validator = Validator::make(Input::all(), $this->validationRulesAdmin);
808
809
        // If validation fails, we'll exit the operation now.
810
        if ($validator->fails()) {
811
            // Ooops.. something went wrong
812
            return Redirect::back()->withInput()->withErrors($validator);
813
        }
814
815
        //check whether use should be activated by default or not
816
        $activate = Input::get('status') != null && Input::get('status') != 0 ? true : false;
817
818
        try {
819
            $birthday = \Carbon\Carbon::createFromFormat('d/m/Y', Input::get('birthday'));
820
821
            // Register the user
822
            $user = Sentinel::register(array(
823
                'gender'   => Input::get('gender'),
824
                'first_name' => Input::get('first_name'),
825
                'last_name'  => Input::get('last_name'),
826
                'username'  => Input::get('username'),
827
                'birthday'   => $birthday,
828
                'email'      => Input::get('email'),
829
                'password'   => Input::get('password'),
830
                'status'   => Input::get('status'),
831
                //'pic'   => isset($safeName)?$safeName:'',
0 ignored issues
show
Unused Code Comprehensibility introduced by
77% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
832
            ), $activate);
833
834
            $user->password = Hash::make(Input::get('password'));
835
            $user->description = Input::get('description');
836
837
            if (Input::get('force_new_password'))
838
                $user->force_new_password = 1;
839
            else
840
                $user->force_new_password = 0;
841
842
            // is new image uploaded?
843 View Code Duplication
            if ($file = Input::file('pic'))
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...
844
            {
845
                $fileName        = $file->getClientOriginalName();
0 ignored issues
show
Unused Code introduced by
$fileName 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...
846
                $extension       = $file->getClientOriginalExtension() ?: 'png';
847
848
                if ($extension == 'png' || $extension == 'PNG' || $extension == 'JGP' || $extension == 'jpg' || $extension == 'gif')
849
                {
850
                    $folderName      = '/uploads/users/';
851
                    $destinationPath = public_path() . $folderName;
852
                    $safeName        = str_random(10).'.'.$extension;
853
                    $file->move($destinationPath, $safeName);
854
855
                    //delete old pic if exists
856
                    if(File::exists(public_path() . $folderName . $user->pic))
857
                        File::delete(public_path() . $folderName . $user->pic);
858
859
                    //save new file path into db
860
                    $user->pic   = $safeName;
861
                }
862
            }
863
864
            $user->save();
865
866
            Base::TargettedLog($user->username . ' (' . $user->first_name . ' ' . $user->last_name . ') account was created by an admin. ', $user->id);
867
868
            if (Input::get('send_new_password_email'))
869
            {
870
                if ($activate)
871
                {
872
                    Mail::queue('emails.account.account-created-by-admin', [ 'user' => $user, 'new_password' => Input::get('password') ], function ($m) use ($user) {
873
                        $m->to($user->email, $user->first_name . ' ' . $user->last_name);
874
                        $m->subject(Lang::get('base.mails.account_created'));
875
                    });
876
                }
877
                else
878
                {
879
                    Mail::queue('emails.account.account-created-by-admin-inactive', [ 'user' => $user, 'new_password' => Input::get('password') ], function ($m2) use ($user) {
880
                        $m2->to($user->email, $user->first_name . ' ' . $user->last_name);
881
                        $m2->subject(Lang::get('base.mails.account_created'));
882
                    });
883
884
                    $activation = Activation::create($user);
885
886
                    // Data to be used on the email view
887
                    $data = array(
888
                        'user'          => $user,
889
                        'activationUrl' => URL::route('activate', [$user->id, $activation->code]),
890
                    );
891
892
                    // Send the activation code through email
893
                    Mail::queue('emails.auth.register-activate', $data, function ($m) use ($user) {
894
                        $m->to($user->email, $user->first_name . ' ' . $user->last_name);
895
                        $m->subject(Lang::get('base.mails.welcome') . ' ' . $user->first_name);
896
                    });
897
898
                }
899
            }
900
901
            //add user to 'User' group
902
            /*$role = Sentinel::findRoleById(Input::get('group'));
0 ignored issues
show
Unused Code Comprehensibility introduced by
46% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
903
            $role->users()->attach($user);
904
905
            //check for activation and send activation mail if not activated by default
906
            if(!Input::get('activate')) {
907
                // Data to be used on the email view
908
                $data = array(
909
                    'user'          => $user,
910
                    'activationUrl' => URL::route('activate', $user->id, Activation::create($user)->code),
911
                );
912
913
                // Send the activation code through email
914
                Mail::send('emails.register-activate', $data, function ($m) use ($user) {
915
                    $m->to($user->email, $user->first_name . ' ' . $user->last_name);
916
                    $m->subject('Welcome ' . $user->first_name);
917
                });
918
            }*/
919
920
            // Redirect to the home page with success menu
921
            return Redirect::route("users")->with('success', Lang::get('base.auth.account.created'));
922
923
        } catch (Exception $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
Bug introduced by
The class jlourenco\base\Controllers\Exception does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
924
        }
925
        $error = Lang::get('base.base.error');
926
927
        // Redirect to the user creation page
928
        return Redirect::back()->withInput()->with('error', $error);
929
    }
930
931
}
932