Passed
Push — master ( e7a97c...b21763 )
by Julito
12:57
created

getAllCoursesFromAllSessionFromDrh()   A

Complexity

Conditions 4
Paths 2

Size

Total Lines 14
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 8
nc 2
nop 1
dl 0
loc 14
rs 10
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. If $session can have other possible types, add them to main/inc/lib/sessionmanager.lib.php:60
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 int    $sessionCategoryId            ID of the session category in which this session is registered
135
     * @param mixed  $coachId                      If int, this is the session coach id,
136
     *                                             if string, the coach ID will be looked for from the user table
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
     *
147
     * @todo use an array to replace all this parameters or use the model.lib.php ...
148
     *
149
     * @return mixed Session ID on success, error message otherwise
150
     * */
151
    public static function create_session(
152
        $name,
153
        $startDate,
154
        $endDate,
155
        $displayStartDate,
156
        $displayEndDate,
157
        $coachStartDate,
158
        $coachEndDate,
159
        $coachId,
160
        $sessionCategoryId,
161
        $visibility = 1,
162
        $fixSessionNameIfExists = false,
163
        $duration = null,
164
        $description = null,
165
        $showDescription = 0,
166
        $extraFields = [],
167
        $sessionAdminId = 0,
168
        $sendSubscriptionNotification = false
169
    ) {
170
        global $_configuration;
171
172
        // Check portal limits
173
        $access_url_id = 1;
174
175
        if (api_get_multiple_access_url()) {
176
            $access_url_id = api_get_current_access_url_id();
177
        }
178
179
        if (is_array($_configuration[$access_url_id]) &&
180
            isset($_configuration[$access_url_id]['hosting_limit_sessions']) &&
181
            $_configuration[$access_url_id]['hosting_limit_sessions'] > 0
182
        ) {
183
            $num = self::count_sessions();
184
            if ($num >= $_configuration[$access_url_id]['hosting_limit_sessions']) {
185
                api_warn_hosting_contact('hosting_limit_sessions');
186
187
                return get_lang('PortalSessionsLimitReached');
188
            }
189
        }
190
191
        $name = Database::escape_string(trim($name));
192
        $sessionCategoryId = intval($sessionCategoryId);
193
        $visibility = intval($visibility);
194
        $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
195
196
        $startDate = Database::escape_string($startDate);
197
        $endDate = Database::escape_string($endDate);
198
199
        if (empty($name)) {
200
            $msg = get_lang('SessionNameIsRequired');
201
202
            return $msg;
203
        } elseif (!empty($startDate) && !api_is_valid_date($startDate, 'Y-m-d H:i') &&
204
            !api_is_valid_date($startDate, 'Y-m-d H:i:s')
205
        ) {
206
            $msg = get_lang('InvalidStartDate');
207
208
            return $msg;
209
        } elseif (!empty($endDate) && !api_is_valid_date($endDate, 'Y-m-d H:i') &&
210
            !api_is_valid_date($endDate, 'Y-m-d H:i:s')
211
        ) {
212
            $msg = get_lang('InvalidEndDate');
213
214
            return $msg;
215
        } elseif (!empty($startDate) && !empty($endDate) && $startDate >= $endDate) {
216
            $msg = get_lang('StartDateShouldBeBeforeEndDate');
217
218
            return $msg;
219
        } else {
220
            $ready_to_create = false;
221
            if ($fixSessionNameIfExists) {
222
                $name = self::generateNextSessionName($name);
223
                if ($name) {
224
                    $ready_to_create = true;
225
                } else {
226
                    $msg = get_lang('SessionNameAlreadyExists');
227
228
                    return $msg;
229
                }
230
            } else {
231
                $rs = Database::query("SELECT 1 FROM $tbl_session WHERE name='".$name."'");
232
                if (Database::num_rows($rs)) {
233
                    $msg = get_lang('SessionNameAlreadyExists');
234
235
                    return $msg;
236
                }
237
                $ready_to_create = true;
238
            }
239
240
            if ($ready_to_create) {
241
                $sessionAdminId = !empty($sessionAdminId) ? $sessionAdminId : api_get_user_id();
242
                $values = [
243
                    'name' => $name,
244
                    'id_coach' => $coachId,
245
                    'session_admin_id' => $sessionAdminId,
246
                    'visibility' => $visibility,
247
                    'description' => $description,
248
                    'show_description' => intval($showDescription),
249
                    'send_subscription_notification' => (int) $sendSubscriptionNotification,
250
                ];
251
252
                if (!empty($startDate)) {
253
                    $values['access_start_date'] = api_get_utc_datetime($startDate);
254
                }
255
256
                if (!empty($endDate)) {
257
                    $values['access_end_date'] = api_get_utc_datetime($endDate);
258
                }
259
260
                if (!empty($displayStartDate)) {
261
                    $values['display_start_date'] = api_get_utc_datetime($displayStartDate);
262
                }
263
264
                if (!empty($displayEndDate)) {
265
                    $values['display_end_date'] = api_get_utc_datetime($displayEndDate);
266
                }
267
268
                if (!empty($coachStartDate)) {
269
                    $values['coach_access_start_date'] = api_get_utc_datetime($coachStartDate);
270
                }
271
                if (!empty($coachEndDate)) {
272
                    $values['coach_access_end_date'] = api_get_utc_datetime($coachEndDate);
273
                }
274
275
                if (!empty($sessionCategoryId)) {
276
                    $values['session_category_id'] = $sessionCategoryId;
277
                }
278
279
                $values['position'] = 0;
280
                $session_id = Database::insert($tbl_session, $values);
281
                $duration = intval($duration);
282
283
                if (!empty($duration)) {
284
                    $sql = "UPDATE $tbl_session SET
285
                        access_start_date = NULL,
286
                        access_end_date = NULL,
287
                        display_start_date = NULL,
288
                        display_end_date = NULL,
289
                        coach_access_start_date = NULL,
290
                        coach_access_end_date = NULL,
291
                        duration = $duration
292
                    WHERE id = $session_id";
293
                    Database::query($sql);
294
                } else {
295
                    $sql = "UPDATE $tbl_session
296
                        SET duration = 0
297
                        WHERE id = $session_id";
298
                    Database::query($sql);
299
                }
300
301
                if (!empty($session_id)) {
302
                    $extraFields['item_id'] = $session_id;
303
                    $sessionFieldValue = new ExtraFieldValue('session');
304
                    $sessionFieldValue->saveFieldValues($extraFields);
305
306
                    /*
307
                      Sends a message to the user_id = 1
308
309
                      $user_info = api_get_user_info(1);
310
                      $complete_name = $user_info['firstname'].' '.$user_info['lastname'];
311
                      $subject = api_get_setting('siteName').' - '.get_lang('ANewSessionWasCreated');
312
                      $message = get_lang('ANewSessionWasCreated')." <br /> ".get_lang('NameOfTheSession').' : '.$name;
313
                      api_mail_html($complete_name, $user_info['email'], $subject, $message);
314
                     *
315
                     */
316
                    //Adding to the correct URL
317
                    $access_url_id = api_get_current_access_url_id();
318
                    UrlManager::add_session_to_url($session_id, $access_url_id);
319
320
                    // add event to system log
321
                    $user_id = api_get_user_id();
322
                    Event::addEvent(
323
                        LOG_SESSION_CREATE,
324
                        LOG_SESSION_ID,
325
                        $session_id,
326
                        api_get_utc_datetime(),
327
                        $user_id
328
                    );
329
                }
330
331
                return $session_id;
332
            }
333
        }
334
    }
