Completed
Push — master ( ae5621...ef667c )
by Julito
13:23
created

SessionManager::clear_session_ref_promotion()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 11
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

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