Passed
Push — master ( bc850c...5e462b )
by Angel Fernando Quiroz
13:45 queued 03:55
created

User::setAuthSource()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
c 0
b 0
f 0
nc 1
nop 1
dl 0
loc 5
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
/* For licensing terms, see /license.txt */
6
7
namespace Chamilo\CoreBundle\Entity;
8
9
use ApiPlatform\Doctrine\Orm\Filter\BooleanFilter;
10
use ApiPlatform\Doctrine\Orm\Filter\SearchFilter;
11
use ApiPlatform\Metadata\ApiFilter;
12
use ApiPlatform\Metadata\ApiProperty;
13
use ApiPlatform\Metadata\ApiResource;
14
use ApiPlatform\Metadata\Delete;
15
use ApiPlatform\Metadata\Get;
16
use ApiPlatform\Metadata\GetCollection;
17
use ApiPlatform\Metadata\Post;
18
use ApiPlatform\Metadata\Put;
19
use Chamilo\CoreBundle\Controller\Api\CreateUserOnAccessUrlAction;
20
use Chamilo\CoreBundle\Controller\Api\UserSkillsController;
21
use Chamilo\CoreBundle\Dto\CreateUserOnAccessUrlInput;
22
use Chamilo\CoreBundle\Entity\Listener\UserListener;
23
use Chamilo\CoreBundle\Filter\PartialSearchOrFilter;
24
use Chamilo\CoreBundle\Repository\Node\UserRepository;
25
use Chamilo\CoreBundle\Traits\UserCreatorTrait;
26
use Chamilo\CourseBundle\Entity\CGroupRelTutor;
27
use Chamilo\CourseBundle\Entity\CGroupRelUser;
28
use Chamilo\CourseBundle\Entity\CSurveyInvitation;
29
use DateTime;
30
use DateTimeInterface;
31
use Doctrine\Common\Collections\ArrayCollection;
32
use Doctrine\Common\Collections\Collection;
33
use Doctrine\Common\Collections\Criteria;
34
use Doctrine\Common\Collections\ReadableCollection;
35
use Doctrine\ORM\Mapping as ORM;
36
use Gedmo\Timestampable\Traits\TimestampableEntity;
37
use Stringable;
38
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
39
use Symfony\Component\Security\Core\User\EquatableInterface;
40
use Symfony\Component\Security\Core\User\LegacyPasswordAuthenticatedUserInterface;
41
use Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface;
42
use Symfony\Component\Security\Core\User\UserInterface;
43
use Symfony\Component\Serializer\Annotation\Groups;
44
use Symfony\Component\Uid\Uuid;
45
use Symfony\Component\Validator\Constraints as Assert;
46
use Symfony\Component\Validator\Mapping\ClassMetadata;
47
use UserManager;
48
49
/**
50
 * EquatableInterface is needed to check if the user needs to be refreshed.
51
 */
52
#[ApiResource(
53
    types: ['http://schema.org/Person'],
54
    operations: [
55
        new Get(security: "is_granted('VIEW', object)"),
56
        new Put(security: "is_granted('EDIT', object)"),
57
        new Delete(security: "is_granted('DELETE', object)"),
58
        new GetCollection(security: "is_granted('ROLE_USER')"),
59
        new Post(security: "is_granted('ROLE_ADMIN')"),
60
        new GetCollection(
61
            uriTemplate: '/users/{id}/skills',
62
            controller: UserSkillsController::class,
63
            normalizationContext: ['groups' => ['user_skills:read']],
64
            name: 'get_user_skills'
65
        ),
66
        new Post(
67
            uriTemplate: '/advanced/create-user-on-access-url',
68
            controller: CreateUserOnAccessUrlAction::class,
69
            denormalizationContext: ['groups' => ['write']],
70
            security: "is_granted('ROLE_ADMIN')",
71
            input: CreateUserOnAccessUrlInput::class,
72
            output: User::class,
73
            deserialize: true,
74
            name: 'create_user_on_access_url'
75
        ),
76
    ],
77
    normalizationContext: ['groups' => ['user:read']],
78
    denormalizationContext: ['groups' => ['user:write']],
79
    security: 'is_granted("ROLE_USER")'
80
)]
81
#[ORM\Table(name: 'user')]
82
#[ORM\Index(columns: ['status'], name: 'status')]
83
#[UniqueEntity('username')]
84
#[ORM\Entity(repositoryClass: UserRepository::class)]
85
#[ORM\EntityListeners([UserListener::class])]
86
#[ApiFilter(
87
    filterClass: SearchFilter::class,
88
    properties: [
89
        'username' => 'partial',
90
        'firstname' => 'partial',
91
        'lastname' => 'partial',
92
    ]
93
)]
94
#[ApiFilter(PartialSearchOrFilter::class, properties: ['username', 'firstname', 'lastname'])]
95
#[ApiFilter(filterClass: BooleanFilter::class, properties: ['isActive'])]
96
class User implements UserInterface, EquatableInterface, ResourceInterface, ResourceIllustrationInterface, PasswordAuthenticatedUserInterface, LegacyPasswordAuthenticatedUserInterface, ExtraFieldItemInterface, Stringable
97
{
98
    use TimestampableEntity;
99
    use UserCreatorTrait;
100
101
    public const USERNAME_MAX_LENGTH = 100;
102
    public const ROLE_DEFAULT = 'ROLE_USER';
103
    public const ANONYMOUS = 6;
104
105
    /**
106
     * Global status for the fallback user.
107
     * This special status is used for a system user that acts as a placeholder
108
     * or fallback for content ownership when regular users are deleted.
109
     * This ensures data integrity and prevents orphaned content within the system.
110
     */
111
    public const ROLE_FALLBACK = 99;
112
113
    /*public const COURSE_MANAGER = 1;
114
      public const TEACHER = 1;
115
      public const SESSION_ADMIN = 3;
116
      public const DRH = 4;
117
      public const STUDENT = 5;
118
      public const ANONYMOUS = 6;*/
119
120
    // User active field constants
121
    public const ACTIVE = 1;
122
    public const INACTIVE = 0;
123
    public const INACTIVE_AUTOMATIC = -1;
124
    public const SOFT_DELETED = -2;
125
126
    #[Groups(['user_json:read'])]
127
    #[ORM\OneToOne(targetEntity: ResourceNode::class, cascade: ['persist'])]
128
    #[ORM\JoinColumn(name: 'resource_node_id', onDelete: 'CASCADE')]
129
    public ?ResourceNode $resourceNode = null;
130
131
    /**
132
     * Resource illustration URL - Property set by ResourceNormalizer.php.
133
     */
134
    #[ApiProperty(iris: ['http://schema.org/contentUrl'])]
135
    #[Groups([
136
        'user_export',
137
        'user:read',
138
        'resource_node:read',
139
        'document:read',
140
        'media_object_read',
141
        'course:read',
142
        'course_rel_user:read',
143
        'user_json:read',
144
        'message:read',
145
        'user_rel_user:read',
146
        'social_post:read',
147
        'user_subscriptions:sessions',
148
    ])]
149
    public ?string $illustrationUrl = null;
150
151
    #[Groups([
152
        'user:read',
153
        'course:read',
154
        'resource_node:read',
155
        'user_json:read',
156
        'message:read',
157
        'user_rel_user:read',
158
        'session:item:read',
159
    ])]
160
    #[ORM\Column(name: 'id', type: 'integer')]
161
    #[ORM\Id]
162
    #[ORM\GeneratedValue]
163
    protected ?int $id = null;
164
165
    #[Assert\NotBlank]
166
    #[Groups([
167
        'user_export',
168
        'user:read',
169
        'user:write',
170
        'course:read',
171
        'course_rel_user:read',
172
        'resource_node:read',
173
        'user_json:read',
174
        'message:read',
175
        'page:read',
176
        'user_rel_user:read',
177
        'social_post:read',
178
        'track_e_exercise:read',
179
        'user_subscriptions:sessions',
180
    ])]
181
    #[ORM\Column(name: 'username', type: 'string', length: 100, unique: true)]
182
    protected string $username;
183
184
    #[ORM\Column(name: 'api_token', type: 'string', unique: true, nullable: true)]
185
    protected ?string $apiToken = null;
186
187
    #[ApiProperty(iris: ['http://schema.org/name'])]
188
    #[Assert\NotBlank]
189
    #[Groups(['user:read', 'user:write', 'resource_node:read', 'user_json:read', 'track_e_exercise:read', 'user_rel_user:read', 'user_subscriptions:sessions'])]
190
    #[ORM\Column(name: 'firstname', type: 'string', length: 64, nullable: true)]
191
    protected ?string $firstname = null;
192
193
    #[Groups(['user:read', 'user:write', 'resource_node:read', 'user_json:read', 'track_e_exercise:read', 'user_rel_user:read', 'user_subscriptions:sessions'])]
194
    #[ORM\Column(name: 'lastname', type: 'string', length: 64, nullable: true)]
195
    protected ?string $lastname = null;
196
197
    #[Groups(['user:read', 'user:write'])]
198
    #[ORM\Column(name: 'website', type: 'string', length: 255, nullable: true)]
199
    protected ?string $website;
200
201
    #[Groups(['user:read', 'user:write'])]
202
    #[ORM\Column(name: 'biography', type: 'text', nullable: true)]
203
    protected ?string $biography;
204
205
    #[Groups(['user:read', 'user:write', 'user_json:read'])]
206
    #[ORM\Column(name: 'locale', type: 'string', length: 10)]
207
    protected string $locale;
208
209
    #[Groups(['user:write'])]
210
    protected ?string $plainPassword = null;
211
212
    #[ORM\Column(name: 'password', type: 'string', length: 255)]
213
    protected string $password;
214
215
    #[ORM\Column(name: 'username_canonical', type: 'string', length: 180)]
216
    protected string $usernameCanonical;
217
218
    #[Groups(['user:read', 'user:write', 'user_json:read'])]
219
    #[ORM\Column(name: 'timezone', type: 'string', length: 64)]
220
    protected string $timezone;
221
222
    #[ORM\Column(name: 'email_canonical', type: 'string', length: 100)]
223
    protected string $emailCanonical;
224
225
    #[Groups(['user:read', 'user:write', 'user_json:read'])]
226
    #[Assert\NotBlank]
227
    #[Assert\Email]
228
    #[ORM\Column(name: 'email', type: 'string', length: 100)]
