Passed
Push — 1.11.x ( 09c424...c315b7 )
by Julito
10:50
created

SessionManager::get_all_session_category()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 15
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

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