Completed
Push — master ( b77cfe...000f93 )
by Julito
22:58 queued 11:19
created

SessionManager::subscribeUsersToSession()   F

Complexity

Conditions 30
Paths > 20000

Size

Total Lines 241
Code Lines 153

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 30
eloc 153
nc 24194
nop 4
dl 0
loc 241
rs 2
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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