335
336
    /**
337
     * @param string $name
338
     *
339
     * @return bool
340
     */
341
    public static function sessionNameExists($name)
342
    {
343
        $name = Database::escape_string($name);
344
        $sql = "SELECT COUNT(*) as count FROM ".Database::get_main_table(TABLE_MAIN_SESSION)."
345
                WHERE name = '$name'";
346
        $result = Database::fetch_array(Database::query($sql));
347
348
        return $result['count'] > 0;
349
    }
350
351
    /**
352
     * @param string $where_condition
353
     *
354
     * @return mixed
355
     */
356
    public static function get_count_admin($where_condition = '')
357
    {
358
        $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
359
        $tbl_session_category = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
360
        $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
361
        $table_access_url_rel_session = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
362
        $tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
363
364
        $where = 'WHERE 1=1 ';
365
        $user_id = api_get_user_id();
366
        $extraJoin = '';
367
368
        if (api_is_session_admin() &&
369
            api_get_setting('allow_session_admins_to_manage_all_sessions') == 'false'
370
        ) {
371
            $where .= " AND (
372
                            s.session_admin_id = $user_id  OR
373
                            sru.user_id = '$user_id' AND
374
                            sru.relation_type = '".SESSION_RELATION_TYPE_RRHH."'
375
                            )
376
                      ";
377
378
            $extraJoin = " INNER JOIN $tbl_session_rel_user sru
379
                           ON sru.session_id = s.id ";
380
        }
381
382
        $today = api_get_utc_datetime();
383
        $today = api_strtotime($today, 'UTC');
384
        $today = date('Y-m-d', $today);
385
386
        if (!empty($where_condition)) {
387
            $where_condition = str_replace("(  session_active = ':'  )", '1=1', $where_condition);
388
389
            $where_condition = str_replace('category_name', 'sc.name', $where_condition);
390
            $where_condition = str_replace(
391
                ["AND session_active = '1'  )", " AND (  session_active = '1'  )"],
392
                [') GROUP BY s.name HAVING session_active = 1 ', " GROUP BY s.name HAVING session_active = 1 "],
393
                $where_condition
394
            );
395
            $where_condition = str_replace(
396
                ["AND session_active = '0'  )", " AND (  session_active = '0'  )"],
397
                [') GROUP BY s.name HAVING session_active = 0 ', " GROUP BY s.name HAVING session_active = '0' "],
398
                $where_condition
399
            );
400
        } else {
401
            $where_condition = " AND 1 = 1";
402
        }
403
404
        $courseCondition = null;
405
        if (strpos($where_condition, 'c.id')) {
406
            $table = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
407
            $tableCourse = Database::get_main_table(TABLE_MAIN_COURSE);
408
            $courseCondition = " INNER JOIN $table course_rel_session
409
                                 ON (s.id = course_rel_session.session_id)
410
                                 INNER JOIN $tableCourse c
411
                                 ON (course_rel_session.c_id = c.id)
412
                                ";
413
        }
414
415
        $sql = "SELECT COUNT(id) as total_rows FROM (
416
                SELECT DISTINCT
417
                 IF (
418
					(s.access_start_date <= '$today' AND '$today' <= s.access_end_date) OR
419
                    (s.access_start_date IS NULL AND s.access_end_date  = IS NULL ) OR
420
					(s.access_start_date <= '$today' AND s.access_end_date IS NULL) OR
421
					('$today' <= s.access_end_date AND s.access_start_date IS NULL)
422
				, 1, 0) as session_active,
423
                s.id
424
                FROM $tbl_session s
425
                LEFT JOIN $tbl_session_category sc
426
                ON s.session_category_id = sc.id
427
                INNER JOIN $tbl_user u
428
                ON s.id_coach = u.user_id
429
                $courseCondition
430
                $extraJoin
431
                $where $where_condition ) as session_table";
432
433
        if (api_is_multiple_url_enabled()) {
434
            $access_url_id = api_get_current_access_url_id();
435
            if ($access_url_id != -1) {
436
                $where .= " AND ar.access_url_id = $access_url_id ";
437
438
                $sql = "SELECT count(id) as total_rows FROM (
439
                SELECT DISTINCT
440
                  IF (
441
					(s.access_start_date <= '$today' AND '$today' <= s.access_end_date) OR
442
                    (s.access_start_date IS NULL AND s.access_end_date IS NULL) OR
443
					(s.access_start_date <= '$today' AND s.access_end_date IS NULL) OR
444
					('$today' <= s.access_end_date AND s.access_start_date IS NULL)
445
				, 1, 0)
446
				as session_active,
447
				s.id
448
                FROM $tbl_session s
449
                    LEFT JOIN  $tbl_session_category sc
450
                    ON s.session_category_id = sc.id
451
                    INNER JOIN $tbl_user u ON s.id_coach = u.user_id
452
                    INNER JOIN $table_access_url_rel_session ar
453
                    ON ar.session_id = s.id
454
                    $courseCondition
455
                    $extraJoin
456
                $where $where_condition) as session_table";
457
            }
