Completed
Push — master ( 0fb228...bf9357 )
by Julito
13:22
created

UserRepository::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

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