229
    protected string $email;
230
231
    #[ORM\Column(name: 'locked', type: 'boolean')]
232
    protected bool $locked;
233
234
    #[Groups(['user:read', 'user:write'])]
235
    #[ORM\Column(name: 'expired', type: 'boolean')]
236
    protected bool $expired;
237
238
    #[ORM\Column(name: 'credentials_expired', type: 'boolean')]
239
    protected bool $credentialsExpired;
240
241
    #[ORM\Column(name: 'credentials_expire_at', type: 'datetime', nullable: true)]
242
    protected ?DateTime $credentialsExpireAt;
243
244
    #[ORM\Column(name: 'date_of_birth', type: 'datetime', nullable: true)]
245
    protected ?DateTime $dateOfBirth;
246
247
    #[Groups(['user:read', 'user:write'])]
248
    #[ORM\Column(name: 'expires_at', type: 'datetime', nullable: true)]
249
    protected ?DateTime $expiresAt;
250
251
    #[Groups(['user:read', 'user:write'])]
252
    #[ORM\Column(name: 'phone', type: 'string', length: 64, nullable: true)]
253
    protected ?string $phone = null;
254
255
    #[Groups(['user:read', 'user:write'])]
256
    #[ORM\Column(name: 'address', type: 'string', length: 250, nullable: true)]
257
    protected ?string $address = null;
258
259
    #[ORM\Column(type: 'string', length: 255)]
260
    protected string $salt;
261
262
    #[ORM\Column(name: 'gender', type: 'string', length: 1, nullable: true)]
263
    protected ?string $gender = null;
264
265
    #[Groups(['user:read'])]
266
    #[ORM\Column(name: 'last_login', type: 'datetime', nullable: true)]
267
    protected ?DateTime $lastLogin = null;
268
269
    /**
270
     * Random string sent to the user email address in order to verify it.
271
     */
272
    #[ORM\Column(name: 'confirmation_token', type: 'string', length: 255, nullable: true)]
273
    protected ?string $confirmationToken = null;
274
275
    #[ORM\Column(name: 'password_requested_at', type: 'datetime', nullable: true)]
276
    protected ?DateTime $passwordRequestedAt;
277
278
    /**
279
     * @var Collection<int, CourseRelUser>
280
     */
281
    #[ORM\OneToMany(mappedBy: 'user', targetEntity: CourseRelUser::class, cascade: ['persist', 'remove'], orphanRemoval: true)]
282
    protected Collection $courses;
283
284
    /**
285
     * @var Collection<int, UsergroupRelUser>
286
     */
287
    #[ORM\OneToMany(mappedBy: 'user', targetEntity: UsergroupRelUser::class)]
288
    protected Collection $classes;
289
290
    /**
291
     * ORM\OneToMany(targetEntity="Chamilo\CourseBundle\Entity\CDropboxPost", mappedBy="user").
292
     */
293
    protected Collection $dropBoxReceivedFiles;
294
295
    /**
296
     * ORM\OneToMany(targetEntity="Chamilo\CourseBundle\Entity\CDropboxFile", mappedBy="userSent").
297
     */
298
    protected Collection $dropBoxSentFiles;
299
300
    /**
301
     * An array of roles. Example: ROLE_USER, ROLE_TEACHER, ROLE_ADMIN.
302
     */
303
    #[Groups(['user:read', 'user:write', 'user_json:read'])]
304
    #[ORM\Column(type: 'array')]
305
    protected array $roles = [];
306
307
    #[ORM\Column(name: 'profile_completed', type: 'boolean', nullable: true)]
308
    protected ?bool $profileCompleted = null;
309
310
    /**
311
     * ORM\OneToMany(targetEntity="Chamilo\CoreBundle\Entity\JuryMembers", mappedBy="user").
312
     */
313
    // protected $jurySubscriptions;
314
315
    /**
316
     * @var Collection<int, Group>
317
     */
318
    #[ORM\JoinTable(name: 'fos_user_user_group')]
319
    #[ORM\JoinColumn(name: 'user_id', referencedColumnName: 'id', onDelete: 'cascade')]
320
    #[ORM\InverseJoinColumn(name: 'group_id', referencedColumnName: 'id')]
321
    #[ORM\ManyToMany(targetEntity: Group::class, inversedBy: 'users')]
322
    protected Collection $groups;
323
324
    /**
325
     * ORM\OneToMany(targetEntity="Chamilo\CoreBundle\Entity\CurriculumItemRelUser", mappedBy="user").
326
     */
327
    protected Collection $curriculumItems;
328
329
    /**
330
     * @var Collection<int, AccessUrlRelUser>
331
     */
332
    #[ORM\OneToMany(
333
        mappedBy: 'user',
334
        targetEntity: AccessUrlRelUser::class,
335
        cascade: ['persist', 'remove'],
336
        orphanRemoval: true
337
    )]
338
    protected Collection $portals;
339
340
    /**
341
     * @var Collection<int, ResourceNode>
342
     */
343
    #[ORM\OneToMany(mappedBy: 'creator', targetEntity: ResourceNode::class, cascade: ['persist', 'remove'])]
344
    protected Collection $resourceNodes;
345
346
    /**
347
     * @var Collection<int, SessionRelCourseRelUser>
348
     */
349
    #[ORM\OneToMany(
350
        mappedBy: 'user',
351
        targetEntity: SessionRelCourseRelUser::class,
352
        cascade: ['persist'],
353
        orphanRemoval: true
354
    )]
355
    protected Collection $sessionRelCourseRelUsers;
356
357
    /**
358
     * @var Collection<int, SessionRelUser>
359
     */
360
    #[ORM\OneToMany(
361
        mappedBy: 'user',
362
        targetEntity: SessionRelUser::class,
363
        cascade: ['persist', 'remove'],
364
        orphanRemoval: true
365
    )]
366
    protected Collection $sessionsRelUser;
367
368
    /**
369
     * @var Collection<int, SkillRelUser>
370
     */
371
    #[ORM\OneToMany(
372
        mappedBy: 'user',
373
        targetEntity: SkillRelUser::class,
374
        cascade: ['persist', 'remove'],
375
        orphanRemoval: true
376
    )]
377
    protected Collection $achievedSkills;
378
379
    /**
380
     * @var Collection<int, SkillRelUserComment>
381
     */
382
    #[ORM\OneToMany(
383
        mappedBy: 'feedbackGiver',
384
        targetEntity: SkillRelUserComment::class,
385
        cascade: ['persist', 'remove'],
386
        orphanRemoval: true
387
    )]
388
    protected Collection $commentedUserSkills;
389
390
    /**
391
     * @var Collection<int, GradebookCategory>
392
     */
393
    #[ORM\OneToMany(mappedBy: 'user', targetEntity: GradebookCategory::class)]
394
    protected Collection $gradeBookCategories;
395
396
    /**
397
     * @var Collection<int, GradebookCertificate>
398
     */
399
    #[ORM\OneToMany(
400
        mappedBy: 'user',
401
        targetEntity: GradebookCertificate::class,
402
        cascade: ['persist', 'remove'],
403
        orphanRemoval: true
404
    )]
405
    protected Collection $gradeBookCertificates;
406
407
    /**
408
     * @var Collection<int, GradebookComment>
409
     */
410
    #[ORM\OneToMany(mappedBy: 'user', targetEntity: GradebookComment::class)]
411
    protected Collection $gradeBookComments;
412
413
    /**
414
     * @var Collection<int, GradebookResult>
415
     */
416
    #[ORM\OneToMany(
417
        mappedBy: 'user',
418
        targetEntity: GradebookResult::class,
419
        cascade: ['persist', 'remove'],
420
        orphanRemoval: true
421
    )]
422
    protected Collection $gradeBookResults;
423
424
    /**
425
     * @var Collection<int, GradebookResultLog>
426
     */
427
    #[ORM\OneToMany(
428
        mappedBy: 'user',
429
        targetEntity: GradebookResultLog::class,
430
        cascade: ['persist', 'remove'],
431
        orphanRemoval: true
432
    )]
433
    protected Collection $gradeBookResultLogs;
434
435
    /**
436
     * @var Collection<int, GradebookScoreLog>
437
     */
438
    #[ORM\OneToMany(
439
        mappedBy: 'user',
440
        targetEntity: GradebookScoreLog::class,
441
        cascade: ['persist', 'remove'],
442
        orphanRemoval: true
443
    )]
444
    protected Collection $gradeBookScoreLogs;
445
446
    /**
447
     * @var Collection<int, UserRelUser>
448
     */
449
    #[ORM\OneToMany(
450
        mappedBy: 'user',
451
        targetEntity: UserRelUser::class,
452
        cascade: ['persist', 'remove'],
453
        fetch: 'EXTRA_LAZY',
454
        orphanRemoval: true
455
    )]
456
    protected Collection $friends;
457
458
    /**
459
     * @var Collection<int, UserRelUser>
460
     */
461
    #[ORM\OneToMany(
462
        mappedBy: 'friend',
463
        targetEntity: UserRelUser::class,
464
        cascade: ['persist', 'remove'],
465
        fetch: 'EXTRA_LAZY',
466
        orphanRemoval: true
467
    )]
468
    protected Collection $friendsWithMe;
469
470
    /**
471
     * @var Collection<int, GradebookLinkevalLog>
472
     */
473
    #[ORM\OneToMany(
474
        mappedBy: 'user',
475
        targetEntity: GradebookLinkevalLog::class,
476
        cascade: ['persist', 'remove'],
477
        orphanRemoval: true
478
    )]
479
    protected Collection $gradeBookLinkEvalLogs;
480
481
    /**
482
     * @var Collection<int, SequenceValue>
483
     */
484
    #[ORM\OneToMany(
485
        mappedBy: 'user',
486
        targetEntity: SequenceValue::class,
487
        cascade: ['persist', 'remove'],
488
        orphanRemoval: true
489
    )]
490
    protected Collection $sequenceValues;
491
492
    /**
493
     * @var Collection<int, TrackEExerciseConfirmation>
494
     */
495
    #[ORM\OneToMany(
496
        mappedBy: 'user',
497
        targetEntity: TrackEExerciseConfirmation::class,
498
        cascade: ['persist', 'remove'],
499
        orphanRemoval: true
500
    )]
501
    protected Collection $trackEExerciseConfirmations;
502
503
    /**
504
     * @var Collection<int, TrackEAttempt>
505
     */