458
        }
459
460
        $result_rows = Database::query($sql);
461
        $row = Database::fetch_array($result_rows);
462
        $num = $row['total_rows'];
463
464
        return $num;
465
    }
466
467
    /**
468
     * Gets the admin session list callback of the session/session_list.php page.
469
     *
470
     * @param array $options           order and limit keys
471
     * @param bool  $get_count         Whether to get all the results or only the count
472
     * @param array $columns
473
     * @param array $extraFieldsToLoad
474
     *
475
     * @return mixed Integer for number of rows, or array of results
476
     * @assert ([],true) !== false
477
     */
478
    public static function get_sessions_admin(
479
        $options = [],
480
        $get_count = false,
481
        $columns = [],
482
        $extraFieldsToLoad = []
483
    ) {
484
        $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
485
        $sessionCategoryTable = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
486
487
        $where = 'WHERE 1 = 1 ';
488
        $user_id = api_get_user_id();
489
490
        if (!api_is_platform_admin()) {
491
            if (api_is_session_admin() &&
492
                api_get_setting('allow_session_admins_to_manage_all_sessions') == 'false'
493
            ) {
494
                $where .= " AND s.session_admin_id = $user_id ";
495
            }
496
        }
497
498
        if (!api_is_platform_admin() &&
499
            api_is_teacher() &&
500
            api_get_setting('allow_teachers_to_create_sessions') == 'true'
501
        ) {
502
            $where .= " AND s.id_coach = $user_id ";
503
        }
504
        $extra_field = new ExtraFieldModel('session');
505
        $conditions = $extra_field->parseConditions($options);
506
        $inject_joins = $conditions['inject_joins'];
507
        $where .= $conditions['where'];
508
        $inject_where = $conditions['inject_where'];
509
        $inject_extra_fields = $conditions['inject_extra_fields'];
510
        $order = $conditions['order'];
511
        $limit = $conditions['limit'];
512
513
        $isMakingOrder = false;
514
        $showCountUsers = false;
515
516
        if ($get_count == true) {
517
            $select = " SELECT count(DISTINCT s.id) as total_rows";
518
        } else {
519
            if (!empty($columns['column_model'])) {
520
                foreach ($columns['column_model'] as $column) {
521
                    if ($column['name'] == 'users') {
522
                        $showCountUsers = true;
523
                    }
524
                }
525
            }
526
527
            $select =
528
                "SELECT DISTINCT 
529
                     s.name,
530
                     s.display_start_date, 
531
                     s.display_end_date, 
532
                     access_start_date, 
533
                     access_end_date, 
534
                     s.visibility, 
535
                     s.session_category_id, 
536
                     $inject_extra_fields 
537
                     s.id 
538
             ";
539
540
            if ($showCountUsers) {
541
                $select .= ', count(su.user_id) users';
542
            }
543
            if (isset($options['order'])) {
544
                $isMakingOrder = strpos($options['order'], 'category_name') === 0;
545
            }
546
        }
547
548
        $isFilteringSessionCategory = strpos($where, 'category_name') !== false;
549
        $isFilteringSessionCategoryWithName = strpos($where, 'sc.name') !== false;
550
551
        if ($isMakingOrder || $isFilteringSessionCategory || $isFilteringSessionCategoryWithName) {
552
            $inject_joins .= " LEFT JOIN $sessionCategoryTable sc ON s.session_category_id = sc.id ";
553
554
            if ($isFilteringSessionCategory) {
555
                $where = str_replace('category_name', 'sc.name', $where);
556
            }
557
558
            if ($isMakingOrder) {
559
                $order = str_replace('category_name', 'sc.name', $order);
560
            }
561
        }
562
563
        if ($showCountUsers) {
564
            $table = Database::get_main_table(TABLE_MAIN_SESSION_USER);
565
            $inject_joins .= " LEFT JOIN $table su ON (su.session_id = s.id)";
566
        }
567
568
        $query = "$select FROM $tbl_session s $inject_joins $where $inject_where";
569
570
        if (api_is_multiple_url_enabled()) {
571
            $table_access_url_rel_session = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
572
            $access_url_id = api_get_current_access_url_id();
573
            if ($access_url_id != -1) {
574
                $where .= " AND ar.access_url_id = $access_url_id ";
575
                $query = "$select
576
                        FROM $tbl_session s $inject_joins
577
                        INNER JOIN $table_access_url_rel_session ar
578
                        ON (ar.session_id = s.id) $where";
579
            }
580
        }
581
582
        if ($showCountUsers) {
583
            $query .= ' GROUP by s.id';
584
        }
585
        $allowOrder = api_get_configuration_value('session_list_order');
586
        if ($allowOrder) {
587
            $order = ' ORDER BY position ASC';
588
        }
589
590
        $query .= $order;
591
        $query .= $limit;
592
        $result = Database::query($query);
593
594
        $categories = self::get_all_session_category();
595
        $orderedCategories = [];
596
        if (!empty($categories)) {
597
            foreach ($categories as $category) {
598
                $orderedCategories[$category['id']] = $category['name'];
599
            }
600
        }
601
        $formatted_sessions = [];
602
        if (Database::num_rows($result)) {
603
            $sessions = Database::store_result($result, 'ASSOC');
604
            if ($get_count) {
605
                return $sessions[0]['total_rows'];
606
            }
607
608
            $activeIcon = Display::return_icon(
609
                'accept.png',
610
                get_lang('Active'),
611
                [],
612
                ICON_SIZE_SMALL
613
            );
614
            $inactiveIcon = Display::return_icon(
615
                'error.png',
616
                get_lang('Inactive'),
617
                [],
618
                ICON_SIZE_SMALL
619
            );
620
621
            foreach ($sessions as $session) {
622
                $session_id = $session['id'];
623
                if ($showCountUsers) {
624
                    $session['users'] = SessionManager::get_users_by_session(
625
                        $session['id'],
626
                        null,
627
                        true
628
                    );
629
                }
630
                $url = api_get_path(WEB_CODE_PATH)."session/resume_session.php?id_session=".$session['id'];
631
                if (api_is_drh()) {
632
                    $url = api_get_path(WEB_CODE_PATH)."session/about.php?session_id=".$session['id'];
633
                }
634
                if (api_is_platform_admin()) {
635
                    $url = api_get_path(WEB_CODE_PATH)."session/resume_session.php?id_session=".$session['id'];
636
                }
637
638
                if ($extraFieldsToLoad) {
639
                    $url = api_get_path(WEB_CODE_PATH)."session/about.php?session_id=".$session['id'];
640
                }
641
                $session['name'] = Display::url(
642
                    $session['name'],
643
                    $url
644
                );
645
646
                if (!empty($extraFieldsToLoad)) {
647
                    foreach ($extraFieldsToLoad as $field) {
648
                        $extraFieldValue = new ExtraFieldValue('session');
649
                        $fieldData = $extraFieldValue->getAllValuesByItemAndField(
650
                            $session['id'],
651
                            $field['id']
652
                        );
653
                        $fieldDataArray = [];
654
                        $fieldDataToString = '';
655
                        if (!empty($fieldData)) {
656
                            foreach ($fieldData as $data) {
657
                                $fieldDataArray[] = $data['value'];
658
                            }
659
                            $fieldDataToString = implode(', ', $fieldDataArray);
660
                        }
661
                        $session[$field['variable']] = $fieldDataToString;
662
                    }
663
                }
664
665
                if (isset($session['session_active']) && $session['session_active'] == 1) {
666
                    $session['session_active'] = $activeIcon;
667
                } else {
668
                    $session['session_active'] = $inactiveIcon;
669
                }
670
671
                $session = self::convert_dates_to_local($session, true);
672
673
                switch ($session['visibility']) {
674
                    case SESSION_VISIBLE_READ_ONLY: //1
675
                        $session['visibility'] = get_lang('ReadOnly');
676
                        break;
677
                    case SESSION_VISIBLE:           //2
678
                    case SESSION_AVAILABLE:         //4
679
                        $session['visibility'] = get_lang('Visible');
680
                        break;
681
                    case SESSION_INVISIBLE:         //3
682
                        $session['visibility'] = api_ucfirst(get_lang('Invisible'));
683
                        break;
684
                }
685
686
                // Cleaning double selects.
687
                foreach ($session as $key => &$value) {
688
                    if (isset($options_by_double[$key]) || isset($options_by_double[$key.'_second'])) {
689
                        $options = explode('::', $value);
690
                    }
691
                    $original_key = $key;
692
693
                    if (strpos($key, '_second') === false) {
0 ignored issues
show
Unused Code introduced by
This if statement is empty and can be removed.

This check looks for the bodies of if statements that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

These if bodies can be removed. If you have an empty if but statements in the else branch, consider inverting the condition.

if (rand(1, 6) > 3) {
//print "Check failed";
} else {
    print "Check succeeded";
}

could be turned into

if (rand(1, 6) <= 3) {
    print "Check succeeded";
}

This is much more concise to read.

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

This check looks for the bodies of if statements that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

These if bodies can be removed. If you have an empty if but statements in the else branch, consider inverting the condition.

if (rand(1, 6) > 3) {
//print "Check failed";
} else {
    print "Check succeeded";
}

could be turned into

if (rand(1, 6) <= 3) {
    print "Check succeeded";
}

This is much more concise to read.

Loading history...
8602
                    } else {
8603
                        $key = str_replace('_second', '', $key);
8604
                    }
8605
8606
                    if (isset($options_by_double[$key])) {
8607
                        if (isset($options[0])) {
8608
                            if (isset($options_by_double[$key][$options[0]])) {
8609
                                if (strpos($original_key, '_second') === false) {
8610
                                    $value = $options_by_double[$key][$options[0]]['option_display_text'];
8611
                                } else {
8612
                                    $value = $options_by_double[$key][$options[1]]['option_display_text'];
8613
                                }
8614
                            }
8615
                        }
8616
                    }
8617
                }
8618
8619
                // Magic filter
8620
                if (isset($formatted_sessions[$session_id])) {
8621
                    $formatted_sessions[$session_id] = self::compareArraysToMerge(
8622
                        $formatted_sessions[$session_id],
8623
                        $session
8624
                    );
8625
                } else {
8626
                    $formatted_sessions[$session_id] = $session;
8627
                }
8628
            }
8629
        }
8630
8631
        return $formatted_sessions;
8632
    }
