-
-
Notifications
You must be signed in to change notification settings - Fork 4k
Expand file tree
/
Copy pathUser.php
More file actions
1689 lines (1501 loc) · 52.4 KB
/
Copy pathUser.php
File metadata and controls
1689 lines (1501 loc) · 52.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
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
namespace App\Models;
use App\Http\Traits\UniqueUndeletedTrait;
use App\Models\Traits\CompanyableTrait;
use App\Models\Traits\HasUploads;
use App\Models\Traits\Loggable;
use App\Models\Traits\Searchable;
use App\Presenters\Presentable;
use App\Presenters\UserPresenter;
use App\Rules\CssColor;
use Illuminate\Auth\Authenticatable;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
use Illuminate\Contracts\Translation\HasLocalePreference;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\Relation;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Foundation\Auth\Access\Authorizable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Str;
use Laravel\Passport\HasApiTokens;
use Watson\Validating\ValidatingTrait;
class User extends SnipeModel implements AuthenticatableContract, AuthorizableContract, CanResetPasswordContract, HasLocalePreference
{
use CompanyableTrait;
use HasFactory;
use HasUploads;
protected $presenter = UserPresenter::class;
use Authenticatable, Authorizable, CanResetPassword, HasApiTokens;
use Loggable, SoftDeletes, ValidatingTrait;
use Notifiable;
use Presentable;
use Searchable;
use UniqueUndeletedTrait;
protected $hidden = [
'password',
'remember_token',
'permissions',
'reset_password_code',
'persist_code',
'two_factor_secret',
'activation_code',
];
protected $table = 'users';
protected $injectUniqueIdentifier = true;
/**
* Transient (non-persisted) ID of the Actionlog entry written by UserObserver::updating()
* during the current request. syncCompaniesWithLogging() merges company changes into this
* entry instead of creating a separate one, so a single edit session produces one log row.
*/
public ?int $currentUpdateLogId = null;
protected $fillable = [
'activated',
'address',
'city',
'company_id',
'country',
'department_id',
'email',
'employee_num',
'first_name',
'jobtitle',
'last_name',
'display_name',
'ldap_import',
'locale',
'location_id',
'manager_id',
'password',
'phone',
'mobile',
'notes',
'state',
'username',
'zip',
'remote',
'start_date',
'end_date',
'scim_externalid',
'avatar',
'gravatar',
'vip',
'autoassign_licenses',
'website',
];
protected $casts = [
'manager_id' => 'integer',
'location_id' => 'integer',
'company_id' => 'integer',
'created_at' => 'datetime',
'updated_at' => 'datetime',
'deleted_at' => 'datetime',
];
/**
* Model validation rules
*
* @var array
*/
protected $rules = [
'first_name' => 'required|string|max:191',
'last_name' => 'nullable|string|max:191',
'display_name' => 'nullable|string|max:191',
'username' => 'required|string|min:1|unique_undeleted|max:191',
'email' => 'email|nullable|max:191',
'password' => 'required|min:8',
'locale' => 'max:10|nullable',
'website' => 'url|nullable|max:191',
'manager_id' => 'nullable|exists:users,id|cant_manage_self',
'location_id' => 'exists:locations,id|nullable',
'start_date' => 'nullable|date_format:Y-m-d',
'end_date' => 'nullable|date_format:Y-m-d|after_or_equal:start_date',
'autoassign_licenses' => 'boolean',
'address' => 'nullable|string|max:191',
'city' => 'nullable|string|max:191',
'state' => 'nullable|string|max:191',
'country' => 'min:2|max:191|nullable',
'zip' => 'max:10|nullable',
'vip' => 'boolean',
'remote' => 'boolean',
'activated' => 'boolean',
];
/**
* The attributes that should be included when searching the model.
*
* @var array
*/
protected $searchableAttributes = [
'address',
'city',
'country',
'display_name',
'email',
'employee_num',
'first_name',
'jobtitle',
'last_name',
'locale',
'mobile',
'notes',
'phone',
'state',
'username',
'website',
'zip',
];
/**
* The relations and their attributes that should be included when searching the model.
*
* @var array
*/
protected $searchableRelations = [
'userloc' => ['name', 'address', 'address2', 'city', 'state', 'zip'],
'department' => ['name'],
'groups' => ['name'],
'companies' => ['name'],
'manager' => ['first_name', 'last_name', 'username', 'display_name'],
'adminuser' => ['first_name', 'last_name', 'display_name'],
];
protected $searchableCounts = [
'accessories_count',
'assets_count',
'licenses_count',
'consumables_count',
'accessories_count',
'manages_users_count',
'manages_locations_count',
];
/**
* Virtual column aliases that map a single filter key to a set of real columns
* searched via CONCAT (SQL) so that, for example, filtering by "name" searches
* across both first_name and last_name together.
*
* Because "name" is not a real column on the users table we cannot add it to
* $searchableAttributes; this map bridges that gap for structured filter queries.
*
* @var array<string, list<string>>
*/
protected $searchableVirtualColumns = [
'name' => ['first_name', 'last_name'],
];
/**
* Maps filter/API keys to the actual Eloquent relation names used in
* $searchableRelations. The User model uses "userloc" as its location
* relation name (to avoid a collision with the framework's own "location"
* magic), but every consumer — UI and API alike — sends the key "location".
*
* @var array<string, string>
*/
protected $searchableRelationAliases = [
'location' => 'userloc',
];
/**
* Narrow structured-filter relation columns for specific UI/API filter keys.
*
* The advanced-search "location" field represents the location name, so
* structured filters should target only userloc.name (not address/city/etc).
*
* @var array<string, list<string>>
*/
protected $searchableRelationFilterColumns = [
'location' => ['name'],
];
/**
* This sets the name property on the user. It's not a real field in the database
* (since we use first_name and last_name), but the Laravel mailable method
* uses this to determine the name of the user to send emails to.
*
* We only have to do this on the User model and no other models because other
* first-class objects have a name field.
*
* @return void
*/
public $name;
protected static function boot()
{
parent::boot();
static::retrieved(
function ($user) {
$user->name = $user->getFullNameAttribute();
}
);
}
protected static function booted(): void
{
// Bridge for factories/seeders that still set company_id directly: ensure
// that company appears in the pivot so FMCS scoping works correctly.
// Application code (controllers, importers) writes only to the pivot.
static::created(function (User $user) {
if ($user->company_id) {
$user->companies()->syncWithoutDetaching([$user->company_id]);
}
});
static::forceDeleted(function (User $user) {
CheckoutRequest::where(['user_id' => $user->id])->forceDelete();
$user->purgeAssociatedPassportTokens();
});
static::softDeleted(function (User $user) {
CheckoutRequest::where(['user_id' => $user->id])->delete();
$user->revokeAssociatedPassportTokens();
});
}
/**
* Revoke all Passport access/refresh tokens associated with this user.
*/
private function revokeAssociatedPassportTokens(): void
{
$accessTokenIds = DB::table('oauth_access_tokens')
->where('user_id', $this->id)
->pluck('id');
if ($accessTokenIds->isEmpty()) {
return;
}
DB::table('oauth_access_tokens')
->whereIn('id', $accessTokenIds)
->update(['revoked' => true]);
DB::table('oauth_refresh_tokens')
->whereIn('access_token_id', $accessTokenIds)
->update(['revoked' => true]);
}
/**
* Hard-delete all Passport access/refresh tokens associated with this user.
*/
private function purgeAssociatedPassportTokens(): void
{
$accessTokenIds = DB::table('oauth_access_tokens')
->where('user_id', $this->id)
->pluck('id');
if ($accessTokenIds->isNotEmpty()) {
DB::table('oauth_refresh_tokens')
->whereIn('access_token_id', $accessTokenIds)
->delete();
}
DB::table('oauth_access_tokens')
->where('user_id', $this->id)
->delete();
}
/**
* This overrides the SnipeModel displayName accessor to return the full name if display_name is not set
*
* @see SnipeModel::displayName()
*/
protected function displayName(): Attribute
{
return Attribute::make(
get: fn (mixed $value) => ($value !== null && $value !== '') ? $value : $this->getFullNameAttribute(),
);
}
public function isAvatarExternal(): bool
{
// Check if it's a google avatar or some external avatar
if (Str::startsWith($this->avatar, ['http://', 'https://'])) {
return true;
}
return false;
}
public function hasIndividualPermissions()
{
$permissions = [];
if (is_object($this->permissions)) {
$permissions = json_decode(json_encode($this->permissions), true);
}
if (is_string($this->permissions)) {
$permissions = json_decode($this->permissions, true);
}
if (($permissions) && (is_array($permissions))) {
foreach ($permissions as $permission) {
if ($permission != 0) {
return true;
}
}
}
return false;
}
/**
* Build a list of effective user permissions grouped by permission section.
*
* Includes explicit denials from user or group permissions so the UI can
* show both allowed and denied entries.
*
* This is kind of duplicative from the other permission-checking methods, but it allows us to build a
* list of permissions for display purposes without having to do a lot of super-confusing and
* redundant checks in the UI layer.
*
* This will likely go away once we refactor the permissions to be in a database table instead of the
* stupiud config file.
*/
public function getEffectivePermissionsBySection(): array
{
$displayablePermissions = collect(config('permissions'))
->map(static fn (array $permissions): array => array_values(array_filter($permissions, static fn (array $permission): bool => ($permission['display'] ?? false) === true)))
->all();
$configuredPermissions = collect($displayablePermissions)
->flatMap(static function (array $permissions, string $section) {
return collect($permissions)->map(static function (array $permission) use ($section): array {
return [
'section' => $section,
'permission' => $permission['permission'],
];
});
})
->unique('permission')
->values();
$directPermissions = $this->decodePermissions();
$directPermissions = is_array($directPermissions) ? $directPermissions : [];
$groupGrantsByPermission = [];
$groupDenialsByPermission = [];
foreach ($this->groups as $group) {
$groupPermissions = $group->decodePermissions();
if (! is_array($groupPermissions)) {
continue;
}
foreach ($groupPermissions as $permissionKey => $permissionValue) {
if ((int) $permissionValue === 1) {
$groupGrantsByPermission[$permissionKey][] = $group->name;
} elseif ((int) $permissionValue === -1) {
$groupDenialsByPermission[$permissionKey][] = $group->name;
}
}
}
$effectiveBySection = [];
foreach ($configuredPermissions as $permissionConfig) {
$permissionKey = $permissionConfig['permission'];
$directPermissionValue = (int) ($directPermissions[$permissionKey] ?? 0);
$isAllowed = $this->hasAccess($permissionKey);
$isDenied = ($directPermissionValue === -1) || ((count($groupDenialsByPermission[$permissionKey] ?? []) > 0) && ! $isAllowed);
if (! $isAllowed && ! $isDenied) {
continue;
}
$status = $isDenied ? 'denied' : 'allowed';
$source = 'group';
$sourceGroups = $isDenied
? ($groupDenialsByPermission[$permissionKey] ?? [])
: ($groupGrantsByPermission[$permissionKey] ?? []);
if ($isDenied && $directPermissionValue === -1) {
$source = 'individual';
$sourceGroups = [];
} elseif ($this->isSuperUser()) {
$source = 'superuser';
$sourceGroups = [];
} elseif (! $isDenied && $directPermissionValue === 1) {
$source = 'individual';
$sourceGroups = [];
}
$effectiveBySection[$permissionConfig['section']][] = [
'permission' => $permissionKey,
'status' => $status,
'source' => $source,
'groups' => array_values(array_unique($sourceGroups)),
'source_label' => $this->buildPermissionSourceLabel(
status: $status,
source: $source,
sourceGroups: $sourceGroups
),
];
}
return $effectiveBySection;
}
/**
* Build a compact source label for a permission entry.
*/
private function buildPermissionSourceLabel(string $status, string $source, array $sourceGroups = []): string
{
$statusLabel = $status === 'denied' ? 'Denied' : 'Allowed';
$sourceLabel = match ($source) {
'individual' => 'Individual',
'superuser' => 'Superuser',
default => 'Group',
};
if ($sourceGroups === []) {
return $statusLabel.' ('.$sourceLabel.')';
}
return $statusLabel.' ('.$sourceLabel.'): '.implode(', ', array_values(array_unique($sourceGroups)));
}
/**
* Internally check the user permission for the given section
*
* @return bool
*/
protected function checkPermissionSection($section)
{
$user_groups = $this->groups;
if (($this->permissions == '') && (count($user_groups) == 0)) {
return false;
}
$user_permissions = $this->permissions;
if (is_object($this->permissions)) {
$user_permissions = json_decode(json_encode($this->permissions), true);
}
if (is_string($this->permissions)) {
$user_permissions = json_decode($this->permissions, true);
}
$is_user_section_permissions_set = ($user_permissions != '') && array_key_exists($section, $user_permissions);
// If the user is explicitly granted, return true
if ($is_user_section_permissions_set && ($user_permissions[$section] == '1')) {
return true;
}
// If the user is explicitly denied, return false
if ($is_user_section_permissions_set && ($user_permissions[$section] == '-1')) {
return false;
}
// Loop through the groups to see if any of them grant this permission
foreach ($user_groups as $user_group) {
$group_permissions = (array) json_decode($user_group->permissions, true);
if (((array_key_exists($section, $group_permissions)) && ($group_permissions[$section] == '1'))) {
return true;
}
}
return false;
}
/**
* Check user permissions
*
* Parses the user and group permission masks to see if the user
* is authorized to do the thing
*
* @author A. Gianotto <snipe@snipe.net>
*
* @since [v1.0]
*
* @return bool
*/
public function hasAccess($section)
{
if ($this->isSuperUser()) {
return true;
}
return $this->checkPermissionSection($section);
}
/**
* Checks if the user is a SuperUser
*
* @author A. Gianotto <snipe@snipe.net>
*
* @since [v1.0]
*
* @return bool
*/
public function isSuperUser()
{
return $this->checkPermissionSection('superuser');
}
/**
* Checks if the user is an admin
*
* @author A. Gianotto <snipe@snipe.net>
*
* @since [v8.1.18]
*
* @return bool
*/
public function isAdmin()
{
return $this->checkPermissionSection('admin');
}
public function isMultiCompany()
{
return $this->checkPermissionSection('multicompany');
}
/**
* Checks if the user can edit their own profile
*
* @author A. Gianotto <snipe@snipe.net>
*
* @since [v6.3.4]
*/
public function canEditProfile(): bool
{
$setting = Setting::getSettings();
if ($setting->profile_edit == 1) {
return true;
}
return false;
}
/**
* Checks if the user is deletable
*
* @author A. Gianotto <snipe@snipe.net>
*
* @since [v6.3.4]
*
* @return bool
*/
public function isDeletable()
{
return Gate::allows('delete', $this)
&& (($this->assets_count ?? $this->assets()->count()) === 0)
&& (($this->accessories_count ?? $this->accessories()->count()) === 0)
&& (($this->licenses_count ?? $this->licenses()->count()) === 0)
&& (($this->consumables_count ?? $this->consumables()->count()) === 0)
&& (($this->manages_users_count ?? $this->managesUsers()->count()) === 0)
&& (($this->manages_locations_count ?? $this->managedLocations()->count()) === 0)
&& ($this->deleted_at == '');
}
/**
* Establishes the user -> company relationship
*
* @author A. Gianotto <snipe@snipe.net>
*
* @since [v2.0]
*
* @return Relation
*/
public function company()
{
return $this->belongsTo(Company::class, 'company_id');
}
public function companies(): BelongsToMany
{
return $this->belongsToMany(Company::class, 'company_user');
}
/**
* Returns whether an FMCS company check should allow this user to receive
* an asset that belongs to the given company.
*
* - If the user has no company associations at all: returns true (no restriction).
* - If the user has associations: returns true only when $companyId is among them.
*/
public function canReceiveFromCompany(int $companyId): bool
{
// Items with no company association are unrestricted — anyone can receive them.
if (! $companyId) {
return true;
}
// Query the pivot directly to avoid the Company model's FMCS global scope,
// which would restrict results to the current actor's visible companies.
$userCompanyIds = DB::table('company_user')
->where('user_id', $this->id)
->pluck('company_id');
if ($userCompanyIds->isEmpty()) {
return (bool) Setting::getSettings()->null_company_is_floater;
}
return $userCompanyIds->contains($companyId);
}
/**
* Returns all companies this user belongs to — union of the primary company_id
* column and the many-to-many pivot — as a deduplicated Collection.
* Used to scope FMCS dropdowns to companies the user is allowed to work with.
*/
public function allCompanies(): Collection
{
return $this->companies->unique('id')->values();
}
/**
* Sync company pivot membership and log the change if the set of companies changed.
*
* When called after $user->save() in the same request, UserObserver::updating() will
* have already written an Actionlog row and stored its ID in $this->currentUpdateLogId.
* In that case we merge the company change into that existing entry so that a single
* edit session (field changes + company changes) produces one log row, not two.
*/
public function syncCompaniesWithLogging(array $companyIds): void
{
$oldIds = $this->companies()->orderBy('companies.id')->pluck('companies.id')->toArray();
$this->companies()->sync($companyIds);
$newIds = $this->companies()->orderBy('companies.id')->pluck('companies.id')->toArray();
if ($oldIds === $newIds) {
return;
}
$companyChange = ['companies' => ['old' => $oldIds, 'new' => $newIds]];
if ($this->currentUpdateLogId && ($existing = Actionlog::find($this->currentUpdateLogId))) {
$meta = json_decode($existing->log_meta ?? '{}', true) ?: [];
$existing->log_meta = json_encode(array_merge($meta, $companyChange));
$existing->save();
$this->currentUpdateLogId = null;
return;
}
$logAction = new Actionlog;
$logAction->item_type = static::class;
$logAction->item_id = $this->id;
$logAction->target_type = static::class;
$logAction->target_id = $this->id;
$logAction->created_at = date('Y-m-d H:i:s');
$logAction->created_by = auth()->id();
$logAction->log_meta = json_encode($companyChange);
$logAction->logaction('update');
}
/**
* Establishes the user -> department relationship
*
* @author A. Gianotto <snipe@snipe.net>
*
* @since [v4.0]
*
* @return Relation
*/
public function department()
{
return $this->belongsTo(Department::class, 'department_id');
}
/**
* Checks activated status
*
* @author A. Gianotto <snipe@snipe.net>
*
* @since [v1.0]
*
* @return bool
*/
public function isActivated()
{
return $this->activated == 1;
}
/**
* Returns the full name attribute
*
* @author A. Gianotto <snipe@snipe.net>
*
* @since [v2.0]
*
* @return string
*/
public function getFullNameAttribute()
{
$setting = Setting::getSettings();
if ($setting?->name_display_format == 'last_first') {
return ($this->last_name) ? $this->last_name.' '.$this->first_name : $this->first_name;
}
return $this->last_name ? $this->first_name.' '.$this->last_name : $this->first_name;
}
protected function linkLightColor(): Attribute
{
return Attribute::make(
get: function (?string $value) {
$fallback = '#296282';
if ($value) {
return CssColor::sanitize($value, $fallback);
}
if (Setting::getSettings()) {
return CssColor::sanitize(Setting::getSettings()->link_light_color, $fallback);
}
return CssColor::sanitize($value, $fallback);
},
);
}
protected function linkDarkColor(): Attribute
{
return Attribute::make(
get: function (?string $value) {
$fallback = '#5fa4cc';
if ($value) {
return CssColor::sanitize($value, $fallback);
}
if (Setting::getSettings()) {
return CssColor::sanitize(Setting::getSettings()->link_dark_color, $fallback);
}
return CssColor::sanitize($value, $fallback);
},
);
}
protected function navLinkColor(): Attribute
{
return Attribute::make(
get: function (?string $value) {
$fallback = '#ffffff';
if ($value) {
return CssColor::sanitize($value, $fallback);
}
if (Setting::getSettings()) {
return CssColor::sanitize(Setting::getSettings()->nav_link_color, $fallback);
}
return CssColor::sanitize($value, $fallback);
},
);
}
/**
* Establishes the user -> assets relationship
*
* @author A. Gianotto <snipe@snipe.net>
*
* @since [v1.0]
*
* @return Relation
*/
public function assets()
{
return $this->morphMany(Asset::class, 'assigned', 'assigned_type', 'assigned_to')->withTrashed()->orderBy('id');
}
/**
* Establishes the user -> maintenances relationship
*
* This would only be used to return maintenances that this user
* created.
*
* @author A. Gianotto <snipe@snipe.net>
*
* @since [v4.0]
*
* @return Relation
*/
public function maintenances()
{
return $this->hasMany(Maintenance::class, 'user_id')->withTrashed();
}
/**
* Establishes the user -> accessories relationship
*
* @author A. Gianotto <snipe@snipe.net>
*
* @since [v2.0]
*
* @return Relation
*/
public function accessories()
{
return $this->belongsToMany(Accessory::class, 'accessories_checkout', 'assigned_to', 'accessory_id')
->where('assigned_type', '=', 'App\Models\User')
->withPivot('id', 'created_at', 'note')->withTrashed()->orderBy('accessory_id');
}
/**
* Establishes the user -> consumables relationship
*
* @author A. Gianotto <snipe@snipe.net>
*
* @since [v3.0]
*
* @return Relation
*/
public function consumables()
{
return $this->belongsToMany(Consumable::class, 'consumables_users', 'assigned_to', 'consumable_id')->withPivot('id', 'created_at', 'note')->withTrashed();
}
/**
* Establishes the user -> license seats relationship
*
* @author A. Gianotto <snipe@snipe.net>
*
* @since [v1.0]
*
* @return Relation
*/
public function licenses()
{
return $this->belongsToMany(License::class, 'license_seats', 'assigned_to', 'license_id')->withPivot('id', 'created_at', 'updated_at');
}
public function directLicenses()
{
return $this->belongsToMany(License::class, 'license_seats', 'assigned_to', 'license_id')->withPivot('id', 'created_at', 'updated_at')->wherePivotNull('asset_id')->withTrashed();
}
/**
* Establishes the user -> reportTemplates relationship
*/
public function reportTemplates(): HasMany
{
return $this->hasMany(ReportTemplate::class, 'created_by');
}
public function getImageUrl($path = null)
{
return $this->present()->gravatar();
}
/**
* Establishes a count of all items assigned
*
* @author J. Vinsmoke
*
* @since [v6.1]
*
* @return Relation
*/
public function allAssignedCount()
{
$assetsCount = $this->assets()->count();
$licensesCount = $this->licenses()->count();
$accessoriesCount = $this->accessories()->count();
$consumablesCount = $this->consumables()->count();
$totalCount = $assetsCount + $licensesCount + $accessoriesCount + $consumablesCount;
return (int) $totalCount;
}
/**
* Establishes the user -> actionlogs relationship
*
* @author A. Gianotto <snipe@snipe.net>
*
* @since [v1.0]
*
* @return Relation
*/
public function userlog()
{
return $this->hasMany(Actionlog::class, 'target_id')->where('target_type', '=', self::class)->orderBy('created_at', 'DESC')->withTrashed();
}
/**
* Establishes the user -> location relationship
*
* Get the asset's location based on the assigned user
*
* @todo - this should be removed once we're sure we've switched it to location()
*
* @author A. Gianotto <snipe@snipe.net>
*
* @since [v4.0]
*
* @return Relation
*/
public function userloc()
{
return $this->belongsTo(Location::class, 'location_id')->withTrashed();
}
/**
* Establishes the user -> location relationship
*
* @author A. Gianotto <snipe@snipe.net>
*
* @since [v3.0]
*
* @return Relation
*/
public function location()
{
return $this->belongsTo(Location::class, 'location_id')->withTrashed();
}
/**
* Establishes the user -> manager relationship
*
* @author A. Gianotto <snipe@snipe.net>
*
* @since [v4.0]
*
* @return Relation
*/
public function manager()
{
return $this->belongsTo(self::class, 'manager_id')->withTrashed();
}
/**
* Establishes the user -> managed users relationship
*
* @author A. Gianotto <snipe@snipe.net>
*
* @since [v6.4.1]
*
* @return Relation
*/
public function managesUsers()
{