506
    #[ORM\OneToMany(
507
        mappedBy: 'user',
508
        targetEntity: TrackEAccessComplete::class,
509
        cascade: [
510
            'persist',
511
            'remove',
512
        ],
513
        orphanRemoval: true
514
    )]
515
    protected Collection $trackEAccessCompleteList;
516
517
    /**
518
     * @var Collection<int, Templates>
519
     */
520
    #[ORM\OneToMany(
521
        mappedBy: 'user',
522
        targetEntity: Templates::class,
523
        cascade: ['persist', 'remove'],
524
        fetch: 'EXTRA_LAZY',
525
        orphanRemoval: true
526
    )]
527
    protected Collection $templates;
528
529
    /**
530
     * @var Collection<int, TrackEAttempt>
531
     */
532
    #[ORM\OneToMany(
533
        mappedBy: 'user',
534
        targetEntity: TrackEAttempt::class,
535
        cascade: ['persist', 'remove'],
536
        orphanRemoval: true
537
    )]
538
    protected Collection $trackEAttempts;
539
540
    /**
541
     * @var Collection<int, TrackECourseAccess>
542
     */
543
    #[ORM\OneToMany(
544
        mappedBy: 'user',
545
        targetEntity: TrackECourseAccess::class,
546
        cascade: ['persist', 'remove'],
547
        orphanRemoval: true
548
    )]
549
    protected Collection $trackECourseAccess;
550
551
    /**
552
     * @var Collection<int, UserCourseCategory>
553
     */
554
    #[ORM\OneToMany(
555
        mappedBy: 'user',
556
        targetEntity: UserCourseCategory::class,
557
        cascade: ['persist', 'remove'],
558
        orphanRemoval: true
559
    )]
560
    protected Collection $userCourseCategories;
561
562
    /**
563
     * @var Collection<int, UserRelCourseVote>
564
     */
565
    #[ORM\OneToMany(
566
        mappedBy: 'user',
567
        targetEntity: UserRelCourseVote::class,
568
        cascade: ['persist', 'remove'],
569
        orphanRemoval: true
570
    )]
571
    protected Collection $userRelCourseVotes;
572
573
    /**
574
     * @var Collection<int, UserRelTag>
575
     */
576
    #[ORM\OneToMany(
577
        mappedBy: 'user',
578
        targetEntity: UserRelTag::class,
579
        cascade: ['persist', 'remove'],
580
        orphanRemoval: true
581
    )]
582
    protected Collection $userRelTags;
583
584
    /**
585
     * @var Collection<int, CGroupRelUser>
586
     */
587
    #[ORM\OneToMany(
588
        mappedBy: 'user',
589
        targetEntity: CGroupRelUser::class,
590
        cascade: ['persist', 'remove'],
591
        orphanRemoval: true
592
    )]
593
    protected Collection $courseGroupsAsMember;
594
595
    /**
596
     * @var Collection<int, CGroupRelTutor>
597
     */
598
    #[ORM\OneToMany(mappedBy: 'user', targetEntity: CGroupRelTutor::class, orphanRemoval: true)]
599
    protected Collection $courseGroupsAsTutor;
600
601
    #[ORM\Column(name: 'status', type: 'integer')]
602
    protected int $status;
603
604
    #[ORM\Column(name: 'official_code', type: 'string', length: 40, nullable: true)]
605
    protected ?string $officialCode = null;
606
607
    #[ORM\Column(name: 'picture_uri', type: 'string', length: 250, nullable: true)]
608
    protected ?string $pictureUri = null;
609
610
    #[ORM\Column(name: 'creator_id', type: 'integer', unique: false, nullable: true)]
611
    protected ?int $creatorId = null;
612
613
    #[ORM\Column(name: 'competences', type: 'text', unique: false, nullable: true)]
614
    protected ?string $competences = null;
615
616
    #[ORM\Column(name: 'diplomas', type: 'text', unique: false, nullable: true)]
617
    protected ?string $diplomas = null;
618
619
    #[ORM\Column(name: 'openarea', type: 'text', unique: false, nullable: true)]
620
    protected ?string $openarea = null;
621
622
    #[ORM\Column(name: 'teach', type: 'text', unique: false, nullable: true)]
623
    protected ?string $teach = null;
624
625
    #[ORM\Column(name: 'productions', type: 'string', length: 250, unique: false, nullable: true)]
626
    protected ?string $productions = null;
627
628
    #[ORM\Column(name: 'expiration_date', type: 'datetime', unique: false, nullable: true)]
629
    protected ?DateTime $expirationDate = null;
630
631
    #[Groups(['user:read', 'user_json:read'])]
632
    #[ORM\Column(name: 'active', type: 'integer')]
633
    protected int $active;
634
635
    #[ORM\Column(name: 'openid', type: 'string', length: 255, unique: false, nullable: true)]
636
    protected ?string $openid = null;
637
638
    #[ORM\Column(name: 'theme', type: 'string', length: 255, unique: false, nullable: true)]
639
    protected ?string $theme = null;
640
641
    #[ORM\Column(name: 'hr_dept_id', type: 'smallint', unique: false, nullable: true)]
642
    protected ?int $hrDeptId = null;
643
644
    #[Groups(['user:write'])]
645
    protected ?AccessUrl $currentUrl = null;
646
647
    /**
648
     * @var Collection<int, MessageTag>
649
     */
650
    #[ORM\OneToMany(
651
        mappedBy: 'user',
652
        targetEntity: MessageTag::class,
653
        cascade: ['persist', 'remove'],
654
        orphanRemoval: true
655
    )]
656
    protected Collection $messageTags;
657
658
    /**
659
     * @var Collection<int, Message>
660
     */
661
    #[ORM\OneToMany(
662
        mappedBy: 'sender',
663
        targetEntity: Message::class,
664
        cascade: ['persist']
665
    )]
666
    protected Collection $sentMessages;
667
668
    /**
669
     * @var Collection<int, MessageRelUser>
670
     */
671
    #[ORM\OneToMany(mappedBy: 'receiver', targetEntity: MessageRelUser::class, cascade: ['persist', 'remove'])]
672
    protected Collection $receivedMessages;
673
674
    /**
675
     * @var Collection<int, CSurveyInvitation>
676
     */
677
    #[ORM\OneToMany(mappedBy: 'user', targetEntity: CSurveyInvitation::class, cascade: ['persist', 'remove'])]
678
    protected Collection $surveyInvitations;
679
680
    /**
681
     * @var Collection<int, TrackELogin>
682
     */
683
    #[ORM\OneToMany(mappedBy: 'user', targetEntity: TrackELogin::class, cascade: ['persist', 'remove'])]
684
    protected Collection $logins;
685
686
    #[ORM\OneToOne(mappedBy: 'user', targetEntity: Admin::class, cascade: ['persist', 'remove'], orphanRemoval: true)]
687
    protected ?Admin $admin = null;
688
689
    #[ORM\Column(type: 'uuid', unique: true)]
690
    protected Uuid $uuid;
691
692
    // Property used only during installation.
693
    protected bool $skipResourceNode = false;
694
695
    #[Groups([
696
        'user:read',
697
        'user_json:read',
698
        'social_post:read',
699
        'course:read',
700
        'course_rel_user:read',
701
        'message:read',
702
        'user_subscriptions:sessions',
703
    ])]
704
    protected string $fullName;
705
706
    #[ORM\OneToMany(mappedBy: 'sender', targetEntity: SocialPost::class, orphanRemoval: true)]
707
    private Collection $sentSocialPosts;
708
709
    #[ORM\OneToMany(mappedBy: 'userReceiver', targetEntity: SocialPost::class)]
710
    private Collection $receivedSocialPosts;
711
712
    #[ORM\OneToMany(mappedBy: 'user', targetEntity: SocialPostFeedback::class, orphanRemoval: true)]
713
    private Collection $socialPostsFeedbacks;
714
715
    #[ORM\Column(name: 'mfa_enabled', type: 'boolean', options: ['default' => false])]
716
    protected bool $mfaEnabled = false;
717
718
    #[ORM\Column(name: 'mfa_service', type: 'string', length: 255, nullable: true)]
719
    protected ?string $mfaService = null;
720
721
    #[ORM\Column(name: 'mfa_secret', type: 'string', length: 255, nullable: true)]
722
    protected ?string $mfaSecret = null;
723
724
    #[ORM\Column(name: 'mfa_backup_codes', type: 'text', nullable: true)]
725
    protected ?string $mfaBackupCodes = null;
726
727
    #[ORM\Column(name: 'mfa_last_used', type: 'datetime', nullable: true)]
728
    protected ?DateTimeInterface $mfaLastUsed = null;
729
730
    /**
731
     * @var Collection<int, UserAuthSource>
732
     */
733
    #[ORM\OneToMany(mappedBy: 'user', targetEntity: UserAuthSource::class, cascade: ['persist'], orphanRemoval: true)]
734
    private Collection $authSources;
735
736
    public function __construct()
