Passed
Push — master ( 8ee120...ab271d )
by Julito
09:45
created

UserRepository::findByStatus()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 5
c 0
b 0
f 0
nc 1
nop 3
dl 0
loc 9
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
/* For licensing terms, see /license.txt */
6
7
namespace Chamilo\CoreBundle\Repository\Node;
8
9
use Agenda;
10
use Chamilo\CoreBundle\Entity\AccessUrl;
11
use Chamilo\CoreBundle\Entity\Course;
12
use Chamilo\CoreBundle\Entity\GradebookCertificate;
13
use Chamilo\CoreBundle\Entity\GradebookResult;
14
use Chamilo\CoreBundle\Entity\Message;
15
use Chamilo\CoreBundle\Entity\ResourceNode;
16
use Chamilo\CoreBundle\Entity\Session;
17
use Chamilo\CoreBundle\Entity\SessionRelCourseRelUser;
18
use Chamilo\CoreBundle\Entity\SkillRelUserComment;
19
use Chamilo\CoreBundle\Entity\Ticket;
20
use Chamilo\CoreBundle\Entity\TicketMessage;
21
use Chamilo\CoreBundle\Entity\TrackEAccess;
22
use Chamilo\CoreBundle\Entity\TrackEAttempt;
23
use Chamilo\CoreBundle\Entity\TrackECourseAccess;
24
use Chamilo\CoreBundle\Entity\TrackEDefault;
25
use Chamilo\CoreBundle\Entity\TrackEDownloads;
26
use Chamilo\CoreBundle\Entity\TrackEExercises;
27
use Chamilo\CoreBundle\Entity\TrackELastaccess;
28
use Chamilo\CoreBundle\Entity\TrackELogin;
29
use Chamilo\CoreBundle\Entity\TrackEOnline;
30
use Chamilo\CoreBundle\Entity\TrackEUploads;
31
use Chamilo\CoreBundle\Entity\User;
32
use Chamilo\CoreBundle\Entity\UserCourseCategory;
33
use Chamilo\CoreBundle\Entity\UserRelCourseVote;
34
use Chamilo\CoreBundle\Repository\ResourceRepository;
35
use Chamilo\CourseBundle\Entity\CAttendanceResult;
36
use Chamilo\CourseBundle\Entity\CAttendanceSheet;
37
use Chamilo\CourseBundle\Entity\CBlogPost;
38
use Chamilo\CourseBundle\Entity\CDropboxFeedback;
39
use Chamilo\CourseBundle\Entity\CDropboxFile;
40
use Chamilo\CourseBundle\Entity\CDropboxPerson;
41
use Chamilo\CourseBundle\Entity\CForumPost;
42
use Chamilo\CourseBundle\Entity\CForumThread;
43
use Chamilo\CourseBundle\Entity\CGroupRelUser;
44
use Chamilo\CourseBundle\Entity\CLpView;
45
use Chamilo\CourseBundle\Entity\CNotebook;
46
use Chamilo\CourseBundle\Entity\CStudentPublication;
47
use Chamilo\CourseBundle\Entity\CStudentPublicationComment;
48
use Chamilo\CourseBundle\Entity\CSurveyAnswer;
49
use Chamilo\CourseBundle\Entity\CWiki;
50
use Datetime;
51
use Doctrine\Common\Collections\Collection;
52
use Doctrine\Common\Collections\Criteria;
53
use Doctrine\DBAL\Types\Types;
54
use Doctrine\ORM\Query\Expr\Join;
55
use Doctrine\ORM\QueryBuilder;
56
use Doctrine\Persistence\ManagerRegistry;
57
use Exception;
58
use SocialManager;
59
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
60
use Symfony\Component\Security\Core\Exception\UserNotFoundException;
61
use Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface;
62
use Symfony\Component\Security\Core\User\PasswordUpgraderInterface;
63
use Symfony\Component\Serializer\Encoder\JsonEncoder;
64
use Symfony\Component\Serializer\Normalizer\AbstractNormalizer;
65
use Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer;
66
use Symfony\Component\Serializer\Serializer;
67
68
class UserRepository extends ResourceRepository implements PasswordUpgraderInterface
69
{
70
    protected ?UserPasswordHasherInterface $hasher = null;
71
72
    public function __construct(ManagerRegistry $registry)
73
    {
74
        parent::__construct($registry, User::class);
75
    }
76
77
    public function loadUserByIdentifier(string $identifier): ?User
78
    {
79
        return $this->findOneBy([
80
            'username' => $identifier,
81
        ]);
82
    }
83
84
    public function setHasher(UserPasswordHasherInterface $hasher): void
85
    {
86
        $this->hasher = $hasher;
87
    }
88
89
    public function createUser(): User
90
    {
91
        return new User();
92
    }
93
94
    public function updateUser(User $user, bool $andFlush = true): void
95
    {
96
        $this->updateCanonicalFields($user);
97
        $this->updatePassword($user);
98
        $this->getEntityManager()->persist($user);
99
        if ($andFlush) {
100
            $this->getEntityManager()->flush();
101
        }
102
    }
103
104
    public function canonicalize(string $string): string
105
    {
106
        $encoding = mb_detect_encoding($string, mb_detect_order(), true);
107
108
        return $encoding
109
            ? mb_convert_case($string, MB_CASE_LOWER, $encoding)
110
            : mb_convert_case($string, MB_CASE_LOWER);
111
    }
112
113
    public function updateCanonicalFields(User $user): void
114
    {
115
        $user->setUsernameCanonical($this->canonicalize($user->getUsername()));
116
        $user->setEmailCanonical($this->canonicalize($user->getEmail()));
117
    }
118
119
    public function updatePassword(User $user): void
120
    {
121
        //UserPasswordEncoderInterface $passwordEncoder
122
        $password = (string) $user->getPlainPassword();
123
        if ('' !== $password) {
124
            $password = $this->hasher->hashPassword($user, $password);
0 ignored issues
show
Bug introduced by
The method hashPassword() does not exist on null. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

124
            /** @scrutinizer ignore-call */ 
125
            $password = $this->hasher->hashPassword($user, $password);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
125
            $user->setPassword($password);
126
            $user->eraseCredentials();
127
            // $encoder = $this->getEncoder($user);
128
            //$user->setPassword($encoder->encodePassword($password, $user->getSalt()));
129
            //$user->eraseCredentials();
130
        }
131
    }
132
133
    public function upgradePassword(PasswordAuthenticatedUserInterface $user, string $newHashedPassword): void
134
    {
135
        // this code is only an example; the exact code will depend on
136
        // your own application needs
137
        /** @var User $user */
138
        $user->setPassword($newHashedPassword);
139
        $this->getEntityManager()->persist($user);
140
        $this->getEntityManager()->flush();
141
    }
142
143
    public function getRootUser(): User
144
    {
145
        $qb = $this->createQueryBuilder('u');
146
        $qb
147
            ->innerJoin(
148
                'u.resourceNode',
149
                'r'
150
            )
151
        ;
152
        $qb
153
            ->where('r.creator = u')
154
            ->andWhere('r.parent IS NULL')
155
            ->getFirstResult()
156
        ;
157
158
        $rootUser = $qb->getQuery()->getSingleResult();
159
160
        if (null === $rootUser) {
161
            throw new UserNotFoundException('Root user not found');
162
        }
163
164
        return $rootUser;
165
    }
166
167
    public function deleteUser(User $user): void
168
    {
169
        $em = $this->getEntityManager();
170
        $type = $user->getResourceNode()->getResourceType();
171
        $rootUser = $this->getRootUser();
172
173
        // User children will be set to the root user.
174
        $criteria = Criteria::create()->where(Criteria::expr()->eq('resourceType', $type));
175
        $userNodeCreatedList = $user->getResourceNodes()->matching($criteria);
176
        /** @var ResourceNode $userCreated */
177
        foreach ($userNodeCreatedList as $userCreated) {
178
            $userCreated->setCreator($rootUser);
179
        }
180
181
        $em->remove($user->getResourceNode());
182
183
        foreach ($user->getGroups() as $group) {
184
            $user->removeGroup($group);
185
        }
186
187
        $em->remove($user);
188
        $em->flush();
189
    }
190
191
    public function addUserToResourceNode(int $userId, int $creatorId): ResourceNode
192
    {
193
        /** @var User $user */
194
        $user = $this->find($userId);
195
        $creator = $this->find($creatorId);
196
197
        $resourceNode = new ResourceNode();
198
        $resourceNode
199
            ->setTitle($user->getUsername())
200
            ->setCreator($creator)
201
            ->setResourceType($this->getResourceType())
202
            //->setParent($resourceNode)
203
        ;
204
205
        $user->setResourceNode($resourceNode);
206
207
        $this->getEntityManager()->persist($resourceNode);
208
        $this->getEntityManager()->persist($user);
209
210
        return $resourceNode;
211
    }
212
213
    public function addRoleListQueryBuilder(array $roleList, QueryBuilder $qb = null): QueryBuilder
214
    {
215
        $qb = $this->getOrCreateQueryBuilder($qb, 'u');
216
        if (!empty($roleList)) {
217
            $qb
218
                ->andWhere('u.roles IN (:roles)')
219
                ->setParameter('roles', $roleList, Types::ARRAY)
220
            ;
221
        }
222
223
        return $qb;
224
    }
225
226
    public function findByUsername(string $username): ?User
227
    {
228
        $user = $this->findOneBy([
229
            'username' => $username,
230
        ]);
231
232
        if (null === $user) {
233
            throw new UserNotFoundException(sprintf("User with id '%s' not found.", $username));
234
        }
235
236
        return $user;
237
    }
238
239
    /**
240
     * Get a filtered list of user by role and (optionally) access url.
241
     *
242
     * @param string $keyword     The query to filter
243
     * @param int    $accessUrlId The access URL ID
244
     *
245
     * @return User[]
246
     */
247
    public function findByRole(string $role, string $keyword, int $accessUrlId = 0)
248
    {
249
        $qb = $this->createQueryBuilder('u');
250
251
        $this->addAccessUrlQueryBuilder($accessUrlId, $qb);
252
        $this->addRoleQueryBuilder($role, $qb);
253
        $this->addSearchByKeywordQueryBuilder($keyword, $qb);
254
255
        return $qb->getQuery()->getResult();
256
    }
257
258
    /**
259
     * Get course user relationship based in the course_rel_user table.
260
     *
261
     * @return Course[]
262
     */
263
    public function getCourses(User $user, AccessUrl $url, int $status, string $keyword = '')
264
    {
265
        $qb = $this->createQueryBuilder('u');
266
267
        $qb
268
            //->select('DISTINCT course')
269
            ->innerJoin('u.courses', 'courseRelUser')
270
            ->innerJoin('courseRelUser.course', 'course')
271
            ->innerJoin('course.urls', 'accessUrlRelCourse')
272
            ->innerJoin('accessUrlRelCourse.url', 'url')
273
            ->where('url = :url')
274
            ->andWhere('courseRelUser.user = :user')
275
            ->andWhere('courseRelUser.status = :status')
276
            ->setParameters(
277
                [
278
                    'user' => $user,
279
                    'url' => $url,
280
                    'status' => $status,
281
                ]
282
            )
283
        //    ->addSelect('courseRelUser')
284
        ;
285
286
        if (!empty($keyword)) {
287
            $qb
288
                ->andWhere('course.title like = :keyword OR course.code like = :keyword')
289
                ->setParameter('keyword', $keyword)
290
            ;
291
        }
292
293
        $qb->orderBy('course.title', Criteria::DESC);
294
295
        $query = $qb->getQuery();
296
297
        return $query->getResult();
298
    }
299
300
    /*
301
    public function getTeachers()
302
    {
303
        $queryBuilder = $this->repository->createQueryBuilder('u');
304
305
        // Selecting course info.
306
        $queryBuilder
307
            ->select('u')
308
            ->where('u.groups.id = :groupId')
309
            ->setParameter('groupId', 1);
310
311
        $query = $queryBuilder->getQuery();
312
313
        return $query->execute();
314
    }*/
315
316
    /*public function getUsers($group)
317
    {
318
        $queryBuilder = $this->repository->createQueryBuilder('u');
319
320
        // Selecting course info.
321
        $queryBuilder
322
            ->select('u')
323
            ->where('u.groups = :groupId')
324
            ->setParameter('groupId', $group);
325
326
        $query = $queryBuilder->getQuery();
327
328
        return $query->execute();
329
    }*/
330
331
    /**
332
     * Get the coaches for a course within a session.
333
     *
334
     * @param Session $session The session
335
     * @param Course  $course  The course
336
     */
337
    public function getCoachesForSessionCourse(Session $session, Course $course): Collection
338
    {
339
        $qb = $this->createQueryBuilder('u');
340
341
        $qb->select('u')
342
            ->innerJoin(
343
                'ChamiloCoreBundle:SessionRelCourseRelUser',
344
                'scu',
345
                Join::WITH,
346
                'scu.user = u'
347
            )
348
            ->where(
349
                $qb->expr()->andX(
350
                    $qb->expr()->eq('scu.session', $session->getId()),
351
                    $qb->expr()->eq('scu.course', $course->getId()),
352
                    $qb->expr()->eq('scu.status', SessionRelCourseRelUser::STATUS_COURSE_COACH)
353
                )
354
            )
355
        ;
356
357
        return $qb->getQuery()->getResult();
358
    }
359
360
    /**
361
     * Get course user relationship based in the course_rel_user table.
362
     *
363
     * @return array
364
     */
365
    /*public function getCourses(User $user)
366
    {
367
        $qb = $this->createQueryBuilder('user');
368
369
        // Selecting course info.
370
        $qb->select('c');
371
372
        // Loading User.
373
        //$qb->from('Chamilo\CoreBundle\Entity\User', 'u');
374
375
        // Selecting course
376
        $qb->innerJoin('Chamilo\CoreBundle\Entity\Course', 'c');
377
378
        //@todo check app settings
379
        //$qb->add('orderBy', 'u.lastname ASC');
380
381
        $wherePart = $qb->expr()->andx();
382
383
        // Get only users subscribed to this course
384
        $wherePart->add($qb->expr()->eq('user.userId', $user->getUserId()));
385
386
        $qb->where($wherePart);
387
        $query = $qb->getQuery();
388
389
        return $query->execute();
390
    }
391
392
    public function getTeachers()
393
    {
394
        $qb = $this->createQueryBuilder('u');
395
396
        // Selecting course info.
397
        $qb
398
            ->select('u')
399
            ->where('u.groups.id = :groupId')
400
            ->setParameter('groupId', 1);
401
402
        $query = $qb->getQuery();
403
404
        return $query->execute();
405
    }*/
406
407
    /*public function getUsers($group)
408
    {
409
        $qb = $this->createQueryBuilder('u');
410
411
        // Selecting course info.
412
        $qb
413
            ->select('u')
414
            ->where('u.groups = :groupId')
415
            ->setParameter('groupId', $group);
416
417
        $query = $qb->getQuery();
418
419
        return $query->execute();
420
    }*/
421
422
    /**
423
     * Get the sessions admins for a user.
424
     *
425
     * @return array
426
     */
427
    public function getSessionAdmins(User $user)
428
    {
429
        $qb = $this->createQueryBuilder('u');
430
        $qb
431
            ->distinct()
432
            ->innerJoin(
433
                'ChamiloCoreBundle:SessionRelUser',
434
                'su',
435
                Join::WITH,
436
                'u = su.user'
437
            )
438
            ->innerJoin(
439
                'ChamiloCoreBundle:SessionRelCourseRelUser',
440
                'scu',
441
                Join::WITH,
442
                'su.session = scu.session'
443
            )
444
            ->where(
445
                $qb->expr()->eq('scu.user', $user->getId())
446
            )
447
            ->andWhere(
448
                $qb->expr()->eq('su.relationType', SESSION_RELATION_TYPE_RRHH)
449
            )
450
        ;
451
452
        return $qb->getQuery()->getResult();
453
    }
454
455
    /**
456
     * Get the student bosses for a user.
457
     *
458
     * @return array
459
     */
460
    public function getStudentBosses(User $user)
461
    {
462
        $qb = $this->createQueryBuilder('u');
463
        $qb
464
            ->distinct()
465
            ->innerJoin(
466
                'ChamiloCoreBundle:UserRelUser',
467
                'uu',
468
                Join::WITH,
469
                'u.id = uu.friendUserId'
470
            )
471
            ->where(
472
                $qb->expr()->eq('uu.relationType', USER_RELATION_TYPE_BOSS)
473
            )
474
            ->andWhere(
475
                $qb->expr()->eq('uu.userId', $user->getId())
476
            )
477
        ;
478
479
        return $qb->getQuery()->getResult();
480
    }
481
482
    /**
483
     * Get number of users in URL.
484
     *
485
     * @return int
486
     */
487
    public function getCountUsersByUrl(AccessUrl $url)
488
    {
489
        return $this->createQueryBuilder('a')
490
            ->select('COUNT(a)')
491
            ->innerJoin('a.portals', 'u')
492
            ->where('u.portal = :u')
493
            ->setParameters([
494
                'u' => $url,
495
            ])
496
            ->getQuery()
497
            ->getSingleScalarResult()
498
        ;
499
    }
500
501
    /**
502
     * Get number of users in URL.
503
     *
504
     * @return int
505
     */
506
    public function getCountTeachersByUrl(AccessUrl $url)
507
    {
508
        $qb = $this->createQueryBuilder('a');
509
510
        return $qb
511
            ->select('COUNT(a)')
512
            ->innerJoin('a.portals', 'u')
513
            ->where('u.portal = :u')
514
            ->andWhere($qb->expr()->in('a.roles', ['ROLE_TEACHER']))
515
            ->setParameters([
516
                'u' => $url,
517
            ])
518
            ->getQuery()
519
            ->getSingleScalarResult()
520
        ;
521
    }
522
523
    /**
524
     * Find potential users to send a message.
525
     *
526
     * @todo remove  api_is_platform_admin
527
     *
528
     * @param int    $currentUserId The current user ID
529
     * @param string $searchFilter  Optional. The search text to filter the user list
530
     * @param int    $limit         Optional. Sets the maximum number of results to retrieve
531
     *
532
     * @return User[]
533
     */
534
    public function findUsersToSendMessage(int $currentUserId, string $searchFilter = null, int $limit = 10)
535
    {
536
        $allowSendMessageToAllUsers = api_get_setting('allow_send_message_to_all_platform_users');
537
        $accessUrlId = api_get_multiple_access_url() ? api_get_current_access_url_id() : 1;
538
539
        $messageTool = 'true' === api_get_setting('allow_message_tool');
540
        if (!$messageTool) {
541
            return [];
542
        }
543
544
        $qb = $this->createQueryBuilder('u');
545
        $this->addActiveAndNotAnonUserQueryBuilder($qb);
546
        $this->addAccessUrlQueryBuilder($accessUrlId, $qb);
547
548
        $dql = null;
549
        if ('true' === api_get_setting('allow_social_tool')) {
550
            // All users
551
            if ('true' === $allowSendMessageToAllUsers || api_is_platform_admin()) {
552
                $this->addNotCurrentUserQueryBuilder($currentUserId, $qb);
553
            /*$dql = "SELECT DISTINCT U
554
                    FROM ChamiloCoreBundle:User U
555
                    LEFT JOIN ChamiloCoreBundle:AccessUrlRelUser R
556
                    WITH U = R.user
557
                    WHERE
558
                        U.active = 1 AND
559
                        U.status != 6  AND
560
                        U.id != {$currentUserId} AND
561
                        R.url = {$accessUrlId}";*/
562
            } else {
563
                $this->addOnlyMyFriendsQueryBuilder($currentUserId, $qb);
564
                /*$dql = 'SELECT DISTINCT U
565
                        FROM ChamiloCoreBundle:AccessUrlRelUser R, ChamiloCoreBundle:UserRelUser UF
566
                        INNER JOIN ChamiloCoreBundle:User AS U
567
                        WITH UF.friendUserId = U
568
                        WHERE
569
                            U.active = 1 AND
570
                            U.status != 6 AND
571
                            UF.relationType NOT IN('.USER_RELATION_TYPE_DELETED.', '.USER_RELATION_TYPE_RRHH.") AND
572
                            UF.user = {$currentUserId} AND
573
                            UF.friendUserId != {$currentUserId} AND
574
                            U = R.user AND
575
                            R.url = {$accessUrlId}";*/
576
            }
577
        } else {
578
            if ('true' === $allowSendMessageToAllUsers) {
579
                $this->addNotCurrentUserQueryBuilder($currentUserId, $qb);
580
            } else {
581
                return [];
582
            }
583
584
            /*else {
585
                $time_limit = (int) api_get_setting('time_limit_whosonline');
586
                $online_time = time() - ($time_limit * 60);
587
                $limit_date = api_get_utc_datetime($online_time);
588
                $dql = "SELECT DISTINCT U
589
                        FROM ChamiloCoreBundle:User U
590
                        INNER JOIN ChamiloCoreBundle:TrackEOnline T
591
                        WITH U.id = T.loginUserId
592
                        WHERE
593
                          U.active = 1 AND
594
                          T.loginDate >= '".$limit_date."'";
595
            }*/
596
        }
597
598
        if (!empty($searchFilter)) {
599
            $this->addSearchByKeywordQueryBuilder($searchFilter, $qb);
600
        }
601
602
        return $qb->getQuery()->getResult();
603
    }
604
605
    /**
606
     * Get the list of HRM who have assigned this user.
607
     *
608
     * @return User[]
609
     */
610
    public function getAssignedHrmUserList(int $userId, int $urlId)
611
    {
612
        $qb = $this->createQueryBuilder('u');
613
        $this->addAccessUrlQueryBuilder($urlId, $qb);
614
        $this->addActiveAndNotAnonUserQueryBuilder($qb);
615
        $this->addUserRelUserQueryBuilder($userId, USER_RELATION_TYPE_RRHH, $qb);
616
617
        return $qb->getQuery()->getResult();
618
    }
619
620
    /**
621
     * Serialize the whole entity to an array.
622
     *
623
     * @param array $substitutionTerms Substitute terms for some elements
624
     *
625
     * @return string
626
     */
627
    public function getPersonalDataToJson(int $userId, array $substitutionTerms)
628
    {
629
        $em = $this->getEntityManager();
630
        $dateFormat = Datetime::ATOM;
631
632
        /** @var User $user */
633
        $user = $this->find($userId);
634
635
        $user->setPassword($substitutionTerms['password']);
636
        $user->setSalt($substitutionTerms['salt']);
637
638
        $noDataLabel = $substitutionTerms['empty'];
639
640
        // Dummy content
641
        $user->setDateOfBirth(null);
642
        //$user->setBiography($noDataLabel);
643
        /*$user->setFacebookData($noDataLabel);
644
        $user->setFacebookName($noDataLabel);
645
        $user->setFacebookUid($noDataLabel);*/
646
        //$user->setImageName($noDataLabel);
647
        //$user->setTwoStepVerificationCode($noDataLabel);
648
        //$user->setGender($noDataLabel);
649
        /*$user->setGplusData($noDataLabel);
650
        $user->setGplusName($noDataLabel);
651
        $user->setGplusUid($noDataLabel);*/
652
        $user->setLocale($noDataLabel);
653
        $user->setTimezone($noDataLabel);
654
        /*$user->setTwitterData($noDataLabel);
655
        $user->setTwitterName($noDataLabel);
656
        $user->setTwitterUid($noDataLabel);*/
657
        $user->setWebsite($noDataLabel);
658
        //$user->setToken($noDataLabel);
659
660
        $friends = SocialManager::get_friends($userId);
661
        $friendList = [];
662
        if (!empty($friends)) {
663
            foreach ($friends as $friend) {
664
                $friendList[] = $friend['user_info']['complete_name'];
665
            }
666
        }
667
668
        $agenda = new Agenda('personal');
669
        $events = $agenda->getEvents(0, 0, 0, 0, $userId, 'array');
670
        $eventList = [];
671
        if (!empty($events)) {
672
            foreach ($events as $event) {
673
                $eventList[] = $event['title'].' '.$event['start_date_localtime'].' / '.$event['end_date_localtime'];
674
            }
675
        }
676
677
        // GradebookCertificate
678
        $result = $em->getRepository(GradebookCertificate::class)->findBy([
679
            'user' => $userId,
680
        ]);
681
        $gradebookCertificate = [];
682
        /** @var GradebookCertificate $item */
683
        foreach ($result as $item) {
684
            $createdAt = $item->getCreatedAt()->format($dateFormat);
685
            $list = [
686
                'Score: '.$item->getScoreCertificate(),
687
                'Path: '.$item->getPathCertificate(),
688
                'Created at: '.$createdAt,
689
            ];
690
            $gradebookCertificate[] = implode(', ', $list);
691
        }
692
693
        // TrackEExercises
694
        $criteria = [
695
            'exeUserId' => $userId,
696
        ];
697
        $result = $em->getRepository(TrackEExercises::class)->findBy($criteria);
698
        $trackEExercises = [];
699
        /** @var TrackEExercises $item */
700
        foreach ($result as $item) {
701
            $date = $item->getExeDate()->format($dateFormat);
702
            $list = [
703
                'IP: '.$item->getUserIp(),
704
                'Start: '.$date,
705
                'Status: '.$item->getStatus(),
706
                // 'Result: '.$item->getExeResult(),
707
                // 'Weighting: '.$item->getExeWeighting(),
708
            ];
709
            $trackEExercises[] = implode(', ', $list);
710
        }
711
712
        // TrackEAttempt
713
        $criteria = [
714
            'user' => $userId,
715
        ];
716
        $result = $em->getRepository(TrackEAttempt::class)->findBy($criteria);
717
        $trackEAttempt = [];
718
        /** @var TrackEAttempt $item */
719
        foreach ($result as $item) {
720
            $date = $item->getTms()->format($dateFormat);
721
            $list = [
722
                'Attempt #'.$item->getExeId(),
723
                'Course # '.$item->getCourse()->getCode(),
724
                //'Answer: '.$item->getAnswer(),
725
                'Session #'.$item->getSessionId(),
726
                //'Marks: '.$item->getMarks(),
727
                'Position: '.$item->getPosition(),
728
                'Date: '.$date,
729
            ];
730
            $trackEAttempt[] = implode(', ', $list);
731
        }
732
733
        // TrackECourseAccess
734
        $criteria = [
735
            'user' => $userId,
736
        ];
737
        $result = $em->getRepository(TrackECourseAccess::class)->findBy($criteria);
738
        $trackECourseAccessList = [];
739
        /** @var TrackECourseAccess $item */
740
        foreach ($result as $item) {
741
            $startDate = $item->getLoginCourseDate()->format($dateFormat);
742
            $endDate = null !== $item->getLogoutCourseDate() ? $item->getLogoutCourseDate()->format($dateFormat) : '';
743
            $list = [
744
                'IP: '.$item->getUserIp(),
745
                'Start: '.$startDate,
746
                'End: '.$endDate,
747
            ];
748
            $trackECourseAccessList[] = implode(', ', $list);
749
        }
750
751
        $checkEntities = [
752
            TrackELogin::class => 'loginUserId',
753
            TrackEAccess::class => 'accessUserId',
754
            TrackEOnline::class => 'loginUserId',
755
            TrackEDefault::class => 'defaultUserId',
756
            TrackELastaccess::class => 'accessUserId',
757
            TrackEUploads::class => 'uploadUserId',
758
            GradebookResult::class => 'user',
759
            TrackEDownloads::class => 'downUserId',
760
        ];
761
762
        $maxResults = 1000;
763
        $trackResults = [];
764
        foreach ($checkEntities as $entity => $field) {
765
            $qb = $em->createQueryBuilder();
766
            $qb->select($qb->expr()->count('l'))
767
                ->from($entity, 'l')
768
                ->where("l.$field = :login")
769
                ->setParameter('login', $userId)
770
            ;
771
            $query = $qb->getQuery();
772
            $count = $query->getSingleScalarResult();
773
774
            if ($count > $maxResults) {
775
                $qb = $em->getRepository($entity)->createQueryBuilder('l');
776
                $qb
777
                    ->select('l')
778
                    ->where("l.$field = :login")
779
                    ->setParameter('login', $userId)
780
                ;
781
                $qb
782
                    ->setFirstResult(0)
783
                    ->setMaxResults($maxResults)
784
                ;
785
                $result = $qb->getQuery()->getResult();
786
            } else {
787
                $criteria = [
788
                    $field => $userId,
789
                ];
790
                $result = $em->getRepository($entity)->findBy($criteria);
791
            }
792
            $trackResults[$entity] = $result;
793
        }
794
795
        $trackELoginList = [];
796
        /** @var TrackELogin $item */
797
        foreach ($trackResults[TrackELogin::class] as $item) {
798
            $startDate = $item->getLoginDate()->format($dateFormat);
799
            $endDate = null !== $item->getLogoutDate() ? $item->getLogoutDate()->format($dateFormat) : '';
800
            $list = [
801
                'IP: '.$item->getUserIp(),
802
                'Start: '.$startDate,
803
                'End: '.$endDate,
804
            ];
805
            $trackELoginList[] = implode(', ', $list);
806
        }
807
808
        // TrackEAccess
809
        $trackEAccessList = [];
810
        /** @var TrackEAccess $item */
811
        foreach ($trackResults[TrackEAccess::class] as $item) {
812
            $date = $item->getAccessDate()->format($dateFormat);
813
            $list = [
814
                'IP: '.$item->getUserIp(),
815
                'Tool: '.$item->getAccessTool(),
816
                'End: '.$date,
817
            ];
818
            $trackEAccessList[] = implode(', ', $list);
819
        }
820
821
        // TrackEOnline
822
        $trackEOnlineList = [];
823
        /** @var TrackEOnline $item */
824
        foreach ($trackResults[TrackEOnline::class] as $item) {
825
            $date = $item->getLoginDate()->format($dateFormat);
826
            $list = [
827
                'IP: '.$item->getUserIp(),
828
                'Login date: '.$date,
829
                'Course # '.$item->getCId(),
830
                'Session # '.$item->getSessionId(),
831
            ];
832
            $trackEOnlineList[] = implode(', ', $list);
833
        }
834
835
        // TrackEDefault
836
        $trackEDefault = [];
837
        /** @var TrackEDefault $item */
838
        foreach ($trackResults[TrackEDefault::class] as $item) {
839
            $date = $item->getDefaultDate()->format($dateFormat);
840
            $list = [
841
                'Type: '.$item->getDefaultEventType(),
842
                'Value: '.$item->getDefaultValue(),
843
                'Value type: '.$item->getDefaultValueType(),
844
                'Date: '.$date,
845
                'Course #'.$item->getCId(),
846
                'Session # '.$item->getSessionId(),
847
            ];
848
            $trackEDefault[] = implode(', ', $list);
849
        }
850
851
        // TrackELastaccess
852
        $trackELastaccess = [];
853
        /** @var TrackELastaccess $item */
854
        foreach ($trackResults[TrackELastaccess::class] as $item) {
855
            $date = $item->getAccessDate()->format($dateFormat);
856
            $list = [
857
                'Course #'.$item->getCId(),
858
                'Session # '.$item->getAccessSessionId(),
859
                'Tool: '.$item->getAccessTool(),
860
                'Access date: '.$date,
861
            ];
862
            $trackELastaccess[] = implode(', ', $list);
863
        }
864
865
        // TrackEUploads
866
        $trackEUploads = [];
867
        /** @var TrackEUploads $item */
868
        foreach ($trackResults[TrackEUploads::class] as $item) {
869
            $date = $item->getUploadDate()->format($dateFormat);
870
            $list = [
871
                'Course #'.$item->getCId(),
872
                'Uploaded at: '.$date,
873
                'Upload id # '.$item->getUploadId(),
874
            ];
875
            $trackEUploads[] = implode(', ', $list);
876
        }
877
878
        $gradebookResult = [];
879
        /** @var GradebookResult $item */
880
        foreach ($trackResults[GradebookResult::class] as $item) {
881
            $date = $item->getCreatedAt()->format($dateFormat);
882
            $list = [
883
                'Evaluation id# '.$item->getEvaluation()->getId(),
884
                //'Score: '.$item->getScore(),
885
                'Creation date: '.$date,
886
            ];
887
            $gradebookResult[] = implode(', ', $list);
888
        }
889
890
        $trackEDownloads = [];
891
        /** @var TrackEDownloads $item */
892
        foreach ($trackResults[TrackEDownloads::class] as $item) {
893
            $date = $item->getDownDate()->format($dateFormat);
894
            $list = [
895
                'File: '.$item->getDownDocPath(),
896
                'Download at: '.$date,
897
            ];
898
            $trackEDownloads[] = implode(', ', $list);
899
        }
900
901
        // UserCourseCategory
902
        $criteria = [
903
            'user' => $userId,
904
        ];
905
        $result = $em->getRepository(UserCourseCategory::class)->findBy($criteria);
906
        $userCourseCategory = [];
907
        /** @var UserCourseCategory $item */
908
        foreach ($result as $item) {
909
            $list = [
910
                'Title: '.$item->getTitle(),
911
            ];
912
            $userCourseCategory[] = implode(', ', $list);
913
        }
914
915
        // Forum
916
        $criteria = [
917
            'user' => $userId,
918
        ];
919
        $result = $em->getRepository(CForumPost::class)->findBy($criteria);
920
        $cForumPostList = [];
921
        /** @var CForumPost $item */
922
        foreach ($result as $item) {
923
            $date = $item->getPostDate()->format($dateFormat);
924
            $list = [
925
                'Title: '.$item->getPostTitle(),
926
                'Creation date: '.$date,
927
            ];
928
            $cForumPostList[] = implode(', ', $list);
929
        }
930
931
        // CForumThread
932
        $criteria = [
933
            'user' => $userId,
934
        ];
935
        $result = $em->getRepository(CForumThread::class)->findBy($criteria);
936
        $cForumThreadList = [];
937
        /** @var CForumThread $item */
938
        foreach ($result as $item) {
939
            $date = $item->getThreadDate()->format($dateFormat);
940
            $list = [
941
                'Title: '.$item->getThreadTitle(),
942
                'Creation date: '.$date,
943
            ];
944
            $cForumThreadList[] = implode(', ', $list);
945
        }
946
947
        // CForumAttachment
948
        /*$criteria = [
949
            'threadPosterId' => $userId,
950
        ];
951
        $result = $em->getRepository('ChamiloCourseBundle:CForumAttachment')->findBy($criteria);
952
        $cForumThreadList = [];
953
        * @var CForumThread $item
954
        foreach ($result as $item) {
955
            $list = [
956
                'Title: '.$item->getThreadTitle(),
957
                'Creation date: '.$item->getThreadDate()->format($dateFormat),
958
            ];
959
            $cForumThreadList[] = implode(', ', $list);
960
        }*/
961
962
        // cGroupRelUser
963
        $criteria = [
964
            'user' => $userId,
965
        ];
966
        $result = $em->getRepository(CGroupRelUser::class)->findBy($criteria);
967
        $cGroupRelUser = [];
968
        /** @var CGroupRelUser $item */
969
        foreach ($result as $item) {
970
            $list = [
971
                'Course # '.$item->getCId(),
972
                'Group #'.$item->getGroup()->getIid(),
973
                'Role: '.$item->getStatus(),
974
            ];
975
            $cGroupRelUser[] = implode(', ', $list);
976
        }
977
978
        // CAttendanceSheet
979
        $criteria = [
980
            'user' => $userId,
981
        ];
982
        $result = $em->getRepository(CAttendanceSheet::class)->findBy($criteria);
983
        $cAttendanceSheetList = [];
984
        /** @var CAttendanceSheet $item */
985
        foreach ($result as $item) {
986
            $list = [
987
                'Presence: '.$item->getPresence(),
988
                'Calendar id: '.$item->getAttendanceCalendar()->getIid(),
989
            ];
990
            $cAttendanceSheetList[] = implode(', ', $list);
991
        }
992
993
        // CBlogPost
994
        $criteria = [
995
            'authorId' => $userId,
996
        ];
997
        $result = $em->getRepository(CBlogPost::class)->findBy($criteria);
998
        $cBlog = [];
999
        /** @var CBlogPost $item */
1000
        foreach ($result as $item) {
1001
            $date = $item->getDateCreation()->format($dateFormat);
1002
            $list = [
1003
                'Title: '.$item->getTitle(),
1004
                'Date: '.$date,
1005
            ];
1006
            $cBlog[] = implode(', ', $list);
1007
        }
1008
1009
        // CAttendanceResult
1010
        $criteria = [
1011
            'user' => $userId,
1012
        ];
1013
        $result = $em->getRepository(CAttendanceResult::class)->findBy($criteria);
1014
        $cAttendanceResult = [];
1015
        /** @var CAttendanceResult $item */
1016
        foreach ($result as $item) {
1017
            $list = [
1018
                'Score : '.$item->getScore(),
1019
                'Calendar id: '.$item->getAttendance()->getIid(),
1020
            ];
1021
            $cAttendanceResult[] = implode(', ', $list);
1022
        }
1023
1024
        // Message
1025
        $criteria = [
1026
            'userSender' => $userId,
1027
        ];
1028
        $result = $em->getRepository(Message::class)->findBy($criteria);
1029
        $messageList = [];
1030
        /** @var Message $item */
1031
        foreach ($result as $item) {
1032
            $date = $item->getSendDate()->format($dateFormat);
1033
            $userName = '';
1034
            if ($item->getUserReceiver()) {
1035
                $userName = $item->getUserReceiver()->getUsername();
1036
            }
1037
            $list = [
1038
                'Title: '.$item->getTitle(),
1039
                'Sent date: '.$date,
1040
                'To user: '.$userName,
1041
                'Status'.$item->getMsgStatus(),
1042
            ];
1043
            $messageList[] = implode(', ', $list);
1044
        }
1045
1046
        // CSurveyAnswer
1047
        $criteria = [
1048
            'user' => $userId,
1049
        ];
1050
        $result = $em->getRepository(CSurveyAnswer::class)->findBy($criteria);
1051
        $cSurveyAnswer = [];
1052
        /** @var CSurveyAnswer $item */
1053
        foreach ($result as $item) {
1054
            $list = [
1055
                'Answer # '.$item->getIid(),
1056
                'Value: '.$item->getValue(),
1057
            ];
1058
            $cSurveyAnswer[] = implode(', ', $list);
1059
        }
1060
1061
        // CDropboxFile
1062
        $criteria = [
1063
            'uploaderId' => $userId,
1064
        ];
1065
        $result = $em->getRepository(CDropboxFile::class)->findBy($criteria);
1066
        $cDropboxFile = [];
1067
        /** @var CDropboxFile $item */
1068
        foreach ($result as $item) {
1069
            $date = $item->getUploadDate()->format($dateFormat);
1070
            $list = [
1071
                'Title: '.$item->getTitle(),
1072
                'Uploaded date: '.$date,
1073
                'File: '.$item->getFilename(),
1074
            ];
1075
            $cDropboxFile[] = implode(', ', $list);
1076
        }
1077
1078
        // CDropboxPerson
1079
        $criteria = [
1080
            'userId' => $userId,
1081
        ];
1082
        $result = $em->getRepository(CDropboxPerson::class)->findBy($criteria);
1083
        $cDropboxPerson = [];
1084
        /** @var CDropboxPerson $item */
1085
        foreach ($result as $item) {
1086
            $list = [
1087
                'File #'.$item->getFileId(),
1088
                'Course #'.$item->getCId(),
1089
            ];
1090
            $cDropboxPerson[] = implode(', ', $list);
1091
        }
1092
1093
        // CDropboxPerson
1094
        $criteria = [
1095
            'authorUserId' => $userId,
1096
        ];
1097
        $result = $em->getRepository(CDropboxFeedback::class)->findBy($criteria);
1098
        $cDropboxFeedback = [];
1099
        /** @var CDropboxFeedback $item */
1100
        foreach ($result as $item) {
1101
            $date = $item->getFeedbackDate()->format($dateFormat);
1102
            $list = [
1103
                'File #'.$item->getFileId(),
1104
                'Feedback: '.$item->getFeedback(),
1105
                'Date: '.$date,
1106
            ];
1107
            $cDropboxFeedback[] = implode(', ', $list);
1108
        }
1109
1110
        // CNotebook
1111
        $criteria = [
1112
            'user' => $userId,
1113
        ];
1114
        $result = $em->getRepository(CNotebook::class)->findBy($criteria);
1115
        $cNotebook = [];
1116
        /** @var CNotebook $item */
1117
        foreach ($result as $item) {
1118
            $date = $item->getUpdateDate()->format($dateFormat);
1119
            $list = [
1120
                'Title: '.$item->getTitle(),
1121
                'Date: '.$date,
1122
            ];
1123
            $cNotebook[] = implode(', ', $list);
1124
        }
1125
1126
        // CLpView
1127
        $criteria = [
1128
            'user' => $userId,
1129
        ];
1130
        $result = $em->getRepository(CLpView::class)->findBy($criteria);
1131
        $cLpView = [];
1132
        /** @var CLpView $item */
1133
        foreach ($result as $item) {
1134
            $list = [
1135
                //'Id #'.$item->getId(),
1136
                'LP #'.$item->getLp()->getIid(),
1137
                'Progress: '.$item->getProgress(),
1138
                //'Course #'.$item->getCId(),
1139
                //'Session #'.$item->getSessionId(),
1140
            ];
1141
            $cLpView[] = implode(', ', $list);
1142
        }
1143
1144
        // CStudentPublication
1145
        $criteria = [
1146
            'user' => $userId,
1147
        ];
1148
        $result = $em->getRepository(CStudentPublication::class)->findBy($criteria);
1149
        $cStudentPublication = [];
1150
        /** @var CStudentPublication $item */
1151
        foreach ($result as $item) {
1152
            $list = [
1153
                'Title: '.$item->getTitle(),
1154
                //'URL: '.$item->getTitle(),
1155
            ];
1156
            $cStudentPublication[] = implode(', ', $list);
1157
        }
1158
1159
        // CStudentPublicationComment
1160
        $criteria = [
1161
            'user' => $userId,
1162
        ];
1163
        $result = $em->getRepository(CStudentPublicationComment::class)->findBy($criteria);
1164
        $cStudentPublicationComment = [];
1165
        /** @var CStudentPublicationComment $item */
1166
        foreach ($result as $item) {
1167
            $date = $item->getSentAt()->format($dateFormat);
1168
            $list = [
1169
                'Commment: '.$item->getComment(),
1170
                'File '.$item->getFile(),
1171
                //'Course # '.$item->getCId(),
1172
                'Date: '.$date,
1173
            ];
1174
            $cStudentPublicationComment[] = implode(', ', $list);
1175
        }
1176
1177
        // CWiki
1178
        $criteria = [
1179
            'userId' => $userId,
1180
        ];
1181
        $result = $em->getRepository(CWiki::class)->findBy($criteria);
1182
        $cWiki = [];
1183
        /** @var CWiki $item */
1184
        foreach ($result as $item) {
1185
            $list = [
1186
                'Title: '.$item->getTitle(),
1187
                'Progress: '.$item->getProgress(),
1188
                'IP: '.$item->getUserIp(),
1189
            ];
1190
            $cWiki[] = implode(', ', $list);
1191
        }
1192
1193
        // Ticket
1194
        $criteria = [
1195
            'insertUserId' => $userId,
1196
        ];
1197
        $result = $em->getRepository(Ticket::class)->findBy($criteria);
1198
        $ticket = [];
1199
        /** @var Ticket $item */
1200
        foreach ($result as $item) {
1201
            $list = [
1202
                'Code: '.$item->getCode(),
1203
                'Subject: '.$item->getSubject(),
1204
            ];
1205
            $ticket[] = implode(', ', $list);
1206
        }
1207
1208
        // Message
1209
        $criteria = [
1210
            'insertUserId' => $userId,
1211
        ];
1212
        $result = $em->getRepository(TicketMessage::class)->findBy($criteria);
1213
        $ticketMessage = [];
1214
        /** @var TicketMessage $item */
1215
        foreach ($result as $item) {
1216
            $date = $item->getInsertDateTime()->format($dateFormat);
1217
            $list = [
1218
                'Subject: '.$item->getSubject(),
1219
                'IP: '.$item->getIpAddress(),
1220
                'Status: '.$item->getStatus(),
1221
                'Creation date: '.$date,
1222
            ];
1223
            $ticketMessage[] = implode(', ', $list);
1224
        }
1225
1226
        // SkillRelUserComment
1227
        $criteria = [
1228
            'feedbackGiver' => $userId,
1229
        ];
1230
        $result = $em->getRepository(SkillRelUserComment::class)->findBy($criteria);
1231
        $skillRelUserComment = [];
1232
        /** @var SkillRelUserComment $item */
1233
        foreach ($result as $item) {
1234
            $date = $item->getFeedbackDateTime()->format($dateFormat);
1235
            $list = [
1236
                'Feedback: '.$item->getFeedbackText(),
1237
                'Value: '.$item->getFeedbackValue(),
1238
                'Created at: '.$date,
1239
            ];
1240
            $skillRelUserComment[] = implode(', ', $list);
1241
        }
1242
1243
        // UserRelCourseVote
1244
        $criteria = [
1245
            'user' => $userId,
1246
        ];
1247
        $result = $em->getRepository(UserRelCourseVote::class)->findBy($criteria);
1248
        $userRelCourseVote = [];
1249
        /** @var UserRelCourseVote $item */
1250
        foreach ($result as $item) {
1251
            $list = [
1252
                'Course #'.$item->getCourse()->getId(),
1253
                //'Session #'.$item->getSession()->getId(),
1254
                'Vote: '.$item->getVote(),
1255
            ];
1256
            $userRelCourseVote[] = implode(', ', $list);
1257
        }
1258
1259
        /*$user->setDropBoxSentFiles(
1260
            [
1261
                'Friends' => $friendList,
1262
                'Events' => $eventList,
1263
                'GradebookCertificate' => $gradebookCertificate,
1264
1265
                'TrackECourseAccess' => $trackECourseAccessList,
1266
                'TrackELogin' => $trackELoginList,
1267
                'TrackEAccess' => $trackEAccessList,
1268
                'TrackEDefault' => $trackEDefault,
1269
                'TrackEOnline' => $trackEOnlineList,
1270
                'TrackEUploads' => $trackEUploads,
1271
                'TrackELastaccess' => $trackELastaccess,
1272
                'GradebookResult' => $gradebookResult,
1273
                'Downloads' => $trackEDownloads,
1274
                'UserCourseCategory' => $userCourseCategory,
1275
                'SkillRelUserComment' => $skillRelUserComment,
1276
                'UserRelCourseVote' => $userRelCourseVote,
1277
1278
                // courses
1279
                'AttendanceResult' => $cAttendanceResult,
1280
                'Blog' => $cBlog,
1281
                'DocumentsAdded' => $documents,
1282
                'Chat' => $chatFiles,
1283
                'ForumPost' => $cForumPostList,
1284
                'ForumThread' => $cForumThreadList,
1285
                'TrackEExercises' => $trackEExercises,
1286
                'TrackEAttempt' => $trackEAttempt,
1287
1288
                'GroupRelUser' => $cGroupRelUser,
1289
                'Message' => $messageList,
1290
                'Survey' => $cSurveyAnswer,
1291
                'StudentPublication' => $cStudentPublication,
1292
                'StudentPublicationComment' => $cStudentPublicationComment,
1293
                'DropboxFile' => $cDropboxFile,
1294
                'DropboxPerson' => $cDropboxPerson,
1295
                'DropboxFeedback' => $cDropboxFeedback,
1296
1297
                'LpView' => $cLpView,
1298
                'Notebook' => $cNotebook,
1299
1300
                'Wiki' => $cWiki,
1301
                // Tickets
1302
1303
                'Ticket' => $ticket,
1304
                'TicketMessage' => $ticketMessage,
1305
            ]
1306
        );*/
1307
1308
        //$user->setDropBoxReceivedFiles([]);
1309
        //$user->setGroups([]);
1310
        //$user->setCurriculumItems([]);
1311
1312
        /*$portals = $user->getPortals();
1313
        if (!empty($portals)) {
1314
            $list = [];
1315
            /** @var AccessUrlRelUser $portal */
1316
        /*foreach ($portals as $portal) {
1317
            $portalInfo = UrlManager::get_url_data_from_id($portal->getUrl()->getId());
1318
            $list[] = $portalInfo['url'];
1319
        }
1320
        }
1321
        $user->setPortals($list);*/
1322
1323
        /*$skillRelUserList = $user->getAchievedSkills();
1324
        $list = [];
1325
        foreach ($skillRelUserList as $skillRelUser) {
1326
            $list[] = $skillRelUser->getSkill()->getName();
1327
        }
1328
        $user->setAchievedSkills($list);
1329
        $user->setCommentedUserSkills([]);*/
1330
1331
        //$extraFieldValues = new \ExtraFieldValue('user');
1332
1333
        $lastLogin = $user->getLastLogin();
1334
        if (empty($lastLogin)) {
1335
            $login = $this->getLastLogin($user);
1336
            if (null !== $login) {
1337
                $lastLogin = $login->getLoginDate();
1338
            }
1339
        }
1340
        $user->setLastLogin($lastLogin);
1341
1342
        /*$dateNormalizer = new GetSetMethodNormalizer();
1343
        $dateNormalizer->setCircularReferenceHandler(function ($object) {
1344
            return get_class($object);
1345
        });*/
1346
1347
        $ignore = [
1348
            'twoStepVerificationCode',
1349
            'biography',
1350
            'dateOfBirth',
1351
            'gender',
1352
            'facebookData',
1353
            'facebookName',
1354
            'facebookUid',
1355
            'gplusData',
1356
            'gplusName',
1357
            'gplusUid',
1358
            'locale',
1359
            'timezone',
1360
            'twitterData',
1361
            'twitterName',
1362
            'twitterUid',
1363
            'gplusUid',
1364
            'token',
1365
            'website',
1366
            'plainPassword',
1367
            'completeNameWithUsername',
1368
            'completeName',
1369
            'completeNameWithClasses',
1370
            'salt',
1371
            'dropBoxSentFiles',
1372
            'dropBoxReceivedFiles',
1373
            'currentUrl',
1374
            'uuid',
1375
            'curriculumItems',
1376
            'currentSession',
1377
            'currentCourse',
1378
            'resourceNode',
1379
        ];
1380
1381
        $callback = function ($dateTime) {
1382
            return $dateTime instanceof DateTime ? $dateTime->format(DateTime::ATOM) : '';
1383
        };
1384
1385
        $defaultContext = [
1386
            AbstractNormalizer::CALLBACKS => [
1387
                'createdAt' => $callback,
1388
                'lastLogin' => $callback,
1389
                'registrationDate' => $callback,
1390
                'memberSince' => $callback,
1391
            ],
1392
            AbstractNormalizer::CIRCULAR_REFERENCE_HANDLER => function ($object, $format, $context) {
1393
                return \get_class($object);
1394
            },
1395
        ];
1396
1397
        $normalizer = new GetSetMethodNormalizer(null, null, null, null, null, $defaultContext);
1398
        $serializer = new Serializer(
1399
            [$normalizer],
1400
            [new JsonEncoder()]
1401
        );
1402
1403
        return $serializer->serialize($user, 'json', [
1404
            AbstractNormalizer::IGNORED_ATTRIBUTES => $ignore,
1405
        ]);
1406
    }
1407
1408
    /**
1409
     * Get the last login from the track_e_login table.
1410
     * This might be different from user.last_login in the case of legacy users
1411
     * as user.last_login was only implemented in 1.10 version with a default
1412
     * value of NULL (not the last record from track_e_login).
1413
     *
1414
     * @throws Exception
1415
     *
1416
     * @return null|TrackELogin
1417
     */
1418
    public function getLastLogin(User $user)
1419
    {
1420
        $repo = $this->getEntityManager()->getRepository(TrackELogin::class);
1421
        $qb = $repo->createQueryBuilder('u');
1422
1423
        return $qb
1424
            ->select('u')
1425
            ->where(
1426
                $qb->expr()->eq('u.loginUserId', $user->getId())
1427
            )
1428
            ->setMaxResults(1)
1429
            ->orderBy('u.loginDate', Criteria::DESC)
1430
            ->getQuery()
1431
            ->getOneOrNullResult()
1432
        ;
1433
    }
1434
1435
    public function addAccessUrlQueryBuilder(int $accessUrlId, QueryBuilder $qb = null): QueryBuilder
1436
    {
1437
        $qb = $this->getOrCreateQueryBuilder($qb, 'u');
1438
        $qb
1439
            ->innerJoin('u.portals', 'p')
1440
            ->andWhere('p.url = :url')
1441
            ->setParameter('url', $accessUrlId, Types::INTEGER)
1442
        ;
1443
1444
        return $qb;
1445
    }
1446
1447
    public function addActiveAndNotAnonUserQueryBuilder(QueryBuilder $qb = null): QueryBuilder
1448
    {
1449
        $qb = $this->getOrCreateQueryBuilder($qb, 'u');
1450
        $qb
1451
            ->andWhere('u.active = 1')
1452
            ->andWhere('u.status <> :status')
1453
            ->setParameter('status', User::ANONYMOUS, Types::INTEGER)
1454
        ;
1455
1456
        return $qb;
1457
    }
1458
1459
    public function addExpirationDateQueryBuilder(QueryBuilder $qb = null): QueryBuilder
1460
    {
1461
        $qb = $this->getOrCreateQueryBuilder($qb, 'u');
1462
        $qb
1463
            ->andWhere('u.registrationDate IS NULL OR u.registrationDate > :now')
1464
            ->setParameter('now', new Datetime(), Types::DATETIME_MUTABLE)
1465
        ;
1466
1467
        return $qb;
1468
    }
1469
1470
    private function addRoleQueryBuilder(string $role, QueryBuilder $qb = null): QueryBuilder
1471
    {
1472
        $qb = $this->getOrCreateQueryBuilder($qb, 'u');
1473
        $qb
1474
            ->andWhere('u.roles LIKE :roles')
1475
            ->setParameter('roles', '%"'.$role.'"%', Types::STRING)
1476
        ;
1477
1478
        return $qb;
1479
    }
1480
1481
    private function addSearchByKeywordQueryBuilder($keyword, QueryBuilder $qb = null): QueryBuilder
1482
    {
1483
        $qb = $this->getOrCreateQueryBuilder($qb, 'u');
1484
        $qb
1485
            ->andWhere('
1486
                u.firstname LIKE :keyword OR
1487
                u.lastname LIKE :keyword OR
1488
                u.email LIKE :keyword OR
1489
                u.username LIKE :keyword
1490
            ')
1491
            ->setParameter('keyword', "%$keyword%", Types::STRING)
1492
            ->orderBy('u.firstname', Criteria::ASC)
1493
        ;
1494
1495
        return $qb;
1496
    }
1497
1498
    private function addUserRelUserQueryBuilder(int $userId, int $relationType, QueryBuilder $qb = null): QueryBuilder
1499
    {
1500
        $qb = $this->getOrCreateQueryBuilder($qb, 'u');
1501
        $qb->leftJoin('u.userRelUsers', 'relations');
1502
        $qb
1503
            ->andWhere('relations.relationType = :relationType')
1504
            ->andWhere('relations.user = :userRelation AND relations.friend <> :userRelation')
1505
            ->setParameter('relationType', $relationType)
1506
            ->setParameter('userRelation', $userId)
1507
        ;
1508
1509
        return $qb;
1510
    }
1511
1512
    private function addOnlyMyFriendsQueryBuilder(int $userId, QueryBuilder $qb = null): QueryBuilder
1513
    {
1514
        $qb = $this->getOrCreateQueryBuilder($qb, 'u');
1515
        $qb
1516
            ->leftJoin('u.userRelUsers', 'relations')
1517
            ->andWhere(
1518
                $qb->expr()->notIn('relations.relationType', [USER_RELATION_TYPE_DELETED, USER_RELATION_TYPE_RRHH])
1519
            )
1520
            ->andWhere('relations.user = :user AND relations.friend <> :user')
1521
            ->setParameter('user', $userId, Types::INTEGER)
1522
        ;
1523
1524
        return $qb;
1525
    }
1526
1527
    private function addNotCurrentUserQueryBuilder(int $userId, QueryBuilder $qb = null): QueryBuilder
1528
    {
1529
        $qb = $this->getOrCreateQueryBuilder($qb, 'u');
1530
        $qb
1531
            ->andWhere('u.id <> :id')
1532
            ->setParameter('id', $userId, Types::INTEGER)
1533
        ;
1534
1535
        return $qb;
1536
    }
1537
}
1538