8633
8634
    /**
8635
     * Compare two arrays.
8636
     *
8637
     * @param array $array1
8638
     * @param array $array2
8639
     *
8640
     * @return array
8641
     */
8642
    public static function compareArraysToMerge($array1, $array2)
8643
    {
8644
        if (empty($array2)) {
8645
            return $array1;
8646
        }
8647
        foreach ($array1 as $key => $item) {
8648
            if (!isset($array1[$key])) {
8649
                //My string is empty try the other one
8650
                if (isset($array2[$key]) && !empty($array2[$key])) {
8651
                    $array1[$key] = $array2[$key];
8652
                }
8653
            }
8654
        }
8655
8656
        return $array1;
8657
    }
8658
8659
    /**
8660
     * Get link to the admin page for this session.
8661
     *
8662
     * @param int $id Session ID
8663
     *
8664
     * @return mixed URL to the admin page to manage the session, or false on error
8665
     */
8666
    public static function getAdminPath($id)
8667
    {
8668
        $id = (int) $id;
8669
        $session = self::fetch($id);
8670
        if (empty($session)) {
8671
            return false;
8672
        }
8673
8674
        return api_get_path(WEB_CODE_PATH).'session/resume_session.php?id_session='.$id;
8675
    }
8676
8677
    /**
8678
     * Get link to the user page for this session.
8679
     * If a course is provided, build the link to the course.
8680
     *
8681
     * @param int $id       Session ID
8682
     * @param int $courseId Course ID (optional) in case the link has to send straight to the course
8683
     *
8684
     * @return mixed URL to the page to use the session, or false on error
8685
     */
8686
    public static function getPath($id, $courseId = 0)