737
    {
738
        $this->skipResourceNode = false;
739
        $this->uuid = Uuid::v4();
740
        $this->apiToken = null;
741
        $this->biography = '';
742
        $this->website = '';
743
        $this->locale = 'en';
744
        $this->timezone = 'Europe\Paris';
745
        $this->status = CourseRelUser::STUDENT;
746
        $this->salt = sha1(uniqid('', true));
747
        $this->active = 1;
748
        $this->locked = false;
749
        $this->expired = false;
750
        $this->courses = new ArrayCollection();
751
        $this->classes = new ArrayCollection();
752
        $this->curriculumItems = new ArrayCollection();
753
        $this->portals = new ArrayCollection();
754
        $this->dropBoxSentFiles = new ArrayCollection();
755
        $this->dropBoxReceivedFiles = new ArrayCollection();
756
        $this->groups = new ArrayCollection();
757
        $this->gradeBookCertificates = new ArrayCollection();
758
        $this->courseGroupsAsMember = new ArrayCollection();
759
        $this->courseGroupsAsTutor = new ArrayCollection();
760
        $this->resourceNodes = new ArrayCollection();
761
        $this->sessionRelCourseRelUsers = new ArrayCollection();
762
        $this->achievedSkills = new ArrayCollection();
763
        $this->commentedUserSkills = new ArrayCollection();
764
        $this->gradeBookCategories = new ArrayCollection();
765
        $this->gradeBookComments = new ArrayCollection();
766
        $this->gradeBookResults = new ArrayCollection();
767
        $this->gradeBookResultLogs = new ArrayCollection();
768
        $this->gradeBookScoreLogs = new ArrayCollection();
769
        $this->friends = new ArrayCollection();
770
        $this->friendsWithMe = new ArrayCollection();
771
        $this->gradeBookLinkEvalLogs = new ArrayCollection();
772
        $this->messageTags = new ArrayCollection();
773
        $this->sequenceValues = new ArrayCollection();
774
        $this->trackEExerciseConfirmations = new ArrayCollection();
775
        $this->trackEAccessCompleteList = new ArrayCollection();
776
        $this->templates = new ArrayCollection();
777
        $this->trackEAttempts = new ArrayCollection();
778
        $this->trackECourseAccess = new ArrayCollection();
779
        $this->userCourseCategories = new ArrayCollection();
780
        $this->userRelCourseVotes = new ArrayCollection();
781
        $this->userRelTags = new ArrayCollection();
782
        $this->sessionsRelUser = new ArrayCollection();
783
        $this->sentMessages = new ArrayCollection();
784
        $this->receivedMessages = new ArrayCollection();
785
        $this->surveyInvitations = new ArrayCollection();
786
        $this->logins = new ArrayCollection();
787
        $this->createdAt = new DateTime();
788
        $this->updatedAt = new DateTime();
789
        $this->roles = [];
790
        $this->credentialsExpired = false;
791
        $this->credentialsExpireAt = new DateTime();
792
        $this->dateOfBirth = new DateTime();
793
        $this->expiresAt = new DateTime();
794
        $this->passwordRequestedAt = new DateTime();
795
        $this->sentSocialPosts = new ArrayCollection();
796
        $this->receivedSocialPosts = new ArrayCollection();
797
        $this->socialPostsFeedbacks = new ArrayCollection();
798
        $this->authSources = new ArrayCollection();
799
    }
800
801
    public function __toString(): string
802
    {
803
        return $this->username;
804
    }
805
806
    public static function getPasswordConstraints(): array
807
    {
808
        return [
809
            new Assert\Length(['min' => 5]),
810
            new Assert\Regex(['pattern' => '/^[a-z\-_0-9]+$/i', 'htmlPattern' => '/^[a-z\-_0-9]+$/i']),
811
            new Assert\Regex(['pattern' => '/[0-9]{2}/', 'htmlPattern' => '/[0-9]{2}/']),
812
        ];
813
    }
814
815
    public static function loadValidatorMetadata(ClassMetadata $metadata): void {}
816
817
    public function getUuid(): Uuid
818
    {
819
        return $this->uuid;
820
    }
821
822
    public function setUuid(Uuid $uuid): self
823
    {
824
        $this->uuid = $uuid;
825
826
        return $this;
827
    }
828
829
    public function getResourceNode(): ?ResourceNode
830
    {
831
        return $this->resourceNode;
832
    }
833
834
    public function setResourceNode(ResourceNode $resourceNode): self
835
    {
836
        $this->resourceNode = $resourceNode;
837
838
        return $this;
839
    }
840
841
    public function hasResourceNode(): bool
842
    {
843
        return $this->resourceNode instanceof ResourceNode;
844
    }
845
846
    public function getResourceNodes(): Collection
847
    {
848
        return $this->resourceNodes;
849
    }
850
851
    public function addResourceNode(ResourceNode $resourceNode): static
852
    {
853
        if (!$this->resourceNodes->contains($resourceNode)) {
854
            $this->resourceNodes->add($resourceNode);
855
            $resourceNode->setCreator($this);
856
        }
857
858
        return $this;
859
    }
860
861
    public function getDropBoxSentFiles(): Collection
862
    {
863
        return $this->dropBoxSentFiles;
864
    }
865
866
    public function setDropBoxSentFiles(Collection $value): self
867
    {
868
        $this->dropBoxSentFiles = $value;
869
870
        return $this;
871
    }
872
873
    public function getCourses(): Collection
874
    {
875
        return $this->courses;
876
    }
877
878
    /**
879
     * @param Collection<int, CourseRelUser> $courses
880
     */
881
    public function setCourses(Collection $courses): self
882
    {
883
        $this->courses = $courses;
884
885
        return $this;
886
    }
887
888
    public function setPortal(AccessUrlRelUser $portal): self
889
    {
890
        $this->portals->add($portal);
891
892
        return $this;
893
    }
894
895
    /**
896
     * Get a bool on whether the user is active or not. Active can be "-1" which means pre-deleted, and is returned as false (not active).
897
     *
898
     * @return bool True if active = 1, false in any other case (0 = inactive, -1 = predeleted)
899
     */
900
    public function getIsActive(): bool
901
    {
902
        return 1 === $this->active;
903
    }
904
905
    public function isEnabled(): bool
906
    {
907
        return $this->isActive();
908
    }
909
910
    /**
911
     * Returns the list of classes for the user.
912
     */
913
    public function getCompleteNameWithClasses(): string
914
    {
915
        $classSubscription = $this->getClasses();
916
        $classList = [];
917
918
        /** @var UsergroupRelUser $subscription */
919
        foreach ($classSubscription as $subscription) {
920
            $class = $subscription->getUsergroup();
921
            $classList[] = $class->getTitle();
922
        }
923
        $classString = empty($classList) ? null : ' ['.implode(', ', $classList).']';
924
925
        return UserManager::formatUserFullName($this).$classString;
926
    }
927
928
    public function getClasses(): Collection
929
    {
930
        return $this->classes;
931
    }
932
933
    /**
934
     * @param Collection<int, UsergroupRelUser> $classes
935
     */
936
    public function setClasses(Collection $classes): self
937
    {
938
        $this->classes = $classes;
939
940
        return $this;
941
    }
942
943
    public function getEmail(): string
944
    {
945
        return $this->email;
946
    }
947
948
    public function setEmail(string $email): self
949
    {
950
        $this->email = $email;
951
952
        return $this;
953
    }
954
955
    public function getOfficialCode(): ?string
956
    {
957
        return $this->officialCode;
958
    }
959
960
    public function setOfficialCode(?string $officialCode): self
961
    {
962
        $this->officialCode = $officialCode;
963
964
        return $this;
965
    }
966
967
    public function getPhone(): ?string
968
    {
969
        return $this->phone;
970
    }
971
972
    public function setPhone(?string $phone): self
973
    {
974
        $this->phone = $phone;
975
976
        return $this;
977
    }
978
979
    public function getAddress(): ?string
980
    {
981
        return $this->address;
982
    }
983
984
    public function setAddress(?string $address): self
985
    {
986
        $this->address = $address;
987
988
        return $this;
989
    }
990
991
    public function getCreatorId(): ?int
992
    {
993
        return $this->creatorId;
994
    }
995
996
    public function setCreatorId(int $creatorId): self
997
    {
998
        $this->creatorId = $creatorId;
999
1000
        return $this;
1001
    }
1002
1003
    public function getCompetences(): ?string
1004
    {
1005
        return $this->competences;
1006
    }
1007
1008
    public function setCompetences(?string $competences): self
1009
    {
1010
        $this->competences = $competences;
1011
1012
        return $this;
1013
    }
1014
1015
    public function getDiplomas(): ?string
1016
    {
1017
        return $this->diplomas;
1018
    }
1019
1020
    public function setDiplomas(?string $diplomas): self
1021
    {
1022
        $this->diplomas = $diplomas;
1023
1024
        return $this;
1025
    }
1026
1027
    public function getOpenarea(): ?string
1028
    {
1029
        return $this->openarea;
1030
    }
1031
1032
    public function setOpenarea(?string $openarea): self
1033
    {
1034
        $this->openarea = $openarea;
1035
1036
        return $this;
1037
    }
1038
1039
    public function getTeach(): ?string
1040
    {
1041
        return $this->teach;
1042
    }
1043
1044
    public function setTeach(?string $teach): self
1045
    {
1046
        $this->teach = $teach;
1047
1048
        return $this;
1049
    }
1050
1051
    public function getProductions(): ?string
1052
    {
1053
        return $this->productions;
1054
    }
1055
1056
    public function setProductions(?string $productions): self
1057
    {
1058
        $this->productions = $productions;
1059
1060
        return $this;
1061
    }
1062
1063
    public function getExpirationDate(): ?DateTime
1064
    {
1065
        return $this->expirationDate;
1066
    }
1067
1068
    public function setExpirationDate(?DateTime $expirationDate): self
1069
    {
1070
        $this->expirationDate = $expirationDate;
1071
1072
        return $this;
1073
    }
1074
1075
    public function getActive(): int
1076
    {
1077
        return $this->active;
1078
    }
1079
1080
    public function isActive(): bool
1081
    {
1082
        return $this->getIsActive();
1083
    }
1084
1085
    public function setActive(int $active): self
1086
    {
1087
        $this->active = $active;
1088
1089
        return $this;
1090
    }
1091
1092
    public function getOpenid(): ?string
1093
    {
1094
        return $this->openid;
1095
    }
1096
1097
    public function setOpenid(string $openid): self
1098
    {
1099
        $this->openid = $openid;
1100
1101
        return $this;
1102
    }
1103
1104
    public function getTheme(): ?string
1105
    {
1106
        return $this->theme;
1107
    }
1108
1109
    public function setTheme(string $theme): self
1110
    {
1111
        $this->theme = $theme;
1112
1113
        return $this;
1114
    }
1115
1116
    public function getHrDeptId(): ?int
1117
    {
1118
        return $this->hrDeptId;
1119
    }
1120
1121
    public function setHrDeptId(int $hrDeptId): self
1122
    {
1123
        $this->hrDeptId = $hrDeptId;
1124
1125
        return $this;
1126
    }
1127
1128
    public function isOnline(): bool
1129
    {
1130
        return false;
1131
    }
1132
1133
    public function getIdentifier(): int
1134
    {
1135
        return $this->getId();
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->getId() could return the type null which is incompatible with the type-hinted return integer. Consider adding an additional type-check to rule them out.
Loading history...
1136
    }
1137
1138
    public function getId(): ?int
1139
    {
1140
        return $this->id;
1141
    }
1142
1143
    public function getIri(): ?string
1144
    {
1145
        if (null === $this->id) {
1146
            return null;
1147
        }
1148
1149
        return '/api/users/'.$this->getId();
1150
    }
1151
1152
    public function getSlug(): string
