Completed
Push — master ( 511324...c26f0f )
by Konstantinos
08:12
created

Player::getRoles()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
dl 0
loc 6
ccs 0
cts 3
cp 0
rs 9.4285
c 1
b 0
f 0
cc 1
eloc 3
nc 1
nop 0
crap 2
1
<?php
2
/**
3
 * This file contains functionality relating to a league player
4
 *
5
 * @package    BZiON\Models
6
 * @license    https://github.com/allejo/bzion/blob/master/LICENSE.md GNU General Public License Version 3
7
 */
8
9
use Symfony\Component\Security\Core\Util\SecureRandom;
10
use Symfony\Component\Security\Core\Util\StringUtils;
11
12
/**
13
 * A league player
14
 * @package    BZiON\Models
15
 */
16
class Player extends AvatarModel implements NamedModel
17
{
18
    /**
19
     * These are built-in roles that cannot be deleted via the web interface so we will be storing these values as
20
     * constant variables. Hopefully, a user won't be silly enough to delete them manually from the database.
21
     *
22
     * @TODO Deprecate these and use the Role constants
23
     */
24
    const DEVELOPER    = Role::DEVELOPER;
25
    const ADMIN        = Role::ADMINISTRATOR;
26
    const COP          = Role::COP;
27
    const REFEREE      = Role::REFEREE;
28
    const S_ADMIN      = Role::SYSADMIN;
29
    const PLAYER       = Role::PLAYER;
30
    const PLAYER_NO_PM = Role::PLAYER_NO_PM;
31
32
    /**
33
     * The bzid of the player
34
     * @var int
35
     */
36
    protected $bzid;
37
38
    /**
39
     * The id of the player's team
40
     * @var int
41
     */
42
    protected $team;
43
44
    /**
45
     * The player's status
46
     * @var string
47
     */
48
    protected $status;
49
50
    /**
51
     * The player's e-mail address
52
     * @var string
53
     */
54
    protected $email;
55
56
    /**
57
     * Whether the player has verified their e-mail address
58
     * @var bool
59
     */
60
    protected $verified;
61
62
    /**
63
     * What kind of events the player should be e-mailed about
64
     * @var string
65
     */
66
    protected $receives;
67
68
    /**
69
     * A confirmation code for the player's e-mail address verification
70
     * @var string
71
     */
72
    protected $confirmCode;
73
74
    /**
75
     * Whether the callsign of the player is outdated
76
     * @var bool
77
     */
78
    protected $outdated;
79
80
    /**
81
     * The player's profile description
82
     * @var string
83
     */
84
    protected $description;
85
86
    /**
87
     * The id of the player's country
88
     * @var int
89
     */
90
    protected $country;
91
92
    /**
93
     * The player's timezone PHP identifier, e.g. "Europe/Paris"
94
     * @var string
95
     */
96
    protected $timezone;
97
98
    /**
99
     * The date the player joined the site
100
     * @var TimeDate
101
     */
102
    protected $joined;
103
104
    /**
105
     * The date of the player's last login
106
     * @var TimeDate
107
     */
108
    protected $last_login;
109
110
    /**
111
     * The roles a player belongs to
112
     * @var Role[]
113
     */
114
    protected $roles;
115
116
    /**
117
     * The permissions a player has
118
     * @var Permission[]
119
     */
120
    protected $permissions;
121
122
    /**
123
     * A section for admins to write notes about players
124
     * @var string
125
     */
126
    protected $admin_notes;
127
128
    /**
129
     * The ban of the player, or null if the player is not banned
130
     * @var Ban|null
131
     */
132
    protected $player;
133
134
    /**
135
     * The name of the database table used for queries
136
     */
137
    const TABLE = "players";
138
139
    /**
140
     * The location where avatars will be stored
141
     */
142
    const AVATAR_LOCATION = "/web/assets/imgs/avatars/players/";
143
144
    const EDIT_PERMISSION = Permission::EDIT_USER;
145
    const SOFT_DELETE_PERMISSION = Permission::SOFT_DELETE_USER;
146
    const HARD_DELETE_PERMISSION = Permission::HARD_DELETE_USER;
147
148
    /**
149
     * {@inheritdoc}
150
     */
151 39
    protected function assignResult($player)
152
    {
153 39
        $this->bzid = $player['bzid'];
154 39
        $this->name = $player['username'];
155 39
        $this->alias = $player['alias'];
156 39
        $this->team = $player['team'];
157 39
        $this->status = $player['status'];
158 39
        $this->avatar = $player['avatar'];
159 39
        $this->country = $player['country'];
160 39
    }
161
162
    /**
163
     * {@inheritdoc}
164
     */
165 39
    protected function assignLazyResult($player)
166
    {
167 39
        $this->email = $player['email'];
168 39
        $this->verified = $player['verified'];
169 39
        $this->receives = $player['receives'];
170 39
        $this->confirmCode = $player['confirm_code'];
171 39
        $this->outdated = $player['outdated'];
172 39
        $this->description = $player['description'];
173 39
        $this->timezone = $player['timezone'];
174 39
        $this->joined = TimeDate::fromMysql($player['joined']);
175 39
        $this->last_login = TimeDate::fromMysql($player['last_login']);
176 39
        $this->admin_notes = $player['admin_notes'];
177 39
        $this->ban = Ban::getBan($this->id);
0 ignored issues
show
Bug introduced by
The property ban does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
178
179 39
        $this->updateUserPermissions();
180 39
    }
181
182
    /**
183
     * Add a player a new role
184
     *
185
     * @param Role|int $role_id The role ID to add a player to
186
     *
187
     * @return bool Whether the operation was successful or not
188
     */
189 39
    public function addRole($role_id)
190
    {
191 39
        if ($role_id instanceof Role) {
192 1
            $role_id = $role_id->getId();
193
        }
194
195 39
        $this->lazyLoad();
196
197
        // Make sure the player doesn't already have the role
198 39
        foreach ($this->roles as $playerRole) {
199 14
            if ($playerRole->getId() == $role_id) {
200 14
                return false;
201
            }
202
        }
203
204 39
        $status = $this->modifyRole($role_id, "add");
205 39
        $this->refresh();
206
207 39
        return $status;
208
    }
209
210
    /**
211
     * Get the notes admins have left about a player
212
     * @return string The notes
213
     */
214
    public function getAdminNotes()
215
    {
216
        $this->lazyLoad();
217
218
        return $this->admin_notes;
219
    }
220
221
    /**
222
     * Get the player's BZID
223
     * @return int The BZID
224
     */
225
    public function getBZID()
226
    {
227
        return $this->bzid;
228
    }
229
230
    /**
231
     * Get the country a player belongs to
232
     *
233
     * @return Country The country belongs to
234
     */
235 1
    public function getCountry()
236
    {
237 1
        return Country::get($this->country);
238
    }
239
240
    /**
241
     * Get the e-mail address of the player
242
     *
243
     * @return string The address
244
     */
245
    public function getEmailAddress()
246
    {
247
        $this->lazyLoad();
248
249
        return $this->email;
250
    }
251
252
    /**
253
     * Returns whether the player has verified their e-mail address
254
     *
255
     * @return bool `true` for verified players
256
     */
257
    public function isVerified()
258
    {
259
        $this->lazyLoad();
260
261
        return $this->verified;
262
    }
263
264
    /**
265
     * Returns the confirmation code for the player's e-mail address verification
266
     *
267
     * @return string The player's confirmation code
268
     */
269
    public function getConfirmCode()
270
    {
271
        $this->lazyLoad();
272
273
        return $this->confirmCode;
274
    }
275
276
    /**
277
     * Returns what kind of events the player should be e-mailed about
278
     *
279
     * @return string The type of notifications
280
     */
281
    public function getReceives()
282
    {
283
        $this->lazyLoad();
284
285
        return $this->receives;
286
    }
287
288
    /**
289
     * Finds out whether the specified player wants and can receive an e-mail
290
     * message
291
     *
292
     * @param  string  $type
293
     * @return bool `true` if the player should be sent an e-mail
294
     */
295 1
    public function canReceive($type)
296
    {
297 1
        $this->lazyLoad();
298
299 1
        if (!$this->email || !$this->isVerified()) {
300
            // Unverified e-mail means the user will receive nothing
301 1
            return false;
302
        }
303
304
        if ($this->receives == 'everything') {
305
            return true;
306
        }
307
308
        return $this->receives == $type;
309
    }
310
311
    /**
312
     * Find out whether the specified confirmation code is correct
313
     *
314
     * This method protects against timing attacks
315
     *
316
     * @return bool `true` for a correct e-mail verification code
317
     */
318
    public function isCorrectConfirmCode($code)
319
    {
320
        $this->lazyLoad();
321
322
        if ($this->confirmCode === null) {
323
            return false;
324
        }
325
326
        return StringUtils::equals($code, $this->confirmCode);
327
    }
328
329
    /**
330
     * Get the player's sanitized description
331
     * @return string The description
332
     */
333
    public function getDescription()
334
    {
335
        $this->lazyLoad();
336
337
        return $this->description;
338
    }
339
340
    /**
341
     * Get the joined date of the player
342
     * @return TimeDate The joined date of the player
343
     */
344
    public function getJoinedDate()
345
    {
346
        $this->lazyLoad();
347
348
        return $this->joined->copy();
349
    }
350
351
    /**
352
     * Get all of the known IPs used by the player
353
     *
354
     * @return string[][] An array containing IPs and hosts
355
     */
356
    public function getKnownIPs()
357
    {
358
        return $this->db->query("SELECT DISTINCT ip, host FROM visits WHERE player = ? LIMIT 10", array($this->getId()));
359
    }
360
361
    /**
362
     * Get the last login for a player
363
     * @return TimeDate The date of the last login
364
     */
365
    public function getLastLogin()
366
    {
367
        $this->lazyLoad();
368
369
        return $this->last_login->copy();
370
    }
371
372
    /**
373
     * Get all of the callsigns a player has used to log in to the website
374
     * @return string[] An array containing all of the past callsigns recorded for a player
375
     */
376
    public function getPastCallsigns()
377
    {
378
        return parent::fetchIds("WHERE player = ?", array($this->id), "past_callsigns", "username");
0 ignored issues
show
Comprehensibility Bug introduced by
It seems like you call parent on a different method (fetchIds() instead of getPastCallsigns()). Are you sure this is correct? If so, you might want to change this to $this->fetchIds().

This check looks for a call to a parent method whose name is different than the method from which it is called.

Consider the following code:

class Daddy
{
    protected function getFirstName()
    {
        return "Eidur";
    }

    protected function getSurName()
    {
        return "Gudjohnsen";
    }
}

class Son
{
    public function getFirstName()
    {
        return parent::getSurname();
    }
}

The getFirstName() method in the Son calls the wrong method in the parent class.

Loading history...
379
    }
380
381
    /**
382
     * Get the player's team
383
     * @return Team The object representing the team
384
     */
385 2
    public function getTeam()
386
    {
387 2
        return Team::get($this->team);
388
    }
389
390
    /**
391
     * Get the player's timezone PHP identifier (example: "Europe/Paris")
392
     * @return string The timezone
393
     */
394 1
    public function getTimezone()
395
    {
396 1
        $this->lazyLoad();
397
398 1
        return ($this->timezone) ?: date_default_timezone_get();
399
    }
400
401
    /**
402
     * Get the roles of the player
403
     * @return Role[]
404
     */
405
    public function getRoles()
406
    {
407
        $this->lazyLoad();
408
409
        return $this->roles;
410
    }
411
412
    /**
413
     * Rebuild the list of permissions a user has been granted
414
     */
415 39
    private function updateUserPermissions()
416
    {
417 39
        $this->roles = Role::getRoles($this->id);
0 ignored issues
show
Documentation Bug introduced by
It seems like \Role::getRoles($this->id) of type array<integer,object<Model>> is incompatible with the declared type array<integer,object<Role>> of property $roles.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
418 39
        $this->permissions = array();
419
420 39
        foreach ($this->roles as $role) {
421 39
            $this->permissions = array_merge($this->permissions, $role->getPerms());
0 ignored issues
show
Documentation Bug introduced by
It seems like array_merge($this->permi...ons, $role->getPerms()) of type array is incompatible with the declared type array<integer,object<Permission>> of property $permissions.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
Bug introduced by
It seems like you code against a specific sub-type and not the parent class Model as the method getPerms() does only exist in the following sub-classes of Model: Permission, Role. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
422
        }
423 39
    }
424
425
    /**
426
     * Check if a player has a specific permission
427
     *
428
     * @param string|null $permission The permission to check for
429
     *
430
     * @return bool Whether or not the player has the permission
431
     */
432 2
    public function hasPermission($permission)
433
    {
434 2
        if ($permission === null) {
435 1
            return false;
436
        }
437
438 2
        $this->lazyLoad();
439
440 2
        return isset($this->permissions[$permission]);
441
    }
442
443
    /**
444
     * Check whether the callsign of the player is outdated
445
     *
446
     * Returns true if this player has probably changed their callsign, making
447
     * the current username stored in the database obsolete
448
     *
449
     * @return bool Whether or not the player is disabled
450
     */
451
    public function isOutdated()
452
    {
453
        $this->lazyLoad();
454
455
        return $this->outdated;
456
    }
457
458
    /**
459
     * Check if a player's account has been disabled
460
     *
461
     * @return bool Whether or not the player is disabled
462
     */
463
    public function isDisabled()
464
    {
465
        return $this->status == "disabled";
466
    }
467
468
    /**
469
     * Check if everyone can log in as this user on a test environment
470
     *
471
     * @return bool
472
     */
473 1
    public function isTestUser()
474
    {
475 1
        return $this->status == "test";
476
    }
477
478
    /**
479
     * Check if a player is teamless
480
     *
481
     * @return bool True if the player is teamless
482
     */
483 18
    public function isTeamless()
484
    {
485 18
        return empty($this->team);
486
    }
487
488
    /**
489
     * Mark a player's account as banned
490
     */
491 1
    public function markAsBanned()
492
    {
493 1
        if ($this->status != 'active') {
494
            return $this;
495
        }
496
497 1
        return $this->updateProperty($this->status, "status", "banned");
498
    }
499
500
    /**
501
     * Mark a player's account as unbanned
502
     */
503
    public function markAsUnbanned()
504
    {
505
        if ($this->status != 'banned') {
506
            return $this;
507
        }
508
509
        return $this->updateProperty($this->status, "status", "active");
510
    }
511
512
    /**
513
     * Find out if a player is banned
514
     *
515
     * @return bool
516
     */
517 2
    public function isBanned()
518
    {
519 2
        return Ban::getBan($this->id) !== null;
520
    }
521
522
    /**
523
     * Get the ban of the player
524
     *
525
     * This method performs a load of all the lazy parameters of the Player
526
     *
527
     * @return Ban|null The current ban of the player, or null if the player is
528
     *                  is not banned
529
     */
530
    public function getBan()
531
    {
532
        $this->lazyLoad();
533
534
        return $this->ban;
535
    }
536
537
    /**
538
     * Remove a player from a role
539
     *
540
     * @param int $role_id The role ID to add or remove
541
     *
542
     * @return bool Whether the operation was successful or not
543
     */
544
    public function removeRole($role_id)
545
    {
546
        $status = $this->modifyRole($role_id, "remove");
547
        $this->refresh();
548
549
        return $status;
550
    }
551
552
    /**
553
     * Set the player's email address and reset their verification status
554
     * @param string $email The address
555
     */
556
    public function setEmailAddress($email)
557
    {
558
        $this->lazyLoad();
559
560
        if ($this->email == $email) {
561
            // The e-mail hasn't changed, don't do anything
562
            return;
563
        }
564
565
        $this->setVerified(false);
566
        $this->generateNewConfirmCode();
567
568
        $this->email = $email;
569
        $this->update("email", $email);
570
    }
571
572
    /**
573
     * Set whether the player has verified their e-mail address
574
     *
575
     * @param  bool $verified Whether the player is verified or not
576
     * @return self
577
     */
578
    public function setVerified($verified)
579
    {
580
        $this->lazyLoad();
581
582
        if ($verified) {
583
            $this->setConfirmCode(null);
584
        }
585
586
        return $this->updateProperty($this->verified, 'verified', $verified);
587
    }
588
589
    /**
590
     * Generate a new random confirmation token for e-mail address verification
591
     *
592
     * @return self
593
     */
594
    public function generateNewConfirmCode()
595
    {
596
        $generator = new SecureRandom();
0 ignored issues
show
Deprecated Code introduced by
The class Symfony\Component\Security\Core\Util\SecureRandom has been deprecated with message: since version 2.8, to be removed in 3.0. Use the random_bytes function instead

This class, trait or interface has been deprecated. The supplier of the file has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the type will be removed from the class and what other constant to use instead.

Loading history...
597
        $random = $generator->nextBytes(16);
598
599
        return $this->setConfirmCode(bin2hex($random));
600
    }
601
602
    /**
603
     * Set the confirmation token for e-mail address verification
604
     *
605
     * @param  string $code The confirmation code
606
     * @return self
607
     */
608
    private function setConfirmCode($code)
609
    {
610
        $this->lazyLoad();
611
612
        return $this->updateProperty($this->confirmCode, 'confirm_code', $code);
613
    }
614
615
    /**
616
     * Set what kind of events the player should be e-mailed about
617
     *
618
     * @param  string $receives The type of notification
619
     * @return self
620
     */
621
    public function setReceives($receives)
622
    {
623
        $this->lazyLoad();
624
625
        return $this->updateProperty($this->receives, 'receives', $receives);
626
    }
627
628
    /**
629
     * Set whether the callsign of the player is outdated
630
     *
631
     * @param  bool $outdated Whether the callsign is outdated
632
     * @return self
633
     */
634 39
    public function setOutdated($outdated)
635
    {
636 39
        $this->lazyLoad();
637
638 39
        return $this->updateProperty($this->outdated, 'outdated', $outdated);
639
    }
640
641
    /**
642
     * Set the player's description
643
     * @param string $description The description
644
     */
645
    public function setDescription($description)
646
    {
647
        $this->description = $description;
648
        $this->update("description", $description);
649
    }
650
651
    /**
652
     * Set the player's timezone
653
     * @param string $timezone The timezone
654
     */
655
    public function setTimezone($timezone)
656
    {
657
        $this->timezone = $timezone;
658
        $this->update("timezone", $timezone);
659
    }
660
661
    /**
662
     * Set the player's team
663
     * @param int $team The team's ID
664
     */
665 18
    public function setTeam($team)
666
    {
667 18
        $this->team = $team;
668 18
        $this->update("team", $team);
669 18
    }
670
671
    /**
672
     * Set the player's status
673
     * @param string $status The new status
674
     */
675
    public function setStatus($status)
676
    {
677
        $this->updateProperty($this->status, 'status', $status);
678
    }
679
680
    /**
681
     * Set the player's admin notes
682
     * @param  string $admin_notes The new admin notes
683
     * @return self
684
     */
685
    public function setAdminNotes($admin_notes)
686
    {
687
        return $this->updateProperty($this->admin_notes, 'admin_notes', $admin_notes);
688
    }
689
690
    /**
691
     * Set the player's country
692
     * @param  int   $country The ID of the new country
693
     * @return self
694
     */
695
    public function setCountry($country)
696
    {
697
        return $this->updateProperty($this->country, 'country', $country);
698
    }
699
700
    /**
701
     * Updates this player's last login
702
     */
703
    public function updateLastLogin()
704
    {
705
        $this->update("last_login", TimeDate::now()->toMysql());
706
    }
707
708
    /**
709
     * Get the player's username
710
     * @return string The username
711
     */
712 1
    public function getUsername()
713
    {
714 1
        return $this->name;
715
    }
716
717
    /**
718
     * Get the player's username, safe for use in your HTML
719
     * @return string The username
720
     */
721 1
    public function getEscapedUsername()
722
    {
723 1
        return $this->getEscapedName();
724
    }
725
726
    /**
727
     * Alias for Player::setUsername()
728
     *
729
     * @param  string $username The new username
730
     * @return self
731
     */
732
    public function setName($username)
733
    {
734
        return $this->setUsername($username);
735
    }
736
737
    /**
738
     * Mark all the unread messages of a player as read
739
     *
740
     * @return void
741
     */
742
    public function markMessagesAsRead()
743
    {
744
        $this->db->execute(
745
            "UPDATE `player_conversations` SET `read` = 1 WHERE `player` = ? AND `read` = 0",
746
            array($this->id)
747
        );
748
    }
749
750
    /**
751
     * Set the roles of a user
752
     *
753
     * @todo   Is it worth making this faster?
754
     * @param  Role[] $roles The new roles of the user
755
     * @return self
756
     */
757
    public function setRoles($roles)
758
    {
759
        $this->lazyLoad();
760
761
        $oldRoles = Role::mapToIds($this->roles);
762
        $this->roles = $roles;
763
        $roleIds = Role::mapToIds($roles);
764
765
        $newRoles     = array_diff($roleIds, $oldRoles);
766
        $removedRoles = array_diff($oldRoles, $roleIds);
767
768
        foreach ($newRoles as $role) {
769
            $this->modifyRole($role, 'add');
770
        }
771
772
        foreach ($removedRoles as $role) {
773
            $this->modifyRole($role, 'remove');
774
        }
775
776
        $this->refresh();
777
778
        return $this;
779
    }
780
781
    /**
782
     * Give or remove a role to/form a player
783
     *
784
     * @param int    $role_id The role ID to add or remove
785
     * @param string $action  Whether to "add" or "remove" a role for a player
786
     *
787
     * @return bool Whether the operation was successful or not
788
     */
789 39
    private function modifyRole($role_id, $action)
790
    {
791 39
        $role = Role::get($role_id);
792
793 39
        if ($role->isValid()) {
794 39
            if ($action == "add") {
795 39
                $this->db->execute("INSERT INTO player_roles (user_id, role_id) VALUES (?, ?)", array($this->getId(), $role_id));
796
            } elseif ($action == "remove") {
797
                $this->db->execute("DELETE FROM player_roles WHERE user_id = ? AND role_id = ?", array($this->getId(), $role_id));
798
            } else {
799
                throw new Exception("Unrecognized role action");
800
            }
801
802 39
            return true;
803
        }
804
805
        return false;
806
    }
807
808
    /**
809
     * Given a player's BZID, get a player object
810
     *
811
     * @param  int    $bzid The player's BZID
812
     * @return Player
813
     */
814 1
    public static function getFromBZID($bzid)
815
    {
816 1
        return self::get(self::fetchIdFrom($bzid, "bzid"));
817
    }
818
819
    /**
820
     * Get a single player by their username
821
     *
822
     * @param  string $username The username to look for
823
     * @return Player
824
     */
825 1
    public static function getFromUsername($username)
826
    {
827 1
        $player = static::get(self::fetchIdFrom($username, 'username'));
828
829 1
        return $player->inject('name', $username);
830
    }
831
832
    /**
833
     * Get all the players in the database that have an active status
834
     * @return Player[] An array of player BZIDs
835
     */
836
    public static function getPlayers()
837
    {
838
        return self::arrayIdToModel(
839
            parent::fetchIdsFrom("status", array("active", "test"), false)
0 ignored issues
show
Comprehensibility Bug introduced by
It seems like you call parent on a different method (fetchIdsFrom() instead of getPlayers()). Are you sure this is correct? If so, you might want to change this to $this->fetchIdsFrom().

This check looks for a call to a parent method whose name is different than the method from which it is called.

Consider the following code:

class Daddy
{
    protected function getFirstName()
    {
        return "Eidur";
    }

    protected function getSurName()
    {
        return "Gudjohnsen";
    }
}

class Son
{
    public function getFirstName()
    {
        return parent::getSurname();
    }
}

The getFirstName() method in the Son calls the wrong method in the parent class.

Loading history...
840
        );
841
    }
842
843
    /**
844
     * Show the number of notifications the user hasn't read yet
845
     * @return int
846
     */
847 1
    public function countUnreadNotifications()
848
    {
849 1
        return Notification::countUnreadNotifications($this->id);
850
    }
851
852
    /**
853
     * Show the number of messages the user hasn't read yet
854
     * @return int
855
     */
856 1
    public function countUnreadMessages()
857
    {
858 1
        return $this->fetchCount("WHERE `player` = ? AND `read` = 0",
859 1
            $this->id, 'player_conversations'
0 ignored issues
show
Documentation introduced by
$this->id is of type integer, but the function expects a array.

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...
860
        );
861
    }
862
863
    /**
864
     * Get all of the members belonging to a team
865
     * @param  int      $teamID The ID of the team to fetch the members of
866
     * @return Player[] An array of Player objects of the team members
867
     */
868 2
    public static function getTeamMembers($teamID)
869
    {
870 2
        return self::arrayIdToModel(
871 2
            parent::fetchIds("WHERE team = ?", array($teamID))
0 ignored issues
show
Comprehensibility Bug introduced by
It seems like you call parent on a different method (fetchIds() instead of getTeamMembers()). Are you sure this is correct? If so, you might want to change this to $this->fetchIds().

This check looks for a call to a parent method whose name is different than the method from which it is called.

Consider the following code:

class Daddy
{
    protected function getFirstName()
    {
        return "Eidur";
    }

    protected function getSurName()
    {
        return "Gudjohnsen";
    }
}

class Son
{
    public function getFirstName()
    {
        return parent::getSurname();
    }
}

The getFirstName() method in the Son calls the wrong method in the parent class.

Loading history...
872
        );
873
    }
874
875
    /**
876
     * {@inheritdoc}
877
     */
878 1
    public static function getActiveStatuses()
879
    {
880 1
        return array('active', 'reported', 'test');
881
    }
882
883
    /**
884
     * {@inheritdoc}
885
     */
886 39
    public static function getEagerColumns()
887
    {
888 39
        return 'id,bzid,team,username,alias,status,avatar,country';
889
    }
890
891
    /**
892
     * {@inheritdoc}
893
     */
894 39
    public static function getLazyColumns()
895
    {
896 39
        return 'email,verified,receives,confirm_code,outdated,description,timezone,joined,last_login,admin_notes';
897
    }
898
899
    /**
900
     * Get a query builder for players
901
     * @return QueryBuilder
902
     */
903 View Code Duplication
    public static function getQueryBuilder()
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...
904
    {
905
        return new QueryBuilder('Player', array(
906
            'columns' => array(
907
                'name'     => 'username',
908
                'team'     => 'team',
909
                'outdated' => 'outdated',
910
                'status'   => 'status'
911
            ),
912
            'name' => 'name',
913
        ));
914
    }
915
916
    /**
917
     * Enter a new player to the database
918
     * @param  int              $bzid        The player's bzid
919
     * @param  string           $username    The player's username
920
     * @param  int              $team        The player's team
921
     * @param  string           $status      The player's status
922
     * @param  int              $role_id     The player's role when they are first created
923
     * @param  string           $avatar      The player's profile avatar
924
     * @param  string           $description The player's profile description
925
     * @param  int              $country     The player's country
926
     * @param  string           $timezone    The player's timezone
927
     * @param  string|\TimeDate $joined      The date the player joined
928
     * @param  string|\TimeDate $last_login  The timestamp of the player's last login
929
     * @return Player           An object representing the player that was just entered
930
     */
931 39
    public static function newPlayer($bzid, $username, $team = null, $status = "active", $role_id = self::PLAYER, $avatar = "", $description = "", $country = 1, $timezone = null, $joined = "now", $last_login = "now")
932
    {
933 39
        $joined = TimeDate::from($joined);
934 39
        $last_login = TimeDate::from($last_login);
935 39
        $timezone = ($timezone) ?: date_default_timezone_get();
936
937 39
        $player = self::create(array(
938 39
            'bzid'        => $bzid,
939 39
            'team'        => $team,
940 39
            'username'    => $username,
941 39
            'alias'       => self::generateAlias($username),
942 39
            'status'      => $status,
943 39
            'avatar'      => $avatar,
944 39
            'description' => $description,
945 39
            'country'     => $country,
946 39
            'timezone'    => $timezone,
947 39
            'joined'      => $joined->toMysql(),
948 39
            'last_login'  => $last_login->toMysql(),
949
        ));
950
951 39
        $player->addRole($role_id);
952 39
        $player->getIdenticon($player->getId());
953 39
        $player->setUsername($username);
954
955 39
        return $player;
956
    }
957
958
    /**
959
     * Determine if a player exists in the database
960
     * @param  int  $bzid The player's bzid
961
     * @return bool Whether the player exists in the database
962
     */
963
    public static function playerBZIDExists($bzid)
964
    {
965
        return self::getFromBZID($bzid)->isValid();
966
    }
967
968
    /**
969
     * Change a player's callsign and add it to the database if it does not
970
     * exist as a past callsign
971
     *
972
     * @param  string $username The new username of the player
973
     * @return self
974
     */
975 39
    public function setUsername($username)
976
    {
977
        // The player's username was just fetched from BzDB, it's definitely not
978
        // outdated
979 39
        $this->setOutdated(false);
980
981
        // Players who have this player's username are considered outdated
982 39
        $this->db->execute("UPDATE {$this->table} SET outdated = 1 WHERE username = ? AND id != ?", array($username, $this->id));
983
984 39
        if ($username === $this->name) {
985
            // The player's username hasn't changed, no need to do anything
986 1
            return $this;
987
        }
988
989
        // Players who used to have our player's username are not outdated anymore,
990
        // unless they are more than one.
991
        // Even though we are sure that the old and new usernames are not equal,
992
        // MySQL makes a different type of string equality tests, which is why we
993
        // also check IDs to make sure not to affect our own player's outdatedness.
994 38
        $this->db->execute("
995 38
            UPDATE {$this->table} SET outdated =
996 38
                (SELECT (COUNT(*)>1) FROM (SELECT 1 FROM {$this->table} WHERE username = ? AND id != ?) t)
997 38
            WHERE username = ? AND id != ?",
998 38
            array($this->name, $this->id, $this->name, $this->id));
999
1000 38
        $this->updateProperty($this->name, 'username', $username);
1001 38
        $this->db->execute("INSERT IGNORE INTO past_callsigns (player, username) VALUES (?, ?)", array($this->id, $username));
1002 38
        $this->resetAlias();
1003
1004 38
        return $this;
1005
    }
1006
1007
    /**
1008
     * Alphabetical order function for use in usort (case-insensitive)
1009
     * @return Closure The sort function
1010
     */
1011
    public static function getAlphabeticalSort()
1012
    {
1013 1
        return function (Player $a, Player $b) {
1014 1
            return strcasecmp($a->getUsername(), $b->getUsername());
1015 1
        };
1016
    }
1017
1018
    /**
1019
     * {@inheritdoc}
1020
     * @todo Add a constraint that does this automatically
1021
     */
1022 39
    public function wipe()
1023
    {
1024 39
        $this->db->execute("DELETE FROM past_callsigns WHERE player = ?", $this->id);
1025
1026 39
        parent::wipe();
1027 39
    }
1028
1029
    /**
1030
     * Find whether the player can delete a model
1031
     *
1032
     * @param  PermissionModel $model       The model that will be seen
1033
     * @param  bool         $showDeleted Whether to show deleted models to admins
1034
     * @return bool
1035
     */
1036 1
    public function canSee($model, $showDeleted = false)
1037
    {
1038 1
        return $model->canBeSeenBy($this, $showDeleted);
1039
    }
1040
1041
    /**
1042
     * Find whether the player can delete a model
1043
     *
1044
     * @param  PermissionModel $model The model that will be deleted
1045
     * @param  bool         $hard  Whether to check for hard-delete perms, as opposed
1046
     *                                to soft-delete ones
1047
     * @return bool
1048
     */
1049 1
    public function canDelete($model, $hard = false)
1050
    {
1051 1
        if ($hard) {
1052
            return $model->canBeHardDeletedBy($this);
1053
        } else {
1054 1
            return $model->canBeSoftDeletedBy($this);
1055
        }
1056
    }
1057
1058
    /**
1059
     * Find whether the player can create a model
1060
     *
1061
     * @param  string  $modelName The PHP class identifier of the model type
1062
     * @return bool
1063
     */
1064 1
    public function canCreate($modelName)
1065
    {
1066 1
        return $modelName::canBeCreatedBy($this);
1067
    }
1068
1069
    /**
1070
     * Find whether the player can edit a model
1071
     *
1072
     * @param  PermissionModel $model The model which will be edited
1073
     * @return bool
1074
     */
1075 1
    public function canEdit($model)
1076
    {
1077 1
        return $model->canBeEditedBy($this);
1078
    }
1079
}
1080