Passed
Push — master ( e381e3...b97ae5 )
by Julito
12:24
created

UserRepository::getLastLogin()   A

Complexity

Conditions 1

Size

Total Lines 16
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

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