1153
    {
1154
        return $this->getUsername();
1155
    }
1156
1157
    public function getUsername(): string
1158
    {
1159
        return $this->username;
1160
    }
1161
1162
    public function setUsername(string $username): self
1163
    {
1164
        $this->username = $username;
1165
1166
        return $this;
1167
    }
1168
1169
    public function setSlug(string $slug): self
1170
    {
1171
        return $this->setUsername($slug);
1172
    }
1173
1174
    public function getLastLogin(): ?DateTime
1175
    {
1176
        return $this->lastLogin;
1177
    }
1178
1179
    public function setLastLogin(?DateTime $lastLogin = null): self
1180
    {
1181
        $this->lastLogin = $lastLogin;
1182
1183
        return $this;
1184
    }
1185
1186
    public function getConfirmationToken(): ?string
1187
    {
1188
        return $this->confirmationToken;
1189
    }
1190
1191
    public function setConfirmationToken(string $confirmationToken): self
1192
    {
1193
        $this->confirmationToken = $confirmationToken;
1194
1195
        return $this;
1196
    }
1197
1198
    public function isPasswordRequestNonExpired(int $ttl): bool
1199
    {
1200
        return $this->getPasswordRequestedAt() instanceof DateTime && $this->getPasswordRequestedAt()->getTimestamp(
1201
        ) + $ttl > time();
1202
    }
1203
1204
    public function getPasswordRequestedAt(): ?DateTime
1205
    {
1206
        return $this->passwordRequestedAt;
1207
    }
1208
1209
    public function setPasswordRequestedAt(?DateTime $date = null): self
1210
    {
1211
        $this->passwordRequestedAt = $date;
1212
1213
        return $this;
1214
    }
1215
1216
    public function getPlainPassword(): ?string
1217
    {
1218
        return $this->plainPassword;
1219
    }
1220
1221
    public function setPlainPassword(?string $password): self
1222
    {
1223
        $this->plainPassword = $password;
1224
        // forces the object to look "dirty" to Doctrine. Avoids
1225
        // Doctrine *not* saving this entity, if only plainPassword changes
1226
        $this->password = '';
1227
1228
        return $this;
1229
    }
1230
1231
    /**
1232
     * Returns the expiration date.
1233
     */
1234
    public function getExpiresAt(): ?DateTime
1235
    {
1236
        return $this->expiresAt;
1237
    }
1238
1239
    public function setExpiresAt(DateTime $date): self
1240
    {
1241
        $this->expiresAt = $date;
1242
1243
        return $this;
1244
    }
1245
1246
    /**
1247
     * Returns the credentials expiration date.
1248
     */
1249
    public function getCredentialsExpireAt(): ?DateTime
1250
    {
1251
        return $this->credentialsExpireAt;
1252
    }
1253
1254
    /**
1255
     * Sets the credentials expiration date.
1256
     */
1257
    public function setCredentialsExpireAt(?DateTime $date = null): self
1258
    {
1259
        $this->credentialsExpireAt = $date;
1260
1261
        return $this;
1262
    }
1263
1264
    public function getFullname(): string
1265
    {
1266
        if (empty($this->fullName)) {
1267
            return \sprintf('%s %s', $this->getFirstname(), $this->getLastname());
1268
        }
1269
1270
        return $this->fullName;
1271
    }
1272
1273
    public function setFullName(string $fullName): self
1274
    {
1275
        $this->fullName = $fullName;
1276
1277
        return $this;
1278
    }
1279
1280
    public function getFirstname(): ?string
1281
    {
1282
        return $this->firstname;
1283
    }
1284
1285
    public function setFirstname(string $firstname): self
1286
    {
1287
        $this->firstname = $firstname;
1288
1289
        return $this;
1290
    }
1291
1292
    public function getLastname(): ?string
1293
    {
1294
        return $this->lastname;
1295
    }
1296
1297
    public function setLastname(string $lastname): self
1298
    {
1299
        $this->lastname = $lastname;
1300
1301
        return $this;
1302
    }
1303
1304
    public function hasGroup(string $name): bool
1305
    {
1306
        return \in_array($name, $this->getGroupNames(), true);
1307
    }
1308
1309
    public function getGroupNames(): array
1310
    {
1311
        $names = [];
1312
        foreach ($this->getGroups() as $group) {
1313
            $names[] = $group->getTitle();
1314
        }
1315
1316
        return $names;
1317
    }
1318
1319
    public function getGroups(): Collection
1320
    {
1321
        return $this->groups;
1322
    }
1323
1324
    /**
1325
     * Sets the user groups.
1326
     */
1327
    public function setGroups(Collection $groups): self
1328
    {
1329
        foreach ($groups as $group) {
1330
            $this->addGroup($group);
1331
        }
1332
1333
        return $this;
1334
    }
1335
1336
    public function addGroup(Group $group): self
1337
    {
1338
        if (!$this->getGroups()->contains($group)) {
1339
            $this->getGroups()->add($group);
1340
        }
1341
1342
        return $this;
1343
    }
1344
1345
    public function removeGroup(Group $group): self
1346
    {
1347
        if ($this->getGroups()->contains($group)) {
1348
            $this->getGroups()->removeElement($group);
1349
        }
1350
1351
        return $this;
1352
    }
1353
1354
    public function isAccountNonExpired(): bool
1355
    {
1356
        return true;
1357
    }
1358
1359
    public function isAccountNonLocked(): bool
1360
    {
1361
        return true;
1362
    }
1363
1364
    public function isCredentialsNonExpired(): bool
1365
    {
1366
        return true;
1367
    }
1368
1369
    public function getCredentialsExpired(): bool
1370
    {
1371
        return $this->credentialsExpired;
1372
    }
1373
1374
    public function setCredentialsExpired(bool $boolean): self
1375
    {
1376
        $this->credentialsExpired = $boolean;
1377
1378
        return $this;
1379
    }
1380
1381
    public function getExpired(): bool
1382
    {
1383
        return $this->expired;
1384
    }
1385
1386
    /**
1387
     * Sets this user to expired.
1388
     */
1389
    public function setExpired(bool $boolean): self
1390
    {
1391
        $this->expired = $boolean;
1392
1393
        return $this;
1394
    }
1395
1396
    public function getLocked(): bool
1397
    {
1398
        return $this->locked;
1399
    }
1400
1401
    public function setLocked(bool $boolean): self
1402
    {
1403
        $this->locked = $boolean;
1404
1405
        return $this;
1406
    }
1407
1408
    /**
1409
     * Check if the user has the skill.
1410
     *
1411
     * @param Skill $skill The skill
1412
     */
1413
    public function hasSkill(Skill $skill): bool
1414
    {
1415
        $achievedSkills = $this->getAchievedSkills();
1416
        foreach ($achievedSkills as $userSkill) {
1417
            if ($userSkill->getSkill()->getId() !== $skill->getId()) {
1418
                continue;
1419
            }
1420
1421
            return true;
1422
        }
1423
1424
        return false;
1425
    }
1426
1427
    /**
1428
     * @return Collection<int, SkillRelUser>
1429
     */
1430
    public function getAchievedSkills(): Collection
1431
    {
1432
        return $this->achievedSkills;
1433
    }
1434
1435
    /**
1436
     * @param Collection<int, SkillRelUser> $value
1437
     */
1438
    public function setAchievedSkills(Collection $value): self
1439
    {
1440
        $this->achievedSkills = $value;
1441
1442
        return $this;
1443
    }
1444
1445
    public function isProfileCompleted(): ?bool
1446
    {
1447
        return $this->profileCompleted;
1448
    }
1449
1450
    public function setProfileCompleted(?bool $profileCompleted): self
1451
    {
1452
        $this->profileCompleted = $profileCompleted;
1453
1454
        return $this;
1455
    }
1456
1457
    public function getCurrentUrl(): ?AccessUrl
1458
    {
1459
        return $this->currentUrl;
1460
    }
1461
1462
    public function setCurrentUrl(AccessUrl $url): self
1463
    {
1464
        $accessUrlRelUser = (new AccessUrlRelUser())->setUrl($url)->setUser($this);
1465
        $this->getPortals()->add($accessUrlRelUser);
1466
1467
        return $this;
1468
    }
1469
1470
    public function getPortals(): Collection
1471
    {
1472
        return $this->portals;
1473
    }
1474
1475
    /**
1476
     * @param Collection<int, AccessUrlRelUser> $value
1477
     */
1478
    public function setPortals(Collection $value): void
1479
    {
1480
        $this->portals = $value;
1481
    }
1482
1483
    public function getSessionsAsGeneralCoach(): array
1484
    {
1485
        return $this->getSessions(Session::GENERAL_COACH);
1486
    }
1487
1488
    /**
1489
     * Retrieves this user's related sessions.
1490
     */
1491
    public function getSessions(int $relationType): array
1492
    {
1493
        $sessions = [];
1494
        foreach ($this->getSessionsRelUser() as $sessionRelUser) {
1495
            if ($sessionRelUser->getRelationType() === $relationType) {
1496
                $sessions[] = $sessionRelUser->getSession();
1497
            }
1498
        }
1499
1500
        return $sessions;
1501
    }
1502
1503
    /**
1504
     * @return Collection<int, SessionRelUser>
1505
     */
1506
    public function getSessionsRelUser(): Collection
1507
    {
1508
        return $this->sessionsRelUser;
1509
    }
1510
1511
    public function getSessionsAsAdmin(): array
1512
    {
1513
        return $this->getSessions(Session::SESSION_ADMIN);
1514
    }
1515
1516
    public function getCommentedUserSkills(): Collection
1517
    {
1518
        return $this->commentedUserSkills;
1519
    }
1520
1521
    /**
1522
     * @param Collection<int, SkillRelUserComment> $commentedUserSkills
1523
     */
1524
    public function setCommentedUserSkills(Collection $commentedUserSkills): self
1525
    {
1526
        $this->commentedUserSkills = $commentedUserSkills;
1527
1528
        return $this;
1529
    }
1530
1531
    public function isEqualTo(UserInterface $user): bool
1532
    {
1533
        if ($this->password !== $user->getPassword()) {
1534
            return false;
1535
        }
1536
        if ($this->salt !== $user->getSalt()) {
1537
            return false;
1538
        }
1539
        if ($this->username !== $user->getUserIdentifier()) {
1540
            return false;
1541
        }
1542
1543
        return true;
1544
    }
