Passed
Pull Request — preprodparkur (#4132)
by
unknown
11:09
created

SessionManager::getCountUsersLangBySession()   A

Complexity

Conditions 5
Paths 8

Size

Total Lines 38
Code Lines 23

Duplication

Lines 0
Ratio 0 %

Importance

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