8687
    {
8688
        $id = (int) $id;
8689
        $session = self::fetch($id);
8690
        if (empty($session)) {
8691
            return false;
8692
        }
8693
        if (empty($courseId)) {
8694
            return api_get_path(WEB_CODE_PATH).'session/index.php?session_id='.$id;
8695
        } else {
8696
            $courseInfo = api_get_course_info_by_id($courseId);
8697
            if ($courseInfo) {
8698
                return $courseInfo['course_public_url'].'?id_session='.$id;
8699
            }
8700
        }
8701
8702
        return false;
8703
    }
8704
8705
    /**
8706
     * Return an associative array 'id_course' => [id_session1, id_session2...]
8707
     * where course id_course is in sessions id_session1, id_session2
8708
     * for course where user is coach
8709
     * i.e. coach for the course or
8710
     * main coach for a session the course is in
8711
     * for a session category (or woth no session category if empty).
8712
     *
8713
     * @param int $userId
8714
     *
8715
     * @return array
8716
     */
8717
    public static function getSessionCourseForUser($userId)
8718
    {
8719
        // list of COURSES where user is COURSE session coach
8720
        $listCourseCourseCoachSession = self::getCoursesForCourseSessionCoach($userId);
8721
        // list of courses where user is MAIN session coach
8722
        $listCourseMainCoachSession = self::getCoursesForMainSessionCoach($userId);
8723
        // merge these 2 array
8724
        $listResCourseSession = $listCourseCourseCoachSession;
8725
        foreach ($listCourseMainCoachSession as $courseId2 => $listSessionId2) {
8726
            if (isset($listResCourseSession[$courseId2])) {
8727
                // if sessionId array exists for this course
8728
                // same courseId, merge the list of session
8729
                foreach ($listCourseMainCoachSession[$courseId2] as $i => $sessionId2) {
8730
                    if (!in_array($sessionId2, $listResCourseSession[$courseId2])) {
8731
                        $listResCourseSession[$courseId2][] = $sessionId2;
8732
                    }
8733
                }
8734
            } else {
8735
                $listResCourseSession[$courseId2] = $listSessionId2;
8736
            }
8737
        }
8738
8739
        return $listResCourseSession;
8740
    }
8741
8742
    /**
8743
     * Return an associative array 'id_course' => [id_session1, id_session2...]
8744
     * where course id_course is in sessions id_session1, id_session2.
8745
     *
8746
     * @param int $userId
8747
     *
8748
     * @return array
8749
     */
8750
    public static function getCoursesForCourseSessionCoach($userId)
8751
    {
8752
        $userId = (int) $userId;
8753
        $listResCourseSession = [];
8754
        $tblCourse = Database::get_main_table(TABLE_MAIN_COURSE);
8755
        $tblSessionRelCourseRelUser = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
8756
8757
        $sql = "SELECT session_id, c_id, c.id
8758
                FROM $tblSessionRelCourseRelUser srcru
8759
                LEFT JOIN $tblCourse c
8760
                ON c.id = srcru.c_id
8761
                WHERE
8762
                    srcru.user_id = $userId AND
8763
                    srcru.status = 2";
8764
8765
        $res = Database::query($sql);
8766
8767
        while ($data = Database::fetch_assoc($res)) {
8768
            if (api_get_session_visibility($data['session_id'])) {
8769
                if (!isset($listResCourseSession[$data['id']])) {
8770
                    $listResCourseSession[$data['id']] = [];
8771
                }
8772
                $listResCourseSession[$data['id']][] = $data['session_id'];
8773
            }
8774
        }
8775
8776
        return $listResCourseSession;
8777
    }
8778
8779
    /**
8780
     * Return an associative array 'id_course' => [id_session1, id_session2...]
8781
     * where course id_course is in sessions id_session1, id_session2.
8782
     *
8783
     * @param $userId
8784
     *
8785
     * @return array
8786
     */
8787
    public static function getCoursesForMainSessionCoach($userId)
8788
    {
8789
        $userId = (int) $userId;
8790
        $listResCourseSession = [];
8791
        $tblSession = Database::get_main_table(TABLE_MAIN_SESSION);
8792
8793
        // list of SESSION where user is session coach
8794
        $sql = "SELECT id FROM $tblSession
8795
                WHERE id_coach = ".$userId;
8796
        $res = Database::query($sql);
8797
8798
        while ($data = Database::fetch_assoc($res)) {
8799
            $sessionId = $data['id'];
8800
            $listCoursesInSession = self::getCoursesInSession($sessionId);
8801
            foreach ($listCoursesInSession as $i => $courseId) {
8802
                if (api_get_session_visibility($sessionId)) {
8803
                    if (!isset($listResCourseSession[$courseId])) {
8804
                        $listResCourseSession[$courseId] = [];
8805
                    }
8806
                    $listResCourseSession[$courseId][] = $sessionId;
8807
                }
8808
            }
8809
        }
8810
8811
        return $listResCourseSession;
8812
    }
8813
8814
    /**
8815
     * Return an array of course_id used in session $sessionId.
8816
     *
8817
     * @param $sessionId
8818
     *
8819
     * @return array
8820
     */
8821
    public static function getCoursesInSession($sessionId)
8822
    {
8823
        if (empty($sessionId)) {
8824
            return [];
8825
        }
8826
8827
        $tblSessionRelCourse = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
8828
        $tblCourse = Database::get_main_table(TABLE_MAIN_COURSE);
8829
8830
        // list of course in this session
8831
        $sql = "SELECT session_id, c.id
8832
                FROM $tblSessionRelCourse src
8833
                LEFT JOIN $tblCourse c
8834
                ON c.id = src.c_id
8835
                WHERE session_id = ".intval($sessionId);
8836
        $res = Database::query($sql);
8837
8838
        $listResultsCourseId = [];
8839
        while ($data = Database::fetch_assoc($res)) {
8840
            $listResultsCourseId[] = $data['id'];
8841
        }
8842
8843
        return $listResultsCourseId;
8844
    }