1545
1546
    public function getPassword(): ?string
1547
    {
1548
        return $this->password;
1549
    }
1550
1551
    public function setPassword(string $password): self
1552
    {
1553
        $this->password = $password;
1554
1555
        return $this;
1556
    }
1557
1558
    public function getSalt(): ?string
1559
    {
1560
        return $this->salt;
1561
    }
1562
1563
    public function setSalt(string $salt): self
1564
    {
1565
        $this->salt = $salt;
1566
1567
        return $this;
1568
    }
1569
1570
    public function getUserIdentifier(): string
1571
    {
1572
        return $this->username;
1573
    }
1574
1575
    /**
1576
     * @return Collection<int, Message>
1577
     */
1578
    public function getSentMessages(): Collection
1579
    {
1580
        return $this->sentMessages;
1581
    }
1582
1583
    public function getReceivedMessages(): Collection
1584
    {
1585
        return $this->receivedMessages;
1586
    }
1587
1588
    public function getCourseGroupsAsMember(): Collection
1589
    {
1590
        return $this->courseGroupsAsMember;
1591
    }
1592
1593
    public function getCourseGroupsAsTutor(): Collection
1594
    {
1595
        return $this->courseGroupsAsTutor;
1596
    }
1597
1598
    public function getCourseGroupsAsMemberFromCourse(Course $course): Collection
1599
    {
1600
        $criteria = Criteria::create();
1601
        $criteria->where(Criteria::expr()->eq('cId', $course));
1602
1603
        return $this->courseGroupsAsMember->matching($criteria);
1604
    }
1605
1606
    public function eraseCredentials(): void
1607
    {
1608
        $this->plainPassword = null;
1609
    }
1610
1611
    /**
1612
     * Returns whether a user can be admin of all multi-URL portals in the case of a multi-URL install
1613
     * @return bool
1614
     */
1615
    public function isSuperAdmin(): bool
1616
    {
1617
        return $this->hasRole('ROLE_SUPER_ADMIN');
1618
    }
1619
1620
    public function hasRole(string $role): bool
1621
    {
1622
        return \in_array(strtoupper($role), $this->getRoles(), true);
1623
    }
1624
1625
    /**
1626
     * Returns the user roles.
1627
     */
1628
    public function getRoles(): array
1629
    {
1630
        $roles = $this->roles;
1631
        foreach ($this->getGroups() as $group) {
1632
            $roles = array_merge($roles, $group->getRoles());
1633
        }
1634
        // we need to make sure to have at least one role
1635
        $roles[] = 'ROLE_USER';
1636
1637
        return array_unique($roles);
1638
    }
1639
1640
    public function setRoles(array $roles): self
1641
    {
1642
        $this->roles = [];
1643
        foreach ($roles as $role) {
1644
            $this->addRole($role);
1645
        }
1646
1647
        return $this;
1648
    }
1649
1650
    public function setRoleFromStatus(int $status): void
1651
    {
1652
        $role = self::getRoleFromStatus($status);
1653
        $this->addRole($role);
1654
    }
1655
1656
    public static function getRoleFromStatus(int $status): string
1657
    {
1658
        return match ($status) {
1659
            COURSEMANAGER => 'ROLE_TEACHER',
1660
            STUDENT => 'ROLE_STUDENT',
1661
            DRH => 'ROLE_HR',
1662
            SESSIONADMIN => 'ROLE_SESSION_MANAGER',
1663
            STUDENT_BOSS => 'ROLE_STUDENT_BOSS',
1664
            INVITEE => 'ROLE_INVITEE',
1665
            default => 'ROLE_USER',
1666
        };
1667
    }
1668
1669
    public function addRole(string $role): self
1670
    {
1671
        $role = strtoupper($role);
1672
        if ($role === static::ROLE_DEFAULT || empty($role)) {
1673
            return $this;
1674
        }
1675
        if (!\in_array($role, $this->roles, true)) {
1676
            $this->roles[] = $role;
1677
        }
1678
1679
        return $this;
1680
    }
1681
1682
    public function removeRole(string $role): self
1683
    {
1684
        if (false !== ($key = array_search(strtoupper($role), $this->roles, true))) {
1685
            unset($this->roles[$key]);
1686
            $this->roles = array_values($this->roles);
1687
        }
1688
1689
        return $this;
1690
    }
1691
1692
    public function getUsernameCanonical(): string
1693
    {
1694
        return $this->usernameCanonical;
1695
    }
1696
1697
    public function setUsernameCanonical(string $usernameCanonical): self
1698
    {
1699
        $this->usernameCanonical = $usernameCanonical;
1700
1701
        return $this;
1702
    }
1703
1704
    public function getEmailCanonical(): string
1705
    {
1706
        return $this->emailCanonical;
1707
    }
1708
1709
    public function setEmailCanonical(string $emailCanonical): self
1710
    {
1711
        $this->emailCanonical = $emailCanonical;
1712
1713
        return $this;
1714
    }
1715
1716
    public function getTimezone(): string
1717
    {
1718
        return $this->timezone;
1719
    }
1720
1721
    public function setTimezone(string $timezone): self
1722
    {
1723
        $this->timezone = $timezone;
1724
1725
        return $this;
1726
    }
1727
1728
    public function getLocale(): string
1729
    {
1730
        return $this->locale;
1731
    }
1732
1733
    public function setLocale(string $locale): self
1734
    {
1735
        $this->locale = $locale;
1736
1737
        return $this;
1738
    }
1739
1740
    public function getApiToken(): ?string
1741
    {
1742
        return $this->apiToken;
1743
    }
1744
1745
    public function setApiToken(string $apiToken): self
1746
    {
1747
        $this->apiToken = $apiToken;
1748
1749
        return $this;
1750
    }
1751
1752
    public function getWebsite(): ?string
1753
    {
1754
        return $this->website;
1755
    }
1756
1757
    public function setWebsite(string $website): self
1758
    {
1759
        $this->website = $website;
1760
1761
        return $this;
1762
    }
1763
1764
    public function getBiography(): ?string
1765
    {
1766
        return $this->biography;
1767
    }
1768
1769
    public function setBiography(string $biography): self
1770
    {
1771
        $this->biography = $biography;
1772
1773
        return $this;
1774
    }
1775
1776
    public function getDateOfBirth(): ?DateTime
1777
    {
1778
        return $this->dateOfBirth;
1779
    }
1780
1781
    public function setDateOfBirth(?DateTime $dateOfBirth = null): self
1782
    {
1783
        $this->dateOfBirth = $dateOfBirth;
1784
1785
        return $this;
1786
    }
1787
1788
    public function getProfileUrl(): string
1789
    {
1790
        return '/main/social/profile.php?u='.$this->id;
1791
    }
1792
1793
    public function getIconStatus(): string
1794
    {
1795
        $hasCertificates = $this->getGradeBookCertificates()->count() > 0;
1796
        $urlImg = '/img/';
1797
        if ($this->isStudent()) {
1798
            $iconStatus = $urlImg.'icons/svg/identifier_student.svg';
1799
            if ($hasCertificates) {
1800
                $iconStatus = $urlImg.'icons/svg/identifier_graduated.svg';
1801
            }
1802
1803
            return $iconStatus;
1804
        }
1805
        if ($this->isTeacher()) {
1806
            $iconStatus = $urlImg.'icons/svg/identifier_teacher.svg';
1807
            if ($this->isAdmin()) {
1808
                $iconStatus = $urlImg.'icons/svg/identifier_admin.svg';
1809
            }
1810
1811
            return $iconStatus;
1812
        }
1813
        if ($this->isStudentBoss()) {
1814
            return $urlImg.'icons/svg/identifier_teacher.svg';
1815
        }
1816
1817
        return '';
1818
    }
1819
1820
    public function getGradeBookCertificates(): Collection
1821
    {
1822
        return $this->gradeBookCertificates;
1823
    }
1824
1825
    /**
1826
     * @param Collection<int, GradebookCertificate> $gradeBookCertificates
1827
     */
1828
    public function setGradeBookCertificates(Collection $gradeBookCertificates): self
1829
    {
1830
        $this->gradeBookCertificates = $gradeBookCertificates;
1831
1832
        return $this;
1833
    }
1834
1835
    public function isStudent(): bool
1836
    {
1837
        return $this->hasRole('ROLE_STUDENT');
1838
    }
1839
1840
    public function isTeacher(): bool
1841
    {
1842
        return $this->hasRole('ROLE_TEACHER');
1843
    }
1844
1845
    public function isAdmin(): bool
1846
    {
1847
        return $this->hasRole('ROLE_ADMIN');
1848
    }
1849
1850
    public function isStudentBoss(): bool
1851
    {
1852
        return $this->hasRole('ROLE_STUDENT_BOSS');
1853
    }
1854
1855
    public function isSessionAdmin(): bool
1856
    {
1857
        return $this->hasRole('ROLE_SESSION_MANAGER');
1858
    }
1859
1860
    public function isInvitee(): bool
1861
    {
1862
        return $this->hasRole('ROLE_INVITEE');
1863
    }
1864
1865
    public function isHRM(): bool
1866
    {
1867
        return $this->hasRole('ROLE_HR');
1868
    }
1869
1870
    public function getStatus(): int
1871
    {
1872
        return $this->status;
1873
    }
1874
1875
    public function setStatus(int $status): self
1876
    {
1877
        $this->status = $status;
1878
1879
        return $this;
1880
    }
1881
1882
    public function getPictureUri(): ?string
1883
    {
1884
        return $this->pictureUri;
1885
    }
1886
1887
    /**
1888
     * @return Collection<int, GradebookCategory>
1889
     */
1890
    public function getGradeBookCategories(): Collection
1891
    {
1892
        return $this->gradeBookCategories;
1893
    }
1894
1895
    /**
1896
     * @return Collection<int, GradebookComment>
1897
     */
1898
    public function getGradeBookComments(): Collection
1899
    {
1900
        return $this->gradeBookComments;
1901
    }
1902
1903
    /**
1904
     * @return Collection<int, GradebookResult>
1905
     */
1906
    public function getGradeBookResults(): Collection
1907
    {
1908
        return $this->gradeBookResults;
1909
    }
1910
1911
    /**
1912
     * @return Collection<int, GradebookResultLog>
1913
     */
1914
    public function getGradeBookResultLogs(): Collection
1915
    {
1916
        return $this->gradeBookResultLogs;
1917
    }
