-
Notifications
You must be signed in to change notification settings - Fork 391
/
Copy pathUser.php
2523 lines (2109 loc) · 75.4 KB
/
User.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0.
// See the LICENCE file in the repository root for full licence text.
namespace App\Models;
use App\Exceptions\ChangeUsernameException;
use App\Exceptions\InvariantException;
use App\Exceptions\ModelNotSavedException;
use App\Jobs\EsDocument;
use App\Libraries\BBCodeForDB;
use App\Libraries\ChangeUsername;
use App\Libraries\Elasticsearch\Indexable;
use App\Libraries\Session\Store as SessionStore;
use App\Libraries\Transactions\AfterCommit;
use App\Libraries\Uploader;
use App\Libraries\User\AvatarHelper;
use App\Libraries\User\Cover;
use App\Libraries\User\DatadogLoginAttempt;
use App\Libraries\User\ProfileBeatmapset;
use App\Libraries\User\UsernamesForDbLookup;
use App\Libraries\UsernameValidation;
use App\Models\Forum\TopicWatch;
use App\Models\OAuth\Client;
use App\Traits\Memoizes;
use App\Traits\Validatable;
use Cache;
use Carbon\Carbon;
use DB;
use Ds\Set;
use Hash;
use Illuminate\Auth\Authenticatable;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Translation\HasLocalePreference;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Database\Eloquent\Relations\HasOneThrough;
use Illuminate\Database\QueryException;
use Laravel\Passport\HasApiTokens;
use League\OAuth2\Server\Exception\OAuthServerException;
use Request;
/**
* @property-read Collection<UserAccountHistory> $accountHistories
* @property-read Collection<ApiKey> $apiKeys
* @property-read Collection<UserBadge> $badges
* @property-read Collection<BeatmapDiscussionVote> $beatmapDiscussionVotes
* @property-read Collection<BeatmapDiscussion> $beatmapDiscussions
* @property-read Collection<BeatmapPlaycount> $beatmapPlaycounts
* @property-read Collection<Beatmap> $beatmaps
* @property-read Collection<BeatmapsetNomination> $beatmapsetNominations
* @property-read Collection<BeatmapsetUserRating> $beatmapsetRatings
* @property-read Collection<BeatmapsetWatch> $beatmapsetWatches
* @property-read Collection<Beatmapset> $beatmapsets
* @property-read Collection<static> $blocks
* @property-read Collection<Changelog> $changelogs
* @property-read Collection<Chat\Channel> $channels
* @property-read Collection<UserClient> $clients
* @property-read Collection<Comment> $comments
* @property-read Country|null $country
* @property string|null $country_acronym
* @property-write string|null $current_password
* @property-read Carbon|null $displayed_last_visit
* @property-read string|null $email
* @property-read Collection<Event> $events
* @property-read Collection<FavouriteBeatmapset> $favourites
* @property-read Collection<Follow> $follows
* @property-read Collection<Forum\Post> $forumPosts
* @property-read Collection<static> $friends
* @property-read GithubUser|null $githubUser
* @property-read Collection<KudosuHistory> $givenKudosu
* @property int $group_id
* @property bool $hide_presence
* @property bool $lock_email_changes
* @property-read Collection<UserMonthlyPlaycount> $monthlyPlaycounts
* @property-read Collection<UserNotificationOption> $notificationOptions
* @property-read Collection<Client> $oauthClients
* @property-read Collection<Store\Order> $orders
* @property int $osu_featurevotes
* @property int $osu_kudosavailable
* @property int $osu_kudosdenied
* @property int $osu_kudostotal
* @property float $osu_mapperrank
* @property string|null $osu_playmode
* @property string[]|null $osu_playstyle
* @property bool $osu_subscriber
* @property Carbon|null $osu_subscriptionexpiry
* @property int $osu_testversion
* @property-write string|null $password
* @property-write string|null $password_confirmation
* @property-read string|null $playmode
* @property bool $pm_friends_only
* @property-read Collection<ProfileBanner> $profileBanners
* @property-read Collection<Beatmapset> $profileBeatmapsetsGraveyard
* @property-read Collection<Beatmapset> $profileBeatmapsetsLoved
* @property-read Collection<Beatmapset> $profileBeatmapsetsPending
* @property-read Collection<Beatmapset> $profileBeatmapsetsRanked
* @property-read Rank $rank
* @property-read Collection<RankHighest> $rankHighests
* @property-read Collection<RankHistory> $rankHistories
* @property-read Collection<KudosuHistory> $receivedKudosu
* @property-read Collection<UserRelation> $relations
* @property string|null $remember_token
* @property-read Collection<UserReplaysWatchedCount> $replaysWatchedCounts
* @property-read Collection<UserReport> $reportsMade
* @property-read Collection<ScorePin> $scorePins
* @property-read Collection<Score\Best\Fruits> $scoresBestFruits
* @property-read Collection<Score\Best\Mania> $scoresBestMania
* @property-read Collection<Score\Best\Osu> $scoresBestOsu
* @property-read Collection<Score\Best\Taiko> $scoresBestTaiko
* @property-read Collection<Score\Best\Fruits> $scoresFirstFruits
* @property-read Collection<Score\Best\Mania> $scoresFirstMania
* @property-read Collection<Score\Best\Osu> $scoresFirstOsu
* @property-read Collection<Score\Best\Taiko> $scoresFirstTaiko
* @property-read Collection<Score\Fruits> $scoresFruits
* @property-read Collection<Score\Mania> $scoresMania
* @property-read Collection<Score\Osu> $scoresOsu
* @property-read Collection<Score\Taiko> $scoresTaiko
* @property-read Collection<UserSeasonScoreAggregate> $seasonScores
* @property-read UserStatistics\Fruits|null $statisticsFruits
* @property-read UserStatistics\Mania|null $statisticsMania
* @property-read UserStatistics\Mania4k|null $statisticsMania4k
* @property-read UserStatistics\Mania7k|null $statisticsMania7k
* @property-read UserStatistics\Osu|null $statisticsOsu
* @property-read UserStatistics\Taiko|null $statisticsTaiko
* @property-read Collection<Store\Address> $storeAddresses
* @property-read Collection<UserDonation> $supporterTagPurchases
* @property-read Collection<UserDonation> $supporterTags
* @property-read Team|null $team
* @property-read TeamApplication|null $teamApplication
* @property-read Collection<OAuth\Token> $tokens
* @property-read Collection<Forum\TopicWatch> $topicWatches
* @property-read Collection<UserAchievement> $userAchievements
* @property-read Collection<UserGroup> $userGroups
* @property-read Collection<UserNotification> $userNotifications
* @property-read Forum\Post|null $userPage
* @property-read UserProfileCustomization|null $userProfileCustomization
* @property string $user_actkey
* @property int $user_allow_massemail
* @property bool $user_allow_pm
* @property int $user_allow_viewemail
* @property bool $user_allow_viewonline
* @property string $user_avatar
* @property int $user_avatar_height
* @property int $user_avatar_type
* @property int $user_avatar_width
* @property string $user_birthday
* @property string|null $user_colour
* @property-read Collection<UserCountryHistory> $userCountryHistory
* @property string $user_dateformat
* @property string|null $user_discord
* @property int $user_dst
* @property string|null $user_email
* @property-write string|null $user_email_confirmation
* @property int $user_emailtime
* @property string|null $user_from
* @property int $user_full_folder
* @property int $user_id
* @property int $user_inactive_reason
* @property int $user_inactive_time
* @property string|null $user_interests
* @property string $user_ip
* @property string|null $user_jabber
* @property string $user_lang
* @property string $user_last_confirm_key
* @property int $user_last_privmsg
* @property int $user_last_search
* @property int $user_last_warning
* @property Carbon|null $user_lastmark
* @property string $user_lastpage
* @property Carbon|null $user_lastpost_time
* @property Carbon|null $user_lastvisit
* @property int $user_login_attempts
* @property int $user_message_rules
* @property string $user_msnm
* @property int $user_new_privmsg
* @property string $user_newpasswd
* @property bool $user_notify
* @property int $user_notify_pm
* @property int $user_notify_type
* @property string|null $user_occ
* @property int $user_options
* @property int $user_passchg
* @property string $user_password
* @property int|null $user_perm_from
* @property string $user_permissions
* @property int $user_post_show_days
* @property string $user_post_sortby_dir
* @property string $user_post_sortby_type
* @property int $user_posts
* @property int|null $user_rank
* @property Carbon $user_regdate
* @property string $user_sig
* @property string $user_sig_bbcode_bitfield
* @property string $user_sig_bbcode_uid
* @property int $user_style
* @property float $user_timezone
* @property int $user_topic_show_days
* @property string $user_topic_sortby_dir
* @property string $user_topic_sortby_type
* @property string|null $user_twitter
* @property int $user_type
* @property int $user_unread_privmsg
* @property int $user_warnings
* @property string|null $user_website
* @property string $username
* @property-read Collection<UsernameChangeHistory> $usernameChangeHistory
* @property-read Collection<UsernameChangeHistory> $usernameChangeHistoryPublic publically visible UsernameChangeHistory containing only user_id and username_last
* @property string $username_clean
* @property string|null $username_previous
* @property int|null $userpage_post_id
* @method static Builder default()
* @method static Builder eagerloadForListing()
* @method static Builder online()
*/
class User extends Model implements AfterCommit, AuthenticatableContract, HasLocalePreference, Indexable, Traits\ReportableInterface
{
use Authenticatable, HasApiTokens, Memoizes, Traits\Es\UserSearch, Traits\Reportable, Traits\UserScoreable, Traits\UserStore, Validatable;
const PLAYSTYLES = [
'mouse' => 1,
'keyboard' => 2,
'tablet' => 4,
'touch' => 8,
];
const CACHING = [
'follower_count' => [
'key' => 'followerCount',
'duration' => 43200, // 12 hours
],
'mapping_follower_count' => [
'key' => 'moddingFollowerCount',
'duration' => 43200, // 12 hours
],
];
const INACTIVE_DAYS = 180;
const MAX_FIELD_LENGTHS = [
'user_discord' => 37, // max 32char username + # + 4-digit discriminator
'user_from' => 25,
'user_interests' => 30,
'user_occ' => 30,
'user_sig' => 3000,
'user_twitter' => 255,
'user_website' => 200,
];
public $password = null;
public $timestamps = false;
protected $attributes = [
'user_allow_pm' => true,
];
protected $casts = [
'lock_email_changes' => 'boolean',
'osu_subscriber' => 'boolean',
'user_allow_pm' => 'boolean',
'user_allow_viewonline' => 'boolean',
'user_lastmark' => 'datetime',
'user_lastpost_time' => 'datetime',
'user_lastvisit' => 'datetime',
'user_notify' => 'boolean',
'user_regdate' => 'datetime',
'user_timezone' => 'float',
];
protected $dateFormat = 'U';
protected $primaryKey = 'user_id';
protected $table = 'phpbb_users';
private Cover $cover;
private Uploader $customCover;
private $validateCurrentPassword = false;
private $validatePasswordConfirmation = false;
private $passwordConfirmation = null;
private $currentPassword = null;
private $emailConfirmation = null;
private $validateEmailConfirmation = false;
private $isSessionVerified;
public static function statisticsRelationName(string $ruleset, ?string $variant = null): ?string
{
if (!Beatmap::isModeValid($ruleset) || !Beatmap::isVariantValid($ruleset, $variant)) {
return null;
}
$variantSuffix = $variant === null ? '' : "_{$variant}";
return 'statistics'.studly_case("{$ruleset}{$variantSuffix}");
}
public function userCountryHistory(): HasMany
{
return $this->hasMany(UserCountryHistory::class);
}
public function team(): HasOneThrough
{
return $this->hasOneThrough(
Team::class,
TeamMember::class,
'user_id',
'id',
'user_id',
'team_id',
);
}
public function teamApplication(): HasOne
{
return $this->hasOne(TeamApplication::class);
}
public function getAuthPassword()
{
return $this->user_password;
}
public function usernameChangeCost()
{
$minTier = $this->usernameChangeHistory()->paid()->exists() ? 1 : 0;
$tier = max(
$this->usernameChangeHistory()
->paid()
->where('timestamp', '>', Carbon::now()->subYears(3))
->count(),
$minTier,
);
return match ($tier) {
0 => 0,
1 => 8,
2 => 16,
3 => 32,
4 => 64,
default => 100,
};
}
public function revertUsername($type = 'revert'): UsernameChangeHistory
{
// TODO: normalize validation with changeUsername.
if ($this->user_id <= 1) {
throw new ChangeUsernameException('user_id is not valid');
}
if (!presence($this->username_previous)) {
throw new ChangeUsernameException('username_previous is blank.');
}
return $this->updateUsername($this->username_previous, $type);
}
public function changeUsername(string $newUsername, string $type): UsernameChangeHistory
{
$errors = $this->validateChangeUsername($newUsername, $type);
if ($errors->isAny()) {
throw new ChangeUsernameException($errors);
}
return $this->getConnection()->transaction(function () use ($newUsername, $type) {
static::findAndRenameUserForInactive($newUsername);
return $this->updateUsername($newUsername, $type);
});
}
public function renameIfInactive(): ?UsernameChangeHistory
{
if ($this->getUsernameAvailableAt() <= Carbon::now()) {
$newUsername = "{$this->username}_old";
return $this->tryUpdateUsername(0, $newUsername, 'inactive');
}
return null;
}
private function tryUpdateUsername(int $try, string $newUsername, string $type): UsernameChangeHistory
{
$name = $try > 0 ? "{$newUsername}_{$try}" : $newUsername;
try {
return $this->updateUsername($name, $type);
} catch (QueryException $ex) {
// Maybe use different suffix altogether if people manage
// to try using same name more than 21 times.
if (!is_sql_unique_exception($ex) || $try > 20) {
throw $ex;
}
return $this->tryUpdateUsername($try + 1, $newUsername, $type);
}
}
private function updateUsername(string $newUsername, string $type): UsernameChangeHistory
{
$oldUsername = $type === 'revert' ? null : $this->getOriginal('username');
$this->username_previous = $oldUsername;
$this->username = $newUsername;
return DB::transaction(function () use ($newUsername, $oldUsername, $type) {
Forum\Forum::where('forum_last_poster_id', $this->user_id)->update(['forum_last_poster_name' => $newUsername]);
// DB::table('phpbb_moderator_cache')->where('user_id', $this->user_id)->update(['username' => $newUsername]);
Forum\Post::where('poster_id', $this->user_id)->update(['post_username' => $newUsername]);
Forum\Topic::where('topic_poster', $this->user_id)
->update(['topic_first_poster_name' => $newUsername]);
Forum\Topic::where('topic_last_poster_id', $this->user_id)
->update(['topic_last_poster_name' => $newUsername]);
$history = $this->usernameChangeHistory()->create([
'username' => $newUsername,
'username_last' => $oldUsername,
'timestamp' => Carbon::now(),
'type' => $type,
]);
if (!$history->exists) {
throw new ModelNotSavedException('failed saving model');
}
$skipValidations = in_array($type, ['inactive', 'revert'], true);
$this->saveOrExplode(['skipValidations' => $skipValidations]);
return $history;
});
}
public static function cleanUsername($username)
{
return strtolower($username);
}
public static function findAndRenameUserForInactive($username): ?self
{
$existing = static::findByUsernameForInactive($username);
if ($existing !== null) {
$existing->renameIfInactive();
// TODO: throw if expected rename doesn't happen?
}
return $existing;
}
// TODO: be able to change which connection this runs on?
public static function findByUsernameForInactive($username): ?self
{
return static::whereIn(
'username',
UsernamesForDbLookup::make($username, trimPrefix: false),
)->first();
}
public static function checkWhenUsernameAvailable($username): Carbon
{
$user = static::findByUsernameForInactive($username);
if ($user !== null) {
return $user->getUsernameAvailableAt();
}
$lastUsage = UsernameChangeHistory::where('username_last', $username)
->where('type', '<>', 'inactive') // don't include changes caused by inactives; this validation needs to be removed on normal save.
->orderBy('change_id', 'desc')
->first();
if ($lastUsage === null) {
return Carbon::now();
}
return Carbon::parse($lastUsage->timestamp)->addDays(static::INACTIVE_DAYS);
}
public function getUsernameAvailableAt(): Carbon
{
$playCount = $this->playCount();
$allGroupIds = array_merge([$this->group_id], $this->groupIds()['active']);
$allowedGroupIds = array_map(function ($groupIdentifier) {
return app('groups')->byIdentifier($groupIdentifier)->getKey();
}, $GLOBALS['cfg']['osu']['user']['allowed_rename_groups']);
// only users which groups are all in the whitelist can be renamed
if (count(array_diff($allGroupIds, $allowedGroupIds)) > 0) {
return Carbon::now()->addYears(10);
}
if ($this->isRestricted()) {
$minDays = 0;
$expMod = 0.35;
$linMod = 0.75;
} else {
$minDays = static::INACTIVE_DAYS;
$expMod = 1;
$linMod = 1;
}
// This is a exponential decay function with the identity 1-e^{-$playCount}.
// The constant multiplier of 1580 causes the formula to flatten out at around 1580 days (~4.3 years).
// $playCount is then divided by the constant value 5900 causing it to flatten out at about 40,000 plays.
// A linear bonus of $playCount * 8 / 5900 is added to reward long-term players.
// Furthermore, when the user is restricted, the exponential decay function and the linear bonus are lowered.
// An interactive graph of the formula can be found at https://www.desmos.com/calculator/s7bxytxbbt
return $this->user_lastvisit
->addDays(
intval(
$minDays +
1580 * (1 - pow(M_E, $playCount * $expMod * -1 / 5900)) +
($playCount * $linMod * 8 / 5900)
)
);
}
public function validateChangeUsername(string $username, string $type = 'paid')
{
return (new ChangeUsername($this, $username, $type))->validate();
}
public static function lookup($usernameOrId, $type = null, $findAll = false): ?self
{
if (!present($usernameOrId)) {
return null;
}
switch ($type) {
case 'username':
$searchUsernames = UsernamesForDbLookup::make($usernameOrId);
$user = static::where(fn ($query) => $query
->whereIn('username', $searchUsernames)
->orWhereIn('username_clean', $searchUsernames));
break;
case 'id':
$user = static::where('user_id', $usernameOrId);
break;
default:
return ctype_digit((string) $usernameOrId)
? static::lookup($usernameOrId, 'id', $findAll)
: static::lookup($usernameOrId, 'username', $findAll);
}
if (!$findAll) {
$user->default();
}
$user = $user->first();
if ($user !== null && $user->hasProfile()) {
return $user;
}
return null;
}
public static function lookupWithHistory($usernameOrId, $type = null, $findAll = false)
{
$user = static::lookup($usernameOrId, $type, $findAll);
if ($user !== null) {
return $user;
}
// don't perform username change history lookup if we're searching by ID
// TODO: remove this parameter and always rely on `@` prefix or digit check.
if ($type === 'id') {
return null;
}
// also reject looking up history when it's all digit and not explicit username search
if ($type !== 'username' && ctype_digit($usernameOrId)) {
return null;
}
$change = UsernameChangeHistory::visible()
->whereIn('username_last', UsernamesForDbLookup::make($usernameOrId))
->orderBy('change_id', 'desc')
->first();
if ($change !== null) {
return static::lookup($change->user_id, 'id');
}
}
public function addToGroup(Group $group, ?array $playmodes = null, ?self $actor = null): void
{
$playmodes = array_unique($playmodes ?? []);
if (!$group->has_playmodes && $playmodes !== []) {
throw new InvariantException('Group does not allow playmodes');
}
$invalidPlaymodes = array_diff($playmodes, array_keys(Beatmap::MODES));
if ($invalidPlaymodes !== []) {
throw new InvariantException('Invalid playmodes: '.implode(', ', $invalidPlaymodes));
}
$activeUserGroup = $this->findUserGroup($group, true);
if ($activeUserGroup === null) {
$userGroup = $this
->userGroups()
->firstOrNew(['group_id' => $group->getKey()])
->setRelation('group', $group)
->fill([
'playmodes' => $playmodes,
'user_pending' => false,
]);
$this->getConnection()->transaction(function () use ($actor, $group, $userGroup) {
UserGroupEvent::logUserAdd($actor, $this, $group, $userGroup->playmodes);
$userGroup->save();
});
} else {
$previousPlaymodes = $activeUserGroup->playmodes ?? [];
$playmodesAdded = array_values(array_diff($playmodes, $previousPlaymodes));
$playmodesRemoved = array_values(array_diff($previousPlaymodes, $playmodes));
if ($playmodesAdded === [] && $playmodesRemoved === []) {
return;
}
$this->getConnection()->transaction(function () use ($activeUserGroup, $actor, $group, $playmodes, $playmodesAdded, $playmodesRemoved) {
if ($playmodesAdded !== []) {
UserGroupEvent::logUserAddPlaymodes($actor, $this, $group, $playmodesAdded);
}
if ($playmodesRemoved !== []) {
UserGroupEvent::logUserRemovePlaymodes($actor, $this, $group, $playmodesRemoved);
}
$activeUserGroup->update(['playmodes' => $playmodes]);
});
}
$this->unsetRelation('userGroups');
$this->resetMemoized();
}
public function removeFromGroup(Group $group, ?self $actor = null): void
{
$userGroup = $this->findUserGroup($group, false);
if ($userGroup === null) {
return;
}
$this->getConnection()->transaction(function () use ($actor, $group, $userGroup) {
if (!$userGroup->user_pending) {
UserGroupEvent::logUserRemove($actor, $this, $group);
}
$userGroup->delete();
if ($this->group_id === $group->getKey()) {
$this->setDefaultGroup(app('groups')->byIdentifier('default'));
}
});
$this->unsetRelation('userGroups');
$this->resetMemoized();
}
public function setDefaultGroup(Group $group, ?self $actor = null): void
{
$this->getConnection()->transaction(function () use ($actor, $group) {
if ($this->findUserGroup($group, true) === null) {
$this->addToGroup($group, null, $actor);
}
if ($this->group_id !== $group->getKey()) {
UserGroupEvent::logUserSetDefault($actor, $this, $group);
}
$this->update([
'group_id' => $group->getKey(),
'user_colour' => $group->group_colour,
'user_rank' => $group->group_rank,
]);
});
}
public function setUserFromAttribute($value)
{
$this->attributes['user_from'] = e(unzalgo($value));
}
public function setUserInterestsAttribute($value)
{
$this->attributes['user_interests'] = e(unzalgo($value));
}
public function setUserOccAttribute($value)
{
$this->attributes['user_occ'] = e(unzalgo($value));
}
public function setUserSigAttribute($value)
{
$bbcode = new BBCodeForDB($value);
$this->attributes['user_sig'] = $bbcode->generate();
$this->attributes['user_sig_bbcode_uid'] = $bbcode->uid;
}
public function setUserStyleAttribute(?int $value): void
{
if ($value === null || $value < 1 || $value > 360) {
$value = 0;
}
$this->attributes['user_style'] = $value;
}
public function setUserWebsiteAttribute($value)
{
// doubles as casting to empty string for not null constraint
// allowing zalgo in urls sounds like a terrible idea.
$value = unzalgo(trim($value), 0);
// FIXME: this can probably be removed after old site is deactivated
// as there's same check in getter function.
if (present($value) && !is_http($value)) {
$value = "https://{$value}";
}
$this->attributes['user_website'] = $value;
}
public function setOsuPlaystyleAttribute($value)
{
$styles = 0;
if ($value !== null) {
foreach (self::PLAYSTYLES as $type => $bit) {
if (in_array($type, $value, true)) {
$styles += $bit;
}
}
}
$this->attributes['osu_playstyle'] = $styles;
}
public function setPmFriendsOnlyAttribute($value)
{
$this->user_allow_pm = !$value;
}
public function setHidePresenceAttribute($value)
{
$this->user_allow_viewonline = !$value;
}
public function setUsernameAttribute($value)
{
$this->attributes['username'] = $value;
$this->username_clean = static::cleanUsername($value);
}
public function isLoginBlocked()
{
return $this->user_email === null;
}
public function isSpecial()
{
return $this->user_id !== null && present($this->user_colour);
}
public function setUserTwitterAttribute($value)
{
$this->attributes['user_twitter'] = trim(ltrim($value, '@'));
}
public function setUserDiscordAttribute($value)
{
$this->attributes['user_jabber'] = trim($value);
}
public function setUserColourAttribute($value)
{
// also functions for casting null to string
$this->attributes['user_colour'] = ltrim($value, '#');
}
public function getAttribute($key)
{
return match ($key) {
'cover_preset_id',
'custom_cover_filename',
'group_id',
'laravel_through_key', // added by hasManyThrough relation in Beatmap
'osu_featurevotes',
'osu_kudosavailable',
'osu_kudosdenied',
'osu_kudostotal',
'osu_mapperrank',
'osu_playmode',
'osu_testversion',
'remember_token',
'user_actkey',
'user_allow_massemail',
'user_allow_viewemail',
'user_avatar_height',
'user_avatar_type',
'user_avatar_width',
'user_birthday',
'user_dateformat',
'user_dst',
'user_email',
'user_emailtime',
'user_full_folder',
'user_id',
'user_inactive_reason',
'user_inactive_time',
'user_ip',
'user_last_confirm_key',
'user_last_privmsg',
'user_last_search',
'user_last_warning',
'user_lastpage',
'user_login_attempts',
'user_message_rules',
'user_msnm',
'user_new_privmsg',
'user_newpasswd',
'user_notify_pm',
'user_notify_type',
'user_options',
'user_passchg',
'user_password',
'user_perm_from',
'user_permissions',
'user_post_show_days',
'user_post_sortby_dir',
'user_post_sortby_type',
'user_posts',
'user_sig',
'user_sig_bbcode_bitfield',
'user_sig_bbcode_uid',
'user_topic_show_days',
'user_topic_sortby_dir',
'user_topic_sortby_type',
'user_type',
'user_unread_privmsg',
'user_warnings',
'username',
'username_clean',
'username_previous',
'userpage_post_id' => $this->getRawAttribute($key),
// boolean, default to false for null value
'lock_email_changes',
'osu_subscriber',
'user_allow_pm',
'user_allow_viewonline',
'user_notify' => (bool) $this->getRawAttribute($key),
// float
'user_timezone' => (float) $this->getRawAttribute($key),
// datetime but unix timestamp
'user_lastmark',
'user_lastpost_time',
'user_lastvisit',
'user_regdate' => Carbon::createFromTimestamp($this->getRawAttribute($key)),
// datetime
'osu_subscriptionexpiry' => $this->getTimeFast($key),
// custom cast
'displayed_last_visit' => $this->getDisplayedLastVisit(),
'osu_playstyle' => $this->getOsuPlaystyle(),
'playmode' => $this->getPlaymode(),
'user_avatar' => AvatarHelper::url($this),
'user_colour' => $this->getUserColour(),
'user_rank' => $this->getUserRank(),
'user_style' => $this->getUserStyle(),
'user_website' => $this->getUserWebsite(),
// one-liner cast
'country_acronym' => presence($this->getRawAttribute($key)),
'email' => $this->user_email,
'hide_presence' => !$this->user_allow_viewonline,
'id' => $this->getKey(), // used by clockwork
'name' => null, // used by mailer
'nonexistent' => null,
'pm_friends_only' => !$this->user_allow_pm,
'user_discord' => $this->user_jabber,
'user_from' => presence(html_entity_decode_better($this->getRawAttribute($key))),
'user_interests' => presence(html_entity_decode_better($this->getRawAttribute($key))),
'user_jabber' => presence($this->getRawAttribute($key)),
'user_lang' => get_valid_locale($this->getRawAttribute($key)),
'user_occ' => presence(html_entity_decode_better($this->getRawAttribute($key))),
'user_twitter' => presence(ltrim($this->getRawAttribute($key), '@')),
// relations
'accountHistories',
'apiKeys',
'badges',
'beatmapDiscussionVotes',
'beatmapDiscussions',
'beatmapPlaycounts',
'beatmaps',
'beatmapsetNominations',
'beatmapsetRatings',
'beatmapsetWatches',
'beatmapsets',
'blocks',
'changelogs',
'channels',
'clients',
'comments',
'country',
'dailyChallengeUserStats',
'events',
'favourites',
'follows',
'forumPosts',
'friends',
'githubUser',
'givenKudosu',
'legacyIrcKey',
'monthlyPlaycounts',
'notificationOptions',
'oauthClients',
'orders',
'pivot', // laravel built-in relation when using belongsToMany
'profileBanners',
'profileBannersActive',
'profileBeatmapsetsGraveyard',
'profileBeatmapsetsLoved',
'profileBeatmapsetsPending',
'profileBeatmapsetsRanked',
'rank',
'rankHighests',
'rankHistories',
'receivedKudosu',
'relationFriends',
'relations',
'replaysWatchedCounts',
'reportedIn',
'reportsMade',
'scorePins',
'scoresBestFruits',
'scoresBestMania',
'scoresBestOsu',
'scoresBestTaiko',
'scoresFirstFruits',
'scoresFirstMania',
'scoresFirstOsu',
'scoresFirstTaiko',
'scoresFruits',
'scoresMania',
'scoresOsu',
'scoresTaiko',
'soloScores',
'statisticsFruits',
'statisticsMania',
'statisticsMania4k',
'statisticsMania7k',
'statisticsOsu',
'statisticsTaiko',
'storeAddresses',
'supporterTagPurchases',
'supporterTags',
'team',
'teamApplication',
'tokens',
'topicWatches',
'userAchievements',
'userCountryHistory',
'userGroups',
'userNotifications',
'userPage',
'userProfileCustomization',
'usernameChangeHistory',
'usernameChangeHistoryPublic' => $this->getRelationValue($key),
};
}
/*
|--------------------------------------------------------------------------
| Permission Checker Functions
|--------------------------------------------------------------------------
|
| This checks to see if a user is in a specified group.
| You should try to be specific.
|
*/