Completed
Push — master ( 249002...76efa7 )
by Julito
09:55
created

UserRepository::getSessionAdmins()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 26
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 18
nc 1
nop 1
dl 0
loc 26
rs 9.6666
c 0
b 0
f 0
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\CourseBundle\Entity\CAttendanceResult;
31
use Chamilo\CourseBundle\Entity\CAttendanceSheet;
32
use Chamilo\CourseBundle\Entity\CBlogPost;
33
use Chamilo\CourseBundle\Entity\CDropboxFeedback;
34
use Chamilo\CourseBundle\Entity\CDropboxFile;
35
use Chamilo\CourseBundle\Entity\CDropboxPerson;
36
use Chamilo\CourseBundle\Entity\CForumPost;
37
use Chamilo\CourseBundle\Entity\CForumThread;
38
use Chamilo\CourseBundle\Entity\CGroupRelUser;
39
use Chamilo\CourseBundle\Entity\CLpView;
40
use Chamilo\CourseBundle\Entity\CNotebook;
41
use Chamilo\CourseBundle\Entity\CStudentPublication;
42
use Chamilo\CourseBundle\Entity\CStudentPublicationComment;
43
use Chamilo\CourseBundle\Entity\CSurveyAnswer;
44
use Chamilo\CourseBundle\Entity\CWiki;
45
use Chamilo\TicketBundle\Entity\Ticket;
46
use Chamilo\UserBundle\Entity\User;
47
use Doctrine\ORM\EntityManagerInterface;
48
use Doctrine\ORM\EntityRepository;
49
use Doctrine\ORM\Query\Expr\Join;
50
use Symfony\Component\Finder\Finder;
51
use Symfony\Component\Serializer\Encoder\JsonEncoder;
52
use Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer;
53
use Symfony\Component\Serializer\Serializer;
54
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
55
use Symfony\Component\Security\Core\Exception\UnsupportedUserException;
56
57
/**
58
 * Class UserRepository.
59
 *
60
 * All functions that query the database (selects)
61
 * Functions should return query builders.
62
 */
