Passed
Push — master ( 5672b3...75cb6d )
by Julito
11:52
created

SessionManager::moveUp()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

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