Completed
Push — master ( fc1588...7621d0 )
by Julito
16:55
created

UserResolver   A

Complexity

Total Complexity 34

Size/Duplication

Total Lines 234
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 108
dl 0
loc 234
rs 9.68
c 0
b 0
f 0
wmc 34

6 Methods

Rating   Name   Duplication   Size   Complexity  
A getEmail() 0 11 2
A getMessageContacts() 0 12 2
A getCourses() 0 20 3
A getSessions() 0 21 2
F findUserSessions() 0 131 24
A getMessages() 0 5 1
1
<?php
2
/* For licensing terms, see /license.txt */
3
4
namespace Chamilo\GraphQlBundle\Resolver;
5
6
use Chamilo\CoreBundle\Entity\Course;
7
use Chamilo\GraphQlBundle\Traits\GraphQLTrait;
8
use Chamilo\UserBundle\Entity\User;
9
use Doctrine\Common\Collections\ArrayCollection;
10
use Overblog\GraphQLBundle\Definition\Argument;
11
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
12
13
/**
14
 * Class UserResolver.
15
 *
16
 * @package Chamilo\GraphQlBundle\Resolver
17
 */
18
class UserResolver implements ContainerAwareInterface
19
{
20
    use GraphQLTrait;
21
22
    /**
23
     * @return string
24
     */
25
    public function getEmail(User $user)
26
    {
27
        $this->protectCurrentUserData($user);
28
29
        $showEmail = $this->settingsManager->getSetting('display.show_email_addresses') === 'true';
30
31
        if (!$showEmail) {
32
            return '';
33
        }
34
35
        return $user->getEmail();
36
    }
37
38
    /**
39
     * @return ArrayCollection
40
     */
41
    public function getMessages(User $user, Argument $args)
42
    {
43
        $this->protectCurrentUserData($user);
44
45
        return $user->getUnreadReceivedMessages($args['lastId']);
46
    }
47
48
    /**
49
     * @return array
50
     */
51
    public function getMessageContacts(User $user, Argument $args)
52
    {
53
        $this->protectCurrentUserData($user);
54
55
        if (strlen($args['filter']) < 3) {
56
            return [];
57
        }
58
59
        $usersRepo = $this->em->getRepository('ChamiloUserBundle:User');
60
        $users = $usersRepo->findUsersToSendMessage($user->getId(), $args['filter']);
61
62
        return $users;
63
    }
64
65
    /**
66
     * @return array
67
     */
68
    public function getCourses(User $user, Argument $args, \ArrayObject $context)
69
    {
70
        $context->offsetSet('session', null);
71
72
        $this->protectCurrentUserData($user);
73
74
        $coursesInfo = \CourseManager::get_courses_list_by_user_id($user->getId());
75
        $coursesRepo = $this->em->getRepository('ChamiloCoreBundle:Course');
76
        $courses = [];
77
78
        foreach ($coursesInfo as $courseInfo) {
79
            /** @var Course $course */
80
            $course = $coursesRepo->find($courseInfo['real_id']);
81
82
            if ($course) {
83
                $courses[] = $course;
84
            }
85
        }
86
87
        return $courses;
88
    }
89
90
    /**
91
     * @return array
92
     */
93
    public function getSessions(User $user)
94
    {
95
        $this->protectCurrentUserData($user);
96
97
        $sessionsId = $this->findUserSessions($user);
98
99
        if (empty($sessionsId)) {
100
            return [];
101
        }
102
103
        $qb = $this->em->createQueryBuilder();
104
        $result = $qb
105
            ->select('s')
106
            ->from('ChamiloCoreBundle:Session', 's')
107
            ->where(
108
                $qb->expr()->in('s.id', $sessionsId)
109
            )
110
            ->getQuery()
111
            ->getResult();
112
113
        return $result;
114
    }
115
116
    /**
117
     * @todo Based on UserManager::get_sessions_by_category. Review to integrate Symfony
118
     *
119
     * @return array
120
     */
121
    private function findUserSessions(User $user)
122
    {
123
        $allowOrder = api_get_configuration_value('session_list_order');
124
        $showAllSessions = api_get_configuration_value('show_all_sessions_on_my_course_page') === true;
125
        $orderBySettings = api_get_configuration_value('my_courses_session_order');
126
127
        $position = '';
128
129
        if ($allowOrder) {
130
            $position = ', s.position AS position ';
131
        }
132
133
        $now = api_get_utc_datetime(null, false, true);
134
135
        $dql = "SELECT DISTINCT
136
                    s.id,
137
                    s.accessEndDate AS access_end_date,
138
                    s.duration,
139
                    CASE WHEN s.accessEndDate IS NULL THEN 1 ELSE 0 END HIDDEN _isFieldNull
140
                    $position
141
                FROM ChamiloCoreBundle:Session AS s
142
                LEFT JOIN ChamiloCoreBundle:SessionRelCourseRelUser AS scu WITH scu.session = s
143
                INNER JOIN ChamiloCoreBundle:AccessUrlRelSession AS url WITH url.session = s.id
144
                LEFT JOIN ChamiloCoreBundle:SessionCategory AS sc WITH s.category = sc
145
                WHERE (scu.user = :user OR s.generalCoach = :user) AND url.url = :url";
146
147
        $order = "ORDER BY sc.name, s.name";
148
149
        if ($showAllSessions) {
150
            $order = "ORDER BY s.accessStartDate";
151
        }
152
153
        if ($allowOrder) {
154
            $order = "ORDER BY s.position";
155
        }
156
157
        if (!empty($orderBySettings) && isset($orderBySettings['field']) && isset($orderBySettings['order'])) {
158
            $field = $orderBySettings['field'];
159
            $orderSetting = $orderBySettings['order'];
160
161
            switch ($field) {
162
                case 'start_date':
163
                    $order = "ORDER BY s.accessStartDate $orderSetting";
164
                    break;
165
                case 'end_date':
166
                    $order = " ORDER BY s.accessEndDate $orderSetting ";
167
                    if ($orderSetting == 'asc') {
168
                        // Put null values at the end
169
                        // https://stackoverflow.com/questions/12652034/how-can-i-order-by-null-in-dql
170
                        $order = "ORDER BY _isFieldNull asc, s.accessEndDate asc";
171
                    }
172
                    break;
173
            }
174
        }
175
176
        $results = [];
177
        $rows = $this->em
178
            ->createQuery("$dql $order")
179
            ->setParameters(
180
                [
181
                    'user' => $user->getId(),
182
                    'url' => api_get_current_access_url_id(),
183
                ]
184
            )
185
            ->getResult();
186
187
        foreach ($rows as $row) {
188
            $coachList = \SessionManager::getCoachesBySession($row['id']);
189
            $courseList = \UserManager::get_courses_list_by_session(
190
                $user->getId(),
191
                $row['id']
192
            );
193
            $daysLeft = \SessionManager::getDayLeftInSession(
194
                ['id' => $row['id'], 'duration' => $row['duration']],
195
                $user->getId()
196
            );
197
            $isGeneralCoach = \SessionManager::user_is_general_coach($user->getId(), $row['id']);
198
            $isCoachOfCourse = in_array($user->getId(), $coachList);
199
200
            if (!$isGeneralCoach && !$isCoachOfCourse) {
201
                // Teachers can access the session depending in the access_coach date
202
                if ($row['duration']) {
203
                    if ($daysLeft <= 0) {
204
                        continue;
205
                    }
206
                } else {
207
                    if (isset($row['access_end_date']) && !empty($row['access_end_date'])) {
208
                        if ($row['access_end_date'] <= $now) {
209
                            continue;
210
                        }
211
                    }
212
                }
213
            }
214
215
            $visibility = api_get_session_visibility($row['id'], null, false);
216
217
            if ($visibility != SESSION_VISIBLE) {
218
                // Course Coach session visibility.
219
                $blockedCourseCount = 0;
220
                $closedVisibilityList = [COURSE_VISIBILITY_CLOSED, COURSE_VISIBILITY_HIDDEN];
221
                $sessionCourseVisibility = SESSION_INVISIBLE;
222
223
                foreach ($courseList as $course) {
224
                    // Checking session visibility
225
                    $sessionCourseVisibility = api_get_session_visibility(
226
                        $row['id'],
227
                        $course['real_id'],
228
                        false
229
                    );
230
231
                    $courseIsVisible = !in_array($course['visibility'], $closedVisibilityList);
232
233
                    if ($courseIsVisible === false || $sessionCourseVisibility == SESSION_INVISIBLE) {
234
                        $blockedCourseCount++;
235
                    }
236
                }
237
238
                // If all courses are blocked then no show in the list.
239
                if ($blockedCourseCount !== count($courseList)) {
240
                    $visibility = $sessionCourseVisibility;
241
                }
242
            }
243
244
            if ($visibility == SESSION_INVISIBLE) {
245
                continue;
246
            }
247
248
            $results[] = $row['id'];
249
        }
250
251
        return $results;
252
    }
253
}
254