Passed
Push — master ( 8f07b0...3fcb32 )
by Julito
15:06
created

UserRepository::addOnlyMyFriendsQueryBuilder()   A

Complexity

Conditions 1

Size

Total Lines 13
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

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

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