8845
8846
    /**
8847
     * Return an array of courses in session for user
8848
     * and for each courses the list of session that use this course for user.
8849
     *
8850
     * [0] => array
8851
     *      userCatId
8852
     *      userCatTitle
8853
     *      courseInUserCatList
8854
     *          [0] => array
8855
     *              courseId
8856
     *              title
8857
     *              courseCode
8858
     *              sessionCatList
8859
     *                  [0] => array
8860
     *                      catSessionId
8861
     *                      catSessionName
8862
     *                      sessionList
8863
     *                          [0] => array
8864
     *                              sessionId
8865
     *                              sessionName
8866
     *
8867
     * @param int $userId
8868
     *
8869
     * @return array
8870
     */
8871
    public static function getNamedSessionCourseForCoach($userId)
8872
    {
8873
        $listResults = [];
8874
        $listCourseSession = self::getSessionCourseForUser($userId);
8875
        foreach ($listCourseSession as $courseId => $listSessionId) {
8876
            // Course info
8877
            $courseInfo = api_get_course_info_by_id($courseId);
8878
            $listOneCourse = [];
8879
            $listOneCourse['courseId'] = $courseId;
8880
            $listOneCourse['title'] = $courseInfo['title'];
8881
            //$listOneCourse['courseCode'] = $courseInfo['code'];
8882
            $listOneCourse['course'] = $courseInfo;
8883
            $listOneCourse['sessionCatList'] = [];
8884
            $listCat = [];
8885
            foreach ($listSessionId as $i => $sessionId) {
8886
                // here we got all session for this course
8887
                // lets check there session categories
8888
                $sessionInfo = self::fetch($sessionId);
8889
                $catId = $sessionInfo['session_category_id'];
8890
                if (!isset($listCat[$catId])) {
8891
                    $listCatInfo = self::get_session_category($catId);
8892
                    $listCat[$catId] = [];
8893
                    $listCat[$catId]['catSessionId'] = $catId;
8894
                    $listCat[$catId]['catSessionName'] = $listCatInfo['name'];
8895
                    $listCat[$catId]['sessionList'] = [];
8896
                }
8897
                $listSessionInfo = self::fetch($sessionId);
8898
                $listSessionIdName = [
8899
                    'sessionId' => $sessionId,
8900
                    'sessionName' => $listSessionInfo['name'],
8901
                ];
8902
                $listCat[$catId]['sessionList'][] = $listSessionIdName;
8903
            }
8904
            // sort $listCat by catSessionName
8905
            usort($listCat, 'self::compareBySessionName');
8906
            // in each catSession sort sessionList by sessionName
8907
            foreach ($listCat as $i => $listCatSessionInfo) {
8908
                $listSessionList = $listCatSessionInfo['sessionList'];
8909
                usort($listSessionList, 'self::compareCatSessionInfo');
8910
                $listCat[$i]['sessionList'] = $listSessionList;
8911
            }
8912
8913
            $listOneCourse['sessionCatList'] = $listCat;
8914
8915
            // user course category
8916
            $courseCategory = CourseManager::getUserCourseCategoryForCourse(
8917
                $userId,
8918
                $courseId
8919
            );
8920
8921
            $userCatTitle = '';
8922
            $userCatId = 0;
8923
            if ($courseCategory) {
8924
                $userCatId = $courseCategory['user_course_cat'];
8925
                $userCatTitle = $courseCategory['title'];
8926
            }
8927
8928
            $listResults[$userCatId]['courseInUserCategoryId'] = $userCatId;
8929
            $listResults[$userCatId]['courseInUserCategoryTitle'] = $userCatTitle;
8930
            $listResults[$userCatId]['courseInUserCatList'][] = $listOneCourse;
8931
        }
8932
8933
        // sort by user course cat
8934
        uasort($listResults, 'self::compareByUserCourseCat');
8935
8936
        // sort by course title
8937
        foreach ($listResults as $userCourseCatId => $tabCoursesInCat) {
8938
            $courseInUserCatList = $tabCoursesInCat['courseInUserCatList'];
8939
            uasort($courseInUserCatList, 'self::compareByCourse');
8940
            $listResults[$userCourseCatId]['courseInUserCatList'] = $courseInUserCatList;
8941
        }
8942
8943
        return $listResults;
8944
    }
8945
8946
    /**
8947
     * Return HTML code for displaying session_course_for_coach.
8948
     *
8949
     * @param $userId
8950
     *
8951
     * @return string
8952
     */
8953
    public static function getHtmlNamedSessionCourseForCoach($userId)
8954
    {
8955
        $htmlRes = '';
8956
        $listInfo = self::getNamedSessionCourseForCoach($userId);
8957
        foreach ($listInfo as $i => $listCoursesInfo) {
8958
            $courseInfo = $listCoursesInfo['course'];
8959
            $courseCode = $listCoursesInfo['course']['code'];
8960
8961
            $listParamsCourse = [];
8962
            $listParamsCourse['icon'] = '<div style="float:left">
8963
                <input style="border:none;" type="button" onclick="$(\'#course-'.$courseCode.'\').toggle(\'fast\')" value="+" /></div>'.
8964
                Display::return_icon('blackboard.png', $courseInfo['title'], [], ICON_SIZE_LARGE);
8965
            $listParamsCourse['link'] = '';
8966
            $listParamsCourse['title'] = Display::tag(
8967
                'a',
8968
                $courseInfo['title'],
8969
                ['href' => $listParamsCourse['link']]
8970
            );
8971
            $htmlCourse = '<div class="well" style="border-color:#27587D">'.
8972
                CourseManager::course_item_html($listParamsCourse, true);
8973
            // for each category of session
8974
            $htmlCatSessions = '';
8975
            foreach ($listCoursesInfo['sessionCatList'] as $j => $listCatSessionsInfo) {
8976
                // we got an array of session categories
8977
                $catSessionId = $listCoursesInfo['sessionCatList'][$j]['catSessionId'];
8978
                $catSessionName = $listCoursesInfo['sessionCatList'][$j]['catSessionName'];
8979
8980
                $listParamsCatSession['icon'] = Display::return_icon('folder_blue.png', $catSessionName, [], ICON_SIZE_LARGE);
8981
                $listParamsCatSession['link'] = '';
8982
                $listParamsCatSession['title'] = $catSessionName;
8983
8984
                $marginShift = 20;
8985
                if ($catSessionName != '') {
8986
                    $htmlCatSessions .= '<div style="margin-left:'.$marginShift.'px;">'.
8987
                        CourseManager::course_item_html($listParamsCatSession, true).'</div>';
8988
                    $marginShift = 40;
8989
                }
8990
8991
                // for each sessions
8992
                $listCatSessionSessionList = $listCoursesInfo['sessionCatList'][$j]['sessionList'];
8993
                $htmlSession = '';
8994
                foreach ($listCatSessionSessionList as $k => $listSessionInfo) {
8995
                    // we got an array of session info
8996
                    $sessionId = $listSessionInfo['sessionId'];
8997
                    $sessionName = $listSessionInfo['sessionName'];
8998
8999
                    $listParamsSession['icon'] = Display::return_icon('blackboard_blue.png', $sessionName, [], ICON_SIZE_LARGE);
9000
                    $listParamsSession['link'] = '';
9001
                    $linkToCourseSession = $courseInfo['course_public_url'].'?id_session='.$sessionId;
9002
                    $listParamsSession['title'] =
9003
                        $sessionName.'<div style="font-weight:normal; font-style:italic">
9004
                            <a href="'.$linkToCourseSession.'">'.get_lang('GoToCourseInsideSession').'</a>
9005
                            </div>';
9006
                    $htmlSession .= '<div style="margin-left:'.$marginShift.'px;">'.
9007
                        CourseManager::course_item_html($listParamsSession, true).'</div>';
9008
                }
9009
                $htmlCatSessions .= $htmlSession;
9010
            }
9011
            $htmlRes .= $htmlCourse.'<div style="display:none" id="course-'.$courseCode.'">'.$htmlCatSessions.'</div></div>';
9012
        }
9013
9014
        return $htmlRes;
9015
    }
