Passed
Push — master ( 5e5f3f...4cfc1e )
by Julito
09:34
created

UserRepository::loadUserByIdentifier()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 1
dl 0
loc 4
rs 10
c 0
b 0
f 0
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\Bridge\Doctrine\Security\User\UserLoaderInterface;
60
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
61
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
62
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
63
use Symfony\Component\Security\Core\User\PasswordUpgraderInterface;
64
use Symfony\Component\Security\Core\User\UserInterface;
65
use Symfony\Component\Serializer\Encoder\JsonEncoder;
66
use Symfony\Component\Serializer\Normalizer\AbstractNormalizer;
67
use Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer;
68
use Symfony\Component\Serializer\Serializer;
69
70
class UserRepository extends ResourceRepository implements UserLoaderInterface, PasswordUpgraderInterface
71
{
72
    protected ?UserPasswordHasherInterface $hasher = null;
73
74
    public function __construct(ManagerRegistry $registry)
75
    {
76
        parent::__construct($registry, User::class);
77
    }
78
79
    public function setHasher(UserPasswordHasherInterface $hasher): void
80
    {
81
        $this->hasher = $hasher;
82
    }
83
84
    public function loadUserByIdentifier(string $identifier): ?User
85
    {
86
        return $this->findOneBy([
87
            'username' => $identifier,
88
        ]);
89
    }
90
91
    public function updateUser(User $user, bool $andFlush = true): void
92
    {
93
        $this->updateCanonicalFields($user);
94
        $this->updatePassword($user);
95
        $this->getEntityManager()->persist($user);
96
        if ($andFlush) {
97
            $this->getEntityManager()->flush();
98
        }
99
    }
100
101
    public function canonicalize(string $string): string
102
    {
103
        $encoding = mb_detect_encoding($string, mb_detect_order(), true);
104
105
        return $encoding
106
            ? mb_convert_case($string, MB_CASE_LOWER, $encoding)
107
            : mb_convert_case($string, MB_CASE_LOWER);
108
    }
109
110
    public function updateCanonicalFields(User $user): void
111
    {
112
        $user->setUsernameCanonical($this->canonicalize($user->getUsername()));
113
        $user->setEmailCanonical($this->canonicalize($user->getEmail()));
114
    }
115
116
    public function updatePassword(User $user): void
117
    {
118
        //UserPasswordEncoderInterface $passwordEncoder
119
        $password = (string) $user->getPlainPassword();
120
        if ('' !== $password) {
121
            $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

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