1918
1919
    /**
1920
     * @return Collection<int, GradebookScoreLog>
1921
     */
1922
    public function getGradeBookScoreLogs(): Collection
1923
    {
1924
        return $this->gradeBookScoreLogs;
1925
    }
1926
1927
    /**
1928
     * @return Collection<int, GradebookLinkevalLog>
1929
     */
1930
    public function getGradeBookLinkEvalLogs(): Collection
1931
    {
1932
        return $this->gradeBookLinkEvalLogs;
1933
    }
1934
1935
    /**
1936
     * @return Collection<int, UserRelCourseVote>
1937
     */
1938
    public function getUserRelCourseVotes(): Collection
1939
    {
1940
        return $this->userRelCourseVotes;
1941
    }
1942
1943
    /**
1944
     * @return Collection<int, UserRelTag>
1945
     */
1946
    public function getUserRelTags(): Collection
1947
    {
1948
        return $this->userRelTags;
1949
    }
1950
1951
    public function getCurriculumItems(): Collection
1952
    {
1953
        return $this->curriculumItems;
1954
    }
1955
1956
    /**
1957
     * @return Collection<int, UserRelUser>
1958
     */
1959
    public function getFriends(): Collection
1960
    {
1961
        return $this->friends;
1962
    }
1963
1964
    /**
1965
     * @return Collection<int, UserRelUser>
1966
     */
1967
    public function getFriendsWithMe(): Collection
1968
    {
1969
        return $this->friendsWithMe;
1970
    }
1971
1972
    public function addFriend(self $friend): self
1973
    {
1974
        return $this->addUserRelUser($friend, UserRelUser::USER_RELATION_TYPE_FRIEND);
1975
    }
1976
1977
    public function addUserRelUser(self $friend, int $relationType): self
1978
    {
1979
        $userRelUser = (new UserRelUser())->setUser($this)->setFriend($friend)->setRelationType($relationType);
1980
        $this->friends->add($userRelUser);
1981
1982
        return $this;
1983
    }
1984
1985
    /**
1986
     * @return Collection<int, Templates>
1987
     */
1988
    public function getTemplates(): Collection
1989
    {
1990
        return $this->templates;
1991
    }
1992
1993
    public function getDropBoxReceivedFiles(): Collection
1994
    {
1995
        return $this->dropBoxReceivedFiles;
1996
    }
1997
1998
    /**
1999
     * @return Collection<int, SequenceValue>
2000
     */
2001
    public function getSequenceValues(): Collection
2002
    {
2003
        return $this->sequenceValues;
2004
    }
2005
2006
    /**
2007
     * @return Collection<int, TrackEExerciseConfirmation>
2008
     */
2009
    public function getTrackEExerciseConfirmations(): Collection
2010
    {
2011
        return $this->trackEExerciseConfirmations;
2012
    }
2013
2014
    /**
2015
     * @return Collection<int, TrackEAttempt>
2016
     */
2017
    public function getTrackEAccessCompleteList(): Collection
2018
    {
2019
        return $this->trackEAccessCompleteList;
2020
    }
2021
2022
    /**
2023
     * @return Collection<int, TrackEAttempt>
2024
     */
2025
    public function getTrackEAttempts(): Collection
2026
    {
2027
        return $this->trackEAttempts;
2028
    }
2029
2030
    /**
2031
     * @return Collection<int, TrackECourseAccess>
2032
     */
2033
    public function getTrackECourseAccess(): Collection
2034
    {
2035
        return $this->trackECourseAccess;
2036
    }
2037
2038
    /**
2039
     * @return Collection<int, UserCourseCategory>
2040
     */
2041
    public function getUserCourseCategories(): Collection
2042
    {
2043
        return $this->userCourseCategories;
2044
    }
2045
2046
    public function getCourseGroupsAsTutorFromCourse(Course $course): Collection
2047
    {
2048
        $criteria = Criteria::create();
2049
        $criteria->where(Criteria::expr()->eq('cId', $course->getId()));
2050
2051
        return $this->courseGroupsAsTutor->matching($criteria);
2052
    }
2053
2054
    /**
2055
     * Retrieves this user's related student sessions.
2056
     *
2057
     * @return Session[]
2058
     */
2059
    public function getSessionsAsStudent(): array
2060
    {
2061
        return $this->getSessions(Session::STUDENT);
2062
    }
2063
2064
    public function addSessionRelUser(SessionRelUser $sessionSubscription): static
2065
    {
2066
        $this->sessionsRelUser->add($sessionSubscription);
2067
2068
        return $this;
2069
    }
2070
2071
    public function isSkipResourceNode(): bool
2072
    {
2073
        return $this->skipResourceNode;
2074
    }
2075
2076
    public function setSkipResourceNode(bool $skipResourceNode): self
2077
    {
2078
        $this->skipResourceNode = $skipResourceNode;
2079
2080
        return $this;
2081
    }
2082
2083
    /**
2084
     * Retrieves this user's related DRH sessions.
2085
     *
2086
     * @return Session[]
2087
     */
2088
    public function getDRHSessions(): array
2089
    {
2090
        return $this->getSessions(Session::DRH);
2091
    }
2092
2093
    /**
2094
     * Get this user's related accessible sessions of a type, student by default.
2095
     *
2096
     * @return Session[]
2097
     */
2098
    public function getCurrentlyAccessibleSessions(int $relationType = Session::STUDENT): array
2099
    {
2100
        $sessions = [];
2101
        foreach ($this->getSessions($relationType) as $session) {
2102
            if ($session->isCurrentlyAccessible()) {
2103
                $sessions[] = $session;
2104
            }
2105
        }
2106
2107
        return $sessions;
2108
    }
2109
2110
    public function getResourceIdentifier(): int
2111
    {
2112
        return $this->id;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->id could return the type null which is incompatible with the type-hinted return integer. Consider adding an additional type-check to rule them out.
Loading history...
2113
    }
2114
2115
    public function getResourceName(): string
2116
    {
2117
        return $this->getUsername();
2118
    }
2119
2120
    public function setResourceName(string $name): void
2121
    {
2122
        $this->setUsername($name);
2123
    }
2124
2125
    public function setParent(AbstractResource $parent): void {}
2126
2127
    public function getDefaultIllustration(int $size): string
2128
    {
2129
        $size = empty($size) ? 32 : $size;
2130
2131
        return \sprintf('/img/icons/%s/unknown.png', $size);
2132
    }
2133
2134
    public function getAdmin(): ?Admin
2135
    {
2136
        return $this->admin;
2137
    }
2138
2139
    public function setAdmin(?Admin $admin): self
2140
    {
2141
        $this->admin = $admin;
2142
2143
        return $this;
2144
    }
2145
2146
    public function addUserAsAdmin(): self
2147
    {
2148
        if (null === $this->admin) {
2149
            $admin = new Admin();
2150
            $admin->setUser($this);
2151
            $this->setAdmin($admin);
2152
            $this->addRole('ROLE_ADMIN');
2153
        }
2154
2155
        return $this;
2156
    }
2157
2158
    public function getSessionsByStatusInCourseSubscription(int $status): ReadableCollection
2159
    {
2160
        $criteria = Criteria::create()->where(Criteria::expr()->eq('status', $status));
2161
2162
        /** @var ArrayCollection $subscriptions */
2163
        $subscriptions = $this->getSessionRelCourseRelUsers();
2164
2165
        return $subscriptions->matching($criteria)->map(
2166
            fn (SessionRelCourseRelUser $sessionRelCourseRelUser) => $sessionRelCourseRelUser->getSession()
2167
        );
2168
    }
2169
2170
    /**
2171
     * @return Collection<int, SessionRelCourseRelUser>
2172
     */
2173
    public function getSessionRelCourseRelUsers(): Collection
2174
    {
2175
        return $this->sessionRelCourseRelUsers;
2176
    }
2177
2178
    /**
2179
     * @param Collection<int, SessionRelCourseRelUser> $sessionRelCourseRelUsers
2180
     */
2181
    public function setSessionRelCourseRelUsers(Collection $sessionRelCourseRelUsers): self
2182
    {
2183
        $this->sessionRelCourseRelUsers = $sessionRelCourseRelUsers;
2184
2185
        return $this;
2186
    }
2187
2188
    public function getGender(): ?string
2189
    {
2190
        return $this->gender;
2191
    }
2192
2193
    public function setGender(?string $gender): self
2194
    {
2195
        $this->gender = $gender;
2196
2197
        return $this;
2198
    }
2199
2200
    /**
2201
     * @return Collection<int, CSurveyInvitation>
2202
     */
2203
    public function getSurveyInvitations(): Collection
2204
    {
2205
        return $this->surveyInvitations;
2206
    }
2207
2208
    public function setSurveyInvitations(Collection $surveyInvitations): self
2209
    {
2210
        $this->surveyInvitations = $surveyInvitations;
2211
2212
        return $this;
2213
    }
2214
2215
    public function getLogin(): string
2216
    {
2217
        return $this->username;
2218
    }
2219
2220
    public function setLogin(string $login): self
2221
    {
2222
        $this->username = $login;
2223
2224
        return $this;
2225
    }
2226
2227
    /**
2228
     * @return Collection<int, TrackELogin>
2229
     */
2230
    public function getLogins(): Collection
2231
    {
2232
        return $this->logins;
2233
    }
2234
2235
    public function setLogins(Collection $logins): self
2236
    {
2237
        $this->logins = $logins;
2238
2239
        return $this;
2240
    }
2241
2242
    /**
2243
     * @return Collection<int, MessageTag>
2244
     */
2245
    public function getMessageTags(): Collection
2246
    {
2247
        return $this->messageTags;
2248
    }
2249
2250
    /**
2251
     * @param Collection<int, MessageTag> $messageTags
2252
     */
2253
    public function setMessageTags(Collection $messageTags): self
2254
    {
2255
        $this->messageTags = $messageTags;
2256
2257
        return $this;
2258
    }
2259
2260
    /**
2261
     * @param null|UserCourseCategory $userCourseCategory the user_course_category
2262
     *
2263
     * @todo move in a repo
2264
     * Find the largest sort value in a given UserCourseCategory
2265
     * This method is used when we are moving a course to a different category
2266
     * and also when a user subscribes to courses (the new course is added at the end of the main category).
2267
     *
2268
     * Used to be implemented in global function \api_max_sort_value.
2269
     * Reimplemented using the ORM cache.
2270
     */
