Passed
Push — 1.11.x ( 2c9737...793471 )
by Julito
11:01
created

SessionManager   F

Complexity

Total Complexity 1221

Size/Duplication

Total Lines 9751
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 5004
dl 0
loc 9751
rs 0.8
c 1
b 0
f 0
wmc 1221

141 Methods

Rating   Name   Duplication   Size   Complexity  
A sessionNameExists() 0 8 1
B get_count_admin() 0 109 7
F fetch() 0 77 14
A __construct() 0 2 1
F create_session() 0 173 33
F formatSessionsAdminForGrid() 0 117 32
F edit_session() 0 144 25
A generateNextSessionName() 0 23 4
F get_user_data_access_tracking_overview() 0 141 20
F get_session_lp_progress() 0 107 13
F get_survey_overview() 0 104 13
F getSessionsForAdmin() 0 176 29
F get_session_progress() 0 341 24
F add_courses_to_session() 0 295 31
A unsubscribe_user_from_session() 0 41 3
A getUsersByCourseSession() 0 35 6
F edit_category_session() 0 58 20
A create_session_extra_field() 0 15 1
B getUsersByCourseAndSessionList() 0 40 8
F subscribe_users_to_session_course() 0 118 15
D create_category_session() 0 65 19
A removeAllDrhFromSession() 0 16 2
A unsubscribe_course_from_session() 0 46 3
B removeUsersFromCourseSession() 0 63 9
A sessionNameExistBesidesMySession() 0 20 3
B set_coach_to_course_session() 0 94 10
A get_all_session_category() 0 15 2
A unSubscribeUserFromCourseSession() 0 30 2
A get_session_by_name() 0 17 3
A clear_session_ref_promotion() 0 11 2
A get_session_category() 0 13 2
C delete() 0 132 12
A delete_session_category() 0 38 4
F subscribeUsersToSession() 0 234 29
B getHotSessions() 0 58 6
A update_session_extra_field_value() 0 10 1
A relation_session_course_exist() 0 15 2
F get_sessions_list() 0 94 17
C subscribeSessionsToDrh() 0 106 12
A getCoachesBySession() 0 18 3
A user_is_general_coach() 0 14 3
A getUserStatusInSession() 0 11 1
A get_course_list_by_session_id_like() 0 33 5
A protectSession() 0 4 2
A getSessionIdFromOriginalId() 0 13 2
A getCourseCountBySessionId() 0 29 3
A allowOnlyMySessions() 0 10 4
A cantEditSession() 0 19 6
A get_sessions_followed_by_drh() 0 24 1
C getTeacherTracking() 0 83 14
A subscribe_sessions_to_promotion() 0 16 3
F getAllUsersFromCoursesFromAllSessionFromStatus() 0 198 26
A getAllCoursesFromAllSessionFromDrh() 0 14 4
B get_users_by_session() 0 60 9
A get_sessions_by_coach() 0 8 1
A get_all_sessions_by_promotion() 0 8 1
A getCoachesByCourseSessionToString() 0 19 5
B copyStudentsFromSession() 0 63 8
A get_user_status_in_course_session() 0 21 2
F getSessionsFollowedByUser() 0 185 32
A getCountUserTracking() 0 51 5
B updateCoaches() 0 28 7
A getCourseToolToBeManaged() 0 5 1
A allowManageAllSessions() 0 7 3
B get_course_list_by_session_id() 0 55 8
A getDrhUsersInSession() 0 3 1
A get_session_by_course() 0 24 2
B checkSubscribeDrhToSessionList() 0 41 11
B getAllCoursesFollowedByUser() 0 71 9
A get_sessions_by_user() 0 24 5
B copyCoachesFromSessionToCourse() 0 60 10
A set_session_status() 0 5 1
A getCoachesByCourseSession() 0 21 3
A installCourse() 0 9 3
A getSessionFollowedByDrh() 0 40 3
F importCSV() 0 958 189
A subscribeDrhToSessionList() 0 17 4
A count_sessions() 0 14 2
F copy() 0 216 39
A unInstallCourse() 0 9 3
A protect_teacher_session_edit() 0 6 3
A get_sessions_by_general_coach() 0 33 5
A getAllCoursesFromAllSessions() 0 14 4
A allowToManageSessions() 0 13 4
B getSessionsCoachedByUser() 0 47 10
A addFlashSessionReadOnly() 0 5 3
B getSessionCategoryIdByName() 0 36 7
A getDefaultSessionTab() 0 10 2
A getSessionListTabs() 0 41 5
A getStatusList() 0 7 1
A compareArraysToMerge() 0 15 6
A searchSession() 0 36 4
A getUserSession() 0 19 4
A addClassesByName() 0 17 4
A getAvoidedCoursesInSession() 0 17 3
C getShortSessionListAndExtraByCategory() 0 96 13
B convertSessionDateToString() 0 42 7
F getGridColumns() 0 393 18
B getCollapsableData() 0 33 7
A getDescriptionFromSessionId() 0 26 3
A getSessionCourseForUser() 0 23 5
B move() 0 62 9
A getDayLeftInSession() 0 27 3
A getSessionVisibility() 0 9 4
A getPath() 0 17 4
A getCoursesListByCourseCoach() 0 10 1
A isValidId() 0 15 3
A getTotalUserCoursesInSession() 0 38 4
A getSessionsFollowedForGroupAdmin() 0 45 5
A moveDown() 0 3 1
A sessionHasCourse() 0 25 3
C getSessionListAndExtraByCategoryId() 0 127 15
A getStatusLabel() 0 9 2
A parseSessionDates() 0 29 1
A getCoursesForCourseSessionCoach() 0 27 4
C importSessionDrhCSV() 0 49 12
A getCountUsersInCourseSession() 0 26 1
C convert_dates_to_local() 0 41 11
A redirectToSession() 0 18 5
A compareBySessionName() 0 12 5
A isUserSubscribedAsStudent() 0 21 3
A moveUp() 0 3 1
A getCoursesInSession() 0 23 3
F get_sessions_admin_complete() 0 257 35
A compareByCourse() 0 8 3
A durationPerUserIsEnabled() 0 3 1
A getTotalUserTimeInPlatform() 0 27 5
D setForm() 0 291 14
A getAdminPath() 0 9 2
A getCoursesForMainSessionCoach() 0 25 5
A compareCatSessionInfo() 0 8 3
B allowed() 0 31 9
A editUserSessionDuration() 0 16 3
A isSessionFollowedByDrh() 0 31 2
B getNamedSessionCourseForCoach() 0 75 8
C get_count_admin_complete() 0 99 10
A searchCourseInSessionsFromUser() 0 14 3
B getFilteredExtraFields() 0 48 8
A compareByUserCourseCat() 0 8 3
A isUserSubscribedAsHRM() 0 22 3
A orderCourseIsEnabled() 0 8 2

How to fix   Complexity   

Complex Class

Complex classes like SessionManager often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use SessionManager, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
/* For licensing terms, see /license.txt */
4
5
use Chamilo\CoreBundle\Entity\Course;
6
use Chamilo\CoreBundle\Entity\ExtraField;
7
use Chamilo\CoreBundle\Entity\Repository\SequenceResourceRepository;
8
use Chamilo\CoreBundle\Entity\SequenceResource;
9
use Chamilo\CoreBundle\Entity\Session;
10
use Chamilo\CoreBundle\Entity\SessionRelCourse;
11
use Chamilo\CoreBundle\Entity\SessionRelCourseRelUser;
12
use Chamilo\CoreBundle\Entity\SessionRelUser;
13
use Chamilo\UserBundle\Entity\User;
14
use ExtraField as ExtraFieldModel;
15
use Monolog\Logger;
16
17
/**
18
 * Class SessionManager.
19
 *
20
 * This is the session library for Chamilo
21
 * (as in courses>session, not as in PHP session)
22
 * All main sessions functions should be placed here.
23
 * This class provides methods for sessions management.
24
 * Include/require it in your code to use its features.
25
 */
26
class SessionManager
27
{
28
    const STATUS_PLANNED = 1;
29
    const STATUS_PROGRESS = 2;
30
    const STATUS_FINISHED = 3;
31
    const STATUS_CANCELLED = 4;
32
33
    public static $_debug = false;
34
35
    /**
36
     * Constructor.
37
     */
38
    public function __construct()
39
    {
40
    }
41
42
    /**
43
     * Fetches a session from the database.
44
     *
45
     * @param int $id Session Id
46
     *
47
     * @return array Session details
48
     */
49
    public static function fetch($id)
50
    {
51
        $em = Database::getManager();
52
53
        if (empty($id)) {
54
            return [];
55
        }
56
57
        /** @var Session $session */
58
        $session = $em->find('ChamiloCoreBundle:Session', $id);
59
60
        if (!$session) {
0 ignored issues
show
introduced by
$session is of type Chamilo\CoreBundle\Entity\Session, thus it always evaluated to true.
Loading history...
61
            return [];
62
        }
63
64
        $result = [
65
            'id' => $session->getId(),
66
            'id_coach' => $session->getGeneralCoach() ? $session->getGeneralCoach()->getId() : null,
67
            'session_category_id' => $session->getCategory() ? $session->getCategory()->getId() : null,
68
            'name' => $session->getName(),
69
            'description' => $session->getDescription(),
70
            'show_description' => $session->getShowDescription(),
71
            'duration' => $session->getDuration(),
72
            'nbr_courses' => $session->getNbrCourses(),
73
            'nbr_users' => $session->getNbrUsers(),
74
            'nbr_classes' => $session->getNbrClasses(),
75
            'session_admin_id' => $session->getSessionAdminId(),
76
            'visibility' => $session->getVisibility(),
77
            'promotion_id' => $session->getPromotionId(),
78
            'display_start_date' => $session->getDisplayStartDate()
79
                ? $session->getDisplayStartDate()->format('Y-m-d H:i:s')
80
                : null,
81
            'display_end_date' => $session->getDisplayEndDate()
82
                ? $session->getDisplayEndDate()->format('Y-m-d H:i:s')
83
                : null,
84
            'access_start_date' => $session->getAccessStartDate()
85
                ? $session->getAccessStartDate()->format('Y-m-d H:i:s')
86
                : null,
87
            'access_end_date' => $session->getAccessEndDate()
88
                ? $session->getAccessEndDate()->format('Y-m-d H:i:s')
89
                : null,
90
            'coach_access_start_date' => $session->getCoachAccessStartDate()
91
                ? $session->getCoachAccessStartDate()->format('Y-m-d H:i:s')
92
                : null,
93
            'coach_access_end_date' => $session->getCoachAccessEndDate()
94
                ? $session->getCoachAccessEndDate()->format('Y-m-d H:i:s')
95
                : null,
96
            'send_subscription_notification' => $session->getSendSubscriptionNotification(),
97
        ];
98
99
        if (api_get_configuration_value('allow_session_status')) {
100
            $table = Database::get_main_table(TABLE_MAIN_SESSION);
101
            $sql = "SELECT status FROM $table WHERE id = $id";
102
            $resultQuery = Database::query($sql);
103
            $row = Database::fetch_array($resultQuery);
104
            $result['status'] = $row['status'];
105
            $result['status_label'] = self::getStatusLabel($row['status']);
106
        }
107
108
        // Converted to local values
109
        $variables = [
110
            'display_start_date',
111
            'display_end_date',
112
            'access_start_date',
113
            'access_end_date',
114
            'coach_access_start_date',
115
            'coach_access_end_date',
116
        ];
117
118
        foreach ($variables as $value) {
119
            $result[$value.'_to_local_time'] = null;
120
            if (!empty($result[$value])) {
121
                $result[$value.'_to_local_time'] = api_get_local_time($result[$value]);
122
            }
123
        }
124
125
        return $result;
126
    }
127
128
    /**
129
     * Create a session.
130
     *
131
     * @author Carlos Vargas <[email protected]>, from existing code
132
     *
133
     * @param string $name
134
     * @param string $startDate                    (YYYY-MM-DD hh:mm:ss)
135
     * @param string $endDate                      (YYYY-MM-DD hh:mm:ss)
136
     * @param string $displayStartDate             (YYYY-MM-DD hh:mm:ss)
137
     * @param string $displayEndDate               (YYYY-MM-DD hh:mm:ss)
138
     * @param string $coachStartDate               (YYYY-MM-DD hh:mm:ss)
139
     * @param string $coachEndDate                 (YYYY-MM-DD hh:mm:ss)
140
     * @param mixed  $coachId                      If int, this is the session coach id,
141
     *                                             if string, the coach ID will be looked for from the user table
142
     * @param int    $sessionCategoryId            ID of the session category in which this session is registered
143
     * @param int    $visibility                   Visibility after end date (0 = read-only, 1 = invisible, 2 = accessible)
144
     * @param bool   $fixSessionNameIfExists
145
     * @param string $duration
146
     * @param string $description                  Optional. The session description
147
     * @param int    $showDescription              Optional. Whether show the session description
148
     * @param array  $extraFields
149
     * @param int    $sessionAdminId               Optional. If this sessions was created by a session admin, assign it to him
150
     * @param bool   $sendSubscriptionNotification Optional.
151
     *                                             Whether send a mail notification to users being subscribed
152
     * @param int    $accessUrlId                  Optional.
153
     * @param int    $status
154
     *
155
     * @return mixed Session ID on success, error message otherwise
156
     *
157
     * @todo   use an array to replace all this parameters or use the model.lib.php ...
158
     */
159
    public static function create_session(
160
        $name,
161
        $startDate,
162
        $endDate,
163
        $displayStartDate,
164
        $displayEndDate,
165
        $coachStartDate,
166
        $coachEndDate,
167
        $coachId,
168
        $sessionCategoryId,
169
        $visibility = 1,
170
        $fixSessionNameIfExists = false,
171
        $duration = null,
172
        $description = null,
173
        $showDescription = 0,
174
        $extraFields = [],
175
        $sessionAdminId = 0,
176
        $sendSubscriptionNotification = false,
177
        $accessUrlId = 0,
178
        $status = 0
179
    ) {
180
        global $_configuration;
181
182
        // Check portal limits
183
        $accessUrlId = api_is_multiple_url_enabled()
184
            ? (empty($accessUrlId) ? api_get_current_access_url_id() : (int) $accessUrlId)
185
            : 1;
186
187
        if (isset($_configuration[$accessUrlId]) &&
188
            is_array($_configuration[$accessUrlId]) &&
189
            isset($_configuration[$accessUrlId]['hosting_limit_sessions']) &&
190
            $_configuration[$accessUrlId]['hosting_limit_sessions'] > 0
191
        ) {
192
            $num = self::count_sessions();
193
            if ($num >= $_configuration[$accessUrlId]['hosting_limit_sessions']) {
194
                api_warn_hosting_contact('hosting_limit_sessions');
195
196
                return get_lang('PortalSessionsLimitReached');
197
            }
198
        }
199
200
        $name = Database::escape_string(trim($name));
201
        $sessionCategoryId = (int) $sessionCategoryId;
202
        $visibility = (int) $visibility;
203
        $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
204
205
        $startDate = Database::escape_string($startDate);
206
        $endDate = Database::escape_string($endDate);
207
208
        if (empty($name)) {
209
            $msg = get_lang('SessionNameIsRequired');
210
211
            return $msg;
212
        } elseif (!empty($startDate) && !api_is_valid_date($startDate, 'Y-m-d H:i') &&
213
            !api_is_valid_date($startDate, 'Y-m-d H:i:s')
214
        ) {
215
            $msg = get_lang('InvalidStartDate');
216
217
            return $msg;
218
        } elseif (!empty($endDate) && !api_is_valid_date($endDate, 'Y-m-d H:i') &&
219
            !api_is_valid_date($endDate, 'Y-m-d H:i:s')
220
        ) {
221
            $msg = get_lang('InvalidEndDate');
222
223
            return $msg;
224
        } elseif (!empty($startDate) && !empty($endDate) && $startDate >= $endDate) {
225
            $msg = get_lang('StartDateShouldBeBeforeEndDate');
226
227
            return $msg;
228
        } else {
229
            $ready_to_create = false;
230
            if ($fixSessionNameIfExists) {
231
                $name = self::generateNextSessionName($name);
232
                if ($name) {
233
                    $ready_to_create = true;
234
                } else {
235
                    $msg = get_lang('SessionNameAlreadyExists');
236
237
                    return $msg;
238
                }
239
            } else {
240
                $rs = Database::query("SELECT 1 FROM $tbl_session WHERE name='".$name."'");
241
                if (Database::num_rows($rs)) {
242
                    $msg = get_lang('SessionNameAlreadyExists');
243
244
                    return $msg;
245
                }
246
                $ready_to_create = true;
247
            }
248
249
            if ($ready_to_create) {
250
                $sessionAdminId = !empty($sessionAdminId) ? $sessionAdminId : api_get_user_id();
251
                $values = [
252
                    'name' => $name,
253
                    'id_coach' => $coachId,
254
                    'session_admin_id' => $sessionAdminId,
255
                    'visibility' => $visibility,
256
                    'description' => $description,
257
                    'show_description' => $showDescription,
258
                    'send_subscription_notification' => (int) $sendSubscriptionNotification,
259
                ];
260
261
                if (!empty($startDate)) {
262
                    $values['access_start_date'] = api_get_utc_datetime($startDate);
263
                }
264
265
                if (!empty($endDate)) {
266
                    $values['access_end_date'] = api_get_utc_datetime($endDate);
267
                }
268
269
                if (!empty($displayStartDate)) {
270
                    $values['display_start_date'] = api_get_utc_datetime($displayStartDate);
271
                }
272
273
                if (!empty($displayEndDate)) {
274
                    $values['display_end_date'] = api_get_utc_datetime($displayEndDate);
275
                }
276
277
                if (!empty($coachStartDate)) {
278
                    $values['coach_access_start_date'] = api_get_utc_datetime($coachStartDate);
279
                }
280
                if (!empty($coachEndDate)) {
281
                    $values['coach_access_end_date'] = api_get_utc_datetime($coachEndDate);
282
                }
283
284
                if (!empty($sessionCategoryId)) {
285
                    $values['session_category_id'] = $sessionCategoryId;
286
                }
287
288
                if (api_get_configuration_value('allow_session_status')) {
289
                    $values['status'] = $status;
290
                }
291
292
                $session_id = Database::insert($tbl_session, $values);
293
                $duration = (int) $duration;
294
295
                if (!empty($duration)) {
296
                    $sql = "UPDATE $tbl_session SET
297
                        access_start_date = NULL,
298
                        access_end_date = NULL,
299
                        display_start_date = NULL,
300
                        display_end_date = NULL,
301
                        coach_access_start_date = NULL,
302
                        coach_access_end_date = NULL,
303
                        duration = $duration
304
                    WHERE id = $session_id";
305
                    Database::query($sql);
306
                } else {
307
                    $sql = "UPDATE $tbl_session
308
                        SET duration = 0
309
                        WHERE id = $session_id";
310
                    Database::query($sql);
311
                }
312
313
                if (!empty($session_id)) {
314
                    $extraFields['item_id'] = $session_id;
315
                    $sessionFieldValue = new ExtraFieldValue('session');
316
                    $sessionFieldValue->saveFieldValues($extraFields);
317
318
                    // Adding to the correct URL
319
                    UrlManager::add_session_to_url($session_id, $accessUrlId);
320
321
                    // add event to system log
322
                    Event::addEvent(
323
                        LOG_SESSION_CREATE,
324
                        LOG_SESSION_ID,
325
                        $session_id,
326
                        api_get_utc_datetime(),
327
                        api_get_user_id()
328
                    );
329
                }
330
331
                return $session_id;
332
            }
333
        }
334
    }
335
336
    /**
337
     * @param string $name
338
     *
339
     * @return bool
340
     */
341
    public static function sessionNameExists($name)
342
    {
343
        $name = Database::escape_string($name);
344
        $sql = "SELECT COUNT(*) as count FROM ".Database::get_main_table(TABLE_MAIN_SESSION)."
345
                WHERE name = '$name'";
346
        $result = Database::fetch_array(Database::query($sql));
347
348
        return $result['count'] > 0;
349
    }
350
351
    /**
352
     * @param string $where_condition
353
     *
354
     * @return mixed
355
     */
356
    public static function get_count_admin($where_condition = '')
357
    {
358
        $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
359
        $tbl_session_category = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
360
        $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
361
        $table_access_url_rel_session = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
362
        $tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
363
364
        $where = 'WHERE 1=1 ';
365
        $user_id = api_get_user_id();
366
        $extraJoin = '';
367
368
        if (api_is_session_admin() &&
369
            api_get_setting('allow_session_admins_to_manage_all_sessions') == 'false'
370
        ) {
371
            $where .= " AND (
372
                            s.session_admin_id = $user_id  OR
373
                            sru.user_id = '$user_id' AND
374
                            sru.relation_type = '".SESSION_RELATION_TYPE_RRHH."'
375
                            )
376
                      ";
377
378
            $extraJoin = " INNER JOIN $tbl_session_rel_user sru
379
                           ON sru.session_id = s.id ";
380
        }
381
382
        $today = api_get_utc_datetime();
383
        $today = api_strtotime($today, 'UTC');
384
        $today = date('Y-m-d', $today);
385
386
        if (!empty($where_condition)) {
387
            $where_condition = str_replace("(  session_active = ':'  )", '1=1', $where_condition);
388
389
            $where_condition = str_replace('category_name', 'sc.name', $where_condition);
390
            $where_condition = str_replace(
391
                ["AND session_active = '1'  )", " AND (  session_active = '1'  )"],
392
                [') GROUP BY s.name HAVING session_active = 1 ', " GROUP BY s.name HAVING session_active = 1 "],
393
                $where_condition
394
            );
395
            $where_condition = str_replace(
396
                ["AND session_active = '0'  )", " AND (  session_active = '0'  )"],
397
                [') GROUP BY s.name HAVING session_active = 0 ', " GROUP BY s.name HAVING session_active = '0' "],
398
                $where_condition
399
            );
400
        } else {
401
            $where_condition = " AND 1 = 1";
402
        }
403
404
        $courseCondition = null;
405
        if (strpos($where_condition, 'c.id')) {
406
            $table = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
407
            $tableCourse = Database::get_main_table(TABLE_MAIN_COURSE);
408
            $courseCondition = " INNER JOIN $table course_rel_session
409
                                 ON (s.id = course_rel_session.session_id)
410
                                 INNER JOIN $tableCourse c
411
                                 ON (course_rel_session.c_id = c.id)
412
                                ";
413
        }
414
415
        $sql = "SELECT COUNT(id) as total_rows FROM (
416
                SELECT DISTINCT
417
                 IF (
418
					(s.access_start_date <= '$today' AND '$today' <= s.access_end_date) OR
419
                    (s.access_start_date IS NULL AND s.access_end_date  = IS NULL ) OR
420
					(s.access_start_date <= '$today' AND s.access_end_date IS NULL) OR
421
					('$today' <= s.access_end_date AND s.access_start_date IS NULL)
422
				, 1, 0) as session_active,
423
                s.id
424
                FROM $tbl_session s
425
                LEFT JOIN $tbl_session_category sc
426
                ON s.session_category_id = sc.id
427
                INNER JOIN $tbl_user u
428
                ON s.id_coach = u.id
429
                $courseCondition
430
                $extraJoin
431
                $where $where_condition ) as session_table";
432
433
        if (api_is_multiple_url_enabled()) {
434
            $access_url_id = api_get_current_access_url_id();
435
            if ($access_url_id != -1) {
436
                $where .= " AND ar.access_url_id = $access_url_id ";
437
438
                $sql = "SELECT count(id) as total_rows FROM (
439
                SELECT DISTINCT
440
                  IF (
441
					(s.access_start_date <= '$today' AND '$today' <= s.access_end_date) OR
442
                    (s.access_start_date IS NULL AND s.access_end_date IS NULL) OR
443
					(s.access_start_date <= '$today' AND s.access_end_date IS NULL) OR
444
					('$today' <= s.access_end_date AND s.access_start_date IS NULL)
445
				, 1, 0)
446
				as session_active,
447
				s.id
448
                FROM $tbl_session s
449
                    LEFT JOIN  $tbl_session_category sc
450
                    ON s.session_category_id = sc.id
451
                    INNER JOIN $tbl_user u ON s.id_coach = u.user_id
452
                    INNER JOIN $table_access_url_rel_session ar
453
                    ON ar.session_id = s.id
454
                    $courseCondition
455
                    $extraJoin
456
                $where $where_condition) as session_table";
457
            }
458
        }
459
460
        $result_rows = Database::query($sql);
461
        $row = Database::fetch_array($result_rows);
462
        $num = $row['total_rows'];
463
464
        return $num;
465
    }
466
467
    /**
468
     * Get session list for a session admin or platform admin.
469
     *
470
     * @param int    $userId   User Id for the session admin.
471
     * @param array  $options  Order and limit keys.
472
     * @param bool   $getCount Whether to get all the results or only the count.
473
     * @param array  $columns  Columns from jqGrid.
474
     * @param string $listType
475
     *
476
     * @return array
477
     */
478
    public static function getSessionsForAdmin(
479
        $userId,
480
        $options = [],
481
        $getCount = false,
482
        $columns = [],
483
        $listType = 'all'
484
    ) {
485
        $tblSession = Database::get_main_table(TABLE_MAIN_SESSION);
486
        $sessionCategoryTable = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
487
488
        $where = 'WHERE 1 = 1 ';
489
490
        $userId = (int) $userId;
491
492
        if (!api_is_platform_admin()) {
493
            if (api_is_session_admin() &&
494
                'false' === api_get_setting('allow_session_admins_to_manage_all_sessions')
495
            ) {
496
                $where .= " AND s.session_admin_id = $userId ";
497
            }
498
        }
499
500
        if (!api_is_platform_admin() &&
501
            api_is_teacher() &&
502
            'true' === api_get_setting('allow_teachers_to_create_sessions')
503
        ) {
504
            $where .= " AND s.id_coach = $userId ";
505
        }
506
507
        $extraFieldModel = new ExtraFieldModel('session');
508
        $conditions = $extraFieldModel->parseConditions($options);
509
510
        $sqlInjectJoins = $conditions['inject_joins'];
511
        $where .= $conditions['where'];
512
        $sqlInjectWhere = $conditions['inject_where'];
513
        $injectExtraFields = $conditions['inject_extra_fields'];
514
        $order = $conditions['order'];
515
        $limit = $conditions['limit'];
516
517
        $isMakingOrder = false;
518
        $showCountUsers = false;
519
520
        if (true === $getCount) {
521
            $select = ' SELECT count(DISTINCT s.id) as total_rows ';
522
        } else {
523
            if (!empty($columns['column_model'])) {
524
                foreach ($columns['column_model'] as $column) {
525
                    if ('users' == $column['name']) {
526
                        $showCountUsers = true;
527
                    }
528
                }
529
            }
530
531
            $select =
532
                "SELECT DISTINCT
533
                     s.name,
534
                     s.display_start_date,
535
                     s.display_end_date,
536
                     access_start_date,
537
                     access_end_date,
538
                     s.visibility,
539
                     s.session_category_id,
540
                     $injectExtraFields
541
                     s.id
542
             ";
543
544
            if ($showCountUsers) {
545
                $select .= ', count(su.user_id) users';
546
            }
547
548
            if (api_get_configuration_value('allow_session_status')) {
549
                $select .= ', status';
550
            }
551
552
            if (isset($options['order'])) {
553
                $isMakingOrder = 0 === strpos($options['order'], 'category_name');
554
            }
555
        }
556
557
        $isFilteringSessionCategory = strpos($where, 'category_name') !== false;
558
        $isFilteringSessionCategoryWithName = strpos($where, 'sc.name') !== false;
559
560
        if ($isMakingOrder || $isFilteringSessionCategory || $isFilteringSessionCategoryWithName) {
561
            $sqlInjectJoins .= " LEFT JOIN $sessionCategoryTable sc ON s.session_category_id = sc.id ";
562
563
            if ($isFilteringSessionCategory) {
564
                $where = str_replace('category_name', 'sc.name', $where);
565
            }
566
567
            if ($isMakingOrder) {
568
                $order = str_replace('category_name', 'sc.name', $order);
569
            }
570
        }
571
572
        if ($showCountUsers) {
573
            $tblSessionRelUser = Database::get_main_table(TABLE_MAIN_SESSION_USER);
574
            $sqlInjectJoins .= " LEFT JOIN $tblSessionRelUser su ON (su.session_id = s.id)";
575
        }
576
577
        $query = "$select FROM $tblSession s $sqlInjectJoins $where $sqlInjectWhere";
578
579
        if (api_is_multiple_url_enabled()) {
580
            $tblAccessUrlRelSession = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
581
            $accessUrlId = api_get_current_access_url_id();
582
583
            if ($accessUrlId != -1) {
584
                $where .= " AND ar.access_url_id = $accessUrlId ";
585
                $query = "$select
586
                    FROM $tblSession s $sqlInjectJoins
587
                    INNER JOIN $tblAccessUrlRelSession ar
588
                    ON (ar.session_id = s.id) $where";
589
            }
590
        }
591
592
        $date = api_get_utc_datetime();
593
594
        switch ($listType) {
595
            case 'all':
596
                break;
597
            case 'active':
598
                $query .= "AND (
599
                    (s.access_end_date IS NULL)
600
                    OR
601
                    (
602
                    s.access_start_date IS NOT NULL AND
603
                    s.access_end_date IS NOT NULL AND
604
                    s.access_start_date <= '$date' AND s.access_end_date >= '$date')
605
                    OR
606
                    (
607
                        s.access_start_date IS NULL AND
608
                        s.access_end_date IS NOT NULL AND
609
                        s.access_end_date >= '$date'
610
                    )
611
                )";
612
                break;
613
            case 'close':
614
                $query .= "AND (
615
                    (
616
                    s.access_start_date IS NOT NULL AND
617
                    s.access_end_date IS NOT NULL AND
618
                    s.access_start_date <= '$date' AND s.access_end_date <= '$date')
619
                    OR
620
                    (
621
                        s.access_start_date IS NULL AND
622
                        s.access_end_date IS NOT NULL AND
623
                        s.access_end_date <= '$date'
624
                    )
625
                )";
626
                break;
627
        }
628
629
        if ($showCountUsers) {
630
            $query .= ' GROUP by s.id';
631
        }
632
633
        $allowOrder = api_get_configuration_value('session_list_order');
634
635
        if ($allowOrder) {
636
            $order = ' ORDER BY position ASC';
637
        }
638
639
        $query .= $order;
640
        $query .= $limit;
641
        $result = Database::query($query);
642
643
        $sessions = Database::store_result($result, 'ASSOC');
644
645
        if ('all' === $listType) {
646
            if ($getCount) {
647
                return $sessions[0]['total_rows'];
648
            }
649
650
            return $sessions;
651
        }
652
653
        return $sessions;
654
    }
655
656
    /**
657
     * Gets the admin session list callback of the session/session_list.php page.
658
     *
659
     * @param array  $options           order and limit keys
660
     * @param bool   $getCount          Whether to get all the results or only the count
661
     * @param array  $columns
662
     * @param array  $extraFieldsToLoad
663
     * @param string $listType
664
     *
665
     * @return mixed Integer for number of rows, or array of results
666
     * @assert ([],true) !== false
667
     */
668
    public static function formatSessionsAdminForGrid(
669
        $options = [],
670
        $getCount = false,
671
        $columns = [],
672
        $extraFieldsToLoad = [],
673
        $listType = 'all'
674
    ) {
675
        $showCountUsers = false;
676
        if (!$getCount && !empty($columns['column_model'])) {
677
            foreach ($columns['column_model'] as $column) {
678
                if ('users' === $column['name']) {
679
                    $showCountUsers = true;
680
                }
681
            }
682
        }
683
684
        $userId = api_get_user_id();
685
        $sessions = self::getSessionsForAdmin($userId, $options, $getCount, $columns, $listType);
686
        if ($getCount) {
687
            return (int) $sessions;
688
        }
689
690
        $formattedSessions = [];
691
        $categories = self::get_all_session_category();
692
        $orderedCategories = [];
693
        if (!empty($categories)) {
694
            foreach ($categories as $category) {
695
                $orderedCategories[$category['id']] = $category['name'];
696
            }
697
        }
698
699
        $activeIcon = Display::return_icon('accept.png', get_lang('Active'));
700
        $inactiveIcon = Display::return_icon('error.png', get_lang('Inactive'));
701
        $webPath = api_get_path(WEB_PATH);
702
703
        foreach ($sessions as $session) {
704
            if ($showCountUsers) {
705
                $session['users'] = self::get_users_by_session($session['id'], 0, true);
706
            }
707
            $url = $webPath.'main/session/resume_session.php?id_session='.$session['id'];
708
            if ($extraFieldsToLoad || api_is_drh()) {
709
                $url = $webPath.'session/'.$session['id'].'/about/';
710
            }
711
712
            $session['name'] = Display::url($session['name'], $url);
713
714
            if (!empty($extraFieldsToLoad)) {
715
                foreach ($extraFieldsToLoad as $field) {
716
                    $extraFieldValue = new ExtraFieldValue('session');
717
                    $fieldData = $extraFieldValue->getAllValuesByItemAndField(
718
                        $session['id'],
719
                        $field['id']
720
                    );
721
                    $fieldDataArray = [];
722
                    $fieldDataToString = '';
723
                    if (!empty($fieldData)) {
724
                        foreach ($fieldData as $data) {
725
                            $fieldDataArray[] = $data['value'];
726
                        }
727
                        $fieldDataToString = implode(', ', $fieldDataArray);
728
                    }
729
                    $session[$field['variable']] = $fieldDataToString;
730
                }
731
            }
732
            if (isset($session['session_active']) && $session['session_active'] == 1) {
733
                $session['session_active'] = $activeIcon;
734
            } else {
735
                $session['session_active'] = $inactiveIcon;
736
            }
737
738
            $session = self::convert_dates_to_local($session, true);
739
740
            switch ($session['visibility']) {
741
                case SESSION_VISIBLE_READ_ONLY: //1
742
                    $session['visibility'] = get_lang('ReadOnly');
743
                    break;
744
                case SESSION_VISIBLE:           //2
745
                case SESSION_AVAILABLE:         //4
746
                    $session['visibility'] = get_lang('Visible');
747
                    break;
748
                case SESSION_INVISIBLE:         //3
749
                    $session['visibility'] = api_ucfirst(get_lang('Invisible'));
750
                    break;
751
            }
752
753
            // Cleaning double selects.
754
            foreach ($session as $key => &$value) {
755
                if (isset($optionsByDouble[$key]) || isset($optionsByDouble[$key.'_second'])) {
756
                    $options = explode('::', $value);
757
                }
758
                $original_key = $key;
759
                if (strpos($key, '_second') !== false) {
760
                    $key = str_replace('_second', '', $key);
761
                }
762
763
                if (isset($optionsByDouble[$key]) &&
764
                    isset($options[0]) &&
765
                    isset($optionsByDouble[$key][$options[0]])
766
                ) {
767
                    if (strpos($original_key, '_second') === false) {
768
                        $value = $optionsByDouble[$key][$options[0]]['option_display_text'];
769
                    } else {
770
                        $value = $optionsByDouble[$key][$options[1]]['option_display_text'];
771
                    }
772
                }
773
            }
774
775
            $categoryName = isset($orderedCategories[$session['session_category_id']]) ? $orderedCategories[$session['session_category_id']] : '';
776
            $session['category_name'] = $categoryName;
777
            if (isset($session['status'])) {
778
                $session['status'] = self::getStatusLabel($session['status']);
779
            }
780
781
            $formattedSessions[] = $session;
782
        }
783
784
        return $formattedSessions;
785
    }
786
787
    /**
788
     * Gets the progress of learning paths in the given session.
789
     *
790
     * @param int    $sessionId
791
     * @param int    $courseId
792
     * @param string $date_from
793
     * @param string $date_to
794
     * @param array options order and limit keys
795
     *
796
     * @return array table with user name, lp name, progress
797
     */
798
    public static function get_session_lp_progress(
799
        $sessionId,
800
        $courseId,
801
        $date_from,
802
        $date_to,
803
        $options
804
    ) {
805
        //escaping vars
806
        $sessionId = $sessionId == 'T' ? 'T' : intval($sessionId);
807
        $courseId = intval($courseId);
808
809
        //tables
810
        $session_course_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
811
        $user = Database::get_main_table(TABLE_MAIN_USER);
812
        $tbl_course_lp_view = Database::get_course_table(TABLE_LP_VIEW);
813
814
        $course = api_get_course_info_by_id($courseId);
815
        $sessionCond = 'and session_id = %s';
816
        if ($sessionId == 'T') {
817
            $sessionCond = '';
818
        }
819
820
        $where = " WHERE c_id = '%s' AND s.status <> 2 $sessionCond";
821
822
        $limit = null;
823
        if (!empty($options['limit'])) {
824
            $limit = " LIMIT ".$options['limit'];
825
        }
826
827
        if (!empty($options['where'])) {
828
            $where .= ' '.$options['where'];
829
        }
830
831
        $order = null;
832
        if (!empty($options['order'])) {
833
            $order = " ORDER BY ".$options['order'];
834
        }
835
836
        $sql = "SELECT u.id as user_id, u.lastname, u.firstname, u.username, u.email, s.c_id
837
                FROM $session_course_user s
838
                INNER JOIN $user u ON u.id = s.user_id
839
                $where
840
                $order
841
                $limit";
842
843
        $sql_query = sprintf($sql, Database::escape_string($course['real_id']), $sessionId);
844
845
        $rs = Database::query($sql_query);
846
        while ($user = Database::fetch_array($rs)) {
847
            $users[$user['user_id']] = $user;
848
        }
849
850
        // Get lessons
851
        $lessons = LearnpathList::get_course_lessons($course['code'], $sessionId);
852
853
        $table = [];
854
        foreach ($users as $user) {
855
            $data = [
856
                'lastname' => $user[1],
857
                'firstname' => $user[2],
858
                'username' => $user[3],
859
            ];
860
861
            $sessionCond = 'AND v.session_id = %d';
862
            if ($sessionId == 'T') {
863
                $sessionCond = "";
864
            }
865
866
            //Get lessons progress by user
867
            $sql = "SELECT v.lp_id as id, v.progress
868
                    FROM  $tbl_course_lp_view v
869
                    WHERE v.c_id = %d
870
                    AND v.user_id = %d
871
            $sessionCond";
872
873
            $sql_query = sprintf(
874
                $sql,
875
                intval($courseId),
876
                intval($user['user_id']),
877
                $sessionId
878
            );
879
880
            $result = Database::query($sql_query);
881
882
            $user_lessons = [];
883
            while ($row = Database::fetch_array($result)) {
884
                $user_lessons[$row['id']] = $row;
885
            }
886
887
            //Match course lessons with user progress
888
            $progress = 0;
889
            $count = 0;
890
            foreach ($lessons as $lesson) {
891
                $data[$lesson['id']] = (!empty($user_lessons[$lesson['id']]['progress'])) ? $user_lessons[$lesson['id']]['progress'] : 0;
892
                $progress += $data[$lesson['id']];
893
                $data[$lesson['id']] = $data[$lesson['id']].'%';
894
                $count++;
895
            }
896
            if ($count == 0) {
897
                $data['total'] = 0;
898
            } else {
899
                $data['total'] = round($progress / $count, 2).'%';
900
            }
901
            $table[] = $data;
902
        }
903
904
        return $table;
905
    }
906
907
    /**
908
     * Gets the survey answers.
909
     *
910
     * @param int $sessionId
911
     * @param int $courseId
912
     * @param int $surveyId
913
     * @param array options order and limit keys
914
     *
915
     * @todo fix the query
916
     *
917
     * @return array table with user name, lp name, progress
918
     */
919
    public static function get_survey_overview(
920
        $sessionId,
921
        $courseId,
922
        $surveyId,
923
        $date_from,
924
        $date_to,
925
        $options
926
    ) {
927
        //escaping vars
928
        $sessionId = intval($sessionId);
929
        $courseId = intval($courseId);
930
        $surveyId = intval($surveyId);
931
932
        //tables
933
        $session_course_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
934
        $user = Database::get_main_table(TABLE_MAIN_USER);
935
        $c_survey = Database::get_course_table(TABLE_SURVEY);
936
        $c_survey_answer = Database::get_course_table(TABLE_SURVEY_ANSWER);
937
        $c_survey_question = Database::get_course_table(TABLE_SURVEY_QUESTION);
938
        $c_survey_question_option = Database::get_course_table(TABLE_SURVEY_QUESTION_OPTION);
939
940
        $course = api_get_course_info_by_id($courseId);
941
942
        $where = " WHERE c_id = '%s' AND s.status <> 2 AND session_id = %s";
943
944
        $limit = null;
945
        if (!empty($options['limit'])) {
946
            $limit = " LIMIT ".$options['limit'];
947
        }
948
949
        if (!empty($options['where'])) {
950
            $where .= ' '.$options['where'];
951
        }
952
953
        $order = null;
954
        if (!empty($options['order'])) {
955
            $order = " ORDER BY ".$options['order'];
956
        }
957
958
        $sql = "SELECT u.user_id, u.lastname, u.firstname, u.username, u.email, s.c_id
959
                FROM $session_course_user s
960
                INNER JOIN $user u ON u.user_id = s.user_id
961
                $where $order $limit";
962
963
        $sql_query = sprintf($sql, intval($course['real_id']), $sessionId);
964
        $rs = Database::query($sql_query);
965
        while ($user = Database::fetch_array($rs)) {
966
            $users[$user['user_id']] = $user;
967
        }
968
969
        //Get survey questions
970
        $questions = SurveyManager::get_questions($surveyId, $courseId);
971
972
        //Survey is anonymous?
973
        $result = Database::query(sprintf("SELECT anonymous FROM $c_survey WHERE survey_id = %d", $surveyId));
974
        $row = Database::fetch_array($result);
975
        $anonymous = ($row['anonymous'] == 1) ? true : false;
976
977
        $table = [];
978
        foreach ($users as $user) {
979
            $data = [
980
                'lastname' => ($anonymous ? '***' : $user[1]),
981
                'firstname' => ($anonymous ? '***' : $user[2]),
982
                'username' => ($anonymous ? '***' : $user[3]),
983
            ];
984
985
            //Get questions by user
986
            $sql = "SELECT sa.question_id, sa.option_id, sqo.option_text, sq.type
987
                    FROM $c_survey_answer sa
988
                    INNER JOIN $c_survey_question sq
989
                    ON sq.question_id = sa.question_id
990
                    LEFT JOIN $c_survey_question_option sqo
991
                    ON
992
                      sqo.c_id = sa.c_id AND
993
                      sqo.question_id = sq.question_id AND
994
                      sqo.question_option_id = sa.option_id AND
995
                      sqo.survey_id = sq.survey_id
996
                    WHERE
997
                      sa.survey_id = %d AND
998
                      sa.c_id = %d AND
999
                      sa.user = %d
1000
            "; //. $where_survey;
1001
            $sql_query = sprintf($sql, $surveyId, $courseId, $user['user_id']);
1002
1003
            $result = Database::query($sql_query);
1004
1005
            $user_questions = [];
1006
            while ($row = Database::fetch_array($result)) {
1007
                $user_questions[$row['question_id']] = $row;
1008
            }
1009
1010
            //Match course lessons with user progress
1011
            foreach ($questions as $question_id => $question) {
1012
                $option_text = 'option_text';
1013
                if ($user_questions[$question_id]['type'] == 'open') {
1014
                    $option_text = 'option_id';
1015
                }
1016
                $data[$question_id] = $user_questions[$question_id][$option_text];
1017
            }
1018
1019
            $table[] = $data;
1020
        }
1021
1022
        return $table;
1023
    }
1024
1025
    /**
1026
     * Gets the progress of the given session.
1027
     *
1028
     * @param int $sessionId
1029
     * @param int $courseId
1030
     * @param array options order and limit keys
1031
     *
1032
     * @return array table with user name, lp name, progress
1033
     */
1034
    public static function get_session_progress(
1035
        $sessionId,
1036
        $courseId,
1037
        $date_from,
1038
        $date_to,
1039
        $options
1040
    ) {
1041
        $sessionId = (int) $sessionId;
1042
1043
        $getAllSessions = false;
1044
        if (empty($sessionId)) {
1045
            $sessionId = 0;
1046
            $getAllSessions = true;
1047
        }
1048
1049
        //tables
1050
        $session_course_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
1051
        $user = Database::get_main_table(TABLE_MAIN_USER);
1052
        $workTable = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
1053
        $workTableAssignment = Database::get_course_table(TABLE_STUDENT_PUBLICATION_ASSIGNMENT);
1054
        $tbl_course_lp = Database::get_course_table(TABLE_LP_MAIN);
1055
        $wiki = Database::get_course_table(TABLE_WIKI);
1056
        $table_stats_default = Database::get_main_table(TABLE_STATISTIC_TRACK_E_DEFAULT);
1057
        $table_stats_access = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ACCESS);
1058
1059
        $course = api_get_course_info_by_id($courseId);
1060
        $where = " WHERE c_id = '%s' AND s.status <> 2 ";
1061
1062
        $limit = null;
1063
        if (!empty($options['limit'])) {
1064
            $limit = " LIMIT ".$options['limit'];
1065
        }
1066
1067
        if (!empty($options['where'])) {
1068
            $where .= ' '.$options['where'];
1069
        }
1070
1071
        $order = null;
1072
        if (!empty($options['order'])) {
1073
            $order = " ORDER BY ".$options['order'];
1074
        }
1075
1076
        //TODO, fix create report without session
1077
        $queryVariables = [$course['real_id']];
1078
        if (!empty($sessionId)) {
1079
            $where .= ' AND session_id = %s';
1080
            $queryVariables[] = $sessionId;
1081
            $sql = "SELECT
1082
                        u.user_id, u.lastname, u.firstname, u.username,
1083
                        u.email, s.c_id, s.session_id
1084
                    FROM $session_course_user s
1085
                    INNER JOIN $user u
1086
                    ON u.user_id = s.user_id
1087
                    $where $order $limit";
1088
        } else {
1089
            $sql = "SELECT
1090
                        u.user_id, u.lastname, u.firstname, u.username,
1091
                        u.email, s.c_id, s.session_id
1092
                    FROM $session_course_user s
1093
                    INNER JOIN $user u ON u.user_id = s.user_id
1094
                    $where $order $limit";
1095
        }
1096
1097
        $sql_query = vsprintf($sql, $queryVariables);
1098
        $rs = Database::query($sql_query);
1099
        while ($user = Database::fetch_array($rs)) {
1100
            $users[$user['user_id']] = $user;
1101
        }
1102
1103
        /**
1104
         *  Lessons.
1105
         */
1106
        $sql = "SELECT * FROM $tbl_course_lp WHERE c_id = %s "; //AND session_id = %s
1107
        $sql_query = sprintf($sql, $course['real_id']);
1108
        $result = Database::query($sql_query);
1109
        $arrLesson = [[]];
1110
        while ($row = Database::fetch_array($result)) {
1111
            if (empty($arrLesson[$row['session_id']]['lessons_total'])) {
1112
                $arrLesson[$row['session_id']]['lessons_total'] = 1;
1113
            } else {
1114
                $arrLesson[$row['session_id']]['lessons_total']++;
1115
            }
1116
        }
1117
1118
        /**
1119
         *  Exercises.
1120
         */
1121
        $exercises = ExerciseLib::get_all_exercises(
1122
            $course,
1123
            $sessionId,
1124
            false,
1125
            '',
1126
            $getAllSessions
1127
        );
1128
        $exercises_total = count($exercises);
1129
1130
        /**
1131
         *  Assignments.
1132
         */
1133
        //total
1134
        $params = [$course['real_id']];
1135
        if ($getAllSessions) {
1136
            $sql = "SELECT count(w.id) as count
1137
                    FROM $workTable w
1138
                    LEFT JOIN $workTableAssignment a
1139
                    ON (a.publication_id = w.id AND a.c_id = w.c_id)
1140
                    WHERE
1141
                        w.c_id = %s AND
1142
                        parent_id = 0 AND
1143
                        active IN (1, 0)";
1144
        } else {
1145
            $sql = "SELECT count(w.id) as count
1146
                    FROM $workTable w
1147
                    LEFT JOIN $workTableAssignment a
1148
                    ON (a.publication_id = w.id AND a.c_id = w.c_id)
1149
                    WHERE
1150
                        w.c_id = %s AND
1151
                        parent_id = 0 AND
1152
                        active IN (1, 0)";
1153
1154
            if (empty($sessionId)) {
1155
                $sql .= ' AND w.session_id = NULL ';
1156
            } else {
1157
                $sql .= ' AND w.session_id = %s ';
1158
                $params[] = $sessionId;
1159
            }
1160
        }
1161
1162
        $sql_query = vsprintf($sql, $params);
1163
        $result = Database::query($sql_query);
1164
        $row = Database::fetch_array($result);
1165
        $assignments_total = $row['count'];
1166
1167
        /**
1168
         * Wiki.
1169
         */
1170
        if ($getAllSessions) {
1171
            $sql = "SELECT count(distinct page_id)  as count FROM $wiki
1172
                    WHERE c_id = %s";
1173
        } else {
1174
            $sql = "SELECT count(distinct page_id)  as count FROM $wiki
1175
                    WHERE c_id = %s and session_id = %s";
1176
        }
1177
        $sql_query = sprintf($sql, $course['real_id'], $sessionId);
1178
        $result = Database::query($sql_query);
1179
        $row = Database::fetch_array($result);
1180
        $wiki_total = $row['count'];
1181
1182
        /**
1183
         * Surveys.
1184
         */
1185
        $survey_user_list = [];
1186
        $survey_list = SurveyManager::get_surveys($course['code'], $sessionId);
1187
1188
        $surveys_total = count($survey_list);
1189
        foreach ($survey_list as $survey) {
1190
            $user_list = SurveyManager::get_people_who_filled_survey(
1191
                $survey['survey_id'],
1192
                false,
1193
                $course['real_id']
1194
            );
1195
            foreach ($user_list as $user_id) {
1196
                isset($survey_user_list[$user_id]) ? $survey_user_list[$user_id]++ : $survey_user_list[$user_id] = 1;
1197
            }
1198
        }
1199
1200
        /**
1201
         * Forums.
1202
         */
1203
        $forums_total = CourseManager::getCountForum(
1204
            $course['real_id'],
1205
            $sessionId,
1206
            $getAllSessions
1207
        );
1208
1209
        //process table info
1210
        foreach ($users as $user) {
1211
            //Course description
1212
            $sql = "SELECT count(*) as count
1213
                    FROM $table_stats_access
1214
                    WHERE access_tool = 'course_description'
1215
                    AND c_id = '%s'
1216
                    AND access_session_id = %s
1217
                    AND access_user_id = %s ";
1218
            $sql_query = sprintf($sql, $course['real_id'], $user['id_session'], $user['user_id']);
1219
1220
            $result = Database::query($sql_query);
1221
            $row = Database::fetch_array($result);
1222
            $course_description_progress = ($row['count'] > 0) ? 100 : 0;
1223
1224
            if (!empty($arrLesson[$user['id_session']]['lessons_total'])) {
1225
                $lessons_total = $arrLesson[$user['id_session']]['lessons_total'];
1226
            } else {
1227
                $lessons_total = !empty($arrLesson[0]['lessons_total']) ? $arrLesson[0]['lessons_total'] : 0;
1228
            }
1229
1230
            //Lessons
1231
            //TODO: Lessons done and left is calculated by progress per item in lesson, maybe we should calculate it only per completed lesson?
1232
            $lessons_progress = Tracking::get_avg_student_progress(
1233
                $user['user_id'],
1234
                $course['code'],
1235
                [],
1236
                $user['id_session']
1237
            );
1238
            $lessons_done = ($lessons_progress * $lessons_total) / 100;
1239
            $lessons_left = $lessons_total - $lessons_done;
1240
1241
            // Exercises
1242
            $exercises_progress = str_replace(
1243
                '%',
1244
                '',
1245
                Tracking::get_exercise_student_progress(
1246
                    $exercises,
1247
                    $user['user_id'],
1248
                    $course['real_id'],
1249
                    $user['id_session']
1250
                )
1251
            );
1252
            $exercises_done = round(($exercises_progress * $exercises_total) / 100);
1253
            $exercises_left = $exercises_total - $exercises_done;
1254
1255
            //Assignments
1256
            $assignments_done = Tracking::count_student_assignments($user['user_id'], $course['code'], $user['id_session']);
1257
            $assignments_left = $assignments_total - $assignments_done;
1258
            if (!empty($assignments_total)) {
1259
                $assignments_progress = round((($assignments_done * 100) / $assignments_total), 2);
1260
            } else {
1261
                $assignments_progress = 0;
1262
            }
1263
1264
            // Wiki
1265
            // total revisions per user
1266
            $sql = "SELECT count(*) as count
1267
                    FROM $wiki
1268
                    WHERE c_id = %s and session_id = %s and user_id = %s";
1269
            $sql_query = sprintf($sql, $course['real_id'], $user['id_session'], $user['user_id']);
1270
            $result = Database::query($sql_query);
1271
            $row = Database::fetch_array($result);
1272
            $wiki_revisions = $row['count'];
1273
            //count visited wiki pages
1274
            $sql = "SELECT count(distinct default_value) as count
1275
                    FROM $table_stats_default
1276
                    WHERE
1277
                        default_user_id = %s AND
1278
                        default_event_type = 'wiki_page_view' AND
1279
                        default_value_type = 'wiki_page_id' AND
1280
                        c_id = %s
1281
                    ";
1282
            $sql_query = sprintf($sql, $user['user_id'], $course['real_id']);
1283
            $result = Database::query($sql_query);
1284
            $row = Database::fetch_array($result);
1285
1286
            $wiki_read = $row['count'];
1287
            $wiki_unread = $wiki_total - $wiki_read;
1288
            if (!empty($wiki_total)) {
1289
                $wiki_progress = round((($wiki_read * 100) / $wiki_total), 2);
1290
            } else {
1291
                $wiki_progress = 0;
1292
            }
1293
1294
            //Surveys
1295
            $surveys_done = (isset($survey_user_list[$user['user_id']]) ? $survey_user_list[$user['user_id']] : 0);
1296
            $surveys_left = $surveys_total - $surveys_done;
1297
            if (!empty($surveys_total)) {
1298
                $surveys_progress = round((($surveys_done * 100) / $surveys_total), 2);
1299
            } else {
1300
                $surveys_progress = 0;
1301
            }
1302
1303
            //Forums
1304
            $forums_done = CourseManager::getCountForumPerUser(
1305
                $user['user_id'],
1306
                $course['real_id'],
1307
                $user['id_session']
1308
            );
1309
            $forums_left = $forums_total - $forums_done;
1310
            if (!empty($forums_total)) {
1311
                $forums_progress = round((($forums_done * 100) / $forums_total), 2);
1312
            } else {
1313
                $forums_progress = 0;
1314
            }
1315
1316
            // Overall Total
1317
            $overall_total = ($course_description_progress + $exercises_progress + $forums_progress + $assignments_progress + $wiki_progress + $surveys_progress) / 6;
1318
1319
            $link = '<a href="'.api_get_path(WEB_CODE_PATH).'mySpace/myStudents.php?student='.$user[0].'&details=true&course='.$course['code'].'&id_session='.$user['id_session'].'"> %s </a>';
1320
            $linkForum = '<a href="'.api_get_path(WEB_CODE_PATH).'forum/index.php?cidReq='.$course['code'].'&id_session='.$user['id_session'].'"> %s </a>';
1321
            $linkWork = '<a href="'.api_get_path(WEB_CODE_PATH).'work/work.php?cidReq='.$course['code'].'&id_session='.$user['id_session'].'"> %s </a>';
1322
            $linkWiki = '<a href="'.api_get_path(WEB_CODE_PATH).'wiki/index.php?cidReq='.$course['code'].'&session_id='.$user['id_session'].'&action=statistics"> %s </a>';
1323
            $linkSurvey = '<a href="'.api_get_path(WEB_CODE_PATH).'survey/survey_list.php?cidReq='.$course['code'].'&id_session='.$user['id_session'].'"> %s </a>';
1324
1325
            $table[] = [
1326
                'lastname' => $user[1],
1327
                'firstname' => $user[2],
1328
                'username' => $user[3],
1329
                //'profile'   => '',
1330
                'total' => round($overall_total, 2).'%',
1331
                'courses' => sprintf($link, $course_description_progress.'%'),
1332
                'lessons' => sprintf($link, $lessons_progress.'%'),
1333
                'exercises' => sprintf($link, $exercises_progress.'%'),
1334
                'forums' => sprintf($link, $forums_progress.'%'),
1335
                'homeworks' => sprintf($link, $assignments_progress.'%'),
1336
                'wikis' => sprintf($link, $wiki_progress.'%'),
1337
                'surveys' => sprintf($link, $surveys_progress.'%'),
1338
                //course description
1339
                'course_description_progress' => $course_description_progress.'%',
1340
                //lessons
1341
                'lessons_total' => sprintf($link, $lessons_total),
1342
                'lessons_done' => sprintf($link, $lessons_done),
1343
                'lessons_left' => sprintf($link, $lessons_left),
1344
                'lessons_progress' => sprintf($link, $lessons_progress.'%'),
1345
                //exercises
1346
                'exercises_total' => sprintf($link, $exercises_total),
1347
                'exercises_done' => sprintf($link, $exercises_done),
1348
                'exercises_left' => sprintf($link, $exercises_left),
1349
                'exercises_progress' => sprintf($link, $exercises_progress.'%'),
1350
                //forums
1351
                'forums_total' => sprintf($linkForum, $forums_total),
1352
                'forums_done' => sprintf($linkForum, $forums_done),
1353
                'forums_left' => sprintf($linkForum, $forums_left),
1354
                'forums_progress' => sprintf($linkForum, $forums_progress.'%'),
1355
                //assignments
1356
                'assignments_total' => sprintf($linkWork, $assignments_total),
1357
                'assignments_done' => sprintf($linkWork, $assignments_done),
1358
                'assignments_left' => sprintf($linkWork, $assignments_left),
1359
                'assignments_progress' => sprintf($linkWork, $assignments_progress.'%'),
1360
                //wiki
1361
                'wiki_total' => sprintf($linkWiki, $wiki_total),
1362
                'wiki_revisions' => sprintf($linkWiki, $wiki_revisions),
1363
                'wiki_read' => sprintf($linkWiki, $wiki_read),
1364
                'wiki_unread' => sprintf($linkWiki, $wiki_unread),
1365
                'wiki_progress' => sprintf($linkWiki, $wiki_progress.'%'),
1366
                //survey
1367
                'surveys_total' => sprintf($linkSurvey, $surveys_total),
1368
                'surveys_done' => sprintf($linkSurvey, $surveys_done),
1369
                'surveys_left' => sprintf($linkSurvey, $surveys_left),
1370
                'surveys_progress' => sprintf($linkSurvey, $surveys_progress.'%'),
1371
            ];
1372
        }
1373
1374
        return $table;
1375
    }
1376
1377
    /**
1378
     * Get the ip, total of clicks, login date and time logged in for all user, in one session.
1379
     *
1380
     * @todo track_e_course_access table should have ip so we dont have to look for it in track_e_login
1381
     *
1382
     * @author César Perales <[email protected]>, Beeznest Team
1383
     *
1384
     * @version 1.9.6
1385
     */
1386
    public static function get_user_data_access_tracking_overview(
1387
        $sessionId,
1388
        $courseId,
1389
        $studentId = 0,
1390
        $profile = '',
1391
        $date_from = '',
1392
        $date_to = '',
1393
        $options = []
1394
    ) {
1395
        $sessionId = intval($sessionId);
1396
        $courseId = intval($courseId);
1397
        $studentId = intval($studentId);
1398
        $profile = intval($profile);
1399
        $date_from = Database::escape_string($date_from);
1400
        $date_to = Database::escape_string($date_to);
1401
1402
        // database table definition
1403
        $user = Database::get_main_table(TABLE_MAIN_USER);
1404
        $course = Database::get_main_table(TABLE_MAIN_COURSE);
1405
        $track_e_login = Database::get_main_table(TABLE_STATISTIC_TRACK_E_LOGIN);
1406
        $track_e_course_access = Database::get_main_table(TABLE_STATISTIC_TRACK_E_COURSE_ACCESS);
1407
        $sessionTable = Database::get_main_table(TABLE_MAIN_SESSION);
1408
1409
        global $export_csv;
1410
        if ($export_csv) {
1411
            $is_western_name_order = api_is_western_name_order(PERSON_NAME_DATA_EXPORT);
1412
        } else {
1413
            $is_western_name_order = api_is_western_name_order();
1414
        }
1415
1416
        $where = null;
1417
        if (isset($sessionId) && !empty($sessionId)) {
1418
            $where = sprintf(" WHERE a.session_id = %d", $sessionId);
1419
        }
1420
        if (isset($courseId) && !empty($courseId)) {
1421
            $where .= sprintf(" AND c.id = %d", $courseId);
1422
        }
1423
        if (isset($studentId) && !empty($studentId)) {
1424
            $where .= sprintf(" AND u.user_id = %d", $studentId);
1425
        }
1426
        if (isset($profile) && !empty($profile)) {
1427
            $where .= sprintf(" AND u.status = %d", $profile);
1428
        }
1429
        if (!empty($date_to) && !empty($date_from)) {
1430
            $where .= sprintf(
1431
                " AND a.login_course_date >= '%s 00:00:00'
1432
                 AND a.login_course_date <= '%s 23:59:59'",
1433
                $date_from,
1434
                $date_to
1435
            );
1436
        }
1437
1438
        $limit = null;
1439
        if (!empty($options['limit'])) {
1440
            $limit = " LIMIT ".$options['limit'];
1441
        }
1442
1443
        if (!empty($options['where'])) {
1444
            $where .= ' '.$options['where'];
1445
        }
1446
1447
        $order = null;
1448
        if (!empty($options['order'])) {
1449
            $order = " ORDER BY ".$options['order'];
1450
        }
1451
1452
        //TODO add course name
1453
        $sql = "SELECT
1454
                a.login_course_date ,
1455
                u.username ,
1456
                ".($is_western_name_order ? "
1457
                    u.firstname,
1458
                    u.lastname,
1459
                    " : "
1460
                    u.lastname,
1461
                    u.firstname,
1462
                ")."
1463
                a.logout_course_date,
1464
                a.counter,
1465
                c.title,
1466
                c.code,
1467
                u.user_id,
1468
                a.session_id
1469
            FROM $track_e_course_access a
1470
            INNER JOIN $user u ON a.user_id = u.user_id
1471
            INNER JOIN $course c ON a.c_id = c.id
1472
            $where $order $limit";
1473
        $result = Database::query(sprintf($sql, $sessionId, $courseId));
1474
1475
        $data = [];
1476
        while ($user = Database::fetch_assoc($result)) {
1477
            $data[] = $user;
1478
        }
1479
1480
        foreach ($data as $key => $info) {
1481
            $sql = "SELECT
1482
                    name
1483
                    FROM $sessionTable
1484
                    WHERE
1485
                    id = {$info['session_id']}";
1486
            $result = Database::query($sql);
1487
            $session = Database::fetch_assoc($result);
1488
1489
            // building array to display
1490
            $return[] = [
1491
                'user_id' => $info['user_id'],
1492
                'logindate' => $info['login_course_date'],
1493
                'username' => $info['username'],
1494
                'firstname' => $info['firstname'],
1495
                'lastname' => $info['lastname'],
1496
                'clicks' => $info['counter'], //+ $clicks[$info['user_id']],
1497
                'ip' => '',
1498
                'timeLoggedIn' => gmdate("H:i:s", strtotime($info['logout_course_date']) - strtotime($info['login_course_date'])),
1499
                'session' => $session['name'],
1500
            ];
1501
        }
1502
1503
        foreach ($return as $key => $info) {
1504
            //Search for ip, we do less querys if we iterate the final array
1505
            $sql = sprintf(
1506
                "SELECT user_ip FROM $track_e_login WHERE login_user_id = %d AND login_date < '%s' ORDER BY login_date DESC LIMIT 1",
1507
                $info['user_id'],
1508
                $info['logindate']
1509
            ); //TODO add select by user too
1510
            $result = Database::query($sql);
1511
            $ip = Database::fetch_assoc($result);
1512
            //if no ip founded, we search the closest higher ip
1513
            if (empty($ip['user_ip'])) {
1514
                $sql = sprintf(
1515
                    "SELECT user_ip FROM $track_e_login WHERE login_user_id = %d AND login_date > '%s'  ORDER BY login_date ASC LIMIT 1",
1516
                    $info['user_id'],
1517
                    $info['logindate']
1518
                ); //TODO add select by user too
1519
                $result = Database::query($sql);
1520
                $ip = Database::fetch_assoc($result);
1521
            }
1522
            //add ip to final array
1523
            $return[$key]['ip'] = $ip['user_ip'];
1524
        }
1525
1526
        return $return;
1527
    }
1528
1529
    /**
1530
     * Creates a new course code based in given code.
1531
     *
1532
     * @param string $session_name
1533
     *                             <code>
1534
     *                             $wanted_code = 'curse' if there are in the DB codes like curse1 curse2 the function will return: course3
1535
     *                             if the course code doest not exist in the DB the same course code will be returned
1536
     *                             </code>
1537
     *
1538
     * @return string wanted unused code
1539
     */
1540
    public static function generateNextSessionName($session_name)
1541
    {
1542
        $session_name_ok = !self::sessionNameExists($session_name);
1543
        if (!$session_name_ok) {
1544
            $table = Database::get_main_table(TABLE_MAIN_SESSION);
1545
            $session_name = Database::escape_string($session_name);
1546
            $sql = "SELECT count(*) as count FROM $table
1547
                    WHERE name LIKE '$session_name%'";
1548
            $result = Database::query($sql);
1549
            if (Database::num_rows($result) > 0) {
1550
                $row = Database::fetch_array($result);
1551
                $count = $row['count'] + 1;
1552
                $session_name = $session_name.'_'.$count;
1553
                $result = self::sessionNameExists($session_name);
1554
                if (!$result) {
1555
                    return $session_name;
1556
                }
1557
            }
1558
1559
            return false;
1560
        }
1561
1562
        return $session_name;
1563
    }
1564
1565
    /**
1566
     * Edit a session.
1567
     *
1568
     * @author Carlos Vargas from existing code
1569
     *
1570
     * @param int    $id                           Session primary key
1571
     * @param string $name
1572
     * @param string $startDate
1573
     * @param string $endDate
1574
     * @param string $displayStartDate
1575
     * @param string $displayEndDate
1576
     * @param string $coachStartDate
1577
     * @param string $coachEndDate
1578
     * @param int    $coachId
1579
     * @param int    $sessionCategoryId
1580
     * @param int    $visibility
1581
     * @param string $description
1582
     * @param int    $showDescription
1583
     * @param int    $duration
1584
     * @param array  $extraFields
1585
     * @param int    $sessionAdminId
1586
     * @param bool   $sendSubscriptionNotification Optional. Whether send a mail notification to users being subscribed
1587
     * @param int    $status
1588
     *
1589
     * @return mixed
1590
     */
1591
    public static function edit_session(
1592
        $id,
1593
        $name,
1594
        $startDate,
1595
        $endDate,
1596
        $displayStartDate,
1597
        $displayEndDate,
1598
        $coachStartDate,
1599
        $coachEndDate,
1600
        $coachId,
1601
        $sessionCategoryId,
1602
        $visibility,
1603
        $description = null,
1604
        $showDescription = 0,
1605
        $duration = null,
1606
        $extraFields = [],
1607
        $sessionAdminId = 0,
1608
        $sendSubscriptionNotification = false,
1609
        $status = 0
1610
    ) {
1611
        $status = (int) $status;
1612
        $coachId = (int) $coachId;
1613
        $sessionCategoryId = (int) $sessionCategoryId;
1614
        $visibility = (int) $visibility;
1615
        $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
1616
1617
        if (empty($name)) {
1618
            Display::addFlash(
1619
                Display::return_message(get_lang('SessionNameIsRequired'), 'warning')
1620
            );
1621
1622
            return false;
1623
        } elseif (empty($coachId)) {
1624
            Display::addFlash(
1625
                Display::return_message(get_lang('CoachIsRequired'), 'warning')
1626
            );
1627
1628
            return false;
1629
        } elseif (!empty($startDate) &&
1630
            !api_is_valid_date($startDate, 'Y-m-d H:i') &&
1631
            !api_is_valid_date($startDate, 'Y-m-d H:i:s')
1632
        ) {
1633
            Display::addFlash(
1634
                Display::return_message(get_lang('InvalidStartDate'), 'warning')
1635
            );
1636
1637
            return false;
1638
        } elseif (!empty($endDate) &&
1639
            !api_is_valid_date($endDate, 'Y-m-d H:i') &&
1640
            !api_is_valid_date($endDate, 'Y-m-d H:i:s')
1641
        ) {
1642
            Display::addFlash(
1643
                Display::return_message(get_lang('InvalidEndDate'), 'warning')
1644
            );
1645
1646
            return false;
1647
        } elseif (!empty($startDate) && !empty($endDate) && $startDate >= $endDate) {
1648
            Display::addFlash(
1649
                Display::return_message(get_lang('StartDateShouldBeBeforeEndDate'), 'warning')
1650
            );
1651
1652
            return false;
1653
        } else {
1654
            $sessionInfo = self::get_session_by_name($name);
1655
            $exists = false;
1656
1657
            if (!empty($sessionInfo)) {
1658
                if ($sessionInfo['id'] != $id) {
1659
                    $exists = true;
1660
                }
1661
            }
1662
1663
            if ($exists) {
1664
                Display::addFlash(
1665
                    Display::return_message(get_lang('SessionNameAlreadyExists'), 'warning')
1666
                );
1667
1668
                return false;
1669
            } else {
1670
                $values = [
1671
                    'name' => $name,
1672
                    'duration' => $duration,
1673
                    'id_coach' => $coachId,
1674
                    'description' => $description,
1675
                    'show_description' => intval($showDescription),
1676
                    'visibility' => $visibility,
1677
                    'send_subscription_notification' => $sendSubscriptionNotification,
1678
                    'access_start_date' => null,
1679
                    'access_end_date' => null,
1680
                    'display_start_date' => null,
1681
                    'display_end_date' => null,
1682
                    'coach_access_start_date' => null,
1683
                    'coach_access_end_date' => null,
1684
                ];
1685
1686
                if (!empty($sessionAdminId)) {
1687
                    $values['session_admin_id'] = $sessionAdminId;
1688
                }
1689
1690
                if (!empty($startDate)) {
1691
                    $values['access_start_date'] = api_get_utc_datetime($startDate);
1692
                }
1693
1694
                if (!empty($endDate)) {
1695
                    $values['access_end_date'] = api_get_utc_datetime($endDate);
1696
                }
1697
1698
                if (!empty($displayStartDate)) {
1699
                    $values['display_start_date'] = api_get_utc_datetime($displayStartDate);
1700
                }
1701
1702
                if (!empty($displayEndDate)) {
1703
                    $values['display_end_date'] = api_get_utc_datetime($displayEndDate);
1704
                }
1705
1706
                if (!empty($coachStartDate)) {
1707
                    $values['coach_access_start_date'] = api_get_utc_datetime($coachStartDate);
1708
                }
1709
                if (!empty($coachEndDate)) {
1710
                    $values['coach_access_end_date'] = api_get_utc_datetime($coachEndDate);
1711
                }
1712
1713
                $values['session_category_id'] = null;
1714
                if (!empty($sessionCategoryId)) {
1715
                    $values['session_category_id'] = $sessionCategoryId;
1716
                }
1717
1718
                if (api_get_configuration_value('allow_session_status')) {
1719
                    $values['status'] = $status;
1720
                }
1721
1722
                Database::update(
1723
                    $tbl_session,
1724
                    $values,
1725
                    ['id = ?' => $id]
1726
                );
1727
1728
                if (!empty($extraFields)) {
1729
                    $extraFields['item_id'] = $id;
1730
                    $sessionFieldValue = new ExtraFieldValue('session');
1731
                    $sessionFieldValue->saveFieldValues($extraFields);
1732
                }
1733
1734
                return $id;
1735
            }
1736
        }
1737
    }
1738
1739
    /**
1740
     * Delete session.
1741
     *
1742
     * @author Carlos Vargas  from existing code
1743
     *
1744
     * @param array $id_checked an array to delete sessions
1745
     * @param bool  $from_ws    optional, true if the function is called
1746
     *                          by a webservice, false otherwise
1747
     *
1748
     * @return bool
1749
     * */
1750
    public static function delete($id_checked, $from_ws = false)
1751
    {
1752
        $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
1753
        $tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
1754
        $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
1755
        $tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
1756
        $tbl_url_session = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
1757
        $tbl_item_properties = Database::get_course_table(TABLE_ITEM_PROPERTY);
1758
        $tbl_student_publication = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
1759
        $tbl_student_publication_assignment = Database::get_course_table(TABLE_STUDENT_PUBLICATION_ASSIGNMENT);
1760
        $userGroupSessionTable = Database::get_main_table(TABLE_USERGROUP_REL_SESSION);
1761
        $trackCourseAccess = Database::get_main_table(TABLE_STATISTIC_TRACK_E_COURSE_ACCESS);
1762
        $trackAccess = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ACCESS);
1763
1764
        $ticket = Database::get_main_table(TABLE_TICKET_TICKET);
1765
        $em = Database::getManager();
1766
        $userId = api_get_user_id();
1767
1768
        /** @var SequenceResourceRepository $repo */
1769
        $repo = Database::getManager()->getRepository('ChamiloCoreBundle:SequenceResource');
1770
        $sequenceResource = $repo->findRequirementForResource(
1771
            $id_checked,
1772
            SequenceResource::SESSION_TYPE
1773
        );
1774
1775
        if ($sequenceResource) {
1776
            Display::addFlash(
1777
                Display::return_message(
1778
                    get_lang('ThereIsASequenceResourceLinkedToThisSessionYouNeedToDeleteItFirst'),
1779
                    'error'
1780
                )
1781
            );
1782
1783
            return false;
1784
        }
1785
1786
        if (is_array($id_checked)) {
1787
            foreach ($id_checked as $sessionId) {
1788
                self::delete($sessionId);
1789
            }
1790
        } else {
1791
            $id_checked = intval($id_checked);
1792
        }
1793
1794
        if (self::allowed($id_checked) && !$from_ws) {
1795
            $qb = $em
1796
                ->createQuery('
1797
                    SELECT s.sessionAdminId FROM ChamiloCoreBundle:Session s
1798
                    WHERE s.id = ?1
1799
                ')
1800
                ->setParameter(1, $id_checked);
1801
1802
            $res = $qb->getSingleScalarResult();
1803
1804
            if ($res != $userId && !api_is_platform_admin()) {
1805
                api_not_allowed(true);
1806
            }
1807
        }
1808
1809
        $sessionInfo = api_get_session_info($id_checked);
1810
1811
        // Delete documents inside a session
1812
        $courses = self::getCoursesInSession($id_checked);
1813
        foreach ($courses as $courseId) {
1814
            $courseInfo = api_get_course_info_by_id($courseId);
1815
            DocumentManager::deleteDocumentsFromSession($courseInfo, $id_checked);
1816
            $works = Database::select(
1817
                '*',
1818
                $tbl_student_publication,
1819
                [
1820
                    'where' => ['session_id = ? AND c_id = ?' => [$id_checked, $courseId]],
1821
                ]
1822
            );
1823
1824
            $currentCourseRepositorySys = api_get_path(SYS_COURSE_PATH).$courseInfo['path'].'/';
1825
            foreach ($works as $index => $work) {
1826
                if ($work['filetype'] = 'folder') {
1827
                    Database::query("DELETE FROM $tbl_student_publication_assignment WHERE publication_id = $index");
1828
                }
1829
                my_delete($currentCourseRepositorySys.'/'.$work['url']);
1830
            }
1831
        }
1832
1833
        // Class
1834
        $sql = "DELETE FROM $userGroupSessionTable
1835
                WHERE session_id IN($id_checked)";
1836
        Database::query($sql);
1837
1838
        Database::query("DELETE FROM $tbl_student_publication WHERE session_id IN($id_checked)");
1839
        Database::query("DELETE FROM $tbl_session_rel_course WHERE session_id IN($id_checked)");
1840
        Database::query("DELETE FROM $tbl_session_rel_course_rel_user WHERE session_id IN($id_checked)");
1841
        Database::query("DELETE FROM $tbl_session_rel_user WHERE session_id IN($id_checked)");
1842
        Database::query("DELETE FROM $tbl_item_properties WHERE session_id IN ($id_checked)");
1843
        Database::query("DELETE FROM $tbl_url_session WHERE session_id IN($id_checked)");
1844
1845
        Database::query("DELETE FROM $trackCourseAccess WHERE session_id IN($id_checked)");
1846
        Database::query("DELETE FROM $trackAccess WHERE access_session_id IN($id_checked)");
1847
1848
        if (api_get_configuration_value('allow_lp_subscription_to_usergroups')) {
1849
            $tableGroup = Database::get_course_table(TABLE_LP_REL_USERGROUP);
1850
            Database::query("DELETE FROM $tableGroup WHERE session_id IN($id_checked)");
1851
            $tableGroup = Database::get_course_table(TABLE_LP_CATEGORY_REL_USERGROUP);
1852
            Database::query("DELETE FROM $tableGroup WHERE session_id IN($id_checked)");
1853
        }
1854
1855
        $sql = "UPDATE $ticket SET session_id = NULL WHERE session_id IN ($id_checked)";
1856
        Database::query($sql);
1857
1858
        $app_plugin = new AppPlugin();
1859
        $app_plugin->performActionsWhenDeletingItem('session', $id_checked);
1860
1861
        $sql = "DELETE FROM $tbl_session WHERE id IN ($id_checked)";
1862
        Database::query($sql);
1863
1864
        $extraFieldValue = new ExtraFieldValue('session');
1865
        $extraFieldValue->deleteValuesByItem($id_checked);
1866
1867
        $repo->deleteResource(
1868
            $id_checked,
1869
            SequenceResource::SESSION_TYPE
1870
        );
1871
1872
        // Add event to system log
1873
        Event::addEvent(
1874
            LOG_SESSION_DELETE,
1875
            LOG_SESSION_ID,
1876
            $sessionInfo['name'].' - id:'.$id_checked,
1877
            api_get_utc_datetime(),
1878
            $userId
1879
        );
1880
1881
        return true;
1882
    }
1883
1884
    /**
1885
     * @param int $id promotion id
1886
     *
1887
     * @return bool
1888
     */
1889
    public static function clear_session_ref_promotion($id)
1890
    {
1891
        $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
1892
        $id = intval($id);
1893
        $sql = "UPDATE $tbl_session
1894
                SET promotion_id = 0
1895
                WHERE promotion_id = $id";
1896
        if (Database::query($sql)) {
1897
            return true;
1898
        } else {
1899
            return false;
1900
        }
1901
    }
1902
1903
    /**
1904
     * Subscribes students to the given session and optionally (default)
1905
     * unsubscribes previous users.
1906
     *
1907
     * @author Carlos Vargas from existing code
1908
     * @author Julio Montoya. Cleaning code.
1909
     *
1910
     * @param int   $sessionId
1911
     * @param array $userList
1912
     * @param int   $session_visibility
1913
     * @param bool  $empty_users
1914
     * @param bool  $registerUsersToAllCourses
1915
     *
1916
     * @return bool
1917
     */
1918
    public static function subscribeUsersToSession(
1919
        $sessionId,
1920
        $userList,
1921
        $session_visibility = SESSION_VISIBLE_READ_ONLY,
1922
        $empty_users = true,
1923
        $registerUsersToAllCourses = true
1924
    ) {
1925
        $sessionId = (int) $sessionId;
1926
1927
        if (empty($sessionId)) {
1928
            return false;
1929
        }
1930
1931
        foreach ($userList as $intUser) {
1932
            if ($intUser != strval(intval($intUser))) {
1933
                return false;
1934
            }
1935
        }
1936
1937
        $tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
1938
        $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
1939
        $tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
1940
        $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
1941
1942
        $session = api_get_session_entity($sessionId);
1943
1944
        // from function parameter
1945
        if (empty($session_visibility)) {
1946
            $session_visibility = $session->getVisibility();
1947
            //default status loaded if empty
1948
            // by default readonly 1
1949
            if (empty($session_visibility)) {
1950
                $session_visibility = SESSION_VISIBLE_READ_ONLY;
1951
            }
1952
        } else {
1953
            if (!in_array($session_visibility, [SESSION_VISIBLE_READ_ONLY, SESSION_VISIBLE, SESSION_INVISIBLE])) {
1954
                $session_visibility = SESSION_VISIBLE_READ_ONLY;
1955
            }
1956
        }
1957
1958
        $sql = "SELECT user_id FROM $tbl_session_rel_course_rel_user
1959
                WHERE session_id = $sessionId AND status = 0";
1960
        $result = Database::query($sql);
1961
        $existingUsers = [];
1962
        while ($row = Database::fetch_array($result)) {
1963
            $existingUsers[] = $row['user_id'];
1964
        }
1965
1966
        $sql = "SELECT c_id FROM $tbl_session_rel_course
1967
                WHERE session_id = $sessionId";
1968
        $result = Database::query($sql);
1969
        $course_list = [];
1970
        while ($row = Database::fetch_array($result)) {
1971
            $course_list[] = $row['c_id'];
1972
        }
1973
1974
        if ($session->getSendSubscriptionNotification() &&
1975
            is_array($userList)
1976
        ) {
1977
            // Sending emails only
1978
            foreach ($userList as $user_id) {
1979
                if (in_array($user_id, $existingUsers)) {
1980
                    continue;
1981
                }
1982
1983
                $tplSubject = new Template(
1984
                    null,
1985
                    false,
1986
                    false,
1987
                    false,
1988
                    false,
1989
                    false
1990
                );
1991
                $layoutSubject = $tplSubject->get_template(
1992
                    'mail/subject_subscription_to_session_confirmation.tpl'
1993
                );
1994
                $subject = $tplSubject->fetch($layoutSubject);
1995
                $user_info = api_get_user_info($user_id);
1996
1997
                $tplContent = new Template(
1998
                    null,
1999
                    false,
2000
                    false,
2001
                    false,
2002
                    false,
2003
                    false
2004
                );
2005
                // Variables for default template
2006
                $tplContent->assign('complete_name', stripslashes($user_info['complete_name']));
2007
                $tplContent->assign('session_name', $session->getName());
2008
                $tplContent->assign('session_coach', $session->getGeneralCoach()->getCompleteName());
2009
                $layoutContent = $tplContent->get_template(
2010
                    'mail/content_subscription_to_session_confirmation.tpl'
2011
                );
2012
                $content = $tplContent->fetch($layoutContent);
2013
2014
                api_mail_html(
2015
                    $user_info['complete_name'],
2016
                    $user_info['mail'],
2017
                    $subject,
2018
                    $content,
2019
                    api_get_person_name(
2020
                        api_get_setting('administratorName'),
2021
                        api_get_setting('administratorSurname')
2022
                    ),
2023
                    api_get_setting('emailAdministrator')
2024
                );
2025
            }
2026
        }
2027
2028
        if ($registerUsersToAllCourses) {
2029
            foreach ($course_list as $courseId) {
2030
                // for each course in the session
2031
                $nbr_users = 0;
2032
                $courseId = (int) $courseId;
2033
2034
                $sql = "SELECT DISTINCT user_id
2035
                        FROM $tbl_session_rel_course_rel_user
2036
                        WHERE
2037
                            session_id = $sessionId AND
2038
                            c_id = $courseId AND
2039
                            status = 0
2040
                        ";
2041
                $result = Database::query($sql);
2042
                $existingUsers = [];
2043
                while ($row = Database::fetch_array($result)) {
2044
                    $existingUsers[] = $row['user_id'];
2045
                }
2046
2047
                // Delete existing users
2048
                if ($empty_users) {
2049
                    foreach ($existingUsers as $existing_user) {
2050
                        if (!in_array($existing_user, $userList)) {
2051
                            self::unSubscribeUserFromCourseSession($existing_user, $courseId, $sessionId);
2052
                        }
2053
                    }
2054
                }
2055
2056
                // Replace with this new function
2057
                // insert new users into session_rel_course_rel_user and ignore if they already exist
2058
                foreach ($userList as $enreg_user) {
2059
                    if (!in_array($enreg_user, $existingUsers)) {
2060
                        $status = self::get_user_status_in_course_session(
2061
                            $enreg_user,
2062
                            $courseId,
2063
                            $sessionId
2064
                        );
2065
2066
                        // Avoid duplicate entries.
2067
                        if ($status === false || ($status !== false && $status != 0)) {
2068
                            $enreg_user = (int) $enreg_user;
2069
                            $sql = "INSERT IGNORE INTO $tbl_session_rel_course_rel_user (session_id, c_id, user_id, visibility, status)
2070
                                    VALUES($sessionId, $courseId, $enreg_user, $session_visibility, 0)";
2071
                            $result = Database::query($sql);
2072
                            if (Database::affected_rows($result)) {
2073
                                $nbr_users++;
2074
                            }
2075
2076
                            Event::addEvent(
2077
                                LOG_SESSION_ADD_USER_COURSE,
2078
                                LOG_USER_ID,
2079
                                $enreg_user,
2080
                                api_get_utc_datetime(),
2081
                                api_get_user_id(),
2082
                                $courseId,
2083
                                $sessionId
2084
                            );
2085
                        }
2086
                    }
2087
                }
2088
2089
                // Count users in this session-course relation
2090
                $sql = "SELECT COUNT(user_id) as nbUsers
2091
                        FROM $tbl_session_rel_course_rel_user
2092
                        WHERE session_id = $sessionId AND c_id = $courseId AND status<>2";
2093
                $rs = Database::query($sql);
2094
                [$nbr_users] = Database::fetch_array($rs);
2095
                // update the session-course relation to add the users total
2096
                $sql = "UPDATE $tbl_session_rel_course SET nbr_users = $nbr_users
2097
                        WHERE session_id = $sessionId AND c_id = $courseId";
2098
                Database::query($sql);
2099
            }
2100
        }
2101
2102
        // Delete users from the session
2103
        if (true === $empty_users) {
2104
            $sql = "DELETE FROM $tbl_session_rel_user
2105
                    WHERE
2106
                      session_id = $sessionId AND
2107
                      relation_type <> ".SESSION_RELATION_TYPE_RRHH;
2108
            // Don't reset session_rel_user.registered_at of users that will be registered later anyways.
2109
            if (!empty($userList)) {
2110
                $avoidDeleteThisUsers = " AND user_id NOT IN ('".implode("','", $userList)."')";
2111
                $sql .= $avoidDeleteThisUsers;
2112
            }
2113
            Event::addEvent(
2114
                LOG_SESSION_DELETE_USER,
2115
                LOG_USER_ID,
2116
                'all',
2117
                api_get_utc_datetime(),
2118
                api_get_user_id(),
2119
                null,
2120
                $sessionId
2121
            );
2122
            Database::query($sql);
2123
        }
2124
2125
        // Insert missing users into session
2126
        foreach ($userList as $enreg_user) {
2127
            $isUserSubscribed = self::isUserSubscribedAsStudent($sessionId, $enreg_user);
2128
            if ($isUserSubscribed === false) {
2129
                $enreg_user = (int) $enreg_user;
2130
                $sql = "INSERT IGNORE INTO $tbl_session_rel_user (relation_type, session_id, user_id, registered_at)
2131
                        VALUES (0, $sessionId, $enreg_user, '".api_get_utc_datetime()."')";
2132
                Database::query($sql);
2133
                Event::addEvent(
2134
                    LOG_SESSION_ADD_USER,
2135
                    LOG_USER_ID,
2136
                    $enreg_user,
2137
                    api_get_utc_datetime(),
2138
                    api_get_user_id(),
2139
                    null,
2140
                    $sessionId
2141
                );
2142
            }
2143
        }
2144
2145
        // update number of users in the session
2146
        $sql = "UPDATE $tbl_session
2147
                SET nbr_users = (SELECT count(user_id) FROM $tbl_session_rel_user WHERE session_id = $sessionId)
2148
                WHERE id = $sessionId";
2149
        Database::query($sql);
2150
2151
        return true;
2152
    }
2153
2154
    /**
2155
     * Returns user list of the current users subscribed in the course-session.
2156
     *
2157
     * @param int   $sessionId
2158
     * @param array $courseInfo
2159
     * @param int   $status
2160
     *
2161
     * @return array
2162
     */
2163
    public static function getUsersByCourseSession(
2164
        $sessionId,
2165
        $courseInfo,
2166
        $status = null
2167
    ) {
2168
        $sessionId = (int) $sessionId;
2169
        $courseId = $courseInfo['real_id'];
2170
2171
        if (empty($sessionId) || empty($courseId)) {
2172
            return [];
2173
        }
2174
2175
        $statusCondition = null;
2176
        if (isset($status) && !is_null($status)) {
2177
            $status = (int) $status;
2178
            $statusCondition = " AND status = $status";
2179
        }
2180
2181
        $table = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
2182
2183
        $sql = "SELECT DISTINCT user_id
2184
                FROM $table
2185
                WHERE
2186
                    session_id = $sessionId AND
2187
                    c_id = $courseId
2188
                    $statusCondition
2189
                ";
2190
2191
        $result = Database::query($sql);
2192
        $existingUsers = [];
2193
        while ($row = Database::fetch_array($result)) {
2194
            $existingUsers[] = $row['user_id'];
2195
        }
2196
2197
        return $existingUsers;
2198
    }
2199
2200
    /**
2201
     * Returns user list of the current users subscribed in the course-session.
2202
     *
2203
     * @param array $sessionList
2204
     * @param array $courseList
2205
     * @param int   $status
2206
     * @param int   $start
2207
     * @param int   $limit
2208
     *
2209
     * @return array
2210
     */
2211
    public static function getUsersByCourseAndSessionList(
2212
        $sessionList,
2213
        $courseList,
2214
        $status = null,
2215
        $start = null,
2216
        $limit = null
2217
    ) {
2218
        if (empty($sessionList) || empty($courseList)) {
2219
            return [];
2220
        }
2221
        $sessionListToString = implode("','", $sessionList);
2222
        $courseListToString = implode("','", $courseList);
2223
2224
        $statusCondition = null;
2225
        if (isset($status) && !is_null($status)) {
2226
            $status = (int) $status;
2227
            $statusCondition = " AND status = $status";
2228
        }
2229
2230
        $table = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
2231
2232
        $sql = "SELECT DISTINCT user_id
2233
                FROM $table
2234
                WHERE
2235
                    session_id IN ('$sessionListToString') AND
2236
                    c_id IN ('$courseListToString')
2237
                    $statusCondition
2238
                ";
2239
        if (!is_null($start) && !is_null($limit)) {
2240
            $start = (int) $start;
2241
            $limit = (int) $limit;
2242
            $sql .= "LIMIT $start, $limit";
2243
        }
2244
        $result = Database::query($sql);
2245
        $existingUsers = [];
2246
        while ($row = Database::fetch_array($result)) {
2247
            $existingUsers[] = $row['user_id'];
2248
        }
2249
2250
        return $existingUsers;
2251
    }
2252
2253
    /**
2254
     * Remove a list of users from a course-session.
2255
     *
2256
     * @param array $userList
2257
     * @param int   $sessionId
2258
     * @param array $courseInfo
2259
     * @param int   $status
2260
     * @param bool  $updateTotal
2261
     *
2262
     * @return bool
2263
     */
2264
    public static function removeUsersFromCourseSession(
2265
        $userList,
2266
        $sessionId,
2267
        $courseInfo,
2268
        $status = null,
2269
        $updateTotal = true
2270
    ) {
2271
        $table = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
2272
        $tableSessionCourse = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
2273
        $sessionId = (int) $sessionId;
2274
2275
        if (empty($sessionId) || empty($userList) || empty($courseInfo)) {
2276
            return false;
2277
        }
2278
2279
        is_array($courseInfo) ? $courseId = $courseInfo['real_id'] : $courseId = $courseInfo;
2280
2281
        $statusCondition = null;
2282
        if (isset($status) && !is_null($status)) {
2283
            $status = (int) $status;
2284
            $statusCondition = " AND status = $status";
2285
        }
2286
2287
        foreach ($userList as $userId) {
2288
            $userId = (int) $userId;
2289
            $sql = "DELETE FROM $table
2290
                    WHERE
2291
                        session_id = $sessionId AND
2292
                        c_id = $courseId AND
2293
                        user_id = $userId
2294
                        $statusCondition
2295
                    ";
2296
            Database::query($sql);
2297
2298
            Event::addEvent(
2299
                LOG_SESSION_DELETE_USER_COURSE,
2300
                LOG_USER_ID,
2301
                $userId,
2302
                api_get_utc_datetime(),
2303
                api_get_user_id(),
2304
                $courseId,
2305
                $sessionId
2306
            );
2307
        }
2308
2309
        if ($updateTotal) {
2310
            // Count users in this session-course relation
2311
            $sql = "SELECT COUNT(user_id) as nbUsers
2312
                    FROM $table
2313
                    WHERE
2314
                        session_id = $sessionId AND
2315
                        c_id = $courseId AND
2316
                        status <> 2";
2317
            $result = Database::query($sql);
2318
            [$userCount] = Database::fetch_array($result);
2319
2320
            // update the session-course relation to add the users total
2321
            $sql = "UPDATE $tableSessionCourse
2322
                    SET nbr_users = $userCount
2323
                    WHERE
2324
                        session_id = $sessionId AND
2325
                        c_id = $courseId";
2326
            Database::query($sql);
2327
        }
2328
    }
2329
2330
    /**
2331
     * Subscribe a user to an specific course inside a session.
2332
     *
2333
     * @param array  $user_list
2334
     * @param int    $session_id
2335
     * @param string $course_code
2336
     * @param int    $session_visibility
2337
     * @param bool   $removeUsersNotInList
2338
     *
2339
     * @return bool
2340
     */
2341
    public static function subscribe_users_to_session_course(
2342
        $user_list,
2343
        $session_id,
2344
        $course_code,
2345
        $session_visibility = SESSION_VISIBLE_READ_ONLY,
2346
        $removeUsersNotInList = false
2347
    ) {
2348
        $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
2349
        $tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
2350
        $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
2351
        $tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
2352
2353
        if (empty($session_id) || empty($course_code)) {
2354
            return false;
2355
        }
2356
2357
        $session_id = (int) $session_id;
2358
        $session_visibility = (int) $session_visibility;
2359
        $course_code = Database::escape_string($course_code);
2360
        $courseInfo = api_get_course_info($course_code);
2361
        $courseId = $courseInfo['real_id'];
2362
        $subscribe = (int) api_get_course_setting('subscribe_users_to_forum_notifications', $courseInfo);
2363
        $forums = [];
2364
        if ($subscribe === 1) {
2365
            require_once api_get_path(SYS_CODE_PATH).'forum/forumfunction.inc.php';
2366
            $forums = get_forums(0, $course_code, true, $session_id);
2367
        }
2368
2369
        if ($removeUsersNotInList) {
2370
            $currentUsers = self::getUsersByCourseSession($session_id, $courseInfo, 0);
2371
2372
            if (!empty($user_list)) {
2373
                $userToDelete = array_diff($currentUsers, $user_list);
2374
            } else {
2375
                $userToDelete = $currentUsers;
2376
            }
2377
2378
            if (!empty($userToDelete)) {
2379
                self::removeUsersFromCourseSession(
2380
                    $userToDelete,
2381
                    $session_id,
2382
                    $courseInfo,
2383
                    0,
2384
                    true
2385
                );
2386
            }
2387
        }
2388
2389
        $nbr_users = 0;
2390
        foreach ($user_list as $enreg_user) {
2391
            $enreg_user = (int) $enreg_user;
2392
            // Checking if user exists in session - course - user table.
2393
            $sql = "SELECT count(user_id) as count
2394
                    FROM $tbl_session_rel_course_rel_user
2395
                    WHERE
2396
                        session_id = $session_id AND
2397
                        c_id = $courseId and
2398
                        user_id = $enreg_user ";
2399
            $result = Database::query($sql);
2400
            $count = 0;
2401
2402
            if (Database::num_rows($result) > 0) {
2403
                $row = Database::fetch_array($result, 'ASSOC');
2404
                $count = $row['count'];
2405
            }
2406
2407
            if ($count == 0) {
2408
                $sql = "INSERT IGNORE INTO $tbl_session_rel_course_rel_user (session_id, c_id, user_id, visibility)
2409
                        VALUES ($session_id, $courseId, $enreg_user, $session_visibility)";
2410
                $result = Database::query($sql);
2411
                if (Database::affected_rows($result)) {
2412
                    $nbr_users++;
2413
                }
2414
            }
2415
2416
            if (!empty($forums)) {
2417
                $userInfo = api_get_user_info($enreg_user);
2418
                foreach ($forums as $forum) {
2419
                    $forumId = $forum['iid'];
2420
                    set_notification('forum', $forumId, false, $userInfo, $courseInfo);
2421
                }
2422
            }
2423
2424
            // Checking if user exists in session - user table.
2425
            $sql = "SELECT count(user_id) as count
2426
                    FROM $tbl_session_rel_user
2427
                    WHERE session_id = $session_id AND user_id = $enreg_user ";
2428
            $result = Database::query($sql);
2429
            $count = 0;
2430
2431
            if (Database::num_rows($result) > 0) {
2432
                $row = Database::fetch_array($result, 'ASSOC');
2433
                $count = $row['count'];
2434
            }
2435
2436
            if (empty($count)) {
2437
                // If user is not registered to a session then add it.
2438
                $sql = "INSERT IGNORE INTO $tbl_session_rel_user (session_id, user_id, registered_at)
2439
                        VALUES ($session_id, $enreg_user, '".api_get_utc_datetime()."')";
2440
                Database::query($sql);
2441
2442
                $sql = "UPDATE $tbl_session SET nbr_users = nbr_users + 1
2443
                        WHERE id = $session_id ";
2444
                Database::query($sql);
2445
            }
2446
        }
2447
2448
        // count users in this session-course relation
2449
        $sql = "SELECT COUNT(user_id) as nbUsers
2450
                FROM $tbl_session_rel_course_rel_user
2451
                WHERE session_id = $session_id AND c_id = $courseId AND status <> 2";
2452
        $rs = Database::query($sql);
2453
        [$nbr_users] = Database::fetch_array($rs);
2454
        // update the session-course relation to add the users total
2455
        $sql = "UPDATE $tbl_session_rel_course
2456
                SET nbr_users = $nbr_users
2457
                WHERE session_id = $session_id AND c_id = $courseId";
2458
        Database::query($sql);
2459
    }
2460
2461
    /**
2462
     * Unsubscribe user from session.
2463
     *
2464
     * @param int Session id
2465
     * @param int User id
2466
     *
2467
     * @return bool True in case of success, false in case of error
2468
     */
2469
    public static function unsubscribe_user_from_session($session_id, $user_id)
2470
    {
2471
        $session_id = (int) $session_id;
2472
        $user_id = (int) $user_id;
2473
2474
        $tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
2475
        $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
2476
2477
        $sql = "DELETE FROM $tbl_session_rel_user
2478
                WHERE
2479
                    session_id = $session_id AND
2480
                    user_id = $user_id AND
2481
                    relation_type <> ".SESSION_RELATION_TYPE_RRHH;
2482
        $result = Database::query($sql);
2483
        $return = Database::affected_rows($result);
2484
2485
        // Update number of users
2486
        $sql = "UPDATE $tbl_session
2487
                SET nbr_users = nbr_users - $return
2488
                WHERE id = $session_id ";
2489
        Database::query($sql);
2490
2491
        Event::addEvent(
2492
            LOG_SESSION_DELETE_USER,
2493
            LOG_USER_ID,
2494
            $user_id,
2495
            api_get_utc_datetime(),
2496
            api_get_user_id(),
2497
            null,
2498
            $session_id
2499
        );
2500
2501
        // Get the list of courses related to this session
2502
        $course_list = self::get_course_list_by_session_id($session_id);
2503
        if (!empty($course_list)) {
2504
            foreach ($course_list as $course) {
2505
                self::unSubscribeUserFromCourseSession($user_id, $course['id'], $session_id);
2506
            }
2507
        }
2508
2509
        return true;
2510
    }
2511
2512
    /**
2513
     * @param int $user_id
2514
     * @param int $courseId
2515
     * @param int $session_id
2516
     */
2517
    public static function unSubscribeUserFromCourseSession($user_id, $courseId, $session_id)
2518
    {
2519
        $user_id = (int) $user_id;
2520
        $courseId = (int) $courseId;
2521
        $session_id = (int) $session_id;
2522
2523
        $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
2524
        $tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
2525
2526
        // Delete user from course
2527
        $sql = "DELETE FROM $tbl_session_rel_course_rel_user
2528
                WHERE session_id = $session_id AND c_id = $courseId AND user_id = $user_id";
2529
        $result = Database::query($sql);
2530
2531
        if (Database::affected_rows($result)) {
2532
            // Update number of users in this relation
2533
            $sql = "UPDATE $tbl_session_rel_course SET
2534
                    nbr_users = nbr_users - 1
2535
                    WHERE session_id = $session_id AND c_id = $courseId";
2536
            Database::query($sql);
2537
        }
2538
2539
        Event::addEvent(
2540
            LOG_SESSION_DELETE_USER_COURSE,
2541
            LOG_USER_ID,
2542
            $user_id,
2543
            api_get_utc_datetime(),
2544
            api_get_user_id(),
2545
            $courseId,
2546
            $session_id
2547
        );
2548
    }
2549
2550
    /**
2551
     * Subscribes courses to the given session and optionally (default)
2552
     * unsubscribe previous users.
2553
     *
2554
     * @author Carlos Vargas from existing code
2555
     *
2556
     * @param int   $sessionId
2557
     * @param array $courseList                     List of courses int ids
2558
     * @param bool  $removeExistingCoursesWithUsers Whether to unsubscribe
2559
     *                                              existing courses and users (true, default) or not (false)
2560
     * @param bool  $copyEvaluation                 from base course to session course
2561
     * @param bool  $copyCourseTeachersAsCoach
2562
     * @param bool  $importAssignments
2563
     *
2564
     * @throws Exception
2565
     *
2566
     * @return bool False on failure, true otherwise
2567
     * */
2568
    public static function add_courses_to_session(
2569
        $sessionId,
2570
        $courseList,
2571
        $removeExistingCoursesWithUsers = true,
2572
        $copyEvaluation = false,
2573
        $copyCourseTeachersAsCoach = false,
2574
        $importAssignments = false
2575
    ) {
2576
        $sessionId = (int) $sessionId;
2577
2578
        if (empty($sessionId) || empty($courseList)) {
2579
            return false;
2580
        }
2581
2582
        if ($importAssignments) {
2583
            require_once api_get_path(SYS_CODE_PATH).'work/work.lib.php';
2584
        }
2585
2586
        $session = api_get_session_entity($sessionId);
2587
2588
        if (!$session) {
2589
            return false;
2590
        }
2591
        $sessionVisibility = $session->getVisibility();
2592
2593
        $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
2594
        $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
2595
        $tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
2596
        $tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
2597
2598
        // Get list of courses subscribed to this session
2599
        $sql = "SELECT c_id
2600
                FROM $tbl_session_rel_course
2601
                WHERE session_id = $sessionId";
2602
        $rs = Database::query($sql);
2603
        $existingCourses = Database::store_result($rs);
2604
        $nbr_courses = count($existingCourses);
2605
2606
        // Get list of users subscribed to this session
2607
        $sql = "SELECT user_id
2608
                FROM $tbl_session_rel_user
2609
                WHERE
2610
                    session_id = $sessionId AND
2611
                    relation_type<>".SESSION_RELATION_TYPE_RRHH;
2612
        $result = Database::query($sql);
2613
        $user_list = Database::store_result($result);
2614
2615
        // Remove existing courses from the session.
2616
        if ($removeExistingCoursesWithUsers === true && !empty($existingCourses)) {
2617
            foreach ($existingCourses as $existingCourse) {
2618
                if (!in_array($existingCourse['c_id'], $courseList)) {
2619
                    $sql = "DELETE FROM $tbl_session_rel_course
2620
                            WHERE
2621
                                c_id = ".$existingCourse['c_id']." AND
2622
                                session_id = $sessionId";
2623
                    Database::query($sql);
2624
2625
                    $sql = "DELETE FROM $tbl_session_rel_course_rel_user
2626
                            WHERE
2627
                                c_id = ".$existingCourse['c_id']." AND
2628
                                session_id = $sessionId";
2629
                    Database::query($sql);
2630
2631
                    Event::addEvent(
2632
                        LOG_SESSION_DELETE_COURSE,
2633
                        LOG_COURSE_ID,
2634
                        $existingCourse['c_id'],
2635
                        api_get_utc_datetime(),
2636
                        api_get_user_id(),
2637
                        $existingCourse['c_id'],
2638
                        $sessionId
2639
                    );
2640
2641
                    CourseManager::remove_course_ranking(
2642
                        $existingCourse['c_id'],
2643
                        $sessionId
2644
                    );
2645
                    $nbr_courses--;
2646
                }
2647
            }
2648
        }
2649
2650
        // Pass through the courses list we want to add to the session
2651
        foreach ($courseList as $courseId) {
2652
            $courseInfo = api_get_course_info_by_id($courseId);
2653
2654
            // If course doesn't exists continue!
2655
            if (empty($courseInfo)) {
2656
                continue;
2657
            }
2658
2659
            $exists = false;
2660
            // check if the course we want to add is already subscribed
2661
            foreach ($existingCourses as $existingCourse) {
2662
                if ($courseId == $existingCourse['c_id']) {
2663
                    $exists = true;
2664
                }
2665
            }
2666
2667
            if (!$exists) {
2668
                // Copy gradebook categories and links (from base course)
2669
                // to the new course session
2670
                if ($copyEvaluation) {
2671
                    $cats = Category::load(null, null, $courseInfo['code']);
2672
                    if (!empty($cats)) {
2673
                        $sessionCategory = Category:: load(
2674
                            null,
2675
                            null,
2676
                            $courseInfo['code'],
2677
                            null,
2678
                            null,
2679
                            $sessionId,
2680
                            false
2681
                        );
2682
2683
                        // @todo remove commented code
2684
                        if (empty($sessionCategory)) {
2685
                            // There is no category for this course+session, so create one
2686
                            $cat = new Category();
2687
                            $sessionName = $session->getName();
2688
                            $cat->set_name($courseInfo['code'].' - '.get_lang('Session').' '.$sessionName);
2689
                            $cat->set_session_id($sessionId);
2690
                            $cat->set_course_code($courseInfo['code']);
2691
                            $cat->set_description(null);
2692
                            //$cat->set_user_id($stud_id);
2693
                            $cat->set_parent_id(0);
2694
                            $cat->set_weight(100);
2695
                            $cat->set_visible(0);
2696
                            $cat->set_certificate_min_score(75);
2697
                            $cat->add();
2698
                            $sessionGradeBookCategoryId = $cat->get_id();
2699
                        } else {
2700
                            if (!empty($sessionCategory[0])) {
2701
                                $sessionGradeBookCategoryId = $sessionCategory[0]->get_id();
2702
                            }
2703
                        }
2704
2705
                        $categoryIdList = [];
2706
                        /** @var Category $cat */
2707
                        foreach ($cats as $cat) {
2708
                            $categoryIdList[$cat->get_id()] = $cat->get_id();
2709
                        }
2710
2711
                        $newCategoryIdList = [];
2712
                        foreach ($cats as $cat) {
2713
                            $links = $cat->get_links(
2714
                                null,
2715
                                false,
2716
                                $courseInfo['code'],
2717
                                0
2718
                            );
2719
2720
                            //$cat->set_session_id($sessionId);
2721
                            //$oldCategoryId = $cat->get_id();
2722
                            //$newId = $cat->add();
2723
                            //$newCategoryIdList[$oldCategoryId] = $newId;
2724
                            //$parentId = $cat->get_parent_id();
2725
2726
                            /*if (!empty($parentId)) {
2727
                                $newParentId = $newCategoryIdList[$parentId];
2728
                                $cat->set_parent_id($newParentId);
2729
                                $cat->save();
2730
                            }*/
2731
2732
                            if (!empty($links)) {
2733
                                /** @var AbstractLink $link */
2734
                                foreach ($links as $link) {
2735
                                    //$newCategoryId = $newCategoryIdList[$link->get_category_id()];
2736
                                    $link->set_category_id($sessionGradeBookCategoryId);
2737
                                    $link->add();
2738
                                }
2739
                            }
2740
2741
                            $evaluationList = $cat->get_evaluations(
2742
                                null,
2743
                                false,
2744
                                $courseInfo['code'],
2745
                                0
2746
                            );
2747
2748
                            if (!empty($evaluationList)) {
2749
                                /** @var Evaluation $evaluation */
2750
                                foreach ($evaluationList as $evaluation) {
2751
                                    //$evaluationId = $newCategoryIdList[$evaluation->get_category_id()];
2752
                                    $evaluation->set_category_id($sessionGradeBookCategoryId);
2753
                                    $evaluation->add();
2754
                                }
2755
                            }
2756
                        }
2757
2758
                        // Create
2759
                        DocumentManager::generateDefaultCertificate(
2760
                            $courseInfo,
2761
                            true,
2762
                            $sessionId
2763
                        );
2764
                    }
2765
                }
2766
2767
                if ($importAssignments) {
2768
                    $workTable = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
2769
                    $sql = " SELECT * FROM $workTable
2770
                             WHERE active = 1 AND
2771
                                   c_id = $courseId AND
2772
                                   parent_id = 0 AND
2773
                                   (session_id IS NULL OR session_id = 0)";
2774
                    $result = Database::query($sql);
2775
                    $workList = Database::store_result($result, 'ASSOC');
2776
2777
                    foreach ($workList as $work) {
2778
                        $values = [
2779
                            'work_title' => $work['title'],
2780
                            'new_dir' => $work['url'].'_session_'.$sessionId,
2781
                            'description' => $work['description'],
2782
                            'qualification' => $work['qualification'],
2783
                            'allow_text_assignment' => $work['allow_text_assignment'],
2784
                        ];
2785
2786
                        addDir(
2787
                            $values,
2788
                            api_get_user_id(),
2789
                            $courseInfo,
2790
                            0,
2791
                            $sessionId
2792
                        );
2793
                    }
2794
                }
2795
2796
                // If the course isn't subscribed yet
2797
                $sql = "INSERT INTO $tbl_session_rel_course (session_id, c_id, nbr_users, position)
2798
                        VALUES ($sessionId, $courseId, 0, 0)";
2799
                Database::query($sql);
2800
2801
                Event::addEvent(
2802
                    LOG_SESSION_ADD_COURSE,
2803
                    LOG_COURSE_ID,
2804
                    $courseId,
2805
                    api_get_utc_datetime(),
2806
                    api_get_user_id(),
2807
                    $courseId,
2808
                    $sessionId
2809
                );
2810
2811
                // We add the current course in the existing courses array,
2812
                // to avoid adding another time the current course
2813
                $existingCourses[] = ['c_id' => $courseId];
2814
                $nbr_courses++;
2815
2816
                // Subscribe all the users from the session to this course inside the session
2817
                $nbr_users = 0;
2818
                foreach ($user_list as $enreg_user) {
2819
                    $enreg_user_id = (int) $enreg_user['user_id'];
2820
                    $sql = "INSERT IGNORE INTO $tbl_session_rel_course_rel_user (session_id, c_id, user_id, visibility)
2821
                            VALUES ($sessionId, $courseId, $enreg_user_id, $sessionVisibility)";
2822
                    $result = Database::query($sql);
2823
2824
                    Event::addEvent(
2825
                        LOG_SESSION_ADD_USER_COURSE,
2826
                        LOG_USER_ID,
2827
                        $enreg_user_id,
2828
                        api_get_utc_datetime(),
2829
                        api_get_user_id(),
2830
                        $courseId,
2831
                        $sessionId
2832
                    );
2833
2834
                    if (Database::affected_rows($result)) {
2835
                        $nbr_users++;
2836
                    }
2837
                }
2838
                $sql = "UPDATE $tbl_session_rel_course
2839
                        SET nbr_users = $nbr_users
2840
                        WHERE session_id = $sessionId AND c_id = $courseId";
2841
                Database::query($sql);
2842
            }
2843
2844
            if ($copyCourseTeachersAsCoach) {
2845
                $teachers = CourseManager::get_teacher_list_from_course_code($courseInfo['code']);
2846
                if (!empty($teachers)) {
2847
                    foreach ($teachers as $teacher) {
2848
                        self::updateCoaches(
2849
                            $sessionId,
2850
                            $courseId,
2851
                            [$teacher['user_id']],
2852
                            false
2853
                        );
2854
                    }
2855
                }
2856
            }
2857
        }
2858
2859
        $sql = "UPDATE $tbl_session SET nbr_courses = $nbr_courses WHERE id = $sessionId";
2860
        Database::query($sql);
2861
2862
        return true;
2863
    }
2864
2865
    /**
2866
     * Unsubscribe course from a session.
2867
     *
2868
     * @param int $session_id
2869
     * @param int $course_id
2870
     *
2871
     * @return bool True in case of success, false otherwise
2872
     */
2873
    public static function unsubscribe_course_from_session($session_id, $course_id)
2874
    {
2875
        $session_id = (int) $session_id;
2876
        $course_id = (int) $course_id;
2877
2878
        $tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
2879
        $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
2880
        $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
2881
2882
        // Get course code
2883
        $course_code = CourseManager::get_course_code_from_course_id($course_id);
2884
2885
        if (empty($course_code)) {
2886
            return false;
2887
        }
2888
2889
        // Unsubscribe course
2890
        $sql = "DELETE FROM $tbl_session_rel_course
2891
                WHERE c_id = $course_id AND session_id = $session_id";
2892
        $result = Database::query($sql);
2893
        $nb_affected = Database::affected_rows($result);
2894
2895
        $sql = "DELETE FROM $tbl_session_rel_course_rel_user
2896
                WHERE c_id = $course_id AND session_id = $session_id";
2897
        Database::query($sql);
2898
2899
        Event::addEvent(
2900
            LOG_SESSION_DELETE_COURSE,
2901
            LOG_COURSE_ID,
2902
            $course_id,
2903
            api_get_utc_datetime(),
2904
            api_get_user_id(),
2905
            $course_id,
2906
            $session_id
2907
        );
2908
2909
        if ($nb_affected > 0) {
2910
            // Update number of courses in the session
2911
            $sql = "UPDATE $tbl_session SET nbr_courses= nbr_courses - $nb_affected
2912
                    WHERE id = $session_id";
2913
            Database::query($sql);
2914
2915
            return true;
2916
        }
2917
2918
        return false;
2919
    }
2920
2921
    /**
2922
     * Creates a new extra field for a given session.
2923
     *
2924
     * @param string $variable    Field's internal variable name
2925
     * @param int    $fieldType   Field's type
2926
     * @param string $displayText Field's language var name
2927
     * @param string $default     Field's default value
2928
     *
2929
     * @return int new extra field id
2930
     */
2931
    public static function create_session_extra_field(
2932
        $variable,
2933
        $fieldType,
2934
        $displayText,
2935
        $default = ''
2936
    ) {
2937
        $extraField = new ExtraFieldModel('session');
2938
        $params = [
2939
            'variable' => $variable,
2940
            'field_type' => $fieldType,
2941
            'display_text' => $displayText,
2942
            'default_value' => $default,
2943
        ];
2944
2945
        return $extraField->save($params);
2946
    }
2947
2948
    /**
2949
     * Update an extra field value for a given session.
2950
     *
2951
     * @param int    $sessionId Session ID
2952
     * @param string $variable  Field variable name
2953
     * @param string $value     Optional. Default field value
2954
     *
2955
     * @return bool|int An integer when register a new extra field. And boolean when update the extrafield
2956
     */
2957
    public static function update_session_extra_field_value($sessionId, $variable, $value = '')
2958
    {
2959
        $extraFieldValue = new ExtraFieldValue('session');
2960
        $params = [
2961
            'item_id' => $sessionId,
2962
            'variable' => $variable,
2963
            'value' => $value,
2964
        ];
2965
2966
        return $extraFieldValue->save($params);
2967
    }
2968
2969
    /**
2970
     * Checks the relationship between a session and a course.
2971
     *
2972
     * @param int $session_id
2973
     * @param int $courseId
2974
     *
2975
     * @return bool returns TRUE if the session and the course are related, FALSE otherwise
2976
     * */
2977
    public static function relation_session_course_exist($session_id, $courseId)
2978
    {
2979
        $tbl_session_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
2980
        $return_value = false;
2981
        $sql = "SELECT c_id FROM $tbl_session_course
2982
                WHERE
2983
                  session_id = ".intval($session_id)." AND
2984
                  c_id = ".intval($courseId);
2985
        $result = Database::query($sql);
2986
        $num = Database::num_rows($result);
2987
        if ($num > 0) {
2988
            $return_value = true;
2989
        }
2990
2991
        return $return_value;
2992
    }
2993
2994
    /**
2995
     * Get the session information by name.
2996
     *
2997
     * @param string $name
2998
     *
2999
     * @return mixed false if the session does not exist, array if the session exist
3000
     */
3001
    public static function get_session_by_name($name)
3002
    {
3003
        $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
3004
        $name = Database::escape_string(trim($name));
3005
        if (empty($name)) {
3006
            return false;
3007
        }
3008
3009
        $sql = 'SELECT *
3010
		        FROM '.$tbl_session.'
3011
		        WHERE name = "'.$name.'"';
3012
        $result = Database::query($sql);
3013
        $num = Database::num_rows($result);
3014
        if ($num > 0) {
3015
            return Database::fetch_array($result);
3016
        } else {
3017
            return false;
3018
        }
3019
    }
3020
3021
    /**
3022
     * @param int $sessionId
3023
     * @param int $name
3024
     *
3025
     * @return bool
3026
     */
3027
    public static function sessionNameExistBesidesMySession($sessionId, $name)
3028
    {
3029
        $table = Database::get_main_table(TABLE_MAIN_SESSION);
3030
        $name = Database::escape_string(trim($name));
3031
        $sessionId = (int) $sessionId;
3032
3033
        if (empty($name)) {
3034
            return false;
3035
        }
3036
3037
        $sql = "SELECT *
3038
		        FROM $table
3039
		        WHERE name = '$name' AND id <> $sessionId ";
3040
        $result = Database::query($sql);
3041
        $num = Database::num_rows($result);
3042
        if ($num > 0) {
3043
            return true;
3044
        }
3045
3046
        return false;
3047
    }
3048
3049
    /**
3050
     * Create a session category.
3051
     *
3052
     * @author Jhon Hinojosa <[email protected]>, from existing code
3053
     *
3054
     * @param string        name
3055
     * @param int        year_start
3056
     * @param int        month_start
3057
     * @param int        day_start
3058
     * @param int        year_end
3059
     * @param int        month_end
3060
     * @param int        day_end
3061
     *
3062
     * @return int session ID
3063
     * */
3064
    public static function create_category_session(
3065
        $sname,
3066
        $syear_start,
3067
        $smonth_start,
3068
        $sday_start,
3069
        $syear_end,
3070
        $smonth_end,
3071
        $sday_end
3072
    ) {
3073
        $tbl_session_category = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
3074
        $name = trim($sname);
3075
        $year_start = intval($syear_start);
3076
        $month_start = intval($smonth_start);
3077
        $day_start = intval($sday_start);
3078
        $year_end = intval($syear_end);
3079
        $month_end = intval($smonth_end);
3080
        $day_end = intval($sday_end);
3081
3082
        $date_start = "$year_start-".(($month_start < 10) ? "0$month_start" : $month_start)."-".(($day_start < 10) ? "0$day_start" : $day_start);
3083
        $date_end = "$year_end-".(($month_end < 10) ? "0$month_end" : $month_end)."-".(($day_end < 10) ? "0$day_end" : $day_end);
3084
3085
        if (empty($name)) {
3086
            $msg = get_lang('SessionCategoryNameIsRequired');
3087
3088
            return $msg;
3089
        } elseif (!$month_start || !$day_start || !$year_start || !checkdate($month_start, $day_start, $year_start)) {
3090
            $msg = get_lang('InvalidStartDate');
3091
3092
            return $msg;
3093
        } elseif (!$month_end && !$day_end && !$year_end) {
3094
            $date_end = '';
3095
        } elseif (!$month_end || !$day_end || !$year_end || !checkdate($month_end, $day_end, $year_end)) {
3096
            $msg = get_lang('InvalidEndDate');
3097
3098
            return $msg;
3099
        } elseif ($date_start >= $date_end) {
3100
            $msg = get_lang('StartDateShouldBeBeforeEndDate');
3101
3102
            return $msg;
3103
        }
3104
3105
        $access_url_id = api_get_current_access_url_id();
3106
        $params = [
3107
            'name' => $name,
3108
            'date_start' => $date_start,
3109
            'access_url_id' => $access_url_id,
3110
        ];
3111
3112
        if (!empty($date_end)) {
3113
            $params['date_end'] = $date_end;
3114
        }
3115
3116
        $id = Database::insert($tbl_session_category, $params);
3117
3118
        // Add event to system log
3119
        $user_id = api_get_user_id();
3120
        Event::addEvent(
3121
            LOG_SESSION_CATEGORY_CREATE,
3122
            LOG_SESSION_CATEGORY_ID,
3123
            $id,
3124
            api_get_utc_datetime(),
3125
            $user_id
3126
        );
3127
3128
        return $id;
3129
    }
3130
3131
    /**
3132
     * Edit a sessions category.
3133
     *
3134
     * @author Jhon Hinojosa <[email protected]>,from existing code
3135
     *
3136
     * @param int        id
3137
     * @param string        name
3138
     * @param int        year_start
3139
     * @param int        month_start
3140
     * @param int        day_start
3141
     * @param int        year_end
3142
     * @param int        month_end
3143
     * @param int        day_end
3144
     *
3145
     * @return bool
3146
     *              The parameter id is a primary key
3147
     * */
3148
    public static function edit_category_session(
3149
        $id,
3150
        $sname,
3151
        $syear_start,
3152
        $smonth_start,
3153
        $sday_start,
3154
        $syear_end,
3155
        $smonth_end,
3156
        $sday_end
3157
    ) {
3158
        $tbl_session_category = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
3159
        $name = trim($sname);
3160
        $year_start = intval($syear_start);
3161
        $month_start = intval($smonth_start);
3162
        $day_start = intval($sday_start);
3163
        $year_end = intval($syear_end);
3164
        $month_end = intval($smonth_end);
3165
        $day_end = intval($sday_end);
3166
        $id = intval($id);
3167
        $date_start = "$year_start-".(($month_start < 10) ? "0$month_start" : $month_start)."-".(($day_start < 10) ? "0$day_start" : $day_start);
3168
        $date_end = "$year_end-".(($month_end < 10) ? "0$month_end" : $month_end)."-".(($day_end < 10) ? "0$day_end" : $day_end);
3169
3170
        if (empty($name)) {
3171
            $msg = get_lang('SessionCategoryNameIsRequired');
3172
3173
            return $msg;
3174
        } elseif (!$month_start || !$day_start || !$year_start || !checkdate($month_start, $day_start, $year_start)) {
3175
            $msg = get_lang('InvalidStartDate');
3176
3177
            return $msg;
3178
        } elseif (!$month_end && !$day_end && !$year_end) {
3179
            $date_end = null;
3180
        } elseif (!$month_end || !$day_end || !$year_end || !checkdate($month_end, $day_end, $year_end)) {
3181
            $msg = get_lang('InvalidEndDate');
3182
3183
            return $msg;
3184
        } elseif ($date_start >= $date_end) {
3185
            $msg = get_lang('StartDateShouldBeBeforeEndDate');
3186
3187
            return $msg;
3188
        }
3189
        if ($date_end != null) {
3190
            $sql = "UPDATE $tbl_session_category
3191
                    SET
3192
                        name = '".Database::escape_string($name)."',
3193
                        date_start = '$date_start' ,
3194
                        date_end = '$date_end'
3195
                    WHERE id= $id";
3196
        } else {
3197
            $sql = "UPDATE $tbl_session_category SET
3198
                        name = '".Database::escape_string($name)."',
3199
                        date_start = '$date_start',
3200
                        date_end = NULL
3201
                    WHERE id= $id";
3202
        }
3203
        $result = Database::query($sql);
3204
3205
        return $result ? true : false;
3206
    }
3207
3208
    /**
3209
     * Delete sessions categories.
3210
     *
3211
     * @param array|int $categoryId
3212
     * @param bool      $deleteSessions Optional. Include delete session.
3213
     * @param bool      $fromWs         Optional. True if the function is called by a webservice, false otherwise.
3214
     *
3215
     * @return bool Nothing, or false on error
3216
     *              The parameters is a array to delete sessions
3217
     *
3218
     * @author Jhon Hinojosa <[email protected]>, from existing code
3219
     */
3220
    public static function delete_session_category($categoryId, $deleteSessions = false, $fromWs = false)
3221
    {
3222
        $tblSessionCategory = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
3223
        $tblSession = Database::get_main_table(TABLE_MAIN_SESSION);
3224
3225
        if (is_array($categoryId)) {
3226
            $categoryId = array_map('intval', $categoryId);
3227
        } else {
3228
            $categoryId = [(int) $categoryId];
3229
        }
3230
3231
        $categoryId = implode(', ', $categoryId);
3232
3233
        if ($deleteSessions) {
3234
            $sql = "SELECT id FROM $tblSession WHERE session_category_id IN ($categoryId)";
3235
            $result = Database::query($sql);
3236
            while ($rows = Database::fetch_array($result)) {
3237
                $sessionId = $rows['id'];
3238
                self::delete($sessionId, $fromWs);
3239
            }
3240
        } else {
3241
            $sql = "UPDATE $tblSession SET session_category_id = NULL WHERE session_category_id IN ($categoryId)";
3242
            Database::query($sql);
3243
        }
3244
3245
        $sql = "DELETE FROM $tblSessionCategory WHERE id IN ($categoryId)";
3246
        Database::query($sql);
3247
3248
        // Add event to system log
3249
        Event::addEvent(
3250
            LOG_SESSION_CATEGORY_DELETE,
3251
            LOG_SESSION_CATEGORY_ID,
3252
            $categoryId,
3253
            api_get_utc_datetime(),
3254
            api_get_user_id()
3255
        );
3256
3257
        return true;
3258
    }
3259
3260
    /**
3261
     * Get a list of sessions of which the given conditions match with an = 'cond'.
3262
     *
3263
     * @param array $conditions          a list of condition example :
3264
     *                                   array('status' => STUDENT) or
3265
     *                                   array('s.name' => array('operator' => 'LIKE', value = '%$needle%'))
3266
     * @param array $order_by            a list of fields on which sort
3267
     * @param int   $urlId
3268
     * @param array $onlyThisSessionList
3269
     *
3270
     * @return array an array with all sessions of the platform
3271
     *
3272
     * @todo   optional course code parameter, optional sorting parameters...
3273
     */
3274
    public static function get_sessions_list(
3275
        $conditions = [],
3276
        $order_by = [],
3277
        $from = null,
3278
        $to = null,
3279
        $urlId = 0,
3280
        $onlyThisSessionList = []
3281
    ) {
3282
        $session_table = Database::get_main_table(TABLE_MAIN_SESSION);
3283
        $session_category_table = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
3284
        $user_table = Database::get_main_table(TABLE_MAIN_USER);
3285
        $table_access_url_rel_session = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
3286
        $session_course_table = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
3287
        $course_table = Database::get_main_table(TABLE_MAIN_COURSE);
3288
        $urlId = empty($urlId) ? api_get_current_access_url_id() : (int) $urlId;
3289
        $return_array = [];
3290
3291
        $sql_query = " SELECT
3292
                    DISTINCT(s.id),
3293
                    s.name,
3294
                    s.nbr_courses,
3295
                    s.access_start_date,
3296
                    s.access_end_date,
3297
                    u.firstname,
3298
                    u.lastname,
3299
                    sc.name as category_name,
3300
                    s.promotion_id
3301
				FROM $session_table s
3302
				INNER JOIN $user_table u ON s.id_coach = u.user_id
3303
				INNER JOIN $table_access_url_rel_session ar ON ar.session_id = s.id
3304
				LEFT JOIN  $session_category_table sc ON s.session_category_id = sc.id
3305
				LEFT JOIN $session_course_table sco ON (sco.session_id = s.id)
3306
				INNER JOIN $course_table c ON sco.c_id = c.id
3307
				WHERE ar.access_url_id = $urlId ";
3308
3309
        $availableFields = [
3310
            's.id',
3311
            's.name',
3312
            'c.id',
3313
        ];
3314
3315
        $availableOperator = [
3316
            'like',
3317
            '>=',
3318
            '<=',
3319
            '=',
3320
        ];
3321
3322
        if (count($conditions) > 0) {
3323
            foreach ($conditions as $field => $options) {
3324
                $operator = strtolower($options['operator']);
3325
                $value = Database::escape_string($options['value']);
3326
                if (in_array($field, $availableFields) && in_array($operator, $availableOperator)) {
3327
                    $sql_query .= ' AND '.$field." $operator '".$value."'";
3328
                }
3329
            }
3330
        }
3331
3332
        if (!empty($onlyThisSessionList)) {
3333
            $onlyThisSessionList = array_map('intval', $onlyThisSessionList);
3334
            $onlyThisSessionList = implode("','", $onlyThisSessionList);
3335
            $sql_query .= " AND s.id IN ('$onlyThisSessionList') ";
3336
        }
3337
3338
        $orderAvailableList = ['name'];
3339
        if (count($order_by) > 0) {
3340
            $order = null;
3341
            $direction = null;
3342
            if (isset($order_by[0]) && in_array($order_by[0], $orderAvailableList)) {
3343
                $order = $order_by[0];
3344
            }
3345
            if (isset($order_by[1]) && in_array(strtolower($order_by[1]), ['desc', 'asc'])) {
3346
                $direction = $order_by[1];
3347
            }
3348
3349
            if (!empty($order)) {
3350
                $sql_query .= " ORDER BY $order $direction ";
3351
            }
3352
        }
3353
3354
        if (!is_null($from) && !is_null($to)) {
3355
            $to = (int) $to;
3356
            $from = (int) $from;
3357
            $sql_query .= "LIMIT $from, $to";
3358
        }
3359
3360
        $sql_result = Database::query($sql_query);
3361
        if (Database::num_rows($sql_result) > 0) {
3362
            while ($result = Database::fetch_array($sql_result)) {
3363
                $return_array[$result['id']] = $result;
3364
            }
3365
        }
3366
3367
        return $return_array;
3368
    }
3369
3370
    /**
3371
     * Get the session category information by id.
3372
     *
3373
     * @param string session category ID
3374
     *
3375
     * @return mixed false if the session category does not exist, array if the session category exists
3376
     */
3377
    public static function get_session_category($id)
3378
    {
3379
        $table = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
3380
        $id = (int) $id;
3381
        $sql = "SELECT id, name, date_start, date_end
3382
                FROM $table
3383
                WHERE id= $id";
3384
        $result = Database::query($sql);
3385
        $num = Database::num_rows($result);
3386
        if ($num > 0) {
3387
            return Database::fetch_array($result);
3388
        } else {
3389
            return false;
3390
        }
3391
    }
3392
3393
    /**
3394
     * Get Hot Sessions (limit 8).
3395
     *
3396
     * @return array with sessions
3397
     */
3398
    public static function getHotSessions()
3399
    {
3400
        $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
3401
        $tbl_session_category = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
3402
        $tbl_users = Database::get_main_table(TABLE_MAIN_USER);
3403
        $tbl_extra_fields = Database::get_main_table(TABLE_EXTRA_FIELD_VALUES);
3404
        $tbl_session_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
3405
        $tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
3406
3407
        $extraField = new ExtraFieldModel('session');
3408
        $field = $extraField->get_handler_field_info_by_field_variable('image');
3409
3410
        $sql = "SELECT
3411
                s.id,
3412
                s.name,
3413
                s.id_coach,
3414
                u.firstname,
3415
                u.lastname,
3416
                s.session_category_id,
3417
                c.name as category_name,
3418
                s.description,
3419
                (SELECT COUNT(*) FROM $tbl_session_user WHERE session_id = s.id) as users,
3420
				(SELECT COUNT(*) FROM $tbl_lp WHERE session_id = s.id) as lessons ";
3421
        if ($field !== false) {
3422
            $fieldId = $field['id'];
3423
            $sql .= ",(SELECT value FROM $tbl_extra_fields WHERE field_id = $fieldId AND item_id = s.id) as image ";
3424
        }
3425
        $sql .= " FROM $tbl_session s
3426
                LEFT JOIN $tbl_session_category c
3427
                    ON s.session_category_id = c.id
3428
                INNER JOIN $tbl_users u
3429
                    ON s.id_coach = u.id
3430
                ORDER BY 9 DESC
3431
                LIMIT 8";
3432
        $result = Database::query($sql);
3433
3434
        if (Database::num_rows($result) > 0) {
3435
            $plugin = BuyCoursesPlugin::create();
3436
            $checker = $plugin->isEnabled();
3437
            $sessions = [];
3438
            while ($row = Database::fetch_array($result, 'ASSOC')) {
3439
                if (!isset($row['image'])) {
3440
                    $row['image'] = '';
3441
                }
3442
                $row['on_sale'] = '';
3443
                if ($checker) {
3444
                    $row['on_sale'] = $plugin->getItemByProduct(
3445
                        $row['id'],
3446
                        BuyCoursesPlugin::PRODUCT_TYPE_SESSION
3447
                    );
3448
                }
3449
                $sessions[] = $row;
3450
            }
3451
3452
            return $sessions;
3453
        }
3454
3455
        return false;
3456
    }
3457
3458
    /**
3459
     * Get all session categories (filter by access_url_id).
3460
     *
3461
     * @return mixed false if the session category does not exist, array if the session category exists
3462
     */
3463
    public static function get_all_session_category()
3464
    {
3465
        $table = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
3466
        $id = api_get_current_access_url_id();
3467
        $sql = 'SELECT * FROM '.$table.'
3468
                WHERE access_url_id = '.$id.'
3469
                ORDER BY name ASC';
3470
        $result = Database::query($sql);
3471
        if (Database::num_rows($result) > 0) {
3472
            $data = Database::store_result($result, 'ASSOC');
3473
3474
            return $data;
3475
        }
3476
3477
        return false;
3478
    }
3479
3480
    /**
3481
     * Assign a coach to course in session with status = 2.
3482
     *
3483
     * @param int  $userId
3484
     * @param int  $sessionId
3485
     * @param int  $courseId
3486
     * @param bool $noCoach   optional, if is true the user don't be a coach now,
3487
     *                        otherwise it'll assign a coach
3488
     *
3489
     * @return bool true if there are affected rows, otherwise false
3490
     */
3491
    public static function set_coach_to_course_session(
3492
        $userId,
3493
        $sessionId = 0,
3494
        $courseId = 0,
3495
        $noCoach = false
3496
    ) {
3497
        // Definition of variables
3498
        $userId = (int) $userId;
3499
3500
        $sessionId = !empty($sessionId) ? (int) $sessionId : api_get_session_id();
3501
        $courseId = !empty($courseId) ? (int) $courseId : api_get_course_id();
3502
3503
        if (empty($sessionId) || empty($courseId) || empty($userId)) {
3504
            return false;
3505
        }
3506
3507
        // Table definition
3508
        $tblSessionRelCourseRelUser = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
3509
        $tblSessionRelUser = Database::get_main_table(TABLE_MAIN_SESSION_USER);
3510
        $tblUser = Database::get_main_table(TABLE_MAIN_USER);
3511
3512
        // check if user is a teacher
3513
        $sql = "SELECT * FROM $tblUser
3514
                WHERE status = 1 AND user_id = $userId";
3515
3516
        $rsCheckUser = Database::query($sql);
3517
3518
        if (Database::num_rows($rsCheckUser) <= 0) {
3519
            return false;
3520
        }
3521
3522
        if ($noCoach) {
3523
            // check if user_id exists in session_rel_user (if the user is
3524
            // subscribed to the session in any manner)
3525
            $sql = "SELECT user_id FROM $tblSessionRelUser
3526
                    WHERE
3527
                        session_id = $sessionId AND
3528
                        user_id = $userId";
3529
            $res = Database::query($sql);
3530
3531
            if (Database::num_rows($res) > 0) {
3532
                // The user is already subscribed to the session. Change the
3533
                // record so the user is NOT a coach for this course anymore
3534
                // and then exit
3535
                $sql = "UPDATE $tblSessionRelCourseRelUser
3536
                        SET status = 0
3537
                        WHERE
3538
                            session_id = $sessionId AND
3539
                            c_id = $courseId AND
3540
                            user_id = $userId ";
3541
                $result = Database::query($sql);
3542
3543
                return Database::affected_rows($result) > 0;
3544
            }
3545
3546
            // The user is not subscribed to the session, so make sure
3547
            // he isn't subscribed to a course in this session either
3548
            // and then exit
3549
            $sql = "DELETE FROM $tblSessionRelCourseRelUser
3550
                    WHERE
3551
                        session_id = $sessionId AND
3552
                        c_id = $courseId AND
3553
                        user_id = $userId ";
3554
            $result = Database::query($sql);
3555
3556
            return Database::affected_rows($result) > 0;
3557
        }
3558
3559
        // Assign user as a coach to course
3560
        // First check if the user is registered to the course
3561
        $sql = "SELECT user_id FROM $tblSessionRelCourseRelUser
3562
                WHERE
3563
                    session_id = $sessionId AND
3564
                    c_id = $courseId AND
3565
                    user_id = $userId";
3566
        $rs_check = Database::query($sql);
3567
3568
        // Then update or insert.
3569
        if (Database::num_rows($rs_check) > 0) {
3570
            $sql = "UPDATE $tblSessionRelCourseRelUser SET status = 2
3571
                    WHERE
3572
                        session_id = $sessionId AND
3573
                        c_id = $courseId AND
3574
                        user_id = $userId ";
3575
            $result = Database::query($sql);
3576
3577
            return Database::affected_rows($result) > 0;
3578
        }
3579
3580
        $sql = "INSERT INTO $tblSessionRelCourseRelUser(session_id, c_id, user_id, status)
3581
                VALUES($sessionId, $courseId, $userId, 2)";
3582
        $result = Database::query($sql);
3583
3584
        return Database::affected_rows($result) > 0;
3585
    }
3586
3587
    /**
3588
     * @param int $sessionId
3589
     *
3590
     * @return bool
3591
     */
3592
    public static function removeAllDrhFromSession($sessionId)
3593
    {
3594
        $tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
3595
        $sessionId = (int) $sessionId;
3596
3597
        if (empty($sessionId)) {
3598
            return false;
3599
        }
3600
3601
        $sql = "DELETE FROM $tbl_session_rel_user
3602
                WHERE
3603
                    session_id = $sessionId AND
3604
                    relation_type =".SESSION_RELATION_TYPE_RRHH;
3605
        Database::query($sql);
3606
3607
        return true;
3608
    }
3609
3610
    /**
3611
     * Subscribes sessions to human resource manager (Dashboard feature).
3612
     *
3613
     * @param array $userInfo               Human Resource Manager info
3614
     * @param array $sessions_list          Sessions id
3615
     * @param bool  $sendEmail
3616
     * @param bool  $removeSessionsFromUser
3617
     *
3618
     * @return int
3619
     * */
3620
    public static function subscribeSessionsToDrh(
3621
        $userInfo,
3622
        $sessions_list,
3623
        $sendEmail = false,
3624
        $removeSessionsFromUser = true
3625
    ) {
3626
        // Database Table Definitions
3627
        $tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
3628
        $tbl_session_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
3629
3630
        if (empty($userInfo)) {
3631
            return 0;
3632
        }
3633
3634
        $userId = $userInfo['user_id'];
3635
3636
        // Only subscribe DRH users.
3637
        $rolesAllowed = [
3638
            DRH,
3639
            SESSIONADMIN,
3640
            PLATFORM_ADMIN,
3641
            COURSE_TUTOR,
3642
        ];
3643
        $isAdmin = api_is_platform_admin_by_id($userInfo['user_id']);
3644
        if (!$isAdmin && !in_array($userInfo['status'], $rolesAllowed)) {
3645
            return 0;
3646
        }
3647
3648
        $affected_rows = 0;
3649
        // Deleting assigned sessions to hrm_id.
3650
        if ($removeSessionsFromUser) {
3651
            if (api_is_multiple_url_enabled()) {
3652
                $sql = "SELECT s.session_id
3653
                        FROM $tbl_session_rel_user s
3654
                        INNER JOIN $tbl_session_rel_access_url a
3655
                        ON (a.session_id = s.session_id)
3656
                        WHERE
3657
                            s.user_id = $userId AND
3658
                            relation_type = ".SESSION_RELATION_TYPE_RRHH." AND
3659
                            access_url_id = ".api_get_current_access_url_id();
3660
            } else {
3661
                $sql = "SELECT s.session_id
3662
                        FROM $tbl_session_rel_user s
3663
                        WHERE user_id = $userId AND relation_type=".SESSION_RELATION_TYPE_RRHH;
3664
            }
3665
            $result = Database::query($sql);
3666
3667
            if (Database::num_rows($result) > 0) {
3668
                while ($row = Database::fetch_array($result)) {
3669
                    $sql = "DELETE FROM $tbl_session_rel_user
3670
                            WHERE
3671
                                session_id = {$row['session_id']} AND
3672
                                user_id = $userId AND
3673
                                relation_type =".SESSION_RELATION_TYPE_RRHH;
3674
                    Database::query($sql);
3675
3676
                    Event::addEvent(
3677
                        LOG_SESSION_DELETE_USER,
3678
                        LOG_USER_ID,
3679
                        $userId,
3680
                        api_get_utc_datetime(),
3681
                        api_get_user_id(),
3682
                        null,
3683
                        $row['session_id']
3684
                    );
3685
                }
3686
            }
3687
        }
3688
3689
        // Inserting new sessions list.
3690
        if (!empty($sessions_list) && is_array($sessions_list)) {
3691
            foreach ($sessions_list as $session_id) {
3692
                $session_id = (int) $session_id;
3693
                $sql = "SELECT session_id
3694
                        FROM $tbl_session_rel_user
3695
                        WHERE
3696
                            session_id = $session_id AND
3697
                            user_id = $userId AND
3698
                            relation_type = '".SESSION_RELATION_TYPE_RRHH."'";
3699
                $result = Database::query($sql);
3700
                if (Database::num_rows($result) == 0) {
3701
                    $sql = "INSERT IGNORE INTO $tbl_session_rel_user (session_id, user_id, relation_type, registered_at)
3702
                            VALUES (
3703
                                $session_id,
3704
                                $userId,
3705
                                '".SESSION_RELATION_TYPE_RRHH."',
3706
                                '".api_get_utc_datetime()."'
3707
                            )";
3708
                    Database::query($sql);
3709
3710
                    Event::addEvent(
3711
                        LOG_SESSION_ADD_USER,
3712
                        LOG_USER_ID,
3713
                        $userId,
3714
                        api_get_utc_datetime(),
3715
                        api_get_user_id(),
3716
                        null,
3717
                        $session_id
3718
                    );
3719
3720
                    $affected_rows++;
3721
                }
3722
            }
3723
        }
3724
3725
        return $affected_rows;
3726
    }
3727
3728
    /**
3729
     * @param int $sessionId
3730
     *
3731
     * @return array
3732
     */
3733
    public static function getDrhUsersInSession($sessionId)
3734
    {
3735
        return self::get_users_by_session($sessionId, SESSION_RELATION_TYPE_RRHH);
3736
    }
3737
3738
    /**
3739
     * @param int $userId
3740
     * @param int $sessionId
3741
     *
3742
     * @return array
3743
     */
3744
    public static function getSessionFollowedByDrh($userId, $sessionId)
3745
    {
3746
        $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
3747
        $tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
3748
        $tbl_session_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
3749
3750
        $userId = (int) $userId;
3751
        $sessionId = (int) $sessionId;
3752
3753
        $select = " SELECT * ";
3754
        if (api_is_multiple_url_enabled()) {
3755
            $sql = " $select FROM $tbl_session s
3756
                    INNER JOIN $tbl_session_rel_user sru ON (sru.session_id = s.id)
3757
                    LEFT JOIN $tbl_session_rel_access_url a ON (s.id = a.session_id)
3758
                    WHERE
3759
                        sru.user_id = '$userId' AND
3760
                        sru.session_id = '$sessionId' AND
3761
                        sru.relation_type = '".SESSION_RELATION_TYPE_RRHH."' AND
3762
                        access_url_id = ".api_get_current_access_url_id()."
3763
                    ";
3764
        } else {
3765
            $sql = "$select FROM $tbl_session s
3766
                     INNER JOIN $tbl_session_rel_user sru
3767
                     ON
3768
                        sru.session_id = s.id AND
3769
                        sru.user_id = '$userId' AND
3770
                        sru.session_id = '$sessionId' AND
3771
                        sru.relation_type = '".SESSION_RELATION_TYPE_RRHH."'
3772
                    ";
3773
        }
3774
3775
        $result = Database::query($sql);
3776
        if (Database::num_rows($result)) {
3777
            $row = Database::fetch_array($result, 'ASSOC');
3778
            $row['course_list'] = self::get_course_list_by_session_id($sessionId);
3779
3780
            return $row;
3781
        }
3782
3783
        return [];
3784
    }
3785
3786
    /**
3787
     * Get sessions followed by human resources manager.
3788
     *
3789
     * @param int    $userId
3790
     * @param int    $start
3791
     * @param int    $limit
3792
     * @param bool   $getCount
3793
     * @param bool   $getOnlySessionId
3794
     * @param bool   $getSql
3795
     * @param string $orderCondition
3796
     * @param string $keyword
3797
     * @param string $description
3798
     * @param array  $options
3799
     *
3800
     * @return array sessions
3801
     */
3802
    public static function get_sessions_followed_by_drh(
3803
        $userId,
3804
        $start = null,
3805
        $limit = null,
3806
        $getCount = false,
3807
        $getOnlySessionId = false,
3808
        $getSql = false,
3809
        $orderCondition = null,
3810
        $keyword = '',
3811
        $description = '',
3812
        $options = []
3813
    ) {
3814
        return self::getSessionsFollowedByUser(
3815
            $userId,
3816
            DRH,
3817
            $start,
3818
            $limit,
3819
            $getCount,
3820
            $getOnlySessionId,
3821
            $getSql,
3822
            $orderCondition,
3823
            $keyword,
3824
            $description,
3825
            $options
3826
        );
3827
    }
3828
3829
    /**
3830
     * Get sessions followed by human resources manager.
3831
     *
3832
     * @param int    $userId
3833
     * @param int    $status           DRH Optional
3834
     * @param int    $start
3835
     * @param int    $limit
3836
     * @param bool   $getCount
3837
     * @param bool   $getOnlySessionId
3838
     * @param bool   $getSql
3839
     * @param string $orderCondition
3840
     * @param string $keyword
3841
     * @param string $description
3842
     * @param array  $options
3843
     *
3844
     * @return array sessions
3845
     */
3846
    public static function getSessionsFollowedByUser(
3847
        $userId,
3848
        $status = null,
3849
        $start = null,
3850
        $limit = null,
3851
        $getCount = false,
3852
        $getOnlySessionId = false,
3853
        $getSql = false,
3854
        $orderCondition = null,
3855
        $keyword = '',
3856
        $description = '',
3857
        $options = []
3858
    ) {
3859
        // Database Table Definitions
3860
        $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
3861
        $tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
3862
        $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
3863
        $tbl_session_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
3864
3865
        $extraFieldModel = new ExtraFieldModel('session');
3866
        $conditions = $extraFieldModel->parseConditions($options);
3867
        $sqlInjectJoins = $conditions['inject_joins'];
3868
        $extraFieldsConditions = $conditions['where'];
3869
        $sqlInjectWhere = $conditions['inject_where'];
3870
        $injectExtraFields = $conditions['inject_extra_fields'];
3871
3872
        if (!empty($injectExtraFields)) {
3873
            $injectExtraFields = ' , '.$injectExtraFields.' s.id';
3874
        }
3875
3876
        $userId = (int) $userId;
3877
3878
        $select = ' SELECT DISTINCT * '.$injectExtraFields;
3879
        if ($getCount) {
3880
            $select = ' SELECT count(DISTINCT(s.id)) as count ';
3881
        }
3882
3883
        if ($getOnlySessionId) {
3884
            $select = ' SELECT DISTINCT(s.id) ';
3885
        }
3886
3887
        $limitCondition = null;
3888
        if (!is_null($start) && !is_null($limit)) {
3889
            $limitCondition = " LIMIT ".intval($start).", ".intval($limit);
3890
        }
3891
3892
        if (empty($orderCondition)) {
3893
            $orderCondition = ' ORDER BY s.name ';
3894
        }
3895
3896
        $whereConditions = null;
3897
        $sessionCourseConditions = null;
3898
        $sessionConditions = null;
3899
        $sessionQuery = '';
3900
        $courseSessionQuery = null;
3901
        switch ($status) {
3902
            case DRH:
3903
                $sessionQuery = "SELECT sru.session_id
3904
                                 FROM
3905
                                 $tbl_session_rel_user sru
3906
                                 WHERE
3907
                                    sru.relation_type = '".SESSION_RELATION_TYPE_RRHH."' AND
3908
                                    sru.user_id = $userId";
3909
                break;
3910
            case COURSEMANAGER:
3911
                $courseSessionQuery = "
3912
                    SELECT scu.session_id as id
3913
                    FROM $tbl_session_rel_course_rel_user scu
3914
                    WHERE (scu.status = 2 AND scu.user_id = $userId)";
3915
3916
                $whereConditions = " OR (s.id_coach = $userId) ";
3917
                break;
3918
            case SESSIONADMIN:
3919
                $sessionQuery = '';
3920
                $sqlInjectJoins .= " AND s.session_admin_id = $userId ";
3921
                break;
3922
            default:
3923
                $sessionQuery = "SELECT sru.session_id
3924
                                 FROM
3925
                                 $tbl_session_rel_user sru
3926
                                 WHERE
3927
                                    sru.user_id = $userId";
3928
                break;
3929
        }
3930
3931
        $keywordCondition = '';
3932
        if (!empty($keyword)) {
3933
            $keyword = Database::escape_string($keyword);
3934
            $keywordCondition = " AND (s.name LIKE '%$keyword%' ) ";
3935
3936
            if (!empty($description)) {
3937
                $description = Database::escape_string($description);
3938
                $keywordCondition = " AND (s.name LIKE '%$keyword%' OR s.description LIKE '%$description%' ) ";
3939
            }
3940
        }
3941
3942
        $whereConditions .= $keywordCondition;
3943
        $subQuery = $sessionQuery.$courseSessionQuery;
3944
3945
        if (!empty($subQuery)) {
3946
            $subQuery = " AND s.id IN ($subQuery)";
3947
        }
3948
3949
        $sql = " $select
3950
                FROM $tbl_session s
3951
                INNER JOIN $tbl_session_rel_access_url a
3952
                ON (s.id = a.session_id)
3953
                $sqlInjectJoins
3954
                WHERE
3955
                    access_url_id = ".api_get_current_access_url_id()."
3956
                    $subQuery
3957
                    $whereConditions
3958
                    $extraFieldsConditions
3959
                    $sqlInjectWhere
3960
                    $orderCondition
3961
                    $limitCondition";
3962
3963
        if ($getSql) {
3964
            return $sql;
3965
        }
3966
        $result = Database::query($sql);
3967
3968
        if ($getCount) {
3969
            $row = Database::fetch_array($result);
3970
            if ($row) {
3971
                return (int) $row['count'];
3972
            }
3973
3974
            return 0;
3975
        }
3976
3977
        $sessions = [];
3978
        if (Database::num_rows($result) > 0) {
3979
            $sysUploadPath = api_get_path(SYS_UPLOAD_PATH).'sessions/';
3980
            $webUploadPath = api_get_path(WEB_UPLOAD_PATH).'sessions/';
3981
            $imgPath = Display::return_icon(
3982
                'session_default_small.png',
3983
                null,
3984
                [],
3985
                ICON_SIZE_SMALL,
3986
                false,
3987
                true
3988
            );
3989
3990
            while ($row = Database::fetch_array($result)) {
3991
                if ($getOnlySessionId) {
3992
                    $sessions[$row['id']] = $row;
3993
                    continue;
3994
                }
3995
                $imageFilename = ExtraFieldModel::FIELD_TYPE_FILE_IMAGE.'_'.$row['id'].'.png';
3996
                $row['image'] = is_file($sysUploadPath.$imageFilename) ? $webUploadPath.$imageFilename : $imgPath;
3997
3998
                if ($row['display_start_date'] === '0000-00-00 00:00:00' || $row['display_start_date'] === '0000-00-00') {
3999
                    $row['display_start_date'] = null;
4000
                }
4001
4002
                if ($row['display_end_date'] === '0000-00-00 00:00:00' || $row['display_end_date'] === '0000-00-00') {
4003
                    $row['display_end_date'] = null;
4004
                }
4005
4006
                if ($row['access_start_date'] === '0000-00-00 00:00:00' || $row['access_start_date'] === '0000-00-00') {
4007
                    $row['access_start_date'] = null;
4008
                }
4009
4010
                if ($row['access_end_date'] === '0000-00-00 00:00:00' || $row['access_end_date'] === '0000-00-00') {
4011
                    $row['access_end_date'] = null;
4012
                }
4013
4014
                if ($row['coach_access_start_date'] === '0000-00-00 00:00:00' ||
4015
                    $row['coach_access_start_date'] === '0000-00-00'
4016
                ) {
4017
                    $row['coach_access_start_date'] = null;
4018
                }
4019
4020
                if ($row['coach_access_end_date'] === '0000-00-00 00:00:00' ||
4021
                    $row['coach_access_end_date'] === '0000-00-00'
4022
                ) {
4023
                    $row['coach_access_end_date'] = null;
4024
                }
4025
4026
                $sessions[$row['id']] = $row;
4027
            }
4028
        }
4029
4030
        return $sessions;
4031
    }
4032
4033
    /**
4034
     * Gets the list (or the count) of courses by session filtered by access_url.
4035
     *
4036
     * @param int    $session_id  The session id
4037
     * @param string $course_name The course code
4038
     * @param string $orderBy     Field to order the data
4039
     * @param bool   $getCount    Optional. Count the session courses
4040
     *
4041
     * @return array|int List of courses. Whether $getCount is true, return the count
4042
     */
4043
    public static function get_course_list_by_session_id(
4044
        $session_id,
4045
        $course_name = '',
4046
        $orderBy = null,
4047
        $getCount = false
4048
    ) {
4049
        $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
4050
        $tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
4051
        $session_id = (int) $session_id;
4052
        $sqlSelect = '*, c.id, c.id as real_id, c.code as course_code';
4053
4054
        if ($getCount) {
4055
            $sqlSelect = 'COUNT(1) as count';
4056
        }
4057
4058
        // select the courses
4059
        $sql = "SELECT $sqlSelect
4060
                FROM $tbl_course c
4061
                INNER JOIN $tbl_session_rel_course src
4062
                ON (c.id = src.c_id)
4063
		        WHERE src.session_id = '$session_id' ";
4064
4065
        if (!empty($course_name)) {
4066
            $course_name = Database::escape_string($course_name);
4067
            $sql .= " AND c.title LIKE '%$course_name%' ";
4068
        }
4069
4070
        if (!empty($orderBy)) {
4071
            $orderBy = Database::escape_string($orderBy);
4072
            $orderBy = " ORDER BY $orderBy";
4073
        } else {
4074
            if (self::orderCourseIsEnabled()) {
4075
                $orderBy .= ' ORDER BY position ';
4076
            } else {
4077
                $orderBy .= ' ORDER BY title ';
4078
            }
4079
        }
4080
4081
        $sql .= Database::escape_string($orderBy);
4082
        $result = Database::query($sql);
4083
        $num_rows = Database::num_rows($result);
4084
        $courses = [];
4085
        if ($num_rows > 0) {
4086
            if ($getCount) {
4087
                $count = Database::fetch_assoc($result);
4088
4089
                return (int) $count['count'];
4090
            }
4091
4092
            while ($row = Database::fetch_array($result, 'ASSOC')) {
4093
                $courses[$row['real_id']] = $row;
4094
            }
4095
        }
4096
4097
        return $courses;
4098
    }
4099
4100
    /**
4101
     * Gets the list of courses by session filtered by access_url.
4102
     *
4103
     * @param $userId
4104
     * @param $sessionId
4105
     * @param null   $from
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $from is correct as it would always require null to be passed?
Loading history...
4106
     * @param null   $limit
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $limit is correct as it would always require null to be passed?
Loading history...
4107
     * @param null   $column
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $column is correct as it would always require null to be passed?
Loading history...
4108
     * @param null   $direction
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $direction is correct as it would always require null to be passed?
Loading history...
4109
     * @param bool   $getCount
4110
     * @param string $keyword
4111
     *
4112
     * @return array
4113
     */
4114
    public static function getAllCoursesFollowedByUser(
4115
        $userId,
4116
        $sessionId,
4117
        $from = null,
4118
        $limit = null,
4119
        $column = null,
4120
        $direction = null,
4121
        $getCount = false,
4122
        $keyword = ''
4123
    ) {
4124
        if (empty($sessionId)) {
4125
            $sessionsSQL = self::get_sessions_followed_by_drh(
4126
                $userId,
4127
                null,
4128
                null,
4129
                null,
4130
                true,
4131
                true
4132
            );
4133
        } else {
4134
            $sessionsSQL = intval($sessionId);
4135
        }
4136
4137
        $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
4138
        $tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
4139
4140
        if ($getCount) {
4141
            $select = "SELECT COUNT(DISTINCT(c.code)) as count ";
4142
        } else {
4143
            $select = "SELECT DISTINCT c.* ";
4144
        }
4145
4146
        $keywordCondition = null;
4147
        if (!empty($keyword)) {
4148
            $keyword = Database::escape_string($keyword);
4149
            $keywordCondition = " AND (c.code LIKE '%$keyword%' OR c.title LIKE '%$keyword%' ) ";
4150
        }
4151
4152
        // Select the courses
4153
        $sql = "$select
4154
                FROM $tbl_course c
4155
                INNER JOIN $tbl_session_rel_course src
4156
                ON c.id = src.c_id
4157
		        WHERE
4158
		            src.session_id IN ($sessionsSQL)
4159
		            $keywordCondition
4160
		        ";
4161
        if ($getCount) {
4162
            $result = Database::query($sql);
4163
            $row = Database::fetch_array($result, 'ASSOC');
4164
4165
            return $row['count'];
4166
        }
4167
4168
        if (isset($from) && isset($limit)) {
4169
            $from = intval($from);
4170
            $limit = intval($limit);
4171
            $sql .= " LIMIT $from, $limit";
4172
        }
4173
4174
        $result = Database::query($sql);
4175
        $num_rows = Database::num_rows($result);
4176
        $courses = [];
4177
4178
        if ($num_rows > 0) {
4179
            while ($row = Database::fetch_array($result, 'ASSOC')) {
4180
                $courses[$row['id']] = $row;
4181
            }
4182
        }
4183
4184
        return $courses;
4185
    }
4186
4187
    /**
4188
     * Gets the list of courses by session filtered by access_url.
4189
     *
4190
     * @param int    $session_id
4191
     * @param string $course_name
4192
     *
4193
     * @return array list of courses
4194
     */
4195
    public static function get_course_list_by_session_id_like($session_id, $course_name = '')
4196
    {
4197
        $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
4198
        $tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
4199
4200
        $session_id = (int) $session_id;
4201
        $course_name = Database::escape_string($course_name);
4202
4203
        // select the courses
4204
        $sql = "SELECT c.id, c.title FROM $tbl_course c
4205
                INNER JOIN $tbl_session_rel_course src
4206
                ON c.id = src.c_id
4207
		        WHERE ";
4208
4209
        if (!empty($session_id)) {
4210
            $sql .= "src.session_id LIKE '$session_id' AND ";
4211
        }
4212
4213
        if (!empty($course_name)) {
4214
            $sql .= "UPPER(c.title) LIKE UPPER('%$course_name%') ";
4215
        }
4216
4217
        $sql .= "ORDER BY title;";
4218
        $result = Database::query($sql);
4219
        $num_rows = Database::num_rows($result);
4220
        $courses = [];
4221
        if ($num_rows > 0) {
4222
            while ($row = Database::fetch_array($result, 'ASSOC')) {
4223
                $courses[$row['id']] = $row;
4224
            }
4225
        }
4226
4227
        return $courses;
4228
    }
4229
4230
    /**
4231
     * Gets the count of courses by session filtered by access_url.
4232
     *
4233
     * @param int session id
4234
     * @param string $keyword
4235
     *
4236
     * @return array list of courses
4237
     */
4238
    public static function getCourseCountBySessionId($session_id, $keyword = '')
4239
    {
4240
        $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
4241
        $tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
4242
        $session_id = (int) $session_id;
4243
4244
        // select the courses
4245
        $sql = "SELECT COUNT(c.code) count
4246
                FROM $tbl_course c
4247
                INNER JOIN $tbl_session_rel_course src
4248
                ON c.id = src.c_id
4249
		        WHERE src.session_id = '$session_id' ";
4250
4251
        $keywordCondition = null;
4252
        if (!empty($keyword)) {
4253
            $keyword = Database::escape_string($keyword);
4254
            $keywordCondition = " AND (c.code LIKE '%$keyword%' OR c.title LIKE '%$keyword%' ) ";
4255
        }
4256
        $sql .= $keywordCondition;
4257
4258
        $result = Database::query($sql);
4259
        $num_rows = Database::num_rows($result);
4260
        if ($num_rows > 0) {
4261
            $row = Database::fetch_array($result, 'ASSOC');
4262
4263
            return $row['count'];
4264
        }
4265
4266
        return null;
4267
    }
4268
4269
    /**
4270
     * Get the session id based on the original id and field name in the extra fields.
4271
     * Returns 0 if session was not found.
4272
     *
4273
     * @param string $value    Original session id
4274
     * @param string $variable Original field name
4275
     *
4276
     * @return int Session id
4277
     */
4278
    public static function getSessionIdFromOriginalId($value, $variable)
4279
    {
4280
        $extraFieldValue = new ExtraFieldValue('session');
4281
        $result = $extraFieldValue->get_item_id_from_field_variable_and_field_value(
4282
            $variable,
4283
            $value
4284
        );
4285
4286
        if (!empty($result)) {
4287
            return $result['item_id'];
4288
        }
4289
4290
        return 0;
4291
    }
4292
4293
    /**
4294
     * Get users by session.
4295
     *
4296
     * @param int  $id       session id
4297
     * @param int  $status   filter by status coach = 2
4298
     * @param bool $getCount Optional. Allow get the number of rows from the result
4299
     * @param int  $urlId
4300
     *
4301
     * @return array|int A list with an user list. If $getCount is true then return a the count of registers
4302
     */
4303
    public static function get_users_by_session(
4304
        $id,
4305
        $status = null,
4306
        $getCount = false,
4307
        $urlId = 0
4308
    ) {
4309
        if (empty($id)) {
4310
            return [];
4311
        }
4312
        $id = (int) $id;
4313
        $urlId = empty($urlId) ? api_get_current_access_url_id() : (int) $urlId;
4314
4315
        $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
4316
        $tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
4317
        $table_access_url_user = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
4318
4319
        $selectedField = '
4320
            u.user_id, u.lastname, u.firstname, u.username, su.relation_type, au.access_url_id,
4321
            su.moved_to, su.moved_status, su.moved_at, su.registered_at
4322
        ';
4323
4324
        if ($getCount) {
4325
            $selectedField = 'count(1) AS count';
4326
        }
4327
4328
        $sql = "SELECT $selectedField
4329
                FROM $tbl_user u
4330
                INNER JOIN $tbl_session_rel_user su
4331
                ON u.user_id = su.user_id AND
4332
                su.session_id = $id
4333
                LEFT OUTER JOIN $table_access_url_user au
4334
                ON (au.user_id = u.user_id)
4335
                ";
4336
4337
        if (is_numeric($status)) {
4338
            $status = (int) $status;
4339
            $sql .= " WHERE su.relation_type = $status AND (au.access_url_id = $urlId OR au.access_url_id is null)";
4340
        } else {
4341
            $sql .= " WHERE (au.access_url_id = $urlId OR au.access_url_id is null )";
4342
        }
4343
4344
        $sql .= ' ORDER BY su.relation_type, ';
4345
        $sql .= api_sort_by_first_name() ? ' u.firstname, u.lastname' : '  u.lastname, u.firstname';
4346
4347
        $result = Database::query($sql);
4348
        if ($getCount) {
4349
            $count = Database::fetch_assoc($result);
4350
            if ($count) {
4351
                return (int) $count['count'];
4352
            }
4353
4354
            return 0;
4355
        }
4356
4357
        $return = [];
4358
        while ($row = Database::fetch_array($result, 'ASSOC')) {
4359
            $return[] = $row;
4360
        }
4361
4362
        return $return;
4363
    }
4364
4365
    /**
4366
     * The general coach (field: session.id_coach).
4367
     *
4368
     * @param int  $user_id         user id
4369
     * @param bool $asPlatformAdmin The user is platform admin, return everything
4370
     *
4371
     * @return array
4372
     */
4373
    public static function get_sessions_by_general_coach($user_id, $asPlatformAdmin = false)
4374
    {
4375
        $session_table = Database::get_main_table(TABLE_MAIN_SESSION);
4376
        $user_id = (int) $user_id;
4377
4378
        // Session where we are general coach
4379
        $sql = "SELECT DISTINCT *
4380
                FROM $session_table";
4381
4382
        if (!$asPlatformAdmin) {
4383
            $sql .= " WHERE id_coach = $user_id";
4384
        }
4385
4386
        if (api_is_multiple_url_enabled()) {
4387
            $tbl_session_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
4388
            $access_url_id = api_get_current_access_url_id();
4389
4390
            $sqlCoach = '';
4391
            if (!$asPlatformAdmin) {
4392
                $sqlCoach = " id_coach = $user_id AND ";
4393
            }
4394
4395
            if ($access_url_id != -1) {
4396
                $sql = 'SELECT DISTINCT session.*
4397
                    FROM '.$session_table.' session INNER JOIN '.$tbl_session_rel_access_url.' session_rel_url
4398
                    ON (session.id = session_rel_url.session_id)
4399
                    WHERE '.$sqlCoach.' access_url_id = '.$access_url_id;
4400
            }
4401
        }
4402
        $sql .= ' ORDER by name';
4403
        $result = Database::query($sql);
4404
4405
        return Database::store_result($result, 'ASSOC');
4406
    }
4407
4408
    /**
4409
     * @param int $user_id
4410
     *
4411
     * @return array
4412
     *
4413
     * @deprecated use get_sessions_by_general_coach()
4414
     */
4415
    public static function get_sessions_by_coach($user_id)
4416
    {
4417
        $session_table = Database::get_main_table(TABLE_MAIN_SESSION);
4418
4419
        return Database::select(
4420
            '*',
4421
            $session_table,
4422
            ['where' => ['id_coach = ?' => $user_id]]
4423
        );
4424
    }
4425
4426
    /**
4427
     * @param int $user_id
4428
     * @param int $courseId
4429
     * @param int $session_id
4430
     *
4431
     * @return array|bool
4432
     */
4433
    public static function get_user_status_in_course_session($user_id, $courseId, $session_id)
4434
    {
4435
        $table = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
4436
        $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
4437
        $sql = "SELECT session_rcru.status
4438
                FROM $table session_rcru
4439
                INNER JOIN $tbl_user user
4440
                ON (session_rcru.user_id = user.user_id)
4441
                WHERE
4442
                    session_rcru.session_id = '".intval($session_id)."' AND
4443
                    session_rcru.c_id ='".intval($courseId)."' AND
4444
                    user.user_id = ".intval($user_id);
4445
4446
        $result = Database::query($sql);
4447
        $status = false;
4448
        if (Database::num_rows($result)) {
4449
            $status = Database::fetch_row($result);
4450
            $status = $status['0'];
4451
        }
4452
4453
        return $status;
4454
    }
4455
4456
    /**
4457
     * Gets user status within a session.
4458
     *
4459
     * @param int $userId
4460
     * @param int $sessionId
4461
     *
4462
     * @return SessionRelUser
4463
     */
4464
    public static function getUserStatusInSession($userId, $sessionId)
4465
    {
4466
        $em = Database::getManager();
4467
        $subscriptions = $em
4468
            ->getRepository('ChamiloCoreBundle:SessionRelUser')
4469
            ->findBy(['session' => $sessionId, 'user' => $userId]);
4470
4471
        /** @var SessionRelUser $subscription */
4472
        $subscription = current($subscriptions);
4473
4474
        return $subscription;
4475
    }
4476
4477
    /**
4478
     * @param int $id
4479
     *
4480
     * @return array
4481
     */
4482
    public static function get_all_sessions_by_promotion($id)
4483
    {
4484
        $table = Database::get_main_table(TABLE_MAIN_SESSION);
4485
4486
        return Database::select(
4487
            '*',
4488
            $table,
4489
            ['where' => ['promotion_id = ?' => $id]]
4490
        );
4491
    }
4492
4493
    /**
4494
     * @param int   $promotion_id
4495
     * @param array $list
4496
     */
4497
    public static function subscribe_sessions_to_promotion($promotion_id, $list)
4498
    {
4499
        $table = Database::get_main_table(TABLE_MAIN_SESSION);
4500
        $params = [];
4501
        $params['promotion_id'] = 0;
4502
        Database::update(
4503
            $table,
4504
            $params,
4505
            ['promotion_id = ?' => $promotion_id]
4506
        );
4507
4508
        $params['promotion_id'] = $promotion_id;
4509
        if (!empty($list)) {
4510
            foreach ($list as $session_id) {
4511
                $session_id = (int) $session_id;
4512
                Database::update($table, $params, ['id = ?' => $session_id]);
4513
            }
4514
        }
4515
    }
4516
4517
    /**
4518
     * Updates a session status.
4519
     *
4520
     * @param int session id
4521
     * @param int status
4522
     */
4523
    public static function set_session_status($session_id, $status)
4524
    {
4525
        $t = Database::get_main_table(TABLE_MAIN_SESSION);
4526
        $params['visibility'] = $status;
4527
        Database::update($t, $params, ['id = ?' => $session_id]);
4528
    }
4529
4530
    /**
4531
     * Copies a session with the same data to a new session.
4532
     * The new copy is not assigned to the same promotion.
4533
     *
4534
     * @param int  $id                         Session ID
4535
     * @param bool $copy_courses               Whether to copy the relationship with courses
4536
     * @param bool $copyTeachersAndDrh
4537
     * @param bool $create_new_courses         New courses will be created
4538
     * @param bool $set_exercises_lp_invisible Set exercises and LPs in the new session to invisible by default
4539
     * @param bool $copyWithSessionContent     Copy course session content into the courses
4540
     *
4541
     * @return int The new session ID on success, 0 otherwise
4542
     *
4543
     * @see subscribe_sessions_to_promotions() for that.
4544
     *
4545
     * @todo make sure the extra session fields are copied too
4546
     */
4547
    public static function copy(
4548
        $id,
4549
        $copy_courses = true,
4550
        $copyTeachersAndDrh = true,
4551
        $create_new_courses = false,
4552
        $set_exercises_lp_invisible = false,
4553
        $copyWithSessionContent = false
4554
    ) {
4555
        $id = (int) $id;
4556
        $s = self::fetch($id);
4557
4558
        if (empty($s)) {
4559
            return false;
4560
        }
4561
4562
        // Check all dates before copying
4563
        // Get timestamp for now in UTC - see http://php.net/manual/es/function.time.php#117251
4564
        $now = time() - date('Z');
4565
        // Timestamp in one month
4566
        $inOneMonth = $now + (30 * 24 * 3600);
4567
        $inOneMonth = api_get_local_time($inOneMonth);
4568
        if (api_strtotime($s['access_start_date']) < $now) {
4569
            $s['access_start_date'] = api_get_local_time($now);
4570
        } else {
4571
            $s['access_start_date'] = api_get_local_time($s['access_start_date']);
4572
        }
4573
        if (api_strtotime($s['display_start_date']) < $now) {
4574
            $s['display_start_date'] = api_get_local_time($now);
4575
        } else {
4576
            $s['display_start_date'] = api_get_local_time($s['display_start_date']);
4577
        }
4578
        if (api_strtotime($s['coach_access_start_date']) < $now) {
4579
            $s['coach_access_start_date'] = api_get_local_time($now);
4580
        } else {
4581
            $s['coach_access_start_date'] = api_get_local_time($s['coach_access_start_date']);
4582
        }
4583
        if (api_strtotime($s['access_end_date']) < $now) {
4584
            $s['access_end_date'] = $inOneMonth;
4585
        } else {
4586
            $s['access_end_date'] = api_get_local_time($s['access_end_date']);
4587
        }
4588
        if (api_strtotime($s['display_end_date']) < $now) {
4589
            $s['display_end_date'] = $inOneMonth;
4590
        } else {
4591
            $s['display_end_date'] = api_get_local_time($s['display_end_date']);
4592
        }
4593
        if (api_strtotime($s['coach_access_end_date']) < $now) {
4594
            $s['coach_access_end_date'] = $inOneMonth;
4595
        } else {
4596
            $s['coach_access_end_date'] = api_get_local_time($s['coach_access_end_date']);
4597
        }
4598
4599
        $extraFieldValue = new ExtraFieldValue('session');
4600
        $extraFieldsValues = $extraFieldValue->getAllValuesByItem($id);
4601
        $extraFieldsValuesToCopy = [];
4602
        if (!empty($extraFieldsValues)) {
4603
            foreach ($extraFieldsValues as $extraFieldValue) {
4604
                $extraFieldsValuesToCopy['extra_'.$extraFieldValue['variable']]['extra_'.$extraFieldValue['variable']] = $extraFieldValue['value'];
4605
            }
4606
        }
4607
4608
        if (isset($extraFieldsValuesToCopy['extra_image']) && isset($extraFieldsValuesToCopy['extra_image']['extra_image'])) {
4609
            $extraFieldsValuesToCopy['extra_image'] = [
4610
                'tmp_name' => api_get_path(SYS_UPLOAD_PATH).$extraFieldsValuesToCopy['extra_image']['extra_image'],
4611
                'error' => 0,
4612
            ];
4613
        }
4614
4615
        // Now try to create the session
4616
        $sid = self::create_session(
4617
            $s['name'].' '.get_lang('CopyLabelSuffix'),
4618
            $s['access_start_date'],
4619
            $s['access_end_date'],
4620
            $s['display_start_date'],
4621
            $s['display_end_date'],
4622
            $s['coach_access_start_date'],
4623
            $s['coach_access_end_date'],
4624
            (int) $s['id_coach'],
4625
            $s['session_category_id'],
4626
            (int) $s['visibility'],
4627
            true,
4628
            $s['duration'],
4629
            $s['description'],
4630
            $s['show_description'],
4631
            $extraFieldsValuesToCopy
4632
        );
4633
4634
        if (!is_numeric($sid) || empty($sid)) {
4635
            return false;
4636
        }
4637
4638
        if ($copy_courses) {
4639
            // Register courses from the original session to the new session
4640
            $courses = self::get_course_list_by_session_id($id);
4641
            $short_courses = $new_short_courses = [];
4642
            if (is_array($courses) && count($courses) > 0) {
4643
                foreach ($courses as $course) {
4644
                    $short_courses[] = $course;
4645
                }
4646
            }
4647
4648
            // We will copy the current courses of the session to new courses
4649
            if (!empty($short_courses)) {
4650
                if ($create_new_courses) {
4651
                    api_set_more_memory_and_time_limits();
4652
                    $params = [];
4653
                    $params['skip_lp_dates'] = true;
4654
4655
                    foreach ($short_courses as $course_data) {
4656
                        $course_info = CourseManager::copy_course_simple(
4657
                            $course_data['title'].' '.get_lang('CopyLabelSuffix'),
4658
                            $course_data['course_code'],
4659
                            $id,
4660
                            $sid,
4661
                            $params
4662
                        );
4663
4664
                        if ($course_info) {
4665
                            //By default new elements are invisible
4666
                            if ($set_exercises_lp_invisible) {
4667
                                $list = new LearnpathList('', $course_info, $sid);
4668
                                $flat_list = $list->get_flat_list();
4669
                                if (!empty($flat_list)) {
4670
                                    foreach ($flat_list as $lp_id => $data) {
4671
                                        api_item_property_update(
4672
                                            $course_info,
4673
                                            TOOL_LEARNPATH,
4674
                                            $lp_id,
4675
                                            'invisible',
4676
                                            api_get_user_id(),
4677
                                            0,
4678
                                            0,
4679
                                            0,
4680
                                            0,
4681
                                            $sid
4682
                                        );
4683
                                    }
4684
                                }
4685
                                $quiz_table = Database::get_course_table(TABLE_QUIZ_TEST);
4686
                                $course_id = $course_info['real_id'];
4687
                                //@todo check this query
4688
                                $sql = "UPDATE $quiz_table SET active = 0
4689
                                        WHERE c_id = $course_id AND session_id = $sid";
4690
                                Database::query($sql);
4691
                            }
4692
                            $new_short_courses[] = $course_info['real_id'];
4693
                        }
4694
                    }
4695
                } else {
4696
                    foreach ($short_courses as $course_data) {
4697
                        $new_short_courses[] = $course_data['id'];
4698
                    }
4699
                }
4700
4701
                $short_courses = $new_short_courses;
4702
                self::add_courses_to_session($sid, $short_courses, true);
4703
4704
                if ($copyWithSessionContent) {
4705
                    foreach ($courses as $course) {
4706
                        CourseManager::copy_course(
4707
                            $course['code'],
4708
                            $id,
4709
                            $course['code'],
4710
                            $sid,
4711
                            [],
4712
                            false
4713
                        );
4714
                    }
4715
                }
4716
4717
                if ($create_new_courses === false && $copyTeachersAndDrh) {
4718
                    foreach ($short_courses as $courseItemId) {
4719
                        $coachList = self::getCoachesByCourseSession($id, $courseItemId);
4720
                        foreach ($coachList as $userId) {
4721
                            self::set_coach_to_course_session($userId, $sid, $courseItemId);
4722
                        }
4723
                    }
4724
                }
4725
            }
4726
        }
4727
4728
        if ($copyTeachersAndDrh) {
4729
            // Register users from the original session to the new session
4730
            $users = self::get_users_by_session($id);
4731
            if (!empty($users)) {
4732
                $userListByStatus = [];
4733
                foreach ($users as $userData) {
4734
                    $userData['relation_type'] = (int) $userData['relation_type'];
4735
                    $userListByStatus[$userData['relation_type']][] = $userData;
4736
                }
4737
4738
                foreach ($userListByStatus as $status => $userList) {
4739
                    $userList = array_column($userList, 'user_id');
4740
                    switch ($status) {
4741
                        case 0:
4742
                            /*self::subscribeUsersToSession(
4743
                                $sid,
4744
                                $userList,
4745
                                SESSION_VISIBLE_READ_ONLY,
4746
                                false,
4747
                                true
4748
                            );*/
4749
                            break;
4750
                        case 1:
4751
                            // drh users
4752
                            foreach ($userList as $drhId) {
4753
                                $userInfo = api_get_user_info($drhId);
4754
                                self::subscribeSessionsToDrh($userInfo, [$sid], false, false);
4755
                            }
4756
                            break;
4757
                    }
4758
                }
4759
            }
4760
        }
4761
4762
        return $sid;
4763
    }
4764
4765
    /**
4766
     * @param int $user_id
4767
     * @param int $session_id
4768
     *
4769
     * @return bool
4770
     */
4771
    public static function user_is_general_coach($user_id, $session_id)
4772
    {
4773
        $session_id = (int) $session_id;
4774
        $user_id = (int) $user_id;
4775
        $table = Database::get_main_table(TABLE_MAIN_SESSION);
4776
        $sql = "SELECT DISTINCT id
4777
	         	FROM $table
4778
	         	WHERE session.id_coach = '".$user_id."' AND id = '$session_id'";
4779
        $result = Database::query($sql);
4780
        if ($result && Database::num_rows($result)) {
4781
            return true;
4782
        }
4783
4784
        return false;
4785
    }
4786
4787
    /**
4788
     * Get the number of sessions.
4789
     *
4790
     * @param int $access_url_id ID of the URL we want to filter on (optional)
4791
     *
4792
     * @return int Number of sessions
4793
     */
4794
    public static function count_sessions($access_url_id = 0)
4795
    {
4796
        $session_table = Database::get_main_table(TABLE_MAIN_SESSION);
4797
        $access_url_rel_session_table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
4798
        $access_url_id = (int) $access_url_id;
4799
        $sql = "SELECT count(s.id) FROM $session_table s";
4800
        if (!empty($access_url_id)) {
4801
            $sql .= ", $access_url_rel_session_table u ".
4802
                " WHERE s.id = u.session_id AND u.access_url_id = $access_url_id";
4803
        }
4804
        $res = Database::query($sql);
4805
        $row = Database::fetch_row($res);
4806
4807
        return $row[0];
4808
    }
4809
4810
    /**
4811
     * @param int  $id
4812
     * @param bool $checkSession
4813
     *
4814
     * @return bool
4815
     */
4816
    public static function cantEditSession($id, $checkSession = true)
4817
    {
4818
        if (!self::allowToManageSessions()) {
4819
            return false;
4820
        }
4821
4822
        if (api_is_platform_admin() && self::allowed($id)) {
4823
            return true;
4824
        }
4825
4826
        if ($checkSession) {
4827
            if (self::allowed($id)) {
4828
                return true;
4829
            }
4830
4831
            return false;
4832
        }
4833
4834
        return true;
4835
    }
4836
4837
    /**
4838
     * Protect a session to be edited.
4839
     *
4840
     * @param int  $id
4841
     * @param bool $checkSession
4842
     *
4843
     * @return mixed | bool true if pass the check, api_not_allowed otherwise
4844
     */
4845
    public static function protectSession($id, $checkSession = true)
4846
    {
4847
        if (!self::cantEditSession($id, $checkSession)) {
4848
            api_not_allowed(true);
4849
        }
4850
    }
4851
4852
    /**
4853
     * @return bool
4854
     */
4855
    public static function allowToManageSessions()
4856
    {
4857
        if (self::allowManageAllSessions()) {
4858
            return true;
4859
        }
4860
4861
        $setting = api_get_setting('allow_teachers_to_create_sessions');
4862
4863
        if (api_is_teacher() && $setting == 'true') {
4864
            return true;
4865
        }
4866
4867
        return false;
4868
    }
4869
4870
    /**
4871
     * @return bool
4872
     */
4873
    public static function allowOnlyMySessions()
4874
    {
4875
        if (self::allowToManageSessions() &&
4876
            !api_is_platform_admin() &&
4877
            api_is_teacher()
4878
        ) {
4879
            return true;
4880
        }
4881
4882
        return false;
4883
    }
4884
4885
    /**
4886
     * @return bool
4887
     */
4888
    public static function allowManageAllSessions()
4889
    {
4890
        if (api_is_platform_admin() || api_is_session_admin()) {
4891
            return true;
4892
        }
4893
4894
        return false;
4895
    }
4896
4897
    /**
4898
     * @param $id
4899
     *
4900
     * @return bool
4901
     */
4902
    public static function protect_teacher_session_edit($id)
4903
    {
4904
        if (!api_is_coach($id) && !api_is_platform_admin()) {
4905
            api_not_allowed(true);
4906
        } else {
4907
            return true;
4908
        }
4909
    }
4910
4911
    /**
4912
     * @param int $courseId
4913
     *
4914
     * @return array
4915
     */
4916
    public static function get_session_by_course($courseId)
4917
    {
4918
        $table_session_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
4919
        $table_session = Database::get_main_table(TABLE_MAIN_SESSION);
4920
        $url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
4921
        $courseId = (int) $courseId;
4922
        $urlId = api_get_current_access_url_id();
4923
4924
        if (empty($courseId)) {
4925
            return [];
4926
        }
4927
4928
        $sql = "SELECT name, s.id
4929
                FROM $table_session_course sc
4930
                INNER JOIN $table_session s
4931
                ON (sc.session_id = s.id)
4932
                INNER JOIN $url u
4933
                ON (u.session_id = s.id)
4934
                WHERE
4935
                    u.access_url_id = $urlId AND
4936
                    sc.c_id = '$courseId' ";
4937
        $result = Database::query($sql);
4938
4939
        return Database::store_result($result);
4940
    }
4941
4942
    /**
4943
     * @param int  $userId
4944
     * @param bool $ignoreVisibilityForAdmins
4945
     * @param bool $ignoreTimeLimit
4946
     *
4947
     * @return array
4948
     */
4949
    public static function get_sessions_by_user(
4950
        $userId,
4951
        $ignoreVisibilityForAdmins = false,
4952
        $ignoreTimeLimit = false
4953
    ) {
4954
        $sessionCategories = UserManager::get_sessions_by_category(
4955
            $userId,
4956
            false,
4957
            $ignoreVisibilityForAdmins,
4958
            $ignoreTimeLimit
4959
        );
4960
4961
        $sessionArray = [];
4962
        if (!empty($sessionCategories)) {
4963
            foreach ($sessionCategories as $category) {
4964
                if (isset($category['sessions'])) {
4965
                    foreach ($category['sessions'] as $session) {
4966
                        $sessionArray[] = $session;
4967
                    }
4968
                }
4969
            }
4970
        }
4971
4972
        return $sessionArray;
4973
    }
4974
4975
    /**
4976
     * @param string $file
4977
     * @param bool   $updateSession                                   true: if the session exists it will be updated.
4978
     *                                                                false: if session exists a new session will be created adding a counter session1, session2, etc
4979
     * @param int    $defaultUserId
4980
     * @param Logger $logger
4981
     * @param array  $extraFields                                     convert a file row to an extra field. Example in CSV file there's a SessionID
4982
     *                                                                then it will converted to extra_external_session_id if you set: array('SessionId' => 'extra_external_session_id')
4983
     * @param string $extraFieldId
4984
     * @param int    $daysCoachAccessBeforeBeginning
4985
     * @param int    $daysCoachAccessAfterBeginning
4986
     * @param int    $sessionVisibility
4987
     * @param array  $fieldsToAvoidUpdate
4988
     * @param bool   $deleteUsersNotInList
4989
     * @param bool   $updateCourseCoaches
4990
     * @param bool   $sessionWithCoursesModifier
4991
     * @param bool   $addOriginalCourseTeachersAsCourseSessionCoaches
4992
     * @param bool   $removeAllTeachersFromCourse
4993
     * @param int    $showDescription
4994
     * @param array  $teacherBackupList
4995
     * @param array  $groupBackup
4996
     *
4997
     * @return array
4998
     */
4999
    public static function importCSV(
5000
        $file,
5001
        $updateSession,
5002
        $defaultUserId = null,
5003
        $logger = null,
5004
        $extraFields = [],
5005
        $extraFieldId = null,
5006
        $daysCoachAccessBeforeBeginning = null,
5007
        $daysCoachAccessAfterBeginning = null,
5008
        $sessionVisibility = 1,
5009
        $fieldsToAvoidUpdate = [],
5010
        $deleteUsersNotInList = false,
5011
        $updateCourseCoaches = false,
5012
        $sessionWithCoursesModifier = false,
5013
        $addOriginalCourseTeachersAsCourseSessionCoaches = true,
5014
        $removeAllTeachersFromCourse = true,
5015
        $showDescription = null,
5016
        &$teacherBackupList = [],
5017
        &$groupBackup = []
5018
    ) {
5019
        $content = file($file);
5020
        $error_message = null;
5021
        $session_counter = 0;
5022
        $defaultUserId = empty($defaultUserId) ? api_get_user_id() : (int) $defaultUserId;
5023
5024
        $eol = PHP_EOL;
5025
        if (PHP_SAPI != 'cli') {
5026
            $eol = '<br />';
5027
        }
5028
5029
        $debug = false;
5030
        if (isset($logger)) {
5031
            $debug = true;
5032
        }
5033
5034
        $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
5035
        $tbl_session_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
5036
        $tbl_session_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
5037
        $tbl_session_course_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
5038
        $sessions = [];
5039
        if (!api_strstr($content[0], ';')) {
5040
            $error_message = get_lang('NotCSV');
5041
        } else {
5042
            $tag_names = [];
5043
            foreach ($content as $key => $enreg) {
5044
                $enreg = explode(';', trim($enreg));
5045
                if ($key) {
5046
                    foreach ($tag_names as $tag_key => $tag_name) {
5047
                        if (isset($enreg[$tag_key])) {
5048
                            $sessions[$key - 1][$tag_name] = $enreg[$tag_key];
5049
                        }
5050
                    }
5051
                } else {
5052
                    foreach ($enreg as $tag_name) {
5053
                        $tag_names[] = api_preg_replace('/[^a-zA-Z0-9_\-]/', '', $tag_name);
5054
                    }
5055
                    if (!in_array('SessionName', $tag_names) ||
5056
                        !in_array('DateStart', $tag_names) ||
5057
                        !in_array('DateEnd', $tag_names)
5058
                    ) {
5059
                        $error_message = get_lang('NoNeededData');
5060
                        break;
5061
                    }
5062
                }
5063
            }
5064
5065
            $sessionList = [];
5066
            $report = [];
5067
5068
            // Looping the sessions.
5069
            foreach ($sessions as $enreg) {
5070
                $user_counter = 0;
5071
                $course_counter = 0;
5072
5073
                if (isset($extraFields) && !empty($extraFields)) {
5074
                    foreach ($extraFields as $original => $to) {
5075
                        $enreg[$to] = isset($enreg[$original]) ? $enreg[$original] : null;
5076
                    }
5077
                }
5078
5079
                $session_name = $enreg['SessionName'];
5080
5081
                if ($debug) {
5082
                    $logger->addInfo('---------------------------------------');
5083
                    $logger->addInfo("Sessions - Start process of session: $session_name");
5084
                    $logger->addInfo('---------------------------------------');
5085
                }
5086
5087
                // Default visibility
5088
                $visibilityAfterExpirationPerSession = $sessionVisibility;
5089
5090
                if (isset($enreg['VisibilityAfterExpiration'])) {
5091
                    $visibility = $enreg['VisibilityAfterExpiration'];
5092
                    switch ($visibility) {
5093
                        case 'read_only':
5094
                            $visibilityAfterExpirationPerSession = SESSION_VISIBLE_READ_ONLY;
5095
                            break;
5096
                        case 'accessible':
5097
                            $visibilityAfterExpirationPerSession = SESSION_VISIBLE;
5098
                            break;
5099
                        case 'not_accessible':
5100
                            $visibilityAfterExpirationPerSession = SESSION_INVISIBLE;
5101
                            break;
5102
                    }
5103
                }
5104
5105
                if (empty($session_name)) {
5106
                    continue;
5107
                }
5108
5109
                $displayAccessStartDate = isset($enreg['DisplayStartDate']) ? $enreg['DisplayStartDate'] : $enreg['DateStart'];
5110
                $displayAccessEndDate = isset($enreg['DisplayEndDate']) ? $enreg['DisplayEndDate'] : $enreg['DateEnd'];
5111
                $coachAccessStartDate = isset($enreg['CoachStartDate']) ? $enreg['CoachStartDate'] : $enreg['DateStart'];
5112
                $coachAccessEndDate = isset($enreg['CoachEndDate']) ? $enreg['CoachEndDate'] : $enreg['DateEnd'];
5113
                // We assume the dates are already in UTC
5114
                $dateStart = explode('/', $enreg['DateStart']);
5115
                $dateEnd = explode('/', $enreg['DateEnd']);
5116
                $dateStart = $dateStart[0].'-'.$dateStart[1].'-'.$dateStart[2].' 00:00:00';
5117
                $dateEnd = $dateEnd[0].'-'.$dateEnd[1].'-'.$dateEnd[2].' 23:59:59';
5118
                $displayAccessStartDate = explode('/', $displayAccessStartDate);
5119
                $displayAccessStartDate = implode('-', $displayAccessStartDate).' 00:00:00';
5120
                $displayAccessEndDate = explode('/', $displayAccessEndDate);
5121
                $displayAccessEndDate = implode('-', $displayAccessEndDate).' 23:59:59';
5122
                $coachAccessStartDate = explode('/', $coachAccessStartDate);
5123
                $coachAccessStartDate = implode('-', $coachAccessStartDate).' 00:00:00';
5124
                $coachAccessEndDate = explode('/', $coachAccessEndDate);
5125
                $coachAccessEndDate = implode('-', $coachAccessEndDate).' 23:59:59';
5126
                $session_category_id = isset($enreg['SessionCategory']) ? $enreg['SessionCategory'] : null;
5127
                $sessionDescription = isset($enreg['SessionDescription']) ? $enreg['SessionDescription'] : null;
5128
                $classes = isset($enreg['Classes']) ? explode('|', $enreg['Classes']) : [];
5129
                $extraParams = [];
5130
                if (!is_null($showDescription)) {
5131
                    $extraParams['show_description'] = intval($showDescription);
5132
                }
5133
5134
                $coachBefore = '';
5135
                $coachAfter = '';
5136
                if (!empty($daysCoachAccessBeforeBeginning) && !empty($daysCoachAccessAfterBeginning)) {
5137
                    $date = new \DateTime($dateStart);
5138
                    $interval = new DateInterval('P'.$daysCoachAccessBeforeBeginning.'D');
5139
                    $date->sub($interval);
5140
                    $coachBefore = $date->format('Y-m-d h:i');
5141
                    $coachAccessStartDate = $coachBefore;
5142
                    $coachBefore = api_get_utc_datetime($coachBefore);
5143
5144
                    $date = new \DateTime($dateEnd);
5145
                    $interval = new DateInterval('P'.$daysCoachAccessAfterBeginning.'D');
5146
                    $date->add($interval);
5147
                    $coachAfter = $date->format('Y-m-d h:i');
5148
                    $coachAccessEndDate = $coachAfter;
5149
                    $coachAfter = api_get_utc_datetime($coachAfter);
5150
                }
5151
5152
                $dateStart = api_get_utc_datetime($dateStart);
5153
                $dateEnd = api_get_utc_datetime($dateEnd);
5154
                $displayAccessStartDate = api_get_utc_datetime($displayAccessStartDate);
5155
                $displayAccessEndDate = api_get_utc_datetime($displayAccessEndDate);
5156
                $coachAccessStartDate = api_get_utc_datetime($coachAccessStartDate);
5157
                $coachAccessEndDate = api_get_utc_datetime($coachAccessEndDate);
5158
5159
                if (!empty($sessionDescription)) {
5160
                    $extraParams['description'] = $sessionDescription;
5161
                }
5162
5163
                if (!empty($session_category_id)) {
5164
                    $extraParams['session_category_id'] = $session_category_id;
5165
                }
5166
5167
                // Searching a general coach.
5168
                if (!empty($enreg['Coach'])) {
5169
                    $coach_id = UserManager::get_user_id_from_username($enreg['Coach']);
5170
                    if ($coach_id === false) {
5171
                        // If the coach-user does not exist - I'm the coach.
5172
                        $coach_id = $defaultUserId;
5173
                    }
5174
                } else {
5175
                    $coach_id = $defaultUserId;
5176
                }
5177
5178
                $users = explode('|', $enreg['Users']);
5179
                $courses = explode('|', $enreg['Courses']);
5180
5181
                $deleteOnlyCourseCoaches = false;
5182
                if (count($courses) == 1) {
5183
                    if ($logger) {
5184
                        $logger->addInfo('Only one course delete old coach list');
5185
                    }
5186
                    $deleteOnlyCourseCoaches = true;
5187
                }
5188
5189
                if (!$updateSession) {
5190
                    // Create a session.
5191
                    $unique_name = false;
5192
                    $i = 0;
5193
                    // Change session name, verify that session doesn't exist.
5194
                    $suffix = null;
5195
                    while (!$unique_name) {
5196
                        if ($i > 1) {
5197
                            $suffix = ' - '.$i;
5198
                        }
5199
                        $sql = 'SELECT 1 FROM '.$tbl_session.'
5200
                                WHERE name="'.Database::escape_string($session_name).$suffix.'"';
5201
                        $rs = Database::query($sql);
5202
                        if (Database::result($rs, 0, 0)) {
5203
                            $i++;
5204
                        } else {
5205
                            $unique_name = true;
5206
                            $session_name .= $suffix;
5207
                        }
5208
                    }
5209
5210
                    $sessionParams = [
5211
                        'name' => $session_name,
5212
                        'id_coach' => $coach_id,
5213
                        'access_start_date' => $dateStart,
5214
                        'access_end_date' => $dateEnd,
5215
                        'display_start_date' => $displayAccessStartDate,
5216
                        'display_end_date' => $displayAccessEndDate,
5217
                        'coach_access_start_date' => $coachAccessStartDate,
5218
                        'coach_access_end_date' => $coachAccessEndDate,
5219
                        'visibility' => $visibilityAfterExpirationPerSession,
5220
                        'session_admin_id' => $defaultUserId,
5221
                    ];
5222
5223
                    if (!empty($extraParams)) {
5224
                        $sessionParams = array_merge($sessionParams, $extraParams);
5225
                    }
5226
                    // Creating the session.
5227
                    $session_id = Database::insert($tbl_session, $sessionParams);
5228
                    if ($debug) {
5229
                        if ($session_id) {
5230
                            foreach ($enreg as $key => $value) {
5231
                                if (substr($key, 0, 6) == 'extra_') { //an extra field
5232
                                    self::update_session_extra_field_value($session_id, substr($key, 6), $value);
5233
                                }
5234
                            }
5235
                            $logger->addInfo("Session created: #$session_id - $session_name");
5236
                        } else {
5237
                            $message = "Sessions - Session NOT created: $session_name";
5238
                            $logger->addError($message);
5239
                            $report[] = $message;
5240
                        }
5241
                    }
5242
                    $session_counter++;
5243
                } else {
5244
                    $sessionId = null;
5245
                    if (isset($extraFields) && !empty($extraFields) && !empty($enreg['extra_'.$extraFieldId])) {
5246
                        $sessionId = self::getSessionIdFromOriginalId($enreg['extra_'.$extraFieldId], $extraFieldId);
5247
                        if (empty($sessionId)) {
5248
                            $my_session_result = false;
5249
                        } else {
5250
                            $my_session_result = true;
5251
                        }
5252
                    } else {
5253
                        $my_session_result = self::get_session_by_name($enreg['SessionName']);
5254
                    }
5255
5256
                    if ($my_session_result === false) {
5257
                        // One more check
5258
                        $sessionExistsWithName = self::get_session_by_name($session_name);
5259
                        if ($sessionExistsWithName) {
5260
                            if ($debug) {
5261
                                $message = "Skip Session - Trying to update a session, but name already exists: $session_name";
5262
                                $logger->addError($message);
5263
                                $report[] = $message;
5264
                            }
5265
                            continue;
5266
                        }
5267
5268
                        $sessionParams = [
5269
                            'name' => $session_name,
5270
                            'id_coach' => $coach_id,
5271
                            'access_start_date' => $dateStart,
5272
                            'access_end_date' => $dateEnd,
5273
                            'display_start_date' => $displayAccessStartDate,
5274
                            'display_end_date' => $displayAccessEndDate,
5275
                            'coach_access_start_date' => $coachAccessStartDate,
5276
                            'coach_access_end_date' => $coachAccessEndDate,
5277
                            'visibility' => $visibilityAfterExpirationPerSession,
5278
                            'session_admin_id' => $defaultUserId,
5279
                        ];
5280
5281
                        if (!empty($extraParams)) {
5282
                            $sessionParams = array_merge($sessionParams, $extraParams);
5283
                        }
5284
                        Database::insert($tbl_session, $sessionParams);
5285
5286
                        // We get the last insert id.
5287
                        $my_session_result = self::get_session_by_name($session_name);
5288
                        $session_id = $my_session_result['id'];
5289
5290
                        if ($session_id) {
5291
                            foreach ($enreg as $key => $value) {
5292
                                if (substr($key, 0, 6) == 'extra_') { //an extra field
5293
                                    self::update_session_extra_field_value($session_id, substr($key, 6), $value);
5294
                                }
5295
                            }
5296
                            if ($debug) {
5297
                                $logger->addInfo("Sessions - #$session_id created: $session_name");
5298
                            }
5299
5300
                            // Delete session-user relation only for students
5301
                            $sql = "DELETE FROM $tbl_session_user
5302
                                    WHERE session_id = '$session_id' AND relation_type <> ".SESSION_RELATION_TYPE_RRHH;
5303
                            Database::query($sql);
5304
5305
                            $sql = "DELETE FROM $tbl_session_course WHERE session_id = '$session_id'";
5306
                            Database::query($sql);
5307
5308
                            // Delete session-course-user relationships students and coaches.
5309
                            if ($updateCourseCoaches) {
5310
                                $sql = "DELETE FROM $tbl_session_course_user
5311
                                        WHERE session_id = '$session_id' AND status in ('0', '2')";
5312
                                Database::query($sql);
5313
                            } else {
5314
                                // Delete session-course-user relation ships *only* for students.
5315
                                $sql = "DELETE FROM $tbl_session_course_user
5316
                                        WHERE session_id = '$session_id' AND status <> 2";
5317
                                Database::query($sql);
5318
                            }
5319
                            if ($deleteOnlyCourseCoaches) {
5320
                                $sql = "DELETE FROM $tbl_session_course_user
5321
                                        WHERE session_id = '$session_id' AND status in ('2')";
5322
                                Database::query($sql);
5323
                            }
5324
                        }
5325
                    } else {
5326
                        // Updating the session.
5327
                        $params = [
5328
                            'id_coach' => $coach_id,
5329
                            'access_start_date' => $dateStart,
5330
                            'access_end_date' => $dateEnd,
5331
                            'display_start_date' => $displayAccessStartDate,
5332
                            'display_end_date' => $displayAccessEndDate,
5333
                            'coach_access_start_date' => $coachAccessStartDate,
5334
                            'coach_access_end_date' => $coachAccessEndDate,
5335
                            'visibility' => $visibilityAfterExpirationPerSession,
5336
                            'session_category_id' => $session_category_id,
5337
                        ];
5338
5339
                        if (!empty($sessionDescription)) {
5340
                            $params['description'] = $sessionDescription;
5341
                        }
5342
5343
                        if (!empty($fieldsToAvoidUpdate)) {
5344
                            foreach ($fieldsToAvoidUpdate as $field) {
5345
                                unset($params[$field]);
5346
                            }
5347
                        }
5348
5349
                        if (isset($sessionId) && !empty($sessionId)) {
5350
                            $session_id = $sessionId;
5351
                            if (!empty($enreg['SessionName'])) {
5352
                                $sessionExistsWithName = self::get_session_by_name($session_name);
5353
                                if ($sessionExistsWithName === false) {
5354
                                    $sessionName = Database::escape_string($enreg['SessionName']);
5355
                                    $sql = "UPDATE $tbl_session SET name = '$sessionName' WHERE id = $session_id";
5356
                                    Database::query($sql);
5357
                                    $logger->addInfo(
5358
                                        "Session #$session_id name IS updated with: '$session_name' External id: ".$enreg['extra_'.$extraFieldId]
5359
                                    );
5360
                                } else {
5361
                                    $sessionExistsBesidesMe = self::sessionNameExistBesidesMySession(
5362
                                        $session_id,
5363
                                        $session_name
5364
                                    );
5365
                                    if ($sessionExistsBesidesMe === true) {
5366
                                        if ($debug) {
5367
                                            $message = "Skip Session. Error when update session Session #$session_id Name: '$session_name'. Other session has the same name. External id: ".$enreg['extra_'.$extraFieldId];
5368
                                            $logger->addError($message);
5369
                                            $report[] = $message;
5370
                                        }
5371
                                        continue;
5372
                                    } else {
5373
                                        if ($debug) {
5374
                                            $logger->addInfo(
5375
                                                "Session #$session_id name is not updated because it didn't change (but update of other session values will continue) Name: '$session_name' External id: ".$enreg['extra_'.$extraFieldId]
5376
                                            );
5377
                                        }
5378
                                    }
5379
                                }
5380
                            }
5381
                        } else {
5382
                            $my_session_result = self::get_session_by_name($session_name);
5383
                            $session_id = $my_session_result['id'];
5384
                        }
5385
5386
                        if ($debug) {
5387
                            $logger->addInfo("Session #$session_id to be updated: '$session_name'");
5388
                        }
5389
5390
                        if ($session_id) {
5391
                            $sessionInfo = api_get_session_info($session_id);
5392
                            $params['show_description'] = isset($sessionInfo['show_description']) ? $sessionInfo['show_description'] : intval($showDescription);
5393
5394
                            if (!empty($daysCoachAccessBeforeBeginning) && !empty($daysCoachAccessAfterBeginning)) {
5395
                                if (empty($sessionInfo['nb_days_access_before_beginning']) ||
5396
                                    (!empty($sessionInfo['nb_days_access_before_beginning']) &&
5397
                                        $sessionInfo['nb_days_access_before_beginning'] < $daysCoachAccessBeforeBeginning)
5398
                                ) {
5399
                                    $params['coach_access_start_date'] = $coachBefore;
5400
                                }
5401
5402
                                if (empty($sessionInfo['nb_days_access_after_end']) ||
5403
                                    (!empty($sessionInfo['nb_days_access_after_end']) &&
5404
                                        $sessionInfo['nb_days_access_after_end'] < $daysCoachAccessAfterBeginning)
5405
                                ) {
5406
                                    $params['coach_access_end_date'] = $coachAfter;
5407
                                }
5408
                            }
5409
5410
                            Database::update($tbl_session, $params, ['id = ?' => $session_id]);
5411
                            foreach ($enreg as $key => $value) {
5412
                                if (substr($key, 0, 6) == 'extra_') { //an extra field
5413
                                    self::update_session_extra_field_value($session_id, substr($key, 6), $value);
5414
                                }
5415
                            }
5416
5417
                            if ($debug) {
5418
                                $logger->addInfo("Session updated #$session_id");
5419
                            }
5420
5421
                            // Delete session-user relation only for students
5422
                            $sql = "DELETE FROM $tbl_session_user
5423
                                    WHERE session_id = '$session_id' AND relation_type <> ".SESSION_RELATION_TYPE_RRHH;
5424
                            Database::query($sql);
5425
5426
                            $sql = "DELETE FROM $tbl_session_course WHERE session_id = '$session_id'";
5427
                            Database::query($sql);
5428
5429
                            // Delete session-course-user relationships students and coaches.
5430
                            if ($updateCourseCoaches) {
5431
                                $sql = "DELETE FROM $tbl_session_course_user
5432
                                        WHERE session_id = '$session_id' AND status in ('0', '2')";
5433
                                Database::query($sql);
5434
                            } else {
5435
                                // Delete session-course-user relation ships *only* for students.
5436
                                $sql = "DELETE FROM $tbl_session_course_user
5437
                                        WHERE session_id = '$session_id' AND status <> 2";
5438
                                Database::query($sql);
5439
                            }
5440
5441
                            if ($deleteOnlyCourseCoaches) {
5442
                                $sql = "DELETE FROM $tbl_session_course_user
5443
                                        WHERE session_id = '$session_id' AND status in ('2')";
5444
                                Database::query($sql);
5445
                            }
5446
                        } else {
5447
                            if ($debug) {
5448
                                $logger->addError(
5449
                                    "Sessions - Session not found"
5450
                                );
5451
                            }
5452
                        }
5453
                    }
5454
                    $session_counter++;
5455
                }
5456
5457
                $sessionList[] = $session_id;
5458
5459
                // Adding the relationship "Session - User" for students
5460
                $userList = [];
5461
                if (is_array($users)) {
5462
                    $extraFieldValueCareer = new ExtraFieldValue('career');
5463
                    $careerList = isset($enreg['extra_careerid']) && !empty($enreg['extra_careerid']) ? $enreg['extra_careerid'] : [];
5464
                    $careerList = str_replace(['[', ']'], '', $careerList);
5465
                    $careerList = explode(',', $careerList);
5466
                    $finalCareerIdList = [];
5467
                    foreach ($careerList as $careerId) {
5468
                        $realCareerIdList = $extraFieldValueCareer->get_item_id_from_field_variable_and_field_value(
5469
                            'external_career_id',
5470
                            $careerId
5471
                        );
5472
                        if (isset($realCareerIdList['item_id'])) {
5473
                            $finalCareerIdList[] = $realCareerIdList['item_id'];
5474
                        }
5475
                    }
5476
5477
                    foreach ($users as $user) {
5478
                        $user_id = UserManager::get_user_id_from_username($user);
5479
                        if ($user_id !== false) {
5480
                            if (!empty($finalCareerIdList)) {
5481
                                foreach ($finalCareerIdList as $careerId) {
5482
                                    UserManager::addUserCareer($user_id, $careerId);
5483
                                }
5484
                            }
5485
5486
                            $userList[] = $user_id;
5487
                            // Insert new users.
5488
                            $sql = "INSERT IGNORE INTO $tbl_session_user SET
5489
                                    user_id = '$user_id',
5490
                                    session_id = '$session_id',
5491
                                    registered_at = '".api_get_utc_datetime()."'";
5492
                            Database::query($sql);
5493
                            if ($debug) {
5494
                                $logger->addInfo("Adding User #$user_id ($user) to session #$session_id");
5495
                            }
5496
                            $user_counter++;
5497
                        }
5498
                    }
5499
                }
5500
5501
                if ($deleteUsersNotInList) {
5502
                    // Getting user in DB in order to compare to the new list.
5503
                    $usersListInDatabase = self::get_users_by_session($session_id, 0);
5504
                    if (!empty($usersListInDatabase)) {
5505
                        if (empty($userList)) {
5506
                            foreach ($usersListInDatabase as $userInfo) {
5507
                                self::unsubscribe_user_from_session($session_id, $userInfo['user_id']);
5508
                            }
5509
                        } else {
5510
                            foreach ($usersListInDatabase as $userInfo) {
5511
                                if (!in_array($userInfo['user_id'], $userList)) {
5512
                                    self::unsubscribe_user_from_session($session_id, $userInfo['user_id']);
5513
                                }
5514
                            }
5515
                        }
5516
                    }
5517
                }
5518
5519
                // See BT#6449
5520
                $onlyAddFirstCoachOrTeacher = false;
5521
                if ($sessionWithCoursesModifier) {
5522
                    if (count($courses) >= 2) {
5523
                        // Only first teacher in course session;
5524
                        $onlyAddFirstCoachOrTeacher = true;
5525
                        // Remove all teachers from course.
5526
                        $removeAllTeachersFromCourse = false;
5527
                    }
5528
                }
5529
5530
                foreach ($courses as $course) {
5531
                    $courseArray = bracketsToArray($course);
5532
                    $course_code = $courseArray[0];
5533
5534
                    if (CourseManager::course_exists($course_code)) {
5535
                        $courseInfo = api_get_course_info($course_code);
5536
                        $courseId = $courseInfo['real_id'];
5537
5538
                        // Adding the course to a session.
5539
                        $sql = "INSERT IGNORE INTO $tbl_session_course
5540
                                SET c_id = '$courseId', session_id='$session_id'";
5541
                        Database::query($sql);
5542
5543
                        self::installCourse($session_id, $courseInfo['real_id']);
5544
5545
                        if ($debug) {
5546
                            $logger->addInfo("Adding course '$course_code' to session #$session_id");
5547
                        }
5548
5549
                        $course_counter++;
5550
                        $course_coaches = isset($courseArray[1]) ? $courseArray[1] : null;
5551
                        $course_users = isset($courseArray[2]) ? $courseArray[2] : null;
5552
                        $course_users = explode(',', $course_users);
5553
                        $course_coaches = explode(',', $course_coaches);
5554
5555
                        // Checking if the flag is set TeachersWillBeAddedAsCoachInAllCourseSessions (course_edit.php)
5556
                        $addTeachersToSession = true;
5557
5558
                        if (array_key_exists('add_teachers_to_sessions_courses', $courseInfo)) {
5559
                            $addTeachersToSession = $courseInfo['add_teachers_to_sessions_courses'];
5560
                        }
5561
5562
                        // If any user provided for a course, use the users array.
5563
                        if (empty($course_users)) {
5564
                            if (!empty($userList)) {
5565
                                self::subscribe_users_to_session_course(
5566
                                    $userList,
5567
                                    $session_id,
5568
                                    $course_code
5569
                                );
5570
                                if ($debug) {
5571
                                    $msg = "Adding student list ".implode(', #', $userList)." to course: '$course_code' and session #$session_id";
5572
                                    $logger->addInfo($msg);
5573
                                }
5574
                            }
5575
                        }
5576
5577
                        // Adding coaches to session course user.
5578
                        if (!empty($course_coaches)) {
5579
                            $savedCoaches = [];
5580
                            // only edit if add_teachers_to_sessions_courses is set.
5581
                            if ($addTeachersToSession) {
5582
                                if ($addOriginalCourseTeachersAsCourseSessionCoaches) {
5583
                                    // Adding course teachers as course session teachers.
5584
                                    $alreadyAddedTeachers = CourseManager::get_teacher_list_from_course_code(
5585
                                        $course_code
5586
                                    );
5587
5588
                                    if (!empty($alreadyAddedTeachers)) {
5589
                                        $teachersToAdd = [];
5590
                                        foreach ($alreadyAddedTeachers as $user) {
5591
                                            $teachersToAdd[] = $user['username'];
5592
                                        }
5593
                                        $course_coaches = array_merge(
5594
                                            $course_coaches,
5595
                                            $teachersToAdd
5596
                                        );
5597
                                    }
5598
                                }
5599
5600
                                foreach ($course_coaches as $course_coach) {
5601
                                    $coach_id = UserManager::get_user_id_from_username($course_coach);
5602
                                    if ($coach_id !== false) {
5603
                                        // Just insert new coaches
5604
                                        self::updateCoaches(
5605
                                            $session_id,
5606
                                            $courseId,
5607
                                            [$coach_id],
5608
                                            false
5609
                                        );
5610
5611
                                        if ($debug) {
5612
                                            $logger->addInfo("Adding course coach: user #$coach_id ($course_coach) to course: '$course_code' and session #$session_id");
5613
                                        }
5614
                                        $savedCoaches[] = $coach_id;
5615
                                    } else {
5616
                                        $error_message .= get_lang('UserDoesNotExist').' : '.$course_coach.$eol;
5617
                                    }
5618
                                }
5619
                            }
5620
5621
                            // Custom courses/session coaches
5622
                            $teacherToAdd = null;
5623
                            // Only one coach is added.
5624
                            if ($onlyAddFirstCoachOrTeacher == true) {
5625
                                if ($debug) {
5626
                                    $logger->addInfo("onlyAddFirstCoachOrTeacher : true");
5627
                                }
5628
5629
                                foreach ($course_coaches as $course_coach) {
5630
                                    $coach_id = UserManager::get_user_id_from_username($course_coach);
5631
                                    if ($coach_id !== false) {
5632
                                        $teacherToAdd = $coach_id;
5633
                                        break;
5634
                                    }
5635
                                }
5636
5637
                                // Un subscribe everyone that's not in the list.
5638
                                $teacherList = CourseManager::get_teacher_list_from_course_code($course_code);
5639
                                if (!empty($teacherList)) {
5640
                                    foreach ($teacherList as $teacher) {
5641
                                        if ($teacherToAdd != $teacher['user_id']) {
5642
                                            $sql = "SELECT * FROM ".Database::get_main_table(TABLE_MAIN_COURSE_USER)."
5643
                                                    WHERE
5644
                                                        user_id = ".$teacher['user_id']." AND
5645
                                                        c_id = '".$courseId."'
5646
                                                    ";
5647
5648
                                            $result = Database::query($sql);
5649
                                            $rows = Database::num_rows($result);
5650
                                            if ($rows > 0) {
5651
                                                $userCourseData = Database::fetch_array($result, 'ASSOC');
5652
                                                if (!empty($userCourseData)) {
5653
                                                    $teacherBackupList[$teacher['user_id']][$course_code] = $userCourseData;
5654
                                                }
5655
                                            }
5656
5657
                                            $sql = "SELECT * FROM ".Database::get_course_table(TABLE_GROUP_USER)."
5658
                                                    WHERE
5659
                                                        user_id = ".$teacher['user_id']." AND
5660
                                                        c_id = '".$courseInfo['real_id']."'
5661
                                                    ";
5662
5663
                                            $result = Database::query($sql);
5664
                                            while ($groupData = Database::fetch_array($result, 'ASSOC')) {
5665
                                                $groupBackup['user'][$teacher['user_id']][$course_code][$groupData['group_id']] = $groupData;
5666
                                            }
5667
5668
                                            $sql = "SELECT * FROM ".Database::get_course_table(TABLE_GROUP_TUTOR)."
5669
                                                    WHERE
5670
                                                        user_id = ".$teacher['user_id']." AND
5671
                                                        c_id = '".$courseInfo['real_id']."'
5672
                                                    ";
5673
5674
                                            $result = Database::query($sql);
5675
                                            while ($groupData = Database::fetch_array($result, 'ASSOC')) {
5676
                                                $groupBackup['tutor'][$teacher['user_id']][$course_code][$groupData['group_id']] = $groupData;
5677
                                            }
5678
5679
                                            CourseManager::unsubscribe_user(
5680
                                                $teacher['user_id'],
5681
                                                $course_code
5682
                                            );
5683
5684
                                            if ($debug) {
5685
                                                $logger->addInfo("Delete user #".$teacher['user_id']." from base course: $course_code");
5686
                                            }
5687
                                        }
5688
                                    }
5689
                                }
5690
5691
                                if (!empty($teacherToAdd)) {
5692
                                    self::updateCoaches(
5693
                                        $session_id,
5694
                                        $courseId,
5695
                                        [$teacherToAdd],
5696
                                        true
5697
                                    );
5698
5699
                                    if ($debug) {
5700
                                        $logger->addInfo("Add coach #$teacherToAdd to course $courseId and session $session_id");
5701
                                    }
5702
5703
                                    $userCourseCategory = '';
5704
                                    if (isset($teacherBackupList[$teacherToAdd]) &&
5705
                                        isset($teacherBackupList[$teacherToAdd][$course_code])
5706
                                    ) {
5707
                                        $courseUserData = $teacherBackupList[$teacherToAdd][$course_code];
5708
                                        $userCourseCategory = $courseUserData['user_course_cat'];
5709
                                    }
5710
5711
                                    CourseManager::subscribeUser(
5712
                                        $teacherToAdd,
5713
                                        $course_code,
5714
                                        COURSEMANAGER,
5715
                                        0,
5716
                                        $userCourseCategory
5717
                                    );
5718
5719
                                    if ($debug) {
5720
                                        $logger->addInfo("Subscribe user #$teacherToAdd as teacher in course $course_code with user userCourseCategory $userCourseCategory");
5721
                                    }
5722
5723
                                    if (isset($groupBackup['user'][$teacherToAdd]) &&
5724
                                        isset($groupBackup['user'][$teacherToAdd][$course_code]) &&
5725
                                        !empty($groupBackup['user'][$teacherToAdd][$course_code])
5726
                                    ) {
5727
                                        foreach ($groupBackup['user'][$teacherToAdd][$course_code] as $data) {
5728
                                            $groupInfo = GroupManager::get_group_properties($data['group_id']);
5729
                                            GroupManager::subscribe_users(
5730
                                                $teacherToAdd,
5731
                                                $groupInfo,
5732
                                                $data['c_id']
5733
                                            );
5734
                                        }
5735
                                    }
5736
5737
                                    if (isset($groupBackup['tutor'][$teacherToAdd]) &&
5738
                                        isset($groupBackup['tutor'][$teacherToAdd][$course_code]) &&
5739
                                        !empty($groupBackup['tutor'][$teacherToAdd][$course_code])
5740
                                    ) {
5741
                                        foreach ($groupBackup['tutor'][$teacherToAdd][$course_code] as $data) {
5742
                                            $groupInfo = GroupManager::get_group_properties($data['group_id']);
5743
                                            GroupManager::subscribe_tutors(
5744
                                                $teacherToAdd,
5745
                                                $groupInfo,
5746
                                                $data['c_id']
5747
                                            );
5748
                                        }
5749
                                    }
5750
                                }
5751
                            }
5752
5753
                            // See BT#6449#note-195
5754
                            // All coaches are added.
5755
                            if ($removeAllTeachersFromCourse) {
5756
                                if ($debug) {
5757
                                    $logger->addInfo("removeAllTeachersFromCourse true");
5758
                                }
5759
                                $teacherToAdd = null;
5760
                                foreach ($course_coaches as $course_coach) {
5761
                                    $coach_id = UserManager::get_user_id_from_username(
5762
                                        $course_coach
5763
                                    );
5764
                                    if ($coach_id !== false) {
5765
                                        $teacherToAdd[] = $coach_id;
5766
                                    }
5767
                                }
5768
5769
                                if (!empty($teacherToAdd)) {
5770
                                    // Deleting all course teachers and adding the only coach as teacher.
5771
                                    $teacherList = CourseManager::get_teacher_list_from_course_code($course_code);
5772
5773
                                    if (!empty($teacherList)) {
5774
                                        foreach ($teacherList as $teacher) {
5775
                                            if (!in_array($teacher['user_id'], $teacherToAdd)) {
5776
                                                $sql = "SELECT * FROM ".Database::get_main_table(TABLE_MAIN_COURSE_USER)."
5777
                                                        WHERE
5778
                                                            user_id = ".$teacher['user_id']." AND
5779
                                                            c_id = '".$courseId."'
5780
                                                        ";
5781
5782
                                                $result = Database::query($sql);
5783
                                                $rows = Database::num_rows($result);
5784
                                                if ($rows > 0) {
5785
                                                    $userCourseData = Database::fetch_array($result, 'ASSOC');
5786
                                                    if (!empty($userCourseData)) {
5787
                                                        $teacherBackupList[$teacher['user_id']][$course_code] = $userCourseData;
5788
                                                    }
5789
                                                }
5790
5791
                                                $sql = "SELECT * FROM ".Database::get_course_table(TABLE_GROUP_USER)."
5792
                                                        WHERE
5793
                                                            user_id = ".$teacher['user_id']." AND
5794
                                                            c_id = '".$courseInfo['real_id']."'
5795
                                                        ";
5796
5797
                                                $result = Database::query($sql);
5798
                                                while ($groupData = Database::fetch_array($result, 'ASSOC')) {
5799
                                                    $groupBackup['user'][$teacher['user_id']][$course_code][$groupData['group_id']] = $groupData;
5800
                                                }
5801
5802
                                                $sql = "SELECT * FROM ".Database::get_course_table(TABLE_GROUP_TUTOR)."
5803
                                                        WHERE
5804
                                                            user_id = ".$teacher['user_id']." AND
5805
                                                            c_id = '".$courseInfo['real_id']."'
5806
                                                        ";
5807
5808
                                                $result = Database::query($sql);
5809
                                                while ($groupData = Database::fetch_array($result, 'ASSOC')) {
5810
                                                    $groupBackup['tutor'][$teacher['user_id']][$course_code][$groupData['group_id']] = $groupData;
5811
                                                }
5812
5813
                                                CourseManager::unsubscribe_user(
5814
                                                    $teacher['user_id'],
5815
                                                    $course_code
5816
                                                );
5817
5818
                                                if ($debug) {
5819
                                                    $logger->addInfo("Delete user #".$teacher['user_id']." from base course: $course_code");
5820
                                                }
5821
                                            }
5822
                                        }
5823
                                    }
5824
5825
                                    foreach ($teacherToAdd as $teacherId) {
5826
                                        $userCourseCategory = '';
5827
                                        if (isset($teacherBackupList[$teacherId]) &&
5828
                                            isset($teacherBackupList[$teacherId][$course_code])
5829
                                        ) {
5830
                                            $courseUserData = $teacherBackupList[$teacherId][$course_code];
5831
                                            $userCourseCategory = $courseUserData['user_course_cat'];
5832
                                        }
5833
5834
                                        CourseManager::subscribeUser(
5835
                                            $teacherId,
5836
                                            $course_code,
5837
                                            COURSEMANAGER,
5838
                                            0,
5839
                                            $userCourseCategory
5840
                                        );
5841
5842
                                        if ($debug) {
5843
                                            $logger->addInfo("Add user as teacher #".$teacherId." in base course: $course_code with userCourseCategory: $userCourseCategory");
5844
                                        }
5845
5846
                                        if (isset($groupBackup['user'][$teacherId]) &&
5847
                                            isset($groupBackup['user'][$teacherId][$course_code]) &&
5848
                                            !empty($groupBackup['user'][$teacherId][$course_code])
5849
                                        ) {
5850
                                            foreach ($groupBackup['user'][$teacherId][$course_code] as $data) {
5851
                                                $groupInfo = GroupManager::get_group_properties($data['group_id']);
5852
                                                GroupManager::subscribe_users(
5853
                                                    $teacherId,
5854
                                                    $groupInfo,
5855
                                                    $data['c_id']
5856
                                                );
5857
                                            }
5858
                                        }
5859
5860
                                        if (isset($groupBackup['tutor'][$teacherId]) &&
5861
                                            isset($groupBackup['tutor'][$teacherId][$course_code]) &&
5862
                                            !empty($groupBackup['tutor'][$teacherId][$course_code])
5863
                                        ) {
5864
                                            foreach ($groupBackup['tutor'][$teacherId][$course_code] as $data) {
5865
                                                $groupInfo = GroupManager::get_group_properties($data['group_id']);
5866
                                                GroupManager::subscribe_tutors(
5867
                                                    $teacherId,
5868
                                                    $groupInfo,
5869
                                                    $data['c_id']
5870
                                                );
5871
                                            }
5872
                                        }
5873
                                    }
5874
                                }
5875
                            }
5876
5877
                            // Continue default behaviour.
5878
                            if ($onlyAddFirstCoachOrTeacher == false) {
5879
                                // Checking one more time see BT#6449#note-149
5880
                                $coaches = self::getCoachesByCourseSession($session_id, $courseId);
5881
                                // Update coaches if only there's 1 course see BT#6449#note-189
5882
                                if (empty($coaches) || count($courses) == 1) {
5883
                                    foreach ($course_coaches as $course_coach) {
5884
                                        $course_coach = trim($course_coach);
5885
                                        $coach_id = UserManager::get_user_id_from_username($course_coach);
5886
                                        if ($coach_id !== false) {
5887
                                            // Just insert new coaches
5888
                                            self::updateCoaches(
5889
                                                $session_id,
5890
                                                $courseId,
5891
                                                [$coach_id],
5892
                                                false
5893
                                            );
5894
5895
                                            if ($debug) {
5896
                                                $logger->addInfo("Sessions - Adding course coach: user #$coach_id ($course_coach) to course: '$course_code' and session #$session_id");
5897
                                            }
5898
                                            $savedCoaches[] = $coach_id;
5899
                                        } else {
5900
                                            $error_message .= get_lang('UserDoesNotExist').' : '.$course_coach.$eol;
5901
                                        }
5902
                                    }
5903
                                }
5904
                            }
5905
                        }
5906
5907
                        // Adding Students, updating relationship "Session - Course - User".
5908
                        $course_users = array_filter($course_users);
5909
                        if (!empty($course_users)) {
5910
                            foreach ($course_users as $user) {
5911
                                $user_id = UserManager::get_user_id_from_username($user);
5912
5913
                                if ($user_id !== false) {
5914
                                    self::subscribe_users_to_session_course(
5915
                                        [$user_id],
5916
                                        $session_id,
5917
                                        $course_code
5918
                                    );
5919
                                    if ($debug) {
5920
                                        $logger->addInfo("Adding student: user #$user_id ($user) to course: '$course_code' and session #$session_id");
5921
                                    }
5922
                                } else {
5923
                                    $error_message .= get_lang('UserDoesNotExist').': '.$user.$eol;
5924
                                }
5925
                            }
5926
                        }
5927
                        $inserted_in_course[$course_code] = $courseInfo['title'];
5928
                    }
5929
                }
5930
                $access_url_id = api_get_current_access_url_id();
5931
                UrlManager::add_session_to_url($session_id, $access_url_id);
5932
                $sql = "UPDATE $tbl_session SET nbr_users = '$user_counter', nbr_courses = '$course_counter'
5933
                        WHERE id = '$session_id'";
5934
                Database::query($sql);
5935
5936
                self::addClassesByName($session_id, $classes, false);
5937
5938
                if ($debug) {
5939
                    $logger->addInfo("End process session #$session_id -------------------- ");
5940
                }
5941
            }
5942
5943
            if (!empty($report)) {
5944
                if ($debug) {
5945
                    $logger->addInfo("--Summary--");
5946
                    foreach ($report as $line) {
5947
                        $logger->addInfo($line);
5948
                    }
5949
                }
5950
            }
5951
        }
5952
5953
        return [
5954
            'error_message' => $error_message,
5955
            'session_counter' => $session_counter,
5956
            'session_list' => $sessionList,
5957
        ];
5958
    }
5959
5960
    /**
5961
     * @param int $sessionId
5962
     * @param int $courseId
5963
     *
5964
     * @return array
5965
     */
5966
    public static function getCoachesByCourseSession($sessionId, $courseId)
5967
    {
5968
        $table = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
5969
        $sessionId = (int) $sessionId;
5970
        $courseId = (int) $courseId;
5971
5972
        $sql = "SELECT user_id FROM $table
5973
                WHERE
5974
                    session_id = '$sessionId' AND
5975
                    c_id = '$courseId' AND
5976
                    status = 2";
5977
        $result = Database::query($sql);
5978
5979
        $coaches = [];
5980
        if (Database::num_rows($result) > 0) {
5981
            while ($row = Database::fetch_array($result)) {
5982
                $coaches[] = $row['user_id'];
5983
            }
5984
        }
5985
5986
        return $coaches;
5987
    }
5988
5989
    /**
5990
     * @param int    $sessionId
5991
     * @param int    $courseId
5992
     * @param string $separator
5993
     *
5994
     * @return string
5995
     */
5996
    public static function getCoachesByCourseSessionToString(
5997
        $sessionId,
5998
        $courseId,
5999
        $separator = ''
6000
    ) {
6001
        $coaches = self::getCoachesByCourseSession($sessionId, $courseId);
6002
        $list = [];
6003
        if (!empty($coaches)) {
6004
            foreach ($coaches as $coachId) {
6005
                $userInfo = api_get_user_info($coachId);
6006
                if ($userInfo) {
6007
                    $list[] = $userInfo['complete_name'];
6008
                }
6009
            }
6010
        }
6011
6012
        $separator = empty($separator) ? CourseManager::USER_SEPARATOR : $separator;
6013
6014
        return array_to_string($list, $separator);
6015
    }
6016
6017
    /**
6018
     * Get all coaches added in the session - course relationship.
6019
     *
6020
     * @param int $sessionId
6021
     *
6022
     * @return array
6023
     */
6024
    public static function getCoachesBySession($sessionId)
6025
    {
6026
        $table = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
6027
        $sessionId = intval($sessionId);
6028
6029
        $sql = "SELECT DISTINCT user_id
6030
                FROM $table
6031
                WHERE session_id = '$sessionId' AND status = 2";
6032
        $result = Database::query($sql);
6033
6034
        $coaches = [];
6035
        if (Database::num_rows($result) > 0) {
6036
            while ($row = Database::fetch_array($result)) {
6037
                $coaches[] = $row['user_id'];
6038
            }
6039
        }
6040
6041
        return $coaches;
6042
    }
6043
6044
    /**
6045
     * @param int $userId
6046
     *
6047
     * @return array
6048
     */
6049
    public static function getAllCoursesFromAllSessionFromDrh($userId)
6050
    {
6051
        $sessions = self::get_sessions_followed_by_drh($userId);
6052
        $coursesFromSession = [];
6053
        if (!empty($sessions)) {
6054
            foreach ($sessions as $session) {
6055
                $courseList = self::get_course_list_by_session_id($session['id']);
6056
                foreach ($courseList as $course) {
6057
                    $coursesFromSession[] = $course['code'];
6058
                }
6059
            }
6060
        }
6061
6062
        return $coursesFromSession;
6063
    }
6064
6065
    /**
6066
     * getAllCoursesFromAllSessions.
6067
     *
6068
     * @return array
6069
     */
6070
    public static function getAllCoursesFromAllSessions()
6071
    {
6072
        $sessions = self::get_sessions_list();
6073
        $coursesFromSession = [];
6074
        if (!empty($sessions)) {
6075
            foreach ($sessions as $session) {
6076
                $courseList = self::get_course_list_by_session_id($session['id']);
6077
                foreach ($courseList as $course) {
6078
                    $coursesFromSession[$course['code'].':'.$session['id']] = $course['visual_code'].' - '.$course['title'].' ('.$session['name'].')';
6079
                }
6080
            }
6081
        }
6082
6083
        return $coursesFromSession;
6084
    }
6085
6086
    /**
6087
     * Return user id list or count of users depending of the $getCount parameter.
6088
     *
6089
     * @param string $status
6090
     * @param int    $userId
6091
     * @param bool   $getCount
6092
     * @param int    $from
6093
     * @param int    $numberItems
6094
     * @param int    $column
6095
     * @param string $direction
6096
     * @param string $keyword
6097
     * @param string $active
6098
     * @param string $lastConnectionDate
6099
     * @param array  $sessionIdList
6100
     * @param array  $studentIdList
6101
     * @param int    $filterByStatus
6102
     *
6103
     * @return array|int
6104
     */
6105
    public static function getAllUsersFromCoursesFromAllSessionFromStatus(
6106
        $status,
6107
        $userId,
6108
        $getCount = false,
6109
        $from = null,
6110
        $numberItems = null,
6111
        $column = 1,
6112
        $direction = 'asc',
6113
        $keyword = null,
6114
        $active = null,
6115
        $lastConnectionDate = null,
6116
        $sessionIdList = [],
6117
        $studentIdList = [],
6118
        $filterByStatus = null
6119
    ) {
6120
        $filterByStatus = (int) $filterByStatus;
6121
        $userId = (int) $userId;
6122
6123
        $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
6124
        $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
6125
        $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
6126
        $tbl_course_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
6127
        $tbl_user_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
6128
        $tbl_course_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
6129
        $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
6130
        $tbl_session_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
6131
6132
        $direction = in_array(strtolower($direction), ['asc', 'desc']) ? $direction : 'asc';
6133
        $column = Database::escape_string($column);
6134
6135
        $urlId = api_get_current_access_url_id();
6136
6137
        $sessionConditions = '';
6138
        $courseConditions = '';
6139
        $userConditions = '';
6140
6141
        if (isset($active)) {
6142
            $active = (int) $active;
6143
            $userConditions .= " AND active = $active";
6144
        }
6145
6146
        $courseList = CourseManager::get_courses_followed_by_drh($userId, DRH);
6147
        if (!empty($courseList)) {
6148
            $courseIdList = array_column($courseList, 'id');
6149
            $courseConditions = ' AND c.id IN ("'.implode('","', $courseIdList).'")';
6150
        }
6151
6152
        $userConditionsFromDrh = '';
6153
6154
        // Classic DRH
6155
        if (empty($studentIdList)) {
6156
            $studentListSql = UserManager::get_users_followed_by_drh(
6157
                $userId,
6158
                $filterByStatus,
6159
                true,
6160
                false
6161
            );
6162
            if (!empty($studentListSql)) {
6163
                $studentIdList = array_keys($studentListSql);
6164
                $studentListSql = "'".implode("','", $studentIdList)."'";
6165
            }
6166
        } else {
6167
            $studentIdList = array_map('intval', $studentIdList);
6168
            $studentListSql = "'".implode("','", $studentIdList)."'";
6169
        }
6170
        if (!empty($studentListSql)) {
6171
            $userConditionsFromDrh = " AND u.user_id IN ($studentListSql) ";
6172
        }
6173
6174
        switch ($status) {
6175
            case 'admin':
6176
            case 'drh':
6177
                break;
6178
            case 'drh_all':
6179
                // Show all by DRH
6180
                if (empty($sessionIdList)) {
6181
                    $sessionListFollowed = self::get_sessions_followed_by_drh(
6182
                        $userId,
6183
                        null,
6184
                        null,
6185
                        false,
6186
                        true
6187
                    );
6188
6189
                    if (!empty($sessionListFollowed)) {
6190
                        $sessionIdList = array_column($sessionListFollowed, 'id');
6191
                    }
6192
                }
6193
6194
                if (!empty($sessionIdList)) {
6195
                    $sessionIdList = array_map('intval', $sessionIdList);
6196
                    $sessionsListSql = "'".implode("','", $sessionIdList)."'";
6197
                    $sessionConditions = " AND s.id IN ($sessionsListSql) ";
6198
                }
6199
6200
                break;
6201
            case 'teacher':
6202
            case 'session_admin':
6203
                $sessionConditions = " AND s.id_coach = $userId ";
6204
                $userConditionsFromDrh = '';
6205
                break;
6206
        }
6207
6208
        $select = 'SELECT DISTINCT u.* ';
6209
        $masterSelect = 'SELECT DISTINCT user_id FROM ';
6210
6211
        if ($getCount) {
6212
            $select = 'SELECT DISTINCT u.user_id ';
6213
            $masterSelect = 'SELECT COUNT(DISTINCT(user_id)) as count FROM ';
6214
        }
6215
6216
        if (!empty($filterByStatus)) {
6217
            $userConditions .= " AND u.status = $filterByStatus";
6218
        }
6219
6220
        if (!empty($lastConnectionDate)) {
6221
            $lastConnectionDate = Database::escape_string($lastConnectionDate);
6222
            $userConditions .= " AND u.last_login <= '$lastConnectionDate' ";
6223
        }
6224
6225
        if (!empty($keyword)) {
6226
            $keyword = Database::escape_string($keyword);
6227
            $userConditions .= " AND (
6228
                u.username LIKE '%$keyword%' OR
6229
                u.firstname LIKE '%$keyword%' OR
6230
                u.lastname LIKE '%$keyword%' OR
6231
                u.official_code LIKE '%$keyword%' OR
6232
                u.email LIKE '%$keyword%'
6233
            )";
6234
        }
6235
6236
        $where = " WHERE
6237
                   access_url_id = $urlId
6238
                   $userConditions
6239
        ";
6240
6241
        $userUnion = '';
6242
        if (!empty($userConditionsFromDrh)) {
6243
            $userUnion = "
6244
            UNION (
6245
                $select
6246
                FROM $tbl_user u
6247
                INNER JOIN $tbl_user_rel_access_url url ON (url.user_id = u.id)
6248
                $where
6249
                $userConditionsFromDrh
6250
            )";
6251
        }
6252
6253
        $sql = "$masterSelect (
6254
                ($select
6255
                    FROM $tbl_session s
6256
                    INNER JOIN $tbl_session_rel_access_url url ON (url.session_id = s.id)
6257
                    INNER JOIN $tbl_session_rel_course_rel_user su ON (s.id = su.session_id)
6258
                    INNER JOIN $tbl_user u ON (u.user_id = su.user_id)
6259
                    $where
6260
                    $sessionConditions
6261
                    $userConditionsFromDrh
6262
                ) UNION (
6263
                    $select
6264
                    FROM $tbl_course c
6265
                    INNER JOIN $tbl_course_rel_access_url url ON (url.c_id = c.id)
6266
                    INNER JOIN $tbl_course_user cu ON (cu.c_id = c.id)
6267
                    INNER JOIN $tbl_user u ON (u.user_id = cu.user_id)
6268
                    $where
6269
                    $courseConditions
6270
                    $userConditionsFromDrh
6271
                ) $userUnion
6272
                ) as t1
6273
                ";
6274
6275
        if ($getCount) {
6276
            $result = Database::query($sql);
6277
6278
            $count = 0;
6279
            if (Database::num_rows($result)) {
6280
                $rows = Database::fetch_array($result);
6281
                $count = $rows['count'];
6282
            }
6283
6284
            return $count;
6285
        }
6286
6287
        if (!empty($column) && !empty($direction)) {
6288
            $column = str_replace('u.', '', $column);
6289
            $sql .= " ORDER BY $column $direction ";
6290
        }
6291
6292
        $limitCondition = '';
6293
        if (isset($from) && isset($numberItems)) {
6294
            $from = (int) $from;
6295
            $numberItems = (int) $numberItems;
6296
            $limitCondition = "LIMIT $from, $numberItems";
6297
        }
6298
6299
        $sql .= $limitCondition;
6300
        $result = Database::query($sql);
6301
6302
        return Database::store_result($result);
6303
    }
6304
6305
    /**
6306
     * @param int   $sessionId
6307
     * @param int   $courseId
6308
     * @param array $coachList
6309
     * @param bool  $deleteCoachesNotInList
6310
     */
6311
    public static function updateCoaches(
6312
        $sessionId,
6313
        $courseId,
6314
        $coachList,
6315
        $deleteCoachesNotInList = false
6316
    ) {
6317
        $currentCoaches = self::getCoachesByCourseSession($sessionId, $courseId);
6318
6319
        if (!empty($coachList)) {
6320
            foreach ($coachList as $userId) {
6321
                self::set_coach_to_course_session($userId, $sessionId, $courseId);
6322
            }
6323
        }
6324
6325
        if ($deleteCoachesNotInList) {
6326
            if (!empty($coachList)) {
6327
                $coachesToDelete = array_diff($currentCoaches, $coachList);
6328
            } else {
6329
                $coachesToDelete = $currentCoaches;
6330
            }
6331
6332
            if (!empty($coachesToDelete)) {
6333
                foreach ($coachesToDelete as $userId) {
6334
                    self::set_coach_to_course_session(
6335
                        $userId,
6336
                        $sessionId,
6337
                        $courseId,
6338
                        true
6339
                    );
6340
                }
6341
            }
6342
        }
6343
    }
6344
6345
    /**
6346
     * @param array $sessions
6347
     * @param array $sessionsDestination
6348
     *
6349
     * @return array
6350
     */
6351
    public static function copyStudentsFromSession($sessions, $sessionsDestination)
6352
    {
6353
        $messages = [];
6354
        if (!empty($sessions)) {
6355
            foreach ($sessions as $sessionId) {
6356
                $sessionInfo = self::fetch($sessionId);
6357
                $userList = self::get_users_by_session($sessionId, 0);
6358
                if (!empty($userList)) {
6359
                    $newUserList = [];
6360
                    $userToString = null;
6361
                    foreach ($userList as $userInfo) {
6362
                        $newUserList[] = $userInfo['user_id'];
6363
                        $userToString .= $userInfo['firstname'].' '.$userInfo['lastname'].'<br />';
6364
                    }
6365
6366
                    if (!empty($sessionsDestination)) {
6367
                        foreach ($sessionsDestination as $sessionDestinationId) {
6368
                            $sessionDestinationInfo = self::fetch($sessionDestinationId);
6369
                            $messages[] = Display::return_message(
6370
                                sprintf(
6371
                                    get_lang(
6372
                                        'AddingStudentsFromSessionXToSessionY'
6373
                                    ),
6374
                                    $sessionInfo['name'],
6375
                                    $sessionDestinationInfo['name']
6376
                                ),
6377
                                'info',
6378
                                false
6379
                            );
6380
                            if ($sessionId == $sessionDestinationId) {
6381
                                $messages[] = Display::return_message(
6382
                                    sprintf(
6383
                                        get_lang('SessionXSkipped'),
6384
                                        $sessionDestinationId
6385
                                    ),
6386
                                    'warning',
6387
                                    false
6388
                                );
6389
                                continue;
6390
                            }
6391
                            $messages[] = Display::return_message(get_lang('StudentList').'<br />'.$userToString, 'info', false);
6392
                            self::subscribeUsersToSession(
6393
                                $sessionDestinationId,
6394
                                $newUserList,
6395
                                SESSION_VISIBLE_READ_ONLY,
6396
                                false
6397
                            );
6398
                        }
6399
                    } else {
6400
                        $messages[] = Display::return_message(get_lang('NoDestinationSessionProvided'), 'warning');
6401
                    }
6402
                } else {
6403
                    $messages[] = Display::return_message(
6404
                        get_lang('NoStudentsFoundForSession').' #'.$sessionInfo['name'],
6405
                        'warning'
6406
                    );
6407
                }
6408
            }
6409
        } else {
6410
            $messages[] = Display::return_message(get_lang('NoData'), 'warning');
6411
        }
6412
6413
        return $messages;
6414
    }
6415
6416
    /**
6417
     * Assign coaches of a session(s) as teachers to a given course (or courses).
6418
     *
6419
     * @param array A list of session IDs
6420
     * @param array A list of course IDs
6421
     *
6422
     * @return string
6423
     */
6424
    public static function copyCoachesFromSessionToCourse($sessions, $courses)
6425
    {
6426
        $coachesPerSession = [];
6427
        foreach ($sessions as $sessionId) {
6428
            $coaches = self::getCoachesBySession($sessionId);
6429
            $coachesPerSession[$sessionId] = $coaches;
6430
        }
6431
6432
        $result = [];
6433
6434
        if (!empty($courses)) {
6435
            foreach ($courses as $courseId) {
6436
                $courseInfo = api_get_course_info_by_id($courseId);
6437
                foreach ($coachesPerSession as $sessionId => $coachList) {
6438
                    CourseManager::updateTeachers(
6439
                        $courseInfo,
6440
                        $coachList,
6441
                        false,
6442
                        false,
6443
                        false
6444
                    );
6445
                    $result[$courseInfo['code']][$sessionId] = $coachList;
6446
                }
6447
            }
6448
        }
6449
        $sessionUrl = api_get_path(WEB_CODE_PATH).'session/resume_session.php?id_session=';
6450
        $htmlResult = null;
6451
6452
        if (!empty($result)) {
6453
            foreach ($result as $courseCode => $data) {
6454
                $url = api_get_course_url($courseCode);
6455
                $htmlResult .= sprintf(
6456
                    get_lang('CoachesSubscribedAsATeacherInCourseX'),
6457
                    Display::url($courseCode, $url, ['target' => '_blank'])
6458
                );
6459
                foreach ($data as $sessionId => $coachList) {
6460
                    $sessionInfo = self::fetch($sessionId);
6461
                    $htmlResult .= '<br />';
6462
                    $htmlResult .= Display::url(
6463
                        get_lang('Session').': '.$sessionInfo['name'].' <br />',
6464
                        $sessionUrl.$sessionId,
6465
                        ['target' => '_blank']
6466
                    );
6467
                    $teacherList = [];
6468
                    foreach ($coachList as $coachId) {
6469
                        $userInfo = api_get_user_info($coachId);
6470
                        $teacherList[] = $userInfo['complete_name'];
6471
                    }
6472
                    if (!empty($teacherList)) {
6473
                        $htmlResult .= implode(', ', $teacherList);
6474
                    } else {
6475
                        $htmlResult .= get_lang('NothingToAdd');
6476
                    }
6477
                }
6478
                $htmlResult .= '<br />';
6479
            }
6480
            $htmlResult = Display::return_message($htmlResult, 'normal', false);
6481
        }
6482
6483
        return $htmlResult;
6484
    }
6485
6486
    /**
6487
     * @param string $keyword
6488
     * @param string $active
6489
     * @param string $lastConnectionDate
6490
     * @param array  $sessionIdList
6491
     * @param array  $studentIdList
6492
     * @param int    $filterUserStatus   STUDENT|COURSEMANAGER constants
6493
     *
6494
     * @return array|int
6495
     */
6496
    public static function getCountUserTracking(
6497
        $keyword = null,
6498
        $active = null,
6499
        $lastConnectionDate = null,
6500
        $sessionIdList = [],
6501
        $studentIdList = [],
6502
        $filterUserStatus = null
6503
    ) {
6504
        $userId = api_get_user_id();
6505
        $drhLoaded = false;
6506
6507
        if (api_is_drh()) {
6508
            if (api_drh_can_access_all_session_content()) {
6509
                $count = self::getAllUsersFromCoursesFromAllSessionFromStatus(
6510
                    'drh_all',
6511
                    $userId,
6512
                    true,
6513
                    null,
6514
                    null,
6515
                    null,
6516
                    null,
6517
                    $keyword,
6518
                    $active,
6519
                    $lastConnectionDate,
6520
                    $sessionIdList,
6521
                    $studentIdList,
6522
                    $filterUserStatus
6523
                );
6524
                $drhLoaded = true;
6525
            }
6526
        }
6527
6528
        if ($drhLoaded == false) {
6529
            $count = UserManager::getUsersFollowedByUser(
6530
                $userId,
6531
                $filterUserStatus,
6532
                false,
6533
                false,
6534
                true,
6535
                null,
6536
                null,
6537
                null,
6538
                null,
6539
                $active,
6540
                $lastConnectionDate,
6541
                api_is_student_boss() ? STUDENT_BOSS : COURSEMANAGER,
6542
                $keyword
6543
            );
6544
        }
6545
6546
        return $count;
6547
    }
6548
6549
    /**
6550
     * Get teachers followed by a user.
6551
     *
6552
     * @param int    $userId
6553
     * @param int    $active
6554
     * @param string $lastConnectionDate
6555
     * @param bool   $getCount
6556
     * @param array  $sessionIdList
6557
     *
6558
     * @return array|int
6559
     */
6560
    public static function getTeacherTracking(
6561
        $userId,
6562
        $active = 1,
6563
        $lastConnectionDate = null,
6564
        $getCount = false,
6565
        $sessionIdList = []
6566
    ) {
6567
        $teacherListId = [];
6568
        if (api_is_drh() || api_is_platform_admin()) {
6569
            // Followed teachers by drh
6570
            if (api_drh_can_access_all_session_content()) {
6571
                if (empty($sessionIdList)) {
6572
                    $sessions = self::get_sessions_followed_by_drh($userId);
6573
                    $sessionIdList = [];
6574
                    foreach ($sessions as $session) {
6575
                        $sessionIdList[] = $session['id'];
6576
                    }
6577
                }
6578
6579
                $sessionIdList = array_map('intval', $sessionIdList);
6580
                $sessionToString = implode("', '", $sessionIdList);
6581
6582
                $course = Database::get_main_table(TABLE_MAIN_COURSE);
6583
                $sessionCourse = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
6584
                $courseUser = Database::get_main_table(TABLE_MAIN_COURSE_USER);
6585
6586
                // Select the teachers.
6587
                $sql = "SELECT DISTINCT(cu.user_id)
6588
                        FROM $course c
6589
                        INNER JOIN $sessionCourse src
6590
                        ON c.id = src.c_id
6591
                        INNER JOIN $courseUser cu
6592
                        ON (cu.c_id = c.id)
6593
		                WHERE src.session_id IN ('$sessionToString') AND cu.status = 1";
6594
                $result = Database::query($sql);
6595
                while ($row = Database::fetch_array($result, 'ASSOC')) {
6596
                    $teacherListId[$row['user_id']] = $row['user_id'];
6597
                }
6598
            } else {
6599
                $teacherResult = UserManager::get_users_followed_by_drh($userId, COURSEMANAGER);
6600
                foreach ($teacherResult as $userInfo) {
6601
                    $teacherListId[] = $userInfo['user_id'];
6602
                }
6603
            }
6604
        }
6605
6606
        if (!empty($teacherListId)) {
6607
            $tableUser = Database::get_main_table(TABLE_MAIN_USER);
6608
6609
            $select = "SELECT DISTINCT u.* ";
6610
            if ($getCount) {
6611
                $select = "SELECT count(DISTINCT(u.user_id)) as count";
6612
            }
6613
6614
            $sql = "$select FROM $tableUser u";
6615
6616
            if (!empty($lastConnectionDate)) {
6617
                $tableLogin = Database::get_main_table(TABLE_STATISTIC_TRACK_E_LOGIN);
6618
                //$sql .= " INNER JOIN $tableLogin l ON (l.login_user_id = u.user_id) ";
6619
            }
6620
            $active = intval($active);
6621
            $teacherListId = implode("','", $teacherListId);
6622
            $where = " WHERE u.active = $active AND u.user_id IN ('$teacherListId') ";
6623
6624
            if (!empty($lastConnectionDate)) {
6625
                $lastConnectionDate = Database::escape_string($lastConnectionDate);
6626
                //$where .= " AND l.login_date <= '$lastConnectionDate' ";
6627
            }
6628
6629
            $sql .= $where;
6630
            $result = Database::query($sql);
6631
            if (Database::num_rows($result)) {
6632
                if ($getCount) {
6633
                    $row = Database::fetch_array($result);
6634
6635
                    return $row['count'];
6636
                } else {
6637
                    return Database::store_result($result, 'ASSOC');
6638
                }
6639
            }
6640
        }
6641
6642
        return 0;
6643
    }
6644
6645
    /**
6646
     * Get the list of course tools that have to be dealt with in case of
6647
     * registering any course to a session.
6648
     *
6649
     * @return array The list of tools to be dealt with (literal names)
6650
     */
6651
    public static function getCourseToolToBeManaged()
6652
    {
6653
        return [
6654
            'courseDescription',
6655
            'courseIntroduction',
6656
        ];
6657
    }
6658
6659
    /**
6660
     * Calls the methods bound to each tool when a course is registered into a session.
6661
     *
6662
     * @param int $sessionId
6663
     * @param int $courseId
6664
     *
6665
     * @return bool
6666
     */
6667
    public static function installCourse($sessionId, $courseId)
6668
    {
6669
        return true;
6670
        $toolList = self::getCourseToolToBeManaged();
0 ignored issues
show
Unused Code introduced by
$toolList = self::getCourseToolToBeManaged() is not reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
6671
6672
        foreach ($toolList as $tool) {
6673
            $method = 'add'.$tool;
6674
            if (method_exists(get_class(), $method)) {
6675
                self::$method($sessionId, $courseId);
6676
            }
6677
        }
6678
    }
6679
6680
    /**
6681
     * Calls the methods bound to each tool when a course is unregistered from
6682
     * a session.
6683
     *
6684
     * @param int $sessionId
6685
     * @param int $courseId
6686
     */
6687
    public static function unInstallCourse($sessionId, $courseId)
6688
    {
6689
        return true;
6690
        $toolList = self::getCourseToolToBeManaged();
0 ignored issues
show
Unused Code introduced by
$toolList = self::getCourseToolToBeManaged() is not reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
6691
6692
        foreach ($toolList as $tool) {
6693
            $method = 'remove'.$tool;
6694
            if (method_exists(get_class(), $method)) {
6695
                self::$method($sessionId, $courseId);
6696
            }
6697
        }
6698
    }
6699
6700
    /**
6701
     * @param array $userSessionList        format see self::importSessionDrhCSV()
6702
     * @param bool  $sendEmail
6703
     * @param bool  $removeOldRelationShips
6704
     */
6705
    public static function subscribeDrhToSessionList(
6706
        $userSessionList,
6707
        $sendEmail,
6708
        $removeOldRelationShips
6709
    ) {
6710
        if (!empty($userSessionList)) {
6711
            foreach ($userSessionList as $userId => $data) {
6712
                $sessionList = [];
6713
                foreach ($data['session_list'] as $sessionInfo) {
6714
                    $sessionList[] = $sessionInfo['session_id'];
6715
                }
6716
                $userInfo = $data['user_info'];
6717
                self::subscribeSessionsToDrh(
6718
                    $userInfo,
6719
                    $sessionList,
6720
                    $sendEmail,
6721
                    $removeOldRelationShips
6722
                );
6723
            }
6724
        }
6725
    }
6726
6727
    /**
6728
     * @param array $userSessionList format see self::importSessionDrhCSV()
6729
     *
6730
     * @return string
6731
     */
6732
    public static function checkSubscribeDrhToSessionList($userSessionList)
6733
    {
6734
        $message = null;
6735
        if (!empty($userSessionList)) {
6736
            if (!empty($userSessionList)) {
6737
                foreach ($userSessionList as $userId => $data) {
6738
                    $userInfo = $data['user_info'];
6739
6740
                    $sessionListSubscribed = self::get_sessions_followed_by_drh($userId);
6741
                    if (!empty($sessionListSubscribed)) {
6742
                        $sessionListSubscribed = array_keys($sessionListSubscribed);
6743
                    }
6744
6745
                    $sessionList = [];
6746
                    if (!empty($data['session_list'])) {
6747
                        foreach ($data['session_list'] as $sessionInfo) {
6748
                            if (in_array($sessionInfo['session_id'], $sessionListSubscribed)) {
6749
                                $sessionList[] = $sessionInfo['session_info']['name'];
6750
                            }
6751
                        }
6752
                    }
6753
6754
                    $message .= '<strong>'.get_lang('User').'</strong>: ';
6755
                    $message .= $userInfo['complete_name_with_username'].' <br />';
6756
6757
                    if (!in_array($userInfo['status'], [DRH]) && !api_is_platform_admin_by_id($userInfo['user_id'])) {
6758
                        $message .= get_lang('UserMustHaveTheDrhRole').'<br />';
6759
                        continue;
6760
                    }
6761
6762
                    if (!empty($sessionList)) {
6763
                        $message .= '<strong>'.get_lang('Sessions').':</strong> <br />';
6764
                        $message .= implode(', ', $sessionList).'<br /><br />';
6765
                    } else {
6766
                        $message .= get_lang('NoSessionProvided').' <br /><br />';
6767
                    }
6768
                }
6769
            }
6770
        }
6771
6772
        return $message;
6773
    }
6774
6775
    /**
6776
     * @param string $file
6777
     * @param bool   $sendEmail
6778
     * @param bool   $removeOldRelationShips
6779
     *
6780
     * @return string
6781
     */
6782
    public static function importSessionDrhCSV($file, $sendEmail, $removeOldRelationShips)
6783
    {
6784
        $list = Import::csv_reader($file);
6785
6786
        if (!empty($list)) {
6787
            $userSessionList = [];
6788
            foreach ($list as $data) {
6789
                $sessionInfo = [];
6790
                if (isset($data['SessionId'])) {
6791
                    $sessionInfo = api_get_session_info($data['SessionId']);
6792
                }
6793
6794
                if (isset($data['SessionName']) && empty($sessionInfo)) {
6795
                    $sessionInfo = self::get_session_by_name($data['SessionName']);
6796
                }
6797
6798
                if (empty($sessionInfo)) {
6799
                    $sessionData = isset($data['SessionName']) ? $data['SessionName'] : $data['SessionId'];
6800
                    Display::addFlash(
6801
                        Display::return_message(get_lang('SessionNotFound').' - '.$sessionData, 'warning')
6802
                    );
6803
                    continue;
6804
                }
6805
6806
                $userList = explode(',', $data['Username']);
6807
6808
                foreach ($userList as $username) {
6809
                    $userInfo = api_get_user_info_from_username($username);
6810
6811
                    if (empty($userInfo)) {
6812
                        Display::addFlash(
6813
                            Display::return_message(get_lang('UserDoesNotExist').' - '.$username, 'warning')
6814
                        );
6815
                        continue;
6816
                    }
6817
6818
                    if (!empty($userInfo) && !empty($sessionInfo)) {
6819
                        $userSessionList[$userInfo['user_id']]['session_list'][] = [
6820
                            'session_id' => $sessionInfo['id'],
6821
                            'session_info' => $sessionInfo,
6822
                        ];
6823
                        $userSessionList[$userInfo['user_id']]['user_info'] = $userInfo;
6824
                    }
6825
                }
6826
            }
6827
6828
            self::subscribeDrhToSessionList($userSessionList, $sendEmail, $removeOldRelationShips);
6829
6830
            return self::checkSubscribeDrhToSessionList($userSessionList);
6831
        }
6832
    }
6833
6834
    /**
6835
     * Courses re-ordering in resume_session.php flag see BT#8316.
6836
     */
6837
    public static function orderCourseIsEnabled()
6838
    {
6839
        $sessionCourseOrder = api_get_setting('session_course_ordering');
6840
        if ($sessionCourseOrder === 'true') {
6841
            return true;
6842
        }
6843
6844
        return false;
6845
    }
6846
6847
    /**
6848
     * @param string $direction (up/down)
6849
     * @param int    $sessionId
6850
     * @param int    $courseId
6851
     *
6852
     * @return bool
6853
     */
6854
    public static function move($direction, $sessionId, $courseId)
6855
    {
6856
        if (!self::orderCourseIsEnabled()) {
6857
            return false;
6858
        }
6859
6860
        $sessionId = intval($sessionId);
6861
        $courseId = intval($courseId);
6862
6863
        $table = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
6864
        $courseList = self::get_course_list_by_session_id($sessionId, null, 'position');
6865
6866
        $position = [];
6867
        $count = 0;
6868
        foreach ($courseList as $course) {
6869
            if ($course['position'] == '') {
6870
                $course['position'] = $count;
6871
            }
6872
            $position[$course['code']] = $course['position'];
6873
            // Saving current order.
6874
            $sql = "UPDATE $table SET position = $count
6875
                    WHERE session_id = $sessionId AND c_id = '".$course['real_id']."'";
6876
            Database::query($sql);
6877
            $count++;
6878
        }
6879
6880
        // Loading new positions.
6881
        $courseList = self::get_course_list_by_session_id($sessionId, null, 'position');
6882
6883
        $found = false;
6884
6885
        switch ($direction) {
6886
            case 'up':
6887
                $courseList = array_reverse($courseList);
6888
                break;
6889
            case 'down':
6890
                break;
6891
        }
6892
6893
        foreach ($courseList as $course) {
6894
            if ($found) {
6895
                $nextId = $course['real_id'];
6896
                $nextOrder = $course['position'];
6897
                break;
6898
            }
6899
6900
            if ($courseId == $course['real_id']) {
6901
                $thisCourseCode = $course['real_id'];
6902
                $thisOrder = $course['position'];
6903
                $found = true;
6904
            }
6905
        }
6906
6907
        $sql1 = "UPDATE $table SET position = '".intval($nextOrder)."'
6908
                 WHERE session_id = $sessionId AND c_id =  $thisCourseCode";
6909
        Database::query($sql1);
6910
6911
        $sql2 = "UPDATE $table SET position = '".intval($thisOrder)."'
6912
                 WHERE session_id = $sessionId AND c_id = $nextId";
6913
        Database::query($sql2);
6914
6915
        return true;
6916
    }
6917
6918
    /**
6919
     * @param int $sessionId
6920
     * @param int $courseId
6921
     *
6922
     * @return bool
6923
     */
6924
    public static function moveUp($sessionId, $courseId)
6925
    {
6926
        return self::move('up', $sessionId, $courseId);
6927
    }
6928
6929
    /**
6930
     * @param int    $sessionId
6931
     * @param string $courseCode
6932
     *
6933
     * @return bool
6934
     */
6935
    public static function moveDown($sessionId, $courseCode)
6936
    {
6937
        return self::move('down', $sessionId, $courseCode);
6938
    }
6939
6940
    /**
6941
     * Use the session duration to allow/block user access see BT#8317
6942
     * Needs these DB changes
6943
     * ALTER TABLE session ADD COLUMN duration int;
6944
     * ALTER TABLE session_rel_user ADD COLUMN duration int;.
6945
     */
6946
    public static function durationPerUserIsEnabled()
6947
    {
6948
        return api_get_configuration_value('session_duration_feature');
6949
    }
6950
6951
    /**
6952
     * Returns the number of days the student has left in a session when using
6953
     * sessions durations.
6954
     *
6955
     * @param int $userId
6956
     *
6957
     * @return int
6958
     */
6959
    public static function getDayLeftInSession(array $sessionInfo, $userId)
6960
    {
6961
        $sessionId = $sessionInfo['id'];
6962
        $subscription = self::getUserSession($userId, $sessionId);
6963
        $duration = empty($subscription['duration'])
6964
            ? $sessionInfo['duration']
6965
            : $sessionInfo['duration'] + $subscription['duration'];
6966
6967
        // Get an array with the details of the first access of the student to
6968
        // this session
6969
        $courseAccess = CourseManager::getFirstCourseAccessPerSessionAndUser(
6970
            $sessionId,
6971
            $userId
6972
        );
6973
6974
        $currentTime = time();
6975
6976
        // If no previous access, return false
6977
        if (count($courseAccess) == 0) {
6978
            return $duration;
6979
        }
6980
6981
        $firstAccess = api_strtotime($courseAccess['login_course_date'], 'UTC');
6982
        $endDateInSeconds = $firstAccess + $duration * 24 * 60 * 60;
6983
        $leftDays = round(($endDateInSeconds - $currentTime) / 60 / 60 / 24);
6984
6985
        return $leftDays;
6986
    }
6987
6988
    /**
6989
     * @param int $duration
6990
     * @param int $userId
6991
     * @param int $sessionId
6992
     *
6993
     * @return bool
6994
     */
6995
    public static function editUserSessionDuration($duration, $userId, $sessionId)
6996
    {
6997
        $duration = (int) $duration;
6998
        $userId = (int) $userId;
6999
        $sessionId = (int) $sessionId;
7000
7001
        if (empty($userId) || empty($sessionId)) {
7002
            return false;
7003
        }
7004
7005
        $table = Database::get_main_table(TABLE_MAIN_SESSION_USER);
7006
        $parameters = ['duration' => $duration];
7007
        $where = ['session_id = ? AND user_id = ? ' => [$sessionId, $userId]];
7008
        Database::update($table, $parameters, $where);
7009
7010
        return true;
7011
    }
7012
7013
    /**
7014
     * Gets one row from the session_rel_user table.
7015
     *
7016
     * @param int $userId
7017
     * @param int $sessionId
7018
     *
7019
     * @return array
7020
     */
7021
    public static function getUserSession($userId, $sessionId)
7022
    {
7023
        $userId = (int) $userId;
7024
        $sessionId = (int) $sessionId;
7025
7026
        if (empty($userId) || empty($sessionId)) {
7027
            return false;
7028
        }
7029
7030
        $table = Database::get_main_table(TABLE_MAIN_SESSION_USER);
7031
        $sql = "SELECT * FROM $table
7032
                WHERE session_id = $sessionId AND user_id = $userId";
7033
        $result = Database::query($sql);
7034
        $values = [];
7035
        if (Database::num_rows($result)) {
7036
            $values = Database::fetch_array($result, 'ASSOC');
7037
        }
7038
7039
        return $values;
7040
    }
7041
7042
    /**
7043
     * Check if user is subscribed inside a session as student.
7044
     *
7045
     * @param int $sessionId The session id
7046
     * @param int $userId    The user id
7047
     *
7048
     * @return bool Whether is subscribed
7049
     */
7050
    public static function isUserSubscribedAsStudent($sessionId, $userId)
7051
    {
7052
        $sessionRelUserTable = Database::get_main_table(TABLE_MAIN_SESSION_USER);
7053
        $sessionId = (int) $sessionId;
7054
        $userId = (int) $userId;
7055
7056
        // COUNT(1) actually returns the number of rows from the table (as if
7057
        // counting the results from the first column)
7058
        $sql = "SELECT COUNT(1) AS qty FROM $sessionRelUserTable
7059
                WHERE
7060
                    session_id = $sessionId AND
7061
                    user_id = $userId AND
7062
                    relation_type = 0";
7063
7064
        $result = Database::fetch_assoc(Database::query($sql));
7065
7066
        if (!empty($result) && $result['qty'] > 0) {
7067
            return true;
7068
        }
7069
7070
        return false;
7071
    }
7072
7073
    /**
7074
     * Check if user is subscribed inside a session as a HRM.
7075
     *
7076
     * @param int $sessionId The session id
7077
     * @param int $userId    The user id
7078
     *
7079
     * @return bool Whether is subscribed
7080
     */
7081
    public static function isUserSubscribedAsHRM($sessionId, $userId)
7082
    {
7083
        $sessionRelUserTable = Database::get_main_table(TABLE_MAIN_SESSION_USER);
7084
7085
        $sessionId = (int) $sessionId;
7086
        $userId = (int) $userId;
7087
7088
        // COUNT(1) actually returns the number of rows from the table (as if
7089
        // counting the results from the first column)
7090
        $sql = "SELECT COUNT(1) AS qty FROM $sessionRelUserTable
7091
                WHERE
7092
                    session_id = $sessionId AND
7093
                    user_id = $userId AND
7094
                    relation_type = ".SESSION_RELATION_TYPE_RRHH;
7095
7096
        $result = Database::fetch_assoc(Database::query($sql));
7097
7098
        if (!empty($result) && $result['qty'] > 0) {
7099
            return true;
7100
        }
7101
7102
        return false;
7103
    }
7104
7105
    /**
7106
     * Get the session coached by a user (general coach and course-session coach).
7107
     *
7108
     * @param int  $coachId                       The coach id
7109
     * @param bool $checkSessionRelUserVisibility Check the session visibility
7110
     * @param bool $asPlatformAdmin               The user is a platform admin and we want all sessions
7111
     *
7112
     * @return array The session list
7113
     */
7114
    public static function getSessionsCoachedByUser(
7115
        $coachId,
7116
        $checkSessionRelUserVisibility = false,
7117
        $asPlatformAdmin = false
7118
    ) {
7119
        // Get all sessions where $coachId is the general coach
7120
        $sessions = self::get_sessions_by_general_coach($coachId, $asPlatformAdmin);
7121
        // Get all sessions where $coachId is the course - session coach
7122
        $courseSessionList = self::getCoursesListByCourseCoach($coachId);
7123
        $sessionsByCoach = [];
7124
        if (!empty($courseSessionList)) {
7125
            foreach ($courseSessionList as $userCourseSubscription) {
7126
                $session = $userCourseSubscription->getSession();
7127
                $sessionsByCoach[$session->getId()] = api_get_session_info(
7128
                    $session->getId()
7129
                );
7130
            }
7131
        }
7132
7133
        if (!empty($sessionsByCoach)) {
7134
            $sessions = array_merge($sessions, $sessionsByCoach);
7135
        }
7136
7137
        // Remove repeated sessions
7138
        if (!empty($sessions)) {
7139
            $cleanSessions = [];
7140
            foreach ($sessions as $session) {
7141
                $cleanSessions[$session['id']] = $session;
7142
            }
7143
            $sessions = $cleanSessions;
7144
        }
7145
7146
        if ($checkSessionRelUserVisibility) {
7147
            if (!empty($sessions)) {
7148
                $newSessions = [];
7149
                foreach ($sessions as $session) {
7150
                    $visibility = api_get_session_visibility($session['id']);
7151
                    if ($visibility == SESSION_INVISIBLE) {
7152
                        continue;
7153
                    }
7154
                    $newSessions[] = $session;
7155
                }
7156
                $sessions = $newSessions;
7157
            }
7158
        }
7159
7160
        return $sessions;
7161
    }
7162
7163
    /**
7164
     * Check if the course belongs to the session.
7165
     *
7166
     * @param int    $sessionId  The session id
7167
     * @param string $courseCode The course code
7168
     *
7169
     * @return bool
7170
     */
7171
    public static function sessionHasCourse($sessionId, $courseCode)
7172
    {
7173
        $sessionId = (int) $sessionId;
7174
        $courseCode = Database::escape_string($courseCode);
7175
        $courseTable = Database::get_main_table(TABLE_MAIN_COURSE);
7176
        $sessionRelCourseTable = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
7177
7178
        $sql = "SELECT COUNT(1) AS qty
7179
                FROM $courseTable c
7180
                INNER JOIN $sessionRelCourseTable src
7181
                ON c.id = src.c_id
7182
                WHERE src.session_id = $sessionId
7183
                AND c.code = '$courseCode'  ";
7184
7185
        $result = Database::query($sql);
7186
7187
        if (false !== $result) {
7188
            $data = Database::fetch_assoc($result);
7189
7190
            if ($data['qty'] > 0) {
7191
                return true;
7192
            }
7193
        }
7194
7195
        return false;
7196
    }
7197
7198
    /**
7199
     * Calculate the total user time in the platform.
7200
     *
7201
     * @param int    $userId The user id
7202
     * @param string $from   Optional. From date
7203
     * @param string $until  Optional. Until date
7204
     *
7205
     * @return string The time (hh:mm:ss)
7206
     */
7207
    public static function getTotalUserTimeInPlatform($userId, $from = '', $until = '')
7208
    {
7209
        $userId = (int) $userId;
7210
        $trackLoginTable = Database::get_main_table(TABLE_STATISTIC_TRACK_E_LOGIN);
7211
        $whereConditions = [
7212
            'login_user_id = ? ' => $userId,
7213
        ];
7214
7215
        if (!empty($from) && !empty($until)) {
7216
            $whereConditions["AND (login_date >= '?' "] = $from;
7217
            $whereConditions["AND logout_date <= DATE_ADD('?', INTERVAL 1 DAY)) "] = $until;
7218
        }
7219
7220
        $trackResult = Database::select(
7221
            'SEC_TO_TIME(SUM(UNIX_TIMESTAMP(logout_date) - UNIX_TIMESTAMP(login_date))) as total_time',
7222
            $trackLoginTable,
7223
            [
7224
                'where' => $whereConditions,
7225
            ],
7226
            'first'
7227
        );
7228
7229
        if (false != $trackResult) {
7230
            return $trackResult['total_time'] ? $trackResult['total_time'] : '00:00:00';
7231
        }
7232
7233
        return '00:00:00';
7234
    }
7235
7236
    /**
7237
     * Get the courses list by a course coach.
7238
     *
7239
     * @param int $coachId The coach id
7240
     *
7241
     * @return array (id, user_id, session_id, c_id, visibility, status, legal_agreement)
7242
     */
7243
    public static function getCoursesListByCourseCoach($coachId)
7244
    {
7245
        $entityManager = Database::getManager();
7246
        $scuRepo = $entityManager->getRepository(
7247
            'ChamiloCoreBundle:SessionRelCourseRelUser'
7248
        );
7249
7250
        return $scuRepo->findBy([
7251
            'user' => $coachId,
7252
            'status' => SessionRelCourseRelUser::STATUS_COURSE_COACH,
7253
        ]);
7254
    }
7255
7256
    /**
7257
     * Get the count of user courses in session.
7258
     *
7259
     * @param int $sessionId
7260
     * @param int $courseId
7261
     *
7262
     * @return array
7263
     */
7264
    public static function getTotalUserCoursesInSession($sessionId, $courseId = 0)
7265
    {
7266
        $tableUser = Database::get_main_table(TABLE_MAIN_USER);
7267
        $table = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
7268
7269
        $sessionId = (int) $sessionId;
7270
7271
        if (empty($sessionId)) {
7272
            return [];
7273
        }
7274
7275
        $courseCondition = '';
7276
        if (!empty($courseId)) {
7277
            $courseId = (int) $courseId;
7278
            $courseCondition = "  c_id = $courseId AND ";
7279
        }
7280
7281
        $sql = "SELECT
7282
                    COUNT(u.id) as count,
7283
                    u.id,
7284
                    scu.status status_in_session,
7285
                    u.status user_status
7286
                FROM $table scu
7287
                INNER JOIN $tableUser u
7288
                ON scu.user_id = u.id
7289
                WHERE
7290
                  $courseCondition
7291
                  scu.session_id = ".$sessionId."
7292
                GROUP BY u.id";
7293
7294
        $result = Database::query($sql);
7295
7296
        $list = [];
7297
        while ($data = Database::fetch_assoc($result)) {
7298
            $list[] = $data;
7299
        }
7300
7301
        return $list;
7302
    }
7303
7304
    /**
7305
     * Returns list of a few data from session (name, short description, start
7306
     * date, end date) and the given extra fields if defined based on a
7307
     * session category Id.
7308
     *
7309
     * @param int    $categoryId  The internal ID of the session category
7310
     * @param string $target      Value to search for in the session field values
7311
     * @param array  $extraFields A list of fields to be scanned and returned
7312
     *
7313
     * @return mixed
7314
     */
7315
    public static function getShortSessionListAndExtraByCategory(
7316
        $categoryId,
7317
        $target,
7318
        $extraFields = null,
7319
        $publicationDate = null
7320
    ) {
7321
        $categoryId = (int) $categoryId;
7322
        $sessionList = [];
7323
        // Check if categoryId is valid
7324
        if ($categoryId > 0) {
7325
            $target = Database::escape_string($target);
7326
            $sTable = Database::get_main_table(TABLE_MAIN_SESSION);
7327
            $sfTable = Database::get_main_table(TABLE_EXTRA_FIELD);
7328
            $sfvTable = Database::get_main_table(TABLE_EXTRA_FIELD_VALUES);
7329
            // Join session field and session field values tables
7330
            $joinTable = $sfTable.' sf INNER JOIN '.$sfvTable.' sfv ON sf.id = sfv.field_id';
7331
            $fieldsArray = [];
7332
            foreach ($extraFields as $field) {
7333
                $fieldsArray[] = Database::escape_string($field);
7334
            }
7335
            $extraFieldType = ExtraField::SESSION_FIELD_TYPE;
7336
            if (isset($publicationDate)) {
7337
                $publicationDateString = $publicationDate->format('Y-m-d H:i:s');
7338
                $wherePublication = " AND id NOT IN (
7339
                    SELECT sfv.item_id FROM $joinTable
7340
                    WHERE
7341
                        sf.extra_field_type = $extraFieldType AND
7342
                        ((sf.variable = 'publication_start_date' AND sfv.value > '$publicationDateString' and sfv.value != '') OR
7343
                        (sf.variable = 'publication_end_date' AND sfv.value < '$publicationDateString' and sfv.value != ''))
7344
                )";
7345
            }
7346
            // Get the session list from session category and target
7347
            $sessionList = Database::select(
7348
                'id, name, access_start_date, access_end_date',
7349
                $sTable,
7350
                [
7351
                    'where' => [
7352
                        "session_category_id = ? AND id IN (
7353
                            SELECT sfv.item_id FROM $joinTable
7354
                            WHERE
7355
                                sf.extra_field_type = $extraFieldType AND
7356
                                sfv.item_id = session.id AND
7357
                                sf.variable = 'target' AND
7358
                                sfv.value = ?
7359
                        ) $wherePublication" => [$categoryId, $target],
7360
                    ],
7361
                ]
7362
            );
7363
            $whereFieldVariables = [];
7364
            $whereFieldIds = [];
7365
            if (
7366
                is_array($fieldsArray) &&
7367
                count($fieldsArray) > 0
7368
            ) {
7369
                $whereParams = '?';
7370
                for ($i = 1; $i < count($fieldsArray); $i++) {
0 ignored issues
show
Performance Best Practice introduced by
It seems like you are calling the size function count() as part of the test condition. You might want to compute the size beforehand, and not on each iteration.

If the size of the collection does not change during the iteration, it is generally a good practice to compute it beforehand, and not on each iteration:

for ($i=0; $i<count($array); $i++) { // calls count() on each iteration
}

// Better
for ($i=0, $c=count($array); $i<$c; $i++) { // calls count() just once
}
Loading history...
7371
                    $whereParams .= ', ?';
7372
                }
7373
                $whereFieldVariables = ' variable IN ( '.$whereParams.' )';
7374
                $whereFieldIds = 'field_id IN ( '.$whereParams.' )';
7375
            }
7376
            // Get session fields
7377
            $extraField = new ExtraFieldModel('session');
7378
            $questionMarks = substr(str_repeat('?, ', count($fieldsArray)), 0, -2);
7379
            $fieldsList = $extraField->get_all([
7380
                ' variable IN ( '.$questionMarks.' )' => $fieldsArray,
7381
            ]);
7382
            // Index session fields
7383
            foreach ($fieldsList as $field) {
7384
                $fields[$field['id']] = $field['variable'];
7385
            }
7386
            // Get session field values
7387
            $extra = new ExtraFieldValue('session');
7388
            $questionMarksFields = substr(str_repeat('?, ', count($fields)), 0, -2);
7389
            $sessionFieldValueList = $extra->get_all(['where' => ['field_id IN ( '.$questionMarksFields.' )' => array_keys($fields)]]);
7390
            // Add session fields values to session list
7391
            foreach ($sessionList as $id => &$session) {
7392
                foreach ($sessionFieldValueList as $sessionFieldValue) {
7393
                    // Match session field values to session
7394
                    if ($sessionFieldValue['item_id'] == $id) {
7395
                        // Check if session field value is set in session field list
7396
                        if (isset($fields[$sessionFieldValue['field_id']])) {
7397
                            // Avoid overwriting the session's ID field
7398
                            if ($fields[$sessionFieldValue['field_id']] != 'id') {
7399
                                $var = $fields[$sessionFieldValue['field_id']];
7400
                                $val = $sessionFieldValue['value'];
7401
                                // Assign session field value to session
7402
                                $session[$var] = $val;
7403
                            }
7404
                        }
7405
                    }
7406
                }
7407
            }
7408
        }
7409
7410
        return $sessionList;
7411
    }
7412
7413
    /**
7414
     * Return the Session Category id searched by name.
7415
     *
7416
     * @param string $categoryName Name attribute of session category used for search query
7417
     * @param bool   $force        boolean used to get even if something is wrong (e.g not unique name)
7418
     *
7419
     * @return int|array If success, return category id (int), else it will return an array
7420
     *                   with the next structure:
7421
     *                   array('error' => true, 'errorMessage' => ERROR_MESSAGE)
7422
     */
7423
    public static function getSessionCategoryIdByName($categoryName, $force = false)
7424
    {
7425
        // Start error result
7426
        $errorResult = ['error' => true, 'errorMessage' => get_lang('ThereWasAnError')];
7427
        $categoryName = Database::escape_string($categoryName);
7428
        // Check if is not empty category name
7429
        if (!empty($categoryName)) {
7430
            $sessionCategoryTable = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
7431
            // Get all session category with same name
7432
            $result = Database::select(
7433
                'id',
7434
                $sessionCategoryTable,
7435
                [
7436
                    'where' => [
7437
                        'name = ?' => $categoryName,
7438
                    ],
7439
                ]
7440
            );
7441
            // Check the result
7442
            if ($result < 1) {
7443
                // If not found any result, update error message
7444
                $errorResult['errorMessage'] = 'Not found any session category name '.$categoryName;
7445
            } elseif (count($result) > 1 && !$force) {
7446
                // If found more than one result and force is disabled, update error message
7447
                $errorResult['errorMessage'] = 'Found many session categories';
7448
            } elseif (count($result) == 1 || $force) {
7449
                // If found just one session category or force option is enabled
7450
7451
                return key($result);
7452
            }
7453
        } else {
7454
            // category name is empty, update error message
7455
            $errorResult['errorMessage'] = 'Not valid category name';
7456
        }
7457
7458
        return $errorResult;
7459
    }
7460
7461
    /**
7462
     * Return all data from sessions (plus extra field, course and coach data) by category id.
7463
     *
7464
     * @param int $sessionCategoryId session category id used to search sessions
7465
     *
7466
     * @return array If success, return session list and more session related data, else it will return an array
7467
     *               with the next structure:
7468
     *               array('error' => true, 'errorMessage' => ERROR_MESSAGE)
7469
     */
7470
    public static function getSessionListAndExtraByCategoryId($sessionCategoryId)
7471
    {
7472
        // Start error result
7473
        $errorResult = [
7474
            'error' => true,
7475
            'errorMessage' => get_lang('ThereWasAnError'),
7476
        ];
7477
7478
        $sessionCategoryId = intval($sessionCategoryId);
7479
        // Check if session category id is valid
7480
        if ($sessionCategoryId > 0) {
7481
            // Get table names
7482
            $sessionTable = Database::get_main_table(TABLE_MAIN_SESSION);
7483
            $sessionFieldTable = Database::get_main_table(TABLE_EXTRA_FIELD);
7484
            $sessionFieldValueTable = Database::get_main_table(TABLE_EXTRA_FIELD_VALUES);
7485
            $sessionCourseUserTable = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
7486
            $userTable = Database::get_main_table(TABLE_MAIN_USER);
7487
            $courseTable = Database::get_main_table(TABLE_MAIN_COURSE);
7488
7489
            // Get all data from all sessions whit the session category specified
7490
            $sessionList = Database::select(
7491
                '*',
7492
                $sessionTable,
7493
                [
7494
                    'where' => [
7495
                        'session_category_id = ?' => $sessionCategoryId,
7496
                    ],
7497
                ]
7498
            );
7499
7500
            $extraFieldType = ExtraField::SESSION_FIELD_TYPE;
7501
7502
            // Check if session list query had result
7503
            if (!empty($sessionList)) {
7504
                // implode all session id
7505
                $sessionIdsString = '('.implode(', ', array_keys($sessionList)).')';
7506
                // Get all field variables
7507
                $sessionFieldList = Database::select(
7508
                    'id, variable',
7509
                    $sessionFieldTable,
7510
                    ['extra_field_type = ? ' => [$extraFieldType]]
7511
                );
7512
7513
                // Get all field values
7514
                $sql = "SELECT item_id, field_id, value FROM
7515
                        $sessionFieldValueTable v INNER JOIN $sessionFieldTable f
7516
                        ON (f.id = v.field_id)
7517
                        WHERE
7518
                            item_id IN $sessionIdsString AND
7519
                            extra_field_type = $extraFieldType
7520
                ";
7521
                $result = Database::query($sql);
7522
                $sessionFieldValueList = Database::store_result($result, 'ASSOC');
7523
7524
                // Check if session field values had result
7525
                if (!empty($sessionFieldValueList)) {
7526
                    $sessionFieldValueListBySession = [];
7527
                    foreach ($sessionFieldValueList as $key => $sessionFieldValue) {
7528
                        // Create an array to index ids to session id
7529
                        $sessionFieldValueListBySession[$sessionFieldValue['item_id']][] = $key;
7530
                    }
7531
                }
7532
                // Query used to find course-coaches from sessions
7533
                $sql = "SELECT
7534
                            scu.session_id,
7535
                            c.id AS course_id,
7536
                            c.code AS course_code,
7537
                            c.title AS course_title,
7538
                            u.username AS coach_username,
7539
                            u.firstname AS coach_firstname,
7540
                            u.lastname AS coach_lastname
7541
                        FROM $courseTable c
7542
                        INNER JOIN $sessionCourseUserTable scu ON c.id = scu.c_id
7543
                        INNER JOIN $userTable u ON scu.user_id = u.user_id
7544
                        WHERE scu.status = 2 AND scu.session_id IN $sessionIdsString
7545
                        ORDER BY scu.session_id ASC ";
7546
                $res = Database::query($sql);
7547
                $sessionCourseList = Database::store_result($res, 'ASSOC');
7548
                // Check if course list had result
7549
                if (!empty($sessionCourseList)) {
7550
                    foreach ($sessionCourseList as $key => $sessionCourse) {
7551
                        // Create an array to index ids to session_id
7552
                        $sessionCourseListBySession[$sessionCourse['session_id']][] = $key;
7553
                    }
7554
                }
7555
                // Join lists
7556
                if (is_array($sessionList)) {
7557
                    foreach ($sessionList as $id => &$row) {
7558
                        if (
7559
                            !empty($sessionFieldValueListBySession) &&
7560
                            is_array($sessionFieldValueListBySession[$id])
7561
                        ) {
7562
                            // If have an index array for session extra fields, use it to join arrays
7563
                            foreach ($sessionFieldValueListBySession[$id] as $key) {
7564
                                $row['extra'][$key] = [
7565
                                    'field_name' => $sessionFieldList[$sessionFieldValueList[$key]['field_id']]['variable'],
7566
                                    'value' => $sessionFieldValueList[$key]['value'],
7567
                                ];
7568
                            }
7569
                        }
7570
                        if (
7571
                            !empty($sessionCourseListBySession) &&
7572
                            is_array($sessionCourseListBySession[$id])
7573
                        ) {
7574
                            // If have an index array for session course coach, use it to join arrays
7575
                            foreach ($sessionCourseListBySession[$id] as $key) {
7576
                                $row['course'][$key] = [
7577
                                    'course_id' => $sessionCourseList[$key]['course_id'],
7578
                                    'course_code' => $sessionCourseList[$key]['course_code'],
7579
                                    'course_title' => $sessionCourseList[$key]['course_title'],
7580
                                    'coach_username' => $sessionCourseList[$key]['coach_username'],
7581
                                    'coach_firstname' => $sessionCourseList[$key]['coach_firstname'],
7582
                                    'coach_lastname' => $sessionCourseList[$key]['coach_lastname'],
7583
                                ];
7584
                            }
7585
                        }
7586
                    }
7587
                }
7588
7589
                return $sessionList;
7590
            } else {
7591
                // Not found result, update error message
7592
                $errorResult['errorMessage'] = 'Not found any session for session category id '.$sessionCategoryId;
7593
            }
7594
        }
7595
7596
        return $errorResult;
7597
    }
7598
7599
    /**
7600
     * Return session description from session id.
7601
     *
7602
     * @param int $sessionId
7603
     *
7604
     * @return string
7605
     */
7606
    public static function getDescriptionFromSessionId($sessionId)
7607
    {
7608
        // Init variables
7609
        $sessionId = (int) $sessionId;
7610
        $description = '';
7611
        // Check if session id is valid
7612
        if ($sessionId > 0) {
7613
            // Select query from session id
7614
            $rows = Database::select(
7615
                'description',
7616
                Database::get_main_table(TABLE_MAIN_SESSION),
7617
                [
7618
                    'where' => [
7619
                        'id = ?' => $sessionId,
7620
                    ],
7621
                ]
7622
            );
7623
7624
            // Check if select query result is not empty
7625
            if (!empty($rows)) {
7626
                // Get session description
7627
                $description = $rows[0]['description'];
7628
            }
7629
        }
7630
7631
        return $description;
7632
    }
7633
7634
    /**
7635
     * Get a session list filtered by name, description or any of the given extra fields.
7636
     *
7637
     * @param string $term                 The term to search
7638
     * @param array  $extraFieldsToInclude Extra fields to include in the session data
7639
     *
7640
     * @return array The list
7641
     */
7642
    public static function searchSession($term, $extraFieldsToInclude = [])
7643
    {
7644
        $sTable = Database::get_main_table(TABLE_MAIN_SESSION);
7645
        $extraFieldTable = Database::get_main_table(TABLE_EXTRA_FIELD);
7646
        $sfvTable = Database::get_main_table(TABLE_EXTRA_FIELD_VALUES);
7647
        $term = Database::escape_string($term);
7648
        $extraFieldType = ExtraField::SESSION_FIELD_TYPE;
7649
        if (is_array($extraFieldsToInclude) && count($extraFieldsToInclude) > 0) {
7650
            $resultData = Database::select('*', $sTable, [
7651
                'where' => [
7652
                    "name LIKE %?% " => $term,
7653
                    " OR description LIKE %?% " => $term,
7654
                    " OR id IN (
7655
                    SELECT item_id
7656
                    FROM $sfvTable v INNER JOIN $extraFieldTable e
7657
                    ON (v.field_id = e.id)
7658
                    WHERE value LIKE %?% AND extra_field_type = $extraFieldType
7659
                ) " => $term,
7660
                ],
7661
            ]);
7662
        } else {
7663
            $resultData = Database::select('*', $sTable, [
7664
                'where' => [
7665
                    "name LIKE %?% " => $term,
7666
                    "OR description LIKE %?% " => $term,
7667
                ],
7668
            ]);
7669
7670
            return $resultData;
7671
        }
7672
7673
        foreach ($resultData as $id => &$session) {
7674
            $session['extra'] = self::getFilteredExtraFields($id, $extraFieldsToInclude);
7675
        }
7676
7677
        return $resultData;
7678
    }
7679
7680
    /**
7681
     * @param int   $sessionId
7682
     * @param array $extraFieldsToInclude (empty means all)
7683
     *
7684
     * @return array
7685
     */
7686
    public static function getFilteredExtraFields($sessionId, $extraFieldsToInclude = [])
7687
    {
7688
        $extraData = [];
7689
        $variables = [];
7690
        $variablePlaceHolders = [];
7691
7692
        foreach ($extraFieldsToInclude as $sessionExtraField) {
7693
            $variablePlaceHolders[] = "?";
7694
            $variables[] = Database::escape_string($sessionExtraField);
7695
        }
7696
7697
        $sessionExtraField = new ExtraFieldModel('session');
7698
        $fieldList = $sessionExtraField->get_all(empty($extraFieldsToInclude) ? [] : [
7699
            "variable IN ( ".implode(", ", $variablePlaceHolders)." ) " => $variables,
7700
        ]);
7701
7702
        if (empty($fieldList)) {
7703
            return [];
7704
        }
7705
7706
        $fields = [];
7707
7708
        // Index session fields
7709
        foreach ($fieldList as $field) {
7710
            $fields[$field['id']] = $field['variable'];
7711
        }
7712
7713
        // Get session field values
7714
        $extra = new ExtraFieldValue('session');
7715
        $sessionFieldValueList = [];
7716
        foreach (array_keys($fields) as $fieldId) {
7717
            $sessionFieldValue = $extra->get_values_by_handler_and_field_id($sessionId, $fieldId);
7718
            if ($sessionFieldValue != false) {
7719
                $sessionFieldValueList[$fieldId] = $sessionFieldValue;
7720
            }
7721
        }
7722
7723
        foreach ($sessionFieldValueList as $sessionFieldValue) {
7724
            $extrafieldVariable = $fields[$sessionFieldValue['field_id']];
7725
            $extrafieldValue = $sessionFieldValue['value'];
7726
7727
            $extraData[] = [
7728
                'variable' => $extrafieldVariable,
7729
                'value' => $extrafieldValue,
7730
            ];
7731
        }
7732
7733
        return $extraData;
7734
    }
7735
7736
    /**
7737
     * @param int $sessionId
7738
     *
7739
     * @return bool
7740
     */
7741
    public static function isValidId($sessionId)
7742
    {
7743
        $sessionId = (int) $sessionId;
7744
        if ($sessionId > 0) {
7745
            $rows = Database::select(
7746
                'id',
7747
                Database::get_main_table(TABLE_MAIN_SESSION),
7748
                ['where' => ['id = ?' => $sessionId]]
7749
            );
7750
            if (!empty($rows)) {
7751
                return true;
7752
            }
7753
        }
7754
7755
        return false;
7756
    }
7757
7758
    /**
7759
     * Get list of sessions based on users of a group for a group admin.
7760
     *
7761
     * @param int $userId The user id
7762
     *
7763
     * @return array
7764
     */
7765
    public static function getSessionsFollowedForGroupAdmin($userId)
7766
    {
7767
        $sessionList = [];
7768
        $sessionTable = Database::get_main_table(TABLE_MAIN_SESSION);
7769
        $sessionUserTable = Database::get_main_table(TABLE_MAIN_SESSION_USER);
7770
        $userGroup = new UserGroup();
7771
        $userIdList = $userGroup->getGroupUsersByUser($userId);
7772
7773
        if (empty($userIdList)) {
7774
            return [];
7775
        }
7776
7777
        $sql = "SELECT DISTINCT s.*
7778
                FROM $sessionTable s
7779
                INNER JOIN $sessionUserTable sru
7780
                ON s.id = sru.id_session
7781
                WHERE
7782
                    (sru.id_user IN (".implode(', ', $userIdList).")
7783
                    AND sru.relation_type = 0
7784
                )";
7785
7786
        if (api_is_multiple_url_enabled()) {
7787
            $sessionAccessUrlTable = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
7788
            $accessUrlId = api_get_current_access_url_id();
7789
7790
            if (-1 != $accessUrlId) {
7791
                $sql = "SELECT DISTINCT s.*
7792
                        FROM $sessionTable s
7793
                        INNER JOIN $sessionUserTable sru ON s.id = sru.id_session
7794
                        INNER JOIN $sessionAccessUrlTable srau ON s.id = srau.session_id
7795
                        WHERE
7796
                            srau.access_url_id = $accessUrlId
7797
                            AND (
7798
                                sru.id_user IN (".implode(', ', $userIdList).")
7799
                                AND sru.relation_type = 0
7800
                            )";
7801
            }
7802
        }
7803
7804
        $result = Database::query($sql);
7805
        while ($row = Database::fetch_assoc($result)) {
7806
            $sessionList[] = $row;
7807
        }
7808
7809
        return $sessionList;
7810
    }
7811
7812
    /**
7813
     * @param array $sessionInfo
7814
     *
7815
     * @return string
7816
     */
7817
    public static function getSessionVisibility($sessionInfo)
7818
    {
7819
        switch ($sessionInfo['visibility']) {
7820
            case 1:
7821
                return get_lang('ReadOnly');
7822
            case 2:
7823
                return get_lang('Visible');
7824
            case 3:
7825
                return api_ucfirst(get_lang('Invisible'));
7826
        }
7827
    }
7828
7829
    /**
7830
     * Returns a human readable string.
7831
     *
7832
     * @param array $sessionInfo An array with all the session dates
7833
     * @param bool  $showTime
7834
     *
7835
     * @return array
7836
     */
7837
    public static function parseSessionDates($sessionInfo, $showTime = false)
7838
    {
7839
        $displayDates = self::convertSessionDateToString(
7840
            $sessionInfo['display_start_date'],
7841
            $sessionInfo['display_end_date'],
7842
            $showTime,
7843
            true
7844
        );
7845
        $accessDates = self::convertSessionDateToString(
7846
            $sessionInfo['access_start_date'],
7847
            $sessionInfo['access_end_date'],
7848
            $showTime,
7849
            true
7850
        );
7851
7852
        $coachDates = self::convertSessionDateToString(
7853
            $sessionInfo['coach_access_start_date'],
7854
            $sessionInfo['coach_access_end_date'],
7855
            $showTime,
7856
            true
7857
        );
7858
7859
        $result = [
7860
            'access' => $accessDates,
7861
            'display' => $displayDates,
7862
            'coach' => $coachDates,
7863
        ];
7864
7865
        return $result;
7866
    }
7867
7868
    /**
7869
     * @param array $sessionInfo Optional
7870
     *
7871
     * @return array
7872
     */
7873
    public static function setForm(FormValidator $form, array $sessionInfo = [])
7874
    {
7875
        $sessionId = 0;
7876
        $coachInfo = [];
7877
7878
        if (!empty($sessionInfo)) {
7879
            $sessionId = (int) $sessionInfo['id'];
7880
            $coachInfo = api_get_user_info($sessionInfo['id_coach']);
7881
        }
7882
7883
        $categoriesList = self::get_all_session_category();
7884
        $userInfo = api_get_user_info();
7885
7886
        $categoriesOptions = [
7887
            '0' => get_lang('None'),
7888
        ];
7889
7890
        if ($categoriesList != false) {
7891
            foreach ($categoriesList as $categoryItem) {
7892
                $categoriesOptions[$categoryItem['id']] = $categoryItem['name'];
7893
            }
7894
        }
7895
7896
        // Database Table Definitions
7897
        $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
7898
7899
        $form->addText(
7900
            'name',
7901
            get_lang('SessionName'),
7902
            true,
7903
            ['maxlength' => 150, 'aria-label' => get_lang('SessionName')]
7904
        );
7905
        $form->addRule('name', get_lang('SessionNameAlreadyExists'), 'callback', 'check_session_name');
7906
7907
        if (!api_is_platform_admin() && api_is_teacher()) {
7908
            $form->addElement(
7909
                'select',
7910
                'coach_username',
7911
                get_lang('CoachName'),
7912
                [api_get_user_id() => $userInfo['complete_name']],
7913
                [
7914
                    'id' => 'coach_username',
7915
                    'style' => 'width:370px;',
7916
                ]
7917
            );
7918
        } else {
7919
            $sql = "SELECT COUNT(1) FROM $tbl_user WHERE status = 1";
7920
            $rs = Database::query($sql);
7921
            $countUsers = (int) Database::result($rs, 0, 0);
7922
7923
            if ($countUsers < 50) {
7924
                $orderClause = 'ORDER BY ';
7925
                $orderClause .= api_sort_by_first_name() ? 'firstname, lastname, username' : 'lastname, firstname, username';
7926
7927
                $sql = "SELECT user_id, lastname, firstname, username
7928
                        FROM $tbl_user
7929
                        WHERE status = '1' ".
7930
                        $orderClause;
7931
7932
                if (api_is_multiple_url_enabled()) {
7933
                    $userRelAccessUrlTable = Database::get_main_table(
7934
                        TABLE_MAIN_ACCESS_URL_REL_USER
7935
                    );
7936
                    $accessUrlId = api_get_current_access_url_id();
7937
                    if ($accessUrlId != -1) {
7938
                        $sql = "SELECT user.user_id, username, lastname, firstname
7939
                        FROM $tbl_user user
7940
                        INNER JOIN $userRelAccessUrlTable url_user
7941
                        ON (url_user.user_id = user.user_id)
7942
                        WHERE
7943
                            access_url_id = $accessUrlId AND
7944
                            status = 1 "
7945
                            .$orderClause;
7946
                    }
7947
                }
7948
7949
                $result = Database::query($sql);
7950
                $coachesList = Database::store_result($result);
7951
                $coachesOptions = [];
7952
                foreach ($coachesList as $coachItem) {
7953
                    $coachesOptions[$coachItem['user_id']] =
7954
                        api_get_person_name($coachItem['firstname'], $coachItem['lastname']).' ('.$coachItem['username'].')';
7955
                }
7956
7957
                $form->addElement(
7958
                    'select',
7959
                    'coach_username',
7960
                    get_lang('CoachName'),
7961
                    $coachesOptions,
7962
                    [
7963
                        'id' => 'coach_username',
7964
                        'style' => 'width:370px;',
7965
                    ]
7966
                );
7967
            } else {
7968
                $form->addElement(
7969
                    'select_ajax',
7970
                    'coach_username',
7971
                    get_lang('CoachName'),
7972
                    $coachInfo ? [$coachInfo['id'] => $coachInfo['complete_name_with_username']] : [],
7973
                    [
7974
                        'url' => api_get_path(WEB_AJAX_PATH).'session.ajax.php?a=search_general_coach',
7975
                        'width' => '100%',
7976
                        'id' => 'coach_username',
7977
                    ]
7978
                );
7979
            }
7980
        }
7981
7982
        $form->addRule('coach_username', get_lang('ThisFieldIsRequired'), 'required');
7983
        $form->addHtml('<div id="ajax_list_coachs"></div>');
7984
7985
        $form->addButtonAdvancedSettings('advanced_params');
7986
        $form->addElement('html', '<div id="advanced_params_options" style="display:none">');
7987
7988
        if (empty($sessionId)) {
7989
            $form->addSelectAjax(
7990
                'session_template',
7991
                get_lang('SessionTemplate'),
7992
                [],
7993
                ['url' => api_get_path(WEB_AJAX_PATH).'session.ajax.php?a=search_template_session', 'id' => 'system_template']
7994
            );
7995
        }
7996
7997
        $form->addSelect(
7998
            'session_category',
7999
            get_lang('SessionCategory'),
8000
            $categoriesOptions,
8001
            [
8002
                'id' => 'session_category',
8003
            ]
8004
        );
8005
8006
        if (api_get_configuration_value('allow_session_status')) {
8007
            $statusList = self::getStatusList();
8008
            $form->addSelect(
8009
                'status',
8010
                get_lang('SessionStatus'),
8011
                $statusList,
8012
                [
8013
                    'id' => 'status',
8014
                ]
8015
            );
8016
        }
8017
8018
        $form->addHtmlEditor(
8019
            'description',
8020
            get_lang('Description'),
8021
            false,
8022
            false,
8023
            [
8024
                'ToolbarSet' => 'Minimal',
8025
            ]
8026
        );
8027
8028
        $form->addElement('checkbox', 'show_description', null, get_lang('ShowDescription'));
8029
8030
        $visibilityGroup = [];
8031
        $visibilityGroup[] = $form->createElement(
8032
            'select',
8033
            'session_visibility',
8034
            null,
8035
            [
8036
                SESSION_VISIBLE_READ_ONLY => get_lang('SessionReadOnly'),
8037
                SESSION_VISIBLE => get_lang('SessionAccessible'),
8038
                SESSION_INVISIBLE => api_ucfirst(get_lang('SessionNotAccessible')),
8039
            ]
8040
        );
8041
        $form->addGroup(
8042
            $visibilityGroup,
8043
            'visibility_group',
8044
            get_lang('SessionVisibility'),
8045
            null,
8046
            false
8047
        );
8048
8049
        $options = [
8050
            0 => get_lang('ByDuration'),
8051
            1 => get_lang('ByDates'),
8052
        ];
8053
8054
        $form->addSelect('access', get_lang('Access'), $options, [
8055
            'onchange' => 'accessSwitcher()',
8056
            'id' => 'access',
8057
        ]);
8058
8059
        $form->addHtml('<div id="duration_div" style="display:none">');
8060
        $form->addElement(
8061
            'number',
8062
            'duration',
8063
            [
8064
                get_lang('SessionDurationTitle'),
8065
                get_lang('SessionDurationDescription'),
8066
            ],
8067
            [
8068
                'maxlength' => 50,
8069
            ]
8070
        );
8071
8072
        $form->addHtml('</div>');
8073
        $form->addHtml('<div id="date_fields" style="display:none">');
8074
8075
        // Dates
8076
        $form->addDateTimePicker(
8077
            'access_start_date',
8078
            [get_lang('SessionStartDate'), get_lang('SessionStartDateComment')],
8079
            ['id' => 'access_start_date']
8080
        );
8081
8082
        $form->addDateTimePicker(
8083
            'access_end_date',
8084
            [get_lang('SessionEndDate'), get_lang('SessionEndDateComment')],
8085
            ['id' => 'access_end_date']
8086
        );
8087
8088
        $form->addRule(
8089
            ['access_start_date', 'access_end_date'],
8090
            get_lang('StartDateMustBeBeforeTheEndDate'),
8091
            'compare_datetime_text',
8092
            '< allow_empty'
8093
        );
8094
8095
        $form->addDateTimePicker(
8096
            'display_start_date',
8097
            [
8098
                get_lang('SessionDisplayStartDate'),
8099
                get_lang('SessionDisplayStartDateComment'),
8100
            ],
8101
            ['id' => 'display_start_date']
8102
        );
8103
8104
        $form->addDateTimePicker(
8105
            'display_end_date',
8106
            [
8107
                get_lang('SessionDisplayEndDate'),
8108
                get_lang('SessionDisplayEndDateComment'),
8109
            ],
8110
            ['id' => 'display_end_date']
8111
        );
8112
8113
        $form->addRule(
8114
            ['display_start_date', 'display_end_date'],
8115
            get_lang('StartDateMustBeBeforeTheEndDate'),
8116
            'compare_datetime_text',
8117
            '< allow_empty'
8118
        );
8119
8120
        $form->addDateTimePicker(
8121
            'coach_access_start_date',
8122
            [
8123
                get_lang('SessionCoachStartDate'),
8124
                get_lang('SessionCoachStartDateComment'),
8125
            ],
8126
            ['id' => 'coach_access_start_date']
8127
        );
8128
8129
        $form->addDateTimePicker(
8130
            'coach_access_end_date',
8131
            [
8132
                get_lang('SessionCoachEndDate'),
8133
                get_lang('SessionCoachEndDateComment'),
8134
            ],
8135
            ['id' => 'coach_access_end_date']
8136
        );
8137
8138
        $form->addRule(
8139
            ['coach_access_start_date', 'coach_access_end_date'],
8140
            get_lang('StartDateMustBeBeforeTheEndDate'),
8141
            'compare_datetime_text',
8142
            '< allow_empty'
8143
        );
8144
8145
        $form->addElement('html', '</div>');
8146
8147
        $form->addCheckBox(
8148
            'send_subscription_notification',
8149
            [
8150
                get_lang('SendSubscriptionNotification'),
8151
                get_lang('SendAnEmailWhenAUserBeingSubscribed'),
8152
            ]
8153
        );
8154
8155
        // Extra fields
8156
        $extra_field = new ExtraFieldModel('session');
8157
        $extra = $extra_field->addElements($form, $sessionId);
8158
8159
        $form->addElement('html', '</div>');
8160
8161
        $js = $extra['jquery_ready_content'];
8162
8163
        return ['js' => $js];
8164
    }
8165
8166
    /**
8167
     * Gets the number of rows in the session table filtered through the given
8168
     * array of parameters.
8169
     *
8170
     * @param array Array of options/filters/keys
8171
     *
8172
     * @return int The number of rows, or false on wrong param
8173
     * @assert ('a') === false
8174
     */
8175
    public static function get_count_admin_complete($options = [])
8176
    {
8177
        if (!is_array($options)) {
8178
            return false;
8179
        }
8180
        $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
8181
        $tbl_session_category = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
8182
        $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
8183
        $sessionCourseUserTable = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
8184
        $courseTable = Database::get_main_table(TABLE_MAIN_COURSE);
8185
        $tbl_session_field_values = Database::get_main_table(TABLE_EXTRA_FIELD_VALUES);
8186
        $tbl_session_field_options = Database::get_main_table(TABLE_EXTRA_FIELD_OPTIONS);
8187
8188
        $where = 'WHERE 1 = 1 ';
8189
        $user_id = api_get_user_id();
8190
8191
        if (api_is_session_admin() &&
8192
            'false' == api_get_setting('allow_session_admins_to_see_all_sessions')
8193
        ) {
8194
            $where .= " WHERE s.session_admin_id = $user_id ";
8195
        }
8196
8197
        $extraFieldTables = '';
8198
        if (!empty($options['where'])) {
8199
            $options['where'] = str_replace('course_title', 'c.title', $options['where']);
8200
            $options['where'] = str_replace("( session_active = '0' )", '1=1', $options['where']);
8201
8202
            $options['where'] = str_replace(
8203
                ["AND session_active = '1'  )", " AND (  session_active = '1'  )"],
8204
                [') GROUP BY s.name HAVING session_active = 1 ', " GROUP BY s.name HAVING session_active = 1 "],
8205
                $options['where']
8206
            );
8207
8208
            $options['where'] = str_replace(
8209
                ["AND session_active = '0'  )", " AND (  session_active = '0'  )"],
8210
                [') GROUP BY s.name HAVING session_active = 0 ', " GROUP BY s.name HAVING session_active = '0' "],
8211
                $options['where']
8212
            );
8213
8214
            if (!empty($options['extra'])) {
8215
                $options['where'] = str_replace(' 1 = 1  AND', '', $options['where']);
8216
                $options['where'] = str_replace('AND', 'OR', $options['where']);
8217
8218
                foreach ($options['extra'] as $extra) {
8219
                    $options['where'] = str_replace(
8220
                        $extra['field'],
8221
                        'fv.field_id = '.$extra['id'].' AND fvo.option_value',
8222
                        $options['where']
8223
                    );
8224
                    $extraFieldTables = "$tbl_session_field_values fv, $tbl_session_field_options fvo, ";
8225
                }
8226
            }
8227
            $where .= ' AND '.$options['where'];
8228
        }
8229
8230
        $today = api_get_utc_datetime();
8231
        $query_rows = "SELECT count(*) as total_rows, c.title as course_title, s.name,
8232
                        IF (
8233
                            (s.access_start_date <= '$today' AND '$today' < s.access_end_date) OR
8234
                            (s.access_start_date = '0000-00-00 00:00:00' AND s.access_end_date = '0000-00-00 00:00:00' ) OR
8235
                            (s.access_start_date IS NULL AND s.access_end_date IS NULL) OR
8236
                            (s.access_start_date <= '$today' AND ('0000-00-00 00:00:00' = s.access_end_date OR s.access_end_date IS NULL )) OR
8237
                            ('$today' < s.access_end_date AND ('0000-00-00 00:00:00' = s.access_start_date OR s.access_start_date IS NULL) )
8238
                        , 1, 0) as session_active
8239
                       FROM $extraFieldTables $tbl_session s
8240
                       LEFT JOIN  $tbl_session_category sc
8241
                       ON s.session_category_id = sc.id
8242
                       INNER JOIN $tbl_user u
8243
                       ON s.id_coach = u.id
8244
                       INNER JOIN $sessionCourseUserTable scu
8245
                       ON s.id = scu.session_id
8246
                       INNER JOIN $courseTable c
8247
                       ON c.id = scu.c_id
8248
                       $where ";
8249
8250
        if (api_is_multiple_url_enabled()) {
8251
            $table_access_url_rel_session = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
8252
            $access_url_id = api_get_current_access_url_id();
8253
            if (-1 != $access_url_id) {
8254
                $where .= " AND ar.access_url_id = $access_url_id ";
8255
                $query_rows = "SELECT count(*) as total_rows
8256
                               FROM $tbl_session s
8257
                               LEFT JOIN  $tbl_session_category sc
8258
                               ON s.session_category_id = sc.id
8259
                               INNER JOIN $tbl_user u
8260
                               ON s.id_coach = u.id
8261
                               INNER JOIN $table_access_url_rel_session ar
8262
                               ON ar.session_id = s.id $where ";
8263
            }
8264
        }
8265
8266
        $result = Database::query($query_rows);
8267
        $num = 0;
8268
        if (Database::num_rows($result)) {
8269
            $rows = Database::fetch_array($result);
8270
            $num = $rows['total_rows'];
8271
        }
8272
8273
        return $num;
8274
    }
8275
8276
    /**
8277
     * @param string $listType
8278
     * @param array  $extraFields
8279
     *
8280
     * @return array
8281
     */
8282
    public static function getGridColumns(
8283
        $listType = 'all',
8284
        $extraFields = [],
8285
        $addExtraFields = true
8286
    ) {
8287
        $showCount = api_get_configuration_value('session_list_show_count_users');
8288
        // Column config
8289
        $operators = ['cn', 'nc'];
8290
        $date_operators = ['gt', 'ge', 'lt', 'le'];
8291
8292
        switch ($listType) {
8293
            case 'my_space':
8294
                $columns = [
8295
                    get_lang('Title'),
8296
                    get_lang('Date'),
8297
                    get_lang('NbCoursesPerSession'),
8298
                    get_lang('NbStudentPerSession'),
8299
                    get_lang('Details'),
8300
                ];
8301
8302
                $columnModel = [
8303
                    ['name' => 'name', 'index' => 'name', 'width' => '255', 'align' => 'left'],
8304
                    ['name' => 'date', 'index' => 'access_start_date', 'width' => '150', 'align' => 'left'],
8305
                    [
8306
                        'name' => 'course_per_session',
8307
                        'index' => 'course_per_session',
8308
                        'width' => '150',
8309
                        'sortable' => 'false',
8310
                        'search' => 'false',
8311
                    ],
8312
                    [
8313
                        'name' => 'student_per_session',
8314
                        'index' => 'student_per_session',
8315
                        'width' => '100',
8316
                        'sortable' => 'false',
8317
                        'search' => 'false',
8318
                    ],
8319
                    [
8320
                        'name' => 'actions',
8321
                        'index' => 'actions',
8322
                        'width' => '100',
8323
                        'sortable' => 'false',
8324
                        'search' => 'false',
8325
                    ],
8326
                ];
8327
                break;
8328
            case 'all':
8329
            case 'active':
8330
            case 'close':
8331
                $columns = [
8332
                    '#',
8333
                    get_lang('Name'),
8334
                    get_lang('Category'),
8335
                    get_lang('SessionDisplayStartDate'),
8336
                    get_lang('SessionDisplayEndDate'),
8337
                    get_lang('Visibility'),
8338
                ];
8339
8340
                $columnModel = [
8341
                    [
8342
                        'name' => 'id',
8343
                        'index' => 's.id',
8344
                        'width' => '160',
8345
                        'hidden' => 'true',
8346
                    ],
8347
                    [
8348
                        'name' => 'name',
8349
                        'index' => 's.name',
8350
                        'width' => '160',
8351
                        'align' => 'left',
8352
                        'search' => 'true',
8353
                        'searchoptions' => ['sopt' => $operators],
8354
                    ],
8355
                    [
8356
                        'name' => 'category_name',
8357
                        'index' => 'category_name',
8358
                        'width' => '40',
8359
                        'align' => 'left',
8360
                        'search' => 'true',
8361
                        'searchoptions' => ['sopt' => $operators],
8362
                    ],
8363
                    [
8364
                        'name' => 'display_start_date',
8365
                        'index' => 'display_start_date',
8366
                        'width' => '50',
8367
                        'align' => 'left',
8368
                        'search' => 'true',
8369
                        'searchoptions' => [
8370
                            'dataInit' => 'date_pick_today',
8371
                            'sopt' => $date_operators,
8372
                        ],
8373
                    ],
8374
                    [
8375
                        'name' => 'display_end_date',
8376
                        'index' => 'display_end_date',
8377
                        'width' => '50',
8378
                        'align' => 'left',
8379
                        'search' => 'true',
8380
                        'searchoptions' => [
8381
                            'dataInit' => 'date_pick_one_month',
8382
                            'sopt' => $date_operators,
8383
                        ],
8384
                    ],
8385
                    [
8386
                        'name' => 'visibility',
8387
                        'index' => 'visibility',
8388
                        'width' => '40',
8389
                        'align' => 'left',
8390
                        'search' => 'false',
8391
                    ],
8392
                ];
8393
8394
                if ($showCount) {
8395
                    $columns[] = get_lang('Users');
8396
                    $columnModel[] = [
8397
                        'name' => 'users',
8398
                        'index' => 'users',
8399
                        'width' => '20',
8400
                        'align' => 'left',
8401
                        'search' => 'false',
8402
                    ];
8403
8404
                    // ofaj
8405
                    $columns[] = get_lang('Teachers');
8406
                    $columnModel[] = [
8407
                        'name' => 'teachers',
8408
                        'index' => 'teachers',
8409
                        'width' => '20',
8410
                        'align' => 'left',
8411
                        'search' => 'false',
8412
                    ];
8413
                }
8414
8415
                if (api_get_configuration_value('allow_session_status')) {
8416
                    $columns[] = get_lang('SessionStatus');
8417
                    $list = self::getStatusList();
8418
                    $listToString = '';
8419
                    foreach ($list as $statusId => $status) {
8420
                        $listToString .= $statusId.':'.$status.';';
8421
                    }
8422
8423
                    $columnModel[] = [
8424
                        'name' => 'status',
8425
                        'index' => 'status',
8426
                        'width' => '25',
8427
                        'align' => 'left',
8428
                        'search' => 'true',
8429
                        'stype' => 'select',
8430
                        // for the bottom bar
8431
                        'searchoptions' => [
8432
                            'defaultValue' => '1',
8433
                            'value' => $listToString,
8434
                        ],
8435
                    ];
8436
                }
8437
                break;
8438
            case 'complete':
8439
                $columns = [
8440
                    get_lang('Name'),
8441
                    get_lang('SessionDisplayStartDate'),
8442
                    get_lang('SessionDisplayEndDate'),
8443
                    get_lang('Coach'),
8444
                    get_lang('Status'),
8445
                    get_lang('Visibility'),
8446
                    get_lang('CourseTitle'),
8447
                ];
8448
                $columnModel = [
8449
                    [
8450
                        'name' => 'name',
8451
                        'index' => 's.name',
8452
                        'width' => '200',
8453
                        'align' => 'left',
8454
                        'search' => 'true',
8455
                        'searchoptions' => ['sopt' => $operators],
8456
                    ],
8457
                    [
8458
                        'name' => 'display_start_date',
8459
                        'index' => 'display_start_date',
8460
                        'width' => '70',
8461
                        'align' => 'left',
8462
                        'search' => 'true',
8463
                        'searchoptions' => ['dataInit' => 'date_pick_today', 'sopt' => $date_operators],
8464
                    ],
8465
                    [
8466
                        'name' => 'display_end_date',
8467
                        'index' => 'display_end_date',
8468
                        'width' => '70',
8469
                        'align' => 'left',
8470
                        'search' => 'true',
8471
                        'searchoptions' => ['dataInit' => 'date_pick_one_month', 'sopt' => $date_operators],
8472
                    ],
8473
                    [
8474
                        'name' => 'coach_name',
8475
                        'index' => 'coach_name',
8476
                        'width' => '70',
8477
                        'align' => 'left',
8478
                        'search' => 'false',
8479
                        'searchoptions' => ['sopt' => $operators],
8480
                    ],
8481
                    [
8482
                        'name' => 'session_active',
8483
                        'index' => 'session_active',
8484
                        'width' => '25',
8485
                        'align' => 'left',
8486
                        'search' => 'true',
8487
                        'stype' => 'select',
8488
                        // for the bottom bar
8489
                        'searchoptions' => [
8490
                            'defaultValue' => '1',
8491
                            'value' => '1:'.get_lang('Active').';0:'.get_lang('Inactive'),
8492
                        ],
8493
                        // for the top bar
8494
                        'editoptions' => [
8495
                            'value' => '" ":'.get_lang('All').';1:'.get_lang('Active').';0:'.get_lang(
8496
                                    'Inactive'
8497
                                ),
8498
                        ],
8499
                    ],
8500
                    [
8501
                        'name' => 'visibility',
8502
                        'index' => 'visibility',
8503
                        'width' => '40',
8504
                        'align' => 'left',
8505
                        'search' => 'false',
8506
                    ],
8507
                    [
8508
                        'name' => 'course_title',
8509
                        'index' => 'course_title',
8510
                        'width' => '50',
8511
                        'hidden' => 'true',
8512
                        'search' => 'true',
8513
                        'searchoptions' => ['searchhidden' => 'true', 'sopt' => $operators],
8514
                    ],
8515
                ];
8516
8517
                break;
8518
8519
            case 'custom':
8520
                $columns = [
8521
                    '#',
8522
                    get_lang('Name'),
8523
                    get_lang('Category'),
8524
                    get_lang('SessionDisplayStartDate'),
8525
                    get_lang('SessionDisplayEndDate'),
8526
                    get_lang('Visibility'),
8527
                ];
8528
                $columnModel = [
8529
                    [
8530
                        'name' => 'id',
8531
                        'index' => 's.id',
8532
                        'width' => '160',
8533
                        'hidden' => 'true',
8534
                    ],
8535
                    [
8536
                        'name' => 'name',
8537
                        'index' => 's.name',
8538
                        'width' => '160',
8539
                        'align' => 'left',
8540
                        'search' => 'true',
8541
                        'searchoptions' => ['sopt' => $operators],
8542
                    ],
8543
                    [
8544
                        'name' => 'category_name',
8545
                        'index' => 'category_name',
8546
                        'width' => '40',
8547
                        'align' => 'left',
8548
                        'search' => 'true',
8549
                        'searchoptions' => ['sopt' => $operators],
8550
                    ],
8551
                    [
8552
                        'name' => 'display_start_date',
8553
                        'index' => 'display_start_date',
8554
                        'width' => '50',
8555
                        'align' => 'left',
8556
                        'search' => 'true',
8557
                        'searchoptions' => [
8558
                            'dataInit' => 'date_pick_today',
8559
                            'sopt' => $date_operators,
8560
                        ],
8561
                    ],
8562
                    [
8563
                        'name' => 'display_end_date',
8564
                        'index' => 'display_end_date',
8565
                        'width' => '50',
8566
                        'align' => 'left',
8567
                        'search' => 'true',
8568
                        'searchoptions' => [
8569
                            'dataInit' => 'date_pick_one_month',
8570
                            'sopt' => $date_operators,
8571
                        ],
8572
                    ],
8573
                    [
8574
                        'name' => 'visibility',
8575
                        'index' => 'visibility',
8576
                        'width' => '40',
8577
                        'align' => 'left',
8578
                        'search' => 'false',
8579
                    ],
8580
                ];
8581
8582
                if ($showCount) {
8583
                    $columns[] = get_lang('Users');
8584
                    $columnModel[] = [
8585
                        'name' => 'users',
8586
                        'index' => 'users',
8587
                        'width' => '20',
8588
                        'align' => 'left',
8589
                        'search' => 'false',
8590
                    ];
8591
8592
                    // ofaj
8593
                    $columns[] = get_lang('Teachers');
8594
                    $columnModel[] = [
8595
                        'name' => 'teachers',
8596
                        'index' => 'teachers',
8597
                        'width' => '20',
8598
                        'align' => 'left',
8599
                        'search' => 'false',
8600
                    ];
8601
                }
8602
8603
                if (api_get_configuration_value('allow_session_status')) {
8604
                    $columns[] = get_lang('SessionStatus');
8605
                    $list = self::getStatusList();
8606
                    $listToString = '';
8607
                    foreach ($list as $statusId => $status) {
8608
                        $listToString .= $statusId.':'.$status.';';
8609
                    }
8610
8611
                    $columnModel[] = [
8612
                        'name' => 'status',
8613
                        'index' => 'status',
8614
                        'width' => '25',
8615
                        'align' => 'left',
8616
                        'search' => 'true',
8617
                        'stype' => 'select',
8618
                        // for the bottom bar
8619
                        'searchoptions' => [
8620
                            'defaultValue' => '1',
8621
                            'value' => $listToString,
8622
                        ],
8623
                    ];
8624
                }
8625
8626
                break;
8627
        }
8628
8629
        if (!empty($extraFields)) {
8630
            foreach ($extraFields as $field) {
8631
                $columns[] = $field['display_text'];
8632
                $columnModel[] = [
8633
                    'name' => $field['variable'],
8634
                    'index' => $field['variable'],
8635
                    'width' => '80',
8636
                    'align' => 'center',
8637
                    'search' => 'false',
8638
                ];
8639
            }
8640
        }
8641
8642
        // Inject extra session fields
8643
        $rules = [];
8644
        if ($addExtraFields) {
8645
            $sessionField = new ExtraFieldModel('session');
8646
            $rules = $sessionField->getRules($columns, $columnModel);
8647
        }
8648
8649
        if (!in_array('actions', array_column($columnModel, 'name'))) {
8650
            $columnModel[] = [
8651
                'name' => 'actions',
8652
                'index' => 'actions',
8653
                'width' => '80',
8654
                'align' => 'left',
8655
                'formatter' => 'action_formatter',
8656
                'sortable' => 'false',
8657
                'search' => 'false',
8658
            ];
8659
            $columns[] = get_lang('Actions');
8660
        }
8661
8662
        $columnName = [];
8663
        foreach ($columnModel as $col) {
8664
            $columnName[] = $col['name'];
8665
        }
8666
8667
        $return = [
8668
            'columns' => $columns,
8669
            'column_model' => $columnModel,
8670
            'rules' => $rules,
8671
            'simple_column_name' => $columnName,
8672
        ];
8673
8674
        return $return;
8675
    }
8676
8677
    /**
8678
     * Converts all dates sent through the param array (given form) to correct dates with timezones.
8679
     *
8680
     * @param array The dates The same array, with times converted
8681
     * @param bool $applyFormat Whether apply the DATE_TIME_FORMAT_SHORT format for sessions
8682
     *
8683
     * @return array The same array, with times converted
8684
     */
8685
    public static function convert_dates_to_local($params, $applyFormat = false)
8686
    {
8687
        if (!is_array($params)) {
8688
            return false;
8689
        }
8690
        $params['display_start_date'] = api_get_local_time($params['display_start_date'], null, null, true);
8691
        $params['display_end_date'] = api_get_local_time($params['display_end_date'], null, null, true);
8692
8693
        $params['access_start_date'] = api_get_local_time($params['access_start_date'], null, null, true);
8694
        $params['access_end_date'] = api_get_local_time($params['access_end_date'], null, null, true);
8695
8696
        $params['coach_access_start_date'] = isset($params['coach_access_start_date']) ? api_get_local_time($params['coach_access_start_date'], null, null, true) : null;
8697
        $params['coach_access_end_date'] = isset($params['coach_access_end_date']) ? api_get_local_time($params['coach_access_end_date'], null, null, true) : null;
8698
8699
        if ($applyFormat) {
8700
            if (isset($params['display_start_date'])) {
8701
                $params['display_start_date'] = api_format_date($params['display_start_date'], DATE_TIME_FORMAT_SHORT);
8702
            }
8703
8704
            if (isset($params['display_end_date'])) {
8705
                $params['display_end_date'] = api_format_date($params['display_end_date'], DATE_TIME_FORMAT_SHORT);
8706
            }
8707
8708
            if (isset($params['access_start_date'])) {
8709
                $params['access_start_date'] = api_format_date($params['access_start_date'], DATE_TIME_FORMAT_SHORT);
8710
            }
8711
8712
            if (isset($params['access_end_date'])) {
8713
                $params['access_end_date'] = api_format_date($params['access_end_date'], DATE_TIME_FORMAT_SHORT);
8714
            }
8715
8716
            if (isset($params['coach_access_start_date'])) {
8717
                $params['coach_access_start_date'] = api_format_date($params['coach_access_start_date'], DATE_TIME_FORMAT_SHORT);
8718
            }
8719
8720
            if (isset($params['coach_access_end_date'])) {
8721
                $params['coach_access_end_date'] = api_format_date($params['coach_access_end_date'], DATE_TIME_FORMAT_SHORT);
8722
            }
8723
        }
8724
8725
        return $params;
8726
    }
8727
8728
    /**
8729
     * Gets the admin session list callback of the session/session_list.php
8730
     * page with all user/details in the right fomat.
8731
     *
8732
     * @param array $options
8733
     *
8734
     * @return array Array of rows results
8735
     * @asset ('a') === false
8736
     */
8737
    public static function get_sessions_admin_complete($options = [])
8738
    {
8739
        if (!is_array($options)) {
8740
            return false;
8741
        }
8742
8743
        $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
8744
        $tbl_session_category = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
8745
        $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
8746
        $tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
8747
        $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
8748
8749
        $extraFieldTable = Database::get_main_table(TABLE_EXTRA_FIELD);
8750
        $tbl_session_field_values = Database::get_main_table(TABLE_EXTRA_FIELD_VALUES);
8751
        $tbl_session_field_options = Database::get_main_table(TABLE_EXTRA_FIELD_OPTIONS);
8752
8753
        $where = 'WHERE 1 = 1 ';
8754
        $user_id = api_get_user_id();
8755
8756
        if (!api_is_platform_admin()) {
8757
            if (api_is_session_admin() &&
8758
                'false' == api_get_setting('allow_session_admins_to_manage_all_sessions')
8759
            ) {
8760
                $where .= " AND s.session_admin_id = $user_id ";
8761
            }
8762
        }
8763
8764
        $coach_name = " CONCAT(u.lastname , ' ', u.firstname) as coach_name ";
8765
        if (api_is_western_name_order()) {
8766
            $coach_name = " CONCAT(u.firstname, ' ', u.lastname) as coach_name ";
8767
        }
8768
8769
        $today = api_get_utc_datetime();
8770
        $injectExtraFields = null;
8771
        $extra_fields_info = [];
8772
8773
        //for now only sessions
8774
        $extra_field = new ExtraFieldModel('session');
8775
        $double_fields = [];
8776
        $extra_field_option = new ExtraFieldOption('session');
8777
8778
        if (isset($options['extra'])) {
8779
            $extra_fields = $options['extra'];
8780
            if (!empty($extra_fields)) {
8781
                foreach ($extra_fields as $extra) {
8782
                    $injectExtraFields .= " IF (fv.field_id = {$extra['id']}, fvo.option_display_text, NULL ) as {$extra['field']} , ";
8783
                    if (isset($extra_fields_info[$extra['id']])) {
8784
                        $info = $extra_fields_info[$extra['id']];
8785
                    } else {
8786
                        $info = $extra_field->get($extra['id']);
8787
                        $extra_fields_info[$extra['id']] = $info;
8788
                    }
8789
8790
                    if (ExtraFieldModel::FIELD_TYPE_DOUBLE_SELECT == $info['field_type']) {
8791
                        $double_fields[$info['id']] = $info;
8792
                    }
8793
                }
8794
            }
8795
        }
8796
8797
        $options_by_double = [];
8798
        foreach ($double_fields as $double) {
8799
            $my_options = $extra_field_option->get_field_options_by_field(
8800
                $double['id'],
8801
                true
8802
            );
8803
            $options_by_double['extra_'.$double['field_variable']] = $my_options;
8804
        }
8805
8806
        //sc.name as category_name,
8807
        $select = "
8808
                SELECT * FROM (
8809
                    SELECT DISTINCT
8810
                        IF (
8811
                            (s.access_start_date <= '$today' AND '$today' < s.access_end_date) OR
8812
                            (s.access_start_date = '0000-00-00 00:00:00' AND s.access_end_date = '0000-00-00 00:00:00' ) OR
8813
                            (s.access_start_date IS NULL AND s.access_end_date IS NULL) OR
8814
                            (s.access_start_date <= '$today' AND ('0000-00-00 00:00:00' = s.access_end_date OR s.access_end_date IS NULL )) OR
8815
                            ('$today' < s.access_end_date AND ('0000-00-00 00:00:00' = s.access_start_date OR s.access_start_date IS NULL) )
8816
                        , 1, 0) as session_active,
8817
                s.name,
8818
                s.nbr_courses,
8819
                s.nbr_users,
8820
                s.display_start_date,
8821
                s.display_end_date,
8822
                $coach_name,
8823
                access_start_date,
8824
                access_end_date,
8825
                s.visibility,
8826
                u.id as user_id,
8827
                $injectExtraFields
8828
                c.title as course_title,
8829
                s.id ";
8830
8831
        if (!empty($options['where'])) {
8832
            if (!empty($options['extra'])) {
8833
                $options['where'] = str_replace(' 1 = 1  AND', '', $options['where']);
8834
                $options['where'] = str_replace('AND', 'OR', $options['where']);
8835
                foreach ($options['extra'] as $extra) {
8836
                    $options['where'] = str_replace($extra['field'], 'fv.field_id = '.$extra['id'].' AND fvo.option_value', $options['where']);
8837
                }
8838
            }
8839
            $options['where'] = str_replace('course_title', 'c.title', $options['where']);
8840
            $options['where'] = str_replace("( session_active = '0' )", '1=1', $options['where']);
8841
            $options['where'] = str_replace(
8842
                ["AND session_active = '1'  )", " AND (  session_active = '1'  )"],
8843
                [') GROUP BY s.name HAVING session_active = 1 ', " GROUP BY s.name HAVING session_active = 1 "],
8844
                $options['where']
8845
            );
8846
8847
            $options['where'] = str_replace(
8848
                ["AND session_active = '0'  )", " AND (  session_active = '0'  )"],
8849
                [') GROUP BY s.name HAVING session_active = 0 ', " GROUP BY s.name HAVING session_active = '0' "],
8850
                $options['where']
8851
            );
8852
8853
            $where .= ' AND '.$options['where'];
8854
        }
8855
8856
        $limit = '';
8857
        if (!empty($options['limit'])) {
8858
            $limit = ' LIMIT '.$options['limit'];
8859
        }
8860
8861
        $query = "$select FROM $tbl_session s
8862
                    LEFT JOIN $tbl_session_field_values fv
8863
                    ON (fv.item_id = s.id)
8864
                    LEFT JOIN $extraFieldTable f
8865
                    ON f.id = fv.field_id
8866
                    LEFT JOIN $tbl_session_field_options fvo
8867
                    ON (fv.field_id = fvo.field_id)
8868
                    LEFT JOIN $tbl_session_rel_course src
8869
                    ON (src.session_id = s.id)
8870
                    LEFT JOIN $tbl_course c
8871
                    ON (src.c_id = c.id)
8872
                    LEFT JOIN $tbl_session_category sc
8873
                    ON (s.session_category_id = sc.id)
8874
                    INNER JOIN $tbl_user u
8875
                    ON (s.id_coach = u.id)
8876
                    $where
8877
                    $limit
8878
        ";
8879
8880
        if (api_is_multiple_url_enabled()) {
8881
            $table_access_url_rel_session = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
8882
            $access_url_id = api_get_current_access_url_id();
8883
            if (-1 != $access_url_id) {
8884
                $query = "$select
8885
                    FROM $tbl_session s
8886
                    LEFT JOIN $tbl_session_field_values fv
8887
                    ON (fv.item_id = s.id)
8888
                    LEFT JOIN $tbl_session_field_options fvo
8889
                    ON (fv.field_id = fvo.field_id)
8890
                    LEFT JOIN $tbl_session_rel_course src
8891
                    ON (src.session_id = s.id)
8892
                    LEFT JOIN $tbl_course c
8893
                    ON (src.c_id = c.id)
8894
                    LEFT JOIN $tbl_session_category sc
8895
                    ON (s.session_category_id = sc.id)
8896
                    INNER JOIN $tbl_user u
8897
                    ON (s.id_coach = u.id)
8898
                    INNER JOIN $table_access_url_rel_session ar
8899
                    ON (ar.session_id = s.id AND ar.access_url_id = $access_url_id)
8900
                    $where
8901
                    $limit
8902
                ";
8903
            }
8904
        }
8905
8906
        $query .= ') AS s';
8907
8908
        if (!empty($options['order'])) {
8909
            $query .= ' ORDER BY '.$options['order'];
8910
        }
8911
8912
        $result = Database::query($query);
8913
8914
        $acceptIcon = Display::return_icon(
8915
            'accept.png',
8916
            get_lang('Active'),
8917
            [],
8918
            ICON_SIZE_SMALL
8919
        );
8920
8921
        $errorIcon = Display::return_icon(
8922
            'error.png',
8923
            get_lang('Inactive'),
8924
            [],
8925
            ICON_SIZE_SMALL
8926
        );
8927
8928
        $formatted_sessions = [];
8929
        if (Database::num_rows($result)) {
8930
            $sessions = Database::store_result($result, 'ASSOC');
8931
            foreach ($sessions as $session) {
8932
                $session_id = $session['id'];
8933
                $session['name'] = Display::url($session['name'], "resume_session.php?id_session=".$session['id']);
8934
                $session['coach_name'] = Display::url($session['coach_name'], "user_information.php?user_id=".$session['user_id']);
8935
                if (1 == $session['session_active']) {
8936
                    $session['session_active'] = $acceptIcon;
8937
                } else {
8938
                    $session['session_active'] = $errorIcon;
8939
                }
8940
8941
                $session = self::convert_dates_to_local($session);
8942
8943
                switch ($session['visibility']) {
8944
                    case SESSION_VISIBLE_READ_ONLY: //1
8945
                        $session['visibility'] = get_lang('ReadOnly');
8946
                        break;
8947
                    case SESSION_VISIBLE:           //2
8948
                    case SESSION_AVAILABLE:         //4
8949
                        $session['visibility'] = get_lang('Visible');
8950
                        break;
8951
                    case SESSION_INVISIBLE:         //3
8952
                        $session['visibility'] = api_ucfirst(get_lang('Invisible'));
8953
                        break;
8954
                }
8955
8956
                // Cleaning double selects
8957
                foreach ($session as $key => &$value) {
8958
                    if (isset($options_by_double[$key]) || isset($options_by_double[$key.'_second'])) {
8959
                        $options = explode('::', $value);
8960
                    }
8961
                    $original_key = $key;
8962
8963
                    if (strpos($key, '_second') === false) {
8964
                    } else {
8965
                        $key = str_replace('_second', '', $key);
8966
                    }
8967
8968
                    if (isset($options_by_double[$key])) {
8969
                        if (isset($options[0])) {
8970
                            if (isset($options_by_double[$key][$options[0]])) {
8971
                                if (strpos($original_key, '_second') === false) {
8972
                                    $value = $options_by_double[$key][$options[0]]['option_display_text'];
8973
                                } else {
8974
                                    $value = $options_by_double[$key][$options[1]]['option_display_text'];
8975
                                }
8976
                            }
8977
                        }
8978
                    }
8979
                }
8980
8981
                // Magic filter
8982
                if (isset($formatted_sessions[$session_id])) {
8983
                    $formatted_sessions[$session_id] = self::compareArraysToMerge(
8984
                        $formatted_sessions[$session_id],
8985
                        $session
8986
                    );
8987
                } else {
8988
                    $formatted_sessions[$session_id] = $session;
8989
                }
8990
            }
8991
        }
8992
8993
        return $formatted_sessions;
8994
    }
8995
8996
    /**
8997
     * Compare two arrays.
8998
     *
8999
     * @param array $array1
9000
     * @param array $array2
9001
     *
9002
     * @return array
9003
     */
9004
    public static function compareArraysToMerge($array1, $array2)
9005
    {
9006
        if (empty($array2)) {
9007
            return $array1;
9008
        }
9009
        foreach ($array1 as $key => $item) {
9010
            if (!isset($array1[$key])) {
9011
                //My string is empty try the other one
9012
                if (isset($array2[$key]) && !empty($array2[$key])) {
9013
                    $array1[$key] = $array2[$key];
9014
                }
9015
            }
9016
        }
9017
9018
        return $array1;
9019
    }
9020
9021
    /**
9022
     * Get link to the admin page for this session.
9023
     *
9024
     * @param int $id Session ID
9025
     *
9026
     * @return mixed URL to the admin page to manage the session, or false on error
9027
     */
9028
    public static function getAdminPath($id)
9029
    {
9030
        $id = (int) $id;
9031
        $session = self::fetch($id);
9032
        if (empty($session)) {
9033
            return false;
9034
        }
9035
9036
        return api_get_path(WEB_CODE_PATH).'session/resume_session.php?id_session='.$id;
9037
    }
9038
9039
    /**
9040
     * Get link to the user page for this session.
9041
     * If a course is provided, build the link to the course.
9042
     *
9043
     * @param int $id       Session ID
9044
     * @param int $courseId Course ID (optional) in case the link has to send straight to the course
9045
     *
9046
     * @return mixed URL to the page to use the session, or false on error
9047
     */
9048
    public static function getPath($id, $courseId = 0)
9049
    {
9050
        $id = (int) $id;
9051
        $session = self::fetch($id);
9052
        if (empty($session)) {
9053
            return false;
9054
        }
9055
        if (empty($courseId)) {
9056
            return api_get_path(WEB_CODE_PATH).'session/index.php?session_id='.$id;
9057
        } else {
9058
            $courseInfo = api_get_course_info_by_id($courseId);
9059
            if ($courseInfo) {
9060
                return $courseInfo['course_public_url'].'?id_session='.$id;
9061
            }
9062
        }
9063
9064
        return false;
9065
    }
9066
9067
    /**
9068
     * Return an associative array 'id_course' => [id_session1, id_session2...]
9069
     * where course id_course is in sessions id_session1, id_session2
9070
     * for course where user is coach
9071
     * i.e. coach for the course or
9072
     * main coach for a session the course is in
9073
     * for a session category (or woth no session category if empty).
9074
     *
9075
     * @param int $userId
9076
     *
9077
     * @return array
9078
     */
9079
    public static function getSessionCourseForUser($userId)
9080
    {
9081
        // list of COURSES where user is COURSE session coach
9082
        $listCourseCourseCoachSession = self::getCoursesForCourseSessionCoach($userId);
9083
        // list of courses where user is MAIN session coach
9084
        $listCourseMainCoachSession = self::getCoursesForMainSessionCoach($userId);
9085
        // merge these 2 array
9086
        $listResCourseSession = $listCourseCourseCoachSession;
9087
        foreach ($listCourseMainCoachSession as $courseId2 => $listSessionId2) {
9088
            if (isset($listResCourseSession[$courseId2])) {
9089
                // if sessionId array exists for this course
9090
                // same courseId, merge the list of session
9091
                foreach ($listCourseMainCoachSession[$courseId2] as $i => $sessionId2) {
9092
                    if (!in_array($sessionId2, $listResCourseSession[$courseId2])) {
9093
                        $listResCourseSession[$courseId2][] = $sessionId2;
9094
                    }
9095
                }
9096
            } else {
9097
                $listResCourseSession[$courseId2] = $listSessionId2;
9098
            }
9099
        }
9100
9101
        return $listResCourseSession;
9102
    }
9103
9104
    /**
9105
     * Return an associative array 'id_course' => [id_session1, id_session2...]
9106
     * where course id_course is in sessions id_session1, id_session2.
9107
     *
9108
     * @param int $userId
9109
     *
9110
     * @return array
9111
     */
9112
    public static function getCoursesForCourseSessionCoach($userId)
9113
    {
9114
        $userId = (int) $userId;
9115
        $listResCourseSession = [];
9116
        $tblCourse = Database::get_main_table(TABLE_MAIN_COURSE);
9117
        $tblSessionRelCourseRelUser = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
9118
9119
        $sql = "SELECT session_id, c_id, c.id
9120
                FROM $tblSessionRelCourseRelUser srcru
9121
                LEFT JOIN $tblCourse c
9122
                ON c.id = srcru.c_id
9123
                WHERE
9124
                    srcru.user_id = $userId AND
9125
                    srcru.status = 2";
9126
9127
        $res = Database::query($sql);
9128
9129
        while ($data = Database::fetch_assoc($res)) {
9130
            if (api_get_session_visibility($data['session_id'])) {
9131
                if (!isset($listResCourseSession[$data['id']])) {
9132
                    $listResCourseSession[$data['id']] = [];
9133
                }
9134
                $listResCourseSession[$data['id']][] = $data['session_id'];
9135
            }
9136
        }
9137
9138
        return $listResCourseSession;
9139
    }
9140
9141
    /**
9142
     * Return an associative array 'id_course' => [id_session1, id_session2...]
9143
     * where course id_course is in sessions id_session1, id_session2.
9144
     *
9145
     * @param $userId
9146
     *
9147
     * @return array
9148
     */
9149
    public static function getCoursesForMainSessionCoach($userId)
9150
    {
9151
        $userId = (int) $userId;
9152
        $listResCourseSession = [];
9153
        $tblSession = Database::get_main_table(TABLE_MAIN_SESSION);
9154
9155
        // list of SESSION where user is session coach
9156
        $sql = "SELECT id FROM $tblSession
9157
                WHERE id_coach = ".$userId;
9158
        $res = Database::query($sql);
9159
9160
        while ($data = Database::fetch_assoc($res)) {
9161
            $sessionId = $data['id'];
9162
            $listCoursesInSession = self::getCoursesInSession($sessionId);
9163
            foreach ($listCoursesInSession as $i => $courseId) {
9164
                if (api_get_session_visibility($sessionId)) {
9165
                    if (!isset($listResCourseSession[$courseId])) {
9166
                        $listResCourseSession[$courseId] = [];
9167
                    }
9168
                    $listResCourseSession[$courseId][] = $sessionId;
9169
                }
9170
            }
9171
        }
9172
9173
        return $listResCourseSession;
9174
    }
9175
9176
    /**
9177
     * Return an array of course_id used in session $sessionId.
9178
     *
9179
     * @param $sessionId
9180
     *
9181
     * @return array
9182
     */
9183
    public static function getCoursesInSession($sessionId)
9184
    {
9185
        if (empty($sessionId)) {
9186
            return [];
9187
        }
9188
9189
        $tblSessionRelCourse = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
9190
        $tblCourse = Database::get_main_table(TABLE_MAIN_COURSE);
9191
9192
        // list of course in this session
9193
        $sql = "SELECT session_id, c.id
9194
                FROM $tblSessionRelCourse src
9195
                LEFT JOIN $tblCourse c
9196
                ON c.id = src.c_id
9197
                WHERE session_id = ".intval($sessionId);
9198
        $res = Database::query($sql);
9199
9200
        $listResultsCourseId = [];
9201
        while ($data = Database::fetch_assoc($res)) {
9202
            $listResultsCourseId[] = $data['id'];
9203
        }
9204
9205
        return $listResultsCourseId;
9206
    }
9207
9208
    /**
9209
     * Return an array of courses in session for user
9210
     * and for each courses the list of session that use this course for user.
9211
     *
9212
     * [0] => array
9213
     *      userCatId
9214
     *      userCatTitle
9215
     *      courseInUserCatList
9216
     *          [0] => array
9217
     *              courseId
9218
     *              title
9219
     *              courseCode
9220
     *              sessionCatList
9221
     *                  [0] => array
9222
     *                      catSessionId
9223
     *                      catSessionName
9224
     *                      sessionList
9225
     *                          [0] => array
9226
     *                              sessionId
9227
     *                              sessionName
9228
     *
9229
     * @param int $userId
9230
     *
9231
     * @return array
9232
     */
9233
    public static function getNamedSessionCourseForCoach($userId)
9234
    {
9235
        $listResults = [];
9236
        $listCourseSession = self::getSessionCourseForUser($userId);
9237
        foreach ($listCourseSession as $courseId => $listSessionId) {
9238
            // Course info
9239
            $courseInfo = api_get_course_info_by_id($courseId);
9240
            $listOneCourse = [];
9241
            $listOneCourse['courseId'] = $courseId;
9242
            $listOneCourse['title'] = $courseInfo['title'];
9243
            //$listOneCourse['courseCode'] = $courseInfo['code'];
9244
            $listOneCourse['course'] = $courseInfo;
9245
            $listOneCourse['sessionCatList'] = [];
9246
            $listCat = [];
9247
            foreach ($listSessionId as $i => $sessionId) {
9248
                // here we got all session for this course
9249
                // lets check there session categories
9250
                $sessionInfo = self::fetch($sessionId);
9251
                $catId = $sessionInfo['session_category_id'];
9252
                if (!isset($listCat[$catId])) {
9253
                    $listCatInfo = self::get_session_category($catId);
9254
                    if ($listCatInfo) {
9255
                        $listCat[$catId] = [];
9256
                        $listCat[$catId]['catSessionId'] = $catId;
9257
                        $listCat[$catId]['catSessionName'] = $listCatInfo['name'];
9258
                        $listCat[$catId]['sessionList'] = [];
9259
                    }
9260
                }
9261
                $listSessionInfo = self::fetch($sessionId);
9262
                $listSessionIdName = [
9263
                    'sessionId' => $sessionId,
9264
                    'sessionName' => $listSessionInfo['name'],
9265
                ];
9266
                $listCat[$catId]['sessionList'][] = $listSessionIdName;
9267
            }
9268
            // sort $listCat by catSessionName
9269
            usort($listCat, 'self::compareBySessionName');
9270
            // in each catSession sort sessionList by sessionName
9271
            foreach ($listCat as $i => $listCatSessionInfo) {
9272
                $listSessionList = $listCatSessionInfo['sessionList'];
9273
                usort($listSessionList, 'self::compareCatSessionInfo');
9274
                $listCat[$i]['sessionList'] = $listSessionList;
9275
            }
9276
9277
            $listOneCourse['sessionCatList'] = $listCat;
9278
9279
            // user course category
9280
            $courseCategory = CourseManager::getUserCourseCategoryForCourse(
9281
                $userId,
9282
                $courseId
9283
            );
9284
9285
            $userCatTitle = '';
9286
            $userCatId = 0;
9287
            if ($courseCategory) {
9288
                $userCatId = $courseCategory['user_course_cat'];
9289
                $userCatTitle = $courseCategory['title'];
9290
            }
9291
9292
            $listResults[$userCatId]['courseInUserCategoryId'] = $userCatId;
9293
            $listResults[$userCatId]['courseInUserCategoryTitle'] = $userCatTitle;
9294
            $listResults[$userCatId]['courseInUserCatList'][] = $listOneCourse;
9295
        }
9296
9297
        // sort by user course cat
9298
        uasort($listResults, 'self::compareByUserCourseCat');
9299
9300
        // sort by course title
9301
        foreach ($listResults as $userCourseCatId => $tabCoursesInCat) {
9302
            $courseInUserCatList = $tabCoursesInCat['courseInUserCatList'];
9303
            uasort($courseInUserCatList, 'self::compareByCourse');
9304
            $listResults[$userCourseCatId]['courseInUserCatList'] = $courseInUserCatList;
9305
        }
9306
9307
        return $listResults;
9308
    }
9309
9310
    /**
9311
     * @param int $userId
9312
     * @param int $courseId
9313
     *
9314
     * @return array
9315
     */
9316
    public static function searchCourseInSessionsFromUser($userId, $courseId)
9317
    {
9318
        $table = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
9319
        $userId = (int) $userId;
9320
        $courseId = (int) $courseId;
9321
        if (empty($userId) || empty($courseId)) {
9322
            return [];
9323
        }
9324
9325
        $sql = "SELECT * FROM $table
9326
                WHERE c_id = $courseId AND user_id = $userId";
9327
        $result = Database::query($sql);
9328
9329
        return Database::store_result($result, 'ASSOC');
9330
    }
9331
9332
    /**
9333
     * Subscribe and redirect to session after inscription.
9334
     */
9335
    public static function redirectToSession()
9336
    {
9337
        $sessionId = (int) ChamiloSession::read('session_redirect');
9338
        $onlyOneCourseSessionToRedirect = ChamiloSession::read('only_one_course_session_redirect');
9339
        if ($sessionId) {
9340
            $sessionInfo = api_get_session_info($sessionId);
9341
            if (!empty($sessionInfo)) {
9342
                $userId = api_get_user_id();
9343
                $response = self::isUserSubscribedAsStudent($sessionId, $userId);
9344
                if ($response) {
9345
                    $urlToRedirect = api_get_path(WEB_CODE_PATH).'session/index.php?session_id='.$sessionId;
9346
                    if (!empty($onlyOneCourseSessionToRedirect)) {
9347
                        $urlToRedirect = api_get_path(WEB_PATH).
9348
                            'courses/'.$onlyOneCourseSessionToRedirect.'/index.php?id_session='.$sessionId;
9349
                    }
9350
9351
                    header('Location: '.$urlToRedirect);
9352
                    exit;
9353
                }
9354
            }
9355
        }
9356
    }
9357
9358
    /**
9359
     * @return int
9360
     */
9361
    public static function getCountUsersInCourseSession(Course $course, Session $session)
9362
    {
9363
        $urlId = api_get_current_access_url_id();
9364
9365
        return Database::getManager()
9366
            ->createQuery("
9367
                SELECT COUNT(scu)
9368
                FROM ChamiloCoreBundle:SessionRelCourseRelUser scu
9369
                INNER JOIN ChamiloCoreBundle:SessionRelUser su
9370
                    WITH scu.user = su.user
9371
                    AND scu.session = su.session
9372
                INNER JOIN ChamiloCoreBundle:AccessUrlRelUser a
9373
                    WITH a.user = su.user
9374
                WHERE
9375
                    scu.course = :course AND
9376
                    su.relationType <> :relationType AND
9377
                    scu.session = :session AND
9378
                    a.portal = :url
9379
            ")
9380
            ->setParameters([
9381
                'course' => $course->getId(),
9382
                'relationType' => SESSION_RELATION_TYPE_RRHH,
9383
                'session' => $session->getId(),
9384
                'url' => $urlId,
9385
            ])
9386
            ->getSingleScalarResult();
9387
    }
9388
9389
    /**
9390
     * Get course IDs where user in not subscribed in session.
9391
     *
9392
     * @return array
9393
     */
9394
    public static function getAvoidedCoursesInSession(User $user, Session $session)
9395
    {
9396
        $courseIds = [];
9397
9398
        /** @var SessionRelCourse $sessionCourse */
9399
        foreach ($session->getCourses() as $sessionCourse) {
9400
            /** @var Course $course */
9401
            $course = $sessionCourse->getCourse();
9402
9403
            if ($session->getUserInCourse($user, $course)->count()) {
9404
                continue;
9405
            }
9406
9407
            $courseIds[] = $course->getId();
9408
        }
9409
9410
        return $courseIds;
9411
    }
9412
9413
    /**
9414
     * @param int             $userId
9415
     * @param int             $sessionId
9416
     * @param ExtraFieldValue $extraFieldValue
9417
     * @param string          $collapsableLink
9418
     *
9419
     * @return array
9420
     */
9421
    public static function getCollapsableData($userId, $sessionId, $extraFieldValue, $collapsableLink)
9422
    {
9423
        $collapsed = 0;
9424
9425
        // Get default collapsed value in extra field
9426
        $value = $extraFieldValue->get_values_by_handler_and_field_variable($sessionId, 'collapsed');
9427
        if (!empty($value) && isset($value['value'])) {
9428
            $collapsed = $value['value'];
9429
        }
9430
9431
        $userRelSession = self::getUserSession($userId, $sessionId);
9432
9433
        if ($userRelSession) {
9434
            if (isset($userRelSession['collapsed']) && '' != $userRelSession['collapsed']) {
9435
                $collapsed = $userRelSession['collapsed'];
9436
            }
9437
        } else {
9438
            return ['collapsed' => $collapsed, 'collapsable_link' => '&nbsp;'];
9439
        }
9440
9441
        $link = $collapsableLink.'&session_id='.$sessionId.'&value=1';
9442
        $image = '<i class="fa fa-folder-open"></i>';
9443
        if (1 == $collapsed) {
9444
            $link = $collapsableLink.'&session_id='.$sessionId.'&value=0';
9445
            $image = '<i class="fa fa-folder"></i>';
9446
        }
9447
9448
        $link = Display::url(
9449
            $image,
9450
            $link
9451
        );
9452
9453
        return ['collapsed' => $collapsed, 'collapsable_link' => $link];
9454
    }
9455
9456
    /**
9457
     * Converts "start date" and "end date" to "From start date to end date" string.
9458
     *
9459
     * @param string $startDate
9460
     * @param string $endDate
9461
     * @param bool   $showTime
9462
     * @param bool   $dateHuman
9463
     *
9464
     * @return string
9465
     */
9466
    public static function convertSessionDateToString($startDate, $endDate, $showTime, $dateHuman)
9467
    {
9468
        // api_get_local_time returns empty if date is invalid like 0000-00-00 00:00:00
9469
        $startDateToLocal = api_get_local_time(
9470
            $startDate,
9471
            null,
9472
            null,
9473
            true,
9474
            $showTime,
9475
            $dateHuman
9476
        );
9477
        $endDateToLocal = api_get_local_time(
9478
            $endDate,
9479
            null,
9480
            null,
9481
            true,
9482
            $showTime,
9483
            $dateHuman
9484
        );
9485
9486
        $format = $showTime ? DATE_TIME_FORMAT_LONG_24H : DATE_FORMAT_LONG_NO_DAY;
9487
9488
        $result = '';
9489
        if (!empty($startDateToLocal) && !empty($endDateToLocal)) {
9490
            $result = sprintf(
9491
                get_lang('FromDateXToDateY'),
9492
                api_format_date($startDateToLocal, $format),
9493
                api_format_date($endDateToLocal, $format)
9494
            );
9495
        } else {
9496
            if (!empty($startDateToLocal)) {
9497
                $result = get_lang('From').' '.api_format_date($startDateToLocal, $format);
9498
            }
9499
            if (!empty($endDateToLocal)) {
9500
                $result = get_lang('Until').' '.api_format_date($endDateToLocal, $format);
9501
            }
9502
        }
9503
        if (empty($result)) {
9504
            $result = get_lang('NoTimeLimits');
9505
        }
9506
9507
        return $result;
9508
    }
9509
9510
    public static function getStatusList()
9511
    {
9512
        return [
9513
            self::STATUS_PLANNED => get_lang('Planned'),
9514
            self::STATUS_PROGRESS => get_lang('InProgress'),
9515
            self::STATUS_FINISHED => get_lang('Finished'),
9516
            self::STATUS_CANCELLED => get_lang('Cancelled'),
9517
        ];
9518
    }
9519
9520
    public static function getStatusLabel($status)
9521
    {
9522
        $list = self::getStatusList();
9523
9524
        if (!isset($list[$status])) {
9525
            return get_lang('NoStatus');
9526
        }
9527
9528
        return $list[$status];
9529
    }
9530
9531
    public static function getDefaultSessionTab()
9532
    {
9533
        $default = 'all';
9534
        $view = api_get_configuration_value('default_session_list_view');
9535
9536
        if (!empty($view)) {
9537
            $default = $view;
9538
        }
9539
9540
        return $default;
9541
    }
9542
9543
    /**
9544
     * @return string
9545
     */
9546
    public static function getSessionListTabs($listType)
9547
    {
9548
        $tabs = [
9549
            [
9550
                'content' => get_lang('AllSessionsShort'),
9551
                'url' => api_get_path(WEB_CODE_PATH).'session/session_list.php?list_type=all',
9552
            ],
9553
            [
9554
                'content' => get_lang('ActiveSessionsShort'),
9555
                'url' => api_get_path(WEB_CODE_PATH).'session/session_list.php?list_type=active',
9556
            ],
9557
            [
9558
                'content' => get_lang('ClosedSessionsShort'),
9559
                'url' => api_get_path(WEB_CODE_PATH).'session/session_list.php?list_type=close',
9560
            ],
9561
            [
9562
                'content' => get_lang('SessionListCustom'),
9563
                'url' => api_get_path(WEB_CODE_PATH).'session/session_list.php?list_type=custom',
9564
            ],
9565
            /*[
9566
                'content' => get_lang('Complete'),
9567
                'url' => api_get_path(WEB_CODE_PATH).'session/session_list_simple.php?list_type=complete',
9568
            ],*/
9569
        ];
9570
9571
        switch ($listType) {
9572
            case 'all':
9573
                $default = 1;
9574
                break;
9575
            case 'active':
9576
                $default = 2;
9577
                break;
9578
            case 'close':
9579
                $default = 3;
9580
                break;
9581
            case 'custom':
9582
                $default = 4;
9583
                break;
9584
        }
9585
9586
        return Display::tabsOnlyLink($tabs, $default);
9587
    }
9588
9589
    /**
9590
     * Check if a session is followed by human resources manager.
9591
     *
9592
     * @param int $sessionId
9593
     * @param int $userId
9594
     *
9595
     * @return bool
9596
     */
9597
    public static function isSessionFollowedByDrh($sessionId, $userId)
9598
    {
9599
        $userId = (int) $userId;
9600
        $sessionId = (int) $sessionId;
9601
9602
        $tblSession = Database::get_main_table(TABLE_MAIN_SESSION);
9603
        $tblSessionRelUser = Database::get_main_table(TABLE_MAIN_SESSION_USER);
9604
9605
        if (api_is_multiple_url_enabled()) {
9606
            $tblSessionRelAccessUrl = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
9607
9608
            $sql = "SELECT s.id FROM $tblSession s
9609
                INNER JOIN $tblSessionRelUser sru ON (sru.session_id = s.id)
9610
                LEFT JOIN $tblSessionRelAccessUrl a ON (s.id = a.session_id)
9611
                WHERE
9612
                    sru.user_id = '$userId' AND
9613
                    sru.session_id = '$sessionId' AND
9614
                    sru.relation_type = '".SESSION_RELATION_TYPE_RRHH."' AND
9615
                    access_url_id = ".api_get_current_access_url_id();
9616
        } else {
9617
            $sql = "SELECT s.id FROM $tblSession s
9618
                INNER JOIN $tblSessionRelUser sru ON sru.session_id = s.id
9619
                WHERE
9620
                    sru.user_id = '$userId' AND
9621
                    sru.session_id = '$sessionId' AND
9622
                    sru.relation_type = '".SESSION_RELATION_TYPE_RRHH."'";
9623
        }
9624
9625
        $result = Database::query($sql);
9626
9627
        return Database::num_rows($result) > 0;
9628
    }
9629
9630
    /**
9631
     * Add a warning message when session is read-only mode.
9632
     */
9633
    public static function addFlashSessionReadOnly()
9634
    {
9635
        if (api_get_session_id() && !api_is_allowed_to_session_edit()) {
9636
            Display::addFlash(
9637
                Display::return_message(get_lang('SessionIsReadOnly'), 'warning')
9638
            );
9639
        }
9640
    }
9641
9642
    /**
9643
     * @param int $id
9644
     *
9645
     * @return bool
9646
     */
9647
    private static function allowed($id)
9648
    {
9649
        $sessionInfo = self::fetch($id);
9650
9651
        if (empty($sessionInfo)) {
9652
            return false;
9653
        }
9654
9655
        if (api_is_platform_admin()) {
9656
            return true;
9657
        }
9658
9659
        $userId = api_get_user_id();
9660
9661
        if (api_is_session_admin() &&
9662
            api_get_setting('allow_session_admins_to_manage_all_sessions') != 'true'
9663
        ) {
9664
            if ($sessionInfo['session_admin_id'] != $userId) {
9665
                return false;
9666
            }
9667
        }
9668
9669
        if (api_is_teacher() &&
9670
            api_get_setting('allow_teachers_to_create_sessions') == 'true'
9671
        ) {
9672
            if ($sessionInfo['id_coach'] != $userId) {
9673
                return false;
9674
            }
9675
        }
9676
9677
        return true;
9678
    }
9679
9680
    /**
9681
     * Add classes (by their names) to a session.
9682
     *
9683
     * @param int   $sessionId
9684
     * @param array $classesNames
9685
     * @param bool  $deleteClassSessions Optional. Empty the session list for the usergroup (class)
9686
     */
9687
    private static function addClassesByName($sessionId, $classesNames, $deleteClassSessions = true)
9688
    {
9689
        if (!$classesNames) {
9690
            return;
9691
        }
9692
9693
        $usergroup = new UserGroup();
9694
9695
        foreach ($classesNames as $className) {
9696
            if (empty($className)) {
9697
                continue;
9698
            }
9699
9700
            $usergroup->subscribe_sessions_to_usergroup(
9701
                $usergroup->getIdByName($className),
9702
                [$sessionId],
9703
                $deleteClassSessions
9704
            );
9705
        }
9706
    }
9707
9708
    /**
9709
     * @param array $listA
9710
     * @param array $listB
9711
     *
9712
     * @return int
9713
     */
9714
    private static function compareCatSessionInfo($listA, $listB)
9715
    {
9716
        if ($listA['sessionName'] == $listB['sessionName']) {
9717
            return 0;
9718
        } elseif ($listA['sessionName'] > $listB['sessionName']) {
9719
            return 1;
9720
        } else {
9721
            return -1;
9722
        }
9723
    }
9724
9725
    /**
9726
     * @param array $listA
9727
     * @param array $listB
9728
     *
9729
     * @return int
9730
     */
9731
    private static function compareBySessionName($listA, $listB)
9732
    {
9733
        if ('' == $listB['catSessionName']) {
9734
            return -1;
9735
        } elseif ('' == $listA['catSessionName']) {
9736
            return 1;
9737
        } elseif ($listA['catSessionName'] == $listB['catSessionName']) {
9738
            return 0;
9739
        } elseif ($listA['catSessionName'] > $listB['catSessionName']) {
9740
            return 1;
9741
        } else {
9742
            return -1;
9743
        }
9744
    }
9745
9746
    /**
9747
     * @param array $listA
9748
     * @param array $listB
9749
     *
9750
     * @return int
9751
     */
9752
    private static function compareByUserCourseCat($listA, $listB)
9753
    {
9754
        if ($listA['courseInUserCategoryTitle'] == $listB['courseInUserCategoryTitle']) {
9755
            return 0;
9756
        } elseif ($listA['courseInUserCategoryTitle'] > $listB['courseInUserCategoryTitle']) {
9757
            return 1;
9758
        } else {
9759
            return -1;
9760
        }
9761
    }
9762
9763
    /**
9764
     * @param array $listA
9765
     * @param array $listB
9766
     *
9767
     * @return int
9768
     */
9769
    private static function compareByCourse($listA, $listB)
9770
    {
9771
        if ($listA['title'] == $listB['title']) {
9772
            return 0;
9773
        } elseif ($listA['title'] > $listB['title']) {
9774
            return 1;
9775
        } else {
9776
            return -1;
9777
        }
9778
    }
9779
}
9780