Passed
Push — master ( a0a481...e98a66 )
by Julito
09:27
created

SessionManager::create_category_session()   D

Complexity

Conditions 19
Paths 128

Size

Total Lines 65
Code Lines 40

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 19
eloc 40
nc 128
nop 7
dl 0
loc 65
rs 4.2833
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

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

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

Commonly applied refactorings include:

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