Passed
Push — 1.11.x ( a03758...1957a3 )
by
unknown
11:16
created

SessionManager   F

Complexity

Total Complexity 1290

Size/Duplication

Total Lines 10268
Duplicated Lines 0 %

Importance

Changes 5
Bugs 2 Features 0
Metric Value
wmc 1290
eloc 5301
c 5
b 2
f 0
dl 0
loc 10268
rs 0.8

147 Methods

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

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\Component\HTMLPurifier\Filter\RemoveOnAttributes;
6
use Chamilo\CoreBundle\Entity\Course;
7
use Chamilo\CoreBundle\Entity\ExtraField;
8
use Chamilo\CoreBundle\Entity\Repository\SequenceResourceRepository;
9
use Chamilo\CoreBundle\Entity\SequenceResource;
10
use Chamilo\CoreBundle\Entity\Session;
11
use Chamilo\CoreBundle\Entity\SessionRelCourse;
12
use Chamilo\CoreBundle\Entity\SessionRelCourseRelUser;
13
use Chamilo\CoreBundle\Entity\SessionRelUser;
14
use Chamilo\UserBundle\Entity\User;
15
use ExtraField as ExtraFieldModel;
16
use Monolog\Logger;
17
18
/**
19
 * Class SessionManager.
20
 *
21
 * This is the session library for Chamilo
22
 * (as in courses>session, not as in PHP session)
23
 * All main sessions functions should be placed here.
24
 * This class provides methods for sessions management.
25
 * Include/require it in your code to use its features.
26
 */
27
class SessionManager
28
{
29
    public const STATUS_PLANNED = 1;
30
    public const STATUS_PROGRESS = 2;
31
    public const STATUS_FINISHED = 3;
32
    public const STATUS_CANCELLED = 4;
33
34
    public static $_debug = false;
35
36
    /**
37
     * Constructor.
38
     */
39
    public function __construct()
40
    {
41
    }
42
43
    /**
44
     * Fetches a session from the database.
45
     *
46
     * @param int $id Session Id
47
     *
48
     * @return array Session details
49
     */
50
    public static function fetch($id)
51
    {
52
        $em = Database::getManager();
53
54
        if (empty($id)) {
55
            return [];
56
        }
57
58
        /** @var Session $session */
59
        $session = $em->find('ChamiloCoreBundle:Session', $id);
60
61
        if (!$session) {
0 ignored issues
show
introduced by
$session is of type Chamilo\CoreBundle\Entity\Session, thus it always evaluated to true.
Loading history...
62
            return [];
63
        }
64
65
        $result = [
66
            'id' => $session->getId(),
67
            'id_coach' => $session->getGeneralCoach() ? $session->getGeneralCoach()->getId() : null,
68
            'session_category_id' => $session->getCategory() ? $session->getCategory()->getId() : null,
69
            'name' => $session->getName(),
70
            'description' => $session->getDescription(),
71
            'show_description' => $session->getShowDescription(),
72
            'duration' => $session->getDuration(),
73
            'nbr_courses' => $session->getNbrCourses(),
74
            'nbr_users' => $session->getNbrUsers(),
75
            'nbr_classes' => $session->getNbrClasses(),
76
            'session_admin_id' => $session->getSessionAdminId(),
77
            'visibility' => $session->getVisibility(),
78
            'promotion_id' => $session->getPromotionId(),
79
            'display_start_date' => $session->getDisplayStartDate()
80
                ? $session->getDisplayStartDate()->format('Y-m-d H:i:s')
81
                : null,
82
            'display_end_date' => $session->getDisplayEndDate()
83
                ? $session->getDisplayEndDate()->format('Y-m-d H:i:s')
84
                : null,
85
            'access_start_date' => $session->getAccessStartDate()
86
                ? $session->getAccessStartDate()->format('Y-m-d H:i:s')
87
                : null,
88
            'access_end_date' => $session->getAccessEndDate()
89
                ? $session->getAccessEndDate()->format('Y-m-d H:i:s')
90
                : null,
91
            'coach_access_start_date' => $session->getCoachAccessStartDate()
92
                ? $session->getCoachAccessStartDate()->format('Y-m-d H:i:s')
93
                : null,
94
            'coach_access_end_date' => $session->getCoachAccessEndDate()
95
                ? $session->getCoachAccessEndDate()->format('Y-m-d H:i:s')
96
                : null,
97
            'send_subscription_notification' => $session->getSendSubscriptionNotification(),
98
        ];
99
100
        if (api_get_configuration_value('allow_session_status')) {
101
            $table = Database::get_main_table(TABLE_MAIN_SESSION);
102
            $sql = "SELECT status FROM $table WHERE id = $id";
103
            $resultQuery = Database::query($sql);
104
            $row = Database::fetch_array($resultQuery);
105
            $result['status'] = $row['status'];
106
            $result['status_label'] = self::getStatusLabel($row['status']);
107
        }
108
109
        // Converted to local values
110
        $variables = [
111
            'display_start_date',
112
            'display_end_date',
113
            'access_start_date',
114
            'access_end_date',
115
            'coach_access_start_date',
116
            'coach_access_end_date',
117
        ];
118
119
        foreach ($variables as $value) {
120
            $result[$value.'_to_local_time'] = null;
121
            if (!empty($result[$value])) {
122
                $result[$value.'_to_local_time'] = api_get_local_time($result[$value]);
123
            }
124
        }
125
126
        return $result;
127
    }
128
129
    /**
130
     * Create a session.
131
     *
132
     * @author Carlos Vargas <[email protected]>, from existing code
133
     *
134
     * @param string $name
135
     * @param string $startDate                    (YYYY-MM-DD hh:mm:ss)
136
     * @param string $endDate                      (YYYY-MM-DD hh:mm:ss)
137
     * @param string $displayStartDate             (YYYY-MM-DD hh:mm:ss)
138
     * @param string $displayEndDate               (YYYY-MM-DD hh:mm:ss)
139
     * @param string $coachStartDate               (YYYY-MM-DD hh:mm:ss)
140
     * @param string $coachEndDate                 (YYYY-MM-DD hh:mm:ss)
141
     * @param mixed  $coachId                      If int, this is the session coach id,
142
     *                                             if string, the coach ID will be looked for from the user table
143
     * @param int    $sessionCategoryId            ID of the session category in which this session is registered
144
     * @param int    $visibility                   Visibility after end date (0 = read-only, 1 = invisible, 2 =
145
     *                                             accessible)
146
     * @param bool   $fixSessionNameIfExists
147
     * @param string $duration
148
     * @param string $description                  Optional. The session description
149
     * @param int    $showDescription              Optional. Whether show the session description
150
     * @param array  $extraFields
151
     * @param int    $sessionAdminId               Optional. If this sessions was created by a session admin, assign it
152
     *                                             to him
153
     * @param bool   $sendSubscriptionNotification Optional.
154
     *                                             Whether send a mail notification to users being subscribed
155
     * @param int    $accessUrlId                  Optional.
156
     * @param int    $status
157
     *
158
     * @return mixed Session ID on success, error message otherwise
159
     *
160
     * @todo   use an array to replace all this parameters or use the model.lib.php ...
161
     */
162
    public static function create_session(
163
        $name,
164
        $startDate,
165
        $endDate,
166
        $displayStartDate,
167
        $displayEndDate,
168
        $coachStartDate,
169
        $coachEndDate,
170
        $coachId,
171
        $sessionCategoryId,
172
        $visibility = 1,
173
        $fixSessionNameIfExists = false,
174
        $duration = null,
175
        $description = null,
176
        $showDescription = 0,
177
        $extraFields = [],
178
        $sessionAdminId = 0,
179
        $sendSubscriptionNotification = false,
180
        $accessUrlId = 0,
181
        $status = 0
182
    ) {
183
        global $_configuration;
184
185
        // Check portal limits
186
        $accessUrlId = api_is_multiple_url_enabled()
187
            ? (empty($accessUrlId) ? api_get_current_access_url_id() : (int) $accessUrlId)
188
            : 1;
189
190
        if (isset($_configuration[$accessUrlId]) &&
191
            is_array($_configuration[$accessUrlId]) &&
192
            isset($_configuration[$accessUrlId]['hosting_limit_sessions']) &&
193
            $_configuration[$accessUrlId]['hosting_limit_sessions'] > 0
194
        ) {
195
            $num = self::count_sessions();
196
            if ($num >= $_configuration[$accessUrlId]['hosting_limit_sessions']) {
197
                api_warn_hosting_contact('hosting_limit_sessions');
198
199
                return get_lang('PortalSessionsLimitReached');
200
            }
201
        }
202
203
        $name = Database::escape_string(trim($name));
204
        $sessionCategoryId = (int) $sessionCategoryId;
205
        $visibility = (int) $visibility;
206
        $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
207
208
        $startDate = Database::escape_string($startDate);
209
        $endDate = Database::escape_string($endDate);
210
211
        if (empty($name)) {
212
            $msg = get_lang('SessionNameIsRequired');
213
214
            return $msg;
215
        } elseif (!empty($startDate) && !api_is_valid_date($startDate, 'Y-m-d H:i') &&
216
            !api_is_valid_date($startDate, 'Y-m-d H:i:s')
217
        ) {
218
            $msg = get_lang('InvalidStartDate');
219
220
            return $msg;
221
        } elseif (!empty($endDate) && !api_is_valid_date($endDate, 'Y-m-d H:i') &&
222
            !api_is_valid_date($endDate, 'Y-m-d H:i:s')
223
        ) {
224
            $msg = get_lang('InvalidEndDate');
225
226
            return $msg;
227
        } elseif (!empty($startDate) && !empty($endDate) && $startDate >= $endDate) {
228
            $msg = get_lang('StartDateShouldBeBeforeEndDate');
229
230
            return $msg;
231
        } else {
232
            $ready_to_create = false;
233
            if ($fixSessionNameIfExists) {
234
                $name = self::generateNextSessionName($name);
235
                if ($name) {
236
                    $ready_to_create = true;
237
                } else {
238
                    $msg = get_lang('SessionNameAlreadyExists');
239
240
                    return $msg;
241
                }
242
            } else {
243
                $rs = Database::query("SELECT 1 FROM $tbl_session WHERE name='".$name."'");
244
                if (Database::num_rows($rs)) {
245
                    $msg = get_lang('SessionNameAlreadyExists');
246
247
                    return $msg;
248
                }
249
                $ready_to_create = true;
250
            }
251
252
            if ($ready_to_create) {
253
                $sessionAdminId = !empty($sessionAdminId) ? $sessionAdminId : api_get_user_id();
254
                $values = [
255
                    'name' => $name,
256
                    'id_coach' => $coachId,
257
                    'session_admin_id' => $sessionAdminId,
258
                    'visibility' => $visibility,
259
                    'description' => $description,
260
                    'show_description' => $showDescription,
261
                    'send_subscription_notification' => (int) $sendSubscriptionNotification,
262
                ];
263
264
                if (!empty($startDate)) {
265
                    $values['access_start_date'] = api_get_utc_datetime($startDate);
266
                }
267
268
                if (!empty($endDate)) {
269
                    $values['access_end_date'] = api_get_utc_datetime($endDate);
270
                }
271
272
                if (!empty($displayStartDate)) {
273
                    $values['display_start_date'] = api_get_utc_datetime($displayStartDate);
274
                }
275
276
                if (!empty($displayEndDate)) {
277
                    $values['display_end_date'] = api_get_utc_datetime($displayEndDate);
278
                }
279
280
                if (!empty($coachStartDate)) {
281
                    $values['coach_access_start_date'] = api_get_utc_datetime($coachStartDate);
282
                }
283
                if (!empty($coachEndDate)) {
284
                    $values['coach_access_end_date'] = api_get_utc_datetime($coachEndDate);
285
                }
286
287
                if (!empty($sessionCategoryId)) {
288
                    $values['session_category_id'] = $sessionCategoryId;
289
                }
290
291
                if (api_get_configuration_value('allow_session_status')) {
292
                    $values['status'] = $status;
293
                }
294
295
                $session_id = Database::insert($tbl_session, $values);
296
                $duration = (int) $duration;
297
298
                if (!empty($duration)) {
299
                    $sql = "UPDATE $tbl_session SET
300
                        access_start_date = NULL,
301
                        access_end_date = NULL,
302
                        display_start_date = NULL,
303
                        display_end_date = NULL,
304
                        coach_access_start_date = NULL,
305
                        coach_access_end_date = NULL,
306
                        duration = $duration
307
                    WHERE id = $session_id";
308
                    Database::query($sql);
309
                } else {
310
                    $sql = "UPDATE $tbl_session
311
                        SET duration = 0
312
                        WHERE id = $session_id";
313
                    Database::query($sql);
314
                }
315
316
                if (!empty($session_id)) {
317
                    $extraFields['item_id'] = $session_id;
318
                    $sessionFieldValue = new ExtraFieldValue('session');
319
                    $sessionFieldValue->saveFieldValues($extraFields);
320
321
                    // Adding to the correct URL
322
                    UrlManager::add_session_to_url($session_id, $accessUrlId);
323
324
                    // add event to system log
325
                    Event::addEvent(
326
                        LOG_SESSION_CREATE,
327
                        LOG_SESSION_ID,
328
                        $session_id,
329
                        api_get_utc_datetime(),
330
                        api_get_user_id()
331
                    );
332
                }
333
334
                return $session_id;
335
            }
336
        }
337
    }
338
339
    /**
340
     * @param string $name
341
     *
342
     * @return bool
343
     */
344
    public static function sessionNameExists($name)
345
    {
346
        $name = Database::escape_string($name);
347
        $sql = "SELECT COUNT(*) as count FROM ".Database::get_main_table(TABLE_MAIN_SESSION)."
348
                WHERE name = '$name'";
349
        $result = Database::fetch_array(Database::query($sql));
350
351
        return $result['count'] > 0;
352
    }
353
354
    /**
355
     * @param string $where_condition
356
     *
357
     * @return mixed
358
     */
359
    public static function get_count_admin($where_condition = '')
360
    {
361
        $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
362
        $tbl_session_category = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
363
        $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
364
        $table_access_url_rel_session = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
365
        $tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
366
367
        $where = 'WHERE 1=1 ';
368
        $user_id = api_get_user_id();
369
        $extraJoin = '';
370
371
        if (api_is_session_admin() &&
372
            api_get_setting('allow_session_admins_to_manage_all_sessions') == 'false'
373
        ) {
374
            $where .= " AND (
375
                            s.session_admin_id = $user_id  OR
376
                            sru.user_id = '$user_id' AND
377
                            sru.relation_type = '".SESSION_RELATION_TYPE_RRHH."'
378
                            )
379
                      ";
380
381
            $extraJoin = " INNER JOIN $tbl_session_rel_user sru
382
                           ON sru.session_id = s.id ";
383
        }
384
385
        $today = api_get_utc_datetime();
386
        $today = api_strtotime($today, 'UTC');
387
        $today = date('Y-m-d', $today);
388
389
        if (!empty($where_condition)) {
390
            $where_condition = str_replace("(  session_active = ':'  )", '1=1', $where_condition);
391
392
            $where_condition = str_replace('category_name', 'sc.name', $where_condition);
393
            $where_condition = str_replace(
394
                ["AND session_active = '1'  )", " AND (  session_active = '1'  )"],
395
                [') GROUP BY s.name HAVING session_active = 1 ', " GROUP BY s.name HAVING session_active = 1 "],
396
                $where_condition
397
            );
398
            $where_condition = str_replace(
399
                ["AND session_active = '0'  )", " AND (  session_active = '0'  )"],
400
                [') GROUP BY s.name HAVING session_active = 0 ', " GROUP BY s.name HAVING session_active = '0' "],
401
                $where_condition
402
            );
403
        } else {
404
            $where_condition = " AND 1 = 1";
405
        }
406
407
        $courseCondition = null;
408
        if (strpos($where_condition, 'c.id')) {
409
            $table = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
410
            $tableCourse = Database::get_main_table(TABLE_MAIN_COURSE);
411
            $courseCondition = " INNER JOIN $table course_rel_session
412
                                 ON (s.id = course_rel_session.session_id)
413
                                 INNER JOIN $tableCourse c
414
                                 ON (course_rel_session.c_id = c.id)
415
                                ";
416
        }
417
418
        $sql = "SELECT COUNT(id) as total_rows FROM (
419
                SELECT DISTINCT
420
                 IF (
421
					(s.access_start_date <= '$today' AND '$today' <= s.access_end_date) OR
422
                    (s.access_start_date IS NULL AND s.access_end_date IS NULL ) OR
423
					(s.access_start_date <= '$today' AND s.access_end_date IS NULL) OR
424
					('$today' <= s.access_end_date AND s.access_start_date IS NULL)
425
				, 1, 0) as session_active,
426
                s.id
427
                FROM $tbl_session s
428
                LEFT JOIN $tbl_session_category sc
429
                ON s.session_category_id = sc.id
430
                INNER JOIN $tbl_user u
431
                ON s.id_coach = u.id
432
                $courseCondition
433
                $extraJoin
434
                $where $where_condition ) as session_table";
435
436
        if (api_is_multiple_url_enabled()) {
437
            $access_url_id = api_get_current_access_url_id();
438
            if ($access_url_id != -1) {
439
                $where .= " AND ar.access_url_id = $access_url_id ";
440
441
                $sql = "SELECT count(id) as total_rows FROM (
442
                SELECT DISTINCT
443
                  IF (
444
					(s.access_start_date <= '$today' AND '$today' <= s.access_end_date) OR
445
                    (s.access_start_date IS NULL AND s.access_end_date IS NULL) OR
446
					(s.access_start_date <= '$today' AND s.access_end_date IS NULL) OR
447
					('$today' <= s.access_end_date AND s.access_start_date IS NULL)
448
				, 1, 0)
449
				as session_active,
450
				s.id
451
                FROM $tbl_session s
452
                    LEFT JOIN  $tbl_session_category sc
453
                    ON s.session_category_id = sc.id
454
                    INNER JOIN $tbl_user u ON s.id_coach = u.user_id
455
                    INNER JOIN $table_access_url_rel_session ar
456
                    ON ar.session_id = s.id
457
                    $courseCondition
458
                    $extraJoin
459
                $where $where_condition) as session_table";
460
            }
461
        }
462
463
        $result_rows = Database::query($sql);
464
        $row = Database::fetch_array($result_rows);
465
        $num = $row['total_rows'];
466
467
        return $num;
468
    }
469
470
    /**
471
     * Get session list for a session admin or platform admin.
472
     *
473
     * @param int    $userId   User Id for the session admin.
474
     * @param array  $options  Order and limit keys.
475
     * @param bool   $getCount Whether to get all the results or only the count.
476
     * @param array  $columns  Columns from jqGrid.
477
     * @param string $listType
478
     *
479
     * @return array
480
     */
481
    public static function getSessionsForAdmin(
482
        $userId,
483
        $options = [],
484
        $getCount = false,
485
        $columns = [],
486
        $listType = 'all'
487
    ) {
488
        $tblSession = Database::get_main_table(TABLE_MAIN_SESSION);
489
        $sessionCategoryTable = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
490
491
        $where = 'WHERE 1 = 1 ';
492
493
        $userId = (int) $userId;
494
495
        if (!api_is_platform_admin() && !api_is_session_admin() && !api_is_teacher()) {
496
            api_not_allowed(true);
497
        }
498
499
        if (!api_is_platform_admin()) {
500
            if (api_is_session_admin() &&
501
                'false' === api_get_setting('allow_session_admins_to_manage_all_sessions')
502
            ) {
503
                $where .= " AND s.session_admin_id = $userId ";
504
            }
505
        }
506
507
        if (!api_is_platform_admin() &&
508
            api_is_teacher() &&
509
            'true' === api_get_setting('allow_teachers_to_create_sessions')
510
        ) {
511
            $where .= " AND s.id_coach = $userId ";
512
        }
513
514
        $extraFieldModel = new ExtraFieldModel('session');
515
        $conditions = $extraFieldModel->parseConditions($options);
516
517
        $sqlInjectJoins = $conditions['inject_joins'];
518
        $where .= $conditions['where'];
519
        $sqlInjectWhere = $conditions['inject_where'];
520
        $injectExtraFields = $conditions['inject_extra_fields'];
521
        $order = $conditions['order'];
522
        $limit = $conditions['limit'];
523
524
        $isMakingOrder = false;
525
        $showCountUsers = false;
526
527
        if (true === $getCount) {
528
            $select = ' SELECT count(DISTINCT s.id) as total_rows ';
529
        } else {
530
            if (!empty($columns['column_model'])) {
531
                foreach ($columns['column_model'] as $column) {
532
                    if ('users' == $column['name']) {
533
                        $showCountUsers = true;
534
                    }
535
                }
536
            }
537
538
            $select =
539
                "SELECT DISTINCT
540
                     s.name,
541
                     s.display_start_date,
542
                     s.display_end_date,
543
                     access_start_date,
544
                     access_end_date,
545
                     s.visibility,
546
                     s.session_category_id,
547
                     $injectExtraFields
548
                     s.id
549
             ";
550
551
            if ($showCountUsers) {
552
                $select .= ', count(su.user_id) users';
553
            }
554
555
            if (api_get_configuration_value('allow_session_status')) {
556
                $select .= ', status';
557
            }
558
559
            if (isset($options['order'])) {
560
                $isMakingOrder = 0 === strpos($options['order'], 'category_name');
561
            }
562
        }
563
564
        $isFilteringSessionCategory = strpos($where, 'category_name') !== false;
565
        $isFilteringSessionCategoryWithName = strpos($where, 'sc.name') !== false;
566
567
        if ($isMakingOrder || $isFilteringSessionCategory || $isFilteringSessionCategoryWithName) {
568
            $sqlInjectJoins .= " LEFT JOIN $sessionCategoryTable sc ON s.session_category_id = sc.id ";
569
570
            if ($isFilteringSessionCategory) {
571
                $where = str_replace('category_name', 'sc.name', $where);
572
            }
573
574
            if ($isMakingOrder) {
575
                $order = str_replace('category_name', 'sc.name', $order);
576
            }
577
        }
578
579
        if ($showCountUsers) {
580
            $tblSessionRelUser = Database::get_main_table(TABLE_MAIN_SESSION_USER);
581
            $sqlInjectJoins .= " LEFT JOIN $tblSessionRelUser su ON (su.session_id = s.id)";
582
        }
583
584
        $query = "$select FROM $tblSession s $sqlInjectJoins $where $sqlInjectWhere";
585
586
        if (api_is_multiple_url_enabled()) {
587
            $tblAccessUrlRelSession = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
588
            $accessUrlId = api_get_current_access_url_id();
589
590
            if ($accessUrlId != -1) {
591
                $where .= " AND ar.access_url_id = $accessUrlId ";
592
                $query = "$select
593
                    FROM $tblSession s $sqlInjectJoins
594
                    INNER JOIN $tblAccessUrlRelSession ar
595
                    ON (ar.session_id = s.id) $where";
596
            }
597
        }
598
599
        $date = api_get_utc_datetime();
600
601
        switch ($listType) {
602
            case 'all':
603
                break;
604
            case 'active':
605
                $query .= "AND (
606
                    (s.access_end_date IS NULL)
607
                    OR
608
                    (
609
                    s.access_start_date IS NOT NULL AND
610
                    s.access_end_date IS NOT NULL AND
611
                    s.access_start_date <= '$date' AND s.access_end_date >= '$date')
612
                    OR
613
                    (
614
                        s.access_start_date IS NULL AND
615
                        s.access_end_date IS NOT NULL AND
616
                        s.access_end_date >= '$date'
617
                    )
618
                )";
619
                break;
620
            case 'close':
621
                $query .= "AND (
622
                    (
623
                    s.access_start_date IS NOT NULL AND
624
                    s.access_end_date IS NOT NULL AND
625
                    s.access_start_date <= '$date' AND s.access_end_date <= '$date')
626
                    OR
627
                    (
628
                        s.access_start_date IS NULL AND
629
                        s.access_end_date IS NOT NULL AND
630
                        s.access_end_date <= '$date'
631
                    )
632
                )";
633
                break;
634
        }
635
636
        if ($showCountUsers) {
637
            $query .= ' GROUP by s.id';
638
        }
639
640
        $allowOrder = api_get_configuration_value('session_list_order');
641
642
        if ($allowOrder) {
643
            $order = ' ORDER BY position ASC';
644
        }
645
646
        $query .= $order;
647
        $query .= $limit;
648
        $result = Database::query($query);
649
650
        $sessions = Database::store_result($result, 'ASSOC');
651
652
        if ('all' === $listType) {
653
            if ($getCount) {
654
                return $sessions[0]['total_rows'];
655
            }
656
657
            return $sessions;
658
        }
659
660
        return $sessions;
661
    }
662
663
    /**
664
     * Gets the admin session list callback of the session/session_list.php page.
665
     *
666
     * @param array  $options           order and limit keys
667
     * @param bool   $getCount          Whether to get all the results or only the count
668
     * @param array  $columns
669
     * @param array  $extraFieldsToLoad
670
     * @param string $listType
671
     *
672
     * @return mixed Integer for number of rows, or array of results
673
     * @assert ([],true) !== false
674
     */
675
    public static function formatSessionsAdminForGrid(
676
        $options = [],
677
        $getCount = false,
678
        $columns = [],
679
        $extraFieldsToLoad = [],
680
        $listType = 'all'
681
    ) {
682
        $showCountUsers = false;
683
        if (!$getCount && !empty($columns['column_model'])) {
684
            foreach ($columns['column_model'] as $column) {
685
                if ('users' === $column['name']) {
686
                    $showCountUsers = true;
687
                }
688
            }
689
        }
690
691
        $userId = api_get_user_id();
692
        $sessions = self::getSessionsForAdmin($userId, $options, $getCount, $columns, $listType);
693
        if ($getCount) {
694
            return (int) $sessions;
695
        }
696
697
        $formattedSessions = [];
698
        $categories = self::get_all_session_category();
699
        $orderedCategories = [];
700
        if (!empty($categories)) {
701
            foreach ($categories as $category) {
702
                $orderedCategories[$category['id']] = $category['name'];
703
            }
704
        }
705
706
        $activeIcon = Display::return_icon('accept.png', get_lang('Active'));
707
        $inactiveIcon = Display::return_icon('error.png', get_lang('Inactive'));
708
        $webPath = api_get_path(WEB_PATH);
709
710
        foreach ($sessions as $session) {
711
            if ($showCountUsers) {
712
                $session['users'] = self::get_users_by_session($session['id'], 0, true);
713
            }
714
            $url = $webPath.'main/session/resume_session.php?id_session='.$session['id'];
715
            if ($extraFieldsToLoad || api_is_drh()) {
716
                $url = $webPath.'session/'.$session['id'].'/about/';
717
            }
718
719
            $session['name'] = Display::url($session['name'], $url);
720
721
            if (!empty($extraFieldsToLoad)) {
722
                foreach ($extraFieldsToLoad as $field) {
723
                    $extraFieldValue = new ExtraFieldValue('session');
724
                    $fieldData = $extraFieldValue->getAllValuesByItemAndField(
725
                        $session['id'],
726
                        $field['id']
727
                    );
728
                    $fieldDataArray = [];
729
                    $fieldDataToString = '';
730
                    if (!empty($fieldData)) {
731
                        foreach ($fieldData as $data) {
732
                            $fieldDataArray[] = $data['value'];
733
                        }
734
                        $fieldDataToString = implode(', ', $fieldDataArray);
735
                    }
736
                    $session[$field['variable']] = $fieldDataToString;
737
                }
738
            }
739
            if (isset($session['session_active']) && $session['session_active'] == 1) {
740
                $session['session_active'] = $activeIcon;
741
            } else {
742
                $session['session_active'] = $inactiveIcon;
743
            }
744
745
            $session = self::convert_dates_to_local($session, true);
746
747
            switch ($session['visibility']) {
748
                case SESSION_VISIBLE_READ_ONLY: //1
749
                    $session['visibility'] = get_lang('ReadOnly');
750
                    break;
751
                case SESSION_VISIBLE:           //2
752
                case SESSION_AVAILABLE:         //4
753
                    $session['visibility'] = get_lang('Visible');
754
                    break;
755
                case SESSION_INVISIBLE:         //3
756
                    $session['visibility'] = api_ucfirst(get_lang('Invisible'));
757
                    break;
758
            }
759
760
            // Cleaning double selects.
761
            foreach ($session as $key => &$value) {
762
                if (isset($optionsByDouble[$key]) || isset($optionsByDouble[$key.'_second'])) {
763
                    $options = explode('::', $value);
764
                }
765
                $original_key = $key;
766
                if (strpos($key, '_second') !== false) {
767
                    $key = str_replace('_second', '', $key);
768
                }
769
770
                if (isset($optionsByDouble[$key]) &&
771
                    isset($options[0]) &&
772
                    isset($optionsByDouble[$key][$options[0]])
773
                ) {
774
                    if (strpos($original_key, '_second') === false) {
775
                        $value = $optionsByDouble[$key][$options[0]]['option_display_text'];
776
                    } else {
777
                        $value = $optionsByDouble[$key][$options[1]]['option_display_text'];
778
                    }
779
                }
780
            }
781
782
            $categoryName = isset($orderedCategories[$session['session_category_id']]) ? $orderedCategories[$session['session_category_id']] : '';
783
            $session['category_name'] = $categoryName;
784
            if (isset($session['status'])) {
785
                $session['status'] = self::getStatusLabel($session['status']);
786
            }
787
788
            $formattedSessions[] = $session;
789
        }
790
791
        return $formattedSessions;
792
    }
793
794
    /**
795
     * Gets the progress of learning paths in the given session.
796
     *
797
     * @param int    $sessionId
798
     * @param int    $courseId
799
     * @param string $date_from
800
     * @param string $date_to
801
     * @param array options order and limit keys
802
     *
803
     * @return array table with user name, lp name, progress
804
     */
805
    public static function get_session_lp_progress(
806
        $sessionId,
807
        $courseId,
808
        $date_from,
809
        $date_to,
810
        $options
811
    ) {
812
        //escaping vars
813
        $sessionId = $sessionId === 'T' ? 'T' : intval($sessionId);
814
        $courseId = intval($courseId);
815
816
        //tables
817
        $session_course_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
818
        $user = Database::get_main_table(TABLE_MAIN_USER);
819
        $tbl_course_lp_view = Database::get_course_table(TABLE_LP_VIEW);
820
821
        $course = api_get_course_info_by_id($courseId);
822
        $sessionCond = 'and session_id = %s';
823
        if ($sessionId === 'T') {
824
            $sessionCond = '';
825
        }
826
827
        $where = " WHERE c_id = '%s' AND s.status <> 2 $sessionCond";
828
829
        $limit = null;
830
        if (!empty($options['limit'])) {
831
            $limit = " LIMIT ".$options['limit'];
832
        }
833
834
        if (!empty($options['where'])) {
835
            $where .= ' '.$options['where'];
836
        }
837
838
        $order = null;
839
        if (!empty($options['order'])) {
840
            $order = " ORDER BY ".$options['order']." ";
841
        }
842
843
        $sql = "SELECT u.id as user_id, u.lastname, u.firstname, u.username, u.email, s.c_id
844
                FROM $session_course_user s
845
                INNER JOIN $user u ON u.id = s.user_id
846
                $where
847
                $order
848
                $limit";
849
850
        $sql_query = sprintf($sql, Database::escape_string($course['real_id']), $sessionId);
851
852
        $rs = Database::query($sql_query);
853
        while ($user = Database::fetch_array($rs)) {
854
            $users[$user['user_id']] = $user;
855
        }
856
857
        // Get lessons
858
        $lessons = LearnpathList::get_course_lessons($course['code'], $sessionId);
859
860
        $table = [];
861
        foreach ($users as $user) {
862
            $data = [
863
                'lastname' => $user[1],
864
                'firstname' => $user[2],
865
                'username' => $user[3],
866
            ];
867
868
            $sessionCond = 'AND v.session_id = %d';
869
            if ($sessionId == 'T') {
870
                $sessionCond = "";
871
            }
872
873
            //Get lessons progress by user
874
            $sql = "SELECT v.lp_id as id, v.progress
875
                    FROM  $tbl_course_lp_view v
876
                    WHERE v.c_id = %d
877
                    AND v.user_id = %d
878
            $sessionCond";
879
880
            $sql_query = sprintf(
881
                $sql,
882
                intval($courseId),
883
                intval($user['user_id']),
884
                $sessionId
885
            );
886
887
            $result = Database::query($sql_query);
888
889
            $user_lessons = [];
890
            while ($row = Database::fetch_array($result)) {
891
                $user_lessons[$row['id']] = $row;
892
            }
893
894
            //Match course lessons with user progress
895
            $progress = 0;
896
            $count = 0;
897
            foreach ($lessons as $lesson) {
898
                $data[$lesson['id']] = (!empty($user_lessons[$lesson['id']]['progress'])) ? $user_lessons[$lesson['id']]['progress'] : 0;
899
                $progress += $data[$lesson['id']];
900
                $data[$lesson['id']] = $data[$lesson['id']].'%';
901
                $count++;
902
            }
903
            if ($count == 0) {
904
                $data['total'] = 0;
905
            } else {
906
                $data['total'] = round($progress / $count, 2).'%';
907
            }
908
            $table[] = $data;
909
        }
910
911
        return $table;
912
    }
913
914
    /**
915
     * Gets the survey answers.
916
     *
917
     * @param int $sessionId
918
     * @param int $courseId
919
     * @param int $surveyId
920
     * @param array options order and limit keys
921
     *
922
     * @todo fix the query
923
     *
924
     * @return array table with user name, lp name, progress
925
     */
926
    public static function get_survey_overview(
927
        $sessionId,
928
        $courseId,
929
        $surveyId,
930
        $date_from,
931
        $date_to,
932
        $options
933
    ) {
934
        //escaping vars
935
        $sessionId = intval($sessionId);
936
        $courseId = intval($courseId);
937
        $surveyId = intval($surveyId);
938
939
        //tables
940
        $session_course_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
941
        $user = Database::get_main_table(TABLE_MAIN_USER);
942
        $c_survey = Database::get_course_table(TABLE_SURVEY);
943
        $c_survey_answer = Database::get_course_table(TABLE_SURVEY_ANSWER);
944
        $c_survey_question = Database::get_course_table(TABLE_SURVEY_QUESTION);
945
        $c_survey_question_option = Database::get_course_table(TABLE_SURVEY_QUESTION_OPTION);
946
947
        $course = api_get_course_info_by_id($courseId);
948
949
        $where = " WHERE c_id = '%s' AND s.status <> 2 AND session_id = %s";
950
951
        $limit = null;
952
        if (!empty($options['limit'])) {
953
            $limit = " LIMIT ".$options['limit'];
954
        }
955
956
        if (!empty($options['where'])) {
957
            $where .= ' '.$options['where'];
958
        }
959
960
        $order = null;
961
        if (!empty($options['order'])) {
962
            $order = " ORDER BY ".$options['order'];
963
        }
964
965
        $sql = "SELECT u.user_id, u.lastname, u.firstname, u.username, u.email, s.c_id
966
                FROM $session_course_user s
967
                INNER JOIN $user u ON u.user_id = s.user_id
968
                $where $order $limit";
969
970
        $sql_query = sprintf($sql, intval($course['real_id']), $sessionId);
971
        $rs = Database::query($sql_query);
972
        while ($user = Database::fetch_array($rs)) {
973
            $users[$user['user_id']] = $user;
974
        }
975
976
        //Get survey questions
977
        $questions = SurveyManager::get_questions($surveyId, $courseId);
978
979
        //Survey is anonymous?
980
        $result = Database::query(sprintf("SELECT anonymous FROM $c_survey WHERE survey_id = %d", $surveyId));
981
        $row = Database::fetch_array($result);
982
        $anonymous = ($row['anonymous'] == 1) ? true : false;
983
984
        $table = [];
985
        foreach ($users as $user) {
986
            $data = [
987
                'lastname' => ($anonymous ? '***' : $user[1]),
988
                'firstname' => ($anonymous ? '***' : $user[2]),
989
                'username' => ($anonymous ? '***' : $user[3]),
990
            ];
991
992
            //Get questions by user
993
            $sql = "SELECT sa.question_id, sa.option_id, sqo.option_text, sq.type
994
                    FROM $c_survey_answer sa
995
                    INNER JOIN $c_survey_question sq
996
                    ON sq.question_id = sa.question_id
997
                    LEFT JOIN $c_survey_question_option sqo
998
                    ON
999
                      sqo.c_id = sa.c_id AND
1000
                      sqo.question_id = sq.question_id AND
1001
                      sqo.question_option_id = sa.option_id AND
1002
                      sqo.survey_id = sq.survey_id
1003
                    WHERE
1004
                      sa.survey_id = %d AND
1005
                      sa.c_id = %d AND
1006
                      sa.user = %d
1007
            "; //. $where_survey;
1008
            $sql_query = sprintf($sql, $surveyId, $courseId, $user['user_id']);
1009
1010
            $result = Database::query($sql_query);
1011
1012
            $user_questions = [];
1013
            while ($row = Database::fetch_array($result)) {
1014
                $user_questions[$row['question_id']] = $row;
1015
            }
1016
1017
            //Match course lessons with user progress
1018
            foreach ($questions as $question_id => $question) {
1019
                $option_text = 'option_text';
1020
                if ($user_questions[$question_id]['type'] == 'open') {
1021
                    $option_text = 'option_id';
1022
                }
1023
                $data[$question_id] = $user_questions[$question_id][$option_text];
1024
            }
1025
1026
            $table[] = $data;
1027
        }
1028
1029
        return $table;
1030
    }
1031
1032
    /**
1033
     * Gets the progress of the given session.
1034
     *
1035
     * @param int $sessionId
1036
     * @param int $courseId
1037
     * @param array options order and limit keys
1038
     *
1039
     * @return array table with user name, lp name, progress
1040
     */
1041
    public static function get_session_progress(
1042
        $sessionId,
1043
        $courseId,
1044
        $date_from,
1045
        $date_to,
1046
        $options
1047
    ) {
1048
        $sessionId = (int) $sessionId;
1049
1050
        $getAllSessions = false;
1051
        if (empty($sessionId)) {
1052
            $sessionId = 0;
1053
            $getAllSessions = true;
1054
        }
1055
1056
        //tables
1057
        $session_course_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
1058
        $user = Database::get_main_table(TABLE_MAIN_USER);
1059
        $workTable = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
1060
        $workTableAssignment = Database::get_course_table(TABLE_STUDENT_PUBLICATION_ASSIGNMENT);
1061
        $tbl_course_lp = Database::get_course_table(TABLE_LP_MAIN);
1062
        $wiki = Database::get_course_table(TABLE_WIKI);
1063
        $table_stats_default = Database::get_main_table(TABLE_STATISTIC_TRACK_E_DEFAULT);
1064
        $table_stats_access = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ACCESS);
1065
1066
        $course = api_get_course_info_by_id($courseId);
1067
        $where = " WHERE c_id = '%s' AND s.status <> 2 ";
1068
1069
        $limit = null;
1070
        if (!empty($options['limit'])) {
1071
            $limit = " LIMIT ".$options['limit'];
1072
        }
1073
1074
        if (!empty($options['where'])) {
1075
            $where .= ' '.$options['where'];
1076
        }
1077
1078
        $order = null;
1079
        if (!empty($options['order'])) {
1080
            $order = " ORDER BY ".$options['order'];
1081
        }
1082
1083
        //TODO, fix create report without session
1084
        $queryVariables = [$course['real_id']];
1085
        if (!empty($sessionId)) {
1086
            $where .= ' AND session_id = %s';
1087
            $queryVariables[] = $sessionId;
1088
            $sql = "SELECT
1089
                        u.user_id, u.lastname, u.firstname, u.username,
1090
                        u.email, s.c_id, s.session_id
1091
                    FROM $session_course_user s
1092
                    INNER JOIN $user u
1093
                    ON u.user_id = s.user_id
1094
                    $where $order $limit";
1095
        } else {
1096
            $sql = "SELECT
1097
                        u.user_id, u.lastname, u.firstname, u.username,
1098
                        u.email, s.c_id, s.session_id
1099
                    FROM $session_course_user s
1100
                    INNER JOIN $user u ON u.user_id = s.user_id
1101
                    $where $order $limit";
1102
        }
1103
1104
        $sql_query = vsprintf($sql, $queryVariables);
1105
        $rs = Database::query($sql_query);
1106
        while ($user = Database::fetch_array($rs)) {
1107
            $users[$user['user_id']] = $user;
1108
        }
1109
1110
        /**
1111
         *  Lessons.
1112
         */
1113
        $sql = "SELECT * FROM $tbl_course_lp WHERE c_id = %s "; //AND session_id = %s
1114
        $sql_query = sprintf($sql, $course['real_id']);
1115
        $result = Database::query($sql_query);
1116
        $arrLesson = [[]];
1117
        while ($row = Database::fetch_array($result)) {
1118
            if (empty($arrLesson[$row['session_id']]['lessons_total'])) {
1119
                $arrLesson[$row['session_id']]['lessons_total'] = 1;
1120
            } else {
1121
                $arrLesson[$row['session_id']]['lessons_total']++;
1122
            }
1123
        }
1124
1125
        /**
1126
         *  Exercises.
1127
         */
1128
        $exercises = ExerciseLib::get_all_exercises(
1129
            $course,
1130
            $sessionId,
1131
            false,
1132
            '',
1133
            $getAllSessions
1134
        );
1135
        $exercises_total = count($exercises);
1136
1137
        /**
1138
         *  Assignments.
1139
         */
1140
        //total
1141
        $params = [$course['real_id']];
1142
        if ($getAllSessions) {
1143
            $sql = "SELECT count(w.id) as count
1144
                    FROM $workTable w
1145
                    LEFT JOIN $workTableAssignment a
1146
                    ON (a.publication_id = w.id AND a.c_id = w.c_id)
1147
                    WHERE
1148
                        w.c_id = %s AND
1149
                        parent_id = 0 AND
1150
                        active IN (1, 0)";
1151
        } else {
1152
            $sql = "SELECT count(w.id) as count
1153
                    FROM $workTable w
1154
                    LEFT JOIN $workTableAssignment a
1155
                    ON (a.publication_id = w.id AND a.c_id = w.c_id)
1156
                    WHERE
1157
                        w.c_id = %s AND
1158
                        parent_id = 0 AND
1159
                        active IN (1, 0)";
1160
1161
            if (empty($sessionId)) {
1162
                $sql .= ' AND w.session_id = NULL ';
1163
            } else {
1164
                $sql .= ' AND w.session_id = %s ';
1165
                $params[] = $sessionId;
1166
            }
1167
        }
1168
1169
        $sql_query = vsprintf($sql, $params);
1170
        $result = Database::query($sql_query);
1171
        $row = Database::fetch_array($result);
1172
        $assignments_total = $row['count'];
1173
1174
        /**
1175
         * Wiki.
1176
         */
1177
        if ($getAllSessions) {
1178
            $sql = "SELECT count(distinct page_id)  as count FROM $wiki
1179
                    WHERE c_id = %s";
1180
        } else {
1181
            $sql = "SELECT count(distinct page_id)  as count FROM $wiki
1182
                    WHERE c_id = %s and session_id = %s";
1183
        }
1184
        $sql_query = sprintf($sql, $course['real_id'], $sessionId);
1185
        $result = Database::query($sql_query);
1186
        $row = Database::fetch_array($result);
1187
        $wiki_total = $row['count'];
1188
1189
        /**
1190
         * Surveys.
1191
         */
1192
        $survey_user_list = [];
1193
        $survey_list = SurveyManager::get_surveys($course['code'], $sessionId);
1194
1195
        $surveys_total = count($survey_list);
1196
        foreach ($survey_list as $survey) {
1197
            $user_list = SurveyManager::get_people_who_filled_survey(
1198
                $survey['survey_id'],
1199
                false,
1200
                $course['real_id']
1201
            );
1202
            foreach ($user_list as $user_id) {
1203
                isset($survey_user_list[$user_id]) ? $survey_user_list[$user_id]++ : $survey_user_list[$user_id] = 1;
1204
            }
1205
        }
1206
1207
        /**
1208
         * Forums.
1209
         */
1210
        $forums_total = CourseManager::getCountForum(
1211
            $course['real_id'],
1212
            $sessionId,
1213
            $getAllSessions
1214
        );
1215
1216
        //process table info
1217
        foreach ($users as $user) {
1218
            //Course description
1219
            $sql = "SELECT count(*) as count
1220
                    FROM $table_stats_access
1221
                    WHERE access_tool = 'course_description'
1222
                    AND c_id = '%s'
1223
                    AND access_session_id = %s
1224
                    AND access_user_id = %s ";
1225
            $sql_query = sprintf($sql, $course['real_id'], $user['id_session'], $user['user_id']);
1226
1227
            $result = Database::query($sql_query);
1228
            $row = Database::fetch_array($result);
1229
            $course_description_progress = ($row['count'] > 0) ? 100 : 0;
1230
1231
            if (!empty($arrLesson[$user['id_session']]['lessons_total'])) {
1232
                $lessons_total = $arrLesson[$user['id_session']]['lessons_total'];
1233
            } else {
1234
                $lessons_total = !empty($arrLesson[0]['lessons_total']) ? $arrLesson[0]['lessons_total'] : 0;
1235
            }
1236
1237
            //Lessons
1238
            //TODO: Lessons done and left is calculated by progress per item in lesson, maybe we should calculate it only per completed lesson?
1239
            $lessons_progress = Tracking::get_avg_student_progress(
1240
                $user['user_id'],
1241
                $course['code'],
1242
                [],
1243
                $user['id_session']
1244
            );
1245
            $lessons_done = ($lessons_progress * $lessons_total) / 100;
1246
            $lessons_left = $lessons_total - $lessons_done;
1247
1248
            // Exercises
1249
            $exercises_progress = str_replace(
1250
                '%',
1251
                '',
1252
                Tracking::get_exercise_student_progress(
1253
                    $exercises,
1254
                    $user['user_id'],
1255
                    $course['real_id'],
1256
                    $user['id_session']
1257
                )
1258
            );
1259
            $exercises_done = round(($exercises_progress * $exercises_total) / 100);
1260
            $exercises_left = $exercises_total - $exercises_done;
1261
1262
            //Assignments
1263
            $assignments_done = Tracking::count_student_assignments($user['user_id'], $course['code'], $user['id_session']);
1264
            $assignments_left = $assignments_total - $assignments_done;
1265
            if (!empty($assignments_total)) {
1266
                $assignments_progress = round((($assignments_done * 100) / $assignments_total), 2);
1267
            } else {
1268
                $assignments_progress = 0;
1269
            }
1270
1271
            // Wiki
1272
            // total revisions per user
1273
            $sql = "SELECT count(*) as count
1274
                    FROM $wiki
1275
                    WHERE c_id = %s and session_id = %s and user_id = %s";
1276
            $sql_query = sprintf($sql, $course['real_id'], $user['id_session'], $user['user_id']);
1277
            $result = Database::query($sql_query);
1278
            $row = Database::fetch_array($result);
1279
            $wiki_revisions = $row['count'];
1280
            //count visited wiki pages
1281
            $sql = "SELECT count(distinct default_value) as count
1282
                    FROM $table_stats_default
1283
                    WHERE
1284
                        default_user_id = %s AND
1285
                        default_event_type = 'wiki_page_view' AND
1286
                        default_value_type = 'wiki_page_id' AND
1287
                        c_id = %s
1288
                    ";
1289
            $sql_query = sprintf($sql, $user['user_id'], $course['real_id']);
1290
            $result = Database::query($sql_query);
1291
            $row = Database::fetch_array($result);
1292
1293
            $wiki_read = $row['count'];
1294
            $wiki_unread = $wiki_total - $wiki_read;
1295
            if (!empty($wiki_total)) {
1296
                $wiki_progress = round((($wiki_read * 100) / $wiki_total), 2);
1297
            } else {
1298
                $wiki_progress = 0;
1299
            }
1300
1301
            //Surveys
1302
            $surveys_done = (isset($survey_user_list[$user['user_id']]) ? $survey_user_list[$user['user_id']] : 0);
1303
            $surveys_left = $surveys_total - $surveys_done;
1304
            if (!empty($surveys_total)) {
1305
                $surveys_progress = round((($surveys_done * 100) / $surveys_total), 2);
1306
            } else {
1307
                $surveys_progress = 0;
1308
            }
1309
1310
            //Forums
1311
            $forums_done = CourseManager::getCountForumPerUser(
1312
                $user['user_id'],
1313
                $course['real_id'],
1314
                $user['id_session']
1315
            );
1316
            $forums_left = $forums_total - $forums_done;
1317
            if (!empty($forums_total)) {
1318
                $forums_progress = round((($forums_done * 100) / $forums_total), 2);
1319
            } else {
1320
                $forums_progress = 0;
1321
            }
1322
1323
            // Overall Total
1324
            $overall_total = ($course_description_progress + $exercises_progress + $forums_progress + $assignments_progress + $wiki_progress + $surveys_progress) / 6;
1325
1326
            $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>';
1327
            $linkForum = '<a href="'.api_get_path(WEB_CODE_PATH).'forum/index.php?cidReq='.$course['code'].'&id_session='.$user['id_session'].'"> %s </a>';
1328
            $linkWork = '<a href="'.api_get_path(WEB_CODE_PATH).'work/work.php?cidReq='.$course['code'].'&id_session='.$user['id_session'].'"> %s </a>';
1329
            $linkWiki = '<a href="'.api_get_path(WEB_CODE_PATH).'wiki/index.php?cidReq='.$course['code'].'&session_id='.$user['id_session'].'&action=statistics"> %s </a>';
1330
            $linkSurvey = '<a href="'.api_get_path(WEB_CODE_PATH).'survey/survey_list.php?cidReq='.$course['code'].'&id_session='.$user['id_session'].'"> %s </a>';
1331
1332
            $table[] = [
1333
                'lastname' => $user[1],
1334
                'firstname' => $user[2],
1335
                'username' => $user[3],
1336
                //'profile'   => '',
1337
                'total' => round($overall_total, 2).'%',
1338
                'courses' => sprintf($link, $course_description_progress.'%'),
1339
                'lessons' => sprintf($link, $lessons_progress.'%'),
1340
                'exercises' => sprintf($link, $exercises_progress.'%'),
1341
                'forums' => sprintf($link, $forums_progress.'%'),
1342
                'homeworks' => sprintf($link, $assignments_progress.'%'),
1343
                'wikis' => sprintf($link, $wiki_progress.'%'),
1344
                'surveys' => sprintf($link, $surveys_progress.'%'),
1345
                //course description
1346
                'course_description_progress' => $course_description_progress.'%',
1347
                //lessons
1348
                'lessons_total' => sprintf($link, $lessons_total),
1349
                'lessons_done' => sprintf($link, $lessons_done),
1350
                'lessons_left' => sprintf($link, $lessons_left),
1351
                'lessons_progress' => sprintf($link, $lessons_progress.'%'),
1352
                //exercises
1353
                'exercises_total' => sprintf($link, $exercises_total),
1354
                'exercises_done' => sprintf($link, $exercises_done),
1355
                'exercises_left' => sprintf($link, $exercises_left),
1356
                'exercises_progress' => sprintf($link, $exercises_progress.'%'),
1357
                //forums
1358
                'forums_total' => sprintf($linkForum, $forums_total),
1359
                'forums_done' => sprintf($linkForum, $forums_done),
1360
                'forums_left' => sprintf($linkForum, $forums_left),
1361
                'forums_progress' => sprintf($linkForum, $forums_progress.'%'),
1362
                //assignments
1363
                'assignments_total' => sprintf($linkWork, $assignments_total),
1364
                'assignments_done' => sprintf($linkWork, $assignments_done),
1365
                'assignments_left' => sprintf($linkWork, $assignments_left),
1366
                'assignments_progress' => sprintf($linkWork, $assignments_progress.'%'),
1367
                //wiki
1368
                'wiki_total' => sprintf($linkWiki, $wiki_total),
1369
                'wiki_revisions' => sprintf($linkWiki, $wiki_revisions),
1370
                'wiki_read' => sprintf($linkWiki, $wiki_read),
1371
                'wiki_unread' => sprintf($linkWiki, $wiki_unread),
1372
                'wiki_progress' => sprintf($linkWiki, $wiki_progress.'%'),
1373
                //survey
1374
                'surveys_total' => sprintf($linkSurvey, $surveys_total),
1375
                'surveys_done' => sprintf($linkSurvey, $surveys_done),
1376
                'surveys_left' => sprintf($linkSurvey, $surveys_left),
1377
                'surveys_progress' => sprintf($linkSurvey, $surveys_progress.'%'),
1378
            ];
1379
        }
1380
1381
        return $table;
1382
    }
1383
1384
    /**
1385
     * Get the ip, total of clicks, login date and time logged in for all user, in one session.
1386
     *
1387
     * @todo track_e_course_access table should have ip so we dont have to look for it in track_e_login
1388
     *
1389
     * @author César Perales <[email protected]>, Beeznest Team
1390
     *
1391
     * @version 1.9.6
1392
     */
1393
    public static function get_user_data_access_tracking_overview(
1394
        $sessionId,
1395
        $courseId = 0,
1396
        $studentId = 0,
1397
        $profile = '',
1398
        $date_from = '',
1399
        $date_to = '',
1400
        $options = []
1401
    ) {
1402
        $sessionId = intval($sessionId);
1403
        $courseId = intval($courseId);
1404
        $studentId = intval($studentId);
1405
        $profile = intval($profile);
1406
        $date_from = Database::escape_string($date_from);
1407
        $date_to = Database::escape_string($date_to);
1408
1409
        // database table definition
1410
        $user = Database::get_main_table(TABLE_MAIN_USER);
1411
        $course = Database::get_main_table(TABLE_MAIN_COURSE);
1412
        $track_e_login = Database::get_main_table(TABLE_STATISTIC_TRACK_E_LOGIN);
1413
        $track_e_course_access = Database::get_main_table(TABLE_STATISTIC_TRACK_E_COURSE_ACCESS);
1414
        $sessionTable = Database::get_main_table(TABLE_MAIN_SESSION);
1415
1416
        global $export_csv;
1417
        if ($export_csv) {
1418
            $is_western_name_order = api_is_western_name_order(PERSON_NAME_DATA_EXPORT);
1419
        } else {
1420
            $is_western_name_order = api_is_western_name_order();
1421
        }
1422
1423
        $where = null;
1424
        if (isset($sessionId) && !empty($sessionId)) {
1425
            $where = sprintf(" WHERE a.session_id = %d", $sessionId);
1426
        }
1427
        if (isset($courseId) && !empty($courseId)) {
1428
            $where .= sprintf(" AND c.id = %d", $courseId);
1429
        }
1430
        if (isset($studentId) && !empty($studentId)) {
1431
            $where .= sprintf(" AND u.user_id = %d", $studentId);
1432
        }
1433
        if (isset($profile) && !empty($profile)) {
1434
            $where .= sprintf(" AND u.status = %d", $profile);
1435
        }
1436
        if (!empty($date_to) && !empty($date_from)) {
1437
            $where .= sprintf(
1438
                " AND a.login_course_date >= '%s 00:00:00'
1439
                 AND a.login_course_date <= '%s 23:59:59'",
1440
                $date_from,
1441
                $date_to
1442
            );
1443
        }
1444
1445
        $limit = null;
1446
        if (!empty($options['limit'])) {
1447
            $limit = " LIMIT ".$options['limit'];
1448
        }
1449
1450
        if (!empty($options['where'])) {
1451
            $where .= ' '.$options['where'];
1452
        }
1453
1454
        $order = null;
1455
        if (!empty($options['order'])) {
1456
            $order = " ORDER BY ".$options['order'];
1457
        }
1458
1459
        //TODO add course name
1460
        $sql = "SELECT
1461
                a.login_course_date ,
1462
                u.username ,
1463
                ".($is_western_name_order ? "
1464
                    u.firstname,
1465
                    u.lastname,
1466
                    " : "
1467
                    u.lastname,
1468
                    u.firstname,
1469
                ")."
1470
                a.logout_course_date,
1471
                a.counter,
1472
                c.title,
1473
                c.code,
1474
                u.user_id,
1475
                a.session_id
1476
            FROM $track_e_course_access a
1477
            INNER JOIN $user u ON a.user_id = u.user_id
1478
            INNER JOIN $course c ON a.c_id = c.id
1479
            $where $order $limit";
1480
        $result = Database::query(sprintf($sql, $sessionId, $courseId));
1481
1482
        $data = [];
1483
        while ($user = Database::fetch_assoc($result)) {
1484
            $data[] = $user;
1485
        }
1486
1487
        foreach ($data as $key => $info) {
1488
            $sql = "SELECT
1489
                    name
1490
                    FROM $sessionTable
1491
                    WHERE
1492
                    id = {$info['session_id']}";
1493
            $result = Database::query($sql);
1494
            $session = Database::fetch_assoc($result);
1495
1496
            // building array to display
1497
            $return[] = [
1498
                'user_id' => $info['user_id'],
1499
                'logindate' => $info['login_course_date'],
1500
                'username' => $info['username'],
1501
                'firstname' => $info['firstname'],
1502
                'lastname' => $info['lastname'],
1503
                'clicks' => $info['counter'], //+ $clicks[$info['user_id']],
1504
                'ip' => '',
1505
                'timeLoggedIn' => gmdate("H:i:s", strtotime($info['logout_course_date']) - strtotime($info['login_course_date'])),
1506
                'session' => $session['name'],
1507
            ];
1508
        }
1509
1510
        foreach ($return as $key => $info) {
1511
            //Search for ip, we do less querys if we iterate the final array
1512
            $sql = sprintf(
1513
                "SELECT user_ip FROM $track_e_login WHERE login_user_id = %d AND login_date < '%s' ORDER BY login_date DESC LIMIT 1",
1514
                $info['user_id'],
1515
                $info['logindate']
1516
            ); //TODO add select by user too
1517
            $result = Database::query($sql);
1518
            $ip = Database::fetch_assoc($result);
1519
            //if no ip founded, we search the closest higher ip
1520
            if (empty($ip['user_ip'])) {
1521
                $sql = sprintf(
1522
                    "SELECT user_ip FROM $track_e_login WHERE login_user_id = %d AND login_date > '%s'  ORDER BY login_date ASC LIMIT 1",
1523
                    $info['user_id'],
1524
                    $info['logindate']
1525
                ); //TODO add select by user too
1526
                $result = Database::query($sql);
1527
                $ip = Database::fetch_assoc($result);
1528
            }
1529
            //add ip to final array
1530
            $return[$key]['ip'] = $ip['user_ip'];
1531
        }
1532
1533
        return $return;
1534
    }
1535
1536
    /**
1537
     * Creates a new course code based in given code.
1538
     *
1539
     * @param string $session_name
1540
     *                             <code>
1541
     *                             $wanted_code = 'curse' if there are in the DB codes like curse1 curse2 the function
1542
     *                             will return: course3 if the course code doest not exist in the DB the same course
1543
     *                             code will be returned
1544
     *                             </code>
1545
     *
1546
     * @return string wanted unused code
1547
     */
1548
    public static function generateNextSessionName($session_name)
1549
    {
1550
        $session_name_ok = !self::sessionNameExists($session_name);
1551
        if (!$session_name_ok) {
1552
            $table = Database::get_main_table(TABLE_MAIN_SESSION);
1553
            $session_name = Database::escape_string($session_name);
1554
            $sql = "SELECT count(*) as count FROM $table
1555
                    WHERE name LIKE '$session_name%'";
1556
            $result = Database::query($sql);
1557
            if (Database::num_rows($result) > 0) {
1558
                $row = Database::fetch_array($result);
1559
                $count = $row['count'] + 1;
1560
                $session_name = $session_name.'_'.$count;
1561
                $result = self::sessionNameExists($session_name);
1562
                if (!$result) {
1563
                    return $session_name;
1564
                }
1565
            }
1566
1567
            return false;
1568
        }
1569
1570
        return $session_name;
1571
    }
1572
1573
    /**
1574
     * Edit a session.
1575
     *
1576
     * @author Carlos Vargas from existing code
1577
     *
1578
     * @param int    $id                           Session primary key
1579
     * @param string $name
1580
     * @param string $startDate
1581
     * @param string $endDate
1582
     * @param string $displayStartDate
1583
     * @param string $displayEndDate
1584
     * @param string $coachStartDate
1585
     * @param string $coachEndDate
1586
     * @param int    $coachId
1587
     * @param int    $sessionCategoryId
1588
     * @param int    $visibility
1589
     * @param string $description
1590
     * @param int    $showDescription
1591
     * @param int    $duration
1592
     * @param array  $extraFields
1593
     * @param int    $sessionAdminId
1594
     * @param bool   $sendSubscriptionNotification Optional. Whether send a mail notification to users being subscribed
1595
     * @param int    $status
1596
     *
1597
     * @return mixed
1598
     */
1599
    public static function edit_session(
1600
        $id,
1601
        $name,
1602
        $startDate,
1603
        $endDate,
1604
        $displayStartDate,
1605
        $displayEndDate,
1606
        $coachStartDate,
1607
        $coachEndDate,
1608
        $coachId,
1609
        $sessionCategoryId,
1610
        $visibility,
1611
        $description = null,
1612
        $showDescription = 0,
1613
        $duration = null,
1614
        $extraFields = [],
1615
        $sessionAdminId = 0,
1616
        $sendSubscriptionNotification = false,
1617
        $status = 0
1618
    ) {
1619
        $status = (int) $status;
1620
        $coachId = (int) $coachId;
1621
        $sessionCategoryId = (int) $sessionCategoryId;
1622
        $visibility = (int) $visibility;
1623
        $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
1624
1625
        if (empty($name)) {
1626
            Display::addFlash(
1627
                Display::return_message(get_lang('SessionNameIsRequired'), 'warning')
1628
            );
1629
1630
            return false;
1631
        } elseif (empty($coachId)) {
1632
            Display::addFlash(
1633
                Display::return_message(get_lang('CoachIsRequired'), 'warning')
1634
            );
1635
1636
            return false;
1637
        } elseif (!empty($startDate) &&
1638
            !api_is_valid_date($startDate, 'Y-m-d H:i') &&
1639
            !api_is_valid_date($startDate, 'Y-m-d H:i:s')
1640
        ) {
1641
            Display::addFlash(
1642
                Display::return_message(get_lang('InvalidStartDate'), 'warning')
1643
            );
1644
1645
            return false;
1646
        } elseif (!empty($endDate) &&
1647
            !api_is_valid_date($endDate, 'Y-m-d H:i') &&
1648
            !api_is_valid_date($endDate, 'Y-m-d H:i:s')
1649
        ) {
1650
            Display::addFlash(
1651
                Display::return_message(get_lang('InvalidEndDate'), 'warning')
1652
            );
1653
1654
            return false;
1655
        } elseif (!empty($startDate) && !empty($endDate) && $startDate >= $endDate) {
1656
            Display::addFlash(
1657
                Display::return_message(get_lang('StartDateShouldBeBeforeEndDate'), 'warning')
1658
            );
1659
1660
            return false;
1661
        } else {
1662
            $sessionInfo = self::get_session_by_name($name);
1663
            $exists = false;
1664
1665
            if (!empty($sessionInfo)) {
1666
                if ($sessionInfo['id'] != $id) {
1667
                    $exists = true;
1668
                }
1669
            }
1670
1671
            if ($exists) {
1672
                Display::addFlash(
1673
                    Display::return_message(get_lang('SessionNameAlreadyExists'), 'warning')
1674
                );
1675
1676
                return false;
1677
            } else {
1678
                $values = [
1679
                    'name' => $name,
1680
                    'duration' => $duration,
1681
                    'id_coach' => $coachId,
1682
                    'description' => $description,
1683
                    'show_description' => intval($showDescription),
1684
                    'visibility' => $visibility,
1685
                    'send_subscription_notification' => $sendSubscriptionNotification,
1686
                    'access_start_date' => null,
1687
                    'access_end_date' => null,
1688
                    'display_start_date' => null,
1689
                    'display_end_date' => null,
1690
                    'coach_access_start_date' => null,
1691
                    'coach_access_end_date' => null,
1692
                ];
1693
1694
                if (!empty($sessionAdminId)) {
1695
                    $values['session_admin_id'] = $sessionAdminId;
1696
                }
1697
1698
                if (!empty($startDate)) {
1699
                    $values['access_start_date'] = api_get_utc_datetime($startDate);
1700
                }
1701
1702
                if (!empty($endDate)) {
1703
                    $values['access_end_date'] = api_get_utc_datetime($endDate);
1704
                }
1705
1706
                if (!empty($displayStartDate)) {
1707
                    $values['display_start_date'] = api_get_utc_datetime($displayStartDate);
1708
                }
1709
1710
                if (!empty($displayEndDate)) {
1711
                    $values['display_end_date'] = api_get_utc_datetime($displayEndDate);
1712
                }
1713
1714
                if (!empty($coachStartDate)) {
1715
                    $values['coach_access_start_date'] = api_get_utc_datetime($coachStartDate);
1716
                }
1717
                if (!empty($coachEndDate)) {
1718
                    $values['coach_access_end_date'] = api_get_utc_datetime($coachEndDate);
1719
                }
1720
1721
                $values['session_category_id'] = null;
1722
                if (!empty($sessionCategoryId)) {
1723
                    $values['session_category_id'] = $sessionCategoryId;
1724
                }
1725
1726
                if (api_get_configuration_value('allow_session_status')) {
1727
                    $values['status'] = $status;
1728
                }
1729
1730
                Database::update(
1731
                    $tbl_session,
1732
                    $values,
1733
                    ['id = ?' => $id]
1734
                );
1735
1736
                if (!empty($extraFields)) {
1737
                    $extraFields['item_id'] = $id;
1738
                    $sessionFieldValue = new ExtraFieldValue('session');
1739
                    $sessionFieldValue->saveFieldValues($extraFields);
1740
                }
1741
1742
                return $id;
1743
            }
1744
        }
1745
    }
1746
1747
    /**
1748
     * Delete session.
1749
     *
1750
     * @author Carlos Vargas  from existing code
1751
     *
1752
     * @param array $id_checked an array to delete sessions
1753
     * @param bool  $from_ws    optional, true if the function is called
1754
     *                          by a webservice, false otherwise
1755
     *
1756
     * @return bool
1757
     * */
1758
    public static function delete($id_checked, $from_ws = false)
1759
    {
1760
        $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
1761
        $tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
1762
        $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
1763
        $tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
1764
        $tbl_url_session = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
1765
        $tbl_item_properties = Database::get_course_table(TABLE_ITEM_PROPERTY);
1766
        $tbl_student_publication = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
1767
        $tbl_student_publication_assignment = Database::get_course_table(TABLE_STUDENT_PUBLICATION_ASSIGNMENT);
1768
        $userGroupSessionTable = Database::get_main_table(TABLE_USERGROUP_REL_SESSION);
1769
        $trackCourseAccess = Database::get_main_table(TABLE_STATISTIC_TRACK_E_COURSE_ACCESS);
1770
        $trackAccess = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ACCESS);
1771
        $tbl_learnpath = Database::get_course_table(TABLE_LP_MAIN);
1772
        $tbl_dropbox = Database::get_course_table(TABLE_DROPBOX_FILE);
1773
        $trackEExercises = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCISES);
1774
        $trackEAttempt = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
1775
1776
        $ticket = Database::get_main_table(TABLE_TICKET_TICKET);
1777
        $em = Database::getManager();
1778
        $userId = api_get_user_id();
1779
1780
        // If this session is involved in any sequence, cancel deletion and ask
1781
        // for the sequence update before deleting.
1782
        /** @var SequenceResourceRepository $repo */
1783
        $repo = Database::getManager()->getRepository('ChamiloCoreBundle:SequenceResource');
1784
        $sequenceResource = $repo->findRequirementForResource(
1785
            $id_checked,
1786
            SequenceResource::SESSION_TYPE
1787
        );
1788
1789
        if ($sequenceResource) {
1790
            Display::addFlash(
1791
                Display::return_message(
1792
                    get_lang('ThereIsASequenceResourceLinkedToThisSessionYouNeedToDeleteItFirst'),
1793
                    'error'
1794
                )
1795
            );
1796
1797
            return false;
1798
        }
1799
1800
        // If the $id_checked param is an array, split it into individual
1801
        // sessions deletion.
1802
        if (is_array($id_checked)) {
1803
            foreach ($id_checked as $sessionId) {
1804
                self::delete($sessionId);
1805
            }
1806
        } else {
1807
            $id_checked = intval($id_checked);
1808
        }
1809
1810
        // Check permissions from the person launching the deletion.
1811
        // If the call is issued from a web service or automated process,
1812
        // we assume the caller checks for permissions ($from_ws).
1813
        if (self::allowed($id_checked) && !$from_ws) {
1814
            $qb = $em
1815
                ->createQuery('
1816
                    SELECT s.sessionAdminId FROM ChamiloCoreBundle:Session s
1817
                    WHERE s.id = ?1
1818
                ')
1819
                ->setParameter(1, $id_checked);
1820
1821
            $res = $qb->getSingleScalarResult();
1822
1823
            if ($res != $userId && !api_is_platform_admin()) {
1824
                api_not_allowed(true);
1825
            }
1826
        }
1827
1828
        $sessionInfo = api_get_session_info($id_checked);
1829
1830
        // Delete documents and assignments inside a session
1831
        $courses = self::getCoursesInSession($id_checked);
1832
        foreach ($courses as $courseId) {
1833
            $courseInfo = api_get_course_info_by_id($courseId);
1834
            // Delete documents
1835
            DocumentManager::deleteDocumentsFromSession($courseInfo, $id_checked);
1836
1837
            // Delete assignments
1838
            $works = Database::select(
1839
                '*',
1840
                $tbl_student_publication,
1841
                [
1842
                    'where' => ['session_id = ? AND c_id = ?' => [$id_checked, $courseId]],
1843
                ]
1844
            );
1845
            $currentCourseRepositorySys = api_get_path(SYS_COURSE_PATH).$courseInfo['path'].'/';
1846
            foreach ($works as $index => $work) {
1847
                if ($work['filetype'] = 'folder') {
1848
                    Database::query("DELETE FROM $tbl_student_publication_assignment WHERE publication_id = $index");
1849
                }
1850
                my_delete($currentCourseRepositorySys.'/'.$work['url']);
1851
            }
1852
1853
            // Delete learning paths
1854
            $learnpaths = Database::select(
1855
                'iid',
1856
                $tbl_learnpath,
1857
                [
1858
                    'where' => ['session_id = ? AND c_id = ?' => [$id_checked, $courseId]],
1859
                ]
1860
            );
1861
            $courseInfo = api_get_course_info_by_id($courseId);
1862
            foreach ($learnpaths as $lpData) {
1863
                $lp = new learnpath($courseInfo['code'], $lpData['iid'], $userId);
1864
                $lp->delete($courseInfo, $lpData['iid'], true);
1865
                unset($lp);
1866
            }
1867
1868
            // Delete dropbox documents
1869
            $dropboxes = Database::select(
1870
                'iid',
1871
                $tbl_dropbox,
1872
                [
1873
                    'where' => ['session_id = ? AND c_id = ?' => [$id_checked, $courseId]],
1874
                ]
1875
            );
1876
            require_once __DIR__.'/../../dropbox/dropbox_functions.inc.php';
1877
            foreach ($dropboxes as $dropbox) {
1878
                $dropboxPerson = new Dropbox_Person(
1879
                    $userId,
1880
                    true,
1881
                    false,
1882
                    $courseId,
1883
                    $id_checked
1884
                );
1885
                $dropboxPerson->deleteReceivedWork($dropbox['iid'], $courseId, $id_checked);
1886
                $dropboxPerson->deleteSentWork($dropbox['iid'], $courseId, $id_checked);
1887
            }
1888
1889
            // TODO: Delete audio files from test answers
1890
            $attempts = Database::select(
1891
                ['id', 'user_id', 'exe_id'],
1892
                $trackEAttempt,
1893
                [
1894
                    'where' => [
1895
                        'session_id = ? AND c_id = ? AND (filename IS NOT NULL AND filename != \'\')' => [
1896
                            $id_checked,
1897
                            $courseId,
1898
                        ],
1899
                    ],
1900
                ]
1901
            );
1902
            foreach ($attempts as $attempt) {
1903
                $oral = new OralExpression();
1904
                $oral->initFile($id_checked, $attempt['user_id'], 0, $attempt['exe_id'], $courseId);
1905
                $filename = $oral->getAbsoluteFilePath(true);
1906
                my_delete($filename);
1907
            }
1908
        }
1909
1910
        // Class
1911
        $sql = "DELETE FROM $userGroupSessionTable
1912
                WHERE session_id IN($id_checked)";
1913
        Database::query($sql);
1914
1915
        Database::query("DELETE FROM $tbl_student_publication WHERE session_id IN($id_checked)");
1916
        Database::query("DELETE FROM $tbl_session_rel_course WHERE session_id IN($id_checked)");
1917
        Database::query("DELETE FROM $tbl_session_rel_course_rel_user WHERE session_id IN($id_checked)");
1918
        Database::query("DELETE FROM $tbl_session_rel_user WHERE session_id IN($id_checked)");
1919
        Database::query("DELETE FROM $tbl_item_properties WHERE session_id IN ($id_checked)");
1920
        Database::query("DELETE FROM $tbl_url_session WHERE session_id IN($id_checked)");
1921
1922
        Database::query("DELETE FROM $trackCourseAccess WHERE session_id IN($id_checked)");
1923
        Database::query("DELETE FROM $trackAccess WHERE access_session_id IN($id_checked)");
1924
1925
        if (api_get_configuration_value('allow_lp_subscription_to_usergroups')) {
1926
            $tableGroup = Database::get_course_table(TABLE_LP_REL_USERGROUP);
1927
            Database::query("DELETE FROM $tableGroup WHERE session_id IN($id_checked)");
1928
            $tableGroup = Database::get_course_table(TABLE_LP_CATEGORY_REL_USERGROUP);
1929
            Database::query("DELETE FROM $tableGroup WHERE session_id IN($id_checked)");
1930
        }
1931
1932
        $sql = "UPDATE $ticket SET session_id = NULL WHERE session_id IN ($id_checked)";
1933
        Database::query($sql);
1934
1935
        $app_plugin = new AppPlugin();
1936
        $app_plugin->performActionsWhenDeletingItem('session', $id_checked);
1937
1938
        $sql = "DELETE FROM $tbl_session WHERE id IN ($id_checked)";
1939
        Database::query($sql);
1940
1941
        $extraFieldValue = new ExtraFieldValue('session');
1942
        $extraFieldValue->deleteValuesByItem($id_checked);
1943
1944
        $repo->deleteResource(
1945
            $id_checked,
1946
            SequenceResource::SESSION_TYPE
1947
        );
1948
1949
        // Add event to system log
1950
        Event::addEvent(
1951
            LOG_SESSION_DELETE,
1952
            LOG_SESSION_ID,
1953
            $sessionInfo['name'].' - id:'.$id_checked,
1954
            api_get_utc_datetime(),
1955
            $userId
1956
        );
1957
1958
        return true;
1959
    }
1960
1961
    /**
1962
     * @param int $id promotion id
1963
     *
1964
     * @return bool
1965
     */
1966
    public static function clear_session_ref_promotion($id)
1967
    {
1968
        $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
1969
        $id = intval($id);
1970
        $sql = "UPDATE $tbl_session
1971
                SET promotion_id = 0
1972
                WHERE promotion_id = $id";
1973
        if (Database::query($sql)) {
1974
            return true;
1975
        } else {
1976
            return false;
1977
        }
1978
    }
1979
1980
    /**
1981
     * Subscribes students to the given session and optionally (default)
1982
     * unsubscribes previous users.
1983
     *
1984
     * @author Carlos Vargas from existing code
1985
     * @author Julio Montoya. Cleaning code.
1986
     *
1987
     * @param int   $sessionId
1988
     * @param array $userList
1989
     * @param int   $session_visibility
1990
     * @param bool  $empty_users
1991
     * @param bool  $registerUsersToAllCourses
1992
     *
1993
     * @return bool
1994
     */
1995
    public static function subscribeUsersToSession(
1996
        $sessionId,
1997
        $userList,
1998
        $session_visibility = SESSION_VISIBLE_READ_ONLY,
1999
        $empty_users = true,
2000
        $registerUsersToAllCourses = true
2001
    ) {
2002
        $sessionId = (int) $sessionId;
2003
2004
        if (empty($sessionId)) {
2005
            return false;
2006
        }
2007
2008
        foreach ($userList as $intUser) {
2009
            if ($intUser != strval(intval($intUser))) {
2010
                return false;
2011
            }
2012
        }
2013
2014
        $tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
2015
        $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
2016
        $tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
2017
        $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
2018
2019
        if (!self::isValidId($sessionId)) {
2020
            return false;
2021
        }
2022
2023
        $session = api_get_session_entity($sessionId);
2024
2025
        // from function parameter
2026
        if (empty($session_visibility)) {
2027
            $session_visibility = $session->getVisibility();
2028
            //default status loaded if empty
2029
            // by default readonly 1
2030
            if (empty($session_visibility)) {
2031
                $session_visibility = SESSION_VISIBLE_READ_ONLY;
2032
            }
2033
        } else {
2034
            if (!in_array($session_visibility, [SESSION_VISIBLE_READ_ONLY, SESSION_VISIBLE, SESSION_INVISIBLE])) {
2035
                $session_visibility = SESSION_VISIBLE_READ_ONLY;
2036
            }
2037
        }
2038
2039
        $sql = "SELECT user_id FROM $tbl_session_rel_course_rel_user
2040
                WHERE session_id = $sessionId AND status = 0";
2041
        $result = Database::query($sql);
2042
        $existingUsers = [];
2043
        while ($row = Database::fetch_array($result)) {
2044
            $existingUsers[] = $row['user_id'];
2045
        }
2046
2047
        $sql = "SELECT c_id FROM $tbl_session_rel_course
2048
                WHERE session_id = $sessionId";
2049
        $result = Database::query($sql);
2050
        $course_list = [];
2051
        while ($row = Database::fetch_array($result)) {
2052
            $course_list[] = $row['c_id'];
2053
        }
2054
2055
        if ($session->getSendSubscriptionNotification() &&
2056
            is_array($userList)
2057
        ) {
2058
            // Sending emails only
2059
            foreach ($userList as $user_id) {
2060
                if (in_array($user_id, $existingUsers)) {
2061
                    continue;
2062
                }
2063
2064
                $tplSubject = new Template(
2065
                    null,
2066
                    false,
2067
                    false,
2068
                    false,
2069
                    false,
2070
                    false
2071
                );
2072
                $layoutSubject = $tplSubject->get_template(
2073
                    'mail/subject_subscription_to_session_confirmation.tpl'
2074
                );
2075
                $subject = $tplSubject->fetch($layoutSubject);
2076
                $user_info = api_get_user_info($user_id);
2077
2078
                $tplContent = new Template(
2079
                    null,
2080
                    false,
2081
                    false,
2082
                    false,
2083
                    false,
2084
                    false
2085
                );
2086
                // Variables for default template
2087
                $tplContent->assign('complete_name', stripslashes($user_info['complete_name']));
2088
                $tplContent->assign('session_name', $session->getName());
2089
                $tplContent->assign('session_coach', $session->getGeneralCoach()->getCompleteName());
2090
                $layoutContent = $tplContent->get_template(
2091
                    'mail/content_subscription_to_session_confirmation.tpl'
2092
                );
2093
2094
                if (api_get_configuration_value('email_template_subscription_to_session_confirmation_username')) {
2095
                    $username = sprintf(
2096
                        get_lang('YourUsernameToAccessIsX'),
2097
                        stripslashes($user_info['username']));
2098
2099
                    $tplContent->assign('username', $username);
2100
                }
2101
2102
                if (api_get_configuration_value('email_template_subscription_to_session_confirmation_lost_password')) {
2103
                    $urlLostPw = api_get_path(WEB_CODE_PATH).'auth/lostPassword.php';
2104
2105
                    $forgotPassword = sprintf(
2106
                        get_lang('InstructionsLostPasswordWithLinkX'),
2107
                        $urlLostPw);
2108
2109
                    $tplContent->assign('lostPassword', $forgotPassword);
2110
                }
2111
2112
                $content = $tplContent->fetch($layoutContent);
2113
2114
                api_mail_html(
2115
                    $user_info['complete_name'],
2116
                    $user_info['mail'],
2117
                    $subject,
2118
                    $content,
2119
                    api_get_person_name(
2120
                        api_get_setting('administratorName'),
2121
                        api_get_setting('administratorSurname')
2122
                    ),
2123
                    api_get_setting('emailAdministrator')
2124
                );
2125
            }
2126
        }
2127
2128
        if ($registerUsersToAllCourses) {
2129
            foreach ($course_list as $courseId) {
2130
                // for each course in the session
2131
                $courseId = (int) $courseId;
2132
2133
                $sql = "SELECT DISTINCT user_id
2134
                        FROM $tbl_session_rel_course_rel_user
2135
                        WHERE
2136
                            session_id = $sessionId AND
2137
                            c_id = $courseId AND
2138
                            status = 0
2139
                        ";
2140
                $result = Database::query($sql);
2141
                $existingUsers = [];
2142
                while ($row = Database::fetch_array($result)) {
2143
                    $existingUsers[] = $row['user_id'];
2144
                }
2145
2146
                // Delete existing users
2147
                if ($empty_users) {
2148
                    foreach ($existingUsers as $existing_user) {
2149
                        if (!in_array($existing_user, $userList)) {
2150
                            self::unSubscribeUserFromCourseSession($existing_user, $courseId, $sessionId);
2151
                        }
2152
                    }
2153
                }
2154
2155
                $usersToSubscribeInCourse = array_filter(
2156
                    $userList,
2157
                    function ($userId) use ($existingUsers) {
2158
                        return !in_array($userId, $existingUsers);
2159
                    }
2160
                );
2161
2162
                self::insertUsersInCourse(
2163
                    $usersToSubscribeInCourse,
2164
                    $courseId,
2165
                    $sessionId,
2166
                    ['visibility' => $session_visibility],
2167
                    false
2168
                );
2169
            }
2170
        }
2171
2172
        // Delete users from the session
2173
        if (true === $empty_users) {
2174
            $sql = "DELETE FROM $tbl_session_rel_user
2175
                    WHERE
2176
                      session_id = $sessionId AND
2177
                      relation_type <> ".SESSION_RELATION_TYPE_RRHH;
2178
            // Don't reset session_rel_user.registered_at of users that will be registered later anyways.
2179
            if (!empty($userList)) {
2180
                $avoidDeleteThisUsers = " AND user_id NOT IN ('".implode("','", $userList)."')";
2181
                $sql .= $avoidDeleteThisUsers;
2182
            }
2183
            Event::addEvent(
2184
                LOG_SESSION_DELETE_USER,
2185
                LOG_USER_ID,
2186
                'all',
2187
                api_get_utc_datetime(),
2188
                api_get_user_id(),
2189
                null,
2190
                $sessionId
2191
            );
2192
            Database::query($sql);
2193
        }
2194
2195
        // Insert missing users into session
2196
        foreach ($userList as $enreg_user) {
2197
            $isUserSubscribed = self::isUserSubscribedAsStudent($sessionId, $enreg_user);
2198
            if ($isUserSubscribed === false) {
2199
                $enreg_user = (int) $enreg_user;
2200
                $sql = "INSERT IGNORE INTO $tbl_session_rel_user (relation_type, session_id, user_id, registered_at)
2201
                        VALUES (0, $sessionId, $enreg_user, '".api_get_utc_datetime()."')";
2202
                Database::query($sql);
2203
                Event::addEvent(
2204
                    LOG_SESSION_ADD_USER,
2205
                    LOG_USER_ID,
2206
                    $enreg_user,
2207
                    api_get_utc_datetime(),
2208
                    api_get_user_id(),
2209
                    null,
2210
                    $sessionId
2211
                );
2212
            }
2213
        }
2214
2215
        // update number of users in the session
2216
        $sql = "UPDATE $tbl_session
2217
                SET nbr_users = (SELECT count(user_id) FROM $tbl_session_rel_user WHERE session_id = $sessionId)
2218
                WHERE id = $sessionId";
2219
        Database::query($sql);
2220
2221
        return true;
2222
    }
2223
2224
    /**
2225
     * Returns user list of the current users subscribed in the course-session.
2226
     *
2227
     * @param int   $sessionId
2228
     * @param array $courseInfo
2229
     * @param int   $status
2230
     *
2231
     * @return array
2232
     */
2233
    public static function getUsersByCourseSession(
2234
        $sessionId,
2235
        $courseInfo,
2236
        $status = null
2237
    ) {
2238
        $sessionId = (int) $sessionId;
2239
        $courseId = $courseInfo['real_id'];
2240
2241
        if (empty($sessionId) || empty($courseId)) {
2242
            return [];
2243
        }
2244
2245
        $statusCondition = null;
2246
        if (isset($status) && !is_null($status)) {
2247
            $status = (int) $status;
2248
            $statusCondition = " AND status = $status";
2249
        }
2250
2251
        $table = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
2252
2253
        $sql = "SELECT DISTINCT user_id
2254
                FROM $table
2255
                WHERE
2256
                    session_id = $sessionId AND
2257
                    c_id = $courseId
2258
                    $statusCondition
2259
                ";
2260
2261
        $result = Database::query($sql);
2262
        $existingUsers = [];
2263
        while ($row = Database::fetch_array($result)) {
2264
            $existingUsers[] = $row['user_id'];
2265
        }
2266
2267
        return $existingUsers;
2268
    }
2269
2270
    /**
2271
     * Returns user list of the current users subscribed in the course-session.
2272
     *
2273
     * @param array $sessionList
2274
     * @param array $courseList
2275
     * @param int   $status
2276
     * @param int   $start
2277
     * @param int   $limit
2278
     *
2279
     * @return array
2280
     */
2281
    public static function getUsersByCourseAndSessionList(
2282
        $sessionList,
2283
        $courseList,
2284
        $status = null,
2285
        $start = null,
2286
        $limit = null
2287
    ) {
2288
        if (empty($sessionList) || empty($courseList)) {
2289
            return [];
2290
        }
2291
        $sessionListToString = implode("','", $sessionList);
2292
        $courseListToString = implode("','", $courseList);
2293
2294
        $statusCondition = null;
2295
        if (isset($status) && !is_null($status)) {
2296
            $status = (int) $status;
2297
            $statusCondition = " AND status = $status";
2298
        }
2299
2300
        $table = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
2301
2302
        $sql = "SELECT DISTINCT user_id
2303
                FROM $table
2304
                WHERE
2305
                    session_id IN ('$sessionListToString') AND
2306
                    c_id IN ('$courseListToString')
2307
                    $statusCondition
2308
                ";
2309
        if (!is_null($start) && !is_null($limit)) {
2310
            $start = (int) $start;
2311
            $limit = (int) $limit;
2312
            $sql .= "LIMIT $start, $limit";
2313
        }
2314
        $result = Database::query($sql);
2315
        $existingUsers = [];
2316
        while ($row = Database::fetch_array($result)) {
2317
            $existingUsers[] = $row['user_id'];
2318
        }
2319
2320
        return $existingUsers;
2321
    }
2322
2323
    /**
2324
     * Remove a list of users from a course-session.
2325
     *
2326
     * @param array $userList
2327
     * @param int   $sessionId
2328
     * @param array $courseInfo
2329
     * @param int   $status
2330
     * @param bool  $updateTotal
2331
     *
2332
     * @return bool
2333
     */
2334
    public static function removeUsersFromCourseSession(
2335
        $userList,
2336
        $sessionId,
2337
        $courseInfo,
2338
        $status = null,
2339
        $updateTotal = true
2340
    ) {
2341
        $table = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
2342
        $tableSessionCourse = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
2343
        $sessionId = (int) $sessionId;
2344
2345
        if (empty($sessionId) || empty($userList) || empty($courseInfo)) {
2346
            return false;
2347
        }
2348
2349
        is_array($courseInfo) ? $courseId = $courseInfo['real_id'] : $courseId = $courseInfo;
2350
2351
        $statusCondition = null;
2352
        if (isset($status) && !is_null($status)) {
2353
            $status = (int) $status;
2354
            $statusCondition = " AND status = $status";
2355
        }
2356
2357
        foreach ($userList as $userId) {
2358
            $userId = (int) $userId;
2359
            $sql = "DELETE FROM $table
2360
                    WHERE
2361
                        session_id = $sessionId AND
2362
                        c_id = $courseId AND
2363
                        user_id = $userId
2364
                        $statusCondition
2365
                    ";
2366
            Database::query($sql);
2367
2368
            Event::addEvent(
2369
                LOG_SESSION_DELETE_USER_COURSE,
2370
                LOG_USER_ID,
2371
                $userId,
2372
                api_get_utc_datetime(),
2373
                api_get_user_id(),
2374
                $courseId,
2375
                $sessionId
2376
            );
2377
        }
2378
2379
        if ($updateTotal) {
2380
            // Count users in this session-course relation
2381
            $sql = "SELECT COUNT(user_id) as nbUsers
2382
                    FROM $table
2383
                    WHERE
2384
                        session_id = $sessionId AND
2385
                        c_id = $courseId AND
2386
                        status <> 2";
2387
            $result = Database::query($sql);
2388
            [$userCount] = Database::fetch_array($result);
2389
2390
            // update the session-course relation to add the users total
2391
            $sql = "UPDATE $tableSessionCourse
2392
                    SET nbr_users = $userCount
2393
                    WHERE
2394
                        session_id = $sessionId AND
2395
                        c_id = $courseId";
2396
            Database::query($sql);
2397
        }
2398
    }
2399
2400
    /**
2401
     * Subscribe a user to an specific course inside a session.
2402
     *
2403
     * @param array  $user_list
2404
     * @param int    $session_id
2405
     * @param string $course_code
2406
     * @param int    $session_visibility
2407
     * @param bool   $removeUsersNotInList
2408
     *
2409
     * @return bool
2410
     */
2411
    public static function subscribe_users_to_session_course(
2412
        $user_list,
2413
        $session_id,
2414
        $course_code,
2415
        $session_visibility = SESSION_VISIBLE_READ_ONLY,
2416
        $removeUsersNotInList = false
2417
    ) {
2418
        if (empty($session_id) || empty($course_code)) {
2419
            return false;
2420
        }
2421
2422
        $session_id = (int) $session_id;
2423
        $session_visibility = (int) $session_visibility;
2424
        $course_code = Database::escape_string($course_code);
2425
        $courseInfo = api_get_course_info($course_code);
2426
        $courseId = $courseInfo['real_id'];
2427
2428
        if ($removeUsersNotInList) {
2429
            $currentUsers = self::getUsersByCourseSession($session_id, $courseInfo, 0);
2430
2431
            if (!empty($user_list)) {
2432
                $userToDelete = array_diff($currentUsers, $user_list);
2433
            } else {
2434
                $userToDelete = $currentUsers;
2435
            }
2436
2437
            if (!empty($userToDelete)) {
2438
                self::removeUsersFromCourseSession(
2439
                    $userToDelete,
2440
                    $session_id,
2441
                    $courseInfo,
2442
                    0,
2443
                    true
2444
                );
2445
            }
2446
        }
2447
2448
        self::insertUsersInCourse(
2449
            $user_list,
2450
            $courseId,
2451
            $session_id,
2452
            ['visibility' => $session_visibility]
2453
        );
2454
    }
2455
2456
    /**
2457
     * Unsubscribe user from session.
2458
     *
2459
     * @param int Session id
2460
     * @param int User id
2461
     *
2462
     * @return bool True in case of success, false in case of error
2463
     */
2464
    public static function unsubscribe_user_from_session($session_id, $user_id)
2465
    {
2466
        $session_id = (int) $session_id;
2467
        $user_id = (int) $user_id;
2468
2469
        $tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
2470
        $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
2471
2472
        if (!self::isValidId($session_id)) {
2473
            return false;
2474
        }
2475
2476
        $sql = "DELETE FROM $tbl_session_rel_user
2477
                WHERE
2478
                    session_id = $session_id AND
2479
                    user_id = $user_id AND
2480
                    relation_type <> ".SESSION_RELATION_TYPE_RRHH;
2481
        $result = Database::query($sql);
2482
        $return = Database::affected_rows($result);
2483
2484
        // Update number of users
2485
        $sql = "UPDATE $tbl_session
2486
                SET nbr_users = nbr_users - $return
2487
                WHERE id = $session_id ";
2488
        Database::query($sql);
2489
2490
        Event::addEvent(
2491
            LOG_SESSION_DELETE_USER,
2492
            LOG_USER_ID,
2493
            $user_id,
2494
            api_get_utc_datetime(),
2495
            api_get_user_id(),
2496
            null,
2497
            $session_id
2498
        );
2499
2500
        // Get the list of courses related to this session
2501
        $course_list = self::get_course_list_by_session_id($session_id);
2502
        if (!empty($course_list)) {
2503
            foreach ($course_list as $course) {
2504
                self::unSubscribeUserFromCourseSession($user_id, $course['id'], $session_id);
2505
            }
2506
        }
2507
2508
        return true;
2509
    }
2510
2511
    /**
2512
     * @param int $user_id
2513
     * @param int $courseId
2514
     * @param int $session_id
2515
     */
2516
    public static function unSubscribeUserFromCourseSession($user_id, $courseId, $session_id)
2517
    {
2518
        $user_id = (int) $user_id;
2519
        $courseId = (int) $courseId;
2520
        $session_id = (int) $session_id;
2521
2522
        $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
2523
        $tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
2524
2525
        // Delete user from course
2526
        $sql = "DELETE FROM $tbl_session_rel_course_rel_user
2527
                WHERE session_id = $session_id AND c_id = $courseId AND user_id = $user_id";
2528
        $result = Database::query($sql);
2529
2530
        if (Database::affected_rows($result)) {
2531
            // Update number of users in this relation
2532
            $sql = "UPDATE $tbl_session_rel_course SET
2533
                    nbr_users = nbr_users - 1
2534
                    WHERE session_id = $session_id AND c_id = $courseId";
2535
            Database::query($sql);
2536
        }
2537
2538
        Event::addEvent(
2539
            LOG_SESSION_DELETE_USER_COURSE,
2540
            LOG_USER_ID,
2541
            $user_id,
2542
            api_get_utc_datetime(),
2543
            api_get_user_id(),
2544
            $courseId,
2545
            $session_id
2546
        );
2547
    }
2548
2549
    /**
2550
     * Subscribes courses to the given session and optionally (default)
2551
     * unsubscribe previous users.
2552
     *
2553
     * @author Carlos Vargas from existing code
2554
     *
2555
     * @param int   $sessionId
2556
     * @param array $courseList                     List of courses int ids
2557
     * @param bool  $removeExistingCoursesWithUsers Whether to unsubscribe
2558
     *                                              existing courses and users (true, default) or not (false)
2559
     * @param bool  $copyEvaluation                 from base course to session course
2560
     * @param bool  $copyCourseTeachersAsCoach
2561
     * @param bool  $importAssignments
2562
     *
2563
     * @throws Exception
2564
     *
2565
     * @return bool False on failure, true otherwise
2566
     * */
2567
    public static function add_courses_to_session(
2568
        $sessionId,
2569
        $courseList,
2570
        $removeExistingCoursesWithUsers = true,
2571
        $copyEvaluation = false,
2572
        $copyCourseTeachersAsCoach = false,
2573
        $importAssignments = false
2574
    ) {
2575
        $sessionId = (int) $sessionId;
2576
2577
        if (empty($sessionId) || empty($courseList)) {
2578
            return false;
2579
        }
2580
2581
        if ($importAssignments) {
2582
            require_once api_get_path(SYS_CODE_PATH).'work/work.lib.php';
2583
        }
2584
2585
        $session = api_get_session_entity($sessionId);
2586
2587
        if (!$session) {
2588
            return false;
2589
        }
2590
        $sessionVisibility = $session->getVisibility();
2591
2592
        $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
2593
        $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
2594
        $tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
2595
        $tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
2596
2597
        // Get list of courses subscribed to this session
2598
        $sql = "SELECT c_id
2599
                FROM $tbl_session_rel_course
2600
                WHERE session_id = $sessionId";
2601
        $rs = Database::query($sql);
2602
        $existingCourses = Database::store_result($rs);
2603
        $nbr_courses = count($existingCourses);
2604
2605
        // Get list of users subscribed to this session
2606
        $sql = "SELECT user_id
2607
                FROM $tbl_session_rel_user
2608
                WHERE
2609
                    session_id = $sessionId AND
2610
                    relation_type<>".SESSION_RELATION_TYPE_RRHH;
2611
        $result = Database::query($sql);
2612
        $user_list = Database::store_result($result);
2613
2614
        // Remove existing courses from the session.
2615
        if ($removeExistingCoursesWithUsers === true && !empty($existingCourses)) {
2616
            foreach ($existingCourses as $existingCourse) {
2617
                if (!in_array($existingCourse['c_id'], $courseList)) {
2618
                    $sql = "DELETE FROM $tbl_session_rel_course
2619
                            WHERE
2620
                                c_id = ".$existingCourse['c_id']." AND
2621
                                session_id = $sessionId";
2622
                    Database::query($sql);
2623
2624
                    $sql = "DELETE FROM $tbl_session_rel_course_rel_user
2625
                            WHERE
2626
                                c_id = ".$existingCourse['c_id']." AND
2627
                                session_id = $sessionId";
2628
                    Database::query($sql);
2629
2630
                    Event::addEvent(
2631
                        LOG_SESSION_DELETE_COURSE,
2632
                        LOG_COURSE_ID,
2633
                        $existingCourse['c_id'],
2634
                        api_get_utc_datetime(),
2635
                        api_get_user_id(),
2636
                        $existingCourse['c_id'],
2637
                        $sessionId
2638
                    );
2639
2640
                    CourseManager::remove_course_ranking(
2641
                        $existingCourse['c_id'],
2642
                        $sessionId
2643
                    );
2644
                    $nbr_courses--;
2645
                }
2646
            }
2647
        }
2648
2649
        $em = Database::getManager();
2650
2651
        // Pass through the courses list we want to add to the session
2652
        foreach ($courseList as $courseId) {
2653
            $courseInfo = api_get_course_info_by_id($courseId);
2654
2655
            // If course doesn't exists continue!
2656
            if (empty($courseInfo)) {
2657
                continue;
2658
            }
2659
2660
            $exists = false;
2661
            // check if the course we want to add is already subscribed
2662
            foreach ($existingCourses as $existingCourse) {
2663
                if ($courseId == $existingCourse['c_id']) {
2664
                    $exists = true;
2665
                }
2666
            }
2667
2668
            if (!$exists) {
2669
                // Copy gradebook categories and links (from base course)
2670
                // to the new course session
2671
                if ($copyEvaluation) {
2672
                    // it gets the main categories ordered by parent
2673
                    $cats = Category::load(null, null, $courseInfo['code'], null, null, null, 'ORDER BY parent_id ASC');
2674
                    if (!empty($cats)) {
2675
                        $sessionCategory = Category::load(
2676
                            null,
2677
                            null,
2678
                            $courseInfo['code'],
2679
                            null,
2680
                            null,
2681
                            $sessionId,
2682
                            false
2683
                        );
2684
2685
                        $sessionCategoriesId = [];
2686
                        if (empty($sessionCategory)) {
2687
                            // It sets the values from the main categories to be copied
2688
                            foreach ($cats as $origCat) {
2689
                                $cat = new Category();
2690
                                $sessionName = $session->getName();
2691
                                $cat->set_name($origCat->get_name().' - '.get_lang('Session').' '.$sessionName);
2692
                                $cat->set_session_id($sessionId);
2693
                                $cat->set_course_code($origCat->get_course_code());
2694
                                $cat->set_description($origCat->get_description());
2695
                                $cat->set_parent_id($origCat->get_parent_id());
2696
                                $cat->set_weight($origCat->get_weight());
2697
                                $cat->set_visible(0);
2698
                                $cat->set_certificate_min_score($origCat->getCertificateMinScore());
2699
                                $cat->setGenerateCertificates($origCat->getGenerateCertificates());
2700
                                $cat->setIsRequirement($origCat->getIsRequirement());
2701
                                $cat->add();
2702
                                $sessionGradeBookCategoryId = $cat->get_id();
2703
                                $sessionCategoriesId[$origCat->get_id()] = $sessionGradeBookCategoryId;
2704
2705
                                // it updates the new parent id
2706
                                if ($origCat->get_parent_id() > 0) {
2707
                                    $cat->updateParentId($sessionCategoriesId[$origCat->get_parent_id()], $sessionGradeBookCategoryId);
2708
                                }
2709
                            }
2710
                        } else {
2711
                            if (!empty($sessionCategory[0])) {
2712
                                $sessionCategoriesId[0] = $sessionCategory[0]->get_id();
2713
                            }
2714
                        }
2715
2716
                        $categoryIdList = [];
2717
                        /** @var Category $cat */
2718
                        foreach ($cats as $cat) {
2719
                            $categoryIdList[$cat->get_id()] = $cat->get_id();
2720
                        }
2721
2722
                        $newCategoryIdList = [];
2723
                        foreach ($cats as $cat) {
2724
                            $links = $cat->get_links(
2725
                                null,
2726
                                false,
2727
                                $courseInfo['code'],
2728
                                0
2729
                            );
2730
2731
                            if (!empty($links)) {
2732
                                /** @var AbstractLink $link */
2733
                                foreach ($links as $link) {
2734
                                    $newCategoryId = isset($sessionCategoriesId[$link->getCategory()->get_id()]) ? $sessionCategoriesId[$link->getCategory()->get_id()] : $sessionCategoriesId[0];
2735
                                    $link->set_category_id($newCategoryId);
2736
                                    $link->add();
2737
                                }
2738
                            }
2739
2740
                            $evaluationList = $cat->get_evaluations(
2741
                                null,
2742
                                false,
2743
                                $courseInfo['code'],
2744
                                0
2745
                            );
2746
2747
                            if (!empty($evaluationList)) {
2748
                                /** @var Evaluation $evaluation */
2749
                                foreach ($evaluationList as $evaluation) {
2750
                                    $newCategoryId = isset($sessionCategoriesId[$evaluation->getCategory()->get_id()]) ? $sessionCategoriesId[$evaluation->getCategory()->get_id()] : $sessionCategoriesId[0];
2751
                                    $evaluation->set_category_id($newCategoryId);
2752
                                    $evaluation->add();
2753
                                }
2754
                            }
2755
                        }
2756
2757
                        // Create
2758
                        DocumentManager::generateDefaultCertificate(
2759
                            $courseInfo,
2760
                            true,
2761
                            $sessionId
2762
                        );
2763
                    }
2764
                }
2765
2766
                if ($importAssignments) {
2767
                    $workTable = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
2768
                    $sql = " SELECT * FROM $workTable
2769
                             WHERE active = 1 AND
2770
                                   c_id = $courseId AND
2771
                                   parent_id = 0 AND
2772
                                   (session_id IS NULL OR session_id = 0)";
2773
                    $result = Database::query($sql);
2774
                    $workList = Database::store_result($result, 'ASSOC');
2775
2776
                    foreach ($workList as $work) {
2777
                        $values = [
2778
                            'work_title' => $work['title'],
2779
                            'new_dir' => $work['url'].'_session_'.$sessionId,
2780
                            'description' => $work['description'],
2781
                            'qualification' => $work['qualification'],
2782
                            'allow_text_assignment' => $work['allow_text_assignment'],
2783
                        ];
2784
2785
                        addDir(
2786
                            $values,
2787
                            api_get_user_id(),
2788
                            $courseInfo,
2789
                            0,
2790
                            $sessionId
2791
                        );
2792
                    }
2793
                }
2794
2795
                // If the course isn't subscribed yet
2796
                $sql = "INSERT INTO $tbl_session_rel_course (session_id, c_id, nbr_users, position)
2797
                        VALUES ($sessionId, $courseId, 0, 0)";
2798
                Database::query($sql);
2799
2800
                if (api_get_configuration_value('allow_skill_rel_items')) {
2801
                    $skillRelCourseRepo = $em->getRepository('ChamiloSkillBundle:SkillRelCourse');
2802
                    $items = $skillRelCourseRepo->findBy(['course' => $courseId, 'session' => null]);
2803
                    /** @var \Chamilo\SkillBundle\Entity\SkillRelCourse $item */
2804
                    foreach ($items as $item) {
2805
                        $exists = $skillRelCourseRepo->findOneBy(['course' => $courseId, 'session' => $session]);
2806
                        if (null === $exists) {
2807
                            $skillRelCourse = clone $item;
2808
                            $skillRelCourse->setSession($session);
2809
                            $em->persist($skillRelCourse);
2810
                        }
2811
                    }
2812
                    $em->flush();
2813
                }
2814
2815
                Event::addEvent(
2816
                    LOG_SESSION_ADD_COURSE,
2817
                    LOG_COURSE_ID,
2818
                    $courseId,
2819
                    api_get_utc_datetime(),
2820
                    api_get_user_id(),
2821
                    $courseId,
2822
                    $sessionId
2823
                );
2824
2825
                // We add the current course in the existing courses array,
2826
                // to avoid adding another time the current course
2827
                $existingCourses[] = ['c_id' => $courseId];
2828
                $nbr_courses++;
2829
2830
                // Subscribe all the users from the session to this course inside the session
2831
                self::insertUsersInCourse(
2832
                    array_column($user_list, 'user_id'),
2833
                    $courseId,
2834
                    $sessionId,
2835
                    ['visibility' => $sessionVisibility]
2836
                );
2837
            }
2838
2839
            if ($copyCourseTeachersAsCoach) {
2840
                $teachers = CourseManager::get_teacher_list_from_course_code($courseInfo['code']);
2841
                if (!empty($teachers)) {
2842
                    foreach ($teachers as $teacher) {
2843
                        self::updateCoaches(
2844
                            $sessionId,
2845
                            $courseId,
2846
                            [$teacher['user_id']],
2847
                            false
2848
                        );
2849
                    }
2850
                }
2851
            }
2852
        }
2853
2854
        $sql = "UPDATE $tbl_session SET nbr_courses = $nbr_courses WHERE id = $sessionId";
2855
        Database::query($sql);
2856
2857
        return true;
2858
    }
2859
2860
    /**
2861
     * Unsubscribe course from a session.
2862
     *
2863
     * @param int $session_id
2864
     * @param int $course_id
2865
     *
2866
     * @return bool True in case of success, false otherwise
2867
     */
2868
    public static function unsubscribe_course_from_session($session_id, $course_id)
2869
    {
2870
        $session_id = (int) $session_id;
2871
        $course_id = (int) $course_id;
2872
2873
        $tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
2874
        $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
2875
        $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
2876
2877
        // Get course code
2878
        $course_code = CourseManager::get_course_code_from_course_id($course_id);
2879
2880
        if (empty($course_code)) {
2881
            return false;
2882
        }
2883
2884
        // Unsubscribe course
2885
        $sql = "DELETE FROM $tbl_session_rel_course
2886
                WHERE c_id = $course_id AND session_id = $session_id";
2887
        $result = Database::query($sql);
2888
        $nb_affected = Database::affected_rows($result);
2889
2890
        $sql = "DELETE FROM $tbl_session_rel_course_rel_user
2891
                WHERE c_id = $course_id AND session_id = $session_id";
2892
        Database::query($sql);
2893
2894
        Event::addEvent(
2895
            LOG_SESSION_DELETE_COURSE,
2896
            LOG_COURSE_ID,
2897
            $course_id,
2898
            api_get_utc_datetime(),
2899
            api_get_user_id(),
2900
            $course_id,
2901
            $session_id
2902
        );
2903
2904
        if ($nb_affected > 0) {
2905
            // Update number of courses in the session
2906
            $sql = "UPDATE $tbl_session SET nbr_courses= nbr_courses - $nb_affected
2907
                    WHERE id = $session_id";
2908
            Database::query($sql);
2909
2910
            return true;
2911
        }
2912
2913
        return false;
2914
    }
2915
2916
    /**
2917
     * Creates a new extra field for a given session.
2918
     *
2919
     * @param string $variable    Field's internal variable name
2920
     * @param int    $fieldType   Field's type
2921
     * @param string $displayText Field's language var name
2922
     * @param string $default     Field's default value
2923
     *
2924
     * @return int new extra field id
2925
     */
2926
    public static function create_session_extra_field(
2927
        $variable,
2928
        $fieldType,
2929
        $displayText,
2930
        $default = ''
2931
    ) {
2932
        $extraField = new ExtraFieldModel('session');
2933
        $params = [
2934
            'variable' => $variable,
2935
            'field_type' => $fieldType,
2936
            'display_text' => $displayText,
2937
            'default_value' => $default,
2938
        ];
2939
2940
        return $extraField->save($params);
2941
    }
2942
2943
    /**
2944
     * Update an extra field value for a given session.
2945
     *
2946
     * @param int    $sessionId Session ID
2947
     * @param string $variable  Field variable name
2948
     * @param string $value     Optional. Default field value
2949
     *
2950
     * @return bool|int An integer when register a new extra field. And boolean when update the extrafield
2951
     */
2952
    public static function update_session_extra_field_value($sessionId, $variable, $value = '')
2953
    {
2954
        $extraFieldValue = new ExtraFieldValue('session');
2955
        $params = [
2956
            'item_id' => $sessionId,
2957
            'variable' => $variable,
2958
            'value' => $value,
2959
        ];
2960
2961
        return $extraFieldValue->save($params);
2962
    }
2963
2964
    /**
2965
     * Checks the relationship between a session and a course.
2966
     *
2967
     * @param int $session_id
2968
     * @param int $courseId
2969
     *
2970
     * @return bool returns TRUE if the session and the course are related, FALSE otherwise
2971
     * */
2972
    public static function relation_session_course_exist($session_id, $courseId)
2973
    {
2974
        $tbl_session_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
2975
        $return_value = false;
2976
        $sql = "SELECT c_id FROM $tbl_session_course
2977
                WHERE
2978
                  session_id = ".intval($session_id)." AND
2979
                  c_id = ".intval($courseId);
2980
        $result = Database::query($sql);
2981
        $num = Database::num_rows($result);
2982
        if ($num > 0) {
2983
            $return_value = true;
2984
        }
2985
2986
        return $return_value;
2987
    }
2988
2989
    /**
2990
     * Get the session information by name.
2991
     *
2992
     * @param string $name
2993
     *
2994
     * @return mixed false if the session does not exist, array if the session exist
2995
     */
2996
    public static function get_session_by_name($name)
2997
    {
2998
        $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
2999
        $name = Database::escape_string(trim($name));
3000
        if (empty($name)) {
3001
            return false;
3002
        }
3003
3004
        $sql = 'SELECT *
3005
		        FROM '.$tbl_session.'
3006
		        WHERE name = "'.$name.'"';
3007
        $result = Database::query($sql);
3008
        $num = Database::num_rows($result);
3009
        if ($num > 0) {
3010
            return Database::fetch_array($result);
3011
        } else {
3012
            return false;
3013
        }
3014
    }
3015
3016
    /**
3017
     * @param int $sessionId
3018
     * @param int $name
3019
     *
3020
     * @return bool
3021
     */
3022
    public static function sessionNameExistBesidesMySession($sessionId, $name)
3023
    {
3024
        $table = Database::get_main_table(TABLE_MAIN_SESSION);
3025
        $name = Database::escape_string(trim($name));
3026
        $sessionId = (int) $sessionId;
3027
3028
        if (empty($name)) {
3029
            return false;
3030
        }
3031
3032
        $sql = "SELECT *
3033
		        FROM $table
3034
		        WHERE name = '$name' AND id <> $sessionId ";
3035
        $result = Database::query($sql);
3036
        $num = Database::num_rows($result);
3037
        if ($num > 0) {
3038
            return true;
3039
        }
3040
3041
        return false;
3042
    }
3043
3044
    /**
3045
     * Create a session category.
3046
     *
3047
     * @author Jhon Hinojosa <[email protected]>, from existing code
3048
     *
3049
     * @param string        name
3050
     * @param int        year_start
3051
     * @param int        month_start
3052
     * @param int        day_start
3053
     * @param int        year_end
3054
     * @param int        month_end
3055
     * @param int        day_end
3056
     *
3057
     * @return int session ID
3058
     * */
3059
    public static function create_category_session(
3060
        $sname,
3061
        $syear_start,
3062
        $smonth_start,
3063
        $sday_start,
3064
        $syear_end,
3065
        $smonth_end,
3066
        $sday_end
3067
    ) {
3068
        $tbl_session_category = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
3069
3070
        $name = trim($sname);
3071
        $name = html_filter($name);
3072
        $name = RemoveOnAttributes::filter($name);
3073
        $name = Database::escape_string($name);
3074
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
        $date_start = "$year_start-".(($month_start < 10) ? "0$month_start" : $month_start)."-".(($day_start < 10) ? "0$day_start" : $day_start);
3082
        $date_end = "$year_end-".(($month_end < 10) ? "0$month_end" : $month_end)."-".(($day_end < 10) ? "0$day_end" : $day_end);
3083
        if (empty($name)) {
3084
            $msg = get_lang('SessionCategoryNameIsRequired');
3085
3086
            return $msg;
3087
        } elseif (!$month_start || !$day_start || !$year_start || !checkdate($month_start, $day_start, $year_start)) {
3088
            $msg = get_lang('InvalidStartDate');
3089
3090
            return $msg;
3091
        } elseif (!$month_end && !$day_end && !$year_end) {
3092
            $date_end = '';
3093
        } elseif (!$month_end || !$day_end || !$year_end || !checkdate($month_end, $day_end, $year_end)) {
3094
            $msg = get_lang('InvalidEndDate');
3095
3096
            return $msg;
3097
        } elseif ($date_start >= $date_end) {
3098
            $msg = get_lang('StartDateShouldBeBeforeEndDate');
3099
3100
            return $msg;
3101
        }
3102
        $access_url_id = api_get_current_access_url_id();
3103
3104
        $params = [
3105
            'name' => $name,
3106
            'date_start' => $date_start,
3107
            'access_url_id' => $access_url_id,
3108
        ];
3109
3110
        if (!empty($date_end)) {
3111
            $params['date_end'] = $date_end;
3112
        }
3113
3114
        $id = Database::insert($tbl_session_category, $params);
3115
3116
        // Add event to system log
3117
        $user_id = api_get_user_id();
3118
        Event::addEvent(
3119
            LOG_SESSION_CATEGORY_CREATE,
3120
            LOG_SESSION_CATEGORY_ID,
3121
            $id,
3122
            api_get_utc_datetime(),
3123
            $user_id
3124
        );
3125
3126
        return $id;
3127
    }
3128
3129
    /**
3130
     * Edit a sessions category.
3131
     *
3132
     * @author Jhon Hinojosa <[email protected]>,from existing code
3133
     *
3134
     * @param int        id
3135
     * @param string        name
3136
     * @param int        year_start
3137
     * @param int        month_start
3138
     * @param int        day_start
3139
     * @param int        year_end
3140
     * @param int        month_end
3141
     * @param int        day_end
3142
     *
3143
     * @return bool
3144
     *              The parameter id is a primary key
3145
     * */
3146
    public static function edit_category_session(
3147
        $id,
3148
        $sname,
3149
        $syear_start,
3150
        $smonth_start,
3151
        $sday_start,
3152
        $syear_end,
3153
        $smonth_end,
3154
        $sday_end
3155
    ) {
3156
        $tbl_session_category = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
3157
        $name = trim($sname);
3158
        $name = html_filter($name);
3159
        $name = RemoveOnAttributes::filter($name);
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 = [];
3473
3474
            while ($category = Database::fetch_assoc($result)) {
3475
                $category['name'] = Security::remove_XSS($category['name']);
3476
                $data[] = $category;
3477
            }
3478
3479
            return $data;
3480
        }
3481
3482
        return false;
3483
    }
3484
3485
    /**
3486
     * Assign a coach to course in session with status = 2.
3487
     *
3488
     * @param int  $userId
3489
     * @param int  $sessionId
3490
     * @param int  $courseId
3491
     * @param bool $noCoach   optional, if is true the user don't be a coach now,
3492
     *                        otherwise it'll assign a coach
3493
     *
3494
     * @return bool true if there are affected rows, otherwise false
3495
     */
3496
    public static function set_coach_to_course_session(
3497
        $userId,
3498
        $sessionId = 0,
3499
        $courseId = 0,
3500
        $noCoach = false
3501
    ) {
3502
        // Definition of variables
3503
        $userId = (int) $userId;
3504
3505
        $sessionId = !empty($sessionId) ? (int) $sessionId : api_get_session_id();
3506
        $courseId = !empty($courseId) ? (int) $courseId : api_get_course_id();
3507
3508
        if (empty($sessionId) || empty($courseId) || empty($userId)) {
3509
            return false;
3510
        }
3511
3512
        // Table definition
3513
        $tblSessionRelCourseRelUser = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
3514
        $tblSessionRelUser = Database::get_main_table(TABLE_MAIN_SESSION_USER);
3515
        $tblUser = Database::get_main_table(TABLE_MAIN_USER);
3516
3517
        $allowedTeachers = implode(',', UserManager::getAllowedRolesAsTeacher());
3518
3519
        // check if user is a teacher
3520
        $sql = "SELECT * FROM $tblUser WHERE status IN ($allowedTeachers) AND user_id = $userId";
3521
3522
        $rsCheckUser = Database::query($sql);
3523
3524
        if (Database::num_rows($rsCheckUser) <= 0) {
3525
            return false;
3526
        }
3527
3528
        if ($noCoach) {
3529
            // check if user_id exists in session_rel_user (if the user is
3530
            // subscribed to the session in any manner)
3531
            $sql = "SELECT user_id FROM $tblSessionRelUser
3532
                    WHERE
3533
                        session_id = $sessionId AND
3534
                        user_id = $userId";
3535
            $res = Database::query($sql);
3536
3537
            if (Database::num_rows($res) > 0) {
3538
                // The user is already subscribed to the session. Change the
3539
                // record so the user is NOT a coach for this course anymore
3540
                // and then exit
3541
                $sql = "UPDATE $tblSessionRelCourseRelUser
3542
                        SET status = 0
3543
                        WHERE
3544
                            session_id = $sessionId AND
3545
                            c_id = $courseId AND
3546
                            user_id = $userId ";
3547
                $result = Database::query($sql);
3548
3549
                return Database::affected_rows($result) > 0;
3550
            }
3551
3552
            // The user is not subscribed to the session, so make sure
3553
            // he isn't subscribed to a course in this session either
3554
            // and then exit
3555
            $sql = "DELETE FROM $tblSessionRelCourseRelUser
3556
                    WHERE
3557
                        session_id = $sessionId AND
3558
                        c_id = $courseId AND
3559
                        user_id = $userId ";
3560
            $result = Database::query($sql);
3561
3562
            return Database::affected_rows($result) > 0;
3563
        }
3564
3565
        // Assign user as a coach to course
3566
        // First check if the user is registered to the course
3567
        $sql = "SELECT user_id FROM $tblSessionRelCourseRelUser
3568
                WHERE
3569
                    session_id = $sessionId AND
3570
                    c_id = $courseId AND
3571
                    user_id = $userId";
3572
        $rs_check = Database::query($sql);
3573
3574
        // Then update or insert.
3575
        if (Database::num_rows($rs_check) > 0) {
3576
            $sql = "UPDATE $tblSessionRelCourseRelUser SET status = 2
3577
                    WHERE
3578
                        session_id = $sessionId AND
3579
                        c_id = $courseId AND
3580
                        user_id = $userId ";
3581
            $result = Database::query($sql);
3582
3583
            return Database::affected_rows($result) > 0;
3584
        }
3585
3586
        $sql = "INSERT INTO $tblSessionRelCourseRelUser(session_id, c_id, user_id, status)
3587
                VALUES($sessionId, $courseId, $userId, 2)";
3588
        $result = Database::query($sql);
3589
3590
        return Database::affected_rows($result) > 0;
3591
    }
3592
3593
    /**
3594
     * @param int $sessionId
3595
     *
3596
     * @return bool
3597
     */
3598
    public static function removeAllDrhFromSession($sessionId)
3599
    {
3600
        $tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
3601
        $sessionId = (int) $sessionId;
3602
3603
        if (empty($sessionId)) {
3604
            return false;
3605
        }
3606
3607
        $sql = "DELETE FROM $tbl_session_rel_user
3608
                WHERE
3609
                    session_id = $sessionId AND
3610
                    relation_type =".SESSION_RELATION_TYPE_RRHH;
3611
        Database::query($sql);
3612
3613
        return true;
3614
    }
3615
3616
    /**
3617
     * Subscribes sessions to human resource manager (Dashboard feature).
3618
     *
3619
     * @param array $userInfo               Human Resource Manager info
3620
     * @param array $sessions_list          Sessions id
3621
     * @param bool  $sendEmail
3622
     * @param bool  $removeSessionsFromUser
3623
     *
3624
     * @return int
3625
     * */
3626
    public static function subscribeSessionsToDrh(
3627
        $userInfo,
3628
        $sessions_list,
3629
        $sendEmail = false,
3630
        $removeSessionsFromUser = true
3631
    ) {
3632
        // Database Table Definitions
3633
        $tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
3634
        $tbl_session_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
3635
3636
        if (empty($userInfo)) {
3637
            return 0;
3638
        }
3639
3640
        $userId = $userInfo['user_id'];
3641
3642
        // Only subscribe DRH users.
3643
        $rolesAllowed = [
3644
            DRH,
3645
            SESSIONADMIN,
3646
            PLATFORM_ADMIN,
3647
            COURSE_TUTOR,
3648
        ];
3649
        $isAdmin = api_is_platform_admin_by_id($userInfo['user_id']);
3650
        if (!$isAdmin && !in_array($userInfo['status'], $rolesAllowed)) {
3651
            return 0;
3652
        }
3653
3654
        $affected_rows = 0;
3655
        // Deleting assigned sessions to hrm_id.
3656
        if ($removeSessionsFromUser) {
3657
            if (api_is_multiple_url_enabled()) {
3658
                $sql = "SELECT s.session_id
3659
                        FROM $tbl_session_rel_user s
3660
                        INNER JOIN $tbl_session_rel_access_url a
3661
                        ON (a.session_id = s.session_id)
3662
                        WHERE
3663
                            s.user_id = $userId AND
3664
                            relation_type = ".SESSION_RELATION_TYPE_RRHH." AND
3665
                            access_url_id = ".api_get_current_access_url_id();
3666
            } else {
3667
                $sql = "SELECT s.session_id
3668
                        FROM $tbl_session_rel_user s
3669
                        WHERE user_id = $userId AND relation_type=".SESSION_RELATION_TYPE_RRHH;
3670
            }
3671
            $result = Database::query($sql);
3672
3673
            if (Database::num_rows($result) > 0) {
3674
                while ($row = Database::fetch_array($result)) {
3675
                    $sql = "DELETE FROM $tbl_session_rel_user
3676
                            WHERE
3677
                                session_id = {$row['session_id']} AND
3678
                                user_id = $userId AND
3679
                                relation_type =".SESSION_RELATION_TYPE_RRHH;
3680
                    Database::query($sql);
3681
3682
                    Event::addEvent(
3683
                        LOG_SESSION_DELETE_USER,
3684
                        LOG_USER_ID,
3685
                        $userId,
3686
                        api_get_utc_datetime(),
3687
                        api_get_user_id(),
3688
                        null,
3689
                        $row['session_id']
3690
                    );
3691
                }
3692
            }
3693
        }
3694
3695
        // Inserting new sessions list.
3696
        if (!empty($sessions_list) && is_array($sessions_list)) {
3697
            foreach ($sessions_list as $session_id) {
3698
                $session_id = (int) $session_id;
3699
                $sql = "SELECT session_id
3700
                        FROM $tbl_session_rel_user
3701
                        WHERE
3702
                            session_id = $session_id AND
3703
                            user_id = $userId AND
3704
                            relation_type = '".SESSION_RELATION_TYPE_RRHH."'";
3705
                $result = Database::query($sql);
3706
                if (Database::num_rows($result) == 0) {
3707
                    $sql = "INSERT IGNORE INTO $tbl_session_rel_user (session_id, user_id, relation_type, registered_at)
3708
                            VALUES (
3709
                                $session_id,
3710
                                $userId,
3711
                                '".SESSION_RELATION_TYPE_RRHH."',
3712
                                '".api_get_utc_datetime()."'
3713
                            )";
3714
                    Database::query($sql);
3715
3716
                    Event::addEvent(
3717
                        LOG_SESSION_ADD_USER,
3718
                        LOG_USER_ID,
3719
                        $userId,
3720
                        api_get_utc_datetime(),
3721
                        api_get_user_id(),
3722
                        null,
3723
                        $session_id
3724
                    );
3725
3726
                    $affected_rows++;
3727
                }
3728
            }
3729
        }
3730
3731
        return $affected_rows;
3732
    }
3733
3734
    /**
3735
     * @param int $sessionId
3736
     *
3737
     * @return array
3738
     */
3739
    public static function getDrhUsersInSession($sessionId)
3740
    {
3741
        return self::get_users_by_session($sessionId, SESSION_RELATION_TYPE_RRHH);
3742
    }
3743
3744
    /**
3745
     * @param int $userId
3746
     * @param int $sessionId
3747
     *
3748
     * @return array
3749
     */
3750
    public static function getSessionFollowedByDrh($userId, $sessionId)
3751
    {
3752
        $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
3753
        $tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
3754
        $tbl_session_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
3755
3756
        $userId = (int) $userId;
3757
        $sessionId = (int) $sessionId;
3758
3759
        $select = " SELECT * ";
3760
        if (api_is_multiple_url_enabled()) {
3761
            $sql = " $select FROM $tbl_session s
3762
                    INNER JOIN $tbl_session_rel_user sru ON (sru.session_id = s.id)
3763
                    LEFT JOIN $tbl_session_rel_access_url a ON (s.id = a.session_id)
3764
                    WHERE
3765
                        sru.user_id = '$userId' AND
3766
                        sru.session_id = '$sessionId' AND
3767
                        sru.relation_type = '".SESSION_RELATION_TYPE_RRHH."' AND
3768
                        access_url_id = ".api_get_current_access_url_id()."
3769
                    ";
3770
        } else {
3771
            $sql = "$select FROM $tbl_session s
3772
                     INNER JOIN $tbl_session_rel_user sru
3773
                     ON
3774
                        sru.session_id = s.id AND
3775
                        sru.user_id = '$userId' AND
3776
                        sru.session_id = '$sessionId' AND
3777
                        sru.relation_type = '".SESSION_RELATION_TYPE_RRHH."'
3778
                    ";
3779
        }
3780
3781
        $result = Database::query($sql);
3782
        if (Database::num_rows($result)) {
3783
            $row = Database::fetch_array($result, 'ASSOC');
3784
            $row['course_list'] = self::get_course_list_by_session_id($sessionId);
3785
3786
            return $row;
3787
        }
3788
3789
        return [];
3790
    }
3791
3792
    /**
3793
     * Get sessions followed by human resources manager.
3794
     *
3795
     * @param int    $userId
3796
     * @param int    $start
3797
     * @param int    $limit
3798
     * @param bool   $getCount
3799
     * @param bool   $getOnlySessionId
3800
     * @param bool   $getSql
3801
     * @param string $orderCondition
3802
     * @param string $keyword
3803
     * @param string $description
3804
     * @param array  $options
3805
     *
3806
     * @return array sessions
3807
     */
3808
    public static function get_sessions_followed_by_drh(
3809
        $userId,
3810
        $start = null,
3811
        $limit = null,
3812
        $getCount = false,
3813
        $getOnlySessionId = false,
3814
        $getSql = false,
3815
        $orderCondition = null,
3816
        $keyword = '',
3817
        $description = '',
3818
        $options = []
3819
    ) {
3820
        return self::getSessionsFollowedByUser(
3821
            $userId,
3822
            DRH,
3823
            $start,
3824
            $limit,
3825
            $getCount,
3826
            $getOnlySessionId,
3827
            $getSql,
3828
            $orderCondition,
3829
            $keyword,
3830
            $description,
3831
            $options
3832
        );
3833
    }
3834
3835
    /**
3836
     * Get sessions followed by human resources manager.
3837
     *
3838
     * @param int    $userId
3839
     * @param int    $status           DRH Optional
3840
     * @param int    $start
3841
     * @param int    $limit
3842
     * @param bool   $getCount
3843
     * @param bool   $getOnlySessionId
3844
     * @param bool   $getSql
3845
     * @param string $orderCondition
3846
     * @param string $keyword
3847
     * @param string $description
3848
     * @param array  $options
3849
     *
3850
     * @return array sessions
3851
     */
3852
    public static function getSessionsFollowedByUser(
3853
        $userId,
3854
        $status = null,
3855
        $start = null,
3856
        $limit = null,
3857
        $getCount = false,
3858
        $getOnlySessionId = false,
3859
        $getSql = false,
3860
        $orderCondition = null,
3861
        $keyword = '',
3862
        $description = '',
3863
        $options = []
3864
    ) {
3865
        // Database Table Definitions
3866
        $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
3867
        $tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
3868
        $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
3869
        $tbl_session_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
3870
3871
        $extraFieldModel = new ExtraFieldModel('session');
3872
        $conditions = $extraFieldModel->parseConditions($options);
3873
        $sqlInjectJoins = $conditions['inject_joins'];
3874
        $extraFieldsConditions = $conditions['where'];
3875
        $sqlInjectWhere = $conditions['inject_where'];
3876
        $injectExtraFields = $conditions['inject_extra_fields'];
3877
3878
        if (!empty($injectExtraFields)) {
3879
            $injectExtraFields = ' , '.$injectExtraFields.' s.id';
3880
        }
3881
3882
        $userId = (int) $userId;
3883
3884
        $select = ' SELECT DISTINCT * '.$injectExtraFields;
3885
        if ($getCount) {
3886
            $select = ' SELECT count(DISTINCT(s.id)) as count ';
3887
        }
3888
3889
        if ($getOnlySessionId) {
3890
            $select = ' SELECT DISTINCT(s.id) ';
3891
        }
3892
3893
        $limitCondition = null;
3894
        if (!is_null($start) && !is_null($limit)) {
3895
            $limitCondition = " LIMIT ".intval($start).", ".intval($limit);
3896
        }
3897
3898
        if (empty($orderCondition)) {
3899
            $orderCondition = ' ORDER BY s.name ';
3900
        }
3901
3902
        $whereConditions = null;
3903
        $sessionCourseConditions = null;
3904
        $sessionConditions = null;
3905
        $sessionQuery = '';
3906
        $courseSessionQuery = null;
3907
        switch ($status) {
3908
            case DRH:
3909
                $sessionQuery = "SELECT sru.session_id
3910
                                 FROM
3911
                                 $tbl_session_rel_user sru
3912
                                 WHERE
3913
                                    sru.relation_type = '".SESSION_RELATION_TYPE_RRHH."' AND
3914
                                    sru.user_id = $userId";
3915
                break;
3916
            case COURSEMANAGER:
3917
                $courseSessionQuery = "
3918
                    SELECT scu.session_id as id
3919
                    FROM $tbl_session_rel_course_rel_user scu
3920
                    WHERE (scu.status = 2 AND scu.user_id = $userId)";
3921
3922
                $whereConditions = " OR (s.id_coach = $userId) ";
3923
                break;
3924
            case SESSIONADMIN:
3925
                $sessionQuery = '';
3926
                if (api_get_setting('allow_session_admins_to_manage_all_sessions') != 'true') {
3927
                    $sqlInjectJoins .= " AND s.session_admin_id = $userId ";
3928
                }
3929
                break;
3930
            default:
3931
                $sessionQuery = "SELECT sru.session_id
3932
                                 FROM
3933
                                 $tbl_session_rel_user sru
3934
                                 WHERE
3935
                                    sru.user_id = $userId";
3936
                break;
3937
        }
3938
3939
        $keywordCondition = '';
3940
        if (!empty($keyword)) {
3941
            $keyword = Database::escape_string($keyword);
3942
            $keywordCondition = " AND (s.name LIKE '%$keyword%' ) ";
3943
3944
            if (!empty($description)) {
3945
                $description = Database::escape_string($description);
3946
                $keywordCondition = " AND (s.name LIKE '%$keyword%' OR s.description LIKE '%$description%' ) ";
3947
            }
3948
        }
3949
3950
        $whereConditions .= $keywordCondition;
3951
        $subQuery = $sessionQuery.$courseSessionQuery;
3952
3953
        if (!empty($subQuery)) {
3954
            $subQuery = " AND s.id IN ($subQuery)";
3955
        }
3956
3957
        $sql = " $select
3958
                FROM $tbl_session s
3959
                INNER JOIN $tbl_session_rel_access_url a
3960
                ON (s.id = a.session_id)
3961
                $sqlInjectJoins
3962
                WHERE
3963
                    access_url_id = ".api_get_current_access_url_id()."
3964
                    $subQuery
3965
                    $whereConditions
3966
                    $extraFieldsConditions
3967
                    $sqlInjectWhere
3968
                    $orderCondition
3969
                    $limitCondition";
3970
3971
        if ($getSql) {
3972
            return $sql;
3973
        }
3974
        $result = Database::query($sql);
3975
3976
        if ($getCount) {
3977
            $row = Database::fetch_array($result);
3978
            if ($row) {
3979
                return (int) $row['count'];
3980
            }
3981
3982
            return 0;
3983
        }
3984
3985
        $sessions = [];
3986
        if (Database::num_rows($result) > 0) {
3987
            $sysUploadPath = api_get_path(SYS_UPLOAD_PATH).'sessions/';
3988
            $webUploadPath = api_get_path(WEB_UPLOAD_PATH).'sessions/';
3989
            $imgPath = Display::return_icon(
3990
                'session_default_small.png',
3991
                null,
3992
                [],
3993
                ICON_SIZE_SMALL,
3994
                false,
3995
                true
3996
            );
3997
3998
            while ($row = Database::fetch_array($result)) {
3999
                if ($getOnlySessionId) {
4000
                    $sessions[$row['id']] = $row;
4001
                    continue;
4002
                }
4003
                $imageFilename = ExtraFieldModel::FIELD_TYPE_FILE_IMAGE.'_'.$row['id'].'.png';
4004
                $row['image'] = is_file($sysUploadPath.$imageFilename) ? $webUploadPath.$imageFilename : $imgPath;
4005
4006
                if ($row['display_start_date'] === '0000-00-00 00:00:00' || $row['display_start_date'] === '0000-00-00') {
4007
                    $row['display_start_date'] = null;
4008
                }
4009
4010
                if ($row['display_end_date'] === '0000-00-00 00:00:00' || $row['display_end_date'] === '0000-00-00') {
4011
                    $row['display_end_date'] = null;
4012
                }
4013
4014
                if ($row['access_start_date'] === '0000-00-00 00:00:00' || $row['access_start_date'] === '0000-00-00') {
4015
                    $row['access_start_date'] = null;
4016
                }
4017
4018
                if ($row['access_end_date'] === '0000-00-00 00:00:00' || $row['access_end_date'] === '0000-00-00') {
4019
                    $row['access_end_date'] = null;
4020
                }
4021
4022
                if ($row['coach_access_start_date'] === '0000-00-00 00:00:00' ||
4023
                    $row['coach_access_start_date'] === '0000-00-00'
4024
                ) {
4025
                    $row['coach_access_start_date'] = null;
4026
                }
4027
4028
                if ($row['coach_access_end_date'] === '0000-00-00 00:00:00' ||
4029
                    $row['coach_access_end_date'] === '0000-00-00'
4030
                ) {
4031
                    $row['coach_access_end_date'] = null;
4032
                }
4033
4034
                $sessions[$row['id']] = $row;
4035
            }
4036
        }
4037
4038
        return $sessions;
4039
    }
4040
4041
    /**
4042
     * Gets the list (or the count) of courses by session filtered by access_url.
4043
     *
4044
     * @param int    $session_id  The session id
4045
     * @param string $course_name The course code
4046
     * @param string $orderBy     Field to order the data
4047
     * @param bool   $getCount    Optional. Count the session courses
4048
     *
4049
     * @return array|int List of courses. Whether $getCount is true, return the count
4050
     */
4051
    public static function get_course_list_by_session_id(
4052
        $session_id,
4053
        $course_name = '',
4054
        $orderBy = null,
4055
        $getCount = false
4056
    ) {
4057
        $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
4058
        $tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
4059
        $session_id = (int) $session_id;
4060
        $sqlSelect = '*, c.id, c.id as real_id, c.code as course_code';
4061
4062
        if ($getCount) {
4063
            $sqlSelect = 'COUNT(1) as count';
4064
        }
4065
4066
        // select the courses
4067
        $sql = "SELECT $sqlSelect
4068
                FROM $tbl_course c
4069
                INNER JOIN $tbl_session_rel_course src
4070
                ON (c.id = src.c_id)
4071
		        WHERE src.session_id = '$session_id' ";
4072
4073
        if (!empty($course_name)) {
4074
            $course_name = Database::escape_string($course_name);
4075
            $sql .= " AND c.title LIKE '%$course_name%' ";
4076
        }
4077
4078
        if (!empty($orderBy)) {
4079
            $orderBy = Database::escape_string($orderBy);
4080
            $orderBy = " ORDER BY $orderBy";
4081
        } else {
4082
            if (self::orderCourseIsEnabled()) {
4083
                $orderBy .= ' ORDER BY position ';
4084
            } else {
4085
                $orderBy .= ' ORDER BY title ';
4086
            }
4087
        }
4088
4089
        $sql .= Database::escape_string($orderBy);
4090
        $result = Database::query($sql);
4091
        $num_rows = Database::num_rows($result);
4092
        $courses = [];
4093
        if ($num_rows > 0) {
4094
            if ($getCount) {
4095
                $count = Database::fetch_assoc($result);
4096
4097
                return (int) $count['count'];
4098
            }
4099
4100
            while ($row = Database::fetch_array($result, 'ASSOC')) {
4101
                $courses[$row['real_id']] = $row;
4102
            }
4103
        }
4104
4105
        return $courses;
4106
    }
4107
4108
    /**
4109
     * Gets the list of courses by session filtered by access_url.
4110
     *
4111
     * @param $userId
4112
     * @param $sessionId
4113
     * @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...
4114
     * @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...
4115
     * @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...
4116
     * @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...
4117
     * @param bool   $getCount
4118
     * @param string $keyword
4119
     *
4120
     * @return array
4121
     */
4122
    public static function getAllCoursesFollowedByUser(
4123
        $userId,
4124
        $sessionId,
4125
        $from = null,
4126
        $limit = null,
4127
        $column = null,
4128
        $direction = null,
4129
        $getCount = false,
4130
        $keyword = ''
4131
    ) {
4132
        if (empty($sessionId)) {
4133
            $sessionsSQL = self::get_sessions_followed_by_drh(
4134
                $userId,
4135
                null,
4136
                null,
4137
                null,
4138
                true,
4139
                true
4140
            );
4141
        } else {
4142
            $sessionsSQL = intval($sessionId);
4143
        }
4144
4145
        $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
4146
        $tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
4147
4148
        if ($getCount) {
4149
            $select = "SELECT COUNT(DISTINCT(c.code)) as count ";
4150
        } else {
4151
            $select = "SELECT DISTINCT c.* ";
4152
        }
4153
4154
        $keywordCondition = null;
4155
        if (!empty($keyword)) {
4156
            $keyword = Database::escape_string($keyword);
4157
            $keywordCondition = " AND (c.code LIKE '%$keyword%' OR c.title LIKE '%$keyword%' ) ";
4158
        }
4159
4160
        // Select the courses
4161
        $sql = "$select
4162
                FROM $tbl_course c
4163
                INNER JOIN $tbl_session_rel_course src
4164
                ON c.id = src.c_id
4165
		        WHERE
4166
		            src.session_id IN ($sessionsSQL)
4167
		            $keywordCondition
4168
		        ";
4169
        if ($getCount) {
4170
            $result = Database::query($sql);
4171
            $row = Database::fetch_array($result, 'ASSOC');
4172
4173
            return $row['count'];
4174
        }
4175
4176
        if (isset($from) && isset($limit)) {
4177
            $from = intval($from);
4178
            $limit = intval($limit);
4179
            $sql .= " LIMIT $from, $limit";
4180
        }
4181
4182
        $result = Database::query($sql);
4183
        $num_rows = Database::num_rows($result);
4184
        $courses = [];
4185
4186
        if ($num_rows > 0) {
4187
            while ($row = Database::fetch_array($result, 'ASSOC')) {
4188
                $courses[$row['id']] = $row;
4189
            }
4190
        }
4191
4192
        return $courses;
4193
    }
4194
4195
    /**
4196
     * Gets the list of courses by session filtered by access_url.
4197
     *
4198
     * @param int    $session_id
4199
     * @param string $course_name
4200
     *
4201
     * @return array list of courses
4202
     */
4203
    public static function get_course_list_by_session_id_like($session_id, $course_name = '')
4204
    {
4205
        $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
4206
        $tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
4207
4208
        $session_id = (int) $session_id;
4209
        $course_name = Database::escape_string($course_name);
4210
4211
        // select the courses
4212
        $sql = "SELECT c.id, c.title FROM $tbl_course c
4213
                INNER JOIN $tbl_session_rel_course src
4214
                ON c.id = src.c_id
4215
		        WHERE ";
4216
4217
        if (!empty($session_id)) {
4218
            $sql .= "src.session_id LIKE '$session_id' AND ";
4219
        }
4220
4221
        if (!empty($course_name)) {
4222
            $sql .= "UPPER(c.title) LIKE UPPER('%$course_name%') ";
4223
        }
4224
4225
        $sql .= "ORDER BY title;";
4226
        $result = Database::query($sql);
4227
        $num_rows = Database::num_rows($result);
4228
        $courses = [];
4229
        if ($num_rows > 0) {
4230
            while ($row = Database::fetch_array($result, 'ASSOC')) {
4231
                $courses[$row['id']] = $row;
4232
            }
4233
        }
4234
4235
        return $courses;
4236
    }
4237
4238
    /**
4239
     * Gets the count of courses by session filtered by access_url.
4240
     *
4241
     * @param int session id
4242
     * @param string $keyword
4243
     *
4244
     * @return array list of courses
4245
     */
4246
    public static function getCourseCountBySessionId($session_id, $keyword = '')
4247
    {
4248
        $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
4249
        $tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
4250
        $session_id = (int) $session_id;
4251
4252
        // select the courses
4253
        $sql = "SELECT COUNT(c.code) count
4254
                FROM $tbl_course c
4255
                INNER JOIN $tbl_session_rel_course src
4256
                ON c.id = src.c_id
4257
		        WHERE src.session_id = '$session_id' ";
4258
4259
        $keywordCondition = null;
4260
        if (!empty($keyword)) {
4261
            $keyword = Database::escape_string($keyword);
4262
            $keywordCondition = " AND (c.code LIKE '%$keyword%' OR c.title LIKE '%$keyword%' ) ";
4263
        }
4264
        $sql .= $keywordCondition;
4265
4266
        $result = Database::query($sql);
4267
        $num_rows = Database::num_rows($result);
4268
        if ($num_rows > 0) {
4269
            $row = Database::fetch_array($result, 'ASSOC');
4270
4271
            return $row['count'];
4272
        }
4273
4274
        return null;
4275
    }
4276
4277
    /**
4278
     * Get the session id based on the original id and field name in the extra fields.
4279
     * Returns 0 if session was not found.
4280
     *
4281
     * @param string $value    Original session id
4282
     * @param string $variable Original field name
4283
     *
4284
     * @return int Session id
4285
     */
4286
    public static function getSessionIdFromOriginalId($value, $variable)
4287
    {
4288
        $extraFieldValue = new ExtraFieldValue('session');
4289
        $result = $extraFieldValue->get_item_id_from_field_variable_and_field_value(
4290
            $variable,
4291
            $value
4292
        );
4293
4294
        if (!empty($result)) {
4295
            return $result['item_id'];
4296
        }
4297
4298
        return 0;
4299
    }
4300
4301
    /**
4302
     * Get users by session.
4303
     *
4304
     * @param int  $id       session id
4305
     * @param int  $status   filter by status coach = 2
4306
     * @param bool $getCount Optional. Allow get the number of rows from the result
4307
     * @param int  $urlId
4308
     *
4309
     * @return array|int A list with an user list. If $getCount is true then return a the count of registers
4310
     */
4311
    public static function get_users_by_session(
4312
        $id,
4313
        $status = null,
4314
        $getCount = false,
4315
        $urlId = 0
4316
    ) {
4317
        if (empty($id)) {
4318
            return [];
4319
        }
4320
        $id = (int) $id;
4321
        $urlId = empty($urlId) ? api_get_current_access_url_id() : (int) $urlId;
4322
4323
        $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
4324
        $tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
4325
        $table_access_url_user = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
4326
4327
        $selectedField = '
4328
            u.id as user_id, u.lastname, u.firstname, u.username, su.relation_type, au.access_url_id,
4329
            su.moved_to, su.moved_status, su.moved_at, su.registered_at
4330
        ';
4331
4332
        if ($getCount) {
4333
            $selectedField = 'count(1) AS count';
4334
        }
4335
4336
        $sql = "SELECT $selectedField
4337
                FROM $tbl_user u
4338
                INNER JOIN $tbl_session_rel_user su
4339
                ON u.user_id = su.user_id AND
4340
                su.session_id = $id
4341
                LEFT OUTER JOIN $table_access_url_user au
4342
                ON (au.user_id = u.user_id)
4343
                ";
4344
4345
        if (is_numeric($status)) {
4346
            $status = (int) $status;
4347
            $sql .= " WHERE su.relation_type = $status AND (au.access_url_id = $urlId OR au.access_url_id is null)";
4348
        } else {
4349
            $sql .= " WHERE (au.access_url_id = $urlId OR au.access_url_id is null )";
4350
        }
4351
4352
        $sql .= ' ORDER BY su.relation_type, ';
4353
        $sql .= api_sort_by_first_name() ? ' u.firstname, u.lastname' : '  u.lastname, u.firstname';
4354
4355
        $result = Database::query($sql);
4356
        if ($getCount) {
4357
            $count = Database::fetch_assoc($result);
4358
            if ($count) {
4359
                return (int) $count['count'];
4360
            }
4361
4362
            return 0;
4363
        }
4364
4365
        $return = [];
4366
        while ($row = Database::fetch_array($result, 'ASSOC')) {
4367
            $return[] = $row;
4368
        }
4369
4370
        return $return;
4371
    }
4372
4373
    /**
4374
     * The general coach (field: session.id_coach).
4375
     *
4376
     * @param int  $user_id         user id
4377
     * @param bool $asPlatformAdmin The user is platform admin, return everything
4378
     *
4379
     * @return array
4380
     */
4381
    public static function get_sessions_by_general_coach($user_id, $asPlatformAdmin = false)
4382
    {
4383
        $session_table = Database::get_main_table(TABLE_MAIN_SESSION);
4384
        $user_id = (int) $user_id;
4385
4386
        // Session where we are general coach
4387
        $sql = "SELECT DISTINCT *
4388
                FROM $session_table";
4389
4390
        if (!$asPlatformAdmin) {
4391
            $sql .= " WHERE id_coach = $user_id";
4392
        }
4393
4394
        if (api_is_multiple_url_enabled()) {
4395
            $tbl_session_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
4396
            $access_url_id = api_get_current_access_url_id();
4397
4398
            $sqlCoach = '';
4399
            if (!$asPlatformAdmin) {
4400
                $sqlCoach = " id_coach = $user_id AND ";
4401
            }
4402
4403
            if ($access_url_id != -1) {
4404
                $sql = 'SELECT DISTINCT session.*
4405
                    FROM '.$session_table.' session INNER JOIN '.$tbl_session_rel_access_url.' session_rel_url
4406
                    ON (session.id = session_rel_url.session_id)
4407
                    WHERE '.$sqlCoach.' access_url_id = '.$access_url_id;
4408
            }
4409
        }
4410
        $sql .= ' ORDER by name';
4411
        $result = Database::query($sql);
4412
4413
        return Database::store_result($result, 'ASSOC');
4414
    }
4415
4416
    /**
4417
     * @param int $user_id
4418
     *
4419
     * @return array
4420
     *
4421
     * @deprecated use get_sessions_by_general_coach()
4422
     */
4423
    public static function get_sessions_by_coach($user_id)
4424
    {
4425
        $session_table = Database::get_main_table(TABLE_MAIN_SESSION);
4426
4427
        return Database::select(
4428
            '*',
4429
            $session_table,
4430
            ['where' => ['id_coach = ?' => $user_id]]
4431
        );
4432
    }
4433
4434
    /**
4435
     * @param int $user_id
4436
     * @param int $courseId
4437
     * @param int $session_id
4438
     *
4439
     * @return array|bool
4440
     */
4441
    public static function get_user_status_in_course_session($user_id, $courseId, $session_id)
4442
    {
4443
        $table = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
4444
        $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
4445
        $sql = "SELECT session_rcru.status
4446
                FROM $table session_rcru
4447
                INNER JOIN $tbl_user user
4448
                ON (session_rcru.user_id = user.user_id)
4449
                WHERE
4450
                    session_rcru.session_id = '".intval($session_id)."' AND
4451
                    session_rcru.c_id ='".intval($courseId)."' AND
4452
                    user.user_id = ".intval($user_id);
4453
4454
        $result = Database::query($sql);
4455
        $status = false;
4456
        if (Database::num_rows($result)) {
4457
            $status = Database::fetch_row($result);
4458
            $status = $status['0'];
4459
        }
4460
4461
        return $status;
4462
    }
4463
4464
    /**
4465
     * Gets user status within a session.
4466
     *
4467
     * @param int $userId
4468
     * @param int $sessionId
4469
     *
4470
     * @return SessionRelUser
4471
     */
4472
    public static function getUserStatusInSession($userId, $sessionId)
4473
    {
4474
        $em = Database::getManager();
4475
        $subscriptions = $em
4476
            ->getRepository('ChamiloCoreBundle:SessionRelUser')
4477
            ->findBy(['session' => $sessionId, 'user' => $userId]);
4478
4479
        /** @var SessionRelUser $subscription */
4480
        $subscription = current($subscriptions);
4481
4482
        return $subscription;
4483
    }
4484
4485
    /**
4486
     * @param int $id
4487
     *
4488
     * @return array
4489
     */
4490
    public static function get_all_sessions_by_promotion($id)
4491
    {
4492
        $table = Database::get_main_table(TABLE_MAIN_SESSION);
4493
4494
        return Database::select(
4495
            '*',
4496
            $table,
4497
            ['where' => ['promotion_id = ?' => $id]]
4498
        );
4499
    }
4500
4501
    /**
4502
     * @param int   $promotion_id
4503
     * @param array $list
4504
     */
4505
    public static function subscribe_sessions_to_promotion($promotion_id, $list)
4506
    {
4507
        $table = Database::get_main_table(TABLE_MAIN_SESSION);
4508
        $params = [];
4509
        $params['promotion_id'] = 0;
4510
        Database::update(
4511
            $table,
4512
            $params,
4513
            ['promotion_id = ?' => $promotion_id]
4514
        );
4515
4516
        $params['promotion_id'] = $promotion_id;
4517
        if (!empty($list)) {
4518
            foreach ($list as $session_id) {
4519
                $session_id = (int) $session_id;
4520
                Database::update($table, $params, ['id = ?' => $session_id]);
4521
            }
4522
        }
4523
    }
4524
4525
    /**
4526
     * Updates a session status.
4527
     *
4528
     * @param int session id
4529
     * @param int status
4530
     */
4531
    public static function set_session_status($session_id, $status)
4532
    {
4533
        $t = Database::get_main_table(TABLE_MAIN_SESSION);
4534
        $params['visibility'] = $status;
4535
        Database::update($t, $params, ['id = ?' => $session_id]);
4536
    }
4537
4538
    /**
4539
     * Copies a session with the same data to a new session.
4540
     * The new copy is not assigned to the same promotion.
4541
     *
4542
     * @param int  $id                         Session ID
4543
     * @param bool $copy_courses               Whether to copy the relationship with courses
4544
     * @param bool $copyTeachersAndDrh
4545
     * @param bool $create_new_courses         New courses will be created
4546
     * @param bool $set_exercises_lp_invisible Set exercises and LPs in the new session to invisible by default
4547
     * @param bool $copyWithSessionContent     Copy course session content into the courses
4548
     *
4549
     * @return int The new session ID on success, 0 otherwise
4550
     *
4551
     * @see subscribe_sessions_to_promotions() for that.
4552
     *
4553
     * @todo make sure the extra session fields are copied too
4554
     */
4555
    public static function copy(
4556
        $id,
4557
        $copy_courses = true,
4558
        $copyTeachersAndDrh = true,
4559
        $create_new_courses = false,
4560
        $set_exercises_lp_invisible = false,
4561
        $copyWithSessionContent = false
4562
    ) {
4563
        $id = (int) $id;
4564
        $s = self::fetch($id);
4565
4566
        if (empty($s)) {
4567
            return false;
4568
        }
4569
4570
        // Check all dates before copying
4571
        // Get timestamp for now in UTC - see http://php.net/manual/es/function.time.php#117251
4572
        $now = time() - date('Z');
4573
        // Timestamp in one month
4574
        $inOneMonth = $now + (30 * 24 * 3600);
4575
        $inOneMonth = api_get_local_time($inOneMonth);
4576
        if (api_strtotime($s['access_start_date']) < $now) {
4577
            $s['access_start_date'] = api_get_local_time($now);
4578
        } else {
4579
            $s['access_start_date'] = api_get_local_time($s['access_start_date']);
4580
        }
4581
        if (api_strtotime($s['display_start_date']) < $now) {
4582
            $s['display_start_date'] = api_get_local_time($now);
4583
        } else {
4584
            $s['display_start_date'] = api_get_local_time($s['display_start_date']);
4585
        }
4586
        if (api_strtotime($s['coach_access_start_date']) < $now) {
4587
            $s['coach_access_start_date'] = api_get_local_time($now);
4588
        } else {
4589
            $s['coach_access_start_date'] = api_get_local_time($s['coach_access_start_date']);
4590
        }
4591
        if (api_strtotime($s['access_end_date']) < $now) {
4592
            $s['access_end_date'] = $inOneMonth;
4593
        } else {
4594
            $s['access_end_date'] = api_get_local_time($s['access_end_date']);
4595
        }
4596
        if (api_strtotime($s['display_end_date']) < $now) {
4597
            $s['display_end_date'] = $inOneMonth;
4598
        } else {
4599
            $s['display_end_date'] = api_get_local_time($s['display_end_date']);
4600
        }
4601
        if (api_strtotime($s['coach_access_end_date']) < $now) {
4602
            $s['coach_access_end_date'] = $inOneMonth;
4603
        } else {
4604
            $s['coach_access_end_date'] = api_get_local_time($s['coach_access_end_date']);
4605
        }
4606
4607
        $extraFieldValue = new ExtraFieldValue('session');
4608
        $extraFieldsValues = $extraFieldValue->getAllValuesByItem($id);
4609
        $extraFieldsValuesToCopy = [];
4610
        if (!empty($extraFieldsValues)) {
4611
            foreach ($extraFieldsValues as $extraFieldValue) {
4612
                $extraFieldsValuesToCopy['extra_'.$extraFieldValue['variable']]['extra_'.$extraFieldValue['variable']] = $extraFieldValue['value'];
4613
            }
4614
        }
4615
4616
        if (isset($extraFieldsValuesToCopy['extra_image']) && isset($extraFieldsValuesToCopy['extra_image']['extra_image'])) {
4617
            $extraFieldsValuesToCopy['extra_image'] = [
4618
                'tmp_name' => api_get_path(SYS_UPLOAD_PATH).$extraFieldsValuesToCopy['extra_image']['extra_image'],
4619
                'error' => 0,
4620
            ];
4621
        }
4622
4623
        // Now try to create the session
4624
        $sid = self::create_session(
4625
            $s['name'].' '.get_lang('CopyLabelSuffix'),
4626
            $s['access_start_date'],
4627
            $s['access_end_date'],
4628
            $s['display_start_date'],
4629
            $s['display_end_date'],
4630
            $s['coach_access_start_date'],
4631
            $s['coach_access_end_date'],
4632
            (int) $s['id_coach'],
4633
            $s['session_category_id'],
4634
            (int) $s['visibility'],
4635
            true,
4636
            $s['duration'],
4637
            $s['description'],
4638
            $s['show_description'],
4639
            $extraFieldsValuesToCopy,
4640
            0,
4641
            $s['send_subscription_notification']
4642
        );
4643
4644
        if (!is_numeric($sid) || empty($sid)) {
4645
            return false;
4646
        }
4647
4648
        if ($copy_courses) {
4649
            // Register courses from the original session to the new session
4650
            $courses = self::get_course_list_by_session_id($id);
4651
            $short_courses = $new_short_courses = [];
4652
            if (is_array($courses) && count($courses) > 0) {
4653
                foreach ($courses as $course) {
4654
                    $short_courses[] = $course;
4655
                }
4656
            }
4657
4658
            // We will copy the current courses of the session to new courses
4659
            if (!empty($short_courses)) {
4660
                if ($create_new_courses) {
4661
                    api_set_more_memory_and_time_limits();
4662
                    $params = [];
4663
                    $params['skip_lp_dates'] = true;
4664
4665
                    foreach ($short_courses as $course_data) {
4666
                        $course_info = CourseManager::copy_course_simple(
4667
                            $course_data['title'].' '.get_lang('CopyLabelSuffix'),
4668
                            $course_data['course_code'],
4669
                            $id,
4670
                            $sid,
4671
                            $params
4672
                        );
4673
4674
                        if ($course_info) {
4675
                            //By default new elements are invisible
4676
                            if ($set_exercises_lp_invisible) {
4677
                                $list = new LearnpathList('', $course_info, $sid);
4678
                                $flat_list = $list->get_flat_list();
4679
                                if (!empty($flat_list)) {
4680
                                    foreach ($flat_list as $lp_id => $data) {
4681
                                        api_item_property_update(
4682
                                            $course_info,
4683
                                            TOOL_LEARNPATH,
4684
                                            $lp_id,
4685
                                            'invisible',
4686
                                            api_get_user_id(),
4687
                                            0,
4688
                                            0,
4689
                                            0,
4690
                                            0,
4691
                                            $sid
4692
                                        );
4693
                                    }
4694
                                }
4695
                                $quiz_table = Database::get_course_table(TABLE_QUIZ_TEST);
4696
                                $course_id = $course_info['real_id'];
4697
                                //@todo check this query
4698
                                $sql = "UPDATE $quiz_table SET active = 0
4699
                                        WHERE c_id = $course_id AND session_id = $sid";
4700
                                Database::query($sql);
4701
                            }
4702
                            $new_short_courses[] = $course_info['real_id'];
4703
                        }
4704
                    }
4705
                } else {
4706
                    foreach ($short_courses as $course_data) {
4707
                        $new_short_courses[] = $course_data['id'];
4708
                    }
4709
                }
4710
4711
                $short_courses = $new_short_courses;
4712
                self::add_courses_to_session($sid, $short_courses, true);
4713
4714
                if ($copyWithSessionContent) {
4715
                    foreach ($courses as $course) {
4716
                        CourseManager::copy_course(
4717
                            $course['code'],
4718
                            $id,
4719
                            $course['code'],
4720
                            $sid,
4721
                            [],
4722
                            false,
4723
                            true
4724
                        );
4725
                    }
4726
                }
4727
4728
                if ($create_new_courses === false && $copyTeachersAndDrh) {
4729
                    foreach ($short_courses as $courseItemId) {
4730
                        $coachList = self::getCoachesByCourseSession($id, $courseItemId);
4731
                        foreach ($coachList as $userId) {
4732
                            self::set_coach_to_course_session($userId, $sid, $courseItemId);
4733
                        }
4734
                    }
4735
                }
4736
            }
4737
        }
4738
4739
        if ($copyTeachersAndDrh) {
4740
            // Register users from the original session to the new session
4741
            $users = self::get_users_by_session($id);
4742
            if (!empty($users)) {
4743
                $userListByStatus = [];
4744
                foreach ($users as $userData) {
4745
                    $userData['relation_type'] = (int) $userData['relation_type'];
4746
                    $userListByStatus[$userData['relation_type']][] = $userData;
4747
                }
4748
4749
                foreach ($userListByStatus as $status => $userList) {
4750
                    $userList = array_column($userList, 'user_id');
4751
                    switch ($status) {
4752
                        case 0:
4753
                            /*self::subscribeUsersToSession(
4754
                                $sid,
4755
                                $userList,
4756
                                SESSION_VISIBLE_READ_ONLY,
4757
                                false,
4758
                                true
4759
                            );*/
4760
                            break;
4761
                        case 1:
4762
                            // drh users
4763
                            foreach ($userList as $drhId) {
4764
                                $userInfo = api_get_user_info($drhId);
4765
                                self::subscribeSessionsToDrh($userInfo, [$sid], false, false);
4766
                            }
4767
                            break;
4768
                    }
4769
                }
4770
            }
4771
        }
4772
4773
        return $sid;
4774
    }
4775
4776
    /**
4777
     * @param int $user_id
4778
     * @param int $session_id
4779
     *
4780
     * @return bool
4781
     */
4782
    public static function user_is_general_coach($user_id, $session_id)
4783
    {
4784
        $session_id = (int) $session_id;
4785
        $user_id = (int) $user_id;
4786
        $table = Database::get_main_table(TABLE_MAIN_SESSION);
4787
        $sql = "SELECT DISTINCT id
4788
	         	FROM $table
4789
	         	WHERE session.id_coach = '".$user_id."' AND id = '$session_id'";
4790
        $result = Database::query($sql);
4791
        if ($result && Database::num_rows($result)) {
4792
            return true;
4793
        }
4794
4795
        return false;
4796
    }
4797
4798
    /**
4799
     * Get the number of sessions.
4800
     *
4801
     * @param int $access_url_id ID of the URL we want to filter on (optional)
4802
     *
4803
     * @return int Number of sessions
4804
     */
4805
    public static function count_sessions($access_url_id = 0)
4806
    {
4807
        $session_table = Database::get_main_table(TABLE_MAIN_SESSION);
4808
        $access_url_rel_session_table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
4809
        $access_url_id = (int) $access_url_id;
4810
        $sql = "SELECT count(s.id) FROM $session_table s";
4811
        if (!empty($access_url_id)) {
4812
            $sql .= ", $access_url_rel_session_table u ".
4813
                " WHERE s.id = u.session_id AND u.access_url_id = $access_url_id";
4814
        }
4815
        $res = Database::query($sql);
4816
        $row = Database::fetch_row($res);
4817
4818
        return $row[0];
4819
    }
4820
4821
    /**
4822
     * @param int  $id
4823
     * @param bool $checkSession
4824
     *
4825
     * @return bool
4826
     */
4827
    public static function cantEditSession($id, $checkSession = true)
4828
    {
4829
        if (!self::allowToManageSessions()) {
4830
            return false;
4831
        }
4832
4833
        if (api_is_platform_admin() && self::allowed($id)) {
4834
            return true;
4835
        }
4836
4837
        if ($checkSession) {
4838
            if (self::allowed($id)) {
4839
                return true;
4840
            }
4841
4842
            return false;
4843
        }
4844
4845
        return true;
4846
    }
4847
4848
    /**
4849
     * Protect a session to be edited.
4850
     *
4851
     * @param int  $id
4852
     * @param bool $checkSession
4853
     *
4854
     * @return mixed|bool true if pass the check, api_not_allowed otherwise
4855
     */
4856
    public static function protectSession($id, $checkSession = true)
4857
    {
4858
        if (!self::cantEditSession($id, $checkSession)) {
4859
            api_not_allowed(true);
4860
        }
4861
    }
4862
4863
    /**
4864
     * @return bool
4865
     */
4866
    public static function allowToManageSessions()
4867
    {
4868
        if (self::allowManageAllSessions()) {
4869
            return true;
4870
        }
4871
4872
        $setting = api_get_setting('allow_teachers_to_create_sessions');
4873
4874
        if (api_is_teacher() && $setting == 'true') {
4875
            return true;
4876
        }
4877
4878
        return false;
4879
    }
4880
4881
    /**
4882
     * @return bool
4883
     */
4884
    public static function allowOnlyMySessions()
4885
    {
4886
        if (self::allowToManageSessions() &&
4887
            !api_is_platform_admin() &&
4888
            api_is_teacher()
4889
        ) {
4890
            return true;
4891
        }
4892
4893
        return false;
4894
    }
4895
4896
    /**
4897
     * @return bool
4898
     */
4899
    public static function allowManageAllSessions()
4900
    {
4901
        if (api_is_platform_admin() || api_is_session_admin()) {
4902
            return true;
4903
        }
4904
4905
        return false;
4906
    }
4907
4908
    /**
4909
     * @param $id
4910
     *
4911
     * @return bool
4912
     */
4913
    public static function protect_teacher_session_edit($id)
4914
    {
4915
        if (!api_is_coach($id) && !api_is_platform_admin()) {
4916
            api_not_allowed(true);
4917
        } else {
4918
            return true;
4919
        }
4920
    }
4921
4922
    /**
4923
     * @todo Add param to get only active sessions (not expires ones)
4924
     */
4925
    public static function get_session_by_course(int $courseId, ?string $startDate = null, ?string $endDate = null): array
4926
    {
4927
        $table_session_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
4928
        $table_session = Database::get_main_table(TABLE_MAIN_SESSION);
4929
        $url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
4930
        $courseId = (int) $courseId;
4931
        $urlId = api_get_current_access_url_id();
4932
4933
        if (empty($courseId)) {
4934
            return [];
4935
        }
4936
4937
        $dateCondition = '';
4938
        if ($startDate && $endDate) {
4939
            $dateCondition .= "AND (s.display_start_date BETWEEN '$startDate' AND '$endDate' OR s.display_end_date BETWEEN '$startDate' AND '$endDate') ";
4940
        } elseif ($startDate) {
4941
            $dateCondition .= "AND s.display_start_date >= '$startDate' ";
4942
        } elseif ($endDate) {
4943
            $dateCondition .= "AND s.display_end_date <= '$endDate' ";
4944
        }
4945
4946
        $sql = "SELECT name, s.id
4947
            FROM $table_session_course sc
4948
            INNER JOIN $table_session s
4949
            ON (sc.session_id = s.id)
4950
            INNER JOIN $url u
4951
            ON (u.session_id = s.id)
4952
            WHERE
4953
                u.access_url_id = $urlId AND
4954
                sc.c_id = '$courseId'
4955
                $dateCondition";
4956
        $result = Database::query($sql);
4957
4958
        return Database::store_result($result);
4959
    }
4960
4961
    /**
4962
     * @param int  $userId
4963
     * @param bool $ignoreVisibilityForAdmins
4964
     * @param bool $ignoreTimeLimit
4965
     *
4966
     * @return array
4967
     */
4968
    public static function get_sessions_by_user(
4969
        $userId,
4970
        $ignoreVisibilityForAdmins = false,
4971
        $ignoreTimeLimit = false
4972
    ) {
4973
        $sessionCategories = UserManager::get_sessions_by_category(
4974
            $userId,
4975
            false,
4976
            $ignoreVisibilityForAdmins,
4977
            $ignoreTimeLimit
4978
        );
4979
4980
        $sessionArray = [];
4981
        if (!empty($sessionCategories)) {
4982
            foreach ($sessionCategories as $category) {
4983
                if (isset($category['sessions'])) {
4984
                    foreach ($category['sessions'] as $session) {
4985
                        $sessionArray[] = $session;
4986
                    }
4987
                }
4988
            }
4989
        }
4990
4991
        return $sessionArray;
4992
    }
4993
4994
    /**
4995
     * @param string $file
4996
     * @param bool   $updateSession                                   true: if the session exists it will be updated.
4997
     *                                                                false: if session exists a new session will be
4998
     *                                                                created adding a counter session1, session2, etc
4999
     * @param int    $defaultUserId
5000
     * @param Logger $logger
5001
     * @param array  $extraFields                                     convert a file row to an extra field. Example in
5002
     *                                                                CSV file there's a SessionID then it will
5003
     *                                                                converted to extra_external_session_id if you
5004
     *                                                                set: array('SessionId' =>
5005
     *                                                                'extra_external_session_id')
5006
     * @param string $extraFieldId
5007
     * @param int    $daysCoachAccessBeforeBeginning
5008
     * @param int    $daysCoachAccessAfterBeginning
5009
     * @param int    $sessionVisibility
5010
     * @param array  $fieldsToAvoidUpdate
5011
     * @param bool   $deleteUsersNotInList
5012
     * @param bool   $updateCourseCoaches
5013
     * @param bool   $sessionWithCoursesModifier
5014
     * @param bool   $addOriginalCourseTeachersAsCourseSessionCoaches
5015
     * @param bool   $removeAllTeachersFromCourse
5016
     * @param int    $showDescription
5017
     * @param array  $teacherBackupList
5018
     * @param array  $groupBackup
5019
     *
5020
     * @return array
5021
     */
5022
    public static function importCSV(
5023
        $file,
5024
        $updateSession,
5025
        $defaultUserId = null,
5026
        $logger = null,
5027
        $extraFields = [],
5028
        $extraFieldId = null,
5029
        $daysCoachAccessBeforeBeginning = null,
5030
        $daysCoachAccessAfterBeginning = null,
5031
        $sessionVisibility = 1,
5032
        $fieldsToAvoidUpdate = [],
5033
        $deleteUsersNotInList = false,
5034
        $updateCourseCoaches = false,
5035
        $sessionWithCoursesModifier = false,
5036
        $addOriginalCourseTeachersAsCourseSessionCoaches = true,
5037
        $removeAllTeachersFromCourse = true,
5038
        $showDescription = null,
5039
        &$teacherBackupList = [],
5040
        &$groupBackup = []
5041
    ) {
5042
        $content = file($file);
5043
        $error_message = null;
5044
        $session_counter = 0;
5045
        $defaultUserId = empty($defaultUserId) ? api_get_user_id() : (int) $defaultUserId;
5046
5047
        $eol = PHP_EOL;
5048
        if (PHP_SAPI != 'cli') {
5049
            $eol = '<br />';
5050
        }
5051
5052
        $debug = false;
5053
        if (isset($logger)) {
5054
            $debug = true;
5055
        }
5056
5057
        $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
5058
        $tbl_session_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
5059
        $tbl_session_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
5060
        $tbl_session_course_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
5061
        $sessions = [];
5062
        if (!api_strstr($content[0], ';')) {
5063
            $error_message = get_lang('NotCSV');
5064
        } else {
5065
            $tag_names = [];
5066
            foreach ($content as $key => $enreg) {
5067
                $enreg = explode(';', trim($enreg));
5068
                if ($key) {
5069
                    foreach ($tag_names as $tag_key => $tag_name) {
5070
                        if (isset($enreg[$tag_key])) {
5071
                            $sessions[$key - 1][$tag_name] = $enreg[$tag_key];
5072
                        }
5073
                    }
5074
                } else {
5075
                    foreach ($enreg as $tag_name) {
5076
                        $tag_names[] = api_preg_replace('/[^a-zA-Z0-9_\-]/', '', $tag_name);
5077
                    }
5078
                    if (!in_array('SessionName', $tag_names) ||
5079
                        !in_array('DateStart', $tag_names) ||
5080
                        !in_array('DateEnd', $tag_names)
5081
                    ) {
5082
                        $error_message = get_lang('NoNeededData');
5083
                        break;
5084
                    }
5085
                }
5086
            }
5087
5088
            $sessionList = [];
5089
            $report = [];
5090
5091
            // Looping the sessions.
5092
            foreach ($sessions as $enreg) {
5093
                $user_counter = 0;
5094
                $course_counter = 0;
5095
5096
                if (isset($extraFields) && !empty($extraFields)) {
5097
                    foreach ($extraFields as $original => $to) {
5098
                        $enreg[$to] = isset($enreg[$original]) ? $enreg[$original] : null;
5099
                    }
5100
                }
5101
5102
                $session_name = trim(trim(api_utf8_decode($enreg['SessionName']), '"'));
5103
5104
                if ($debug) {
5105
                    $logger->addInfo('---------------------------------------');
5106
                    $logger->addInfo("Sessions - Start process of session: $session_name");
5107
                    $logger->addInfo('---------------------------------------');
5108
                }
5109
5110
                // Default visibility
5111
                $visibilityAfterExpirationPerSession = $sessionVisibility;
5112
5113
                if (isset($enreg['VisibilityAfterExpiration'])) {
5114
                    $visibility = $enreg['VisibilityAfterExpiration'];
5115
                    switch ($visibility) {
5116
                        case 'read_only':
5117
                            $visibilityAfterExpirationPerSession = SESSION_VISIBLE_READ_ONLY;
5118
                            break;
5119
                        case 'accessible':
5120
                            $visibilityAfterExpirationPerSession = SESSION_VISIBLE;
5121
                            break;
5122
                        case 'not_accessible':
5123
                            $visibilityAfterExpirationPerSession = SESSION_INVISIBLE;
5124
                            break;
5125
                    }
5126
                }
5127
5128
                if (empty($session_name)) {
5129
                    continue;
5130
                }
5131
5132
                $displayAccessStartDate = $enreg['DisplayStartDate'] ?? $enreg['DateStart'];
5133
                $displayAccessEndDate = $enreg['DisplayEndDate'] ?? $enreg['DateEnd'];
5134
                $coachAccessStartDate = $enreg['CoachStartDate'] ?? $enreg['DateStart'];
5135
                $coachAccessEndDate = $enreg['CoachEndDate'] ?? $enreg['DateEnd'];
5136
                // We assume the dates are already in UTC
5137
                $dateStart = explode('/', $enreg['DateStart']);
5138
                $dateEnd = explode('/', $enreg['DateEnd']);
5139
                $dateStart = $dateStart[0].'-'.$dateStart[1].'-'.$dateStart[2].' 00:00:00';
5140
                $dateEnd = $dateEnd[0].'-'.$dateEnd[1].'-'.$dateEnd[2].' 23:59:59';
5141
                $displayAccessStartDate = explode('/', $displayAccessStartDate);
5142
                $displayAccessStartDate = implode('-', $displayAccessStartDate).' 00:00:00';
5143
                $displayAccessEndDate = explode('/', $displayAccessEndDate);
5144
                $displayAccessEndDate = implode('-', $displayAccessEndDate).' 23:59:59';
5145
                $coachAccessStartDate = explode('/', $coachAccessStartDate);
5146
                $coachAccessStartDate = implode('-', $coachAccessStartDate).' 00:00:00';
5147
                $coachAccessEndDate = explode('/', $coachAccessEndDate);
5148
                $coachAccessEndDate = implode('-', $coachAccessEndDate).' 23:59:59';
5149
                $session_category_id = $enreg['SessionCategory'] ?? null;
5150
                $sessionDescription = $enreg['SessionDescription'] ?? null;
5151
                $classes = isset($enreg['Classes']) ? explode('|', $enreg['Classes']) : [];
5152
                $extraParams = [];
5153
                if (!is_null($showDescription)) {
5154
                    $extraParams['show_description'] = intval($showDescription);
5155
                }
5156
5157
                $coachBefore = '';
5158
                $coachAfter = '';
5159
                if (!empty($daysCoachAccessBeforeBeginning) && !empty($daysCoachAccessAfterBeginning)) {
5160
                    $date = new DateTime($dateStart);
5161
                    $interval = new DateInterval('P'.$daysCoachAccessBeforeBeginning.'D');
5162
                    $date->sub($interval);
5163
                    $coachBefore = $date->format('Y-m-d h:i');
5164
                    $coachAccessStartDate = $coachBefore;
5165
                    $coachBefore = api_get_utc_datetime($coachBefore);
5166
5167
                    $date = new DateTime($dateEnd);
5168
                    $interval = new DateInterval('P'.$daysCoachAccessAfterBeginning.'D');
5169
                    $date->add($interval);
5170
                    $coachAfter = $date->format('Y-m-d h:i');
5171
                    $coachAccessEndDate = $coachAfter;
5172
                    $coachAfter = api_get_utc_datetime($coachAfter);
5173
                }
5174
5175
                $dateStart = api_get_utc_datetime($dateStart);
5176
                $dateEnd = api_get_utc_datetime($dateEnd);
5177
                $displayAccessStartDate = api_get_utc_datetime($displayAccessStartDate);
5178
                $displayAccessEndDate = api_get_utc_datetime($displayAccessEndDate);
5179
                $coachAccessStartDate = api_get_utc_datetime($coachAccessStartDate);
5180
                $coachAccessEndDate = api_get_utc_datetime($coachAccessEndDate);
5181
5182
                if (!empty($sessionDescription)) {
5183
                    $extraParams['description'] = $sessionDescription;
5184
                }
5185
5186
                if (!empty($session_category_id)) {
5187
                    $extraParams['session_category_id'] = $session_category_id;
5188
                }
5189
5190
                // Searching a general coach.
5191
                if (!empty($enreg['Coach'])) {
5192
                    $coach_id = UserManager::get_user_id_from_username($enreg['Coach']);
5193
                    if ($coach_id === false) {
5194
                        // If the coach-user does not exist - I'm the coach.
5195
                        $coach_id = $defaultUserId;
5196
                    }
5197
                } else {
5198
                    $coach_id = $defaultUserId;
5199
                }
5200
5201
                $users = explode('|', $enreg['Users']);
5202
                $courses = explode('|', $enreg['Courses']);
5203
5204
                $deleteOnlyCourseCoaches = false;
5205
                if (count($courses) == 1) {
5206
                    if ($logger) {
5207
                        $logger->addInfo('Only one course delete old coach list');
5208
                    }
5209
                    $deleteOnlyCourseCoaches = true;
5210
                }
5211
5212
                if (!$updateSession) {
5213
                    // Create a session.
5214
                    $unique_name = false;
5215
                    $i = 0;
5216
                    // Change session name, verify that session doesn't exist.
5217
                    $suffix = null;
5218
                    while (!$unique_name) {
5219
                        if ($i > 1) {
5220
                            $suffix = ' - '.$i;
5221
                        }
5222
                        $sql = 'SELECT id FROM '.$tbl_session.'
5223
                                WHERE name="'.Database::escape_string($session_name).$suffix.'"';
5224
                        $rs = Database::query($sql);
5225
                        if (Database::result($rs, 0, 0)) {
5226
                            $i++;
5227
                        } else {
5228
                            $unique_name = true;
5229
                            $session_name .= $suffix;
5230
                        }
5231
                    }
5232
5233
                    $sessionParams = [
5234
                        'name' => $session_name,
5235
                        'id_coach' => $coach_id,
5236
                        'access_start_date' => $dateStart,
5237
                        'access_end_date' => $dateEnd,
5238
                        'display_start_date' => $displayAccessStartDate,
5239
                        'display_end_date' => $displayAccessEndDate,
5240
                        'coach_access_start_date' => $coachAccessStartDate,
5241
                        'coach_access_end_date' => $coachAccessEndDate,
5242
                        'visibility' => $visibilityAfterExpirationPerSession,
5243
                        'session_admin_id' => $defaultUserId,
5244
                    ];
5245
5246
                    if (!empty($extraParams)) {
5247
                        $sessionParams = array_merge($sessionParams, $extraParams);
5248
                    }
5249
                    // Creating the session.
5250
                    $session_id = Database::insert($tbl_session, $sessionParams);
5251
                    if ($debug) {
5252
                        if ($session_id) {
5253
                            foreach ($enreg as $key => $value) {
5254
                                if (substr($key, 0, 6) == 'extra_') { //an extra field
5255
                                    self::update_session_extra_field_value($session_id, substr($key, 6), $value);
5256
                                }
5257
                            }
5258
                            $logger->addInfo("Session created: #$session_id - $session_name");
5259
                        } else {
5260
                            $message = "Sessions - Session NOT created: $session_name";
5261
                            $logger->addError($message);
5262
                            $report[] = $message;
5263
                        }
5264
                    }
5265
                    $session_counter++;
5266
                } else {
5267
                    $sessionId = null;
5268
                    if (isset($extraFields) && !empty($extraFields) && !empty($enreg['extra_'.$extraFieldId])) {
5269
                        $sessionId = self::getSessionIdFromOriginalId($enreg['extra_'.$extraFieldId], $extraFieldId);
5270
                        if (empty($sessionId)) {
5271
                            $my_session_result = false;
5272
                        } else {
5273
                            $my_session_result = true;
5274
                        }
5275
                    } else {
5276
                        $my_session_result = self::get_session_by_name($enreg['SessionName']);
5277
                    }
5278
5279
                    if ($my_session_result === false) {
5280
                        // One more check
5281
                        $sessionExistsWithName = self::get_session_by_name($session_name);
5282
                        if ($sessionExistsWithName) {
5283
                            if ($debug) {
5284
                                $message = "Skip Session - Trying to update a session, but name already exists: $session_name";
5285
                                $logger->addError($message);
5286
                                $report[] = $message;
5287
                            }
5288
                            continue;
5289
                        }
5290
5291
                        $sessionParams = [
5292
                            'name' => $session_name,
5293
                            'id_coach' => $coach_id,
5294
                            'access_start_date' => $dateStart,
5295
                            'access_end_date' => $dateEnd,
5296
                            'display_start_date' => $displayAccessStartDate,
5297
                            'display_end_date' => $displayAccessEndDate,
5298
                            'coach_access_start_date' => $coachAccessStartDate,
5299
                            'coach_access_end_date' => $coachAccessEndDate,
5300
                            'visibility' => $visibilityAfterExpirationPerSession,
5301
                            'session_admin_id' => $defaultUserId,
5302
                        ];
5303
5304
                        if (!empty($extraParams)) {
5305
                            $sessionParams = array_merge($sessionParams, $extraParams);
5306
                        }
5307
                        Database::insert($tbl_session, $sessionParams);
5308
5309
                        // We get the last insert id.
5310
                        $my_session_result = self::get_session_by_name($session_name);
5311
                        $session_id = $my_session_result['id'];
5312
5313
                        if ($session_id) {
5314
                            foreach ($enreg as $key => $value) {
5315
                                if (substr($key, 0, 6) == 'extra_') { //an extra field
5316
                                    self::update_session_extra_field_value($session_id, substr($key, 6), $value);
5317
                                }
5318
                            }
5319
                            if ($debug) {
5320
                                $logger->addInfo("Sessions - #$session_id created: $session_name");
5321
                            }
5322
5323
                            // Delete session-user relation only for students
5324
                            $sql = "DELETE FROM $tbl_session_user
5325
                                    WHERE session_id = '$session_id' AND relation_type <> ".SESSION_RELATION_TYPE_RRHH;
5326
                            Database::query($sql);
5327
5328
                            $sql = "DELETE FROM $tbl_session_course WHERE session_id = '$session_id'";
5329
                            Database::query($sql);
5330
5331
                            // Delete session-course-user relationships students and coaches.
5332
                            if ($updateCourseCoaches) {
5333
                                $sql = "DELETE FROM $tbl_session_course_user
5334
                                        WHERE session_id = '$session_id' AND status in ('0', '2')";
5335
                                Database::query($sql);
5336
                            } else {
5337
                                // Delete session-course-user relation ships *only* for students.
5338
                                $sql = "DELETE FROM $tbl_session_course_user
5339
                                        WHERE session_id = '$session_id' AND status <> 2";
5340
                                Database::query($sql);
5341
                            }
5342
                            if ($deleteOnlyCourseCoaches) {
5343
                                $sql = "DELETE FROM $tbl_session_course_user
5344
                                        WHERE session_id = '$session_id' AND status in ('2')";
5345
                                Database::query($sql);
5346
                            }
5347
                        }
5348
                    } else {
5349
                        // Updating the session.
5350
                        $params = [
5351
                            'id_coach' => $coach_id,
5352
                            'access_start_date' => $dateStart,
5353
                            'access_end_date' => $dateEnd,
5354
                            'display_start_date' => $displayAccessStartDate,
5355
                            'display_end_date' => $displayAccessEndDate,
5356
                            'coach_access_start_date' => $coachAccessStartDate,
5357
                            'coach_access_end_date' => $coachAccessEndDate,
5358
                            'visibility' => $visibilityAfterExpirationPerSession,
5359
                            'session_category_id' => $session_category_id,
5360
                        ];
5361
5362
                        if (!empty($sessionDescription)) {
5363
                            $params['description'] = $sessionDescription;
5364
                        }
5365
5366
                        if (!empty($fieldsToAvoidUpdate)) {
5367
                            foreach ($fieldsToAvoidUpdate as $field) {
5368
                                unset($params[$field]);
5369
                            }
5370
                        }
5371
5372
                        if (isset($sessionId) && !empty($sessionId)) {
5373
                            $session_id = $sessionId;
5374
                            if (!empty($enreg['SessionName'])) {
5375
                                $sessionExistsWithName = self::get_session_by_name($session_name);
5376
                                if ($sessionExistsWithName === false) {
5377
                                    $sessionName = Database::escape_string($enreg['SessionName']);
5378
                                    $sql = "UPDATE $tbl_session SET name = '$sessionName' WHERE id = $session_id";
5379
                                    Database::query($sql);
5380
                                    $logger->addInfo(
5381
                                        "Session #$session_id name IS updated with: '$session_name' External id: ".$enreg['extra_'.$extraFieldId]
5382
                                    );
5383
                                } else {
5384
                                    $sessionExistsBesidesMe = self::sessionNameExistBesidesMySession(
5385
                                        $session_id,
5386
                                        $session_name
5387
                                    );
5388
                                    if ($sessionExistsBesidesMe === true) {
5389
                                        if ($debug) {
5390
                                            $message = "Skip Session. Error when update session Session #$session_id Name: '$session_name'. Other session has the same name. External id: ".$enreg['extra_'.$extraFieldId];
5391
                                            $logger->addError($message);
5392
                                            $report[] = $message;
5393
                                        }
5394
                                        continue;
5395
                                    } else {
5396
                                        if ($debug) {
5397
                                            $logger->addInfo(
5398
                                                "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]
5399
                                            );
5400
                                        }
5401
                                    }
5402
                                }
5403
                            }
5404
                        } else {
5405
                            $my_session_result = self::get_session_by_name($session_name);
5406
                            $session_id = $my_session_result['id'];
5407
                        }
5408
5409
                        if ($debug) {
5410
                            $logger->addInfo("Session #$session_id to be updated: '$session_name'");
5411
                        }
5412
5413
                        if ($session_id) {
5414
                            $sessionInfo = api_get_session_info($session_id);
5415
                            $params['show_description'] = isset($sessionInfo['show_description']) ? $sessionInfo['show_description'] : intval($showDescription);
5416
5417
                            if (!empty($daysCoachAccessBeforeBeginning) && !empty($daysCoachAccessAfterBeginning)) {
5418
                                if (empty($sessionInfo['nb_days_access_before_beginning']) ||
5419
                                    (!empty($sessionInfo['nb_days_access_before_beginning']) &&
5420
                                        $sessionInfo['nb_days_access_before_beginning'] < $daysCoachAccessBeforeBeginning)
5421
                                ) {
5422
                                    $params['coach_access_start_date'] = $coachBefore;
5423
                                }
5424
5425
                                if (empty($sessionInfo['nb_days_access_after_end']) ||
5426
                                    (!empty($sessionInfo['nb_days_access_after_end']) &&
5427
                                        $sessionInfo['nb_days_access_after_end'] < $daysCoachAccessAfterBeginning)
5428
                                ) {
5429
                                    $params['coach_access_end_date'] = $coachAfter;
5430
                                }
5431
                            }
5432
5433
                            Database::update($tbl_session, $params, ['id = ?' => $session_id]);
5434
                            foreach ($enreg as $key => $value) {
5435
                                if (substr($key, 0, 6) == 'extra_') { //an extra field
5436
                                    self::update_session_extra_field_value($session_id, substr($key, 6), $value);
5437
                                }
5438
                            }
5439
5440
                            if ($debug) {
5441
                                $logger->addInfo("Session updated #$session_id");
5442
                            }
5443
5444
                            // Delete session-user relation only for students
5445
                            $sql = "DELETE FROM $tbl_session_user
5446
                                    WHERE session_id = '$session_id' AND relation_type <> ".SESSION_RELATION_TYPE_RRHH;
5447
                            Database::query($sql);
5448
5449
                            $sql = "DELETE FROM $tbl_session_course WHERE session_id = '$session_id'";
5450
                            Database::query($sql);
5451
5452
                            // Delete session-course-user relationships students and coaches.
5453
                            if ($updateCourseCoaches) {
5454
                                $sql = "DELETE FROM $tbl_session_course_user
5455
                                        WHERE session_id = '$session_id' AND status in ('0', '2')";
5456
                                Database::query($sql);
5457
                            } else {
5458
                                // Delete session-course-user relation ships *only* for students.
5459
                                $sql = "DELETE FROM $tbl_session_course_user
5460
                                        WHERE session_id = '$session_id' AND status <> 2";
5461
                                Database::query($sql);
5462
                            }
5463
5464
                            if ($deleteOnlyCourseCoaches) {
5465
                                $sql = "DELETE FROM $tbl_session_course_user
5466
                                        WHERE session_id = '$session_id' AND status in ('2')";
5467
                                Database::query($sql);
5468
                            }
5469
                        } else {
5470
                            if ($debug) {
5471
                                $logger->addError(
5472
                                    "Sessions - Session not found"
5473
                                );
5474
                            }
5475
                        }
5476
                    }
5477
                    $session_counter++;
5478
                }
5479
5480
                $sessionList[] = $session_id;
5481
5482
                // Adding the relationship "Session - User" for students
5483
                $userList = [];
5484
                if (is_array($users)) {
5485
                    $extraFieldValueCareer = new ExtraFieldValue('career');
5486
                    $careerList = isset($enreg['extra_careerid']) && !empty($enreg['extra_careerid']) ? $enreg['extra_careerid'] : [];
5487
                    $careerList = str_replace(['[', ']'], '', $careerList);
5488
                    $finalCareerIdList = [];
5489
                    if (!empty($careerList)) {
5490
                        $careerList = explode(',', $careerList);
5491
                        foreach ($careerList as $careerId) {
5492
                            $realCareerIdList = $extraFieldValueCareer->get_item_id_from_field_variable_and_field_value(
5493
                                'external_career_id',
5494
                                $careerId
5495
                            );
5496
                            if (isset($realCareerIdList['item_id'])) {
5497
                                $finalCareerIdList[] = $realCareerIdList['item_id'];
5498
                            }
5499
                        }
5500
                    }
5501
                    foreach ($users as $user) {
5502
                        $user_id = UserManager::get_user_id_from_username($user);
5503
                        if ($user_id !== false) {
5504
                            if (!empty($finalCareerIdList)) {
5505
                                foreach ($finalCareerIdList as $careerId) {
5506
                                    UserManager::addUserCareer($user_id, $careerId);
5507
                                }
5508
                            }
5509
5510
                            $userList[] = $user_id;
5511
                            // Insert new users.
5512
                            $sql = "INSERT IGNORE INTO $tbl_session_user SET
5513
                                    user_id = '$user_id',
5514
                                    session_id = '$session_id',
5515
                                    registered_at = '".api_get_utc_datetime()."'";
5516
                            Database::query($sql);
5517
                            if ($debug) {
5518
                                $logger->addInfo("Adding User #$user_id ($user) to session #$session_id");
5519
                            }
5520
                            $user_counter++;
5521
                        }
5522
                    }
5523
                }
5524
5525
                if ($deleteUsersNotInList) {
5526
                    // Getting user in DB in order to compare to the new list.
5527
                    $usersListInDatabase = self::get_users_by_session($session_id, 0);
5528
                    if (!empty($usersListInDatabase)) {
5529
                        if (empty($userList)) {
5530
                            foreach ($usersListInDatabase as $userInfo) {
5531
                                self::unsubscribe_user_from_session($session_id, $userInfo['user_id']);
5532
                            }
5533
                        } else {
5534
                            foreach ($usersListInDatabase as $userInfo) {
5535
                                if (!in_array($userInfo['user_id'], $userList)) {
5536
                                    self::unsubscribe_user_from_session($session_id, $userInfo['user_id']);
5537
                                }
5538
                            }
5539
                        }
5540
                    }
5541
                }
5542
5543
                // See BT#6449
5544
                $onlyAddFirstCoachOrTeacher = false;
5545
                if ($sessionWithCoursesModifier) {
5546
                    if (count($courses) >= 2) {
5547
                        // Only first teacher in course session;
5548
                        $onlyAddFirstCoachOrTeacher = true;
5549
                        // Remove all teachers from course.
5550
                        $removeAllTeachersFromCourse = false;
5551
                    }
5552
                }
5553
5554
                $position = 0;
5555
                foreach ($courses as $course) {
5556
                    $courseArray = bracketsToArray($course);
5557
                    $course_code = $courseArray[0];
5558
5559
                    if (CourseManager::course_exists($course_code)) {
5560
                        $courseInfo = api_get_course_info($course_code);
5561
                        $courseId = $courseInfo['real_id'];
5562
5563
                        // Adding the course to a session.
5564
                        $sql = "INSERT IGNORE INTO $tbl_session_course
5565
                                SET c_id = '$courseId', session_id='$session_id', position = '$position'";
5566
                        Database::query($sql);
5567
5568
                        self::installCourse($session_id, $courseInfo['real_id']);
5569
5570
                        if ($debug) {
5571
                            $logger->addInfo("Adding course '$course_code' to session #$session_id");
5572
                        }
5573
5574
                        $course_counter++;
5575
                        $course_coaches = isset($courseArray[1]) ? $courseArray[1] : null;
5576
                        $course_users = isset($courseArray[2]) ? $courseArray[2] : null;
5577
                        $course_users = explode(',', $course_users);
5578
                        $course_coaches = explode(',', $course_coaches);
5579
5580
                        // Checking if the flag is set TeachersWillBeAddedAsCoachInAllCourseSessions (course_edit.php)
5581
                        $addTeachersToSession = true;
5582
5583
                        if (array_key_exists('add_teachers_to_sessions_courses', $courseInfo)) {
5584
                            $addTeachersToSession = $courseInfo['add_teachers_to_sessions_courses'];
5585
                        }
5586
5587
                        // If any user provided for a course, use the users array.
5588
                        if (empty($course_users)) {
5589
                            if (!empty($userList)) {
5590
                                self::subscribe_users_to_session_course(
5591
                                    $userList,
5592
                                    $session_id,
5593
                                    $course_code
5594
                                );
5595
                                if ($debug) {
5596
                                    $msg = "Adding student list ".implode(', #', $userList)." to course: '$course_code' and session #$session_id";
5597
                                    $logger->addInfo($msg);
5598
                                }
5599
                            }
5600
                        }
5601
5602
                        // Adding coaches to session course user.
5603
                        if (!empty($course_coaches)) {
5604
                            $savedCoaches = [];
5605
                            // only edit if add_teachers_to_sessions_courses is set.
5606
                            if ($addTeachersToSession) {
5607
                                if ($addOriginalCourseTeachersAsCourseSessionCoaches) {
5608
                                    // Adding course teachers as course session teachers.
5609
                                    $alreadyAddedTeachers = CourseManager::get_teacher_list_from_course_code(
5610
                                        $course_code
5611
                                    );
5612
5613
                                    if (!empty($alreadyAddedTeachers)) {
5614
                                        $teachersToAdd = [];
5615
                                        foreach ($alreadyAddedTeachers as $user) {
5616
                                            $teachersToAdd[] = $user['username'];
5617
                                        }
5618
                                        $course_coaches = array_merge(
5619
                                            $course_coaches,
5620
                                            $teachersToAdd
5621
                                        );
5622
                                    }
5623
                                }
5624
5625
                                foreach ($course_coaches as $course_coach) {
5626
                                    $coach_id = UserManager::get_user_id_from_username($course_coach);
5627
                                    if ($coach_id !== false) {
5628
                                        // Just insert new coaches
5629
                                        self::updateCoaches(
5630
                                            $session_id,
5631
                                            $courseId,
5632
                                            [$coach_id],
5633
                                            false
5634
                                        );
5635
5636
                                        if ($debug) {
5637
                                            $logger->addInfo("Adding course coach: user #$coach_id ($course_coach) to course: '$course_code' and session #$session_id");
5638
                                        }
5639
                                        $savedCoaches[] = $coach_id;
5640
                                    } else {
5641
                                        $error_message .= get_lang('UserDoesNotExist').' : '.$course_coach.$eol;
5642
                                    }
5643
                                }
5644
                            }
5645
5646
                            // Custom courses/session coaches
5647
                            $teacherToAdd = null;
5648
                            // Only one coach is added.
5649
                            if ($onlyAddFirstCoachOrTeacher == true) {
5650
                                if ($debug) {
5651
                                    $logger->addInfo("onlyAddFirstCoachOrTeacher : true");
5652
                                }
5653
5654
                                foreach ($course_coaches as $course_coach) {
5655
                                    $coach_id = UserManager::get_user_id_from_username($course_coach);
5656
                                    if ($coach_id !== false) {
5657
                                        $teacherToAdd = $coach_id;
5658
                                        break;
5659
                                    }
5660
                                }
5661
5662
                                // Un subscribe everyone that's not in the list.
5663
                                $teacherList = CourseManager::get_teacher_list_from_course_code($course_code);
5664
                                if (!empty($teacherList)) {
5665
                                    foreach ($teacherList as $teacher) {
5666
                                        if ($teacherToAdd != $teacher['user_id']) {
5667
                                            $sql = "SELECT * FROM ".Database::get_main_table(TABLE_MAIN_COURSE_USER)."
5668
                                                    WHERE
5669
                                                        user_id = ".$teacher['user_id']." AND
5670
                                                        c_id = '".$courseId."'
5671
                                                    ";
5672
5673
                                            $result = Database::query($sql);
5674
                                            $rows = Database::num_rows($result);
5675
                                            if ($rows > 0) {
5676
                                                $userCourseData = Database::fetch_array($result, 'ASSOC');
5677
                                                if (!empty($userCourseData)) {
5678
                                                    $teacherBackupList[$teacher['user_id']][$course_code] = $userCourseData;
5679
                                                }
5680
                                            }
5681
5682
                                            $sql = "SELECT * FROM ".Database::get_course_table(TABLE_GROUP_USER)."
5683
                                                    WHERE
5684
                                                        user_id = ".$teacher['user_id']." AND
5685
                                                        c_id = '".$courseInfo['real_id']."'
5686
                                                    ";
5687
5688
                                            $result = Database::query($sql);
5689
                                            while ($groupData = Database::fetch_array($result, 'ASSOC')) {
5690
                                                $groupBackup['user'][$teacher['user_id']][$course_code][$groupData['group_id']] = $groupData;
5691
                                            }
5692
5693
                                            $sql = "SELECT * FROM ".Database::get_course_table(TABLE_GROUP_TUTOR)."
5694
                                                    WHERE
5695
                                                        user_id = ".$teacher['user_id']." AND
5696
                                                        c_id = '".$courseInfo['real_id']."'
5697
                                                    ";
5698
5699
                                            $result = Database::query($sql);
5700
                                            while ($groupData = Database::fetch_array($result, 'ASSOC')) {
5701
                                                $groupBackup['tutor'][$teacher['user_id']][$course_code][$groupData['group_id']] = $groupData;
5702
                                            }
5703
5704
                                            CourseManager::unsubscribe_user(
5705
                                                $teacher['user_id'],
5706
                                                $course_code
5707
                                            );
5708
5709
                                            if ($debug) {
5710
                                                $logger->addInfo("Delete user #".$teacher['user_id']." from base course: $course_code");
5711
                                            }
5712
                                        }
5713
                                    }
5714
                                }
5715
5716
                                if (!empty($teacherToAdd)) {
5717
                                    self::updateCoaches(
5718
                                        $session_id,
5719
                                        $courseId,
5720
                                        [$teacherToAdd],
5721
                                        true
5722
                                    );
5723
5724
                                    if ($debug) {
5725
                                        $logger->addInfo("Add coach #$teacherToAdd to course $courseId and session $session_id");
5726
                                    }
5727
5728
                                    $userCourseCategory = '';
5729
                                    if (isset($teacherBackupList[$teacherToAdd]) &&
5730
                                        isset($teacherBackupList[$teacherToAdd][$course_code])
5731
                                    ) {
5732
                                        $courseUserData = $teacherBackupList[$teacherToAdd][$course_code];
5733
                                        $userCourseCategory = $courseUserData['user_course_cat'];
5734
                                    }
5735
5736
                                    CourseManager::subscribeUser(
5737
                                        $teacherToAdd,
5738
                                        $course_code,
5739
                                        COURSEMANAGER,
5740
                                        0,
5741
                                        $userCourseCategory
5742
                                    );
5743
5744
                                    if ($debug) {
5745
                                        $logger->addInfo("Subscribe user #$teacherToAdd as teacher in course $course_code with user userCourseCategory $userCourseCategory");
5746
                                    }
5747
5748
                                    if (isset($groupBackup['user'][$teacherToAdd]) &&
5749
                                        isset($groupBackup['user'][$teacherToAdd][$course_code]) &&
5750
                                        !empty($groupBackup['user'][$teacherToAdd][$course_code])
5751
                                    ) {
5752
                                        foreach ($groupBackup['user'][$teacherToAdd][$course_code] as $data) {
5753
                                            $groupInfo = GroupManager::get_group_properties($data['group_id']);
5754
                                            GroupManager::subscribe_users(
5755
                                                $teacherToAdd,
5756
                                                $groupInfo,
5757
                                                $data['c_id']
5758
                                            );
5759
                                        }
5760
                                    }
5761
5762
                                    if (isset($groupBackup['tutor'][$teacherToAdd]) &&
5763
                                        isset($groupBackup['tutor'][$teacherToAdd][$course_code]) &&
5764
                                        !empty($groupBackup['tutor'][$teacherToAdd][$course_code])
5765
                                    ) {
5766
                                        foreach ($groupBackup['tutor'][$teacherToAdd][$course_code] as $data) {
5767
                                            $groupInfo = GroupManager::get_group_properties($data['group_id']);
5768
                                            GroupManager::subscribe_tutors(
5769
                                                $teacherToAdd,
5770
                                                $groupInfo,
5771
                                                $data['c_id']
5772
                                            );
5773
                                        }
5774
                                    }
5775
                                }
5776
                            }
5777
5778
                            // See BT#6449#note-195
5779
                            // All coaches are added.
5780
                            if ($removeAllTeachersFromCourse) {
5781
                                if ($debug) {
5782
                                    $logger->addInfo("removeAllTeachersFromCourse true");
5783
                                }
5784
                                $teacherToAdd = null;
5785
                                foreach ($course_coaches as $course_coach) {
5786
                                    $coach_id = UserManager::get_user_id_from_username(
5787
                                        $course_coach
5788
                                    );
5789
                                    if ($coach_id !== false) {
5790
                                        $teacherToAdd[] = $coach_id;
5791
                                    }
5792
                                }
5793
5794
                                if (!empty($teacherToAdd)) {
5795
                                    // Deleting all course teachers and adding the only coach as teacher.
5796
                                    $teacherList = CourseManager::get_teacher_list_from_course_code($course_code);
5797
5798
                                    if (!empty($teacherList)) {
5799
                                        foreach ($teacherList as $teacher) {
5800
                                            if (!in_array($teacher['user_id'], $teacherToAdd)) {
5801
                                                $sql = "SELECT * FROM ".Database::get_main_table(TABLE_MAIN_COURSE_USER)."
5802
                                                        WHERE
5803
                                                            user_id = ".$teacher['user_id']." AND
5804
                                                            c_id = '".$courseId."'
5805
                                                        ";
5806
5807
                                                $result = Database::query($sql);
5808
                                                $rows = Database::num_rows($result);
5809
                                                if ($rows > 0) {
5810
                                                    $userCourseData = Database::fetch_array($result, 'ASSOC');
5811
                                                    if (!empty($userCourseData)) {
5812
                                                        $teacherBackupList[$teacher['user_id']][$course_code] = $userCourseData;
5813
                                                    }
5814
                                                }
5815
5816
                                                $sql = "SELECT * FROM ".Database::get_course_table(TABLE_GROUP_USER)."
5817
                                                        WHERE
5818
                                                            user_id = ".$teacher['user_id']." AND
5819
                                                            c_id = '".$courseInfo['real_id']."'
5820
                                                        ";
5821
5822
                                                $result = Database::query($sql);
5823
                                                while ($groupData = Database::fetch_array($result, 'ASSOC')) {
5824
                                                    $groupBackup['user'][$teacher['user_id']][$course_code][$groupData['group_id']] = $groupData;
5825
                                                }
5826
5827
                                                $sql = "SELECT * FROM ".Database::get_course_table(TABLE_GROUP_TUTOR)."
5828
                                                        WHERE
5829
                                                            user_id = ".$teacher['user_id']." AND
5830
                                                            c_id = '".$courseInfo['real_id']."'
5831
                                                        ";
5832
5833
                                                $result = Database::query($sql);
5834
                                                while ($groupData = Database::fetch_array($result, 'ASSOC')) {
5835
                                                    $groupBackup['tutor'][$teacher['user_id']][$course_code][$groupData['group_id']] = $groupData;
5836
                                                }
5837
5838
                                                CourseManager::unsubscribe_user(
5839
                                                    $teacher['user_id'],
5840
                                                    $course_code
5841
                                                );
5842
5843
                                                if ($debug) {
5844
                                                    $logger->addInfo("Delete user #".$teacher['user_id']." from base course: $course_code");
5845
                                                }
5846
                                            }
5847
                                        }
5848
                                    }
5849
5850
                                    foreach ($teacherToAdd as $teacherId) {
5851
                                        $userCourseCategory = '';
5852
                                        if (isset($teacherBackupList[$teacherId]) &&
5853
                                            isset($teacherBackupList[$teacherId][$course_code])
5854
                                        ) {
5855
                                            $courseUserData = $teacherBackupList[$teacherId][$course_code];
5856
                                            $userCourseCategory = $courseUserData['user_course_cat'];
5857
                                        }
5858
5859
                                        CourseManager::subscribeUser(
5860
                                            $teacherId,
5861
                                            $course_code,
5862
                                            COURSEMANAGER,
5863
                                            0,
5864
                                            $userCourseCategory
5865
                                        );
5866
5867
                                        if ($debug) {
5868
                                            $logger->addInfo("Add user as teacher #".$teacherId." in base course: $course_code with userCourseCategory: $userCourseCategory");
5869
                                        }
5870
5871
                                        if (isset($groupBackup['user'][$teacherId]) &&
5872
                                            isset($groupBackup['user'][$teacherId][$course_code]) &&
5873
                                            !empty($groupBackup['user'][$teacherId][$course_code])
5874
                                        ) {
5875
                                            foreach ($groupBackup['user'][$teacherId][$course_code] as $data) {
5876
                                                $groupInfo = GroupManager::get_group_properties($data['group_id']);
5877
                                                GroupManager::subscribe_users(
5878
                                                    $teacherId,
5879
                                                    $groupInfo,
5880
                                                    $data['c_id']
5881
                                                );
5882
                                            }
5883
                                        }
5884
5885
                                        if (isset($groupBackup['tutor'][$teacherId]) &&
5886
                                            isset($groupBackup['tutor'][$teacherId][$course_code]) &&
5887
                                            !empty($groupBackup['tutor'][$teacherId][$course_code])
5888
                                        ) {
5889
                                            foreach ($groupBackup['tutor'][$teacherId][$course_code] as $data) {
5890
                                                $groupInfo = GroupManager::get_group_properties($data['group_id']);
5891
                                                GroupManager::subscribe_tutors(
5892
                                                    $teacherId,
5893
                                                    $groupInfo,
5894
                                                    $data['c_id']
5895
                                                );
5896
                                            }
5897
                                        }
5898
                                    }
5899
                                }
5900
                            }
5901
5902
                            // Continue default behaviour.
5903
                            if ($onlyAddFirstCoachOrTeacher == false) {
5904
                                // Checking one more time see BT#6449#note-149
5905
                                $coaches = self::getCoachesByCourseSession($session_id, $courseId);
5906
                                // Update coaches if only there's 1 course see BT#6449#note-189
5907
                                if (empty($coaches) || count($courses) == 1) {
5908
                                    foreach ($course_coaches as $course_coach) {
5909
                                        $course_coach = trim($course_coach);
5910
                                        $coach_id = UserManager::get_user_id_from_username($course_coach);
5911
                                        if ($coach_id !== false) {
5912
                                            // Just insert new coaches
5913
                                            self::updateCoaches(
5914
                                                $session_id,
5915
                                                $courseId,
5916
                                                [$coach_id],
5917
                                                false
5918
                                            );
5919
5920
                                            if ($debug) {
5921
                                                $logger->addInfo("Sessions - Adding course coach: user #$coach_id ($course_coach) to course: '$course_code' and session #$session_id");
5922
                                            }
5923
                                            $savedCoaches[] = $coach_id;
5924
                                        } else {
5925
                                            $error_message .= get_lang('UserDoesNotExist').' : '.$course_coach.$eol;
5926
                                        }
5927
                                    }
5928
                                }
5929
                            }
5930
                        }
5931
5932
                        // Adding Students, updating relationship "Session - Course - User".
5933
                        $course_users = array_filter($course_users);
5934
                        if (!empty($course_users)) {
5935
                            foreach ($course_users as $user) {
5936
                                $user_id = UserManager::get_user_id_from_username($user);
5937
5938
                                if ($user_id !== false) {
5939
                                    self::subscribe_users_to_session_course(
5940
                                        [$user_id],
5941
                                        $session_id,
5942
                                        $course_code
5943
                                    );
5944
                                    if ($debug) {
5945
                                        $logger->addInfo("Adding student: user #$user_id ($user) to course: '$course_code' and session #$session_id");
5946
                                    }
5947
                                } else {
5948
                                    $error_message .= get_lang('UserDoesNotExist').': '.$user.$eol;
5949
                                }
5950
                            }
5951
                        }
5952
                        $inserted_in_course[$course_code] = $courseInfo['title'];
5953
                        $position++;
5954
                    }
5955
                }
5956
                $access_url_id = api_get_current_access_url_id();
5957
                UrlManager::add_session_to_url($session_id, $access_url_id);
5958
                $sql = "UPDATE $tbl_session SET nbr_users = '$user_counter', nbr_courses = '$course_counter'
5959
                        WHERE id = '$session_id'";
5960
                Database::query($sql);
5961
5962
                self::addClassesByName($session_id, $classes, false, $error_message);
5963
5964
                if ($debug) {
5965
                    $logger->addInfo("End process session #$session_id -------------------- ");
5966
                }
5967
            }
5968
5969
            if (!empty($report)) {
5970
                if ($debug) {
5971
                    $logger->addInfo("--Summary--");
5972
                    foreach ($report as $line) {
5973
                        $logger->addInfo($line);
5974
                    }
5975
                }
5976
            }
5977
        }
5978
5979
        return [
5980
            'error_message' => $error_message,
5981
            'session_counter' => $session_counter,
5982
            'session_list' => $sessionList,
5983
        ];
5984
    }
5985
5986
    /**
5987
     * @param int $sessionId
5988
     * @param int $courseId
5989
     *
5990
     * @return array
5991
     */
5992
    public static function getCoachesByCourseSession($sessionId, $courseId)
5993
    {
5994
        $table = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
5995
        $sessionId = (int) $sessionId;
5996
        $courseId = (int) $courseId;
5997
5998
        $sql = "SELECT user_id FROM $table
5999
                WHERE
6000
                    session_id = '$sessionId' AND
6001
                    c_id = '$courseId' AND
6002
                    status = 2";
6003
        $result = Database::query($sql);
6004
6005
        $coaches = [];
6006
        if (Database::num_rows($result) > 0) {
6007
            while ($row = Database::fetch_array($result)) {
6008
                $coaches[] = $row['user_id'];
6009
            }
6010
        }
6011
6012
        return $coaches;
6013
    }
6014
6015
    /**
6016
     * @param int    $sessionId
6017
     * @param int    $courseId
6018
     * @param string $separator
6019
     *
6020
     * @return string
6021
     */
6022
    public static function getCoachesByCourseSessionToString(
6023
        $sessionId,
6024
        $courseId,
6025
        $separator = ''
6026
    ) {
6027
        $coaches = self::getCoachesByCourseSession($sessionId, $courseId);
6028
        $list = [];
6029
        if (!empty($coaches)) {
6030
            foreach ($coaches as $coachId) {
6031
                $userInfo = api_get_user_info($coachId);
6032
                if ($userInfo) {
6033
                    $list[] = $userInfo['complete_name'];
6034
                }
6035
            }
6036
        }
6037
6038
        $separator = empty($separator) ? CourseManager::USER_SEPARATOR : $separator;
6039
6040
        return array_to_string($list, $separator);
6041
    }
6042
6043
    /**
6044
     * Get all coaches added in the session - course relationship.
6045
     *
6046
     * @param int $sessionId
6047
     *
6048
     * @return array
6049
     */
6050
    public static function getCoachesBySession($sessionId)
6051
    {
6052
        $table = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
6053
        $sessionId = intval($sessionId);
6054
6055
        $sql = "SELECT DISTINCT user_id
6056
                FROM $table
6057
                WHERE session_id = '$sessionId' AND status = 2";
6058
        $result = Database::query($sql);
6059
6060
        $coaches = [];
6061
        if (Database::num_rows($result) > 0) {
6062
            while ($row = Database::fetch_array($result)) {
6063
                $coaches[] = $row['user_id'];
6064
            }
6065
        }
6066
6067
        return $coaches;
6068
    }
6069
6070
    /**
6071
     * @param int $userId
6072
     *
6073
     * @return array
6074
     */
6075
    public static function getAllCoursesFromAllSessionFromDrh($userId)
6076
    {
6077
        $sessions = self::get_sessions_followed_by_drh($userId);
6078
        $coursesFromSession = [];
6079
        if (!empty($sessions)) {
6080
            foreach ($sessions as $session) {
6081
                $courseList = self::get_course_list_by_session_id($session['id']);
6082
                foreach ($courseList as $course) {
6083
                    $coursesFromSession[] = $course['code'];
6084
                }
6085
            }
6086
        }
6087
6088
        return $coursesFromSession;
6089
    }
6090
6091
    /**
6092
     * getAllCoursesFromAllSessions.
6093
     *
6094
     * @return array
6095
     */
6096
    public static function getAllCoursesFromAllSessions()
6097
    {
6098
        $sessions = self::get_sessions_list();
6099
        $coursesFromSession = [];
6100
        if (!empty($sessions)) {
6101
            foreach ($sessions as $session) {
6102
                $courseList = self::get_course_list_by_session_id($session['id']);
6103
                foreach ($courseList as $course) {
6104
                    $coursesFromSession[$course['code'].':'.$session['id']] = $course['visual_code'].' - '.$course['title'].' ('.$session['name'].')';
6105
                }
6106
            }
6107
        }
6108
6109
        return $coursesFromSession;
6110
    }
6111
6112
    /**
6113
     * Return user id list or count of users depending of the $getCount parameter.
6114
     *
6115
     * @param string $status
6116
     * @param int    $userId
6117
     * @param bool   $getCount
6118
     * @param int    $from
6119
     * @param int    $numberItems
6120
     * @param int    $column
6121
     * @param string $direction
6122
     * @param string $keyword
6123
     * @param string $active
6124
     * @param string $lastConnectionDate
6125
     * @param array  $sessionIdList
6126
     * @param array  $studentIdList
6127
     * @param int    $filterByStatus
6128
     *
6129
     * @return array|int
6130
     */
6131
    public static function getAllUsersFromCoursesFromAllSessionFromStatus(
6132
        $status,
6133
        $userId,
6134
        $getCount = false,
6135
        $from = null,
6136
        $numberItems = null,
6137
        $column = '',
6138
        $direction = 'asc',
6139
        $keyword = null,
6140
        $active = null,
6141
        $lastConnectionDate = null,
6142
        $sessionIdList = [],
6143
        $studentIdList = [],
6144
        $filterByStatus = null,
6145
        $filterUsers = null
6146
    ) {
6147
        $filterByStatus = (int) $filterByStatus;
6148
        $userId = (int) $userId;
6149
6150
        if (empty($column)) {
6151
            $column = 'u.lastname';
6152
            if (api_is_western_name_order()) {
6153
                $column = 'u.firstname';
6154
            }
6155
        }
6156
6157
        $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
6158
        $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
6159
        $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
6160
        $tbl_course_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
6161
        $tbl_user_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
6162
        $tbl_course_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
6163
        $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
6164
        $tbl_session_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
6165
6166
        $direction = in_array(strtolower($direction), ['asc', 'desc']) ? $direction : 'asc';
6167
        $column = Database::escape_string($column);
6168
6169
        $urlId = api_get_current_access_url_id();
6170
6171
        $sessionConditions = '';
6172
        $courseConditions = '';
6173
        $userConditions = '';
6174
6175
        if (isset($active)) {
6176
            $active = (int) $active;
6177
            $userConditions .= " AND active = $active";
6178
        }
6179
6180
        $courseList = CourseManager::get_courses_followed_by_drh($userId, DRH);
6181
        if (!empty($courseList)) {
6182
            $courseIdList = array_column($courseList, 'id');
6183
            $courseConditions = ' AND c.id IN ("'.implode('","', $courseIdList).'")';
6184
        }
6185
6186
        $userConditionsFromDrh = '';
6187
6188
        // Classic DRH
6189
        if (empty($studentIdList)) {
6190
            $studentListSql = UserManager::get_users_followed_by_drh(
6191
                $userId,
6192
                $filterByStatus,
6193
                true,
6194
                false
6195
            );
6196
            if (!empty($studentListSql)) {
6197
                $studentIdList = array_keys($studentListSql);
6198
                $studentListSql = "'".implode("','", $studentIdList)."'";
6199
            }
6200
        } else {
6201
            $studentIdList = array_map('intval', $studentIdList);
6202
            $studentListSql = "'".implode("','", $studentIdList)."'";
6203
        }
6204
        if (!empty($studentListSql)) {
6205
            $userConditionsFromDrh = " AND u.user_id IN ($studentListSql) ";
6206
        }
6207
6208
        switch ($status) {
6209
            case 'admin':
6210
            case 'drh':
6211
                break;
6212
            case 'drh_all':
6213
                // Show all by DRH
6214
                if (empty($sessionIdList)) {
6215
                    $sessionListFollowed = self::get_sessions_followed_by_drh(
6216
                        $userId,
6217
                        null,
6218
                        null,
6219
                        false,
6220
                        true
6221
                    );
6222
6223
                    if (!empty($sessionListFollowed)) {
6224
                        $sessionIdList = array_column($sessionListFollowed, 'id');
6225
                    }
6226
                }
6227
6228
                if (!empty($sessionIdList)) {
6229
                    $sessionIdList = array_map('intval', $sessionIdList);
6230
                    $sessionsListSql = "'".implode("','", $sessionIdList)."'";
6231
                    $sessionConditions = " AND s.id IN ($sessionsListSql) ";
6232
                }
6233
6234
                break;
6235
            case 'teacher':
6236
            case 'session_admin':
6237
                $sessionConditions = " AND s.id_coach = $userId ";
6238
                $userConditionsFromDrh = '';
6239
                break;
6240
        }
6241
6242
        $select = 'SELECT DISTINCT u.* ';
6243
        $masterSelect = 'SELECT DISTINCT user_id FROM ';
6244
6245
        if ($getCount) {
6246
            $select = 'SELECT DISTINCT u.user_id ';
6247
            $masterSelect = 'SELECT COUNT(DISTINCT(user_id)) as count FROM ';
6248
        }
6249
6250
        if (!empty($filterByStatus)) {
6251
            $userConditions .= " AND u.status = $filterByStatus";
6252
        }
6253
6254
        if (!empty($lastConnectionDate)) {
6255
            $lastConnectionDate = Database::escape_string($lastConnectionDate);
6256
            $userConditions .= " AND u.last_login <= '$lastConnectionDate' ";
6257
        }
6258
6259
        if (!empty($filterUsers)) {
6260
            $userConditions .= " AND u.id IN(".implode(',', $filterUsers).")";
6261
        }
6262
6263
        if (!empty($keyword)) {
6264
            $keyword = trim(Database::escape_string($keyword));
6265
            $keywordParts = array_filter(explode(' ', $keyword));
6266
            $extraKeyword = '';
6267
            if (!empty($keywordParts)) {
6268
                $keywordPartsFixed = Database::escape_string(implode('%', $keywordParts));
6269
                if (!empty($keywordPartsFixed)) {
6270
                    $extraKeyword .= " OR
6271
                        CONCAT(u.firstname, ' ', u.lastname) LIKE '%$keywordPartsFixed%' OR
6272
                        CONCAT(u.lastname, ' ', u.firstname) LIKE '%$keywordPartsFixed%' ";
6273
                }
6274
            }
6275
6276
            $userConditions .= " AND (
6277
                u.username LIKE '%$keyword%' OR
6278
                u.firstname LIKE '%$keyword%' OR
6279
                u.lastname LIKE '%$keyword%' OR
6280
                u.official_code LIKE '%$keyword%' OR
6281
                u.email LIKE '%$keyword%' OR
6282
                CONCAT(u.firstname, ' ', u.lastname) LIKE '%$keyword%' OR
6283
                CONCAT(u.lastname, ' ', u.firstname) LIKE '%$keyword%'
6284
                $extraKeyword
6285
            )";
6286
        }
6287
6288
        $where = " WHERE
6289
                   access_url_id = $urlId
6290
                   $userConditions
6291
        ";
6292
6293
        $userUnion = '';
6294
        if (!empty($userConditionsFromDrh)) {
6295
            $userUnion = "
6296
            UNION (
6297
                $select
6298
                FROM $tbl_user u
6299
                INNER JOIN $tbl_user_rel_access_url url ON (url.user_id = u.id)
6300
                $where
6301
                $userConditionsFromDrh
6302
            )";
6303
        }
6304
6305
        $sql = "$masterSelect (
6306
                ($select
6307
                    FROM $tbl_session s
6308
                    INNER JOIN $tbl_session_rel_access_url url ON (url.session_id = s.id)
6309
                    INNER JOIN $tbl_session_rel_course_rel_user su ON (s.id = su.session_id)
6310
                    INNER JOIN $tbl_user u ON (u.user_id = su.user_id)
6311
                    $where
6312
                    $sessionConditions
6313
                    $userConditionsFromDrh
6314
                ) UNION (
6315
                    $select
6316
                    FROM $tbl_course c
6317
                    INNER JOIN $tbl_course_rel_access_url url ON (url.c_id = c.id)
6318
                    INNER JOIN $tbl_course_user cu ON (cu.c_id = c.id)
6319
                    INNER JOIN $tbl_user u ON (u.user_id = cu.user_id)
6320
                    $where
6321
                    $courseConditions
6322
                    $userConditionsFromDrh
6323
                ) $userUnion
6324
                ) as t1
6325
                ";
6326
6327
        if ($getCount) {
6328
            $result = Database::query($sql);
6329
6330
            $count = 0;
6331
            if (Database::num_rows($result)) {
6332
                $rows = Database::fetch_array($result);
6333
                $count = $rows['count'];
6334
            }
6335
6336
            return $count;
6337
        }
6338
6339
        if (!empty($column) && !empty($direction)) {
6340
            $column = str_replace('u.', '', $column);
6341
            $sql .= " ORDER BY `$column` $direction ";
6342
        }
6343
6344
        $limitCondition = '';
6345
        if (isset($from) && isset($numberItems)) {
6346
            $from = (int) $from;
6347
            $numberItems = (int) $numberItems;
6348
            $limitCondition = "LIMIT $from, $numberItems";
6349
        }
6350
6351
        $sql .= $limitCondition;
6352
6353
        $result = Database::query($sql);
6354
6355
        return Database::store_result($result);
6356
    }
6357
6358
    /**
6359
     * @param int   $sessionId
6360
     * @param int   $courseId
6361
     * @param array $coachList
6362
     * @param bool  $deleteCoachesNotInList
6363
     */
6364
    public static function updateCoaches(
6365
        $sessionId,
6366
        $courseId,
6367
        $coachList,
6368
        $deleteCoachesNotInList = false
6369
    ) {
6370
        $currentCoaches = self::getCoachesByCourseSession($sessionId, $courseId);
6371
6372
        if (!empty($coachList)) {
6373
            foreach ($coachList as $userId) {
6374
                self::set_coach_to_course_session($userId, $sessionId, $courseId);
6375
            }
6376
        }
6377
6378
        if ($deleteCoachesNotInList) {
6379
            if (!empty($coachList)) {
6380
                $coachesToDelete = array_diff($currentCoaches, $coachList);
6381
            } else {
6382
                $coachesToDelete = $currentCoaches;
6383
            }
6384
6385
            if (!empty($coachesToDelete)) {
6386
                foreach ($coachesToDelete as $userId) {
6387
                    self::set_coach_to_course_session(
6388
                        $userId,
6389
                        $sessionId,
6390
                        $courseId,
6391
                        true
6392
                    );
6393
                }
6394
            }
6395
        }
6396
    }
6397
6398
    /**
6399
     * @param array $sessions
6400
     * @param array $sessionsDestination
6401
     *
6402
     * @return array
6403
     */
6404
    public static function copyStudentsFromSession($sessions, $sessionsDestination)
6405
    {
6406
        $messages = [];
6407
        if (!empty($sessions)) {
6408
            foreach ($sessions as $sessionId) {
6409
                $sessionInfo = self::fetch($sessionId);
6410
                $userList = self::get_users_by_session($sessionId, 0);
6411
                if (!empty($userList)) {
6412
                    $newUserList = [];
6413
                    $userToString = null;
6414
                    foreach ($userList as $userInfo) {
6415
                        $newUserList[] = $userInfo['user_id'];
6416
                        $userToString .= $userInfo['firstname'].' '.$userInfo['lastname'].'<br />';
6417
                    }
6418
6419
                    if (!empty($sessionsDestination)) {
6420
                        foreach ($sessionsDestination as $sessionDestinationId) {
6421
                            $sessionDestinationInfo = self::fetch($sessionDestinationId);
6422
                            $messages[] = Display::return_message(
6423
                                sprintf(
6424
                                    get_lang(
6425
                                        'AddingStudentsFromSessionXToSessionY'
6426
                                    ),
6427
                                    $sessionInfo['name'],
6428
                                    $sessionDestinationInfo['name']
6429
                                ),
6430
                                'info',
6431
                                false
6432
                            );
6433
                            if ($sessionId == $sessionDestinationId) {
6434
                                $messages[] = Display::return_message(
6435
                                    sprintf(
6436
                                        get_lang('SessionXSkipped'),
6437
                                        $sessionDestinationId
6438
                                    ),
6439
                                    'warning',
6440
                                    false
6441
                                );
6442
                                continue;
6443
                            }
6444
                            $messages[] = Display::return_message(get_lang('StudentList').'<br />'.$userToString, 'info', false);
6445
                            self::subscribeUsersToSession(
6446
                                $sessionDestinationId,
6447
                                $newUserList,
6448
                                SESSION_VISIBLE_READ_ONLY,
6449
                                false
6450
                            );
6451
                        }
6452
                    } else {
6453
                        $messages[] = Display::return_message(get_lang('NoDestinationSessionProvided'), 'warning');
6454
                    }
6455
                } else {
6456
                    $messages[] = Display::return_message(
6457
                        get_lang('NoStudentsFoundForSession').' #'.$sessionInfo['name'],
6458
                        'warning'
6459
                    );
6460
                }
6461
            }
6462
        } else {
6463
            $messages[] = Display::return_message(get_lang('NoData'), 'warning');
6464
        }
6465
6466
        return $messages;
6467
    }
6468
6469
    /**
6470
     * Assign coaches of a session(s) as teachers to a given course (or courses).
6471
     *
6472
     * @param array A list of session IDs
6473
     * @param array A list of course IDs
6474
     *
6475
     * @return string
6476
     */
6477
    public static function copyCoachesFromSessionToCourse($sessions, $courses)
6478
    {
6479
        $coachesPerSession = [];
6480
        foreach ($sessions as $sessionId) {
6481
            $coaches = self::getCoachesBySession($sessionId);
6482
            $coachesPerSession[$sessionId] = $coaches;
6483
        }
6484
6485
        $result = [];
6486
6487
        if (!empty($courses)) {
6488
            foreach ($courses as $courseId) {
6489
                $courseInfo = api_get_course_info_by_id($courseId);
6490
                foreach ($coachesPerSession as $sessionId => $coachList) {
6491
                    CourseManager::updateTeachers(
6492
                        $courseInfo,
6493
                        $coachList,
6494
                        false,
6495
                        false,
6496
                        false
6497
                    );
6498
                    $result[$courseInfo['code']][$sessionId] = $coachList;
6499
                }
6500
            }
6501
        }
6502
        $sessionUrl = api_get_path(WEB_CODE_PATH).'session/resume_session.php?id_session=';
6503
        $htmlResult = null;
6504
6505
        if (!empty($result)) {
6506
            foreach ($result as $courseCode => $data) {
6507
                $url = api_get_course_url($courseCode);
6508
                $htmlResult .= sprintf(
6509
                    get_lang('CoachesSubscribedAsATeacherInCourseX'),
6510
                    Display::url($courseCode, $url, ['target' => '_blank'])
6511
                );
6512
                foreach ($data as $sessionId => $coachList) {
6513
                    $sessionInfo = self::fetch($sessionId);
6514
                    $htmlResult .= '<br />';
6515
                    $htmlResult .= Display::url(
6516
                        get_lang('Session').': '.$sessionInfo['name'].' <br />',
6517
                        $sessionUrl.$sessionId,
6518
                        ['target' => '_blank']
6519
                    );
6520
                    $teacherList = [];
6521
                    foreach ($coachList as $coachId) {
6522
                        $userInfo = api_get_user_info($coachId);
6523
                        $teacherList[] = $userInfo['complete_name'];
6524
                    }
6525
                    if (!empty($teacherList)) {
6526
                        $htmlResult .= implode(', ', $teacherList);
6527
                    } else {
6528
                        $htmlResult .= get_lang('NothingToAdd');
6529
                    }
6530
                }
6531
                $htmlResult .= '<br />';
6532
            }
6533
            $htmlResult = Display::return_message($htmlResult, 'normal', false);
6534
        }
6535
6536
        return $htmlResult;
6537
    }
6538
6539
    /**
6540
     * @param string $keyword
6541
     * @param string $active
6542
     * @param string $lastConnectionDate
6543
     * @param array  $sessionIdList
6544
     * @param array  $studentIdList
6545
     * @param int    $filterUserStatus   STUDENT|COURSEMANAGER constants
6546
     *
6547
     * @return array|int
6548
     */
6549
    public static function getCountUserTracking(
6550
        $keyword = null,
6551
        $active = null,
6552
        $lastConnectionDate = null,
6553
        $sessionIdList = [],
6554
        $studentIdList = [],
6555
        $filterUserStatus = null
6556
    ) {
6557
        $userId = api_get_user_id();
6558
        $drhLoaded = false;
6559
        if (api_is_drh()) {
6560
            if (api_drh_can_access_all_session_content()) {
6561
                $count = self::getAllUsersFromCoursesFromAllSessionFromStatus(
6562
                    'drh_all',
6563
                    $userId,
6564
                    true,
6565
                    null,
6566
                    null,
6567
                    null,
6568
                    null,
6569
                    $keyword,
6570
                    $active,
6571
                    $lastConnectionDate,
6572
                    $sessionIdList,
6573
                    $studentIdList,
6574
                    $filterUserStatus
6575
                );
6576
                $drhLoaded = true;
6577
            }
6578
            $allowDhrAccessToAllStudents = api_get_configuration_value('drh_allow_access_to_all_students');
6579
            if ($allowDhrAccessToAllStudents) {
6580
                $conditions = ['status' => STUDENT];
6581
                if (isset($active)) {
6582
                    $conditions['active'] = (int) $active;
6583
                }
6584
                $students = UserManager::get_user_list(
6585
                    $conditions,
6586
                    [],
6587
                    false,
6588
                    false,
6589
                    null,
6590
                    $keyword,
6591
                    $lastConnectionDate
6592
                );
6593
                $count = count($students);
6594
                $drhLoaded = true;
6595
            }
6596
        }
6597
6598
        $checkSessionVisibility = api_get_configuration_value('show_users_in_active_sessions_in_tracking');
6599
6600
        if (false === $drhLoaded) {
6601
            $count = UserManager::getUsersFollowedByUser(
6602
                $userId,
6603
                $filterUserStatus,
6604
                false,
6605
                false,
6606
                true,
6607
                null,
6608
                null,
6609
                null,
6610
                null,
6611
                $active,
6612
                $lastConnectionDate,
6613
                api_is_student_boss() ? STUDENT_BOSS : COURSEMANAGER,
6614
                $keyword,
6615
                $checkSessionVisibility
6616
            );
6617
        }
6618
6619
        return $count;
6620
    }
6621
6622
    /**
6623
     * Get teachers followed by a user.
6624
     *
6625
     * @param int    $userId
6626
     * @param int    $active
6627
     * @param string $lastConnectionDate
6628
     * @param bool   $getCount
6629
     * @param array  $sessionIdList
6630
     *
6631
     * @return array|int
6632
     */
6633
    public static function getTeacherTracking(
6634
        $userId,
6635
        $active = 1,
6636
        $lastConnectionDate = null,
6637
        $getCount = false,
6638
        $sessionIdList = []
6639
    ) {
6640
        $teacherListId = [];
6641
        if (api_is_drh() || api_is_platform_admin()) {
6642
            // Followed teachers by drh
6643
            if (api_drh_can_access_all_session_content()) {
6644
                if (empty($sessionIdList)) {
6645
                    $sessions = self::get_sessions_followed_by_drh($userId);
6646
                    $sessionIdList = [];
6647
                    foreach ($sessions as $session) {
6648
                        $sessionIdList[] = $session['id'];
6649
                    }
6650
                }
6651
6652
                $sessionIdList = array_map('intval', $sessionIdList);
6653
                $sessionToString = implode("', '", $sessionIdList);
6654
6655
                $course = Database::get_main_table(TABLE_MAIN_COURSE);
6656
                $sessionCourse = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
6657
                $courseUser = Database::get_main_table(TABLE_MAIN_COURSE_USER);
6658
6659
                // Select the teachers.
6660
                $sql = "SELECT DISTINCT(cu.user_id)
6661
                        FROM $course c
6662
                        INNER JOIN $sessionCourse src
6663
                        ON c.id = src.c_id
6664
                        INNER JOIN $courseUser cu
6665
                        ON (cu.c_id = c.id)
6666
		                WHERE src.session_id IN ('$sessionToString') AND cu.status = 1";
6667
                $result = Database::query($sql);
6668
                while ($row = Database::fetch_array($result, 'ASSOC')) {
6669
                    $teacherListId[$row['user_id']] = $row['user_id'];
6670
                }
6671
            } else {
6672
                $teacherResult = UserManager::get_users_followed_by_drh($userId, COURSEMANAGER);
6673
                foreach ($teacherResult as $userInfo) {
6674
                    $teacherListId[] = $userInfo['user_id'];
6675
                }
6676
            }
6677
        }
6678
6679
        if (!empty($teacherListId)) {
6680
            $tableUser = Database::get_main_table(TABLE_MAIN_USER);
6681
6682
            $select = "SELECT DISTINCT u.* ";
6683
            if ($getCount) {
6684
                $select = "SELECT count(DISTINCT(u.user_id)) as count";
6685
            }
6686
6687
            $sql = "$select FROM $tableUser u";
6688
6689
            if (!empty($lastConnectionDate)) {
6690
                $tableLogin = Database::get_main_table(TABLE_STATISTIC_TRACK_E_LOGIN);
6691
                //$sql .= " INNER JOIN $tableLogin l ON (l.login_user_id = u.user_id) ";
6692
            }
6693
            $active = intval($active);
6694
            $teacherListId = implode("','", $teacherListId);
6695
            $where = " WHERE u.active = $active AND u.user_id IN ('$teacherListId') ";
6696
6697
            if (!empty($lastConnectionDate)) {
6698
                $lastConnectionDate = Database::escape_string($lastConnectionDate);
6699
                //$where .= " AND l.login_date <= '$lastConnectionDate' ";
6700
            }
6701
6702
            $sql .= $where;
6703
            $result = Database::query($sql);
6704
            if (Database::num_rows($result)) {
6705
                if ($getCount) {
6706
                    $row = Database::fetch_array($result);
6707
6708
                    return $row['count'];
6709
                } else {
6710
                    return Database::store_result($result, 'ASSOC');
6711
                }
6712
            }
6713
        }
6714
6715
        return 0;
6716
    }
6717
6718
    /**
6719
     * Get the list of course tools that have to be dealt with in case of
6720
     * registering any course to a session.
6721
     *
6722
     * @return array The list of tools to be dealt with (literal names)
6723
     */
6724
    public static function getCourseToolToBeManaged()
6725
    {
6726
        return [
6727
            'courseDescription',
6728
            'courseIntroduction',
6729
        ];
6730
    }
6731
6732
    /**
6733
     * Calls the methods bound to each tool when a course is registered into a session.
6734
     *
6735
     * @param int $sessionId
6736
     * @param int $courseId
6737
     *
6738
     * @return bool
6739
     *
6740
     * @deprecated
6741
     */
6742
    public static function installCourse($sessionId, $courseId)
6743
    {
6744
        return true;
6745
        $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...
6746
6747
        foreach ($toolList as $tool) {
6748
            $method = 'add'.$tool;
6749
            if (method_exists(get_class(), $method)) {
6750
                self::$method($sessionId, $courseId);
6751
            }
6752
        }
6753
    }
6754
6755
    /**
6756
     * Calls the methods bound to each tool when a course is unregistered from
6757
     * a session.
6758
     *
6759
     * @param int $sessionId
6760
     * @param int $courseId
6761
     */
6762
    public static function unInstallCourse($sessionId, $courseId)
6763
    {
6764
        return true;
6765
        $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...
6766
6767
        foreach ($toolList as $tool) {
6768
            $method = 'remove'.$tool;
6769
            if (method_exists(get_class(), $method)) {
6770
                self::$method($sessionId, $courseId);
6771
            }
6772
        }
6773
    }
6774
6775
    /**
6776
     * @param array $userSessionList        format see self::importSessionDrhCSV()
6777
     * @param bool  $sendEmail
6778
     * @param bool  $removeOldRelationShips
6779
     */
6780
    public static function subscribeDrhToSessionList(
6781
        $userSessionList,
6782
        $sendEmail,
6783
        $removeOldRelationShips
6784
    ) {
6785
        if (!empty($userSessionList)) {
6786
            foreach ($userSessionList as $userId => $data) {
6787
                $sessionList = [];
6788
                foreach ($data['session_list'] as $sessionInfo) {
6789
                    $sessionList[] = $sessionInfo['session_id'];
6790
                }
6791
                $userInfo = $data['user_info'];
6792
                self::subscribeSessionsToDrh(
6793
                    $userInfo,
6794
                    $sessionList,
6795
                    $sendEmail,
6796
                    $removeOldRelationShips
6797
                );
6798
            }
6799
        }
6800
    }
6801
6802
    /**
6803
     * @param array $userSessionList format see self::importSessionDrhCSV()
6804
     *
6805
     * @return string
6806
     */
6807
    public static function checkSubscribeDrhToSessionList($userSessionList)
6808
    {
6809
        $message = null;
6810
        if (!empty($userSessionList)) {
6811
            if (!empty($userSessionList)) {
6812
                foreach ($userSessionList as $userId => $data) {
6813
                    $userInfo = $data['user_info'];
6814
6815
                    $sessionListSubscribed = self::get_sessions_followed_by_drh($userId);
6816
                    if (!empty($sessionListSubscribed)) {
6817
                        $sessionListSubscribed = array_keys($sessionListSubscribed);
6818
                    }
6819
6820
                    $sessionList = [];
6821
                    if (!empty($data['session_list'])) {
6822
                        foreach ($data['session_list'] as $sessionInfo) {
6823
                            if (in_array($sessionInfo['session_id'], $sessionListSubscribed)) {
6824
                                $sessionList[] = $sessionInfo['session_info']['name'];
6825
                            }
6826
                        }
6827
                    }
6828
6829
                    $message .= '<strong>'.get_lang('User').'</strong>: ';
6830
                    $message .= $userInfo['complete_name_with_username'].' <br />';
6831
6832
                    if (!in_array($userInfo['status'], [DRH]) && !api_is_platform_admin_by_id($userInfo['user_id'])) {
6833
                        $message .= get_lang('UserMustHaveTheDrhRole').'<br />';
6834
                        continue;
6835
                    }
6836
6837
                    if (!empty($sessionList)) {
6838
                        $message .= '<strong>'.get_lang('Sessions').':</strong> <br />';
6839
                        $message .= implode(', ', $sessionList).'<br /><br />';
6840
                    } else {
6841
                        $message .= get_lang('NoSessionProvided').' <br /><br />';
6842
                    }
6843
                }
6844
            }
6845
        }
6846
6847
        return $message;
6848
    }
6849
6850
    /**
6851
     * @param string $file
6852
     * @param bool   $sendEmail
6853
     * @param bool   $removeOldRelationShips
6854
     *
6855
     * @return string
6856
     */
6857
    public static function importSessionDrhCSV($file, $sendEmail, $removeOldRelationShips)
6858
    {
6859
        $list = Import::csv_reader($file);
6860
6861
        if (!empty($list)) {
6862
            $userSessionList = [];
6863
            foreach ($list as $data) {
6864
                $sessionInfo = [];
6865
                if (isset($data['SessionId'])) {
6866
                    $sessionInfo = api_get_session_info($data['SessionId']);
6867
                }
6868
6869
                if (isset($data['SessionName']) && empty($sessionInfo)) {
6870
                    $sessionInfo = self::get_session_by_name($data['SessionName']);
6871
                }
6872
6873
                if (empty($sessionInfo)) {
6874
                    $sessionData = isset($data['SessionName']) ? $data['SessionName'] : $data['SessionId'];
6875
                    Display::addFlash(
6876
                        Display::return_message(get_lang('SessionNotFound').' - '.$sessionData, 'warning')
6877
                    );
6878
                    continue;
6879
                }
6880
6881
                $userList = explode(',', $data['Username']);
6882
6883
                foreach ($userList as $username) {
6884
                    $userInfo = api_get_user_info_from_username($username);
6885
6886
                    if (empty($userInfo)) {
6887
                        Display::addFlash(
6888
                            Display::return_message(get_lang('UserDoesNotExist').' - '.$username, 'warning')
6889
                        );
6890
                        continue;
6891
                    }
6892
6893
                    if (!empty($userInfo) && !empty($sessionInfo)) {
6894
                        $userSessionList[$userInfo['user_id']]['session_list'][] = [
6895
                            'session_id' => $sessionInfo['id'],
6896
                            'session_info' => $sessionInfo,
6897
                        ];
6898
                        $userSessionList[$userInfo['user_id']]['user_info'] = $userInfo;
6899
                    }
6900
                }
6901
            }
6902
6903
            self::subscribeDrhToSessionList($userSessionList, $sendEmail, $removeOldRelationShips);
6904
6905
            return self::checkSubscribeDrhToSessionList($userSessionList);
6906
        }
6907
    }
6908
6909
    /**
6910
     * Courses re-ordering in resume_session.php flag see BT#8316.
6911
     */
6912
    public static function orderCourseIsEnabled()
6913
    {
6914
        $sessionCourseOrder = api_get_setting('session_course_ordering');
6915
        if ($sessionCourseOrder === 'true') {
6916
            return true;
6917
        }
6918
6919
        return false;
6920
    }
6921
6922
    /**
6923
     * @param string $direction (up/down)
6924
     * @param int    $sessionId
6925
     * @param int    $courseId
6926
     *
6927
     * @return bool
6928
     */
6929
    public static function move($direction, $sessionId, $courseId)
6930
    {
6931
        if (!self::orderCourseIsEnabled()) {
6932
            return false;
6933
        }
6934
6935
        $sessionId = intval($sessionId);
6936
        $courseId = intval($courseId);
6937
6938
        $table = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
6939
        $courseList = self::get_course_list_by_session_id($sessionId, null, 'position');
6940
6941
        $position = [];
6942
        $count = 0;
6943
        foreach ($courseList as $course) {
6944
            if ($course['position'] == '') {
6945
                $course['position'] = $count;
6946
            }
6947
            $position[$course['code']] = $course['position'];
6948
            // Saving current order.
6949
            $sql = "UPDATE $table SET position = $count
6950
                    WHERE session_id = $sessionId AND c_id = '".$course['real_id']."'";
6951
            Database::query($sql);
6952
            $count++;
6953
        }
6954
6955
        // Loading new positions.
6956
        $courseList = self::get_course_list_by_session_id($sessionId, null, 'position');
6957
6958
        $found = false;
6959
6960
        switch ($direction) {
6961
            case 'up':
6962
                $courseList = array_reverse($courseList);
6963
                break;
6964
            case 'down':
6965
                break;
6966
        }
6967
6968
        foreach ($courseList as $course) {
6969
            if ($found) {
6970
                $nextId = $course['real_id'];
6971
                $nextOrder = $course['position'];
6972
                break;
6973
            }
6974
6975
            if ($courseId == $course['real_id']) {
6976
                $thisCourseCode = $course['real_id'];
6977
                $thisOrder = $course['position'];
6978
                $found = true;
6979
            }
6980
        }
6981
6982
        $sql1 = "UPDATE $table SET position = '".intval($nextOrder)."'
6983
                 WHERE session_id = $sessionId AND c_id =  $thisCourseCode";
6984
        Database::query($sql1);
6985
6986
        $sql2 = "UPDATE $table SET position = '".intval($thisOrder)."'
6987
                 WHERE session_id = $sessionId AND c_id = $nextId";
6988
        Database::query($sql2);
6989
6990
        return true;
6991
    }
6992
6993
    /**
6994
     * @param int $sessionId
6995
     * @param int $courseId
6996
     *
6997
     * @return bool
6998
     */
6999
    public static function moveUp($sessionId, $courseId)
7000
    {
7001
        return self::move('up', $sessionId, $courseId);
7002
    }
7003
7004
    /**
7005
     * @param int    $sessionId
7006
     * @param string $courseCode
7007
     *
7008
     * @return bool
7009
     */
7010
    public static function moveDown($sessionId, $courseCode)
7011
    {
7012
        return self::move('down', $sessionId, $courseCode);
7013
    }
7014
7015
    /**
7016
     * Use the session duration to allow/block user access see BT#8317
7017
     * Needs these DB changes
7018
     * ALTER TABLE session ADD COLUMN duration int;
7019
     * ALTER TABLE session_rel_user ADD COLUMN duration int;.
7020
     */
7021
    public static function durationPerUserIsEnabled()
7022
    {
7023
        return api_get_configuration_value('session_duration_feature');
7024
    }
7025
7026
    /**
7027
     * Returns the number of days the student has left in a session when using
7028
     * sessions durations.
7029
     *
7030
     * @param int $userId
7031
     *
7032
     * @return int
7033
     */
7034
    public static function getDayLeftInSession(array $sessionInfo, $userId)
7035
    {
7036
        $sessionId = $sessionInfo['id'];
7037
        $subscription = self::getUserSession($userId, $sessionId);
7038
        $duration = empty($subscription['duration'])
7039
            ? $sessionInfo['duration']
7040
            : $sessionInfo['duration'] + $subscription['duration'];
7041
7042
        // Get an array with the details of the first access of the student to
7043
        // this session
7044
        $courseAccess = CourseManager::getFirstCourseAccessPerSessionAndUser(
7045
            $sessionId,
7046
            $userId
7047
        );
7048
7049
        $currentTime = time();
7050
7051
        // If no previous access, return false
7052
        if (count($courseAccess) == 0) {
7053
            return $duration;
7054
        }
7055
7056
        $firstAccess = api_strtotime($courseAccess['login_course_date'], 'UTC');
7057
        $endDateInSeconds = $firstAccess + $duration * 24 * 60 * 60;
7058
        $leftDays = round(($endDateInSeconds - $currentTime) / 60 / 60 / 24);
7059
7060
        return $leftDays;
7061
    }
7062
7063
    /**
7064
     * @param int $duration
7065
     * @param int $userId
7066
     * @param int $sessionId
7067
     *
7068
     * @return bool
7069
     */
7070
    public static function editUserSessionDuration($duration, $userId, $sessionId)
7071
    {
7072
        $duration = (int) $duration;
7073
        $userId = (int) $userId;
7074
        $sessionId = (int) $sessionId;
7075
7076
        if (empty($userId) || empty($sessionId)) {
7077
            return false;
7078
        }
7079
7080
        $table = Database::get_main_table(TABLE_MAIN_SESSION_USER);
7081
        $parameters = ['duration' => $duration];
7082
        $where = ['session_id = ? AND user_id = ? ' => [$sessionId, $userId]];
7083
        Database::update($table, $parameters, $where);
7084
7085
        return true;
7086
    }
7087
7088
    /**
7089
     * Gets one row from the session_rel_user table.
7090
     *
7091
     * @param int $userId
7092
     * @param int $sessionId
7093
     *
7094
     * @return array
7095
     */
7096
    public static function getUserSession($userId, $sessionId)
7097
    {
7098
        $userId = (int) $userId;
7099
        $sessionId = (int) $sessionId;
7100
7101
        if (empty($userId) || empty($sessionId)) {
7102
            return false;
7103
        }
7104
7105
        $table = Database::get_main_table(TABLE_MAIN_SESSION_USER);
7106
        $sql = "SELECT * FROM $table
7107
                WHERE session_id = $sessionId AND user_id = $userId";
7108
        $result = Database::query($sql);
7109
        $values = [];
7110
        if (Database::num_rows($result)) {
7111
            $values = Database::fetch_array($result, 'ASSOC');
7112
        }
7113
7114
        return $values;
7115
    }
7116
7117
    /**
7118
     * Check if user is subscribed inside a session as student.
7119
     *
7120
     * @param int $sessionId The session id
7121
     * @param int $userId    The user id
7122
     *
7123
     * @return bool Whether is subscribed
7124
     */
7125
    public static function isUserSubscribedAsStudent($sessionId, $userId)
7126
    {
7127
        $sessionRelUserTable = Database::get_main_table(TABLE_MAIN_SESSION_USER);
7128
        $sessionId = (int) $sessionId;
7129
        $userId = (int) $userId;
7130
7131
        // COUNT(1) actually returns the number of rows from the table (as if
7132
        // counting the results from the first column)
7133
        $sql = "SELECT COUNT(1) AS qty FROM $sessionRelUserTable
7134
                WHERE
7135
                    session_id = $sessionId AND
7136
                    user_id = $userId AND
7137
                    relation_type = 0";
7138
7139
        $result = Database::fetch_assoc(Database::query($sql));
7140
7141
        if (!empty($result) && $result['qty'] > 0) {
7142
            return true;
7143
        }
7144
7145
        return false;
7146
    }
7147
7148
    /**
7149
     * Check if user is subscribed inside a session as a HRM.
7150
     *
7151
     * @param int $sessionId The session id
7152
     * @param int $userId    The user id
7153
     *
7154
     * @return bool Whether is subscribed
7155
     */
7156
    public static function isUserSubscribedAsHRM($sessionId, $userId)
7157
    {
7158
        $sessionRelUserTable = Database::get_main_table(TABLE_MAIN_SESSION_USER);
7159
7160
        $sessionId = (int) $sessionId;
7161
        $userId = (int) $userId;
7162
7163
        // COUNT(1) actually returns the number of rows from the table (as if
7164
        // counting the results from the first column)
7165
        $sql = "SELECT COUNT(1) AS qty FROM $sessionRelUserTable
7166
                WHERE
7167
                    session_id = $sessionId AND
7168
                    user_id = $userId AND
7169
                    relation_type = ".SESSION_RELATION_TYPE_RRHH;
7170
7171
        $result = Database::fetch_assoc(Database::query($sql));
7172
7173
        if (!empty($result) && $result['qty'] > 0) {
7174
            return true;
7175
        }
7176
7177
        return false;
7178
    }
7179
7180
    /**
7181
     * Get the session coached by a user (general coach and course-session coach).
7182
     *
7183
     * @param int  $coachId                       The coach id
7184
     * @param bool $checkSessionRelUserVisibility Check the session visibility
7185
     * @param bool $asPlatformAdmin               The user is a platform admin and we want all sessions
7186
     *
7187
     * @return array The session list
7188
     */
7189
    public static function getSessionsCoachedByUser(
7190
        $coachId,
7191
        $checkSessionRelUserVisibility = false,
7192
        $asPlatformAdmin = false
7193
    ) {
7194
        // Get all sessions where $coachId is the general coach
7195
        $sessions = self::get_sessions_by_general_coach($coachId, $asPlatformAdmin);
7196
        // Get all sessions where $coachId is the course - session coach
7197
        $courseSessionList = self::getCoursesListByCourseCoach($coachId);
7198
        $sessionsByCoach = [];
7199
        if (!empty($courseSessionList)) {
7200
            foreach ($courseSessionList as $userCourseSubscription) {
7201
                $session = $userCourseSubscription->getSession();
7202
                $sessionsByCoach[$session->getId()] = api_get_session_info(
7203
                    $session->getId()
7204
                );
7205
            }
7206
        }
7207
7208
        if (!empty($sessionsByCoach)) {
7209
            $sessions = array_merge($sessions, $sessionsByCoach);
7210
        }
7211
7212
        // Remove repeated sessions
7213
        if (!empty($sessions)) {
7214
            $cleanSessions = [];
7215
            foreach ($sessions as $session) {
7216
                $cleanSessions[$session['id']] = $session;
7217
            }
7218
            $sessions = $cleanSessions;
7219
        }
7220
7221
        if ($checkSessionRelUserVisibility) {
7222
            if (!empty($sessions)) {
7223
                $newSessions = [];
7224
                foreach ($sessions as $session) {
7225
                    $visibility = api_get_session_visibility($session['id']);
7226
                    if ($visibility == SESSION_INVISIBLE) {
7227
                        continue;
7228
                    }
7229
                    $newSessions[] = $session;
7230
                }
7231
                $sessions = $newSessions;
7232
            }
7233
        }
7234
7235
        return $sessions;
7236
    }
7237
7238
    /**
7239
     * Check if the course belongs to the session.
7240
     *
7241
     * @param int    $sessionId  The session id
7242
     * @param string $courseCode The course code
7243
     *
7244
     * @return bool
7245
     */
7246
    public static function sessionHasCourse($sessionId, $courseCode)
7247
    {
7248
        $sessionId = (int) $sessionId;
7249
        $courseCode = Database::escape_string($courseCode);
7250
        $courseTable = Database::get_main_table(TABLE_MAIN_COURSE);
7251
        $sessionRelCourseTable = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
7252
7253
        $sql = "SELECT COUNT(1) AS qty
7254
                FROM $courseTable c
7255
                INNER JOIN $sessionRelCourseTable src
7256
                ON c.id = src.c_id
7257
                WHERE src.session_id = $sessionId
7258
                AND c.code = '$courseCode'  ";
7259
7260
        $result = Database::query($sql);
7261
7262
        if (false !== $result) {
7263
            $data = Database::fetch_assoc($result);
7264
7265
            if ($data['qty'] > 0) {
7266
                return true;
7267
            }
7268
        }
7269
7270
        return false;
7271
    }
7272
7273
    /**
7274
     * Calculate the total user time in the platform.
7275
     *
7276
     * @param int    $userId The user id
7277
     * @param string $from   Optional. From date
7278
     * @param string $until  Optional. Until date
7279
     *
7280
     * @return string The time (hh:mm:ss)
7281
     */
7282
    public static function getTotalUserTimeInPlatform($userId, $from = '', $until = '')
7283
    {
7284
        $userId = (int) $userId;
7285
        $trackLoginTable = Database::get_main_table(TABLE_STATISTIC_TRACK_E_LOGIN);
7286
        $whereConditions = [
7287
            'login_user_id = ? ' => $userId,
7288
        ];
7289
7290
        if (!empty($from) && !empty($until)) {
7291
            $whereConditions["AND (login_date >= '?' "] = $from;
7292
            $whereConditions["AND logout_date <= DATE_ADD('?', INTERVAL 1 DAY)) "] = $until;
7293
        }
7294
7295
        $trackResult = Database::select(
7296
            'SEC_TO_TIME(SUM(UNIX_TIMESTAMP(logout_date) - UNIX_TIMESTAMP(login_date))) as total_time',
7297
            $trackLoginTable,
7298
            [
7299
                'where' => $whereConditions,
7300
            ],
7301
            'first'
7302
        );
7303
7304
        if (false != $trackResult) {
7305
            return $trackResult['total_time'] ? $trackResult['total_time'] : '00:00:00';
7306
        }
7307
7308
        return '00:00:00';
7309
    }
7310
7311
    /**
7312
     * Get the courses list by a course coach.
7313
     *
7314
     * @param int $coachId The coach id
7315
     *
7316
     * @return array (id, user_id, session_id, c_id, visibility, status, legal_agreement)
7317
     */
7318
    public static function getCoursesListByCourseCoach($coachId)
7319
    {
7320
        $entityManager = Database::getManager();
7321
        $scuRepo = $entityManager->getRepository(
7322
            'ChamiloCoreBundle:SessionRelCourseRelUser'
7323
        );
7324
7325
        return $scuRepo->findBy([
7326
            'user' => $coachId,
7327
            'status' => SessionRelCourseRelUser::STATUS_COURSE_COACH,
7328
        ]);
7329
    }
7330
7331
    /**
7332
     * Get the count of user courses in session.
7333
     *
7334
     * @param int $sessionId
7335
     * @param int $courseId
7336
     *
7337
     * @return array
7338
     */
7339
    public static function getTotalUserCoursesInSession($sessionId, $courseId = 0)
7340
    {
7341
        $tableUser = Database::get_main_table(TABLE_MAIN_USER);
7342
        $table = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
7343
7344
        $sessionId = (int) $sessionId;
7345
7346
        if (empty($sessionId)) {
7347
            return [];
7348
        }
7349
7350
        $courseCondition = '';
7351
        if (!empty($courseId)) {
7352
            $courseId = (int) $courseId;
7353
            $courseCondition = "  c_id = $courseId AND ";
7354
        }
7355
7356
        $sql = "SELECT
7357
                    COUNT(u.id) as count,
7358
                    u.id,
7359
                    scu.status status_in_session,
7360
                    u.status user_status
7361
                FROM $table scu
7362
                INNER JOIN $tableUser u
7363
                ON scu.user_id = u.id
7364
                WHERE
7365
                  $courseCondition
7366
                  scu.session_id = ".$sessionId."
7367
                GROUP BY u.id";
7368
7369
        $result = Database::query($sql);
7370
7371
        $list = [];
7372
        while ($data = Database::fetch_assoc($result)) {
7373
            $list[] = $data;
7374
        }
7375
7376
        return $list;
7377
    }
7378
7379
    /**
7380
     * Returns list of a few data from session (name, short description, start
7381
     * date, end date) and the given extra fields if defined based on a
7382
     * session category Id.
7383
     *
7384
     * @param int    $categoryId  The internal ID of the session category
7385
     * @param string $target      Value to search for in the session field values
7386
     * @param array  $extraFields A list of fields to be scanned and returned
7387
     *
7388
     * @return mixed
7389
     */
7390
    public static function getShortSessionListAndExtraByCategory(
7391
        $categoryId,
7392
        $target,
7393
        $extraFields = null,
7394
        $publicationDate = null
7395
    ) {
7396
        $categoryId = (int) $categoryId;
7397
        $sessionList = [];
7398
        // Check if categoryId is valid
7399
        if ($categoryId > 0) {
7400
            $target = Database::escape_string($target);
7401
            $sTable = Database::get_main_table(TABLE_MAIN_SESSION);
7402
            $sfTable = Database::get_main_table(TABLE_EXTRA_FIELD);
7403
            $sfvTable = Database::get_main_table(TABLE_EXTRA_FIELD_VALUES);
7404
            // Join session field and session field values tables
7405
            $joinTable = $sfTable.' sf INNER JOIN '.$sfvTable.' sfv ON sf.id = sfv.field_id';
7406
            $fieldsArray = [];
7407
            foreach ($extraFields as $field) {
7408
                $fieldsArray[] = Database::escape_string($field);
7409
            }
7410
            $extraFieldType = ExtraField::SESSION_FIELD_TYPE;
7411
            if (isset($publicationDate)) {
7412
                $publicationDateString = $publicationDate->format('Y-m-d H:i:s');
7413
                $wherePublication = " AND id NOT IN (
7414
                    SELECT sfv.item_id FROM $joinTable
7415
                    WHERE
7416
                        sf.extra_field_type = $extraFieldType AND
7417
                        ((sf.variable = 'publication_start_date' AND sfv.value > '$publicationDateString' and sfv.value != '') OR
7418
                        (sf.variable = 'publication_end_date' AND sfv.value < '$publicationDateString' and sfv.value != ''))
7419
                )";
7420
            }
7421
            // Get the session list from session category and target
7422
            $sessionList = Database::select(
7423
                'id, name, access_start_date, access_end_date',
7424
                $sTable,
7425
                [
7426
                    'where' => [
7427
                        "session_category_id = ? AND id IN (
7428
                            SELECT sfv.item_id FROM $joinTable
7429
                            WHERE
7430
                                sf.extra_field_type = $extraFieldType AND
7431
                                sfv.item_id = session.id AND
7432
                                sf.variable = 'target' AND
7433
                                sfv.value = ?
7434
                        ) $wherePublication" => [$categoryId, $target],
7435
                    ],
7436
                ]
7437
            );
7438
            $whereFieldVariables = [];
7439
            $whereFieldIds = [];
7440
            if (
7441
                is_array($fieldsArray) &&
7442
                count($fieldsArray) > 0
7443
            ) {
7444
                $whereParams = '?';
7445
                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...
7446
                    $whereParams .= ', ?';
7447
                }
7448
                $whereFieldVariables = ' variable IN ( '.$whereParams.' )';
7449
                $whereFieldIds = 'field_id IN ( '.$whereParams.' )';
7450
            }
7451
            // Get session fields
7452
            $extraField = new ExtraFieldModel('session');
7453
            $questionMarks = substr(str_repeat('?, ', count($fieldsArray)), 0, -2);
7454
            $fieldsList = $extraField->get_all([
7455
                ' variable IN ( '.$questionMarks.' )' => $fieldsArray,
7456
            ]);
7457
            // Index session fields
7458
            foreach ($fieldsList as $field) {
7459
                $fields[$field['id']] = $field['variable'];
7460
            }
7461
            // Get session field values
7462
            $extra = new ExtraFieldValue('session');
7463
            $questionMarksFields = substr(str_repeat('?, ', count($fields)), 0, -2);
7464
            $sessionFieldValueList = $extra->get_all(['where' => ['field_id IN ( '.$questionMarksFields.' )' => array_keys($fields)]]);
7465
            // Add session fields values to session list
7466
            foreach ($sessionList as $id => &$session) {
7467
                foreach ($sessionFieldValueList as $sessionFieldValue) {
7468
                    // Match session field values to session
7469
                    if ($sessionFieldValue['item_id'] == $id) {
7470
                        // Check if session field value is set in session field list
7471
                        if (isset($fields[$sessionFieldValue['field_id']])) {
7472
                            // Avoid overwriting the session's ID field
7473
                            if ($fields[$sessionFieldValue['field_id']] != 'id') {
7474
                                $var = $fields[$sessionFieldValue['field_id']];
7475
                                $val = $sessionFieldValue['value'];
7476
                                // Assign session field value to session
7477
                                $session[$var] = $val;
7478
                            }
7479
                        }
7480
                    }
7481
                }
7482
            }
7483
        }
7484
7485
        return $sessionList;
7486
    }
7487
7488
    /**
7489
     * Return the Session Category id searched by name.
7490
     *
7491
     * @param string $categoryName Name attribute of session category used for search query
7492
     * @param bool   $force        boolean used to get even if something is wrong (e.g not unique name)
7493
     *
7494
     * @return int|array If success, return category id (int), else it will return an array
7495
     *                   with the next structure:
7496
     *                   array('error' => true, 'errorMessage' => ERROR_MESSAGE)
7497
     */
7498
    public static function getSessionCategoryIdByName($categoryName, $force = false)
7499
    {
7500
        // Start error result
7501
        $errorResult = ['error' => true, 'errorMessage' => get_lang('ThereWasAnError')];
7502
        $categoryName = Database::escape_string($categoryName);
7503
        // Check if is not empty category name
7504
        if (!empty($categoryName)) {
7505
            $sessionCategoryTable = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
7506
            // Get all session category with same name
7507
            $result = Database::select(
7508
                'id',
7509
                $sessionCategoryTable,
7510
                [
7511
                    'where' => [
7512
                        'name = ?' => $categoryName,
7513
                    ],
7514
                ]
7515
            );
7516
            // Check the result
7517
            if ($result < 1) {
7518
                // If not found any result, update error message
7519
                $errorResult['errorMessage'] = 'Not found any session category name '.$categoryName;
7520
            } elseif (count($result) > 1 && !$force) {
7521
                // If found more than one result and force is disabled, update error message
7522
                $errorResult['errorMessage'] = 'Found many session categories';
7523
            } elseif (count($result) == 1 || $force) {
7524
                // If found just one session category or force option is enabled
7525
7526
                return key($result);
7527
            }
7528
        } else {
7529
            // category name is empty, update error message
7530
            $errorResult['errorMessage'] = 'Not valid category name';
7531
        }
7532
7533
        return $errorResult;
7534
    }
7535
7536
    /**
7537
     * Return all data from sessions (plus extra field, course and coach data) by category id.
7538
     *
7539
     * @param int $sessionCategoryId session category id used to search sessions
7540
     *
7541
     * @return array If success, return session list and more session related data, else it will return an array
7542
     *               with the next structure:
7543
     *               array('error' => true, 'errorMessage' => ERROR_MESSAGE)
7544
     */
7545
    public static function getSessionListAndExtraByCategoryId($sessionCategoryId)
7546
    {
7547
        // Start error result
7548
        $errorResult = [
7549
            'error' => true,
7550
            'errorMessage' => get_lang('ThereWasAnError'),
7551
        ];
7552
7553
        $sessionCategoryId = intval($sessionCategoryId);
7554
        // Check if session category id is valid
7555
        if ($sessionCategoryId > 0) {
7556
            // Get table names
7557
            $sessionTable = Database::get_main_table(TABLE_MAIN_SESSION);
7558
            $sessionFieldTable = Database::get_main_table(TABLE_EXTRA_FIELD);
7559
            $sessionFieldValueTable = Database::get_main_table(TABLE_EXTRA_FIELD_VALUES);
7560
            $sessionCourseUserTable = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
7561
            $userTable = Database::get_main_table(TABLE_MAIN_USER);
7562
            $courseTable = Database::get_main_table(TABLE_MAIN_COURSE);
7563
7564
            // Get all data from all sessions whit the session category specified
7565
            $sessionList = Database::select(
7566
                '*',
7567
                $sessionTable,
7568
                [
7569
                    'where' => [
7570
                        'session_category_id = ?' => $sessionCategoryId,
7571
                    ],
7572
                ]
7573
            );
7574
7575
            $extraFieldType = ExtraField::SESSION_FIELD_TYPE;
7576
7577
            // Check if session list query had result
7578
            if (!empty($sessionList)) {
7579
                // implode all session id
7580
                $sessionIdsString = '('.implode(', ', array_keys($sessionList)).')';
7581
                // Get all field variables
7582
                $sessionFieldList = Database::select(
7583
                    'id, variable',
7584
                    $sessionFieldTable,
7585
                    ['extra_field_type = ? ' => [$extraFieldType]]
7586
                );
7587
7588
                // Get all field values
7589
                $sql = "SELECT item_id, field_id, value FROM
7590
                        $sessionFieldValueTable v INNER JOIN $sessionFieldTable f
7591
                        ON (f.id = v.field_id)
7592
                        WHERE
7593
                            item_id IN $sessionIdsString AND
7594
                            extra_field_type = $extraFieldType
7595
                ";
7596
                $result = Database::query($sql);
7597
                $sessionFieldValueList = Database::store_result($result, 'ASSOC');
7598
7599
                // Check if session field values had result
7600
                if (!empty($sessionFieldValueList)) {
7601
                    $sessionFieldValueListBySession = [];
7602
                    foreach ($sessionFieldValueList as $key => $sessionFieldValue) {
7603
                        // Create an array to index ids to session id
7604
                        $sessionFieldValueListBySession[$sessionFieldValue['item_id']][] = $key;
7605
                    }
7606
                }
7607
                // Query used to find course-coaches from sessions
7608
                $sql = "SELECT
7609
                            scu.session_id,
7610
                            c.id AS course_id,
7611
                            c.code AS course_code,
7612
                            c.title AS course_title,
7613
                            u.username AS coach_username,
7614
                            u.firstname AS coach_firstname,
7615
                            u.lastname AS coach_lastname
7616
                        FROM $courseTable c
7617
                        INNER JOIN $sessionCourseUserTable scu ON c.id = scu.c_id
7618
                        INNER JOIN $userTable u ON scu.user_id = u.user_id
7619
                        WHERE scu.status = 2 AND scu.session_id IN $sessionIdsString
7620
                        ORDER BY scu.session_id ASC ";
7621
                $res = Database::query($sql);
7622
                $sessionCourseList = Database::store_result($res, 'ASSOC');
7623
                // Check if course list had result
7624
                if (!empty($sessionCourseList)) {
7625
                    foreach ($sessionCourseList as $key => $sessionCourse) {
7626
                        // Create an array to index ids to session_id
7627
                        $sessionCourseListBySession[$sessionCourse['session_id']][] = $key;
7628
                    }
7629
                }
7630
                // Join lists
7631
                if (is_array($sessionList)) {
7632
                    foreach ($sessionList as $id => &$row) {
7633
                        if (
7634
                            !empty($sessionFieldValueListBySession) &&
7635
                            is_array($sessionFieldValueListBySession[$id])
7636
                        ) {
7637
                            // If have an index array for session extra fields, use it to join arrays
7638
                            foreach ($sessionFieldValueListBySession[$id] as $key) {
7639
                                $row['extra'][$key] = [
7640
                                    'field_name' => $sessionFieldList[$sessionFieldValueList[$key]['field_id']]['variable'],
7641
                                    'value' => $sessionFieldValueList[$key]['value'],
7642
                                ];
7643
                            }
7644
                        }
7645
                        if (
7646
                            !empty($sessionCourseListBySession) &&
7647
                            is_array($sessionCourseListBySession[$id])
7648
                        ) {
7649
                            // If have an index array for session course coach, use it to join arrays
7650
                            foreach ($sessionCourseListBySession[$id] as $key) {
7651
                                $row['course'][$key] = [
7652
                                    'course_id' => $sessionCourseList[$key]['course_id'],
7653
                                    'course_code' => $sessionCourseList[$key]['course_code'],
7654
                                    'course_title' => $sessionCourseList[$key]['course_title'],
7655
                                    'coach_username' => $sessionCourseList[$key]['coach_username'],
7656
                                    'coach_firstname' => $sessionCourseList[$key]['coach_firstname'],
7657
                                    'coach_lastname' => $sessionCourseList[$key]['coach_lastname'],
7658
                                ];
7659
                            }
7660
                        }
7661
                    }
7662
                }
7663
7664
                return $sessionList;
7665
            } else {
7666
                // Not found result, update error message
7667
                $errorResult['errorMessage'] = 'Not found any session for session category id '.$sessionCategoryId;
7668
            }
7669
        }
7670
7671
        return $errorResult;
7672
    }
7673
7674
    /**
7675
     * Return session description from session id.
7676
     *
7677
     * @param int $sessionId
7678
     *
7679
     * @return string
7680
     */
7681
    public static function getDescriptionFromSessionId($sessionId)
7682
    {
7683
        // Init variables
7684
        $sessionId = (int) $sessionId;
7685
        $description = '';
7686
        // Check if session id is valid
7687
        if ($sessionId > 0) {
7688
            // Select query from session id
7689
            $rows = Database::select(
7690
                'description',
7691
                Database::get_main_table(TABLE_MAIN_SESSION),
7692
                [
7693
                    'where' => [
7694
                        'id = ?' => $sessionId,
7695
                    ],
7696
                ]
7697
            );
7698
7699
            // Check if select query result is not empty
7700
            if (!empty($rows)) {
7701
                // Get session description
7702
                $description = $rows[0]['description'];
7703
            }
7704
        }
7705
7706
        return $description;
7707
    }
7708
7709
    /**
7710
     * Get a session list filtered by name, description or any of the given extra fields.
7711
     *
7712
     * @param string $term                 The term to search
7713
     * @param array  $extraFieldsToInclude Extra fields to include in the session data
7714
     *
7715
     * @return array The list
7716
     */
7717
    public static function searchSession($term, $extraFieldsToInclude = [])
7718
    {
7719
        $sTable = Database::get_main_table(TABLE_MAIN_SESSION);
7720
        $extraFieldTable = Database::get_main_table(TABLE_EXTRA_FIELD);
7721
        $sfvTable = Database::get_main_table(TABLE_EXTRA_FIELD_VALUES);
7722
        $term = Database::escape_string($term);
7723
        $extraFieldType = ExtraField::SESSION_FIELD_TYPE;
7724
        if (is_array($extraFieldsToInclude) && count($extraFieldsToInclude) > 0) {
7725
            $resultData = Database::select('*', $sTable, [
7726
                'where' => [
7727
                    "name LIKE %?% " => $term,
7728
                    " OR description LIKE %?% " => $term,
7729
                    " OR id IN (
7730
                    SELECT item_id
7731
                    FROM $sfvTable v INNER JOIN $extraFieldTable e
7732
                    ON (v.field_id = e.id)
7733
                    WHERE value LIKE %?% AND extra_field_type = $extraFieldType
7734
                ) " => $term,
7735
                ],
7736
            ]);
7737
        } else {
7738
            $resultData = Database::select('*', $sTable, [
7739
                'where' => [
7740
                    "name LIKE %?% " => $term,
7741
                    "OR description LIKE %?% " => $term,
7742
                ],
7743
            ]);
7744
7745
            return $resultData;
7746
        }
7747
7748
        foreach ($resultData as $id => &$session) {
7749
            $session['extra'] = self::getFilteredExtraFields($id, $extraFieldsToInclude);
7750
        }
7751
7752
        return $resultData;
7753
    }
7754
7755
    /**
7756
     * @param int   $sessionId
7757
     * @param array $extraFieldsToInclude (empty means all)
7758
     *
7759
     * @return array
7760
     */
7761
    public static function getFilteredExtraFields($sessionId, $extraFieldsToInclude = [])
7762
    {
7763
        $extraData = [];
7764
        $variables = [];
7765
        $variablePlaceHolders = [];
7766
7767
        foreach ($extraFieldsToInclude as $sessionExtraField) {
7768
            $variablePlaceHolders[] = "?";
7769
            $variables[] = Database::escape_string($sessionExtraField);
7770
        }
7771
7772
        $sessionExtraField = new ExtraFieldModel('session');
7773
        $fieldList = $sessionExtraField->get_all(empty($extraFieldsToInclude) ? [] : [
7774
            "variable IN ( ".implode(", ", $variablePlaceHolders)." ) " => $variables,
7775
        ]);
7776
7777
        if (empty($fieldList)) {
7778
            return [];
7779
        }
7780
7781
        $fields = [];
7782
7783
        // Index session fields
7784
        foreach ($fieldList as $field) {
7785
            $fields[$field['id']] = $field['variable'];
7786
        }
7787
7788
        // Get session field values
7789
        $extra = new ExtraFieldValue('session');
7790
        $sessionFieldValueList = [];
7791
        foreach (array_keys($fields) as $fieldId) {
7792
            $sessionFieldValue = $extra->get_values_by_handler_and_field_id($sessionId, $fieldId);
7793
            if ($sessionFieldValue != false) {
7794
                $sessionFieldValueList[$fieldId] = $sessionFieldValue;
7795
            }
7796
        }
7797
7798
        foreach ($sessionFieldValueList as $sessionFieldValue) {
7799
            $extrafieldVariable = $fields[$sessionFieldValue['field_id']];
7800
            $extrafieldValue = $sessionFieldValue['value'];
7801
7802
            $extraData[] = [
7803
                'variable' => $extrafieldVariable,
7804
                'value' => $extrafieldValue,
7805
            ];
7806
        }
7807
7808
        return $extraData;
7809
    }
7810
7811
    /**
7812
     * @param int $sessionId
7813
     *
7814
     * @return bool
7815
     */
7816
    public static function isValidId($sessionId)
7817
    {
7818
        $sessionId = (int) $sessionId;
7819
        if ($sessionId > 0) {
7820
            $rows = Database::select(
7821
                'id',
7822
                Database::get_main_table(TABLE_MAIN_SESSION),
7823
                ['where' => ['id = ?' => $sessionId]]
7824
            );
7825
            if (!empty($rows)) {
7826
                return true;
7827
            }
7828
        }
7829
7830
        return false;
7831
    }
7832
7833
    /**
7834
     * Get list of sessions based on users of a group for a group admin.
7835
     *
7836
     * @param int $userId The user id
7837
     *
7838
     * @return array
7839
     */
7840
    public static function getSessionsFollowedForGroupAdmin($userId)
7841
    {
7842
        $sessionList = [];
7843
        $sessionTable = Database::get_main_table(TABLE_MAIN_SESSION);
7844
        $sessionUserTable = Database::get_main_table(TABLE_MAIN_SESSION_USER);
7845
        $userGroup = new UserGroup();
7846
        $userIdList = $userGroup->getGroupUsersByUser($userId);
7847
7848
        if (empty($userIdList)) {
7849
            return [];
7850
        }
7851
7852
        $sql = "SELECT DISTINCT s.*
7853
                FROM $sessionTable s
7854
                INNER JOIN $sessionUserTable sru
7855
                ON s.id = sru.id_session
7856
                WHERE
7857
                    (sru.id_user IN (".implode(', ', $userIdList).")
7858
                    AND sru.relation_type = 0
7859
                )";
7860
7861
        if (api_is_multiple_url_enabled()) {
7862
            $sessionAccessUrlTable = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
7863
            $accessUrlId = api_get_current_access_url_id();
7864
7865
            if (-1 != $accessUrlId) {
7866
                $sql = "SELECT DISTINCT s.*
7867
                        FROM $sessionTable s
7868
                        INNER JOIN $sessionUserTable sru ON s.id = sru.id_session
7869
                        INNER JOIN $sessionAccessUrlTable srau ON s.id = srau.session_id
7870
                        WHERE
7871
                            srau.access_url_id = $accessUrlId
7872
                            AND (
7873
                                sru.id_user IN (".implode(', ', $userIdList).")
7874
                                AND sru.relation_type = 0
7875
                            )";
7876
            }
7877
        }
7878
7879
        $result = Database::query($sql);
7880
        while ($row = Database::fetch_assoc($result)) {
7881
            $sessionList[] = $row;
7882
        }
7883
7884
        return $sessionList;
7885
    }
7886
7887
    /**
7888
     * @param array $sessionInfo
7889
     *
7890
     * @return string
7891
     */
7892
    public static function getSessionVisibility($sessionInfo)
7893
    {
7894
        switch ($sessionInfo['visibility']) {
7895
            case 1:
7896
                return get_lang('ReadOnly');
7897
            case 2:
7898
                return get_lang('Visible');
7899
            case 3:
7900
                return api_ucfirst(get_lang('Invisible'));
7901
        }
7902
    }
7903
7904
    /**
7905
     * Returns a human readable string.
7906
     *
7907
     * @param array $sessionInfo An array with all the session dates
7908
     * @param bool  $showTime
7909
     *
7910
     * @return array
7911
     */
7912
    public static function parseSessionDates($sessionInfo, $showTime = false)
7913
    {
7914
        $displayDates = self::convertSessionDateToString(
7915
            $sessionInfo['display_start_date'],
7916
            $sessionInfo['display_end_date'],
7917
            $showTime,
7918
            true
7919
        );
7920
        $accessDates = self::convertSessionDateToString(
7921
            $sessionInfo['access_start_date'],
7922
            $sessionInfo['access_end_date'],
7923
            $showTime,
7924
            true
7925
        );
7926
7927
        $coachDates = self::convertSessionDateToString(
7928
            $sessionInfo['coach_access_start_date'],
7929
            $sessionInfo['coach_access_end_date'],
7930
            $showTime,
7931
            true
7932
        );
7933
7934
        $result = [
7935
            'access' => $accessDates,
7936
            'display' => $displayDates,
7937
            'coach' => $coachDates,
7938
        ];
7939
7940
        return $result;
7941
    }
7942
7943
    /**
7944
     * @param array $sessionInfo Optional
7945
     *
7946
     * @return array
7947
     */
7948
    public static function setForm(FormValidator $form, array $sessionInfo = [])
7949
    {
7950
        $sessionId = 0;
7951
        $coachInfo = [];
7952
7953
        if (!empty($sessionInfo)) {
7954
            $sessionId = (int) $sessionInfo['id'];
7955
            $coachInfo = api_get_user_info($sessionInfo['id_coach']);
7956
        }
7957
7958
        $categoriesList = self::get_all_session_category();
7959
        $userInfo = api_get_user_info();
7960
7961
        $categoriesOptions = [
7962
            '0' => get_lang('None'),
7963
        ];
7964
7965
        if ($categoriesList != false) {
7966
            foreach ($categoriesList as $categoryItem) {
7967
                $categoriesOptions[$categoryItem['id']] = $categoryItem['name'];
7968
            }
7969
        }
7970
7971
        // Database Table Definitions
7972
        $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
7973
7974
        $form->addText(
7975
            'name',
7976
            get_lang('SessionName'),
7977
            true,
7978
            ['maxlength' => 150, 'aria-label' => get_lang('SessionName')]
7979
        );
7980
        $form->addRule('name', get_lang('SessionNameAlreadyExists'), 'callback', 'check_session_name');
7981
7982
        if (!api_is_platform_admin() && api_is_teacher()) {
7983
            $form->addElement(
7984
                'select',
7985
                'coach_username',
7986
                get_lang('CoachName'),
7987
                [api_get_user_id() => $userInfo['complete_name']],
7988
                [
7989
                    'id' => 'coach_username',
7990
                    'style' => 'width:370px;',
7991
                ]
7992
            );
7993
        } else {
7994
            $sql = "SELECT COUNT(1) FROM $tbl_user WHERE status = 1";
7995
            $rs = Database::query($sql);
7996
            $countUsers = (int) Database::result($rs, 0, 0);
7997
7998
            if ($countUsers < 50) {
7999
                $orderClause = 'ORDER BY ';
8000
                $orderClause .= api_sort_by_first_name() ? 'firstname, lastname, username' : 'lastname, firstname, username';
8001
8002
                $sql = "SELECT user_id, lastname, firstname, username
8003
                        FROM $tbl_user
8004
                        WHERE status = '1' ".
8005
                        $orderClause;
8006
8007
                if (api_is_multiple_url_enabled()) {
8008
                    $userRelAccessUrlTable = Database::get_main_table(
8009
                        TABLE_MAIN_ACCESS_URL_REL_USER
8010
                    );
8011
                    $accessUrlId = api_get_current_access_url_id();
8012
                    if ($accessUrlId != -1) {
8013
                        $sql = "SELECT user.user_id, username, lastname, firstname
8014
                        FROM $tbl_user user
8015
                        INNER JOIN $userRelAccessUrlTable url_user
8016
                        ON (url_user.user_id = user.user_id)
8017
                        WHERE
8018
                            access_url_id = $accessUrlId AND
8019
                            status = 1 "
8020
                            .$orderClause;
8021
                    }
8022
                }
8023
8024
                $result = Database::query($sql);
8025
                $coachesList = Database::store_result($result);
8026
                $coachesOptions = [];
8027
                foreach ($coachesList as $coachItem) {
8028
                    $coachesOptions[$coachItem['user_id']] =
8029
                        api_get_person_name($coachItem['firstname'], $coachItem['lastname']).' ('.$coachItem['username'].')';
8030
                }
8031
8032
                $form->addElement(
8033
                    'select',
8034
                    'coach_username',
8035
                    get_lang('CoachName'),
8036
                    $coachesOptions,
8037
                    [
8038
                        'id' => 'coach_username',
8039
                        'style' => 'width:370px;',
8040
                    ]
8041
                );
8042
            } else {
8043
                $form->addElement(
8044
                    'select_ajax',
8045
                    'coach_username',
8046
                    get_lang('CoachName'),
8047
                    $coachInfo ? [$coachInfo['id'] => $coachInfo['complete_name_with_username']] : [],
8048
                    [
8049
                        'url' => api_get_path(WEB_AJAX_PATH).'session.ajax.php?a=search_general_coach',
8050
                        'width' => '100%',
8051
                        'id' => 'coach_username',
8052
                    ]
8053
                );
8054
            }
8055
        }
8056
8057
        $form->addRule('coach_username', get_lang('ThisFieldIsRequired'), 'required');
8058
        $form->addHtml('<div id="ajax_list_coachs"></div>');
8059
8060
        $form->addButtonAdvancedSettings('advanced_params');
8061
        $form->addElement('html', '<div id="advanced_params_options" style="display:none">');
8062
8063
        if (empty($sessionId)) {
8064
            $form->addSelectAjax(
8065
                'session_template',
8066
                get_lang('SessionTemplate'),
8067
                [],
8068
                ['url' => api_get_path(WEB_AJAX_PATH).'session.ajax.php?a=search_template_session', 'id' => 'system_template']
8069
            );
8070
        }
8071
8072
        $form->addSelect(
8073
            'session_category',
8074
            get_lang('SessionCategory'),
8075
            $categoriesOptions,
8076
            [
8077
                'id' => 'session_category',
8078
            ]
8079
        );
8080
8081
        if (api_get_configuration_value('allow_session_status')) {
8082
            $statusList = self::getStatusList();
8083
            $form->addSelect(
8084
                'status',
8085
                get_lang('SessionStatus'),
8086
                $statusList,
8087
                [
8088
                    'id' => 'status',
8089
                ]
8090
            );
8091
        }
8092
8093
        $form->addHtmlEditor(
8094
            'description',
8095
            get_lang('Description'),
8096
            false,
8097
            false,
8098
            [
8099
                'ToolbarSet' => 'Minimal',
8100
            ]
8101
        );
8102
8103
        $form->addElement('checkbox', 'show_description', null, get_lang('ShowDescription'));
8104
8105
        $visibilityOptions = [
8106
            SESSION_VISIBLE_READ_ONLY => get_lang('SessionReadOnly'),
8107
            SESSION_VISIBLE => get_lang('SessionAccessible'),
8108
            SESSION_INVISIBLE => api_ucfirst(get_lang('SessionNotAccessible')),
8109
        ];
8110
8111
        $visibilityOptionsConfiguration = api_get_configuration_value('session_visibility_after_end_date_options_configuration');
8112
        if (!empty($visibilityOptionsConfiguration)) {
8113
            foreach ($visibilityOptionsConfiguration['visibility_options_to_hide'] as $option) {
8114
                $option = trim($option);
8115
                if (defined($option)) {
8116
                    $constantValue = constant($option);
8117
                    if (isset($visibilityOptions[$constantValue])) {
8118
                        unset($visibilityOptions[$constantValue]);
8119
                    }
8120
                }
8121
            }
8122
        }
8123
8124
        $visibilityGroup = [];
8125
        $visibilityGroup[] = $form->createElement(
8126
            'select',
8127
            'session_visibility',
8128
            null,
8129
            $visibilityOptions
8130
        );
8131
        $form->addGroup(
8132
            $visibilityGroup,
8133
            'visibility_group',
8134
            get_lang('SessionVisibility'),
8135
            null,
8136
            false
8137
        );
8138
8139
        $options = [
8140
            0 => get_lang('ByDuration'),
8141
            1 => get_lang('ByDates'),
8142
        ];
8143
8144
        $form->addSelect('access', get_lang('Access'), $options, [
8145
            'onchange' => 'accessSwitcher()',
8146
            'id' => 'access',
8147
        ]);
8148
8149
        $form->addHtml('<div id="duration_div" style="display:none">');
8150
        $form->addElement(
8151
            'number',
8152
            'duration',
8153
            [
8154
                get_lang('SessionDurationTitle'),
8155
                get_lang('SessionDurationDescription'),
8156
            ],
8157
            [
8158
                'maxlength' => 50,
8159
            ]
8160
        );
8161
8162
        $form->addHtml('</div>');
8163
        $form->addHtml('<div id="date_fields" style="display:none">');
8164
8165
        // Dates
8166
        $form->addDateTimePicker(
8167
            'access_start_date',
8168
            [get_lang('SessionStartDate'), get_lang('SessionStartDateComment')],
8169
            ['id' => 'access_start_date']
8170
        );
8171
8172
        $form->addDateTimePicker(
8173
            'access_end_date',
8174
            [get_lang('SessionEndDate'), get_lang('SessionEndDateComment')],
8175
            ['id' => 'access_end_date']
8176
        );
8177
8178
        $form->addRule(
8179
            ['access_start_date', 'access_end_date'],
8180
            get_lang('StartDateMustBeBeforeTheEndDate'),
8181
            'compare_datetime_text',
8182
            '< allow_empty'
8183
        );
8184
8185
        $form->addDateTimePicker(
8186
            'display_start_date',
8187
            [
8188
                get_lang('SessionDisplayStartDate'),
8189
                get_lang('SessionDisplayStartDateComment'),
8190
            ],
8191
            ['id' => 'display_start_date']
8192
        );
8193
8194
        $form->addDateTimePicker(
8195
            'display_end_date',
8196
            [
8197
                get_lang('SessionDisplayEndDate'),
8198
                get_lang('SessionDisplayEndDateComment'),
8199
            ],
8200
            ['id' => 'display_end_date']
8201
        );
8202
8203
        $form->addRule(
8204
            ['display_start_date', 'display_end_date'],
8205
            get_lang('StartDateMustBeBeforeTheEndDate'),
8206
            'compare_datetime_text',
8207
            '< allow_empty'
8208
        );
8209
8210
        $form->addDateTimePicker(
8211
            'coach_access_start_date',
8212
            [
8213
                get_lang('SessionCoachStartDate'),
8214
                get_lang('SessionCoachStartDateComment'),
8215
            ],
8216
            ['id' => 'coach_access_start_date']
8217
        );
8218
8219
        $form->addDateTimePicker(
8220
            'coach_access_end_date',
8221
            [
8222
                get_lang('SessionCoachEndDate'),
8223
                get_lang('SessionCoachEndDateComment'),
8224
            ],
8225
            ['id' => 'coach_access_end_date']
8226
        );
8227
8228
        $form->addRule(
8229
            ['coach_access_start_date', 'coach_access_end_date'],
8230
            get_lang('StartDateMustBeBeforeTheEndDate'),
8231
            'compare_datetime_text',
8232
            '< allow_empty'
8233
        );
8234
8235
        $form->addElement('html', '</div>');
8236
8237
        $form->addCheckBox(
8238
            'send_subscription_notification',
8239
            [
8240
                get_lang('SendSubscriptionNotification'),
8241
                get_lang('SendAnEmailWhenAUserBeingSubscribed'),
8242
            ]
8243
        );
8244
8245
        // Extra fields
8246
        $setExtraFieldsMandatory = api_get_configuration_value('session_creation_form_set_extra_fields_mandatory');
8247
        $fieldsRequired = [];
8248
        if (false !== $setExtraFieldsMandatory && !empty($setExtraFieldsMandatory['fields'])) {
8249
            $fieldsRequired = $setExtraFieldsMandatory['fields'];
8250
        }
8251
        $extra_field = new ExtraFieldModel('session');
8252
        $extra = $extra_field->addElements(
8253
            $form,
8254
            $sessionId,
8255
            [],
8256
            false,
8257
            false,
8258
            [],
8259
            [],
8260
            [],
8261
            false,
8262
            false,
8263
            [],
8264
            [],
8265
            false,
8266
            [],
8267
            $fieldsRequired
8268
        );
8269
8270
        $form->addElement('html', '</div>');
8271
8272
        $js = $extra['jquery_ready_content'];
8273
8274
        return ['js' => $js];
8275
    }
8276
8277
    /**
8278
     * Gets the number of rows in the session table filtered through the given
8279
     * array of parameters.
8280
     *
8281
     * @param array Array of options/filters/keys
8282
     *
8283
     * @return int The number of rows, or false on wrong param
8284
     * @assert ('a') === false
8285
     */
8286
    public static function get_count_admin_complete($options = [])
8287
    {
8288
        if (!is_array($options)) {
8289
            return false;
8290
        }
8291
        $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
8292
        $tbl_session_category = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
8293
        $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
8294
        $sessionCourseUserTable = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
8295
        $courseTable = Database::get_main_table(TABLE_MAIN_COURSE);
8296
        $tbl_session_field_values = Database::get_main_table(TABLE_EXTRA_FIELD_VALUES);
8297
        $tbl_session_field_options = Database::get_main_table(TABLE_EXTRA_FIELD_OPTIONS);
8298
8299
        $where = 'WHERE 1 = 1 ';
8300
        $user_id = api_get_user_id();
8301
8302
        if (api_is_session_admin() &&
8303
            'false' == api_get_setting('allow_session_admins_to_see_all_sessions')
8304
        ) {
8305
            $where .= " WHERE s.session_admin_id = $user_id ";
8306
        }
8307
8308
        $extraFieldTables = '';
8309
        if (!empty($options['where'])) {
8310
            $options['where'] = str_replace('course_title', 'c.title', $options['where']);
8311
            $options['where'] = str_replace("( session_active = '0' )", '1=1', $options['where']);
8312
8313
            $options['where'] = str_replace(
8314
                ["AND session_active = '1'  )", " AND (  session_active = '1'  )"],
8315
                [') GROUP BY s.name HAVING session_active = 1 ', " GROUP BY s.name HAVING session_active = 1 "],
8316
                $options['where']
8317
            );
8318
8319
            $options['where'] = str_replace(
8320
                ["AND session_active = '0'  )", " AND (  session_active = '0'  )"],
8321
                [') GROUP BY s.name HAVING session_active = 0 ', " GROUP BY s.name HAVING session_active = '0' "],
8322
                $options['where']
8323
            );
8324
8325
            if (!empty($options['extra'])) {
8326
                $options['where'] = str_replace(' 1 = 1  AND', '', $options['where']);
8327
                $options['where'] = str_replace('AND', 'OR', $options['where']);
8328
8329
                foreach ($options['extra'] as $extra) {
8330
                    $options['where'] = str_replace(
8331
                        $extra['field'],
8332
                        'fv.field_id = '.$extra['id'].' AND fvo.option_value',
8333
                        $options['where']
8334
                    );
8335
                    $extraFieldTables = "$tbl_session_field_values fv, $tbl_session_field_options fvo, ";
8336
                }
8337
            }
8338
            $where .= ' AND '.$options['where'];
8339
        }
8340
8341
        $today = api_get_utc_datetime();
8342
        $query_rows = "SELECT count(*) as total_rows, c.title as course_title, s.name,
8343
                        IF (
8344
                            (s.access_start_date <= '$today' AND '$today' < s.access_end_date) OR
8345
                            (s.access_start_date = '0000-00-00 00:00:00' AND s.access_end_date = '0000-00-00 00:00:00' ) OR
8346
                            (s.access_start_date IS NULL AND s.access_end_date IS NULL) OR
8347
                            (s.access_start_date <= '$today' AND ('0000-00-00 00:00:00' = s.access_end_date OR s.access_end_date IS NULL )) OR
8348
                            ('$today' < s.access_end_date AND ('0000-00-00 00:00:00' = s.access_start_date OR s.access_start_date IS NULL) )
8349
                        , 1, 0) as session_active
8350
                       FROM $extraFieldTables $tbl_session s
8351
                       LEFT JOIN  $tbl_session_category sc
8352
                       ON s.session_category_id = sc.id
8353
                       INNER JOIN $tbl_user u
8354
                       ON s.id_coach = u.id
8355
                       INNER JOIN $sessionCourseUserTable scu
8356
                       ON s.id = scu.session_id
8357
                       INNER JOIN $courseTable c
8358
                       ON c.id = scu.c_id
8359
                       $where ";
8360
8361
        if (api_is_multiple_url_enabled()) {
8362
            $table_access_url_rel_session = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
8363
            $access_url_id = api_get_current_access_url_id();
8364
            if (-1 != $access_url_id) {
8365
                $where .= " AND ar.access_url_id = $access_url_id ";
8366
                $query_rows = "SELECT count(*) as total_rows
8367
                               FROM $tbl_session s
8368
                               LEFT JOIN  $tbl_session_category sc
8369
                               ON s.session_category_id = sc.id
8370
                               INNER JOIN $tbl_user u
8371
                               ON s.id_coach = u.id
8372
                               INNER JOIN $table_access_url_rel_session ar
8373
                               ON ar.session_id = s.id $where ";
8374
            }
8375
        }
8376
8377
        $result = Database::query($query_rows);
8378
        $num = 0;
8379
        if (Database::num_rows($result)) {
8380
            $rows = Database::fetch_array($result);
8381
            $num = $rows['total_rows'];
8382
        }
8383
8384
        return $num;
8385
    }
8386
8387
    /**
8388
     * @param string $listType
8389
     * @param array  $extraFields
8390
     *
8391
     * @return array
8392
     */
8393
    public static function getGridColumns(
8394
        $listType = 'all',
8395
        $extraFields = [],
8396
        $addExtraFields = true
8397
    ) {
8398
        $showCount = api_get_configuration_value('session_list_show_count_users');
8399
        // Column config
8400
        $operators = ['cn', 'nc'];
8401
        $date_operators = ['gt', 'ge', 'lt', 'le'];
8402
8403
        $columnModel = [];
8404
8405
        switch ($listType) {
8406
            case 'my_space':
8407
                $columns = [
8408
                    get_lang('Title'),
8409
                    get_lang('Date'),
8410
                    get_lang('NbCoursesPerSession'),
8411
                    get_lang('NbStudentPerSession'),
8412
                    get_lang('Details'),
8413
                ];
8414
8415
                $columnModel = [
8416
                    ['name' => 'name', 'index' => 'name', 'width' => '255', 'align' => 'left'],
8417
                    ['name' => 'date', 'index' => 'access_start_date', 'width' => '150', 'align' => 'left'],
8418
                    [
8419
                        'name' => 'course_per_session',
8420
                        'index' => 'course_per_session',
8421
                        'width' => '150',
8422
                        'sortable' => 'false',
8423
                        'search' => 'false',
8424
                    ],
8425
                    [
8426
                        'name' => 'student_per_session',
8427
                        'index' => 'student_per_session',
8428
                        'width' => '100',
8429
                        'sortable' => 'false',
8430
                        'search' => 'false',
8431
                    ],
8432
                    [
8433
                        'name' => 'actions',
8434
                        'index' => 'actions',
8435
                        'width' => '100',
8436
                        'sortable' => 'false',
8437
                        'search' => 'false',
8438
                    ],
8439
                ];
8440
                break;
8441
            case 'all':
8442
            case 'active':
8443
            case 'close':
8444
                $columns = [
8445
                    '#',
8446
                    get_lang('Name'),
8447
                    get_lang('Category'),
8448
                    get_lang('SessionDisplayStartDate'),
8449
                    get_lang('SessionDisplayEndDate'),
8450
                    get_lang('Visibility'),
8451
                ];
8452
8453
                $columnModel = [
8454
                    [
8455
                        'name' => 'id',
8456
                        'index' => 's.id',
8457
                        'width' => '160',
8458
                        'hidden' => 'true',
8459
                    ],
8460
                    [
8461
                        'name' => 'name',
8462
                        'index' => 's.name',
8463
                        'width' => '160',
8464
                        'align' => 'left',
8465
                        'search' => 'true',
8466
                        'searchoptions' => ['sopt' => $operators],
8467
                    ],
8468
                    [
8469
                        'name' => 'category_name',
8470
                        'index' => 'category_name',
8471
                        'width' => '40',
8472
                        'align' => 'left',
8473
                        'search' => 'true',
8474
                        'searchoptions' => ['sopt' => $operators],
8475
                    ],
8476
                    [
8477
                        'name' => 'display_start_date',
8478
                        'index' => 'display_start_date',
8479
                        'width' => '50',
8480
                        'align' => 'left',
8481
                        'search' => 'true',
8482
                        'searchoptions' => [
8483
                            'dataInit' => 'date_pick_today',
8484
                            'sopt' => $date_operators,
8485
                        ],
8486
                    ],
8487
                    [
8488
                        'name' => 'display_end_date',
8489
                        'index' => 'display_end_date',
8490
                        'width' => '50',
8491
                        'align' => 'left',
8492
                        'search' => 'true',
8493
                        'searchoptions' => [
8494
                            'dataInit' => 'date_pick_one_month',
8495
                            'sopt' => $date_operators,
8496
                        ],
8497
                    ],
8498
                    [
8499
                        'name' => 'visibility',
8500
                        'index' => 'visibility',
8501
                        'width' => '40',
8502
                        'align' => 'left',
8503
                        'search' => 'false',
8504
                    ],
8505
                ];
8506
8507
                if ($showCount) {
8508
                    $columns[] = get_lang('Users');
8509
                    $columnModel[] = [
8510
                        'name' => 'users',
8511
                        'index' => 'users',
8512
                        'width' => '20',
8513
                        'align' => 'left',
8514
                        'search' => 'false',
8515
                    ];
8516
8517
                    // ofaj
8518
                    $columns[] = get_lang('Teachers');
8519
                    $columnModel[] = [
8520
                        'name' => 'teachers',
8521
                        'index' => 'teachers',
8522
                        'width' => '20',
8523
                        'align' => 'left',
8524
                        'search' => 'false',
8525
                    ];
8526
                }
8527
8528
                if (api_get_configuration_value('allow_session_status')) {
8529
                    $columns[] = get_lang('SessionStatus');
8530
                    $list = self::getStatusList();
8531
                    $listToString = '';
8532
                    foreach ($list as $statusId => $status) {
8533
                        $listToString .= $statusId.':'.$status.';';
8534
                    }
8535
8536
                    $columnModel[] = [
8537
                        'name' => 'status',
8538
                        'index' => 'status',
8539
                        'width' => '25',
8540
                        'align' => 'left',
8541
                        'search' => 'true',
8542
                        'stype' => 'select',
8543
                        // for the bottom bar
8544
                        'searchoptions' => [
8545
                            'defaultValue' => '1',
8546
                            'value' => $listToString,
8547
                        ],
8548
                    ];
8549
                }
8550
                break;
8551
            case 'complete':
8552
                $columns = [
8553
                    get_lang('Name'),
8554
                    get_lang('SessionDisplayStartDate'),
8555
                    get_lang('SessionDisplayEndDate'),
8556
                    get_lang('Coach'),
8557
                    get_lang('Status'),
8558
                    get_lang('Visibility'),
8559
                    get_lang('CourseTitle'),
8560
                ];
8561
                $columnModel = [
8562
                    [
8563
                        'name' => 'name',
8564
                        'index' => 's.name',
8565
                        'width' => '200',
8566
                        'align' => 'left',
8567
                        'search' => 'true',
8568
                        'searchoptions' => ['sopt' => $operators],
8569
                    ],
8570
                    [
8571
                        'name' => 'display_start_date',
8572
                        'index' => 'display_start_date',
8573
                        'width' => '70',
8574
                        'align' => 'left',
8575
                        'search' => 'true',
8576
                        'searchoptions' => ['dataInit' => 'date_pick_today', 'sopt' => $date_operators],
8577
                    ],
8578
                    [
8579
                        'name' => 'display_end_date',
8580
                        'index' => 'display_end_date',
8581
                        'width' => '70',
8582
                        'align' => 'left',
8583
                        'search' => 'true',
8584
                        'searchoptions' => ['dataInit' => 'date_pick_one_month', 'sopt' => $date_operators],
8585
                    ],
8586
                    [
8587
                        'name' => 'coach_name',
8588
                        'index' => 'coach_name',
8589
                        'width' => '70',
8590
                        'align' => 'left',
8591
                        'search' => 'false',
8592
                        'searchoptions' => ['sopt' => $operators],
8593
                    ],
8594
                    [
8595
                        'name' => 'session_active',
8596
                        'index' => 'session_active',
8597
                        'width' => '25',
8598
                        'align' => 'left',
8599
                        'search' => 'true',
8600
                        'stype' => 'select',
8601
                        // for the bottom bar
8602
                        'searchoptions' => [
8603
                            'defaultValue' => '1',
8604
                            'value' => '1:'.get_lang('Active').';0:'.get_lang('Inactive'),
8605
                        ],
8606
                        // for the top bar
8607
                        'editoptions' => [
8608
                            'value' => '" ":'.get_lang('All').';1:'.get_lang('Active').';0:'.get_lang(
8609
                                    'Inactive'
8610
                                ),
8611
                        ],
8612
                    ],
8613
                    [
8614
                        'name' => 'visibility',
8615
                        'index' => 'visibility',
8616
                        'width' => '40',
8617
                        'align' => 'left',
8618
                        'search' => 'false',
8619
                    ],
8620
                    [
8621
                        'name' => 'course_title',
8622
                        'index' => 'course_title',
8623
                        'width' => '50',
8624
                        'hidden' => 'true',
8625
                        'search' => 'true',
8626
                        'searchoptions' => ['searchhidden' => 'true', 'sopt' => $operators],
8627
                    ],
8628
                ];
8629
8630
                break;
8631
8632
            case 'custom':
8633
                $columns = [
8634
                    '#',
8635
                    get_lang('Name'),
8636
                    get_lang('Category'),
8637
                    get_lang('SessionDisplayStartDate'),
8638
                    get_lang('SessionDisplayEndDate'),
8639
                    get_lang('Visibility'),
8640
                ];
8641
                $columnModel = [
8642
                    [
8643
                        'name' => 'id',
8644
                        'index' => 's.id',
8645
                        'width' => '160',
8646
                        'hidden' => 'true',
8647
                    ],
8648
                    [
8649
                        'name' => 'name',
8650
                        'index' => 's.name',
8651
                        'width' => '160',
8652
                        'align' => 'left',
8653
                        'search' => 'true',
8654
                        'searchoptions' => ['sopt' => $operators],
8655
                    ],
8656
                    [
8657
                        'name' => 'category_name',
8658
                        'index' => 'category_name',
8659
                        'width' => '40',
8660
                        'align' => 'left',
8661
                        'search' => 'true',
8662
                        'searchoptions' => ['sopt' => $operators],
8663
                    ],
8664
                    [
8665
                        'name' => 'display_start_date',
8666
                        'index' => 'display_start_date',
8667
                        'width' => '50',
8668
                        'align' => 'left',
8669
                        'search' => 'true',
8670
                        'searchoptions' => [
8671
                            'dataInit' => 'date_pick_today',
8672
                            'sopt' => $date_operators,
8673
                        ],
8674
                    ],
8675
                    [
8676
                        'name' => 'display_end_date',
8677
                        'index' => 'display_end_date',
8678
                        'width' => '50',
8679
                        'align' => 'left',
8680
                        'search' => 'true',
8681
                        'searchoptions' => [
8682
                            'dataInit' => 'date_pick_one_month',
8683
                            'sopt' => $date_operators,
8684
                        ],
8685
                    ],
8686
                    [
8687
                        'name' => 'visibility',
8688
                        'index' => 'visibility',
8689
                        'width' => '40',
8690
                        'align' => 'left',
8691
                        'search' => 'false',
8692
                    ],
8693
                ];
8694
8695
                if ($showCount) {
8696
                    $columns[] = get_lang('Users');
8697
                    $columnModel[] = [
8698
                        'name' => 'users',
8699
                        'index' => 'users',
8700
                        'width' => '20',
8701
                        'align' => 'left',
8702
                        'search' => 'false',
8703
                    ];
8704
8705
                    // ofaj
8706
                    $columns[] = get_lang('Teachers');
8707
                    $columnModel[] = [
8708
                        'name' => 'teachers',
8709
                        'index' => 'teachers',
8710
                        'width' => '20',
8711
                        'align' => 'left',
8712
                        'search' => 'false',
8713
                    ];
8714
                }
8715
8716
                if (api_get_configuration_value('allow_session_status')) {
8717
                    $columns[] = get_lang('SessionStatus');
8718
                    $list = self::getStatusList();
8719
                    $listToString = '';
8720
                    foreach ($list as $statusId => $status) {
8721
                        $listToString .= $statusId.':'.$status.';';
8722
                    }
8723
8724
                    $columnModel[] = [
8725
                        'name' => 'status',
8726
                        'index' => 'status',
8727
                        'width' => '25',
8728
                        'align' => 'left',
8729
                        'search' => 'true',
8730
                        'stype' => 'select',
8731
                        // for the bottom bar
8732
                        'searchoptions' => [
8733
                            'defaultValue' => '1',
8734
                            'value' => $listToString,
8735
                        ],
8736
                    ];
8737
                }
8738
8739
                break;
8740
        }
8741
8742
        if (!empty($extraFields)) {
8743
            foreach ($extraFields as $field) {
8744
                $columns[] = $field['display_text'];
8745
                $columnModel[] = [
8746
                    'name' => $field['variable'],
8747
                    'index' => $field['variable'],
8748
                    'width' => '80',
8749
                    'align' => 'center',
8750
                    'search' => 'false',
8751
                ];
8752
            }
8753
        }
8754
8755
        // Inject extra session fields
8756
        $rules = [];
8757
        if ($addExtraFields) {
8758
            $sessionField = new ExtraFieldModel('session');
8759
            $rules = $sessionField->getRules($columns, $columnModel);
8760
        }
8761
8762
        if (!in_array('actions', array_column($columnModel, 'name'))) {
8763
            $columnModel[] = [
8764
                'name' => 'actions',
8765
                'index' => 'actions',
8766
                'width' => '80',
8767
                'align' => 'left',
8768
                'formatter' => 'action_formatter',
8769
                'sortable' => 'false',
8770
                'search' => 'false',
8771
            ];
8772
            $columns[] = get_lang('Actions');
8773
        }
8774
8775
        $columnName = [];
8776
        foreach ($columnModel as $col) {
8777
            $columnName[] = $col['name'];
8778
        }
8779
8780
        $return = [
8781
            'columns' => $columns,
8782
            'column_model' => $columnModel,
8783
            'rules' => $rules,
8784
            'simple_column_name' => $columnName,
8785
        ];
8786
8787
        return $return;
8788
    }
8789
8790
    /**
8791
     * Converts all dates sent through the param array (given form) to correct dates with timezones.
8792
     *
8793
     * @param array The dates The same array, with times converted
8794
     * @param bool $applyFormat Whether apply the DATE_TIME_FORMAT_SHORT format for sessions
8795
     *
8796
     * @return array The same array, with times converted
8797
     */
8798
    public static function convert_dates_to_local($params, $applyFormat = false)
8799
    {
8800
        if (!is_array($params)) {
8801
            return false;
8802
        }
8803
        $params['display_start_date'] = api_get_local_time($params['display_start_date'], null, null, true);
8804
        $params['display_end_date'] = api_get_local_time($params['display_end_date'], null, null, true);
8805
8806
        $params['access_start_date'] = api_get_local_time($params['access_start_date'], null, null, true);
8807
        $params['access_end_date'] = api_get_local_time($params['access_end_date'], null, null, true);
8808
8809
        $params['coach_access_start_date'] = isset($params['coach_access_start_date']) ? api_get_local_time($params['coach_access_start_date'], null, null, true) : null;
8810
        $params['coach_access_end_date'] = isset($params['coach_access_end_date']) ? api_get_local_time($params['coach_access_end_date'], null, null, true) : null;
8811
8812
        if ($applyFormat) {
8813
            if (isset($params['display_start_date'])) {
8814
                $params['display_start_date'] = api_format_date($params['display_start_date'], DATE_TIME_FORMAT_SHORT);
8815
            }
8816
8817
            if (isset($params['display_end_date'])) {
8818
                $params['display_end_date'] = api_format_date($params['display_end_date'], DATE_TIME_FORMAT_SHORT);
8819
            }
8820
8821
            if (isset($params['access_start_date'])) {
8822
                $params['access_start_date'] = api_format_date($params['access_start_date'], DATE_TIME_FORMAT_SHORT);
8823
            }
8824
8825
            if (isset($params['access_end_date'])) {
8826
                $params['access_end_date'] = api_format_date($params['access_end_date'], DATE_TIME_FORMAT_SHORT);
8827
            }
8828
8829
            if (isset($params['coach_access_start_date'])) {
8830
                $params['coach_access_start_date'] = api_format_date($params['coach_access_start_date'], DATE_TIME_FORMAT_SHORT);
8831
            }
8832
8833
            if (isset($params['coach_access_end_date'])) {
8834
                $params['coach_access_end_date'] = api_format_date($params['coach_access_end_date'], DATE_TIME_FORMAT_SHORT);
8835
            }
8836
        }
8837
8838
        return $params;
8839
    }
8840
8841
    /**
8842
     * Gets the admin session list callback of the session/session_list.php
8843
     * page with all user/details in the right fomat.
8844
     *
8845
     * @param array $options
8846
     *
8847
     * @return array Array of rows results
8848
     * @asset ('a') === false
8849
     */
8850
    public static function get_sessions_admin_complete($options = [])
8851
    {
8852
        if (!is_array($options)) {
8853
            return false;
8854
        }
8855
8856
        $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
8857
        $tbl_session_category = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
8858
        $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
8859
        $tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
8860
        $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
8861
8862
        $extraFieldTable = Database::get_main_table(TABLE_EXTRA_FIELD);
8863
        $tbl_session_field_values = Database::get_main_table(TABLE_EXTRA_FIELD_VALUES);
8864
        $tbl_session_field_options = Database::get_main_table(TABLE_EXTRA_FIELD_OPTIONS);
8865
8866
        $where = 'WHERE 1 = 1 ';
8867
        $user_id = api_get_user_id();
8868
8869
        if (!api_is_platform_admin()) {
8870
            if (api_is_session_admin() &&
8871
                'false' == api_get_setting('allow_session_admins_to_manage_all_sessions')
8872
            ) {
8873
                $where .= " AND s.session_admin_id = $user_id ";
8874
            }
8875
        }
8876
8877
        $coach_name = " CONCAT(u.lastname , ' ', u.firstname) as coach_name ";
8878
        if (api_is_western_name_order()) {
8879
            $coach_name = " CONCAT(u.firstname, ' ', u.lastname) as coach_name ";
8880
        }
8881
8882
        $today = api_get_utc_datetime();
8883
        $injectExtraFields = null;
8884
        $extra_fields_info = [];
8885
8886
        //for now only sessions
8887
        $extra_field = new ExtraFieldModel('session');
8888
        $double_fields = [];
8889
        $extra_field_option = new ExtraFieldOption('session');
8890
8891
        if (isset($options['extra'])) {
8892
            $extra_fields = $options['extra'];
8893
            if (!empty($extra_fields)) {
8894
                foreach ($extra_fields as $extra) {
8895
                    $injectExtraFields .= " IF (fv.field_id = {$extra['id']}, fvo.option_display_text, NULL ) as {$extra['field']} , ";
8896
                    if (isset($extra_fields_info[$extra['id']])) {
8897
                        $info = $extra_fields_info[$extra['id']];
8898
                    } else {
8899
                        $info = $extra_field->get($extra['id']);
8900
                        $extra_fields_info[$extra['id']] = $info;
8901
                    }
8902
8903
                    if (ExtraFieldModel::FIELD_TYPE_DOUBLE_SELECT == $info['field_type']) {
8904
                        $double_fields[$info['id']] = $info;
8905
                    }
8906
                }
8907
            }
8908
        }
8909
8910
        $options_by_double = [];
8911
        foreach ($double_fields as $double) {
8912
            $my_options = $extra_field_option->get_field_options_by_field(
8913
                $double['id'],
8914
                true
8915
            );
8916
            $options_by_double['extra_'.$double['field_variable']] = $my_options;
8917
        }
8918
8919
        //sc.name as category_name,
8920
        $select = "
8921
                SELECT * FROM (
8922
                    SELECT DISTINCT
8923
                        IF (
8924
                            (s.access_start_date <= '$today' AND '$today' < s.access_end_date) OR
8925
                            (s.access_start_date = '0000-00-00 00:00:00' AND s.access_end_date = '0000-00-00 00:00:00' ) OR
8926
                            (s.access_start_date IS NULL AND s.access_end_date IS NULL) OR
8927
                            (s.access_start_date <= '$today' AND ('0000-00-00 00:00:00' = s.access_end_date OR s.access_end_date IS NULL )) OR
8928
                            ('$today' < s.access_end_date AND ('0000-00-00 00:00:00' = s.access_start_date OR s.access_start_date IS NULL) )
8929
                        , 1, 0) as session_active,
8930
                s.name,
8931
                s.nbr_courses,
8932
                s.nbr_users,
8933
                s.display_start_date,
8934
                s.display_end_date,
8935
                $coach_name,
8936
                access_start_date,
8937
                access_end_date,
8938
                s.visibility,
8939
                u.id as user_id,
8940
                $injectExtraFields
8941
                c.title as course_title,
8942
                s.id ";
8943
8944
        if (!empty($options['where'])) {
8945
            if (!empty($options['extra'])) {
8946
                $options['where'] = str_replace(' 1 = 1  AND', '', $options['where']);
8947
                $options['where'] = str_replace('AND', 'OR', $options['where']);
8948
                foreach ($options['extra'] as $extra) {
8949
                    $options['where'] = str_replace($extra['field'], 'fv.field_id = '.$extra['id'].' AND fvo.option_value', $options['where']);
8950
                }
8951
            }
8952
            $options['where'] = str_replace('course_title', 'c.title', $options['where']);
8953
            $options['where'] = str_replace("( session_active = '0' )", '1=1', $options['where']);
8954
            $options['where'] = str_replace(
8955
                ["AND session_active = '1'  )", " AND (  session_active = '1'  )"],
8956
                [') GROUP BY s.name HAVING session_active = 1 ', " GROUP BY s.name HAVING session_active = 1 "],
8957
                $options['where']
8958
            );
8959
8960
            $options['where'] = str_replace(
8961
                ["AND session_active = '0'  )", " AND (  session_active = '0'  )"],
8962
                [') GROUP BY s.name HAVING session_active = 0 ', " GROUP BY s.name HAVING session_active = '0' "],
8963
                $options['where']
8964
            );
8965
8966
            $where .= ' AND '.$options['where'];
8967
        }
8968
8969
        $limit = '';
8970
        if (!empty($options['limit'])) {
8971
            $limit = ' LIMIT '.$options['limit'];
8972
        }
8973
8974
        $query = "$select FROM $tbl_session s
8975
                    LEFT JOIN $tbl_session_field_values fv
8976
                    ON (fv.item_id = s.id)
8977
                    LEFT JOIN $extraFieldTable f
8978
                    ON f.id = fv.field_id
8979
                    LEFT JOIN $tbl_session_field_options fvo
8980
                    ON (fv.field_id = fvo.field_id)
8981
                    LEFT JOIN $tbl_session_rel_course src
8982
                    ON (src.session_id = s.id)
8983
                    LEFT JOIN $tbl_course c
8984
                    ON (src.c_id = c.id)
8985
                    LEFT JOIN $tbl_session_category sc
8986
                    ON (s.session_category_id = sc.id)
8987
                    INNER JOIN $tbl_user u
8988
                    ON (s.id_coach = u.id)
8989
                    $where
8990
                    $limit
8991
        ";
8992
8993
        if (api_is_multiple_url_enabled()) {
8994
            $table_access_url_rel_session = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
8995
            $access_url_id = api_get_current_access_url_id();
8996
            if (-1 != $access_url_id) {
8997
                $query = "$select
8998
                    FROM $tbl_session s
8999
                    LEFT JOIN $tbl_session_field_values fv
9000
                    ON (fv.item_id = s.id)
9001
                    LEFT JOIN $tbl_session_field_options fvo
9002
                    ON (fv.field_id = fvo.field_id)
9003
                    LEFT JOIN $tbl_session_rel_course src
9004
                    ON (src.session_id = s.id)
9005
                    LEFT JOIN $tbl_course c
9006
                    ON (src.c_id = c.id)
9007
                    LEFT JOIN $tbl_session_category sc
9008
                    ON (s.session_category_id = sc.id)
9009
                    INNER JOIN $tbl_user u
9010
                    ON (s.id_coach = u.id)
9011
                    INNER JOIN $table_access_url_rel_session ar
9012
                    ON (ar.session_id = s.id AND ar.access_url_id = $access_url_id)
9013
                    $where
9014
                    $limit
9015
                ";
9016
            }
9017
        }
9018
9019
        $query .= ') AS s';
9020
9021
        if (!empty($options['order'])) {
9022
            $query .= ' ORDER BY '.$options['order'];
9023
        }
9024
9025
        $result = Database::query($query);
9026
9027
        $acceptIcon = Display::return_icon(
9028
            'accept.png',
9029
            get_lang('Active'),
9030
            [],
9031
            ICON_SIZE_SMALL
9032
        );
9033
9034
        $errorIcon = Display::return_icon(
9035
            'error.png',
9036
            get_lang('Inactive'),
9037
            [],
9038
            ICON_SIZE_SMALL
9039
        );
9040
9041
        $formatted_sessions = [];
9042
        if (Database::num_rows($result)) {
9043
            $sessions = Database::store_result($result, 'ASSOC');
9044
            foreach ($sessions as $session) {
9045
                $session_id = $session['id'];
9046
                $session['name'] = Display::url($session['name'], "resume_session.php?id_session=".$session['id']);
9047
                $session['coach_name'] = Display::url($session['coach_name'], "user_information.php?user_id=".$session['user_id']);
9048
                if (1 == $session['session_active']) {
9049
                    $session['session_active'] = $acceptIcon;
9050
                } else {
9051
                    $session['session_active'] = $errorIcon;
9052
                }
9053
9054
                $session = self::convert_dates_to_local($session);
9055
9056
                switch ($session['visibility']) {
9057
                    case SESSION_VISIBLE_READ_ONLY: //1
9058
                        $session['visibility'] = get_lang('ReadOnly');
9059
                        break;
9060
                    case SESSION_VISIBLE:           //2
9061
                    case SESSION_AVAILABLE:         //4
9062
                        $session['visibility'] = get_lang('Visible');
9063
                        break;
9064
                    case SESSION_INVISIBLE:         //3
9065
                        $session['visibility'] = api_ucfirst(get_lang('Invisible'));
9066
                        break;
9067
                }
9068
9069
                // Cleaning double selects
9070
                foreach ($session as $key => &$value) {
9071
                    if (isset($options_by_double[$key]) || isset($options_by_double[$key.'_second'])) {
9072
                        $options = explode('::', $value);
9073
                    }
9074
                    $original_key = $key;
9075
9076
                    if (strpos($key, '_second') === false) {
9077
                    } else {
9078
                        $key = str_replace('_second', '', $key);
9079
                    }
9080
9081
                    if (isset($options_by_double[$key])) {
9082
                        if (isset($options[0])) {
9083
                            if (isset($options_by_double[$key][$options[0]])) {
9084
                                if (strpos($original_key, '_second') === false) {
9085
                                    $value = $options_by_double[$key][$options[0]]['option_display_text'];
9086
                                } else {
9087
                                    $value = $options_by_double[$key][$options[1]]['option_display_text'];
9088
                                }
9089
                            }
9090
                        }
9091
                    }
9092
                }
9093
9094
                // Magic filter
9095
                if (isset($formatted_sessions[$session_id])) {
9096
                    $formatted_sessions[$session_id] = self::compareArraysToMerge(
9097
                        $formatted_sessions[$session_id],
9098
                        $session
9099
                    );
9100
                } else {
9101
                    $formatted_sessions[$session_id] = $session;
9102
                }
9103
            }
9104
        }
9105
9106
        return $formatted_sessions;
9107
    }
9108
9109
    /**
9110
     * Compare two arrays.
9111
     *
9112
     * @param array $array1
9113
     * @param array $array2
9114
     *
9115
     * @return array
9116
     */
9117
    public static function compareArraysToMerge($array1, $array2)
9118
    {
9119
        if (empty($array2)) {
9120
            return $array1;
9121
        }
9122
        foreach ($array1 as $key => $item) {
9123
            if (!isset($array1[$key])) {
9124
                //My string is empty try the other one
9125
                if (isset($array2[$key]) && !empty($array2[$key])) {
9126
                    $array1[$key] = $array2[$key];
9127
                }
9128
            }
9129
        }
9130
9131
        return $array1;
9132
    }
9133
9134
    /**
9135
     * Get link to the admin page for this session.
9136
     *
9137
     * @param int $id Session ID
9138
     *
9139
     * @return mixed URL to the admin page to manage the session, or false on error
9140
     */
9141
    public static function getAdminPath($id)
9142
    {
9143
        $id = (int) $id;
9144
        $session = self::fetch($id);
9145
        if (empty($session)) {
9146
            return false;
9147
        }
9148
9149
        return api_get_path(WEB_CODE_PATH).'session/resume_session.php?id_session='.$id;
9150
    }
9151
9152
    /**
9153
     * Get link to the user page for this session.
9154
     * If a course is provided, build the link to the course.
9155
     *
9156
     * @param int $id       Session ID
9157
     * @param int $courseId Course ID (optional) in case the link has to send straight to the course
9158
     *
9159
     * @return mixed URL to the page to use the session, or false on error
9160
     */
9161
    public static function getPath($id, $courseId = 0)
9162
    {
9163
        $id = (int) $id;
9164
        $session = self::fetch($id);
9165
        if (empty($session)) {
9166
            return false;
9167
        }
9168
        if (empty($courseId)) {
9169
            return api_get_path(WEB_CODE_PATH).'session/index.php?session_id='.$id;
9170
        } else {
9171
            $courseInfo = api_get_course_info_by_id($courseId);
9172
            if ($courseInfo) {
9173
                return $courseInfo['course_public_url'].'?id_session='.$id;
9174
            }
9175
        }
9176
9177
        return false;
9178
    }
9179
9180
    /**
9181
     * Return an associative array 'id_course' => [id_session1, id_session2...]
9182
     * where course id_course is in sessions id_session1, id_session2
9183
     * for course where user is coach
9184
     * i.e. coach for the course or
9185
     * main coach for a session the course is in
9186
     * for a session category (or woth no session category if empty).
9187
     *
9188
     * @param int $userId
9189
     *
9190
     * @return array
9191
     */
9192
    public static function getSessionCourseForUser($userId)
9193
    {
9194
        // list of COURSES where user is COURSE session coach
9195
        $listCourseCourseCoachSession = self::getCoursesForCourseSessionCoach($userId);
9196
        // list of courses where user is MAIN session coach
9197
        $listCourseMainCoachSession = self::getCoursesForMainSessionCoach($userId);
9198
        // merge these 2 array
9199
        $listResCourseSession = $listCourseCourseCoachSession;
9200
        foreach ($listCourseMainCoachSession as $courseId2 => $listSessionId2) {
9201
            if (isset($listResCourseSession[$courseId2])) {
9202
                // if sessionId array exists for this course
9203
                // same courseId, merge the list of session
9204
                foreach ($listCourseMainCoachSession[$courseId2] as $i => $sessionId2) {
9205
                    if (!in_array($sessionId2, $listResCourseSession[$courseId2])) {
9206
                        $listResCourseSession[$courseId2][] = $sessionId2;
9207
                    }
9208
                }
9209
            } else {
9210
                $listResCourseSession[$courseId2] = $listSessionId2;
9211
            }
9212
        }
9213
9214
        return $listResCourseSession;
9215
    }
9216
9217
    /**
9218
     * Return an associative array 'id_course' => [id_session1, id_session2...]
9219
     * where course id_course is in sessions id_session1, id_session2.
9220
     *
9221
     * @param int $userId
9222
     *
9223
     * @return array
9224
     */
9225
    public static function getCoursesForCourseSessionCoach($userId)
9226
    {
9227
        $userId = (int) $userId;
9228
        $listResCourseSession = [];
9229
        $tblCourse = Database::get_main_table(TABLE_MAIN_COURSE);
9230
        $tblSessionRelCourseRelUser = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
9231
9232
        $sql = "SELECT session_id, c_id, c.id
9233
                FROM $tblSessionRelCourseRelUser srcru
9234
                LEFT JOIN $tblCourse c
9235
                ON c.id = srcru.c_id
9236
                WHERE
9237
                    srcru.user_id = $userId AND
9238
                    srcru.status = 2";
9239
9240
        $res = Database::query($sql);
9241
9242
        while ($data = Database::fetch_assoc($res)) {
9243
            if (api_get_session_visibility($data['session_id'])) {
9244
                if (!isset($listResCourseSession[$data['id']])) {
9245
                    $listResCourseSession[$data['id']] = [];
9246
                }
9247
                $listResCourseSession[$data['id']][] = $data['session_id'];
9248
            }
9249
        }
9250
9251
        return $listResCourseSession;
9252
    }
9253
9254
    /**
9255
     * Return an associative array 'id_course' => [id_session1, id_session2...]
9256
     * where course id_course is in sessions id_session1, id_session2.
9257
     *
9258
     * @param $userId
9259
     *
9260
     * @return array
9261
     */
9262
    public static function getCoursesForMainSessionCoach($userId)
9263
    {
9264
        $userId = (int) $userId;
9265
        $listResCourseSession = [];
9266
        $tblSession = Database::get_main_table(TABLE_MAIN_SESSION);
9267
9268
        // list of SESSION where user is session coach
9269
        $sql = "SELECT id FROM $tblSession
9270
                WHERE id_coach = ".$userId;
9271
        $res = Database::query($sql);
9272
9273
        while ($data = Database::fetch_assoc($res)) {
9274
            $sessionId = $data['id'];
9275
            $listCoursesInSession = self::getCoursesInSession($sessionId);
9276
            foreach ($listCoursesInSession as $i => $courseId) {
9277
                if (api_get_session_visibility($sessionId)) {
9278
                    if (!isset($listResCourseSession[$courseId])) {
9279
                        $listResCourseSession[$courseId] = [];
9280
                    }
9281
                    $listResCourseSession[$courseId][] = $sessionId;
9282
                }
9283
            }
9284
        }
9285
9286
        return $listResCourseSession;
9287
    }
9288
9289
    /**
9290
     * Return an array of course_id used in session $sessionId.
9291
     *
9292
     * @param $sessionId
9293
     *
9294
     * @return array
9295
     */
9296
    public static function getCoursesInSession($sessionId)
9297
    {
9298
        if (empty($sessionId)) {
9299
            return [];
9300
        }
9301
9302
        $tblSessionRelCourse = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
9303
        $tblCourse = Database::get_main_table(TABLE_MAIN_COURSE);
9304
9305
        // list of course in this session
9306
        $sql = "SELECT session_id, c.id
9307
                FROM $tblSessionRelCourse src
9308
                LEFT JOIN $tblCourse c
9309
                ON c.id = src.c_id
9310
                WHERE session_id = ".intval($sessionId);
9311
        $res = Database::query($sql);
9312
9313
        $listResultsCourseId = [];
9314
        while ($data = Database::fetch_assoc($res)) {
9315
            $listResultsCourseId[] = $data['id'];
9316
        }
9317
9318
        return $listResultsCourseId;
9319
    }
9320
9321
    /**
9322
     * Return an array of courses in session for user
9323
     * and for each courses the list of session that use this course for user.
9324
     *
9325
     * [0] => array
9326
     *      userCatId
9327
     *      userCatTitle
9328
     *      courseInUserCatList
9329
     *          [0] => array
9330
     *              courseId
9331
     *              title
9332
     *              courseCode
9333
     *              sessionCatList
9334
     *                  [0] => array
9335
     *                      catSessionId
9336
     *                      catSessionName
9337
     *                      sessionList
9338
     *                          [0] => array
9339
     *                              sessionId
9340
     *                              sessionName
9341
     *
9342
     * @param int $userId
9343
     *
9344
     * @return array
9345
     */
9346
    public static function getNamedSessionCourseForCoach($userId)
9347
    {
9348
        $listResults = [];
9349
        $listCourseSession = self::getSessionCourseForUser($userId);
9350
        foreach ($listCourseSession as $courseId => $listSessionId) {
9351
            // Course info
9352
            $courseInfo = api_get_course_info_by_id($courseId);
9353
            $listOneCourse = [];
9354
            $listOneCourse['courseId'] = $courseId;
9355
            $listOneCourse['title'] = $courseInfo['title'];
9356
            //$listOneCourse['courseCode'] = $courseInfo['code'];
9357
            $listOneCourse['course'] = $courseInfo;
9358
            $listOneCourse['sessionCatList'] = [];
9359
            $listCat = [];
9360
            foreach ($listSessionId as $i => $sessionId) {
9361
                // here we got all session for this course
9362
                // lets check there session categories
9363
                $sessionInfo = self::fetch($sessionId);
9364
                $catId = $sessionInfo['session_category_id'];
9365
                if (!isset($listCat[$catId])) {
9366
                    $listCatInfo = self::get_session_category($catId);
9367
                    if ($listCatInfo) {
9368
                        $listCat[$catId] = [];
9369
                        $listCat[$catId]['catSessionId'] = $catId;
9370
                        $listCat[$catId]['catSessionName'] = $listCatInfo['name'];
9371
                        $listCat[$catId]['sessionList'] = [];
9372
                    }
9373
                }
9374
                $listSessionInfo = self::fetch($sessionId);
9375
                $listSessionIdName = [
9376
                    'sessionId' => $sessionId,
9377
                    'sessionName' => $listSessionInfo['name'],
9378
                ];
9379
                $listCat[$catId]['sessionList'][] = $listSessionIdName;
9380
            }
9381
            // sort $listCat by catSessionName
9382
            usort($listCat, 'self::compareBySessionName');
9383
            // in each catSession sort sessionList by sessionName
9384
            foreach ($listCat as $i => $listCatSessionInfo) {
9385
                $listSessionList = $listCatSessionInfo['sessionList'];
9386
                usort($listSessionList, 'self::compareCatSessionInfo');
9387
                $listCat[$i]['sessionList'] = $listSessionList;
9388
            }
9389
9390
            $listOneCourse['sessionCatList'] = $listCat;
9391
9392
            // user course category
9393
            $courseCategory = CourseManager::getUserCourseCategoryForCourse(
9394
                $userId,
9395
                $courseId
9396
            );
9397
9398
            $userCatTitle = '';
9399
            $userCatId = 0;
9400
            if ($courseCategory) {
9401
                $userCatId = $courseCategory['user_course_cat'];
9402
                $userCatTitle = $courseCategory['title'];
9403
            }
9404
9405
            $listResults[$userCatId]['courseInUserCategoryId'] = $userCatId;
9406
            $listResults[$userCatId]['courseInUserCategoryTitle'] = $userCatTitle;
9407
            $listResults[$userCatId]['courseInUserCatList'][] = $listOneCourse;
9408
        }
9409
9410
        // sort by user course cat
9411
        uasort($listResults, 'self::compareByUserCourseCat');
9412
9413
        // sort by course title
9414
        foreach ($listResults as $userCourseCatId => $tabCoursesInCat) {
9415
            $courseInUserCatList = $tabCoursesInCat['courseInUserCatList'];
9416
            uasort($courseInUserCatList, 'self::compareByCourse');
9417
            $listResults[$userCourseCatId]['courseInUserCatList'] = $courseInUserCatList;
9418
        }
9419
9420
        return $listResults;
9421
    }
9422
9423
    /**
9424
     * @param int $userId
9425
     * @param int $courseId
9426
     *
9427
     * @return array
9428
     */
9429
    public static function searchCourseInSessionsFromUser($userId, $courseId)
9430
    {
9431
        $table = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
9432
        $userId = (int) $userId;
9433
        $courseId = (int) $courseId;
9434
        if (empty($userId) || empty($courseId)) {
9435
            return [];
9436
        }
9437
9438
        $sql = "SELECT * FROM $table
9439
                WHERE c_id = $courseId AND user_id = $userId";
9440
        $result = Database::query($sql);
9441
9442
        return Database::store_result($result, 'ASSOC');
9443
    }
9444
9445
    /**
9446
     * Subscribe and redirect to session after inscription.
9447
     */
9448
    public static function redirectToSession()
9449
    {
9450
        $sessionId = (int) ChamiloSession::read('session_redirect');
9451
        $onlyOneCourseSessionToRedirect = ChamiloSession::read('only_one_course_session_redirect');
9452
        if ($sessionId) {
9453
            $sessionInfo = api_get_session_info($sessionId);
9454
            if (!empty($sessionInfo)) {
9455
                $userId = api_get_user_id();
9456
                $response = self::isUserSubscribedAsStudent($sessionId, $userId);
9457
                if ($response) {
9458
                    $urlToRedirect = api_get_path(WEB_CODE_PATH).'session/index.php?session_id='.$sessionId;
9459
                    if (!empty($onlyOneCourseSessionToRedirect)) {
9460
                        $urlToRedirect = api_get_path(WEB_PATH).
9461
                            'courses/'.$onlyOneCourseSessionToRedirect.'/index.php?id_session='.$sessionId;
9462
                    }
9463
9464
                    header('Location: '.$urlToRedirect);
9465
                    exit;
9466
                }
9467
            }
9468
        }
9469
    }
9470
9471
    /**
9472
     * @return int
9473
     */
9474
    public static function getCountUsersInCourseSession(Course $course, Session $session)
9475
    {
9476
        $urlId = api_get_current_access_url_id();
9477
9478
        return Database::getManager()
9479
            ->createQuery("
9480
                SELECT COUNT(scu)
9481
                FROM ChamiloCoreBundle:SessionRelCourseRelUser scu
9482
                INNER JOIN ChamiloCoreBundle:SessionRelUser su
9483
                    WITH scu.user = su.user
9484
                    AND scu.session = su.session
9485
                INNER JOIN ChamiloCoreBundle:AccessUrlRelUser a
9486
                    WITH a.user = su.user
9487
                WHERE
9488
                    scu.course = :course AND
9489
                    su.relationType <> :relationType AND
9490
                    scu.session = :session AND
9491
                    a.portal = :url
9492
            ")
9493
            ->setParameters([
9494
                'course' => $course->getId(),
9495
                'relationType' => SESSION_RELATION_TYPE_RRHH,
9496
                'session' => $session->getId(),
9497
                'url' => $urlId,
9498
            ])
9499
            ->getSingleScalarResult();
9500
    }
9501
9502
    /**
9503
     * Get course IDs where user in not subscribed in session.
9504
     *
9505
     * @return array
9506
     */
9507
    public static function getAvoidedCoursesInSession(User $user, Session $session)
9508
    {
9509
        $courseIds = [];
9510
9511
        /** @var SessionRelCourse $sessionCourse */
9512
        foreach ($session->getCourses() as $sessionCourse) {
9513
            /** @var Course $course */
9514
            $course = $sessionCourse->getCourse();
9515
9516
            if ($session->getUserInCourse($user, $course)->count()) {
9517
                continue;
9518
            }
9519
9520
            $courseIds[] = $course->getId();
9521
        }
9522
9523
        return $courseIds;
9524
    }
9525
9526
    /**
9527
     * @param int             $userId
9528
     * @param int             $sessionId
9529
     * @param ExtraFieldValue $extraFieldValue
9530
     * @param string          $collapsableLink
9531
     *
9532
     * @return array
9533
     */
9534
    public static function getCollapsableData($userId, $sessionId, $extraFieldValue, $collapsableLink)
9535
    {
9536
        $collapsed = 0;
9537
9538
        // Get default collapsed value in extra field
9539
        $value = $extraFieldValue->get_values_by_handler_and_field_variable($sessionId, 'collapsed');
9540
        if (!empty($value) && isset($value['value'])) {
9541
            $collapsed = $value['value'];
9542
        }
9543
9544
        $userRelSession = self::getUserSession($userId, $sessionId);
9545
9546
        if ($userRelSession) {
9547
            if (isset($userRelSession['collapsed']) && '' != $userRelSession['collapsed']) {
9548
                $collapsed = $userRelSession['collapsed'];
9549
            }
9550
        } else {
9551
            return ['collapsed' => $collapsed, 'collapsable_link' => '&nbsp;'];
9552
        }
9553
9554
        $link = $collapsableLink.'&session_id='.$sessionId.'&value=1';
9555
        $image = '<i class="fa fa-folder-open"></i>';
9556
        if (1 == $collapsed) {
9557
            $link = $collapsableLink.'&session_id='.$sessionId.'&value=0';
9558
            $image = '<i class="fa fa-folder"></i>';
9559
        }
9560
9561
        $link = Display::url(
9562
            $image,
9563
            $link
9564
        );
9565
9566
        return ['collapsed' => $collapsed, 'collapsable_link' => $link];
9567
    }
9568
9569
    /**
9570
     * Converts "start date" and "end date" to "From start date to end date" string.
9571
     *
9572
     * @param string $startDate
9573
     * @param string $endDate
9574
     * @param bool   $showTime
9575
     * @param bool   $dateHuman
9576
     *
9577
     * @return string
9578
     */
9579
    public static function convertSessionDateToString($startDate, $endDate, $showTime, $dateHuman)
9580
    {
9581
        // api_get_local_time returns empty if date is invalid like 0000-00-00 00:00:00
9582
        $startDateToLocal = api_get_local_time(
9583
            $startDate,
9584
            null,
9585
            null,
9586
            true,
9587
            $showTime,
9588
            $dateHuman
9589
        );
9590
        $endDateToLocal = api_get_local_time(
9591
            $endDate,
9592
            null,
9593
            null,
9594
            true,
9595
            $showTime,
9596
            $dateHuman
9597
        );
9598
9599
        $format = $showTime ? DATE_TIME_FORMAT_LONG_24H : DATE_FORMAT_LONG_NO_DAY;
9600
9601
        $result = '';
9602
        if (!empty($startDateToLocal) && !empty($endDateToLocal)) {
9603
            $result = sprintf(
9604
                get_lang('FromDateXToDateY'),
9605
                api_format_date($startDateToLocal, $format),
9606
                api_format_date($endDateToLocal, $format)
9607
            );
9608
        } else {
9609
            if (!empty($startDateToLocal)) {
9610
                $result = get_lang('From').' '.api_format_date($startDateToLocal, $format);
9611
            }
9612
            if (!empty($endDateToLocal)) {
9613
                $result = get_lang('Until').' '.api_format_date($endDateToLocal, $format);
9614
            }
9615
        }
9616
        if (empty($result)) {
9617
            $result = get_lang('NoTimeLimits');
9618
        }
9619
9620
        return $result;
9621
    }
9622
9623
    public static function getStatusList()
9624
    {
9625
        return [
9626
            self::STATUS_PLANNED => get_lang('Planned'),
9627
            self::STATUS_PROGRESS => get_lang('InProgress'),
9628
            self::STATUS_FINISHED => get_lang('Finished'),
9629
            self::STATUS_CANCELLED => get_lang('Cancelled'),
9630
        ];
9631
    }
9632
9633
    public static function getStatusLabel($status)
9634
    {
9635
        $list = self::getStatusList();
9636
9637
        if (!isset($list[$status])) {
9638
            return get_lang('NoStatus');
9639
        }
9640
9641
        return $list[$status];
9642
    }
9643
9644
    public static function getDefaultSessionTab()
9645
    {
9646
        $default = 'all';
9647
        $view = api_get_configuration_value('default_session_list_view');
9648
9649
        if (!empty($view)) {
9650
            $default = $view;
9651
        }
9652
9653
        return $default;
9654
    }
9655
9656
    /**
9657
     * @return string
9658
     */
9659
    public static function getSessionListTabs($listType)
9660
    {
9661
        $tabs = [
9662
            [
9663
                'content' => get_lang('AllSessionsShort'),
9664
                'url' => api_get_path(WEB_CODE_PATH).'session/session_list.php?list_type=all',
9665
            ],
9666
            [
9667
                'content' => get_lang('ActiveSessionsShort'),
9668
                'url' => api_get_path(WEB_CODE_PATH).'session/session_list.php?list_type=active',
9669
            ],
9670
            [
9671
                'content' => get_lang('ClosedSessionsShort'),
9672
                'url' => api_get_path(WEB_CODE_PATH).'session/session_list.php?list_type=close',
9673
            ],
9674
            [
9675
                'content' => get_lang('SessionListCustom'),
9676
                'url' => api_get_path(WEB_CODE_PATH).'session/session_list.php?list_type=custom',
9677
            ],
9678
            /*[
9679
                'content' => get_lang('Complete'),
9680
                'url' => api_get_path(WEB_CODE_PATH).'session/session_list_simple.php?list_type=complete',
9681
            ],*/
9682
        ];
9683
9684
        switch ($listType) {
9685
            case 'all':
9686
                $default = 1;
9687
                break;
9688
            case 'active':
9689
                $default = 2;
9690
                break;
9691
            case 'close':
9692
                $default = 3;
9693
                break;
9694
            case 'custom':
9695
                $default = 4;
9696
                break;
9697
        }
9698
9699
        return Display::tabsOnlyLink($tabs, $default);
9700
    }
9701
9702
    /**
9703
     * Check if a session is followed by human resources manager.
9704
     *
9705
     * @param int $sessionId
9706
     * @param int $userId
9707
     *
9708
     * @return bool
9709
     */
9710
    public static function isSessionFollowedByDrh($sessionId, $userId)
9711
    {
9712
        $userId = (int) $userId;
9713
        $sessionId = (int) $sessionId;
9714
9715
        $tblSession = Database::get_main_table(TABLE_MAIN_SESSION);
9716
        $tblSessionRelUser = Database::get_main_table(TABLE_MAIN_SESSION_USER);
9717
9718
        if (api_is_multiple_url_enabled()) {
9719
            $tblSessionRelAccessUrl = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
9720
9721
            $sql = "SELECT s.id FROM $tblSession s
9722
                INNER JOIN $tblSessionRelUser sru ON (sru.session_id = s.id)
9723
                LEFT JOIN $tblSessionRelAccessUrl a ON (s.id = a.session_id)
9724
                WHERE
9725
                    sru.user_id = '$userId' AND
9726
                    sru.session_id = '$sessionId' AND
9727
                    sru.relation_type = '".SESSION_RELATION_TYPE_RRHH."' AND
9728
                    access_url_id = ".api_get_current_access_url_id();
9729
        } else {
9730
            $sql = "SELECT s.id FROM $tblSession s
9731
                INNER JOIN $tblSessionRelUser sru ON sru.session_id = s.id
9732
                WHERE
9733
                    sru.user_id = '$userId' AND
9734
                    sru.session_id = '$sessionId' AND
9735
                    sru.relation_type = '".SESSION_RELATION_TYPE_RRHH."'";
9736
        }
9737
9738
        $result = Database::query($sql);
9739
9740
        return Database::num_rows($result) > 0;
9741
    }
9742
9743
    /**
9744
     * Add a warning message when session is read-only mode.
9745
     */
9746
    public static function addFlashSessionReadOnly()
9747
    {
9748
        if (api_get_session_id() && !api_is_allowed_to_session_edit()) {
9749
            Display::addFlash(
9750
                Display::return_message(get_lang('SessionIsReadOnly'), 'warning')
9751
            );
9752
        }
9753
    }
9754
9755
    public static function insertUsersInCourses(array $studentIds, array $courseIds, int $sessionId)
9756
    {
9757
        $tblSessionUser = Database::get_main_table(TABLE_MAIN_SESSION_USER);
9758
        $tblSession = Database::get_main_table(TABLE_MAIN_SESSION);
9759
9760
        foreach ($courseIds as $courseId) {
9761
            self::insertUsersInCourse($studentIds, $courseId, $sessionId, [], false);
9762
        }
9763
9764
        foreach ($studentIds as $studentId) {
9765
            Database::query(
9766
                "INSERT IGNORE INTO $tblSessionUser (session_id, user_id, registered_at)
9767
                VALUES ($sessionId, $studentId, '".api_get_utc_datetime()."')"
9768
            );
9769
        }
9770
9771
        Database::query(
9772
            "UPDATE $tblSession s
9773
            SET s.nbr_users = (
9774
                SELECT COUNT(1) FROM session_rel_user sru
9775
                WHERE sru.session_id = $sessionId AND sru.relation_type <> ".Session::DRH."
9776
            )
9777
            WHERE s.id = $sessionId"
9778
        );
9779
    }
9780
9781
    public static function insertUsersInCourse(
9782
        array $studentIds,
9783
        int $courseId,
9784
        int $sessionId,
9785
        array $relationInfo = [],
9786
        bool $updateSession = true
9787
    ) {
9788
        $tblSessionCourseUser = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
9789
        $tblSessionCourse = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
9790
        $tblSessionUser = Database::get_main_table(TABLE_MAIN_SESSION_USER);
9791
        $tblSession = Database::get_main_table(TABLE_MAIN_SESSION);
9792
9793
        $relationInfo = array_merge(['visibility' => 0, 'status' => Session::STUDENT], $relationInfo);
9794
        $courseInfo = api_get_course_info_by_id($courseId);
9795
        $courseCode = $courseInfo['code'];
9796
        $subscribeToForums = (int) api_get_course_setting('subscribe_users_to_forum_notifications', $courseInfo);
9797
        if ($subscribeToForums) {
9798
            $forums = [];
9799
            $forumsBaseCourse = [];
9800
            require_once api_get_path(SYS_CODE_PATH).'forum/forumfunction.inc.php';
9801
            $forums = get_forums(0, $courseCode, true, $sessionId);
9802
            if (api_get_configuration_value('subscribe_users_to_forum_notifications_also_in_base_course')) {
9803
                $forumsBaseCourse = get_forums(0, $courseCode, true, 0);
9804
            }
9805
        }
9806
9807
        $sessionCourseUser = [
9808
            'session_id' => $sessionId,
9809
            'c_id' => $courseId,
9810
            'visibility' => $relationInfo['visibility'],
9811
            'status' => $relationInfo['status'],
9812
        ];
9813
        $sessionUser = [
9814
            'session_id' => $sessionId,
9815
            'registered_at' => api_get_utc_datetime(),
9816
        ];
9817
9818
        foreach ($studentIds as $studentId) {
9819
            $sessionCourseUser['user_id'] = $studentId;
9820
9821
            $count = Database::select(
9822
                'COUNT(1) as nbr',
9823
                $tblSessionCourseUser,
9824
                ['where' => ['session_id = ? AND c_id = ? AND user_id = ?' => [$sessionId, $courseId, $studentId]]],
9825
                'first'
9826
            );
9827
9828
            if (empty($count['nbr'])) {
9829
                Database::insert($tblSessionCourseUser, $sessionCourseUser);
9830
9831
                Event::logUserSubscribedInCourseSession($studentId, $courseId, $sessionId);
9832
                if ($subscribeToForums) {
9833
                    $userInfo = api_get_user_info($studentId);
9834
                    if (!empty($forums)) {
9835
                        foreach ($forums as $forum) {
9836
                            $forumId = $forum['iid'];
9837
                            set_notification('forum', $forumId, false, $userInfo, $courseInfo);
9838
                        }
9839
                    }
9840
                    if (!empty($forumsBaseCourse)) {
9841
                        foreach ($forumsBaseCourse as $forum) {
9842
                            $forumId = $forum['iid'];
9843
                            set_notification('forum', $forumId, false, $userInfo, $courseInfo);
9844
                        }
9845
                    }
9846
                }
9847
            }
9848
9849
            if ($updateSession) {
9850
                $sessionUser['user_id'] = $studentId;
9851
9852
                $count = Database::select(
9853
                    'COUNT(1) as nbr',
9854
                    $tblSessionUser,
9855
                    ['where' => ['session_id = ? AND user_id = ?' => [$sessionId, $studentId]]],
9856
                    'first'
9857
                );
9858
9859
                if (empty($count['nbr'])) {
9860
                    Database::insert($tblSessionUser, $sessionUser);
9861
                }
9862
            }
9863
        }
9864
9865
        Database::query(
9866
            "UPDATE $tblSessionCourse src
9867
            SET src.nbr_users = (
9868
                SELECT COUNT(1) FROM $tblSessionCourseUser srcru
9869
                WHERE
9870
                    srcru.session_id = $sessionId AND srcru.c_id = $courseId AND srcru.status <> ".Session::COACH."
9871
            )
9872
            WHERE src.session_id = $sessionId AND src.c_id = $courseId"
9873
        );
9874
9875
        if ($updateSession) {
9876
            Database::query(
9877
                "UPDATE $tblSession s
9878
                SET s.nbr_users = (
9879
                    SELECT COUNT(1) FROM session_rel_user sru
9880
                    WHERE sru.session_id = $sessionId AND sru.relation_type <> ".Session::DRH."
9881
                )
9882
                WHERE s.id = $sessionId"
9883
            );
9884
        }
9885
    }
9886
9887
    public static function getCareersFromSession(int $sessionId): array
9888
    {
9889
        $extraFieldValueSession = new ExtraFieldValue('session');
9890
        $extraFieldValueCareer = new ExtraFieldValue('career');
9891
9892
        $value = $extraFieldValueSession->get_values_by_handler_and_field_variable($sessionId, 'careerid');
9893
        $careers = [];
9894
        if (isset($value['value']) && !empty($value['value'])) {
9895
            $careerList = str_replace(['[', ']'], '', $value['value']);
9896
            $careerList = explode(',', $careerList);
9897
            $careerManager = new Career();
9898
            foreach ($careerList as $career) {
9899
                $careerIdValue = $extraFieldValueCareer->get_item_id_from_field_variable_and_field_value(
9900
                    'external_career_id',
9901
                    $career
9902
                );
9903
                if (isset($careerIdValue['item_id']) && !empty($careerIdValue['item_id'])) {
9904
                    $finalCareerId = $careerIdValue['item_id'];
9905
                    $careerInfo = $careerManager->get($finalCareerId);
9906
                    if (!empty($careerInfo)) {
9907
                        $careers[] = $careerInfo;
9908
                    }
9909
                }
9910
            }
9911
        }
9912
9913
        return $careers;
9914
    }
9915
9916
    public static function getCareerDiagramPerSessionList($sessionList, $userId)
9917
    {
9918
        if (empty($sessionList) || empty($userId)) {
9919
            return '';
9920
        }
9921
9922
        $userId = (int) $userId;
9923
        $careersAdded = [];
9924
        $careerModel = new Career();
9925
        $frames = '';
9926
        foreach ($sessionList as $sessionId) {
9927
            $visibility = api_get_session_visibility($sessionId, null, false, $userId);
9928
            if (SESSION_AVAILABLE === $visibility) {
9929
                $careerList = self::getCareersFromSession($sessionId);
9930
                if (empty($careerList)) {
9931
                    continue;
9932
                }
9933
                foreach ($careerList as $career) {
9934
                    $careerId = $careerIdToShow = $career['id'];
9935
                    if (api_get_configuration_value('use_career_external_id_as_identifier_in_diagrams')) {
9936
                        $careerIdToShow = $careerModel->getCareerIdFromInternalToExternal($careerId);
9937
                    }
9938
9939
                    if (!in_array($careerId, $careersAdded)) {
9940
                        $careersAdded[] = $careerId;
9941
                        $careerUrl = api_get_path(WEB_CODE_PATH).'user/career_diagram.php?iframe=1&career_id='.$careerIdToShow.'&user_id='.$userId;
9942
                        $frames .= '
9943
                            <iframe
9944
                                onload="resizeIframe(this)"
9945
                                style="width:100%;"
9946
                                border="0"
9947
                                frameborder="0"
9948
                                scrolling="no"
9949
                                src="'.$careerUrl.'"
9950
                            ></iframe>';
9951
                    }
9952
                }
9953
            }
9954
        }
9955
9956
        $content = '';
9957
        if (!empty($frames)) {
9958
            $content = Display::page_subheader(get_lang('OngoingTraining'));
9959
            $content .= '
9960
               <script>
9961
                resizeIframe = function(iFrame) {
9962
                    iFrame.height = iFrame.contentWindow.document.body.scrollHeight + 20;
9963
                }
9964
                </script>
9965
            ';
9966
            $content .= $frames;
9967
            $content .= Career::renderDiagramFooter();
9968
        }
9969
9970
        return $content;
9971
    }
9972
9973
    public static function importAgendaFromSessionModel(int $modelSessionId, int $sessionId, int $courseId)
9974
    {
9975
        $em = Database::getManager();
9976
        $repo = $em->getRepository('ChamiloCourseBundle:CCalendarEvent');
9977
9978
        $courseInfo = api_get_course_info_by_id($courseId);
9979
        $session = api_get_session_entity($sessionId);
9980
        $modelSession = api_get_session_entity($modelSessionId);
9981
9982
        $sessionDateDiff = $modelSession->getAccessStartDate()->diff($session->getAccessStartDate());
9983
9984
        $events = $repo->findBy(
9985
            ['cId' => $courseId, 'sessionId' => $modelSessionId]
9986
        );
9987
9988
        $agenda = new Agenda('course');
9989
        $agenda->set_course($courseInfo);
9990
        $agenda->setSessionId($sessionId);
9991
9992
        foreach ($events as $event) {
9993
            $startDate = $event->getStartDate()->add($sessionDateDiff);
9994
            $endDate = $event->getEndDate()->add($sessionDateDiff);
9995
9996
            $agenda->addEvent(
9997
                $startDate->format('Y-m-d H:i:s'),
9998
                $endDate->format('Y-m-d H:i:s'),
9999
                'false',
10000
                $event->getTitle(),
10001
                $event->getContent(),
10002
                ['GROUP:0'],
10003
                false,
10004
                null,
10005
                [],
10006
                [],
10007
                $event->getComment(),
10008
                $event->getColor()
10009
            );
10010
        }
10011
    }
10012
10013
    /**
10014
     * Export an Excel report for a specific course within a session.
10015
     *
10016
     * The report includes session details and a list of certified users
10017
     * with their extra field values.
10018
     *
10019
     * @param int    $sessionId  ID of the session
10020
     * @param string $courseCode Course code of the course in the session
10021
     */
10022
    public static function exportCourseSessionReport(int $sessionId, string $courseCode): void
10023
    {
10024
        $courseInfo = api_get_course_info($courseCode);
10025
        $sessionInfo = api_get_session_info($sessionId);
10026
10027
        if (empty($courseInfo) || empty($sessionInfo)) {
10028
            exit('Invalid course or session.');
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
10029
        }
10030
10031
        $config = api_get_configuration_value('session_course_excel_export');
10032
        if (empty($config)) {
10033
            exit('Configuration not set.');
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
10034
        }
10035
10036
        $sessionFields = $config['session_fields'] ?? [];
10037
        $userFieldsBefore = $config['user_fields_before'] ?? [];
10038
        $userFieldsAfter = $config['user_fields_after'] ?? [];
10039
10040
        // 1. SESSION HEADER
10041
        $header1 = [''];
10042
        $header1[] = $config['session_start_date_header'] ?? get_lang('StartDate');
10043
        $header1[] = $config['session_end_date_header'] ?? get_lang('EndDate');
10044
10045
        foreach ($sessionFields as $entry) {
10046
            $header1[] = $entry['header'] ?? '';
10047
        }
10048
10049
        // 2. SESSION DATA
10050
        $row2 = $config['course_field_value'] ? [$config['course_field_value']] : [$courseInfo['title']];
10051
        $row2[] = (new DateTime($sessionInfo['access_start_date']))->format('d/m/Y');
10052
        $row2[] = (new DateTime($sessionInfo['access_end_date']))->format('d/m/T');
10053
10054
        $extraValuesObj = new ExtraFieldValue('session');
10055
        $sessionExtra = $extraValuesObj->getAllValuesByItem($sessionId);
10056
        $sessionExtraMap = array_column($sessionExtra, 'value', 'variable');
10057
10058
        foreach ($sessionFields as $entry) {
10059
            if (!empty($entry['field'])) {
10060
                $value = $sessionExtraMap[$entry['field']] ?? '';
10061
                if (!empty($entry['numberOfLetter']) && $entry['numberOfLetter'] > 0) {
10062
                    $value = mb_substr($value, 0, $entry['numberOfLetter']);
10063
                }
10064
            } else {
10065
                $value = '';
10066
            }
10067
            $row2[] = $value;
10068
        }
10069
10070
        // 3. USER HEADER
10071
        $header3 = [''];
10072
10073
        foreach ($userFieldsBefore as $entry) {
10074
            $header3[] = $entry['header'] ?? '';
10075
        }
10076
10077
        $header3[] = $config['user_firstname_header'] ?? get_lang('FirstName');
10078
        $header3[] = $config['user_lastname_header'] ?? get_lang('LastName');
10079
10080
        foreach ($userFieldsAfter as $entry) {
10081
            $header3[] = $entry['header'] ?? '';
10082
        }
10083
10084
        // 4. USERS WITH CERTIFICATE
10085
        $dataRows = [];
10086
10087
        $tblCat = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CATEGORY);
10088
        $sql = "
10089
            SELECT id FROM $tblCat
10090
            WHERE course_code = '".Database::escape_string($courseCode)."'
10091
            AND session_id = ".intval($sessionId)."
10092
            AND generate_certificates = 1
10093
            LIMIT 1
10094
        ";
10095
        $res = Database::query($sql);
10096
        $row = Database::fetch_array($res);
10097
        $catId = $row ? (int) $row['id'] : 0;
10098
10099
        if ($catId > 0) {
10100
            $tableCertificate = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CERTIFICATE);
10101
            $sql = "SELECT DISTINCT user_id FROM $tableCertificate WHERE cat_id = $catId";
10102
            $res = Database::query($sql);
10103
10104
            $rowIndex = 0;
10105
            while ($cert = Database::fetch_array($res)) {
10106
                $userId = $cert['user_id'];
10107
                $userInfo = api_get_user_info($userId);
10108
10109
                $row = [];
10110
                $row[] = get_lang('Learners');
10111
10112
                $userExtraObj = new ExtraFieldValue('user');
10113
                $userExtra = $userExtraObj->getAllValuesByItem($userId);
10114
                $userExtraMap = array_column($userExtra, 'value', 'variable');
10115
10116
                foreach ($userFieldsBefore as $entry) {
10117
                    if (!empty($entry['field'])) {
10118
                        $value = $userExtraMap[$entry['field']] ?? '';
10119
                    } else {
10120
                        $value = '';
10121
                    }
10122
                    $row[] = $value;
10123
                }
10124
10125
                $row[] = $userInfo['firstname'];
10126
                $row[] = $userInfo['lastname'];
10127
10128
                foreach ($userFieldsAfter as $entry) {
10129
                    if (!empty($entry['field'])) {
10130
                        $value = $userExtraMap[$entry['field']] ?? '';
10131
                    } else {
10132
                        $value = '';
10133
                    }
10134
                    $row[] = $value;
10135
                }
10136
10137
                $dataRows[] = $row;
10138
                $rowIndex++;
10139
            }
10140
        }
10141
10142
        // 5. EXPORT FINAL
10143
        $rows = [];
10144
        $rows[] = $header1;
10145
        $rows[] = $row2;
10146
        $rows[] = $header3;
10147
        $rows = array_merge($rows, $dataRows);
10148
10149
        $filename = 'session_'.$sessionId.'_course_'.$courseCode;
10150
        Export::arrayToXls($rows, $filename);
10151
    }
10152
10153
    /**
10154
     * @param int $id
10155
     *
10156
     * @return bool
10157
     */
10158
    private static function allowed($id)
10159
    {
10160
        $sessionInfo = self::fetch($id);
10161
10162
        if (empty($sessionInfo)) {
10163
            return false;
10164
        }
10165
10166
        if (api_is_platform_admin()) {
10167
            return true;
10168
        }
10169
10170
        $userId = api_get_user_id();
10171
10172
        if (api_is_session_admin() &&
10173
            api_get_setting('allow_session_admins_to_manage_all_sessions') != 'true'
10174
        ) {
10175
            if ($sessionInfo['session_admin_id'] != $userId) {
10176
                return false;
10177
            }
10178
        }
10179
10180
        if (api_is_teacher() &&
10181
            api_get_setting('allow_teachers_to_create_sessions') == 'true'
10182
        ) {
10183
            if ($sessionInfo['id_coach'] != $userId) {
10184
                return false;
10185
            }
10186
        }
10187
10188
        return true;
10189
    }
10190
10191
    /**
10192
     * Add classes (by their names) to a session.
10193
     *
10194
     * @param int   $sessionId
10195
     * @param array $classesNames
10196
     * @param bool  $deleteClassSessions Optional. Empty the session list for the usergroup (class)
10197
     */
10198
    private static function addClassesByName($sessionId, $classesNames, $deleteClassSessions = true, ?string &$error_message = '')
10199
    {
10200
        if (!$classesNames) {
10201
            return;
10202
        }
10203
10204
        $usergroup = new UserGroup();
10205
10206
        foreach ($classesNames as $className) {
10207
            if (empty($className)) {
10208
                continue;
10209
            }
10210
10211
            $classIdByName = $usergroup->getIdByName($className);
10212
10213
            if (empty($classIdByName)) {
10214
                $error_message .= sprintf(get_lang('ClassNameXDoesntExists'), $className).'<br>';
10215
                continue;
10216
            }
10217
10218
            $usergroup->subscribe_sessions_to_usergroup(
10219
                $usergroup->getIdByName($className),
10220
                [$sessionId],
10221
                $deleteClassSessions
10222
            );
10223
        }
10224
    }
10225
10226
    /**
10227
     * @param array $listA
10228
     * @param array $listB
10229
     *
10230
     * @return int
10231
     */
10232
    private static function compareCatSessionInfo($listA, $listB)
10233
    {
10234
        if ($listA['sessionName'] == $listB['sessionName']) {
10235
            return 0;
10236
        } elseif ($listA['sessionName'] > $listB['sessionName']) {
10237
            return 1;
10238
        } else {
10239
            return -1;
10240
        }
10241
    }
10242
10243
    /**
10244
     * @param array $listA
10245
     * @param array $listB
10246
     *
10247
     * @return int
10248
     */
10249
    private static function compareBySessionName($listA, $listB)
10250
    {
10251
        if ('' == $listB['catSessionName']) {
10252
            return -1;
10253
        } elseif ('' == $listA['catSessionName']) {
10254
            return 1;
10255
        } elseif ($listA['catSessionName'] == $listB['catSessionName']) {
10256
            return 0;
10257
        } elseif ($listA['catSessionName'] > $listB['catSessionName']) {
10258
            return 1;
10259
        } else {
10260
            return -1;
10261
        }
10262
    }
10263
10264
    /**
10265
     * @param array $listA
10266
     * @param array $listB
10267
     *
10268
     * @return int
10269
     */
10270
    private static function compareByUserCourseCat($listA, $listB)
10271
    {
10272
        if ($listA['courseInUserCategoryTitle'] == $listB['courseInUserCategoryTitle']) {
10273
            return 0;
10274
        } elseif ($listA['courseInUserCategoryTitle'] > $listB['courseInUserCategoryTitle']) {
10275
            return 1;
10276
        } else {
10277
            return -1;
10278
        }
10279
    }
10280
10281
    /**
10282
     * @param array $listA
10283
     * @param array $listB
10284
     *
10285
     * @return int
10286
     */
10287
    private static function compareByCourse($listA, $listB)
10288
    {
10289
        if ($listA['title'] == $listB['title']) {
10290
            return 0;
10291
        } elseif ($listA['title'] > $listB['title']) {
10292
            return 1;
10293
        } else {
10294
            return -1;
10295
        }
10296
    }
10297
}
10298