Passed
Push — master ( e72130...d886e7 )
by Julito
16:11
created

UserRepository::getCoachesForSessionCourse()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 21
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 13
c 1
b 0
f 0
nc 1
nop 2
dl 0
loc 21
rs 9.8333
1
<?php
2
3
declare(strict_types=1);
4
5
/* For licensing terms, see /license.txt */
6
7
namespace Chamilo\CoreBundle\Repository\Node;
8
9
use Agenda;
10
use Chamilo\CoreBundle\Entity\AccessUrl;
11
use Chamilo\CoreBundle\Entity\AccessUrlRelUser;
12
use Chamilo\CoreBundle\Entity\Course;
13
use Chamilo\CoreBundle\Entity\CourseRelUser;
14
use Chamilo\CoreBundle\Entity\GradebookCertificate;
15
use Chamilo\CoreBundle\Entity\GradebookResult;
16
use Chamilo\CoreBundle\Entity\Message;
17
use Chamilo\CoreBundle\Entity\ResourceNode;
18
use Chamilo\CoreBundle\Entity\Session;
19
use Chamilo\CoreBundle\Entity\SessionRelCourseRelUser;
20
use Chamilo\CoreBundle\Entity\SkillRelUserComment;
21
use Chamilo\CoreBundle\Entity\Ticket;
22
use Chamilo\CoreBundle\Entity\TicketMessage;
23
use Chamilo\CoreBundle\Entity\TrackEAccess;
24
use Chamilo\CoreBundle\Entity\TrackEAttempt;
25
use Chamilo\CoreBundle\Entity\TrackECourseAccess;
26
use Chamilo\CoreBundle\Entity\TrackEDefault;
27
use Chamilo\CoreBundle\Entity\TrackEDownloads;
28
use Chamilo\CoreBundle\Entity\TrackEExercises;
29
use Chamilo\CoreBundle\Entity\TrackELastaccess;
30
use Chamilo\CoreBundle\Entity\TrackELogin;
31
use Chamilo\CoreBundle\Entity\TrackEOnline;
32
use Chamilo\CoreBundle\Entity\TrackEUploads;
33
use Chamilo\CoreBundle\Entity\User;
34
use Chamilo\CoreBundle\Entity\UserCourseCategory;
35
use Chamilo\CoreBundle\Entity\UserRelCourseVote;
36
use Chamilo\CoreBundle\Repository\ResourceRepository;
37
use Chamilo\CourseBundle\Entity\CAttendanceResult;
38
use Chamilo\CourseBundle\Entity\CAttendanceSheet;
39
use Chamilo\CourseBundle\Entity\CBlogPost;
40
use Chamilo\CourseBundle\Entity\CDropboxFeedback;
41
use Chamilo\CourseBundle\Entity\CDropboxFile;
42
use Chamilo\CourseBundle\Entity\CDropboxPerson;
43
use Chamilo\CourseBundle\Entity\CForumPost;
44
use Chamilo\CourseBundle\Entity\CForumThread;
45
use Chamilo\CourseBundle\Entity\CGroupRelUser;
46
use Chamilo\CourseBundle\Entity\CLpView;
47
use Chamilo\CourseBundle\Entity\CNotebook;
48
use Chamilo\CourseBundle\Entity\CStudentPublication;
49
use Chamilo\CourseBundle\Entity\CStudentPublicationComment;
50
use Chamilo\CourseBundle\Entity\CSurveyAnswer;
51
use Chamilo\CourseBundle\Entity\CWiki;
52
use Datetime;
53
use Doctrine\Common\Collections\Collection;
54
use Doctrine\Common\Collections\Criteria;
55
use Doctrine\DBAL\Types\Types;
56
use Doctrine\ORM\Query\Expr\Join;
57
use Doctrine\ORM\QueryBuilder;
58
use Doctrine\Persistence\ManagerRegistry;
59
use Exception;
60
use SocialManager;
61
use Symfony\Bridge\Doctrine\Security\User\UserLoaderInterface;
62
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
63
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
64
use Symfony\Component\Security\Core\User\PasswordUpgraderInterface;
65
use Symfony\Component\Security\Core\User\UserInterface;
66
use Symfony\Component\Serializer\Encoder\JsonEncoder;
67
use Symfony\Component\Serializer\Normalizer\AbstractNormalizer;
68
use Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer;
69
use Symfony\Component\Serializer\Serializer;
70
use UrlManager;
71
72
/**
73
 * Class UserRepository.
74
 *
75
 * All functions that query the database (selects)
76
 * Functions should return query builders.
77
 */
78
class UserRepository extends ResourceRepository implements UserLoaderInterface, PasswordUpgraderInterface
79
{
80
    protected ?UserPasswordEncoderInterface $encoder = null;
81
82
    public function __construct(ManagerRegistry $registry)
83
    {
84
        parent::__construct($registry, User::class);
85
    }
86
87
    public function setEncoder(UserPasswordEncoderInterface $encoder): void
88
    {
89
        $this->encoder = $encoder;
90
    }
91
92
    public function loadUserByUsername(string $username): ?User
93
    {
94
        return $this->findOneBy([
95
            'username' => $username,
96
        ]);
97
    }
98
99
    public function updateUser(User $user, bool $andFlush = true): void
100
    {
101
        $this->updateCanonicalFields($user);
102
        $this->updatePassword($user);
103
        $this->getEntityManager()->persist($user);
104
        if ($andFlush) {
105
            $this->getEntityManager()->flush();
106
        }
107
    }
108
109
    public function canonicalize(string $string): string
110
    {
111
        $encoding = mb_detect_encoding($string, mb_detect_order(), true);
112
113
        return $encoding
114
            ? mb_convert_case($string, MB_CASE_LOWER, $encoding)
115
            : mb_convert_case($string, MB_CASE_LOWER);
116
    }
117
118
    public function updateCanonicalFields(User $user): void
119
    {
120
        $user->setUsernameCanonical($this->canonicalize($user->getUsername()));
121
        $user->setEmailCanonical($this->canonicalize($user->getEmail()));
122
    }
123
124
    public function updatePassword(User $user): void
125
    {
126
        //UserPasswordEncoderInterface $passwordEncoder
127
        $password = (string) $user->getPlainPassword();
128
        if ('' !== $password) {
129
            $password = $this->encoder->encodePassword($user, $password);
0 ignored issues
show
Bug introduced by
The method encodePassword() does not exist on null. ( Ignorable by Annotation )

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

129
            /** @scrutinizer ignore-call */ 
130
            $password = $this->encoder->encodePassword($user, $password);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

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