63
class UserRepository
64
{
65
    /**
66
     * @var EntityRepository
67
     */
68
    private $repository;
69
70
    public function __construct(EntityManagerInterface $entityManager)
71
    {
72
        $this->repository = $entityManager->getRepository(User::class);
73
    }
74
75
    public function findByUsername(string $username): ?User
76
    {
77
        return $this->repository->findOneBy(['username' => $username]);
78
    }
79
80
    /**
81
     * @param string $keyword
82
     *
83
     * @return mixed
84
     */
85
    public function searchUserByKeyword($keyword)
86
    {
87
        $qb = $this->repository->createQueryBuilder('a');
88
89
        // Selecting user info
90
        $qb->select('DISTINCT b');
91
92
        $qb->from('Chamilo\UserBundle\Entity\User', 'b');
93
94
        // Selecting courses for users
95
        //$qb->innerJoin('u.courses', 'c');
96
97
        //@todo check app settings
98
        $qb->add('orderBy', 'b.firstname ASC');
99
        $qb->where('b.firstname LIKE :keyword OR b.lastname LIKE :keyword ');
100
        $qb->setParameter('keyword', "%$keyword%");
101
        $query = $qb->getQuery();
102
103
        return $query->execute();
104
    }
105
106
    /**
107
     * @param string $role
108
     *
109
     * @return array
110
     */
111
    public function findByRole($role)
112
    {
113
        $em = $this->repository->getEntityManager();
114
        $qb = $em->createQueryBuilder();
115
116
        $qb->select('u')
117
            ->from($this->_entityName, 'u')
0 ignored issues
show
Bug Best Practice introduced by
The property _entityName does not exist on Chamilo\UserBundle\Repository\UserRepository. Did you maybe forget to declare it?
Loading history...
118
            ->where('u.roles LIKE :roles')
119
            ->setParameter('roles', '%"'.$role.'"%');
120
121
        return $qb->getQuery()->getResult();
122
    }
123
124
    /**
125
     * Get course user relationship based in the course_rel_user table.
126
     *
127
     * @return array
128
     */
129
    /*public function getCourses(User $user)
130
    {
131
        $queryBuilder = $this->createQueryBuilder('user');
132
133
        // Selecting course info.
134
        $queryBuilder->select('c');
135
136
        // Loading User.
137
        //$qb->from('Chamilo\UserBundle\Entity\User', 'u');
138
139
        // Selecting course
140
        $queryBuilder->innerJoin('Chamilo\CoreBundle\Entity\Course', 'c');
141
142
        //@todo check app settings
143
        //$qb->add('orderBy', 'u.lastname ASC');
144
145
        $wherePart = $queryBuilder->expr()->andx();
146
147
        // Get only users subscribed to this course
148
        $wherePart->add($queryBuilder->expr()->eq('user.userId', $user->getUserId()));
149
150
        $queryBuilder->where($wherePart);
151
        $query = $queryBuilder->getQuery();
152
153
        return $query->execute();
154
    }
155
156
    public function getTeachers()
157
    {
158
        $queryBuilder = $this->createQueryBuilder('u');
159
160
        // Selecting course info.
161
        $queryBuilder
162
            ->select('u')
163
            ->where('u.groups.id = :groupId')
164
            ->setParameter('groupId', 1);
165
166
        $query = $queryBuilder->getQuery();
167
168
        return $query->execute();
169
    }*/
170
171
    /*public function getUsers($group)
172
    {
173
        $queryBuilder = $this->createQueryBuilder('u');
174
175
        // Selecting course info.
176
        $queryBuilder
177
            ->select('u')
178
            ->where('u.groups = :groupId')
179
            ->setParameter('groupId', $group);
180
181
        $query = $queryBuilder->getQuery();
182
183
        return $query->execute();
184
    }*/
185
186
    /**
187
     * Get a filtered list of user by status and (optionally) access url.
188
     *
189
     * @todo not use status
190
     *
191
     * @param string $query       The query to filter
192
     * @param int    $status      The status
193
     * @param int    $accessUrlId The access URL ID
194
     *
195
     * @return array
196
     */
197
    public function searchUsersByStatus($query, $status, $accessUrlId = null)
198
    {
199
        $accessUrlId = (int) $accessUrlId;
200
        $queryBuilder = $this->repository->createQueryBuilder('u');
201
202
        if ($accessUrlId > 0) {
203
            $queryBuilder->innerJoin(
204
                'ChamiloCoreBundle:AccessUrlRelUser',
205
                'auru',
206
                Join::WITH,
207
                'u.id = auru.user'
208
            );
209
        }
210
211
        $queryBuilder->where('u.status = :status')
212
            ->andWhere('u.username LIKE :query OR u.firstname LIKE :query OR u.lastname LIKE :query')
213
            ->setParameter('status', $status)
214
            ->setParameter('query', "$query%");
215
216
        if ($accessUrlId > 0) {
217
            $queryBuilder->andWhere('auru.url = :url')
218
                ->setParameter(':url', $accessUrlId);
219
        }
220
221
        return $queryBuilder->getQuery()->getResult();
222
    }
223
224
    /**
225
     * Get the coaches for a course within a session.
226
     *
227
     * @param Session $session The session
228
     * @param Course  $course  The course
229
     *
230
     * @return \Doctrine\ORM\QueryBuilder
231
     */
232
    public function getCoachesForSessionCourse(Session $session, Course $course)
233
    {
234
        $queryBuilder = $this->repository->createQueryBuilder('u');
235
236
        $queryBuilder->select('u')
237
            ->innerJoin(
238
                'ChamiloCoreBundle:SessionRelCourseRelUser',
239
                'scu',
240
                Join::WITH,
241
                'scu.user = u'
242
            )
243
            ->where(
244
                $queryBuilder->expr()->andX(
245
                    $queryBuilder->expr()->eq('scu.session', $session->getId()),
246
                    $queryBuilder->expr()->eq('scu.course', $course->getId()),
247
                    $queryBuilder->expr()->eq('scu.status', SessionRelCourseRelUser::STATUS_COURSE_COACH)
248
                )
249
            );
250
251
        return $queryBuilder->getQuery()->getResult();
252
    }
253
254
    /**
255
     * Get course user relationship based in the course_rel_user table.
256
     *
257
     * @return array
258
     */
259
    /*public function getCourses(User $user)
260
    {
261
        $queryBuilder = $this->createQueryBuilder('user');
262
263
        // Selecting course info.
264
        $queryBuilder->select('c');
265
266
        // Loading User.
267
        //$qb->from('Chamilo\UserBundle\Entity\User', 'u');
268
269
        // Selecting course
270
        $queryBuilder->innerJoin('Chamilo\CoreBundle\Entity\Course', 'c');
271
272
        //@todo check app settings
273
        //$qb->add('orderBy', 'u.lastname ASC');
274
275
        $wherePart = $queryBuilder->expr()->andx();
276
277
        // Get only users subscribed to this course
278
        $wherePart->add($queryBuilder->expr()->eq('user.userId', $user->getUserId()));
279
280
        $queryBuilder->where($wherePart);
281
        $query = $queryBuilder->getQuery();
282
283
        return $query->execute();
284
    }
285
286
    public function getTeachers()
287
    {
288
        $queryBuilder = $this->createQueryBuilder('u');
289
290
        // Selecting course info.
291
        $queryBuilder
292
            ->select('u')
293
            ->where('u.groups.id = :groupId')
294
            ->setParameter('groupId', 1);
295
296
        $query = $queryBuilder->getQuery();
297
298
        return $query->execute();
299
    }*/
300
301
    /*public function getUsers($group)
302
    {
303
        $queryBuilder = $this->createQueryBuilder('u');
304
305
        // Selecting course info.
306
        $queryBuilder
307
            ->select('u')
308
            ->where('u.groups = :groupId')
309
            ->setParameter('groupId', $group);
310
311
        $query = $queryBuilder->getQuery();
312
313
        return $query->execute();
314
    }*/
315
316
    /**
317
     * Get the sessions admins for a user.
318
     *
319
     * @return array
320
     */
321
    public function getSessionAdmins(User $user)
322
    {
323
        $queryBuilder = $this->repository->createQueryBuilder('u');
324
        $queryBuilder
325
            ->distinct()
326
            ->innerJoin(
327
                'ChamiloCoreBundle:SessionRelUser',
328
                'su',
329
                Join::WITH,
330
                $queryBuilder->expr()->eq('u', 'su.user')
331
            )
332
            ->innerJoin(
333
                'ChamiloCoreBundle:SessionRelCourseRelUser',
334
                'scu',
335
                Join::WITH,
336
                $queryBuilder->expr()->eq('su.session', 'scu.session')
337
            )
338
            ->where(
339
                $queryBuilder->expr()->eq('scu.user', $user->getId())
340
            )
341
            ->andWhere(
342
                $queryBuilder->expr()->eq('su.relationType', SESSION_RELATION_TYPE_RRHH)
343
            )
344
        ;
345
346
        return $queryBuilder->getQuery()->getResult();
347
    }
348
349
    /**
350
     * Get the student bosses for a user.
351
     *
352
     * @return array
353
     */
354
    public function getStudentBosses(User $user)
355
    {
356
        $queryBuilder = $this->repository->createQueryBuilder('u');
357
        $queryBuilder
358
            ->distinct()
359
            ->innerJoin(
360
                'ChamiloCoreBundle:UserRelUser',
361
                'uu',
362
                Join::WITH,
363
                $queryBuilder->expr()->eq('u.id', 'uu.friendUserId')
364
            )
365
            ->where(
366
                $queryBuilder->expr()->eq('uu.relationType', USER_RELATION_TYPE_BOSS)
367
            )
368
            ->andWhere(
369
                $queryBuilder->expr()->eq('uu.userId', $user->getId())
370
            );
371
372
        return $queryBuilder->getQuery()->getResult();
373
    }
374
375
    /**
376
     * Get number of users in URL.
377
     *
378
     * @return int
379
     */
380
    public function getCountUsersByUrl(AccessUrl $url)
381
    {
382
        return $this->repository->createQueryBuilder('a')
383
            ->select('COUNT(a)')
384
            ->innerJoin('a.portals', 'u')
385
            ->where('u.portal = :u')
386
            ->setParameters(['u' => $url])
387
            ->getQuery()
388
            ->getSingleScalarResult();
389
    }
390
391
    /**
392
     * Get number of users in URL.
393
     *
394
     * @return int
395
     */
396
    public function getCountTeachersByUrl(AccessUrl $url)
397
    {
398
        $qb = $this->repository->createQueryBuilder('a');
399
400
        return $qb
401
            ->select('COUNT(a)')
402
            ->innerJoin('a.portals', 'u')
403
            ->where('u.portal = :u and u.group = :g')
404
            ->andWhere($qb->expr()->in('a.roles', ['ROLE_TEACHER']))
405
            ->setParameters(['u' => $url, 'g' => $group])
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $group seems to be never defined.
Loading history...
406
            ->getQuery()
407
            ->getSingleScalarResult()
408
        ;
409
    }
410
411
    /**
412
     * Find potential users to send a message.
413
     *
414
     * @param int    $currentUserId The current user ID
415
     * @param string $searchFilter  Optional. The search text to filter the user list
416
     * @param int    $limit         Optional. Sets the maximum number of results to retrieve
417
     *
418
     * @return mixed
419
     */
420
    public function findUsersToSendMessage($currentUserId, $searchFilter = null, $limit = 10)
421
    {
422
        $allowSendMessageToAllUsers = api_get_setting('allow_send_message_to_all_platform_users');
423
        $accessUrlId = api_get_multiple_access_url() ? api_get_current_access_url_id() : 1;
424
425
        if (api_get_setting('allow_social_tool') === 'true' &&
426
            api_get_setting('allow_message_tool') === 'true'
427
        ) {
428
            // All users
429
            if ($allowSendMessageToAllUsers === 'true' || api_is_platform_admin()) {
430
                $dql = "SELECT DISTINCT U
431
                        FROM ChamiloUserBundle:User U
432
                        LEFT JOIN ChamiloCoreBundle:AccessUrlRelUser R
433
                        WITH U = R.user
434
                        WHERE
435
                            U.active = 1 AND
436
                            U.status != 6  AND
437
                            U.id != $currentUserId AND
438
                            R.url = $accessUrlId";
439
            } else {
440
                $dql = "SELECT DISTINCT U
441
                        FROM ChamiloCoreBundle:AccessUrlRelUser R, ChamiloCoreBundle:UserRelUser UF
442
                        INNER JOIN ChamiloUserBundle:User AS U 
443
                        WITH UF.friendUserId = U
444
                        WHERE
445
                            U.active = 1 AND
446
                            U.status != 6 AND
447
                            UF.relationType NOT IN(".USER_RELATION_TYPE_DELETED.", ".USER_RELATION_TYPE_RRHH.") AND
448
                            UF.userId = $currentUserId AND
449
                            UF.friendUserId != $currentUserId AND
450
                            U = R.user AND
451
                            R.url = $accessUrlId";
452
            }
453
        } elseif (
454
            api_get_setting('allow_social_tool') === 'false' &&
455
            api_get_setting('allow_message_tool') === 'true'
456
        ) {
457
            if ($allowSendMessageToAllUsers === 'true') {
458
                $dql = "SELECT DISTINCT U
459
                        FROM ChamiloUserBundle:User U
460
                        LEFT JOIN ChamiloCoreBundle:AccessUrlRelUser R 
461
                        WITH U = R.user
462
                        WHERE
463
                            U.active = 1 AND
464
                            U.status != 6  AND
465
                            U.id != $currentUserId AND
466
                            R.url = $accessUrlId";
467
            } else {
468
                $time_limit = api_get_setting('time_limit_whosonline');
469
                $online_time = time() - $time_limit * 60;
470
                $limit_date = api_get_utc_datetime($online_time);
471
                $dql = "SELECT DISTINCT U
472
                        FROM ChamiloUserBundle:User U
473
                        INNER JOIN ChamiloCoreBundle:TrackEOnline T 
474
                        WITH U.id = T.loginUserId
475
                        WHERE 
476
                          U.active = 1 AND 
477
                          T.loginDate >= '".$limit_date."'";
478
            }
479
        }
480
481
        $parameters = [];
482
483
        if (!empty($searchFilter)) {
484
            $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...
485
            $parameters['search'] = "%$searchFilter%";
486
        }
487
488
        return $this->getEntityManager()
0 ignored issues
show
Bug introduced by
The method getEntityManager() does not exist on Chamilo\UserBundle\Repository\UserRepository. ( Ignorable by Annotation )

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

488
        return $this->/** @scrutinizer ignore-call */ getEntityManager()

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...
489
            ->createQuery($dql)
490
            ->setMaxResults($limit)
491
            ->setParameters($parameters)
492
            ->getResult();
493
    }
494
495
    /**
496
     * Get the list of HRM who have assigned this user.
497
     *
498
     * @param int $userId
499
     * @param int $urlId
500
     *
501
     * @return array
502
     */
503
    public function getAssignedHrmUserList($userId, $urlId)
504
    {
505
        $qb = $this->repository->createQueryBuilder('user');
506
507
        $hrmList = $qb
508
            ->select('uru')
509
            ->innerJoin('ChamiloCoreBundle:UserRelUser', 'uru', Join::WITH, 'uru.userId = user.id')
510
            ->innerJoin('ChamiloCoreBundle:AccessUrlRelUser', 'auru', Join::WITH, 'auru.user = uru.friendUserId')
511
            ->where(
512
                $qb->expr()->eq('auru.url', $urlId)
513
            )
514
            ->andWhere(
515
                $qb->expr()->eq('uru.userId', $userId)
516
            )
517
            ->andWhere(
518
                $qb->expr()->eq('uru.relationType', USER_RELATION_TYPE_RRHH)
519
            )
520
            ->getQuery()
521
            ->getResult();
522
523
        return $hrmList;
524
    }
525
526
    /**
527
     * Serialize the whole entity to an array.
528
     *
529
     * @param int   $userId
530
     * @param array $substitutionTerms Substitute terms for some elements
531
     *
532
     * @return string
533
     */
534
    public function getPersonalDataToJson($userId, array $substitutionTerms)
535
    {
536
        $em = $this->getEntityManager();
537
        $dateFormat = \Datetime::ATOM;
538
539
        /** @var User $user */
540
        $user = $this->find($userId);
0 ignored issues
show
Bug introduced by
The method find() does not exist on Chamilo\UserBundle\Repository\UserRepository. ( Ignorable by Annotation )

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

540
        /** @scrutinizer ignore-call */ 
541
        $user = $this->find($userId);

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...
541
542
        $user->setPassword($substitutionTerms['password']);
543
        $user->setSalt($substitutionTerms['salt']);
544
        $noDataLabel = $substitutionTerms['empty'];
545
546
        // Dummy content
547
        $user->setDateOfBirth(null);
548
        //$user->setBiography($noDataLabel);
549
        $user->setFacebookData($noDataLabel);
550
        $user->setFacebookName($noDataLabel);
551
        $user->setFacebookUid($noDataLabel);
552
        //$user->setImageName($noDataLabel);
553
        //$user->setTwoStepVerificationCode($noDataLabel);
554
        $user->setGender($noDataLabel);
555
        $user->setGplusData($noDataLabel);
556
        $user->setGplusName($noDataLabel);
557
        $user->setGplusUid($noDataLabel);
558
        $user->setLocale($noDataLabel);
559
        $user->setTimezone($noDataLabel);
560
        $user->setTwitterData($noDataLabel);
561
        $user->setTwitterName($noDataLabel);
562
        $user->setTwitterUid($noDataLabel);
563
        $user->setWebsite($noDataLabel);
564
        $user->setToken($noDataLabel);
565
566
        $courses = $user->getCourses();
567
        $list = [];
568
        $chatFiles = [];
569
        /** @var CourseRelUser $course */
570
        foreach ($courses as $course) {
571
            $list[] = $course->getCourse()->getCode();
572
            $courseDir = api_get_path(SYS_COURSE_PATH).$course->getCourse()->getDirectory();
573
            $documentDir = $courseDir.'/document/chat_files/';
574
            if (is_dir($documentDir)) {
575
                $fs = new Finder();
576
                $fs->files()->in($documentDir);
577
                foreach ($fs as $file) {
578
                    $chatFiles[] =
579
                        $course->getCourse()->getDirectory().'/document/chat_files/'.$file->getFilename().' - '.
580
                        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.');
581
                }
582
            }
583
        }
584
585
        $user->setCourses($list);
586
587
        $classes = $user->getClasses();
588
        $list = [];
589
        /** @var UsergroupRelUser $class */
590
        foreach ($classes as $class) {
591
            $name = $class->getUsergroup()->getName();
592
            $list[$class->getUsergroup()->getGroupType()][] = $name.' - Status: '.$class->getRelationType();
593
        }
594
        $user->setClasses($list);
595
596
        $collection = $user->getSessionCourseSubscriptions();
597
        $list = [];
598
        /** @var SessionRelCourseRelUser $item */
599
        foreach ($collection as $item) {
600
            $list[$item->getSession()->getName()][] = $item->getCourse()->getCode();
601
        }
602
        $user->setSessionCourseSubscriptions($list);
603
604
        $documents = \DocumentManager::getAllDocumentsCreatedByUser($userId);
605
606
        $friends = \SocialManager::get_friends($userId);
607
        $friendList = [];
608
        if (!empty($friends)) {
609
            foreach ($friends as $friend) {
610
                $friendList[] = $friend['user_info']['complete_name'];
611
            }
612
        }
613
614
        $agenda = new \Agenda('personal');
615
        $events = $agenda->getEvents('', '', null, null, $userId, 'array');
616
        $eventList = [];
617
        if (!empty($events)) {
618
            foreach ($events as $event) {
619
                $eventList[] = $event['title'].' '.$event['start_date_localtime'].' / '.$event['end_date_localtime'];
620
            }
621
        }
622
623
        // GradebookCertificate
624
        $criteria = [
625
            'userId' => $userId,
626
        ];
627
        $result = $em->getRepository('ChamiloCoreBundle:GradebookCertificate')->findBy($criteria);
628
        $gradebookCertificate = [];
629
        /** @var GradebookCertificate $item */
630
        foreach ($result as $item) {
631
            $createdAt = $item->getCreatedAt() ? $item->getCreatedAt()->format($dateFormat) : '';
632
            $list = [
633
                'Score: '.$item->getScoreCertificate(),
634
                'Path: '.$item->getPathCertificate(),
635
                'Created at: '.$createdAt,
636
            ];
637
            $gradebookCertificate[] = implode(', ', $list);
638
        }
639
640
        // TrackEExercises
641
        $criteria = [
642
            'exeUserId' => $userId,
643
        ];
644
        $result = $em->getRepository('ChamiloCoreBundle:TrackEExercises')->findBy($criteria);
645
        $trackEExercises = [];
646
        /** @var TrackEExercises $item */
647
        foreach ($result as $item) {
648
            $date = $item->getExeDate() ? $item->getExeDate()->format($dateFormat) : '';
649
            $list = [
650
                'IP: '.$item->getUserIp(),
651
                'Start: '.$date,
652
                'Status: '.$item->getStatus(),
653
                // 'Result: '.$item->getExeResult(),
654
                // 'Weighting: '.$item->getExeWeighting(),
655
            ];
656
            $trackEExercises[] = implode(', ', $list);
657
        }
658
659
        // TrackEAttempt
660
        $criteria = [
661
            'userId' => $userId,
662
        ];
663
        $result = $em->getRepository('ChamiloCoreBundle:TrackEAttempt')->findBy($criteria);
664
        $trackEAttempt = [];
665
        /** @var TrackEAttempt $item */
666
        foreach ($result as $item) {
667
            $date = $item->getTms() ? $item->getTms()->format($dateFormat) : '';
668
            $list = [
669
                'Attempt #'.$item->getExeId(),
670
                'Course # '.$item->getCourse()->getCode(),
671
                //'Answer: '.$item->getAnswer(),
672
                'Session #'.$item->getSessionId(),
673
                //'Marks: '.$item->getMarks(),
674
                'Position: '.$item->getPosition(),
675
                'Date: '.$date,
676
            ];
677
            $trackEAttempt[] = implode(', ', $list);
678
        }
679
680
        // TrackECourseAccess
681
        $criteria = [
682
            'userId' => $userId,
683
        ];
684
        $result = $em->getRepository('ChamiloCoreBundle:TrackECourseAccess')->findBy($criteria);
685
        $trackECourseAccessList = [];
686
        /** @var TrackECourseAccess $item */
687
        foreach ($result as $item) {
688
            $startDate = $item->getLoginCourseDate() ? $item->getLoginCourseDate()->format($dateFormat) : '';
689
            $endDate = $item->getLogoutCourseDate() ? $item->getLogoutCourseDate()->format($dateFormat) : '';
690
            $list = [
691
                'IP: '.$item->getUserIp(),
692
                'Start: '.$startDate,
693
                'End: '.$endDate,
694
            ];
695
            $trackECourseAccessList[] = implode(', ', $list);
696
        }
697
698
        $checkEntities = [
699
            'ChamiloCoreBundle:TrackELogin' => 'loginUserId',
700
            'ChamiloCoreBundle:TrackEAccess' => 'accessUserId',
701
            'ChamiloCoreBundle:TrackEOnline' => 'loginUserId',
702
            'ChamiloCoreBundle:TrackEDefault' => 'defaultUserId',
703
            'ChamiloCoreBundle:TrackELastaccess' => 'accessUserId',
704
            'ChamiloCoreBundle:TrackEUploads' => 'uploadUserId',
705
            'ChamiloCoreBundle:GradebookResult' => 'userId',
706
            'ChamiloCoreBundle:TrackEDownloads' => 'downUserId',
707
        ];
708
709
        $maxResults = 1000;
710
        $trackResults = [];
711
        foreach ($checkEntities as $entity => $field) {
712
            $qb = $em->createQueryBuilder();
713
            $qb->select($qb->expr()->count('l'))
714
                ->from($entity, 'l')
715
                ->where("l.$field = :login")
716
                ->setParameter('login', $userId);
717
            $query = $qb->getQuery();
718
            $count = $query->getSingleScalarResult();
719
720
            if ($count > $maxResults) {
721
                $qb = $em->getRepository($entity)->createQueryBuilder('l');
722
                $qb
723
                    ->select('l')
724
                    ->where("l.$field = :login")
725
                    ->setParameter('login', $userId);
726
                $qb
727
                    ->setFirstResult(0)
728
                    ->setMaxResults($maxResults)
729
                ;
730
                $result = $qb->getQuery()->getResult();
731
            } else {
732
                $criteria = [
733
                    $field => $userId,
734
                ];
735
                $result = $em->getRepository($entity)->findBy($criteria);
736
            }
737
            $trackResults[$entity] = $result;
738
        }
739
740
        $trackELoginList = [];
741
        /** @var TrackELogin $item */
742
        foreach ($trackResults['ChamiloCoreBundle:TrackELogin'] as $item) {
743
            $startDate = $item->getLoginDate() ? $item->getLoginDate()->format($dateFormat) : '';
744
            $endDate = $item->getLogoutDate() ? $item->getLogoutDate()->format($dateFormat) : '';
745
            $list = [
746
                'IP: '.$item->getUserIp(),
747
                'Start: '.$startDate,
748
                'End: '.$endDate,
749
            ];
750
            $trackELoginList[] = implode(', ', $list);
751
        }
752
753
        // TrackEAccess
754
        $trackEAccessList = [];
755
        /** @var TrackEAccess $item */
756
        foreach ($trackResults['ChamiloCoreBundle:TrackEAccess'] as $item) {
757
            $date = $item->getAccessDate() ? $item->getAccessDate()->format($dateFormat) : '';
758
            $list = [
759
                'IP: '.$item->getUserIp(),
760
                'Tool: '.$item->getAccessTool(),
761
                'End: '.$date,
762
            ];
763
            $trackEAccessList[] = implode(', ', $list);
764
        }
765
766
        // TrackEOnline
767
        $trackEOnlineList = [];
768
        /** @var TrackEOnline $item */
769
        foreach ($trackResults['ChamiloCoreBundle:TrackEOnline'] as $item) {
770
            $date = $item->getLoginDate() ? $item->getLoginDate()->format($dateFormat) : '';
771
            $list = [
772
                'IP: '.$item->getUserIp(),
773
                'Login date: '.$date,
774
                'Course # '.$item->getCId(),
775
                'Session # '.$item->getSessionId(),
776
            ];
777
            $trackEOnlineList[] = implode(', ', $list);
778
        }
779
780
        // TrackEDefault
781
        $trackEDefault = [];
782
        /** @var TrackEDefault $item */
783
        foreach ($trackResults['ChamiloCoreBundle:TrackEDefault'] as $item) {
784
            $date = $item->getDefaultDate() ? $item->getDefaultDate()->format($dateFormat) : '';
785
            $list = [
786
                'Type: '.$item->getDefaultEventType(),
787
                'Value: '.$item->getDefaultValue(),
788
                'Value type: '.$item->getDefaultValueType(),
789
                'Date: '.$date,
790
                'Course #'.$item->getCId(),
791
                'Session # '.$item->getSessionId(),
792
            ];
793
            $trackEDefault[] = implode(', ', $list);
794
        }
795
796
        // TrackELastaccess
797
        $trackELastaccess = [];
798
        /** @var TrackELastaccess $item */
799
        foreach ($trackResults['ChamiloCoreBundle:TrackELastaccess'] as $item) {
800
            $date = $item->getAccessDate() ? $item->getAccessDate()->format($dateFormat) : '';
801
            $list = [
802
                'Course #'.$item->getCId(),
803
                'Session # '.$item->getAccessSessionId(),
804
                'Tool: '.$item->getAccessTool(),
805
                'Access date: '.$date,
806
            ];
807
            $trackELastaccess[] = implode(', ', $list);
808
        }
809
810
        // TrackEUploads
811
        $trackEUploads = [];
812
        /** @var TrackEUploads $item */
813
        foreach ($trackResults['ChamiloCoreBundle:TrackEUploads'] as $item) {
814
            $date = $item->getUploadDate() ? $item->getUploadDate()->format($dateFormat) : '';
815
            $list = [
816
                'Course #'.$item->getCId(),
817
                'Uploaded at: '.$date,
818
                'Upload id # '.$item->getUploadId(),
819
            ];
820
            $trackEUploads[] = implode(', ', $list);
821
        }
822
823
        $gradebookResult = [];
824
        /** @var GradebookResult $item */
825
        foreach ($trackResults['ChamiloCoreBundle:GradebookResult'] as $item) {
826
            $date = $item->getCreatedAt() ? $item->getCreatedAt()->format($dateFormat) : '';
827
            $list = [
828
                'Evaluation id# '.$item->getEvaluationId(),
829
                //'Score: '.$item->getScore(),
830
                'Creation date: '.$date,
831
            ];
832
            $gradebookResult[] = implode(', ', $list);
833
        }
834
835
        $trackEDownloads = [];
836
        /** @var TrackEDownloads $item */
837
        foreach ($trackResults['ChamiloCoreBundle:TrackEDownloads'] as $item) {
838
            $date = $item->getDownDate() ? $item->getDownDate()->format($dateFormat) : '';
839
            $list = [
840
                'File: '.$item->getDownDocPath(),
841
                'Download at: '.$date,
842
            ];
843
            $trackEDownloads[] = implode(', ', $list);
844
        }
845
846
        // UserCourseCategory
847
        $criteria = [
848
            'userId' => $userId,
849
        ];
850
        $result = $em->getRepository('ChamiloCoreBundle:UserCourseCategory')->findBy($criteria);
851
        $userCourseCategory = [];
852
        /** @var UserCourseCategory $item */
853
        foreach ($result as $item) {
854
            $list = [
855
                'Title: '.$item->getTitle(),
856
            ];
857
            $userCourseCategory[] = implode(', ', $list);
858
        }
859
860
        // Forum
861
        $criteria = [
862
            'posterId' => $userId,
863
        ];
864
        $result = $em->getRepository('ChamiloCourseBundle:CForumPost')->findBy($criteria);
865
        $cForumPostList = [];
866
        /** @var CForumPost $item */
867
        foreach ($result as $item) {
868
            $date = $item->getPostDate() ? $item->getPostDate()->format($dateFormat) : '';
869
            $list = [
870
                'Title: '.$item->getPostTitle(),
871
                'Creation date: '.$date,
872
            ];
873
            $cForumPostList[] = implode(', ', $list);
874
        }
875
876
        // CForumThread
877
        $criteria = [
878
            'threadPosterId' => $userId,
879
        ];
880
        $result = $em->getRepository('ChamiloCourseBundle:CForumThread')->findBy($criteria);
881
        $cForumThreadList = [];
882
        /** @var CForumThread $item */
883
        foreach ($result as $item) {
884
            $date = $item->getThreadDate() ? $item->getThreadDate()->format($dateFormat) : '';
885
            $list = [
886
                'Title: '.$item->getThreadTitle(),
887
                'Creation date: '.$date,
888
            ];
889
            $cForumThreadList[] = implode(', ', $list);
890
        }
891
892
        // CForumAttachment
893
        /*$criteria = [
894
            'threadPosterId' => $userId,
895
        ];
896
        $result = $em->getRepository('ChamiloCourseBundle:CForumAttachment')->findBy($criteria);
897
        $cForumThreadList = [];
898
        * @var CForumThread $item
899
        foreach ($result as $item) {
900
            $list = [
901
                'Title: '.$item->getThreadTitle(),
902
                'Creation date: '.$item->getThreadDate()->format($dateFormat),
903
            ];
904
            $cForumThreadList[] = implode(', ', $list);
905
        }*/
906
907
        // cGroupRelUser
908
        $criteria = [
909
            'user' => $userId,
910
        ];
911
        $result = $em->getRepository('ChamiloCourseBundle:CGroupRelUser')->findBy($criteria);
912
        $cGroupRelUser = [];
913
        /** @var CGroupRelUser $item */
914
        foreach ($result as $item) {
915
            $list = [
916
                'Course # '.$item->getCId(),
917
                'Group #'.$item->getGroup()->getId(),
918
                'Role: '.$item->getStatus(),
919
            ];
920
            $cGroupRelUser[] = implode(', ', $list);
921
        }
922
923
        // CAttendanceSheet
924
        $criteria = [
925
            'userId' => $userId,
926
        ];
927
        $result = $em->getRepository('ChamiloCourseBundle:CAttendanceSheet')->findBy($criteria);
928
        $cAttendanceSheetList = [];
929
        /** @var CAttendanceSheet $item */
930
        foreach ($result as $item) {
931
            $list = [
932
                'Presence: '.$item->getPresence(),
933
                'Calendar id: '.$item->getAttendanceCalendarId(),
934
            ];
935
            $cAttendanceSheetList[] = implode(', ', $list);
936
        }
937
938
        // CBlogPost
939
        $criteria = [
940
            'authorId' => $userId,
941
        ];
942
        $result = $em->getRepository('ChamiloCourseBundle:CBlogPost')->findBy($criteria);
943
        $cBlog = [];
944
        /** @var CBlogPost $item */
945
        foreach ($result as $item) {
946
            $date = $item->getDateCreation() ? $item->getDateCreation()->format($dateFormat) : '';
947
            $list = [
948
                'Title: '.$item->getTitle(),
949
                'Date: '.$date,
950
            ];
951
            $cBlog[] = implode(', ', $list);
952
        }
953
954
        // CAttendanceResult
955
        $criteria = [
956
            'userId' => $userId,
957
        ];
958
        $result = $em->getRepository('ChamiloCourseBundle:CAttendanceResult')->findBy($criteria);
959
        $cAttendanceResult = [];
960
        /** @var CAttendanceResult $item */
961
        foreach ($result as $item) {
962
            $list = [
963
                'Score : '.$item->getScore(),
964
                'Calendar id: '.$item->getAttendanceId(),
965
            ];
966
            $cAttendanceResult[] = implode(', ', $list);
967
        }
968
969
        // Message
970
        $criteria = [
971
            'userSender' => $userId,
972
        ];
973
        $result = $em->getRepository('ChamiloCoreBundle:Message')->findBy($criteria);
974
        $messageList = [];
975
        /** @var Message $item */
976
        foreach ($result as $item) {
977
            $date = $item->getSendDate() ? $item->getSendDate()->format($dateFormat) : '';
978
            $userName = '';
979
            if ($item->getUserReceiver()) {
980
                $userName = $item->getUserReceiver()->getUsername();
981
            }
982
            $list = [
983
                'Title: '.$item->getTitle(),
984
                'Sent date: '.$date,
985
                'To user: '.$userName,
986
                'Status'.$item->getMsgStatus(),
987
            ];
988
            $messageList[] = implode(', ', $list);
989
        }
990
991
        // CSurveyAnswer
992
        $criteria = [
993
            'user' => $userId,
994
        ];
995
        $result = $em->getRepository('ChamiloCourseBundle:CSurveyAnswer')->findBy($criteria);
996
        $cSurveyAnswer = [];
997
        /** @var CSurveyAnswer $item */
998
        foreach ($result as $item) {
999
            $list = [
1000
                'Answer # '.$item->getAnswerId(),
1001
                'Value: '.$item->getValue(),
1002
            ];
1003
            $cSurveyAnswer[] = implode(', ', $list);
1004
        }
1005
1006
        // CDropboxFile
1007
        $criteria = [
1008
            'uploaderId' => $userId,
1009
        ];
1010
        $result = $em->getRepository('ChamiloCourseBundle:CDropboxFile')->findBy($criteria);
1011
        $cDropboxFile = [];
1012
        /** @var CDropboxFile $item */
1013
        foreach ($result as $item) {
1014
            $date = $item->getUploadDate() ? $item->getUploadDate()->format($dateFormat) : '';
1015
            $list = [
1016
                'Title: '.$item->getTitle(),
1017
                'Uploaded date: '.$date,
1018
                'File: '.$item->getFilename(),
1019
            ];
1020
            $cDropboxFile[] = implode(', ', $list);
1021
        }
1022
1023
        // CDropboxPerson
1024
        $criteria = [
1025
            'userId' => $userId,
1026
        ];
1027
        $result = $em->getRepository('ChamiloCourseBundle:CDropboxPerson')->findBy($criteria);
1028
        $cDropboxPerson = [];
1029
        /** @var CDropboxPerson $item */
1030
        foreach ($result as $item) {
1031
            $list = [
1032
                'File #'.$item->getFileId(),
1033
                'Course #'.$item->getCId(),
1034
            ];
1035
            $cDropboxPerson[] = implode(', ', $list);
1036
        }
1037
1038
        // CDropboxPerson
1039
        $criteria = [
1040
            'authorUserId' => $userId,
1041
        ];
1042
        $result = $em->getRepository('ChamiloCourseBundle:CDropboxFeedback')->findBy($criteria);
1043
        $cDropboxFeedback = [];
1044
        /** @var CDropboxFeedback $item */
1045
        foreach ($result as $item) {
1046
            $date = $item->getFeedbackDate() ? $item->getFeedbackDate()->format($dateFormat) : '';
1047
            $list = [
1048
                'File #'.$item->getFileId(),
1049
                'Feedback: '.$item->getFeedback(),
1050
                'Date: '.$date,
1051
            ];
1052
            $cDropboxFeedback[] = implode(', ', $list);
1053
        }
1054
1055
        // CNotebook
1056
        $criteria = [
1057
            'userId' => $userId,
1058
        ];
1059
        $result = $em->getRepository('ChamiloCourseBundle:CNotebook')->findBy($criteria);
1060
        $cNotebook = [];
1061
        /** @var CNotebook $item */
1062
        foreach ($result as $item) {
1063
            $date = $item->getUpdateDate() ? $item->getUpdateDate()->format($dateFormat) : '';
1064
            $list = [
1065
                'Title: '.$item->getTitle(),
1066
                'Date: '.$date,
1067
            ];
1068
            $cNotebook[] = implode(', ', $list);
1069
        }
1070
1071
        // CLpView
1072
        $criteria = [
1073
            'userId' => $userId,
1074
        ];
1075
        $result = $em->getRepository('ChamiloCourseBundle:CLpView')->findBy($criteria);
1076
        $cLpView = [];
1077
        /** @var CLpView $item */
1078
        foreach ($result as $item) {
1079
            $list = [
1080
                //'Id #'.$item->getId(),
1081
                'LP #'.$item->getLpId(),
1082
                'Progress: '.$item->getProgress(),
1083
                'Course #'.$item->getCId(),
1084
                'Session #'.$item->getSessionId(),
1085
            ];
1086
            $cLpView[] = implode(', ', $list);
1087
        }
1088
1089
        // CStudentPublication
1090
        $criteria = [
1091
            'userId' => $userId,
1092
        ];
1093
        $result = $em->getRepository('ChamiloCourseBundle:CStudentPublication')->findBy($criteria);
1094
        $cStudentPublication = [];
1095
        /** @var CStudentPublication $item */
1096
        foreach ($result as $item) {
1097
            $list = [
1098
                'Title: '.$item->getTitle(),
1099
                'URL: '.$item->getUrl(),
1100
            ];
1101
            $cStudentPublication[] = implode(', ', $list);
1102
        }
1103
1104
        // CStudentPublicationComment
1105
        $criteria = [
1106
            'userId' => $userId,
1107
        ];
1108
        $result = $em->getRepository('ChamiloCourseBundle:CStudentPublicationComment')->findBy($criteria);
1109
        $cStudentPublicationComment = [];
1110
        /** @var CStudentPublicationComment $item */
1111
        foreach ($result as $item) {
1112
            $date = $item->getSentAt() ? $item->getSentAt()->format($dateFormat) : '';
1113
            $list = [
1114
                'Commment: '.$item->getComment(),
1115
                'File '.$item->getFile(),
1116
                'Course # '.$item->getCId(),
1117
                'Date: '.$date,
1118
            ];
1119
            $cStudentPublicationComment[] = implode(', ', $list);
1120
        }
1121
1122
        // CWiki
1123
        $criteria = [
1124
            'userId' => $userId,
1125
        ];
1126
        $result = $em->getRepository('ChamiloCourseBundle:CWiki')->findBy($criteria);
1127
        $cWiki = [];
1128
        /** @var CWiki $item */
1129
        foreach ($result as $item) {
1130
            $list = [
1131
                'Title: '.$item->getTitle(),
1132
                'Progress: '.$item->getProgress(),
1133
                'IP: '.$item->getUserIp(),
1134
            ];
1135
            $cWiki[] = implode(', ', $list);
1136
        }
1137
1138
        // Ticket
1139
        $criteria = [
1140
            'insertUserId' => $userId,
1141
        ];
1142
        $result = $em->getRepository('ChamiloTicketBundle:Ticket')->findBy($criteria);
1143
        $ticket = [];
1144
        /** @var Ticket $item */
1145
        foreach ($result as $item) {
1146
            $list = [
1147
                'Code: '.$item->getCode(),
1148
                'Subject: '.$item->getSubject(),
1149
            ];
1150
            $ticket[] = implode(', ', $list);
1151
        }
1152
1153
        // Message
1154
        $criteria = [
1155
            'insertUserId' => $userId,
1156
        ];
1157
        $result = $em->getRepository('ChamiloTicketBundle:Message')->findBy($criteria);
1158
        $ticketMessage = [];
1159
        /** @var \Chamilo\TicketBundle\Entity\Message $item */
1160
        foreach ($result as $item) {
1161
            $date = $item->getInsertDateTime() ? $item->getInsertDateTime()->format($dateFormat) : '';
1162
            $list = [
1163
                'Subject: '.$item->getSubject(),
1164
                'IP: '.$item->getIpAddress(),
1165
                'Status: '.$item->getStatus(),
1166
                'Creation date: '.$date,
1167
            ];
1168
            $ticketMessage[] = implode(', ', $list);
1169
        }
1170
1171
        // SkillRelUserComment
1172
        $criteria = [
1173
            'feedbackGiver' => $userId,
1174
        ];
1175
        $result = $em->getRepository('ChamiloCoreBundle:SkillRelUserComment')->findBy($criteria);
1176
        $skillRelUserComment = [];
1177
        /** @var SkillRelUserComment $item */
1178
        foreach ($result as $item) {
1179
            $date = $item->getFeedbackDateTime() ? $item->getFeedbackDateTime()->format($dateFormat) : '';
1180
            $list = [
1181
                'Feedback: '.$item->getFeedbackText(),
1182
                'Value: '.$item->getFeedbackValue(),
1183
                'Created at: '.$date,
1184
            ];
1185
            $skillRelUserComment[] = implode(', ', $list);
1186
        }
1187
1188
        // UserRelCourseVote
1189
        $criteria = [
1190
            'userId' => $userId,
1191
        ];
1192
        $result = $em->getRepository('ChamiloCoreBundle:UserRelCourseVote')->findBy($criteria);
1193
        $userRelCourseVote = [];
1194
        /** @var UserRelCourseVote $item */
1195
        foreach ($result as $item) {
1196
            $list = [
1197
                'Course #'.$item->getCId(),
1198
                'Session #'.$item->getSessionId(),
1199
                'Vote: '.$item->getVote(),
1200
            ];
1201
            $userRelCourseVote[] = implode(', ', $list);
1202
        }
1203
1204
        // UserApiKey
1205
        $criteria = [
1206
            'userId' => $userId,
1207
        ];
1208
        $result = $em->getRepository('ChamiloCoreBundle:UserApiKey')->findBy($criteria);
1209
        $userApiKey = [];
1210
        /** @var UserApiKey $item */
1211
        foreach ($result as $item) {
1212
            $validityStart = $item->getValidityStartDate() ? $item->getValidityStartDate()->format($dateFormat) : '';
1213
            $validityEnd = $item->getValidityEndDate() ? $item->getValidityEndDate()->format($dateFormat) : '';
1214
            $created = $item->getCreatedDate() ? $item->getCreatedDate()->format($dateFormat) : '';
1215
1216
            $list = [
1217
                'ApiKey #'.$item->getApiKey(),
1218
                'Service: '.$item->getApiService(),
1219
                'EndPoint: '.$item->getApiEndPoint(),
1220
                'Validity start date: '.$validityStart,
1221
                'Validity enddate: '.$validityEnd,
1222
                'Created at: '.$created,
1223
            ];
1224
            $userApiKey[] = implode(', ', $list);
1225
        }
1226
1227
        $user->setDropBoxSentFiles(
1228
            [
1229
                'Friends' => $friendList,
1230
                'Events' => $eventList,
1231
                'GradebookCertificate' => $gradebookCertificate,
1232
1233
                'TrackECourseAccess' => $trackECourseAccessList,
1234
                'TrackELogin' => $trackELoginList,
1235
                'TrackEAccess' => $trackEAccessList,
1236
                'TrackEDefault' => $trackEDefault,
1237
                'TrackEOnline' => $trackEOnlineList,
1238
                'TrackEUploads' => $trackEUploads,
1239
                'TrackELastaccess' => $trackELastaccess,
1240
                'GradebookResult' => $gradebookResult,
1241
                'Downloads' => $trackEDownloads,
1242
                'UserCourseCategory' => $userCourseCategory,
1243
                'SkillRelUserComment' => $skillRelUserComment,
1244
                'UserRelCourseVote' => $userRelCourseVote,
1245
                'UserApiKey' => $userApiKey,
1246
1247
                // courses
1248
                'AttendanceResult' => $cAttendanceResult,
1249
                'Blog' => $cBlog,
1250
                'DocumentsAdded' => $documents,
1251
                'Chat' => $chatFiles,
1252
                'ForumPost' => $cForumPostList,
1253
                'ForumThread' => $cForumThreadList,
1254
                'TrackEExercises' => $trackEExercises,
1255
                'TrackEAttempt' => $trackEAttempt,
1256
1257
                'GroupRelUser' => $cGroupRelUser,
1258
                'Message' => $messageList,
1259
                'Survey' => $cSurveyAnswer,
1260
                'StudentPublication' => $cStudentPublication,
1261
                'StudentPublicationComment' => $cStudentPublicationComment,
1262
                'DropboxFile' => $cDropboxFile,
1263
                'DropboxPerson' => $cDropboxPerson,
1264
                'DropboxFeedback' => $cDropboxFeedback,
1265
1266
                'LpView' => $cLpView,
1267
                'Notebook' => $cNotebook,
1268
1269
                'Wiki' => $cWiki,
1270
                // Tickets
1271
1272
                'Ticket' => $ticket,
1273
                'TicketMessage' => $ticketMessage,
1274
            ]
1275
        );
1276
1277
        $user->setDropBoxReceivedFiles([]);
1278
        //$user->setGroups([]);
1279
        $user->setCurriculumItems([]);
1280
1281
        $portals = $user->getPortals();
1282
        if (!empty($portals)) {
1283
            $list = [];
1284
            /** @var AccessUrlRelUser $portal */
1285
            foreach ($portals as $portal) {
1286
                $portalInfo = \UrlManager::get_url_data_from_id($portal->getUrl()->getId());
1287
                $list[] = $portalInfo['url'];
1288
            }
1289
        }
1290
        $user->setPortals($list);
1291
1292
        $coachList = $user->getSessionAsGeneralCoach();
1293
        $list = [];
1294
        /** @var Session $session */
1295
        foreach ($coachList as $session) {
1296
            $list[] = $session->getName();
1297
        }
1298
        $user->setSessionAsGeneralCoach($list);
1299
1300
        $skillRelUserList = $user->getAchievedSkills();
1301
        $list = [];
1302
        /** @var SkillRelUser $skillRelUser */
1303
        foreach ($skillRelUserList as $skillRelUser) {
1304
            $list[] = $skillRelUser->getSkill()->getName();
1305
        }
1306
        $user->setAchievedSkills($list);
1307
        $user->setCommentedUserSkills([]);
1308
1309
        $extraFieldValues = new \ExtraFieldValue('user');
1310
        $items = $extraFieldValues->getAllValuesByItem($userId);
1311
        //$user->setExtraFields($items);
1312
        //$user->setExtraFields([]);
1313
1314
        $lastLogin = $user->getLastLogin();
1315
        if (empty($lastLogin)) {
1316
            $login = $this->getLastLogin($user);
1317
            if ($login) {
1318
                $lastLogin = $login->getLoginDate();
1319
            }
1320
        }
1321
        $user->setLastLogin($lastLogin);
1322
1323
        $dateNormalizer = new GetSetMethodNormalizer();
1324
        $dateNormalizer->setCircularReferenceHandler(function ($object) {
1325
            return get_class($object);
1326
        });
1327
1328
        $ignore = [
1329
            'twoStepVerificationCode',
1330
            'biography',
1331
            'dateOfBirth',
1332
            'gender',
1333
            'facebookData',
1334
            'facebookName',
1335
            'facebookUid',
1336
            'gplusData',
1337
            'gplusName',
1338
            'gplusUid',
1339
            'locale',
1340
            'timezone',
1341
            'twitterData',
1342
            'twitterName',
1343
            'twitterUid',
1344
            'gplusUid',
1345
            'token',
1346
            'website',
1347
            'plainPassword',
1348
            'completeNameWithUsername',
1349
            'completeName',
1350
            'completeNameWithClasses',
1351
            'salt',
1352
        ];
1353
1354
        $dateNormalizer->setIgnoredAttributes($ignore);
1355
1356
        $callback = function ($dateTime) {
1357
            return $dateTime instanceof \DateTime ? $dateTime->format(\DateTime::ATOM) : '';
1358
        };
1359
1360
        $dateNormalizer->setCallbacks(
1361
            [
1362
                'createdAt' => $callback,
1363
                'lastLogin' => $callback,
1364
                'registrationDate' => $callback,
1365
                'memberSince' => $callback,
1366
            ]
1367
        );
1368
1369
        $normalizers = [$dateNormalizer];
1370
        $serializer = new Serializer($normalizers, [new JsonEncoder()]);
1371
1372
        $jsonContent = $serializer->serialize($user, 'json');
1373
1374
        return $jsonContent;
1375
    }
1376
1377
    /**
1378
     * Get the last login from the track_e_login table.
1379
     * This might be different from user.last_login in the case of legacy users
1380
     * as user.last_login was only implemented in 1.10 version with a default
1381
     * value of NULL (not the last record from track_e_login).
1382
     *
1383
     * @throws \Exception
1384
     *
1385
     * @return TrackELogin|null
1386
     */
1387
    public function getLastLogin(User $user)
1388
    {
1389
        $repo = $this->getEntityManager()->getRepository('ChamiloCoreBundle:TrackELogin');
1390
        $qb = $repo->createQueryBuilder('l');
1391
1392
        $login = $qb
1393
            ->select('l')
1394
            ->where(
1395
                $qb->expr()->eq('l.loginUserId', $user->getId())
1396
            )
1397
            ->setMaxResults(1)
1398
            ->orderBy('l.loginDate', 'DESC')
1399
            ->getQuery()
1400
            ->getOneOrNullResult();
1401
1402
        return $login;
1403
    }
1404
}
1405