2271
    public function getMaxSortValue(?UserCourseCategory $userCourseCategory = null): int
2272
    {
2273
        $categoryCourses = $this->courses->matching(
2274
            Criteria::create()->where(Criteria::expr()->neq('relationType', COURSE_RELATION_TYPE_RRHH))->andWhere(
2275
                Criteria::expr()->eq('userCourseCat', $userCourseCategory)
2276
            )
2277
        );
2278
2279
        return $categoryCourses->isEmpty() ? 0 : max(
2280
            $categoryCourses->map(fn ($courseRelUser) => $courseRelUser->getSort())->toArray()
2281
        );
2282
    }
2283
2284
    public function hasFriendWithRelationType(self $friend, int $relationType): bool
2285
    {
2286
        $friends = $this->getFriendsByRelationType($relationType);
2287
2288
        return $friends->exists(fn (int $index, UserRelUser $userRelUser) => $userRelUser->getFriend() === $friend);
2289
    }
2290
2291
    public function isFriendWithMeByRelationType(self $friend, int $relationType): bool
2292
    {
2293
        return $this
2294
            ->getFriendsWithMeByRelationType($relationType)
2295
            ->exists(fn (int $index, UserRelUser $userRelUser) => $userRelUser->getUser() === $friend)
2296
        ;
2297
    }
2298
2299
    /**
2300
     * @param int $relationType Example: UserRelUser::USER_RELATION_TYPE_BOSS
2301
     *
2302
     * @return Collection<int, UserRelUser>
2303
     */
2304
    public function getFriendsByRelationType(int $relationType): Collection
2305
    {
2306
        $criteria = Criteria::create();
2307
        $criteria->where(Criteria::expr()->eq('relationType', $relationType));
2308
2309
        return $this->friends->matching($criteria);
2310
    }
2311
2312
    public function getFriendsWithMeByRelationType(int $relationType): Collection
2313
    {
2314
        $criteria = Criteria::create();
2315
        $criteria->where(Criteria::expr()->eq('relationType', $relationType));
2316
2317
        return $this->friendsWithMe->matching($criteria);
2318
    }
2319
2320
    public function getFriendsOfFriends(): array
2321
    {
2322
        $friendsOfFriends = [];
2323
        foreach ($this->getFriends() as $friendRelation) {
2324
            foreach ($friendRelation->getFriend()->getFriends() as $friendOfFriendRelation) {
2325
                $friendsOfFriends[] = $friendOfFriendRelation->getFriend();
2326
            }
2327
        }
2328
2329
        return $friendsOfFriends;
2330
    }
2331
2332
    /**
2333
     * @return Collection<int, SocialPost>
2334
     */
2335
    public function getSentSocialPosts(): Collection
2336
    {
2337
        return $this->sentSocialPosts;
2338
    }
2339
2340
    public function addSentSocialPost(SocialPost $sentSocialPost): self
2341
    {
2342
        if (!$this->sentSocialPosts->contains($sentSocialPost)) {
2343
            $this->sentSocialPosts[] = $sentSocialPost;
2344
            $sentSocialPost->setSender($this);
2345
        }
2346
2347
        return $this;
2348
    }
2349
2350
    /**
2351
     * @return Collection<int, SocialPost>
2352
     */
2353
    public function getReceivedSocialPosts(): Collection
2354
    {
2355
        return $this->receivedSocialPosts;
2356
    }
2357
2358
    public function addReceivedSocialPost(SocialPost $receivedSocialPost): self
2359
    {
2360
        if (!$this->receivedSocialPosts->contains($receivedSocialPost)) {
2361
            $this->receivedSocialPosts[] = $receivedSocialPost;
2362
            $receivedSocialPost->setUserReceiver($this);
2363
        }
2364
2365
        return $this;
2366
    }
2367
2368
    public function getSocialPostFeedbackBySocialPost(SocialPost $post): ?SocialPostFeedback
2369
    {
2370
        $filtered = $this->getSocialPostsFeedbacks()->filter(
2371
            fn (SocialPostFeedback $postFeedback) => $postFeedback->getSocialPost() === $post
2372
        );
2373
        if ($filtered->count() > 0) {
2374
            return $filtered->first();
2375
        }
2376
2377
        return null;
2378
    }
2379
2380
    /**
2381
     * @return Collection<int, SocialPostFeedback>
2382
     */
2383
    public function getSocialPostsFeedbacks(): Collection
2384
    {
2385
        return $this->socialPostsFeedbacks;
2386
    }
2387
2388
    public function addSocialPostFeedback(SocialPostFeedback $socialPostFeedback): self
2389
    {
2390
        if (!$this->socialPostsFeedbacks->contains($socialPostFeedback)) {
2391
            $this->socialPostsFeedbacks[] = $socialPostFeedback;
2392
            $socialPostFeedback->setUser($this);
2393
        }
2394
2395
        return $this;
2396
    }
2397
2398
    public function getSubscriptionToSession(Session $session): ?SessionRelUser
2399
    {
2400
        $criteria = Criteria::create();
2401
        $criteria->where(
2402
            Criteria::expr()->eq('session', $session)
2403
        );
2404
2405
        $match = $this->sessionsRelUser->matching($criteria);
2406
2407
        if ($match->count() > 0) {
2408
            return $match->first();
2409
        }
2410
2411
        return null;
2412
    }
2413
2414
    public function getFirstAccessToSession(Session $session): ?TrackECourseAccess
2415
    {
2416
        $criteria = Criteria::create()
2417
            ->where(
2418
                Criteria::expr()->eq('sessionId', $session->getId())
2419
            )
2420
        ;
2421
2422
        $match = $this->trackECourseAccess->matching($criteria);
2423
2424
        return $match->count() > 0 ? $match->first() : null;
2425
    }
2426
2427
    public function isCourseTutor(?Course $course = null, ?Session $session = null): bool
2428
    {
2429
        return $session?->hasCoachInCourseList($this) || $course?->getSubscriptionByUser($this)?->isTutor();
2430
    }
2431
2432
    /**
2433
     * @return Collection<int, UserAuthSource>
2434
     */
2435
    public function getAuthSources(): Collection
2436
    {
2437
        return $this->authSources;
2438
    }
2439
2440
    public function getAuthSourcesByUrl(AccessUrl $url): Collection
2441
    {
2442
        $criteria = Criteria::create();
2443
        $criteria->where(
2444
            Criteria::expr()->eq('url', $url)
2445
        );
2446
2447
        return $this->authSources->matching($criteria);
2448
    }
2449
2450
    /**
2451
     * @return array<int, string>
2452
     */
2453
    public function getAuthSourcesAuthentications(?AccessUrl $url = null): array
2454
    {
2455
        $authSources = $url ? $this->getAuthSourcesByUrl($url) : $this->getAuthSources();
2456
2457
        return $authSources->map(fn (UserAuthSource $authSource) => $authSource->getAuthentication())->toArray();
2458
    }
2459
2460
    public function addAuthSource(UserAuthSource $authSource): static
2461
    {
2462
        if (!$this->authSources->contains($authSource)) {
2463
            $this->authSources->add($authSource);
2464
            $authSource->setUser($this);
2465
        }
2466
2467
        return $this;
2468
    }
2469
2470
    public function addAuthSourceByAuthentication(string $authentication, AccessUrl $url): static
2471
    {
2472
        $authSource = (new UserAuthSource())
2473
            ->setAuthentication($authentication)
2474
            ->setUrl($url)
2475
        ;
2476
2477
        $this->addAuthSource($authSource);
2478
2479
        return $this;
2480
    }
2481
2482
    public function hasAuthSourceByAuthentication(string $authentication): bool
2483
    {
2484
        return $this->authSources
2485
            ->exists(fn (UserAuthSource $authSource) => $authSource->getAuthentication() === $authentication)
2486
        ;
2487
    }
2488
2489
    public function getAuthSourceByAuthentication(string $authentication): UserAuthSource
2490
    {
2491
        return $this->authSources->findFirst(
2492
            fn (UserAuthSource $authSource) => $authSource->getAuthentication() === $authentication
2493
        );
2494
    }
2495
2496
    public function removeAuthSources(): static
2497
    {
2498
        foreach ($this->authSources as $authSource) {
2499
            $authSource->setUser(null);
2500
        }
2501
2502
        $this->authSources = new ArrayCollection();
2503
2504
        return $this;
2505
    }
2506
2507
    public function removeAuthSource(UserAuthSource $authSource): static
2508
    {
2509
        if ($this->authSources->removeElement($authSource)) {
2510
            // set the owning side to null (unless already changed)
2511
            if ($authSource->getUser() === $this) {
2512
                $authSource->setUser(null);
2513
            }
2514
        }
2515
2516
        return $this;
2517
    }
2518
2519
    public function getMfaEnabled(): bool
2520
    {
2521
        return $this->mfaEnabled;
2522
    }
2523
2524
    public function setMfaEnabled(bool $mfaEnabled): self
2525
    {
2526
        $this->mfaEnabled = $mfaEnabled;
2527
2528
        return $this;
2529
    }
2530
2531
    public function getMfaService(): ?string
2532
    {
2533
        return $this->mfaService;
2534
    }
2535
2536
    public function setMfaService(?string $mfaService): self
2537
    {
2538
        $this->mfaService = $mfaService;
2539
2540
        return $this;
2541
    }
2542
2543
    public function getMfaSecret(): ?string
2544
    {
2545
        return $this->mfaSecret;
2546
    }
2547
2548
    public function setMfaSecret(?string $mfaSecret): self
2549
    {
2550
        $this->mfaSecret = $mfaSecret;
2551
2552
        return $this;
2553
    }
2554
2555
    public function getMfaBackupCodes(): ?string
2556
    {
2557
        return $this->mfaBackupCodes;
2558
    }
2559
2560
    public function setMfaBackupCodes(?string $mfaBackupCodes): self
2561
    {
2562
        $this->mfaBackupCodes = $mfaBackupCodes;
2563
2564
        return $this;
2565
    }
2566
2567
    public function getMfaLastUsed(): ?DateTimeInterface
2568
    {
2569
        return $this->mfaLastUsed;
2570
    }
2571
2572
    public function setMfaLastUsed(?DateTimeInterface $mfaLastUsed): self
2573
    {
2574
        $this->mfaLastUsed = $mfaLastUsed;
2575
2576
        return $this;
2577
    }
2578
}
2579