9016
9017
    /**
9018
     * @param int $userId
9019
     * @param int $courseId
9020
     *
9021
     * @return array
9022
     */
9023
    public static function searchCourseInSessionsFromUser($userId, $courseId)
9024
    {
9025
        $table = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
9026
        $userId = (int) $userId;
9027
        $courseId = (int) $courseId;
9028
        if (empty($userId) || empty($courseId)) {
9029
            return [];
9030
        }
9031
9032
        $sql = "SELECT * FROM $table 
9033
                WHERE c_id = $courseId AND user_id = $userId";
9034
        $result = Database::query($sql);
9035
9036
        return Database::store_result($result, 'ASSOC');
9037
    }
9038
9039
    /**
9040
     * Subscribe and redirect to session after inscription.
9041
     */
9042
    public static function redirectToSession()
9043
    {
9044
        $sessionId = ChamiloSession::read('session_redirect');
9045
        $onlyOneCourseSessionToRedirect = ChamiloSession::read('only_one_course_session_redirect');
9046
        if ($sessionId) {
9047
            $sessionInfo = api_get_session_info($sessionId);
9048
            if (!empty($sessionInfo)) {
9049
                $userId = api_get_user_id();
9050
                $response = self::isUserSubscribedAsStudent($sessionId, $userId);
9051
                if ($response) {
9052
                    $urlToRedirect = api_get_path(WEB_CODE_PATH).'session/index.php?session_id='.$sessionId;
9053
                    if (!empty($onlyOneCourseSessionToRedirect)) {
9054
                        $urlToRedirect = api_get_path(WEB_PATH).
9055
                            'courses/'.$onlyOneCourseSessionToRedirect.'/index.php?id_session='.$sessionId;
9056
                    }
9057
9058
                    header('Location: '.$urlToRedirect);
9059
                    exit;
9060
                }
9061
            }
9062
        }
9063
    }
9064
9065
    /**
9066
     * @param Course  $course
9067
     * @param Session $session
9068
     *
9069
     * @return int
9070
     */
