Completed
Push — master ( 441dc8...d4012c )
by Julito
09:56
created

SessionManager::getSessionCourseForUser()   A

Complexity

Conditions 5
Paths 3

Size

Total Lines 23
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

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