forked from TheRestartProject/restarters.net
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUser.php
More file actions
676 lines (566 loc) · 21.4 KB
/
User.php
File metadata and controls
676 lines (566 loc) · 21.4 KB
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
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Attributes\Scope;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use App\Events\UserDeleted;
use App\Events\UserUpdated;
use Stevebauman\Purify\Facades\Purify;
use App\Helpers\Fixometer;
use App\Models\Network;
use App\Models\UserGroups;
use App\Models\UsersPermissions;
use DB;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Support\Str;
use OwenIt\Auditing\Contracts\Auditable;
use Illuminate\Contracts\Translation\HasLocalePreference;
class User extends Authenticatable implements Auditable, HasLocalePreference
{
use HasFactory;
use Notifiable;
use SoftDeletes;
use \OwenIt\Auditing\Auditable;
// Use the Authorizable trait so that we can call can() on a user to evaluation policies.
use \Illuminate\Foundation\Auth\Access\Authorizable;
// Radius within which a group has to be for it to be considered nearby.
const NEARBY_KM = 50;
protected $table = 'users';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'email', 'password', 'role', 'recovery', 'recovery_expires', 'language', 'repair_network', 'location', 'age', 'gender', 'country_code', 'newsletter', 'invites', 'biography', 'consent_future_data', 'consent_past_data', 'consent_gdpr', 'number_of_logins', 'latitude', 'longitude', 'last_login_at', 'api_token', 'access_group_tag_id', 'calendar_hash', 'repairdir_role', 'mediawiki', 'username', 'external_user_id', 'external_username',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* Attributes to exclude from the Audit.
*
* @var array
*/
protected $auditExclude = [
'number_of_logins',
'last_login_at',
'remember_token',
];
public function setNameAttribute($value)
{
$this->attributes['name'] = $value === null ? null : strip_tags((string) $value);
}
public function setLocationAttribute($value)
{
$this->attributes['location'] = $value === null ? null : strip_tags((string) $value);
}
public function setBiographyAttribute($value)
{
$this->attributes['biography'] = $value === null ? null : Purify::clean((string) $value);
}
/**
* The event map for the model.
*
* @var array
*/
protected $dispatchesEvents = [
'updated' => UserUpdated::class,
'deleted' => UserDeleted::class,
];
public function role(): HasOne
{
return $this->hasOne(\App\Models\Role::class, 'idroles', 'role');
}
public function repairdir_role()
{
// Make sure we don't return a null value. The client select would struggle with null values.
return $this->repairdir_role ? $this->repairdir_role : Role::REPAIR_DIRECTORY_NONE;
}
public function userSkills(): HasMany
{
return $this->hasMany(\App\Models\UsersSkills::class, 'user', 'id');
}
public function skills(): BelongsToMany
{
return $this->belongsToMany(\App\Models\Skills::class, 'users_skills', 'user', 'skill');
}
// This is an incorrect relationship, but leaving it here for now as it is used in a strange way in two legacy places and apparently working in those instances somehow.
// Use skills() for correct belongsToMany relationship.
public function skillsold(): BelongsToMany
{
return $this->belongsToMany(\App\Models\UsersSkills::class, 'users_skills', 'user', 'skill');
}
public function hasSkill($skill)
{
return $this->skills->contains($skill->id);
}
public function assignSkill($skill)
{
if (! $this->hasSkill($skill->id)) {
$this->skills()->attach($skill->id);
}
}
public function groups(): BelongsToMany
{
return $this->belongsToMany(\App\Models\Group::class, 'users_groups', 'user', 'group');
}
/**
* Return a list of repair groups near the user that they are not already a member of.
*
* @param int $numberOfGroups How many groups to return
* @param string String of minimum creation date
*/
public function groupsNearby(int $numberOfGroups = 10, $createdSince = null, $nearby = self::NEARBY_KM)
{
if (is_null($this->latitude) || is_null($this->longitude)) {
return [];
}
$groupsNearbyQuery = Group::selectRaw(
'*, ( 6371 * acos( cos( radians(?) ) * cos( radians( latitude ) ) * cos( radians( longitude ) - radians(?) ) + sin( radians(?) ) * sin( radians( latitude ) ) ) ) AS dist',
[$this->latitude, $this->longitude, $this->latitude]
)->where(function ($q) {
$q->whereNull('archived_at');
// Only show approved groups.
$q->where('approved', true);
})->having('dist', '<=', $nearby)
->groupBy('idgroups');
if ($createdSince) {
$groupsNearbyQuery->whereDate('created_at', '>=', date('Y-m-d', strtotime($createdSince)));
}
$groups = $groupsNearbyQuery->orderBy('dist', 'ASC')
->take($numberOfGroups)
->get();
// Expand the image
$groupsNearby = [];
if ($groups) {
foreach ($groups as $group) {
$group_image = $group->groupImage;
if (is_object($group_image) && is_object($group_image->image)) {
$group_image->image->path;
}
// Store for later retrieval. This is unusual because the value is not stored in the table.
$group->setDistanceAttribute($group->dist);
$groupsNearby[] = $group;
}
}
return $groupsNearby;
}
public function preferences(): BelongsToMany
{
return $this->belongsToMany(self::class, 'users_preferences', 'user_id', 'preference_id');
}
public function permissions(): BelongsToMany
{
return $this->belongsToMany(self::class, 'users_permissions', 'user_id', 'permission_id');
}
public function addPreference($slug)
{
/** @var Preferences $preference */
$preference = Preferences::where(['slug' => $slug])->first();
UsersPreferences::create([
'user_id' => $this->getKey(),
'preference_id' => $preference->getKey(),
]);
}
public function getRolePermissions($role)
{
return DB::select('SELECT p.idpermissions, p.permission, r.idroles, r.role FROM permissions AS p
INNER JOIN roles_permissions AS rp ON rp.permission = p.idpermissions
INNER JOIN roles AS r ON rp.role= r.idroles
WHERE r.role = :role', ['role' => $role]);
}
public function getUserGroups($user)
{
return DB::select('SELECT * FROM `'.$this->table.'` AS `u`
INNER JOIN `users_groups` AS `ug` ON `ug`.`user` = `u`.`id`
INNER JOIN `groups` AS `g` ON `ug`.`group` = `g`.`idgroups`
WHERE `u`.`id` = :id', ['id' => $user]);
}
// Setters
public function setPassword($password)
{
$this->password = $password;
}
//Getters
public static function getProfile($id)
{
//Tested!
try {
return self::where('users.id', '=', $id)
->leftJoin('images', function ($join) use ($id) {
$join->join('xref', 'xref.object', '=', 'images.idimages')
->where('xref.object_type', '=', 5)
->where('xref.reference_type', '=', 1)
->where('xref.reference', '=', $id)
->groupBy('images.path')
->select('images.*');
})->first();
} catch (\Illuminate\Database\QueryException $e) {
return false;
}
}
// public function find($params){//Laravel method called find already. Need Solution!!//Tested!
// $sql = 'SELECT * FROM ' . $this->table . '
// INNER JOIN roles ON roles.idroles = ' . $this->table . '.role
// WHERE ';
// $clauses = array();
// foreach($params as $field => $value) {
// $clauses[] = $field . ' = :' . $field;
//
// $sql .= implode(' AND ', $clauses);
//
// try {
// return DB::select($sql, $params);
// } catch (\Illuminate\Database\QueryException $e) {
// return false;
// }
// }
public function getUserList($eloquent = false)
{
//Tested!
if (! $eloquent) {
$Users = DB::select('SELECT users.id AS id, users.name, users.email, roles.role FROM users
INNER JOIN roles ON roles.idroles = users.role WHERE users.deleted_at IS NULL
ORDER BY users.id ASC'); //INNER JOIN sessions ON sessions.user = users.id, UNIX_TIMESTAMP(sessions.modified_at) AS modified_at
if (is_array($Users)) {
$User = new self;
foreach ($Users as $key => $user) {
$Users[$key]->permissions = $User->getRolePermissions($user->role);
}
}
} else {
$Users = self::join('roles', 'users.role', '=', 'roles.idroles');
}
return $Users;
}
public function partyEligible()
{
//Tested!
return DB::select('SELECT
users.id AS id,
users.name,
users.email,
roles.role
FROM '.$this->table.'
INNER JOIN roles ON roles.idroles = users.role
WHERE users.role > 1
ORDER BY users.name ASC');
}
public function inGroup($group)
{
return DB::select('SELECT
users.id AS id,
users.name,
users.email,
roles.role
FROM '.$this->table.'
INNER JOIN roles ON roles.idroles = users.role
WHERE users.role > 1
AND users.id IN
(SELECT `user` FROM users_groups WHERE `group` = :group)
ORDER BY users.name ASC', ['group' => $group]);
}
public function isInGroup($groupId)
{
return UserGroups::where('user', $this->id)
->where('group', $groupId)
->exists();
}
//This create user function is already done by the RegisterController
/** check if email is already in the database **/
public function checkEmail($email)
{
//Tested!
$r = DB::select('SELECT COUNT(id) AS emails FROM '.$this->table.' WHERE email = :email', ['email' => $email]);
return ($r[0]->emails > 0) ? false : true;
}
#[Scope]
protected function nearbyRestarters($query, $latitude, $longitude, $radius = 20)
{
return $query->selectRaw(
'*, ( 6371 * acos( cos( radians(?) ) * cos( radians( latitude ) ) * cos( radians( longitude ) - radians(?) ) + sin( radians(?) ) * sin( radians( latitude ) ) ) ) AS distance',
[$latitude, $longitude, $latitude]
)
->whereNotNull('location')
->whereNotNull('latitude')
->whereNotNull('longitude')
->having('distance', '<=', $radius);
}
/*
*
* This allows us to check whether consent has been provided - couples with custom middleware
*
*/
public function hasUserGivenConsent()
{
if (is_null($this->consent_future_data)) {
return false;
}
//Past data is only required for users who created their account prior to the Laravel app launch
if (is_null($this->consent_past_data) && strtotime($this->created_at) <= strtotime(date('2018-06-26'))) {
return false;
}
if (is_null($this->consent_gdpr)) {
return false;
}
return true;
}
public function lastLogin(): \Carbon\Carbon
{
return new \Carbon\Carbon($this->last_login_at);
}
/**
* Anonymise user details before soft deletion.
*/
public function anonymise()
{
$this->name = 'Deleted User';
$this->email = $this->id.'@deleted.invalid';
// TODO: country, city, gender, age, also required?
return $this;
}
/**
* Attempt to get first name from full name.
*/
public function getFirstName()
{
if ($this->name == '') {
return '';
}
$nameParts = explode(' ', $this->name);
return $nameParts[0];
}
public function existsOnDiscourse()
{
if (! config('restarters.features.discourse_integration')) {
return false;
}
return $this->username != NULL;
}
/**
* Convert the user's role to be a Host.
*
* Currently, the only role that should be convertible to a Host is a Restarter. Admins and NetworkCoordinators should not be downgraded, and if already a Host, no need to change it.
*/
public function convertToHost()
{
if ($this->role == Role::RESTARTER) {
$this->role = Role::HOST;
$this->save();
}
}
public function groupTag(): HasOne
{
return $this->hasOne(GroupTags::class, 'id', 'access_group_tag_id');
}
/**
* Generate a username based on the user's name, and set it against this user.
*
* Attempts to mimic the same logic as Discourse username generation.
*/
public function generateAndSetUsername()
{
if (empty($this->name)) {
throw new \Exception('Name is empty');
}
$name = $this->name;
$name = trim($name);
$name = transliterator_transliterate('Any-Latin;Latin-ASCII;', $name);
$name_parts = explode(' ', $name);
$desired_username = implode('_', $name_parts);
// Discourse doesn't allow repeated special characters - see https://github.com/discourse/discourse/blob/main/app/models/username_validator.rb.
$desired_username = preg_replace('/[-_.]{2,}/', '_', $desired_username);
if (! (self::where('username', '=', $desired_username)->exists())) {
$username = $desired_username;
} else { // someone already has the desired username
$username = $desired_username.'_'.$this->id;
}
$this->username = $username;
}
public function isRepairDirectoryNone()
{
return $this->repairdir_role == Role::REPAIR_DIRECTORY_NONE;
}
public function isRepairDirectorySuperAdmin()
{
return $this->repairdir_role == Role::REPAIR_DIRECTORY_SUPERADMIN;
}
public function isRepairDirectoryRegionalAdmin()
{
return $this->repairdir_role == Role::REPAIR_DIRECTORY_REGIONAL_ADMIN;
}
public function isRepairDirectoryEditor()
{
return $this->repairdir_role == Role::REPAIR_DIRECTORY_EDITOR;
}
public function hasRole($roleName)
{
$usersRole = $this->role()->first()->role;
// Root assumed to have all available roles.
if ($usersRole == 'Root') {
return true;
}
if ($usersRole == $roleName) {
return true;
}
return false;
}
public function hasPermission($permissionName)
{
$has_permission = UsersPermissions::join('permissions', 'permissions.idpermissions', '=', 'users_permissions.permission_id')
->where('users_permissions.user_id', $this->id)
->where('permissions.slug', $permissionName)
->first();
if (empty($has_permission)) {
return false;
}
return true;
}
public function getTalkProfileUrl()
{
return env('DISCOURSE_URL').'/u/'.$this->username;
}
// If just one of the networks that the group is a member of
// should push to Wordpress, then we should push.
public function changesShouldPushToZapier()
{
$network = Network::find($this->repair_network);
return $network->include_in_zapier;
}
public function isCoordinatorOf($network)
{
return $this->networks->contains($network);
}
public function networks(): BelongsToMany
{
return $this->belongsToMany(Network::class, 'user_network', 'user_id', 'network_id');
}
public function isCoordinatorForGroup($group)
{
foreach ($group->networks as $groupNetwork) {
foreach ($this->networks as $userNetwork) {
if ($groupNetwork->name == $userNetwork->name) {
return true;
}
}
}
return false;
}
public function groupsInChargeOf()
{
$groupsUserIsInChargeOf = Group::join('users_groups', 'groups.idgroups', '=', 'users_groups.group')
->where('user', $this->id)
->where('role', 3)
->get();
if ($this->hasRole('NetworkCoordinator')) {
foreach ($this->networks as $network) {
foreach ($network->groups as $group) {
$groupsUserIsInChargeOf->push($group);
}
}
} elseif ($this->hasRole('Administrator')) {
$groupsUserIsInChargeOf = Group::all();
}
return $groupsUserIsInChargeOf->unique();
}
public function ensureAPIToken()
{
// Generate an API token if we don't already have one.
$api_token = $this->api_token;
if (! $api_token) {
$api_token = \Illuminate\Support\Str::random(60);
$this->api_token = $api_token;
$this->save();
}
return $api_token;
}
/**
* Get the user's preferred locale. This is automatically used by email notifications.
*/
public function preferredLocale(): string
{
// TODO Use of preferredLocale should mean we don't have to explicitly pass the locale. But that isn't
// working. So at the moment we are passing a locale explicitly in the translations in the notifications
// to users (not admins).
return $this->language ?? config('app.locale', 'en');
}
/**
* Sync user from external service data
*/
public static function syncFromExternal(array $externalUserData): User
{
$user = self::where('external_user_id', $externalUserData['userid'])->first();
if ($user) {
// User exists, update without changing role to preserve manual changes
$user->update([
'name' => $externalUserData['username'],
'email' => $externalUserData['login'],
'external_username' => $externalUserData['unique_username'] ?? null,
'username' => $externalUserData['unique_username'] ?? null,
]);
return $user;
} else {
// User doesn't exist, create with mapped role from iFixit privilege level
$role = Role::RESTARTER; // Default role for external users
if (isset($externalUserData['greatest_privilege']) && $externalUserData['greatest_privilege'] === 'Admin') {
$role = Role::ADMINISTRATOR;
}
$user = self::create([
'name' => $externalUserData['username'],
'email' => $externalUserData['login'],
'external_user_id' => $externalUserData['userid'],
'external_username' => $externalUserData['unique_username'] ?? null,
'role' => $role,
'username' => $externalUserData['unique_username'] ?? null,
'password' => null, // External users don't have local passwords
'repairdir_role' => Role::REPAIR_DIRECTORY_NONE,
'calendar_hash' => Str::random(15)
]);
// Generate username if not provided
if (!$user->username) {
$user->generateAndSetUsername();
$user->save();
}
return $user;
}
}
/**
* Check if this user is an external user (iFixit, etc.)
*/
public function isExternalUser(): bool
{
return !empty($this->external_user_id);
}
/**
* Check if user can login with password (local users only)
*/
public function canLoginWithPassword(): bool
{
return !$this->isExternalUser() && !empty($this->password);
}
public static function userCanSeeEvent($user, $event) {
// We need to filter based on approved visibility:
// - where the group is approved, this event is visible
// - where the group is not approved, this event is visible to network coordinators or group hosts.
$amHost = $user && $user->hasRole('Host');
$admin = $user && $user->hasRole('Administrator');
$group = Group::find($event->group);
if (($event->approved && $group->approved) ||
$admin ||
($user && $user->isCoordinatorForGroup($group)) ||
($amHost && $user && Fixometer::userIsHostOfGroup($group->idgroups, $user->id))) {
return true;
}
return false;
}
}