9071
    public static function getCountUsersInCourseSession(
9072
        Course $course,
9073
        Session $session
9074
    ) {
9075
        return Database::getManager()
9076
            ->createQuery("
9077
                SELECT COUNT(scu)
9078
                FROM ChamiloCoreBundle:SessionRelCourseRelUser scu
9079
                INNER JOIN ChamiloCoreBundle:SessionRelUser su
9080
                    WITH scu.user = su.user
9081
                    AND scu.session = su.session
9082
                WHERE 
9083
                    scu.course = :course AND 
9084
                    su.relationType <> :relationType AND 
9085
                    scu.session = :session
9086
            ")
9087
            ->setParameters([
9088
                'course' => $course->getId(),
9089
                'relationType' => SESSION_RELATION_TYPE_RRHH,
9090
                'session' => $session->getId(),
9091
            ])
9092
            ->getSingleScalarResult();
9093
    }
9094
9095
    /**
9096
     * Get course IDs where user in not subscribed in session.
9097
     *
9098
     * @param User    $user
9099
     * @param Session $session
9100
     *
9101
     * @return array
9102
     */
9103
    public static function getAvoidedCoursesInSession(User $user, Session $session)
9104
    {
9105
        $courseIds = [];
9106
9107
        /** @var SessionRelCourse $sessionCourse */
9108
        foreach ($session->getCourses() as $sessionCourse) {
9109
            /** @var Course $course */
9110
            $course = $sessionCourse->getCourse();
9111
9112
            if ($session->getUserInCourse($user, $course)->count()) {
9113
                continue;
9114
            }
9115
9116
            $courseIds[] = $course->getId();
9117
        }
9118
9119
        return $courseIds;
9120
    }
9121
9122
    /**
9123
     * @param int $id
9124
     *
9125
     * @return bool
9126
     */
9127
    private static function allowed($id)
9128
    {
9129
        $sessionInfo = self::fetch($id);
9130
9131
        if (empty($sessionInfo)) {
9132
            return false;
9133
        }
9134
9135
        if (api_is_platform_admin()) {
9136
            return true;
9137
        }
9138
9139
        $userId = api_get_user_id();
9140
9141
        if (api_is_session_admin() &&
9142
            api_get_setting('allow_session_admins_to_manage_all_sessions') != 'true'
9143
        ) {
9144
            if ($sessionInfo['session_admin_id'] != $userId) {
9145
                return false;
9146
            }
9147
        }
9148
9149
        if (api_is_teacher() &&
9150
            api_get_setting('allow_teachers_to_create_sessions') == 'true'
9151
        ) {
9152
            if ($sessionInfo['id_coach'] != $userId) {
9153
                return false;
9154
            }
9155
        }
9156
9157
        return true;
9158
    }
9159
9160
    /**
9161
     * Add classes (by their names) to a session.
9162
     *
9163
     * @param int   $sessionId
9164
     * @param array $classesNames
9165
     * @param bool  $deleteClassSessions Optional. Empty the session list for the usergroup (class)
9166
     */
9167
    private static function addClassesByName($sessionId, $classesNames, $deleteClassSessions = true)
9168
    {
9169
        if (!$classesNames) {
9170
            return;
9171
        }
9172
9173
        $usergroup = new UserGroup();
9174
9175
        foreach ($classesNames as $className) {
9176
            if (empty($className)) {
9177
                continue;
9178
            }
9179
9180
            $usergroup->subscribe_sessions_to_usergroup(
9181
                $usergroup->get_id_by_name($className),
9182
                [$sessionId],
9183
                $deleteClassSessions
9184
            );
9185
        }
9186
    }
9187
9188
    /**
9189
     * Converts "start date" and "end date" to "From start date to end date" string.
9190
     *
9191
     * @param string $startDate
9192
     * @param string $endDate
9193
     * @param bool   $showTime
9194
     * @param bool   $dateHuman
9195
     *
9196
     * @return string
9197
     */
9198
    private static function convertSessionDateToString($startDate, $endDate, $showTime, $dateHuman)
9199
    {
9200
        // api_get_local_time returns empty if date is invalid like 0000-00-00 00:00:00
9201
        $startDateToLocal = api_get_local_time(
9202
            $startDate,
9203
            null,
9204
            null,
9205
            true,
9206
            $showTime,
9207
            $dateHuman
9208
        );
9209
        $endDateToLocal = api_get_local_time(
9210
            $endDate,
9211
            null,
9212
            null,
9213
            true,
9214
            $showTime,
9215
            $dateHuman
9216
        );
9217
9218
        $result = '';
9219
        if (!empty($startDateToLocal) && !empty($endDateToLocal)) {
9220
            $result = sprintf(
9221
                get_lang('FromDateXToDateY'),
9222
                api_format_date($startDateToLocal, DATE_TIME_FORMAT_LONG_24H),
9223
                api_format_date($endDateToLocal, DATE_TIME_FORMAT_LONG_24H)
9224
            );
9225
        } else {
9226
            if (!empty($startDateToLocal)) {
9227
                $result = get_lang('From').' '.api_format_date($startDateToLocal, DATE_TIME_FORMAT_LONG_24H);
9228
            }
9229
            if (!empty($endDateToLocal)) {
9230
                $result = get_lang('Until').' '.api_format_date($endDateToLocal, DATE_TIME_FORMAT_LONG_24H);
9231
            }
9232
        }
9233
        if (empty($result)) {
9234
            $result = get_lang('NoTimeLimits');
9235
        }
9236
9237
        return $result;
9238
    }
9239
9240
    /**
9241
     * @param array $listA
9242
     * @param array $listB
9243
     *
9244
     * @return int
9245
     */
9246
    private static function compareCatSessionInfo($listA, $listB)
9247
    {
9248
        if ($listA['sessionName'] == $listB['sessionName']) {
9249
            return 0;
9250
        } elseif ($listA['sessionName'] > $listB['sessionName']) {
9251
            return 1;
9252
        } else {
9253
            return -1;
9254
        }
9255
    }
9256
9257
    /**
9258
     * @param array $listA
9259
     * @param array $listB
9260
     *
9261
     * @return int
9262
     */
9263
    private static function compareBySessionName($listA, $listB)
9264
    {
9265
        if ($listB['catSessionName'] == '') {
9266
            return -1;
9267
        } elseif ($listA['catSessionName'] == '') {
9268
            return 1;
9269
        } elseif ($listA['catSessionName'] == $listB['catSessionName']) {
9270
            return 0;
9271
        } elseif ($listA['catSessionName'] > $listB['catSessionName']) {
9272
            return 1;
9273
        } else {
9274
            return -1;
9275
        }
9276
    }
9277
9278
    /**
9279
     * @param array $listA
9280
     * @param array $listB
9281
     *
9282
     * @return int
9283
     */
9284
    private static function compareByUserCourseCat($listA, $listB)
9285
    {
9286
        if ($listA['courseInUserCategoryTitle'] == $listB['courseInUserCategoryTitle']) {
9287
            return 0;
9288
        } elseif ($listA['courseInUserCategoryTitle'] > $listB['courseInUserCategoryTitle']) {
9289
            return 1;
9290
        } else {
9291
            return -1;
9292
        }
9293
    }
9294
9295
    /**
9296
     * @param array $listA
9297
     * @param array $listB
9298
     *
9299
     * @return int
9300
     */
9301
    private static function compareByCourse($listA, $listB)
9302
    {
9303
        if ($listA['title'] == $listB['title']) {
9304
            return 0;
9305
        } elseif ($listA['title'] > $listB['title']) {
9306
            return 1;
9307
        } else {
9308
            return -1;
9309
        }
9310
    }
9311
9312
    /**
9313
     * @param int $id
9314
     *
9315
     * @return string
9316
     */
9317
    public static function getSessionChangeUserReason($id) : string
9318
    {
9319
        $reasons = self::getSessionChangeUserReasons();
9320
9321
        return $reasons[$id] ?? '';
9322
    }
9323
9324
    /**
9325
     * @return array
9326
     */
9327
    public static function getSessionChangeUserReasons() : array
9328
    {
9329
        return array(
9330
            self::SESSION_CHANGE_USER_REASON_SCHEDULE => get_lang('ScheduleChanged'),
9331
            self::SESSION_CHANGE_USER_REASON_CLASSROOM => get_lang('ClassRoomChanged'),
9332
            self::SESSION_CHANGE_USER_REASON_LOCATION => get_lang('LocationChanged'),
9333
            //self::SESSION_CHANGE_USER_REASON_ENROLLMENT_ANNULATION => get_lang('EnrollmentAnnulation'),
9334
        );
9335
    }
9336
}
9337