Completed
Push — 1.11.x ( 772bf4...b5113d )
by José
28:31
created

SessionManager::redirectToSession()   B

Complexity

Conditions 6
Paths 16

Size

Total Lines 25
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
eloc 13
nc 16
nop 0
dl 0
loc 25
rs 8.439
c 0
b 0
f 0
1
<?php
2
/* For licensing terms, see /license.txt */
3
4
use Chamilo\CoreBundle\Entity\SessionRelCourseRelUser;
5
use \ExtraField as ExtraFieldModel;
6
use Chamilo\CoreBundle\Entity\ExtraField;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, ExtraField.

Let’s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let’s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
7
use Chamilo\CoreBundle\Entity\Session;
8
9
/**
10
 * Class SessionManager
11
 *
12
 * This is the session library for Chamilo.
13
 * All main sessions functions should be placed here.
14
 * This class provides methods for sessions management.
15
 * Include/require it in your code to use its features.
16
 *
17
 * @package chamilo.library
18
 *
19
 */
20
class SessionManager
21
{
22
    public static $_debug = false;
23
24
    /**
25
     * Constructor
26
     */
27
    public function __construct()
28
    {
29
    }
30
31
    /**
32
     * Fetches a session from the database
33
     * @param  int $id Session Id
34
     *
35
     * @return  array   Session details
36
     */
37
    public static function fetch($id)
38
    {
39
        $em = Database::getManager();
40
        /** @var Session $session */
41
        $session = $em->find('ChamiloCoreBundle:Session', $id);
42
43
        if (!$session) {
44
            return [];
45
        }
46
47
        return [
48
            'id' => $session->getId(),
49
            'id_coach' => $session->getGeneralCoach() ? $session->getGeneralCoach()->getId() : null,
50
            'session_category_id' => $session->getCategory() ? $session->getCategory()->getId() : null,
51
            'name' => $session->getName(),
52
            'description' => $session->getDescription(),
53
            'show_description' => $session->getShowDescription(),
54
            'duration' => $session->getDuration(),
55
            'nbr_courses' => $session->getNbrCourses(),
56
            'nbr_users' => $session->getNbrUsers(),
57
            'nbr_classes' => $session->getNbrClasses(),
58
            'session_admin_id' => $session->getSessionAdminId(),
59
            'visibility' => $session->getVisibility(),
60
            'promotion_id' => $session->getPromotionId(),
61
            'display_start_date' => $session->getDisplayStartDate()
62
                ? $session->getDisplayStartDate()->format('Y-m-d H:i:s')
63
                : null,
64
            'display_end_date' => $session->getDisplayEndDate()
65
                ? $session->getDisplayEndDate()->format('Y-m-d H:i:s')
66
                : null,
67
            'access_start_date' => $session->getAccessStartDate()
68
                ? $session->getAccessStartDate()->format('Y-m-d H:i:s')
69
                : null,
70
            'access_end_date' => $session->getAccessEndDate()
71
                ? $session->getAccessEndDate()->format('Y-m-d H:i:s')
72
                : null,
73
            'coach_access_start_date' => $session->getCoachAccessStartDate()
74
                ? $session->getCoachAccessStartDate()->format('Y-m-d H:i:s')
75
                : null,
76
            'coach_access_end_date' => $session->getCoachAccessEndDate()
77
                ? $session->getCoachAccessEndDate()->format('Y-m-d H:i:s')
78
                : null,
79
            'send_subscription_notification' => $session->getSendSubscriptionNotification()
80
        ];
81
    }
82
83
    /**
84
     * Create a session
85
     * @author Carlos Vargas <[email protected]>, from existing code
86
     * @param   string  $name
87
     * @param   string  $startDate (YYYY-MM-DD hh:mm:ss)
88
     * @param   string  $endDate (YYYY-MM-DD hh:mm:ss)
89
     * @param   string  $displayStartDate (YYYY-MM-DD hh:mm:ss)
90
     * @param   string  $displayEndDate (YYYY-MM-DD hh:mm:ss)
91
     * @param   string  $coachStartDate (YYYY-MM-DD hh:mm:ss)
92
     * @param   string  $coachEndDate (YYYY-MM-DD hh:mm:ss)
93
     * @param   mixed   $coachId If integer, this is the session coach id, if string, the coach ID will be looked for from the user table
94
     * @param   integer $sessionCategoryId ID of the session category in which this session is registered
95
     * @param   integer $visibility Visibility after end date (0 = read-only, 1 = invisible, 2 = accessible)
96
     * @param   bool    $fixSessionNameIfExists
97
     * @param   string  $duration
98
     * @param   string  $description Optional. The session description
99
     * @param   int     $showDescription Optional. Whether show the session description
100
     * @param   array   $extraFields
101
     * @param   int     $sessionAdminId Optional. If this sessions was created by a session admin, assign it to him
102
     * @param boolean $sendSubscriptionNotification Optional.
103
     *          Whether send a mail notification to users being subscribed
104
     * @todo use an array to replace all this parameters or use the model.lib.php ...
105
     * @return mixed       Session ID on success, error message otherwise
106
     * */
107
    public static function create_session(
108
        $name,
109
        $startDate,
110
        $endDate,
111
        $displayStartDate,
112
        $displayEndDate,
113
        $coachStartDate,
114
        $coachEndDate,
115
        $coachId,
116
        $sessionCategoryId,
117
        $visibility = 1,
118
        $fixSessionNameIfExists = false,
119
        $duration = null,
120
        $description = null,
121
        $showDescription = 0,
122
        $extraFields = array(),
123
        $sessionAdminId = 0,
124
        $sendSubscriptionNotification = false
125
    ) {
126
        global $_configuration;
127
128
        //Check portal limits
129
        $access_url_id = 1;
130
131
        if (api_get_multiple_access_url()) {
132
            $access_url_id = api_get_current_access_url_id();
133
        }
134
135
        if (is_array($_configuration[$access_url_id]) &&
136
            isset($_configuration[$access_url_id]['hosting_limit_sessions']) &&
137
            $_configuration[$access_url_id]['hosting_limit_sessions'] > 0
138
        ) {
139
            $num = self::count_sessions();
140
            if ($num >= $_configuration[$access_url_id]['hosting_limit_sessions']) {
141
                api_warn_hosting_contact('hosting_limit_sessions');
142
                return get_lang('PortalSessionsLimitReached');
143
            }
144
        }
145
146
        $name = Database::escape_string(trim($name));
147
        $sessionCategoryId = intval($sessionCategoryId);
148
        $visibility = intval($visibility);
149
        $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
150
151
        $startDate = Database::escape_string($startDate);
152
        $endDate = Database::escape_string($endDate);
153
154
        if (empty($name)) {
155
            $msg = get_lang('SessionNameIsRequired');
156
            return $msg;
157
        } elseif (empty($coachId)) {
158
            $msg = get_lang('CoachIsRequired');
159
            return $msg;
160
        } elseif (!empty($startDate) && !api_is_valid_date($startDate, 'Y-m-d H:i') && !api_is_valid_date($startDate, 'Y-m-d H:i:s')) {
161
            $msg = get_lang('InvalidStartDate');
162
            return $msg;
163
        } elseif (!empty($endDate) && !api_is_valid_date($endDate, 'Y-m-d H:i') && !api_is_valid_date($endDate, 'Y-m-d H:i:s')) {
164
            $msg = get_lang('InvalidEndDate');
165
            return $msg;
166
        } elseif (!empty($startDate) && !empty($endDate) && $startDate >= $endDate) {
167
            $msg = get_lang('StartDateShouldBeBeforeEndDate');
168
            return $msg;
169
        } else {
170
            $ready_to_create = false;
171
            if ($fixSessionNameIfExists) {
172
                $name = self::generateNextSessionName($name);
173
                if ($name) {
174
                    $ready_to_create = true;
175
                } else {
176
                    $msg = get_lang('SessionNameAlreadyExists');
177
                    return $msg;
178
                }
179
            } else {
180
                $rs = Database::query("SELECT 1 FROM $tbl_session WHERE name='" . $name . "'");
181
                if (Database::num_rows($rs)) {
182
                    $msg = get_lang('SessionNameAlreadyExists');
183
                    return $msg;
184
                }
185
                $ready_to_create = true;
186
            }
187
188
            if ($ready_to_create) {
189
                $sessionAdminId = !empty($sessionAdminId) ? $sessionAdminId : api_get_user_id();
190
                $values = array(
191
                    'name' => $name,
192
                    'id_coach' => $coachId,
193
                    'session_admin_id' => $sessionAdminId,
194
                    'visibility' => $visibility,
195
                    'description' => $description,
196
                    'show_description' => intval($showDescription),
197
                    'send_subscription_notification' => (int) $sendSubscriptionNotification
198
                );
199
200
                if (!empty($startDate)) {
201
                    $values['access_start_date'] = api_get_utc_datetime($startDate);
202
                }
203
204
                if (!empty($endDate)) {
205
                    $values['access_end_date'] = api_get_utc_datetime($endDate);
206
                }
207
208
                if (!empty($displayStartDate)) {
209
                    $values['display_start_date'] = api_get_utc_datetime($displayStartDate);
210
                }
211
212
                if (!empty($displayEndDate)) {
213
                    $values['display_end_date'] = api_get_utc_datetime($displayEndDate);
214
                }
215
216
                if (!empty($coachStartDate)) {
217
                    $values['coach_access_start_date'] = api_get_utc_datetime($coachStartDate);
218
                }
219
                if (!empty($coachEndDate)) {
220
                    $values['coach_access_end_date'] = api_get_utc_datetime($coachEndDate);
221
                }
222
223
                if (!empty($sessionCategoryId)) {
224
                    $values['session_category_id'] = $sessionCategoryId;
225
                }
226
227
                $session_id = Database::insert($tbl_session, $values);
228
229
                $duration = intval($duration);
230
231 View Code Duplication
                if (!empty($duration)) {
232
                    $sql = "UPDATE $tbl_session SET
233
                        access_start_date = NULL,
234
                        access_end_date = NULL,
235
                        display_start_date = NULL,
236
                        display_end_date = NULL,
237
                        coach_access_start_date = NULL,
238
                        coach_access_end_date = NULL,
239
                        duration = $duration
240
                    WHERE id = $session_id";
241
                    Database::query($sql);
242
                } else {
243
                    $sql = "UPDATE $tbl_session
244
                        SET duration = 0
245
                        WHERE id = $session_id";
246
                    Database::query($sql);
247
                }
248
249
                if (!empty($session_id)) {
250
                    $extraFields['item_id'] = $session_id;
251
252
                    $sessionFieldValue = new ExtraFieldValue('session');
253
                    $sessionFieldValue->saveFieldValues($extraFields);
254
255
                    /*
256
                      Sends a message to the user_id = 1
257
258
                      $user_info = api_get_user_info(1);
259
                      $complete_name = $user_info['firstname'].' '.$user_info['lastname'];
260
                      $subject = api_get_setting('siteName').' - '.get_lang('ANewSessionWasCreated');
261
                      $message = get_lang('ANewSessionWasCreated')." <br /> ".get_lang('NameOfTheSession').' : '.$name;
262
                      api_mail_html($complete_name, $user_info['email'], $subject, $message);
263
                     *
264
                     */
265
                    //Adding to the correct URL
266
                    $access_url_id = api_get_current_access_url_id();
267
                    UrlManager::add_session_to_url($session_id, $access_url_id);
268
269
                    // add event to system log
270
                    $user_id = api_get_user_id();
271
                    Event::addEvent(
272
                        LOG_SESSION_CREATE,
273
                        LOG_SESSION_ID,
274
                        $session_id,
275
                        api_get_utc_datetime(),
276
                        $user_id
277
                    );
278
                }
279
280
                return $session_id;
281
            }
282
        }
283
    }
284
285
    /**
286
     * @param string $name
287
     *
288
     * @return bool
289
     */
290
    public static function session_name_exists($name)
291
    {
292
        $name = Database::escape_string($name);
293
        $sql = "SELECT COUNT(*) as count FROM " . Database::get_main_table(TABLE_MAIN_SESSION) . "
294
                WHERE name = '$name'";
295
        $result = Database::fetch_array(Database::query($sql));
0 ignored issues
show
Bug introduced by
It seems like \Database::query($sql) can be null; however, fetch_array() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
296
297
        return $result['count'] > 0;
298
    }
299
300
    /**
301
     * @param string $where_condition
302
     *
303
     * @return mixed
304
     */
305
    public static function get_count_admin($where_condition = '')
306
    {
307
        $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
308
        $tbl_session_category = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
309
        $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
310
        $table_access_url_rel_session = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
311
        $tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
312
313
        $where = 'WHERE 1=1 ';
314
        $user_id = api_get_user_id();
315
316
        $extraJoin = '';
317
318
        if (api_is_session_admin() &&
319
            api_get_setting('allow_session_admins_to_manage_all_sessions') == 'false'
320
        ) {
321
            $where .= " AND (
322
                            s.session_admin_id = $user_id  OR
323
                            sru.user_id = '$user_id' AND
324
                            sru.relation_type = '" . SESSION_RELATION_TYPE_RRHH . "'
325
                            )
326
                      ";
327
328
            $extraJoin = " INNER JOIN $tbl_session_rel_user sru
329
                           ON sru.session_id = s.id ";
330
        }
331
332
        $today = api_get_utc_datetime();
333
        $today = api_strtotime($today, 'UTC');
334
        $today = date('Y-m-d', $today);
335
336
        if (!empty($where_condition)) {
337
            $where_condition = str_replace("(  session_active = ':'  )", '1=1', $where_condition);
338
339
            $where_condition = str_replace('category_name', 'sc.name', $where_condition);
340
            $where_condition = str_replace(
341
                array("AND session_active = '1'  )", " AND (  session_active = '1'  )"),
342
                array(') GROUP BY s.name HAVING session_active = 1 ', " GROUP BY s.name HAVING session_active = 1 " )
343
                , $where_condition
344
            );
345
            $where_condition = str_replace(
346
                array("AND session_active = '0'  )", " AND (  session_active = '0'  )"),
347
                array(') GROUP BY s.name HAVING session_active = 0 ', " GROUP BY s.name HAVING session_active = '0' "),
348
                $where_condition
349
            );
350
        } else {
351
            $where_condition = " AND 1 = 1";
352
        }
353
354
        $courseCondition = null;
355
        if (strpos($where_condition, 'c.id')) {
356
            $table = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
357
            $tableCourse = Database::get_main_table(TABLE_MAIN_COURSE);
358
            $courseCondition = " INNER JOIN $table course_rel_session
359
                                 ON (s.id = course_rel_session.session_id)
360
                                 INNER JOIN $tableCourse c
361
                                 ON (course_rel_session.c_id = c.id)
362
                                ";
363
        }
364
365
        $sql = "SELECT COUNT(id) as total_rows FROM (
366
                SELECT DISTINCT
367
                 IF (
368
					(s.access_start_date <= '$today' AND '$today' <= s.access_end_date) OR
369
                    (s.access_start_date IS NULL AND s.access_end_date  = IS NULL ) OR
370
					(s.access_start_date <= '$today' AND s.access_end_date IS NULL) OR
371
					('$today' <= s.access_end_date AND s.access_start_date IS NULL)
372
				, 1, 0) as session_active,
373
                s.id
374
                FROM $tbl_session s
375
                LEFT JOIN $tbl_session_category sc
376
                ON s.session_category_id = sc.id
377
                INNER JOIN $tbl_user u
378
                ON s.id_coach = u.user_id
379
                $courseCondition
380
                $extraJoin
381
                $where $where_condition ) as session_table";
382
383
        if (api_is_multiple_url_enabled()) {
384
385
            $access_url_id = api_get_current_access_url_id();
386
            if ($access_url_id != -1) {
387
                $where.= " AND ar.access_url_id = $access_url_id ";
388
389
                $sql = "SELECT count(id) as total_rows FROM (
390
                SELECT DISTINCT
391
                  IF (
392
					(s.access_start_date <= '$today' AND '$today' <= s.access_end_date) OR
393
                    (s.access_start_date IS NULL AND s.access_end_date IS NULL) OR
394
					(s.access_start_date <= '$today' AND s.access_end_date IS NULL) OR
395
					('$today' <= s.access_end_date AND s.access_start_date IS NULL)
396
				, 1, 0)
397
				as session_active,
398
				s.id
399
                FROM $tbl_session s
400
                    LEFT JOIN  $tbl_session_category sc
401
                    ON s.session_category_id = sc.id
402
                    INNER JOIN $tbl_user u ON s.id_coach = u.user_id
403
                    INNER JOIN $table_access_url_rel_session ar
404
                    ON ar.session_id = s.id
405
                    $courseCondition
406
                    $extraJoin
407
                $where $where_condition) as session_table";
408
            }
409
        }
410
411
        $result_rows = Database::query($sql);
412
        $row = Database::fetch_array($result_rows);
413
        $num = $row['total_rows'];
414
415
        return $num;
416
    }
417
418
    /**
419
     * Gets the admin session list callback of the session/session_list.php page
420
     * @param array $options order and limit keys
421
     * @param boolean $get_count Whether to get all the results or only the count
422
     * @return mixed Integer for number of rows, or array of results
423
     * @assert (array(),true) !== false
424
     */
425
    public static function get_sessions_admin($options = array(), $get_count = false)
426
    {
427
        $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
428
        $sessionCategoryTable = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
429
430
        $where = 'WHERE 1 = 1 ';
431
        $user_id = api_get_user_id();
432
433 View Code Duplication
        if (!api_is_platform_admin()) {
434
            if (api_is_session_admin() &&
435
                api_get_setting('allow_session_admins_to_manage_all_sessions') == 'false'
436
            ) {
437
                $where .=" AND s.session_admin_id = $user_id ";
438
            }
439
        }
440
441
        if (!api_is_platform_admin() && api_is_teacher() &&
442
            api_get_setting('allow_teachers_to_create_sessions') == 'true'
443
        ) {
444
            $where .=" AND s.id_coach = $user_id ";
445
        }
446
447
        $extra_field = new ExtraFieldModel('session');
448
        $conditions = $extra_field->parseConditions($options);
449
        $inject_joins = $conditions['inject_joins'];
450
        $where .= $conditions['where'];
451
        $inject_where = $conditions['inject_where'];
452
        $inject_extra_fields = $conditions['inject_extra_fields'];
453
454
        $order = $conditions['order'];
455
        $limit = $conditions['limit'];
456
457
        $isMakingOrder = false;
458
459
        if ($get_count == true) {
460
            $select = " SELECT count(DISTINCT s.id) as total_rows";
461
        } else {
462
            $select =
463
                "SELECT DISTINCT 
464
                     s.name,
465
                     s.display_start_date, 
466
                     s.display_end_date, 
467
                     access_start_date, 
468
                     access_end_date, 
469
                     s.visibility, 
470
                     s.session_category_id, 
471
                     $inject_extra_fields 
472
                     s.id 
473
             ";
474
475
            $isMakingOrder = strpos($options['order'], 'category_name') === 0;
476
        }
477
478
        $isFilteringSessionCategory = strpos($where, 'category_name') !== false;
479
        $isFilteringSessionCategoryWithName = strpos($where, 'sc.name') !== false;
480
481
        if ($isMakingOrder || $isFilteringSessionCategory || $isFilteringSessionCategoryWithName) {
482
            $inject_joins .= " LEFT JOIN $sessionCategoryTable sc ON s.session_category_id = sc.id ";
483
484
            if ($isFilteringSessionCategory) {
485
                $where = str_replace('category_name', 'sc.name', $where);
486
            }
487
488
            if ($isMakingOrder) {
489
                $order = str_replace('category_name', 'sc.name', $order);
490
            }
491
        }
492
493
        $query = "$select FROM $tbl_session s $inject_joins $where $inject_where";
494
495 View Code Duplication
        if (api_is_multiple_url_enabled()) {
496
            $table_access_url_rel_session= Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
497
            $access_url_id = api_get_current_access_url_id();
498
            if ($access_url_id != -1) {
499
                $where.= " AND ar.access_url_id = $access_url_id ";
500
                $query = "$select
501
                        FROM $tbl_session s $inject_joins
502
                        INNER JOIN $table_access_url_rel_session ar
503
                        ON (ar.session_id = s.id) $where";
504
            }
505
        }
506
507
        $query .= $order;
508
        $query .= $limit;
509
        $result = Database::query($query);
510
511
        $categories = self::get_all_session_category();
512
        $orderedCategories = array();
513
        if (!empty($categories)) {
514
            foreach ($categories as $category) {
515
                $orderedCategories[$category['id']] = $category['name'];
516
            }
517
        }
518
519
        $formatted_sessions = array();
520
        if (Database::num_rows($result)) {
521
            $sessions = Database::store_result($result, 'ASSOC');
522
            if ($get_count) {
523
                return $sessions[0]['total_rows'];
524
            }
525
526
            foreach ($sessions as $session) {
527
                $session_id = $session['id'];
528
                $session['name'] = Display::url($session['name'], "resume_session.php?id_session=".$session['id']);
529
530 View Code Duplication
                if (isset($session['session_active']) && $session['session_active'] == 1) {
531
                    $session['session_active'] = Display::return_icon('accept.png', get_lang('Active'), array(), ICON_SIZE_SMALL);
532
                } else {
533
                    $session['session_active'] = Display::return_icon('error.png', get_lang('Inactive'), array(), ICON_SIZE_SMALL);
534
                }
535
536
                $session = self::convert_dates_to_local($session, true);
537
538 View Code Duplication
                switch ($session['visibility']) {
539
                    case SESSION_VISIBLE_READ_ONLY: //1
540
                        $session['visibility'] = get_lang('ReadOnly');
541
                        break;
542
                    case SESSION_VISIBLE:           //2
543
                    case SESSION_AVAILABLE:         //4
544
                        $session['visibility'] = get_lang('Visible');
545
                        break;
546
                    case SESSION_INVISIBLE:         //3
547
                        $session['visibility'] = api_ucfirst(get_lang('Invisible'));
548
                        break;
549
                }
550
551
                // Cleaning double selects.
552 View Code Duplication
                foreach ($session as $key => &$value) {
0 ignored issues
show
Bug introduced by
The expression $session of type false|array<string,strin...d_date":"string|null"}> is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
553
                    if (isset($options_by_double[$key]) || isset($options_by_double[$key.'_second'])) {
554
                        $options = explode('::', $value);
555
                    }
556
                    $original_key = $key;
557
558
                    if (strpos($key, '_second') === false) {
0 ignored issues
show
Unused Code introduced by
This if statement is empty and can be removed.

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

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

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

could be turned into

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

This is much more concise to read.

Loading history...
559
                    } else {
560
                        $key = str_replace('_second', '', $key);
561
                    }
562
563
                    if (isset($options_by_double[$key])) {
564
                        if (isset($options[0])) {
565
                            if (isset($options_by_double[$key][$options[0]])) {
566
                                if (strpos($original_key, '_second') === false) {
567
                                    $value = $options_by_double[$key][$options[0]]['option_display_text'];
568
                                } else {
569
                                    $value = $options_by_double[$key][$options[1]]['option_display_text'];
570
                                }
571
                            }
572
                        }
573
                    }
574
                }
575
                $formatted_sessions[$session_id] = $session;
576
                $categoryName = isset($orderedCategories[$session['session_category_id']]) ? $orderedCategories[$session['session_category_id']] : '';
577
                $formatted_sessions[$session_id]['category_name'] = $categoryName;
578
            }
579
        }
580
        return $formatted_sessions;
581
    }
582
583
    /**
584
     *  Get total of records for progress of learning paths in the given session
585
     *  @param int session id
586
     *  @return int
587
     */
588
    public static function get_count_session_lp_progress($sessionId = 0)
589
    {
590
        $tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
591
        $tbl_lp_view = Database::get_course_table(TABLE_LP_VIEW);
592
        $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
593
        $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
594
595
        $sessionId = intval($sessionId);
596
597
        $sql = "SELECT  count(*) as total_rows
598
                FROM $tbl_lp_view v
599
                INNER JOIN $tbl_lp l ON l.id = v.lp_id
600
                INNER JOIN $tbl_user u ON u.user_id = v.user_id
601
                INNER JOIN $tbl_course c
602
                WHERE v.session_id = " . $sessionId;
603
        $result_rows = Database::query($sql);
604
        $row = Database::fetch_array($result_rows);
605
        $num = $row['total_rows'];
606
607
        return $num;
608
    }
609
610
    /**
611
     * Gets the progress of learning paths in the given session
612
     * @param int   $sessionId
613
     * @param int $courseId
614
     * @param string $date_from
615
     * @param string $date_to
616
     * @param array options order and limit keys
617
     * @return array table with user name, lp name, progress
618
     */
619
    public static function get_session_lp_progress($sessionId = 0, $courseId = 0, $date_from, $date_to, $options)
620
    {
621
        //escaping vars
622
        $sessionId = $sessionId == 'T' ? 'T' : intval($sessionId);
623
        $courseId = intval($courseId);
624
        $date_from = Database :: escape_string($date_from);
625
        $date_to = Database :: escape_string($date_to);
626
627
        //tables
628
        $session_course_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
629
        $user = Database::get_main_table(TABLE_MAIN_USER);
630
        $tbl_course_lp_view = Database::get_course_table(TABLE_LP_VIEW);
631
632
        $course = api_get_course_info_by_id($courseId);
633
634
        //getting all the students of the course
635
        //we are not using this because it only returns user ids
636
        /* if (empty($sessionId)
637
          {
638
          // Registered students in a course outside session.
639
          $users = CourseManager :: get_student_list_from_course_code($course_code);
640
          } else {
641
          // Registered students in session.
642
          $users = CourseManager :: get_student_list_from_course_code($course_code, true, $sessionId);
643
          } */
644
645
        $sessionCond = 'and session_id = %s';
646
        if ($sessionId == 'T') {
647
            $sessionCond = "";
648
        }
649
650
        $where = " WHERE c_id = '%s' AND s.status <> 2 $sessionCond";
651
652
        $limit = null;
653
        if (!empty($options['limit'])) {
654
            $limit = " LIMIT " . $options['limit'];
655
        }
656
657
        if (!empty($options['where'])) {
658
            $where .= ' '.$options['where'];
659
        }
660
661
        $order = null;
662
        if (!empty($options['order'])) {
663
            $order = " ORDER BY " . $options['order'];
664
        }
665
666
        $sql = "SELECT u.user_id, u.lastname, u.firstname, u.username, u.email, s.c_id
667
                FROM $session_course_user s
668
                INNER JOIN $user u ON u.user_id = s.user_id
669
                $where
670
                $order
671
                $limit";
672
673
        $sql_query = sprintf($sql, Database::escape_string($course['real_id']), $sessionId);
674
675
        $rs = Database::query($sql_query);
676
        while ($user = Database::fetch_array($rs)) {
677
            $users[$user['user_id']] = $user;
678
        }
679
680
        //Get lessons
681
        $lessons = LearnpathList::get_course_lessons($course['code'], $sessionId);
682
683
        $table = array();
684
        foreach ($users as $user) {
685
            $data = array(
686
                'lastname' => $user[1],
687
                'firstname' => $user[2],
688
                'username' => $user[3],
689
            );
690
691
            $sessionCond = 'AND v.session_id = %d';
692
            if ($sessionId == 'T') {
693
                $sessionCond = "";
694
            }
695
696
            //Get lessons progress by user
697
            $sql = "SELECT v.lp_id as id, v.progress
698
                    FROM  $tbl_course_lp_view v
699
                    WHERE v.c_id = %d
700
                    AND v.user_id = %d
701
            $sessionCond";
702
703
            $sql_query = sprintf($sql,
704
                intval($courseId),
705
                intval($user['user_id']),
706
                $sessionId
707
            );
708
709
            $result = Database::query($sql_query);
710
711
            $user_lessons = array();
712
            while ($row = Database::fetch_array($result)) {
713
                $user_lessons[$row['id']] = $row;
714
            }
715
716
            //Match course lessons with user progress
717
            $progress = 0;
718
            $count = 0;
719
            foreach ($lessons as $lesson) {
720
                $data[$lesson['id']] = (!empty($user_lessons[$lesson['id']]['progress'])) ? $user_lessons[$lesson['id']]['progress'] : 0;
721
                $progress += $data[$lesson['id']];
722
                $data[$lesson['id']] = $data[$lesson['id']] . '%';
723
                $count++;
724
            }
725
            if ($count == 0) {
726
                $data['total'] = 0;
727
            } else {
728
                $data['total'] = round($progress / $count, 2) . '%';
729
            }
730
            $table[] = $data;
731
        }
732
733
        return $table;
734
    }
735
736
    /**
737
     * Gets the survey answers
738
     * @param int   $sessionId
739
     * @param int   $courseId
740
     * @param int   $surveyId
741
     * @param array options order and limit keys
742
     * @todo fix the query
743
     * @return array table with user name, lp name, progress
744
     */
745
    public static function get_survey_overview($sessionId = 0, $courseId = 0, $surveyId = 0, $date_from, $date_to, $options)
746
    {
747
        //escaping vars
748
        $sessionId = intval($sessionId);
749
        $courseId = intval($courseId);
750
        $surveyId = intval($surveyId);
751
        $date_from = Database::escape_string($date_from);
752
        $date_to = Database::escape_string($date_to);
753
754
        //tables
755
        $session_course_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
756
        $user = Database::get_main_table(TABLE_MAIN_USER);
757
        $tbl_course_lp_view = Database::get_course_table(TABLE_LP_VIEW);
758
        $c_survey = Database::get_course_table(TABLE_SURVEY);
759
        $c_survey_answer = Database::get_course_table(TABLE_SURVEY_ANSWER);
760
        $c_survey_question = Database::get_course_table(TABLE_SURVEY_QUESTION);
761
        $c_survey_question_option = Database::get_course_table(TABLE_SURVEY_QUESTION_OPTION);
762
763
        $course = api_get_course_info_by_id($courseId);
764
765
        $where = " WHERE c_id = '%s' AND s.status <> 2 AND session_id = %s";
766
767
        $limit = null;
768
        if (!empty($options['limit'])) {
769
            $limit = " LIMIT " . $options['limit'];
770
        }
771
772
        if (!empty($options['where'])) {
773
            $where .= ' '.$options['where'];
774
        }
775
776
        $order = null;
777
        if (!empty($options['order'])) {
778
            $order = " ORDER BY " . $options['order'];
779
        }
780
781
        $sql = "SELECT u.user_id, u.lastname, u.firstname, u.username, u.email, s.c_id
782
                FROM $session_course_user s
783
                INNER JOIN $user u ON u.user_id = s.user_id
784
                $where $order $limit";
785
786
        $sql_query = sprintf($sql, intval($course['real_id']), $sessionId);
787
        $rs = Database::query($sql_query);
788
        while ($user = Database::fetch_array($rs)) {
789
            $users[$user['user_id']] = $user;
790
        }
791
792
        //Get survey questions
793
        $questions = SurveyManager::get_questions($surveyId, $courseId);
794
795
        //Survey is anonymous?
796
        $result = Database::query(sprintf("SELECT anonymous FROM $c_survey WHERE survey_id = %d", $surveyId));
797
        $row = Database::fetch_array($result);
798
        $anonymous = ($row['anonymous'] == 1) ? true : false;
799
800
        $table = array();
801
        foreach ($users as $user) {
802
            $data = array(
803
                'lastname' => ($anonymous ? '***' : $user[1]),
804
                'firstname' => ($anonymous ? '***' : $user[2]),
805
                'username' => ($anonymous ? '***' : $user[3]),
806
            );
807
808
            //Get questions by user
809
            $sql = "SELECT sa.question_id, sa.option_id, sqo.option_text, sq.type
810
                    FROM $c_survey_answer sa
811
                    INNER JOIN $c_survey_question sq
812
                    ON sq.question_id = sa.question_id
813
                    LEFT JOIN $c_survey_question_option sqo
814
                    ON
815
                      sqo.c_id = sa.c_id AND
816
                      sqo.question_id = sq.question_id AND
817
                      sqo.question_option_id = sa.option_id AND
818
                      sqo.survey_id = sq.survey_id
819
                    WHERE
820
                      sa.survey_id = %d AND
821
                      sa.c_id = %d AND
822
                      sa.user = %d
823
            "; //. $where_survey;
824
            $sql_query = sprintf($sql, $surveyId, $courseId, $user['user_id']);
825
826
            $result = Database::query($sql_query);
827
828
            $user_questions = array();
829
            while ($row = Database::fetch_array($result)) {
830
                $user_questions[$row['question_id']] = $row;
831
            }
832
833
            //Match course lessons with user progress
834
            foreach ($questions as $question_id => $question) {
835
                $option_text = 'option_text';
836
                if ($user_questions[$question_id]['type'] == 'open') {
837
                    $option_text = 'option_id';
838
                }
839
                $data[$question_id] = $user_questions[$question_id][$option_text];
840
            }
841
842
            $table[] = $data;
843
        }
844
        return $table;
845
    }
846
847
    /**
848
     * Gets the progress of the given session
849
     * @param int   $sessionId
850
     * @param int   $courseId
851
     * @param array options order and limit keys
852
     *
853
     * @return array table with user name, lp name, progress
854
     */
855
    public static function get_session_progress($sessionId, $courseId, $date_from, $date_to, $options)
856
    {
857
        $sessionId = intval($sessionId);
858
859
        $getAllSessions = false;
860
        if (empty($sessionId)) {
861
            $sessionId = 0;
862
            $getAllSessions = true;
863
        }
864
865
        //tables
866
        $session_course_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
867
        $user = Database::get_main_table(TABLE_MAIN_USER);
868
        $workTable = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
869
        $workTableAssignment = Database::get_course_table(TABLE_STUDENT_PUBLICATION_ASSIGNMENT);
870
        $tbl_course_lp = Database::get_course_table(TABLE_LP_MAIN);
871
        $wiki = Database::get_course_table(TABLE_WIKI);
872
        $table_stats_default = Database::get_main_table(TABLE_STATISTIC_TRACK_E_DEFAULT);
873
        $table_stats_access = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ACCESS);
874
875
        $course = api_get_course_info_by_id($courseId);
876
        $where = " WHERE c_id = '%s' AND s.status <> 2 ";
877
878
        $limit = null;
879
        if (!empty($options['limit'])) {
880
            $limit = " LIMIT " . $options['limit'];
881
        }
882
883
        if (!empty($options['where'])) {
884
            $where .= ' '.$options['where'];
885
        }
886
887
        $order = null;
888
        if (!empty($options['order'])) {
889
            $order = " ORDER BY " . $options['order'];
890
        }
891
892
        //TODO, fix create report without session
893
        $queryVariables = array($course['real_id']);
894
        if (!empty($sessionId)) {
895
            $where .= ' AND session_id = %s';
896
            $queryVariables[] = $sessionId;
897
            $sql = "SELECT
898
                        u.user_id, u.lastname, u.firstname, u.username,
899
                        u.email, s.c_id, s.session_id
900
                    FROM $session_course_user s
901
                    INNER JOIN $user u
902
                    ON u.user_id = s.user_id
903
                    $where $order $limit";
904
        } else {
905
            $sql = "SELECT
906
                        u.user_id, u.lastname, u.firstname, u.username,
907
                        u.email, s.c_id, s.session_id
908
                    FROM $session_course_user s
909
                    INNER JOIN $user u ON u.user_id = s.user_id
910
                    $where $order $limit";
911
        }
912
913
        $sql_query = vsprintf($sql, $queryVariables);
914
        $rs = Database::query($sql_query);
915
        while ($user = Database::fetch_array($rs)) {
916
            $users[$user['user_id']] = $user;
917
        }
918
919
        /**
920
         *  Lessons
921
         */
922
        $sql = "SELECT * FROM $tbl_course_lp WHERE c_id = %s ";  //AND session_id = %s
923
        $sql_query = sprintf($sql, $course['real_id']);
924
        $result = Database::query($sql_query);
925
        $arrLesson = array(array());
926
        while ($row = Database::fetch_array($result)) {
927
            if (empty($arrLesson[$row['session_id']]['lessons_total'])) {
928
                $arrLesson[$row['session_id']]['lessons_total'] = 1;
929
            } else {
930
                $arrLesson[$row['session_id']]['lessons_total'] ++;
931
            }
932
        }
933
934
        /**
935
         *  Exercises
936
         */
937
        $exercises = ExerciseLib::get_all_exercises($course, $sessionId, false, '', $getAllSessions);
938
        $exercises_total = count($exercises);
939
940
        /**
941
         *  Assignments
942
         */
943
        //total
944
        $params = [$course['real_id']];
945
        if ($getAllSessions) {
946
            $sql = "SELECT count(w.id) as count
947
                    FROM $workTable w
948
                    LEFT JOIN $workTableAssignment a
949
                    ON (a.publication_id = w.id AND a.c_id = w.c_id)
950
                    WHERE 
951
                        w.c_id = %s AND 
952
                        parent_id = 0 AND 
953
                        active IN (1, 0)";
954
        } else {
955
            $sql = "SELECT count(w.id) as count
956
                    FROM $workTable w
957
                    LEFT JOIN $workTableAssignment a
958
                    ON (a.publication_id = w.id AND a.c_id = w.c_id)
959
                    WHERE 
960
                        w.c_id = %s AND 
961
                        parent_id = 0 AND 
962
                        active IN (1, 0)";
963
964
            if (empty($sessionId)) {
965
                $sql .= ' AND w.session_id = NULL ';
966
            } else {
967
                $sql .= ' AND w.session_id = %s ';
968
                $params[] = $sessionId;
969
            }
970
        }
971
972
        $sql_query = vsprintf($sql, $params);
973
        $result = Database::query($sql_query);
974
        $row = Database::fetch_array($result);
975
        $assignments_total = $row['count'];
976
977
        /**
978
         * Wiki
979
         */
980
        if ($getAllSessions) {
981
            $sql = "SELECT count(distinct page_id)  as count FROM $wiki
982
                    WHERE c_id = %s";
983
        } else {
984
            $sql = "SELECT count(distinct page_id)  as count FROM $wiki
985
                    WHERE c_id = %s and session_id = %s";
986
        }
987
        $sql_query = sprintf($sql, $course['real_id'], $sessionId);
988
        $result = Database::query($sql_query);
989
        $row = Database::fetch_array($result);
990
        $wiki_total = $row['count'];
991
992
        /**
993
         * Surveys
994
         */
995
        $survey_user_list = array();
996
        $survey_list = SurveyManager::get_surveys($course['code'], $sessionId);
997
998
        $surveys_total = count($survey_list);
999 View Code Duplication
        foreach ($survey_list as $survey) {
0 ignored issues
show
Bug introduced by
The expression $survey_list of type false|array is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
1000
            $user_list = SurveyManager::get_people_who_filled_survey(
1001
                $survey['survey_id'],
1002
                false,
1003
                $course['real_id']
1004
            );
1005
            foreach ($user_list as $user_id) {
1006
                isset($survey_user_list[$user_id]) ? $survey_user_list[$user_id] ++ : $survey_user_list[$user_id] = 1;
1007
            }
1008
        }
1009
1010
        /**
1011
         * Forums
1012
         */
1013
        $forums_total = CourseManager::getCountForum(
1014
            $course['real_id'],
1015
            $sessionId,
1016
            $getAllSessions
1017
        );
1018
1019
        //process table info
1020
        foreach ($users as $user) {
1021
            //Course description
1022
            $sql = "SELECT count(*) as count
1023
                    FROM $table_stats_access
1024
                    WHERE access_tool = 'course_description'
1025
                    AND c_id = '%s'
1026
                    AND access_session_id = %s
1027
                    AND access_user_id = %s ";
1028
            $sql_query = sprintf($sql, $course['real_id'], $user['id_session'], $user['user_id']);
1029
1030
            $result = Database::query($sql_query);
1031
            $row = Database::fetch_array($result);
1032
            $course_description_progress = ($row['count'] > 0) ? 100 : 0;
1033
1034
            if (!empty($arrLesson[$user['id_session']]['lessons_total'])) {
1035
                $lessons_total = $arrLesson[$user['id_session']]['lessons_total'];
1036
            } else {
1037
                $lessons_total = !empty($arrLesson[0]['lessons_total']) ? $arrLesson[0]['lessons_total'] : 0;
1038
            }
1039
1040
            //Lessons
1041
            //TODO: Lessons done and left is calculated by progress per item in lesson, maybe we should calculate it only per completed lesson?
1042
            $lessons_progress = Tracking::get_avg_student_progress(
1043
                $user['user_id'],
1044
                $course['code'],
1045
                array(),
1046
                $user['id_session']
1047
            );
1048
            $lessons_done = ($lessons_progress * $lessons_total) / 100;
1049
            $lessons_left = $lessons_total - $lessons_done;
1050
1051
            //Exercises
1052
            $exercises_progress = str_replace('%', '', Tracking::get_exercise_student_progress($exercises, $user['user_id'], $course['real_id'], $user['id_session']));
1053
            $exercises_done = round(($exercises_progress * $exercises_total) / 100);
1054
            $exercises_left = $exercises_total - $exercises_done;
1055
1056
            //Assignments
1057
            $assignments_done = Tracking::count_student_assignments($user['user_id'], $course['code'], $user['id_session']);
1058
            $assignments_left = $assignments_total - $assignments_done;
1059
            if (!empty($assignments_total)) {
1060
                $assignments_progress = round((( $assignments_done * 100 ) / $assignments_total), 2);
1061
            } else {
1062
                $assignments_progress = 0;
1063
            }
1064
1065
            //Wiki
1066
            //total revisions per user
1067
            $sql = "SELECT count(*) as count
1068
                    FROM $wiki
1069
                    WHERE c_id = %s and session_id = %s and user_id = %s";
1070
            $sql_query = sprintf($sql, $course['real_id'], $user['id_session'], $user['user_id']);
1071
            $result = Database::query($sql_query);
1072
            $row = Database::fetch_array($result);
1073
            $wiki_revisions = $row['count'];
1074
            //count visited wiki pages
1075
            $sql = "SELECT count(distinct default_value) as count
1076
                    FROM $table_stats_default
1077
                    WHERE
1078
                        default_user_id = %s AND
1079
                        default_event_type = 'wiki_page_view' AND
1080
                        default_value_type = 'wiki_page_id' AND
1081
                        c_id = %s
1082
                    ";
1083
            $sql_query = sprintf($sql, $user['user_id'], $course['real_id']);
1084
            $result = Database::query($sql_query);
1085
            $row = Database::fetch_array($result);
1086
1087
            $wiki_read = $row['count'];
1088
            $wiki_unread = $wiki_total - $wiki_read;
1089
            if (!empty($wiki_total)) {
1090
                $wiki_progress = round((( $wiki_read * 100 ) / $wiki_total), 2);
1091
            } else {
1092
                $wiki_progress = 0;
1093
            }
1094
1095
            //Surveys
1096
            $surveys_done = (isset($survey_user_list[$user['user_id']]) ? $survey_user_list[$user['user_id']] : 0);
1097
            $surveys_left = $surveys_total - $surveys_done;
1098
            if (!empty($surveys_total)) {
1099
                $surveys_progress = round((( $surveys_done * 100 ) / $surveys_total), 2);
1100
            } else {
1101
                $surveys_progress = 0;
1102
            }
1103
1104
            //Forums
1105
            $forums_done = CourseManager::getCountForumPerUser(
1106
                $user['user_id'],
1107
                $course['real_id'],
1108
                $user['id_session']
1109
            );
1110
            $forums_left = $forums_total - $forums_done;
1111
            if (!empty($forums_total)) {
1112
                $forums_progress = round((( $forums_done * 100 ) / $forums_total), 2);
1113
            } else {
1114
                $forums_progress = 0;
1115
            }
1116
1117
            //Overall Total
1118
            $overall_total = ($course_description_progress + $exercises_progress + $forums_progress + $assignments_progress + $wiki_progress + $surveys_progress) / 6;
1119
1120
            $link = '<a href="' . api_get_path(WEB_CODE_PATH) . 'mySpace/myStudents.php?student=' . $user[0] . '&details=true&course=' . $course['code'] . '&id_session=' . $user['id_session'] . '"> %s </a>';
1121
            $linkForum = '<a href="' . api_get_path(WEB_CODE_PATH) . 'forum/index.php?cidReq=' . $course['code'] . '&id_session=' . $user['id_session'] . '"> %s </a>';
1122
            $linkWork = '<a href="' . api_get_path(WEB_CODE_PATH) . 'work/work.php?cidReq=' . $course['code'] . '&id_session=' . $user['id_session'] . '"> %s </a>';
1123
            $linkWiki = '<a href="' . api_get_path(WEB_CODE_PATH) . 'wiki/index.php?cidReq=' . $course['code'] . '&session_id=' . $user['id_session'] . '&action=statistics"> %s </a>';
1124
            $linkSurvey = '<a href="' . api_get_path(WEB_CODE_PATH) . 'survey/survey_list.php?cidReq=' . $course['code'] . '&id_session=' . $user['id_session'] . '"> %s </a>';
1125
1126
            $table[] = array(
1127
                'lastname' => $user[1],
1128
                'firstname' => $user[2],
1129
                'username' => $user[3],
1130
                #'profile'   => '',
1131
                'total' => round($overall_total, 2) . '%',
1132
                'courses' => sprintf($link, $course_description_progress . '%'),
1133
                'lessons' => sprintf($link, $lessons_progress . '%'),
1134
                'exercises' => sprintf($link, $exercises_progress . '%'),
1135
                'forums' => sprintf($link, $forums_progress . '%'),
1136
                'homeworks' => sprintf($link, $assignments_progress . '%'),
1137
                'wikis' => sprintf($link, $wiki_progress . '%'),
1138
                'surveys' => sprintf($link, $surveys_progress . '%'),
1139
                //course description
1140
                'course_description_progress' => $course_description_progress . '%',
1141
                //lessons
1142
                'lessons_total' => sprintf($link, $lessons_total),
1143
                'lessons_done' => sprintf($link, $lessons_done),
1144
                'lessons_left' => sprintf($link, $lessons_left),
1145
                'lessons_progress' => sprintf($link, $lessons_progress . '%'),
1146
                //exercises
1147
                'exercises_total' => sprintf($link, $exercises_total),
1148
                'exercises_done' => sprintf($link, $exercises_done),
1149
                'exercises_left' => sprintf($link, $exercises_left),
1150
                'exercises_progress' => sprintf($link, $exercises_progress . '%'),
1151
                //forums
1152
                'forums_total' => sprintf($linkForum, $forums_total),
1153
                'forums_done' => sprintf($linkForum, $forums_done),
1154
                'forums_left' => sprintf($linkForum, $forums_left),
1155
                'forums_progress' => sprintf($linkForum, $forums_progress . '%'),
1156
                //assignments
1157
                'assignments_total' => sprintf($linkWork, $assignments_total),
1158
                'assignments_done' => sprintf($linkWork, $assignments_done),
1159
                'assignments_left' => sprintf($linkWork, $assignments_left),
1160
                'assignments_progress' => sprintf($linkWork, $assignments_progress . '%'),
1161
                //wiki
1162
                'wiki_total' => sprintf($linkWiki, $wiki_total),
1163
                'wiki_revisions' => sprintf($linkWiki, $wiki_revisions),
1164
                'wiki_read' => sprintf($linkWiki, $wiki_read),
1165
                'wiki_unread' => sprintf($linkWiki, $wiki_unread),
1166
                'wiki_progress' => sprintf($linkWiki, $wiki_progress . '%'),
1167
                //survey
1168
                'surveys_total' => sprintf($linkSurvey, $surveys_total),
1169
                'surveys_done' => sprintf($linkSurvey, $surveys_done),
1170
                'surveys_left' => sprintf($linkSurvey, $surveys_left),
1171
                'surveys_progress' => sprintf($linkSurvey, $surveys_progress . '%'),
1172
            );
1173
        }
1174
1175
        return $table;
1176
    }
1177
1178
    /**
1179
     * @return int
1180
     */
1181 View Code Duplication
    public static function get_number_of_tracking_access_overview()
1182
    {
1183
        $table = Database :: get_main_table(TABLE_STATISTIC_TRACK_E_COURSE_ACCESS);
1184
        $sql = "SELECT COUNT(course_access_id) count FROM $table";
1185
        $result = Database::query($sql);
1186
        $row = Database::fetch_assoc($result);
1187
1188
        return $row['count'];
1189
    }
1190
1191
    /**
1192
     * Get the ip, total of clicks, login date and time logged in for all user, in one session
1193
     * @todo track_e_course_access table should have ip so we dont have to look for it in track_e_login
1194
     *
1195
     * @author César Perales <[email protected]>, Beeznest Team
1196
     * @version 1.9.6
1197
     */
1198
    public static function get_user_data_access_tracking_overview(
1199
        $sessionId,
1200
        $courseId,
1201
        $studentId = 0,
1202
        $profile = '',
1203
        $date_from = '',
1204
        $date_to = '',
1205
        $options
1206
    ) {
1207
        //escaping variables
1208
        $sessionId = intval($sessionId);
1209
        $courseId = intval($courseId);
1210
        $studentId = intval($studentId);
1211
        $profile = intval($profile);
1212
        $date_from = Database::escape_string($date_from);
1213
        $date_to = Database::escape_string($date_to);
1214
1215
        // database table definition
1216
        $user = Database :: get_main_table(TABLE_MAIN_USER);
1217
        $course = Database :: get_main_table(TABLE_MAIN_COURSE);
1218
        $track_e_login = Database :: get_main_table(TABLE_STATISTIC_TRACK_E_LOGIN);
1219
        $track_e_course_access = Database :: get_main_table(TABLE_STATISTIC_TRACK_E_COURSE_ACCESS);
1220
        $sessionTable = Database :: get_main_table(TABLE_MAIN_SESSION);
1221
1222
        global $export_csv;
1223
        if ($export_csv) {
1224
            $is_western_name_order = api_is_western_name_order(PERSON_NAME_DATA_EXPORT);
1225
        } else {
1226
            $is_western_name_order = api_is_western_name_order();
1227
        }
1228
1229
        $where = null;
1230
        if (isset($sessionId) && !empty($sessionId)) {
1231
            $where = sprintf(" WHERE a.session_id = %d", $sessionId);
1232
        }
1233
        if (isset($courseId) && !empty($courseId)) {
1234
            $where .= sprintf(" AND c.id = %d", $courseId);
1235
        }
1236
        if (isset($studentId) && !empty($studentId)) {
1237
            $where .= sprintf(" AND u.user_id = %d", $studentId);
1238
        }
1239
        if (isset($profile) && !empty($profile)) {
1240
            $where .= sprintf(" AND u.status = %d", $profile);
1241
        }
1242
        if (!empty($date_to) && !empty($date_from)) {
1243
            $where .= sprintf(
1244
                " AND a.login_course_date >= '%s 00:00:00'
1245
                 AND a.login_course_date <= '%s 23:59:59'",
1246
                $date_from,
1247
                $date_to
1248
            );
1249
        }
1250
1251
        $limit = null;
1252
        if (!empty($options['limit'])) {
1253
            $limit = " LIMIT " . $options['limit'];
1254
        }
1255
1256
        if (!empty($options['where'])) {
1257
            $where .= ' '.$options['where'];
1258
        }
1259
1260
        $order = null;
1261
        if (!empty($options['order'])) {
1262
            $order = " ORDER BY " . $options['order'];
1263
        }
1264
1265
        //TODO add course name
1266
        $sql = "SELECT
1267
                a.login_course_date ,
1268
                u.username ,
1269
                " . ($is_western_name_order ? "
1270
                    u.firstname,
1271
                    u.lastname,
1272
                    " : "
1273
                    u.lastname,
1274
                    u.firstname,
1275
                ") . "
1276
                a.logout_course_date,
1277
                a.counter,
1278
                c.title,
1279
                c.code,
1280
                u.user_id,
1281
                a.session_id
1282
            FROM $track_e_course_access a
1283
            INNER JOIN $user u ON a.user_id = u.user_id
1284
            INNER JOIN $course c ON a.c_id = c.id
1285
            $where $order $limit";
1286
        $result = Database::query(sprintf($sql, $sessionId, $courseId));
1287
1288
        $data = array();
1289
        while ($user = Database::fetch_assoc($result)) {
1290
            $data[] = $user;
1291
        }
1292
1293
        //foreach
1294
        foreach ($data as $key => $info) {
1295
            $sql = "SELECT
1296
                    name
1297
                    FROM $sessionTable
1298
                    WHERE
1299
                    id = {$info['session_id']}";
1300
            $result = Database::query($sql);
1301
            $session = Database::fetch_assoc($result);
1302
1303
            // building array to display
1304
            $return[] = array(
1305
                'user_id' => $info['user_id'],
1306
                'logindate' => $info['login_course_date'],
1307
                'username' => $info['username'],
1308
                'firstname' => $info['firstname'],
1309
                'lastname' => $info['lastname'],
1310
                'clicks' => $info['counter'], //+ $clicks[$info['user_id']],
1311
                'ip' => '',
1312
                'timeLoggedIn' => gmdate("H:i:s", strtotime($info['logout_course_date']) - strtotime($info['login_course_date'])),
1313
                'session' => $session['name']
1314
            );
1315
        }
1316
1317
        foreach ($return as $key => $info) {
1318
            //Search for ip, we do less querys if we iterate the final array
1319
            $sql = sprintf("SELECT user_ip FROM $track_e_login WHERE login_user_id = %d AND login_date < '%s' ORDER BY login_date DESC LIMIT 1", $info['user_id'], $info['logindate']); //TODO add select by user too
1320
            $result = Database::query($sql);
1321
            $ip = Database::fetch_assoc($result);
1322
            //if no ip founded, we search the closest higher ip
1323
            if (empty($ip['user_ip'])) {
1324
                $sql = sprintf("SELECT user_ip FROM $track_e_login WHERE login_user_id = %d AND login_date > '%s'  ORDER BY login_date ASC LIMIT 1", $info['user_id'], $info['logindate']); //TODO add select by user too
1325
                $result = Database::query($sql);
1326
                $ip = Database::fetch_assoc($result);
1327
            }
1328
            #add ip to final array
1329
            $return[$key]['ip'] = $ip['user_ip'];
1330
        }
1331
1332
        return $return;
1333
    }
1334
1335
    /**
1336
     * Creates a new course code based in given code
1337
     *
1338
     * @param string	$session_name
1339
     * <code>
1340
     * $wanted_code = 'curse' if there are in the DB codes like curse1 curse2 the function will return: course3
1341
     * if the course code doest not exist in the DB the same course code will be returned
1342
     * </code>
1343
     * @return string	wanted unused code
1344
     */
1345 View Code Duplication
    public static function generateNextSessionName($session_name)
1346
    {
1347
        $session_name_ok = !self::session_name_exists($session_name);
1348
        if (!$session_name_ok) {
1349
            $table = Database::get_main_table(TABLE_MAIN_SESSION);
1350
            $session_name = Database::escape_string($session_name);
1351
            $sql = "SELECT count(*) as count FROM $table
1352
                    WHERE name LIKE '$session_name%'";
1353
            $result = Database::query($sql);
1354
            if (Database::num_rows($result) > 0) {
1355
                $row = Database::fetch_array($result);
1356
                $count = $row['count'] + 1;
1357
                $session_name = $session_name . '_' . $count;
1358
                $result = self::session_name_exists($session_name);
1359
                if (!$result) {
1360
                    return $session_name;
1361
                }
1362
            }
1363
            return false;
1364
        }
1365
1366
        return $session_name;
1367
    }
1368
1369
    /**
1370
     * Edit a session
1371
     * @author Carlos Vargas from existing code
1372
     * @param integer   $id Session primary key
1373
     * @param string    $name
1374
     * @param string    $startDate
1375
     * @param string    $endDate
1376
     * @param string    $displayStartDate
1377
     * @param string    $displayEndDate
1378
     * @param string    $coachStartDate
1379
     * @param string    $coachEndDate
1380
     * @param integer   $coachId
1381
     * @param integer   $sessionCategoryId
1382
     * @param int       $visibility
1383
     * @param string    $description
1384
     * @param int       $showDescription
1385
     * @param int       $duration
1386
     * @param array     $extraFields
1387
     * @param int       $sessionAdminId
1388
     * @param boolean $sendSubscriptionNotification Optional.
1389
     *          Whether send a mail notification to users being subscribed
1390
     * @return mixed
1391
     */
1392
    public static function edit_session(
1393
        $id,
1394
        $name,
1395
        $startDate,
1396
        $endDate,
1397
        $displayStartDate,
1398
        $displayEndDate,
1399
        $coachStartDate,
1400
        $coachEndDate,
1401
        $coachId,
1402
        $sessionCategoryId,
1403
        $visibility,
1404
        $description = null,
1405
        $showDescription = 0,
1406
        $duration = null,
1407
        $extraFields = array(),
1408
        $sessionAdminId = 0,
1409
        $sendSubscriptionNotification = false
1410
    ) {
1411
        $coachId = intval($coachId);
1412
        $sessionCategoryId = intval($sessionCategoryId);
1413
        $visibility = intval($visibility);
1414
        $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
1415
1416
        if (empty($name)) {
1417
            Display::addFlash(
1418
                Display::return_message(get_lang('SessionNameIsRequired'), 'warning')
1419
            );
1420
1421
            return false;
1422
        } elseif (empty($coachId)) {
1423
            Display::addFlash(
1424
                Display::return_message(get_lang('CoachIsRequired'), 'warning')
1425
            );
1426
1427
            return false;
1428
        } elseif (!empty($startDate) && !api_is_valid_date($startDate, 'Y-m-d H:i') && !api_is_valid_date($startDate, 'Y-m-d H:i:s')) {
1429
            Display::addFlash(
1430
                Display::return_message(get_lang('InvalidStartDate'), 'warning')
1431
            );
1432
1433
            return false;
1434
        } elseif (!empty($endDate) && !api_is_valid_date($endDate, 'Y-m-d H:i') && !api_is_valid_date($endDate, 'Y-m-d H:i:s')) {
1435
            Display::addFlash(
1436
                Display::return_message(get_lang('InvalidEndDate'), 'warning')
1437
            );
1438
1439
            return false;
1440
        } elseif (!empty($startDate) && !empty($endDate) && $startDate >= $endDate) {
1441
            Display::addFlash(
1442
                Display::return_message(get_lang('StartDateShouldBeBeforeEndDate'), 'warning')
1443
            );
1444
1445
            return false;
1446
        } else {
1447
            $sessionInfo = self::get_session_by_name($name);
1448
            $exists = false;
1449
1450
            if (!empty($sessionInfo)) {
1451
                if ($sessionInfo['id'] != $id) {
1452
                    $exists = true;
1453
                }
1454
            }
1455
1456
            if ($exists) {
1457
                Display::addFlash(
1458
                    Display::return_message(get_lang('SessionNameAlreadyExists'), 'warning')
1459
                );
1460
1461
                return false;
1462
            } else {
1463
                $values = [
1464
                    'name' => $name,
1465
                    'duration' => $duration,
1466
                    'id_coach' => $coachId,
1467
                    'description'=> $description,
1468
                    'show_description' => intval($showDescription),
1469
                    'visibility' => $visibility,
1470
                    'send_subscription_notification' => $sendSubscriptionNotification,
1471
                    'access_start_date' => null,
1472
                    'access_end_date' => null,
1473
                    'display_start_date' => null,
1474
                    'display_end_date' => null,
1475
                    'coach_access_start_date' => null,
1476
                    'coach_access_end_date' => null
1477
                ];
1478
1479
                if (!empty($sessionAdminId)) {
1480
                    $values['session_admin_id'] = $sessionAdminId;
1481
                }
1482
1483
                if (!empty($startDate)) {
1484
                    $values['access_start_date'] = api_get_utc_datetime($startDate);
1485
                }
1486
1487
                if (!empty($endDate)) {
1488
                    $values['access_end_date'] = api_get_utc_datetime($endDate);
1489
                }
1490
1491
                if (!empty($displayStartDate)) {
1492
                    $values['display_start_date'] = api_get_utc_datetime($displayStartDate);
1493
                }
1494
1495
                if (!empty($displayEndDate)) {
1496
                    $values['display_end_date'] = api_get_utc_datetime($displayEndDate);
1497
                }
1498
1499
                if (!empty($coachStartDate)) {
1500
                    $values['coach_access_start_date'] = api_get_utc_datetime($coachStartDate);
1501
                }
1502
                if (!empty($coachEndDate)) {
1503
                    $values['coach_access_end_date'] = api_get_utc_datetime($coachEndDate);
1504
                }
1505
1506
                if (!empty($sessionCategoryId)) {
1507
                    $values['session_category_id'] = $sessionCategoryId;
1508
                } else {
1509
                    $values['session_category_id'] = null;
1510
                }
1511
1512
                Database::update(
1513
                    $tbl_session,
1514
                    $values,
1515
                    array('id = ?' => $id)
1516
                );
1517
1518
                if (!empty($extraFields)) {
1519
                    $extraFields['item_id'] = $id;
1520
                    $sessionFieldValue = new ExtraFieldValue('session');
1521
                    $sessionFieldValue->saveFieldValues($extraFields);
1522
                }
1523
1524
                return $id;
1525
            }
1526
        }
1527
    }
1528
1529
    /**
1530
     * Delete session
1531
     * @author Carlos Vargas  from existing code
1532
     * @param	array	$id_checked an array to delete sessions
1533
     * @param   boolean  $from_ws optional, true if the function is called
1534
     * by a webservice, false otherwise.
1535
     * @return	void	Nothing, or false on error
1536
     * */
1537
    public static function delete($id_checked, $from_ws = false)
1538
    {
1539
        $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
1540
        $tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
1541
        $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
1542
        $tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
1543
        $tbl_url_session = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
1544
        $tbl_item_properties = Database::get_course_table(TABLE_ITEM_PROPERTY);
1545
        $tbl_student_publication = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
1546
        $tbl_student_publication_assignment = Database :: get_course_table(TABLE_STUDENT_PUBLICATION_ASSIGNMENT);
1547
        $ticket = Database::get_main_table(TABLE_TICKET_TICKET);
1548
        $em = Database::getManager();
1549
1550
        $userId = api_get_user_id();
1551
1552
        /** @var \Chamilo\CoreBundle\Entity\Repository\SequenceRepository $repo */
1553
        $repo = Database::getManager()->getRepository('ChamiloCoreBundle:SequenceResource');
1554
        $sequenceResourse = $repo->findRequirementForResource(
1555
            $id_checked,
1556
            \Chamilo\CoreBundle\Entity\SequenceResource::SESSION_TYPE
1557
        );
1558
1559
        if ($sequenceResourse) {
1560
            Display::addFlash(Display::return_message(get_lang('ThereIsASequenceResourceLinkedToThisSessionYouNeedToDeleteItFirst'), 'error'));
1561
            return false;
1562
        }
1563
1564
        if (is_array($id_checked)) {
1565
            foreach ($id_checked as $sessionId) {
1566
                self::delete($sessionId);
1567
            }
1568
        } else {
1569
            $id_checked = intval($id_checked);
1570
        }
1571
1572
        if (SessionManager::allowed($id_checked) && !$from_ws) {
0 ignored issues
show
Bug introduced by
It seems like $id_checked defined by parameter $id_checked on line 1537 can also be of type array; however, SessionManager::allowed() does only seem to accept integer, maybe add an additional type check?

This check looks at variables that have been passed in as parameters and are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
1573
            $qb = $em
1574
                ->createQuery('
1575
                    SELECT s.sessionAdminId FROM ChamiloCoreBundle:Session s
1576
                    WHERE s.id = ?1
1577
                ')
1578
                ->setParameter(1, $id_checked);
1579
1580
            $res = $qb->getSingleScalarResult();
1581
1582
            if ($res != $userId && !api_is_platform_admin()) {
1583
                api_not_allowed(true);
1584
            }
1585
        }
1586
1587
        // Delete documents inside a session
1588
        $courses = SessionManager::getCoursesInSession($id_checked);
1589
        foreach ($courses as $courseId) {
1590
            $courseInfo = api_get_course_info_by_id($courseId);
1591
            DocumentManager::deleteDocumentsFromSession($courseInfo, $id_checked);
0 ignored issues
show
Bug introduced by
It seems like $id_checked defined by parameter $id_checked on line 1537 can also be of type array; however, DocumentManager::deleteDocumentsFromSession() does only seem to accept integer, maybe add an additional type check?

This check looks at variables that have been passed in as parameters and are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
1592
1593
            $works = Database::select(
1594
                '*',
1595
                $tbl_student_publication,
1596
                [
1597
                    'where' => ['session_id = ? AND c_id = ?' => [$id_checked, $courseId]]
1598
                ]
1599
            );
1600
1601
            $currentCourseRepositorySys = api_get_path(SYS_COURSE_PATH).$courseInfo['path'].'/';
1602
1603
            foreach ($works as $index => $work) {
1604
                if ($work['filetype'] = 'folder') {
1605
                    Database::query("DELETE FROM $tbl_student_publication_assignment WHERE publication_id = $index");
1606
                }
1607
                my_delete($currentCourseRepositorySys.'/'.$work['url']);
1608
            }
1609
        }
1610
1611
        Database::query("DELETE FROM $tbl_student_publication WHERE session_id IN($id_checked)");
1612
        Database::query("DELETE FROM $tbl_session_rel_course WHERE session_id IN($id_checked)");
1613
        Database::query("DELETE FROM $tbl_session_rel_course_rel_user WHERE session_id IN($id_checked)");
1614
        Database::query("DELETE FROM $tbl_session_rel_user WHERE session_id IN($id_checked)");
1615
        Database::query("DELETE FROM $tbl_item_properties WHERE session_id IN ($id_checked)");
1616
        Database::query("DELETE FROM $tbl_url_session WHERE session_id IN($id_checked)");
1617
1618
        $sql = "UPDATE $ticket SET session_id = NULL WHERE session_id IN ($id_checked)";
1619
        Database::query($sql);
1620
1621
        $sql = "DELETE FROM $tbl_session WHERE id IN ($id_checked)";
1622
        Database::query($sql);
1623
1624
        $extraFieldValue = new ExtraFieldValue('session');
1625
        $extraFieldValue->deleteValuesByItem($id_checked);
0 ignored issues
show
Bug introduced by
It seems like $id_checked defined by parameter $id_checked on line 1537 can also be of type array; however, ExtraFieldValue::deleteValuesByItem() does only seem to accept integer, maybe add an additional type check?

This check looks at variables that have been passed in as parameters and are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
1626
1627
        $repo->deleteResource(
1628
            $id_checked,
0 ignored issues
show
Bug introduced by
It seems like $id_checked defined by parameter $id_checked on line 1537 can also be of type array; however, Chamilo\CoreBundle\Entit...itory::deleteResource() does only seem to accept integer, maybe add an additional type check?

This check looks at variables that have been passed in as parameters and are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
1629
            \Chamilo\CoreBundle\Entity\SequenceResource::SESSION_TYPE
1630
        );
1631
1632
        // Add event to system log
1633
        Event::addEvent(
1634
            LOG_SESSION_DELETE,
1635
            LOG_SESSION_ID,
1636
            $id_checked,
1637
            api_get_utc_datetime(),
1638
            $userId
1639
        );
1640
1641
        return true;
1642
    }
1643
1644
    /**
1645
     * @param int $id promotion id
1646
     *
1647
     * @return bool
1648
     */
1649 View Code Duplication
    public static function clear_session_ref_promotion($id)
1650
    {
1651
        $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
1652
        $id = intval($id);
1653
        $sql = "UPDATE $tbl_session 
1654
                SET promotion_id = 0
1655
                WHERE promotion_id = $id";
1656
        if (Database::query($sql)) {
1657
            return true;
1658
        } else {
1659
            return false;
1660
        }
1661
    }
1662
1663
    /**
1664
     * Subscribes students to the given session and optionally (default) unsubscribes previous users
1665
     *
1666
     * @author Carlos Vargas from existing code
1667
     * @author Julio Montoya. Cleaning code.
1668
     * @param int $id_session
1669
     * @param array $user_list
1670
     * @param int $session_visibility
1671
     * @param bool $empty_users
1672
     * @return bool
1673
     */
1674
    public static function subscribe_users_to_session(
1675
        $id_session,
1676
        $user_list,
1677
        $session_visibility = SESSION_VISIBLE_READ_ONLY,
1678
        $empty_users = true
1679
    ) {
1680
        if ($id_session != strval(intval($id_session))) {
1681
            return false;
1682
        }
1683
1684
        foreach ($user_list as $intUser) {
1685
            if ($intUser != strval(intval($intUser))) {
1686
                return false;
1687
            }
1688
        }
1689
1690
        $tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
1691
        $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
1692
        $tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
1693
        $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
1694
1695
        $entityManager = Database::getManager();
1696
        $session = $entityManager->find('ChamiloCoreBundle:Session', $id_session);
1697
1698
        // from function parameter
1699
        if (empty($session_visibility)) {
1700
            $session_visibility = $session->getVisibility();
1701
            //default status loaded if empty
1702
            // by default readonly 1
1703
            if (empty($session_visibility)) {
1704
                $session_visibility = SESSION_VISIBLE_READ_ONLY;
1705
            }
1706
        } else {
1707
            if (!in_array($session_visibility, array(SESSION_VISIBLE_READ_ONLY, SESSION_VISIBLE, SESSION_INVISIBLE))) {
1708
                $session_visibility = SESSION_VISIBLE_READ_ONLY;
1709
            }
1710
        }
1711
1712
        $sql = "SELECT user_id FROM $tbl_session_rel_course_rel_user
1713
                WHERE session_id = $id_session AND status = 0";
1714
        $result = Database::query($sql);
1715
        $existingUsers = array();
1716
        while ($row = Database::fetch_array($result)) {
1717
            $existingUsers[] = $row['user_id'];
1718
        }
1719
1720
        $sql = "SELECT c_id FROM $tbl_session_rel_course
1721
                WHERE session_id = $id_session";
1722
        $result = Database::query($sql);
1723
        $course_list = array();
1724
        while ($row = Database::fetch_array($result)) {
1725
            $course_list[] = $row['c_id'];
1726
        }
1727
1728
        if ($session->getSendSubscriptionNotification() &&
1729
            is_array($user_list)
1730
        ) {
1731
            // Sending emails only
1732
            foreach ($user_list as $user_id) {
1733
                if (in_array($user_id, $existingUsers)) {
1734
                    continue;
1735
                }
1736
1737
                $tplSubject = new Template(null, false, false, false, false, false);
1738
                $layoutSubject = $tplSubject->get_template(
1739
                    'mail/subject_subscription_to_session_confirmation.tpl'
1740
                );
1741
                $subject = $tplSubject->fetch($layoutSubject);
1742
1743
                $user_info = api_get_user_info($user_id);
1744
1745
                $tplContent = new Template(null, false, false, false, false, false);
1746
                // Variables for default template
1747
                $tplContent->assign(
1748
                    'complete_name',
1749
                    stripslashes($user_info['complete_name'])
1750
                );
1751
                $tplContent->assign('session_name', $session->getName());
1752
                $tplContent->assign(
1753
                    'session_coach',
1754
                    $session->getGeneralCoach()->getCompleteName()
1755
                );
1756
                $layoutContent = $tplContent->get_template(
1757
                    'mail/content_subscription_to_session_confirmation.tpl'
1758
                );
1759
                $content = $tplContent->fetch($layoutContent);
1760
1761
                api_mail_html(
1762
                    $user_info['complete_name'],
1763
                    $user_info['mail'],
1764
                    $subject,
1765
                    $content,
1766
                    api_get_person_name(
1767
                        api_get_setting('administratorName'),
1768
                        api_get_setting('administratorSurname')
1769
                    ),
1770
                    api_get_setting('emailAdministrator')
1771
                );
1772
            }
1773
        }
1774
1775
        foreach ($course_list as $courseId) {
1776
            // for each course in the session
1777
            $nbr_users = 0;
1778
            $courseId = intval($courseId);
1779
1780
            $sql = "SELECT DISTINCT user_id
1781
                    FROM $tbl_session_rel_course_rel_user
1782
                    WHERE
1783
                        session_id = $id_session AND
1784
                        c_id = $courseId AND
1785
                        status = 0
1786
                    ";
1787
            $result = Database::query($sql);
1788
            $existingUsers = array();
1789
            while ($row = Database::fetch_array($result)) {
1790
                $existingUsers[] = $row['user_id'];
1791
            }
1792
1793
            // Delete existing users
1794 View Code Duplication
            if ($empty_users) {
1795
                foreach ($existingUsers as $existing_user) {
1796
                    if (!in_array($existing_user, $user_list)) {
1797
                        $sql = "DELETE FROM $tbl_session_rel_course_rel_user
1798
                                WHERE
1799
                                    session_id = $id_session AND
1800
                                    c_id = $courseId AND
1801
                                    user_id = $existing_user AND
1802
                                    status = 0 ";
1803
                        $result = Database::query($sql);
1804
1805
                        Event::addEvent(
1806
                            LOG_SESSION_DELETE_USER_COURSE,
1807
                            LOG_USER_ID,
1808
                            $existing_user,
1809
                            api_get_utc_datetime(),
1810
                            api_get_user_id(),
1811
                            $courseId,
1812
                            $id_session
1813
                        );
1814
1815
                        if (Database::affected_rows($result)) {
1816
                            $nbr_users--;
1817
                        }
1818
                    }
1819
                }
1820
            }
1821
1822
            // Replace with this new function
1823
            // insert new users into session_rel_course_rel_user and ignore if they already exist
1824
1825
            foreach ($user_list as $enreg_user) {
1826 View Code Duplication
                if (!in_array($enreg_user, $existingUsers)) {
1827
                    $enreg_user = Database::escape_string($enreg_user);
1828
                    $sql = "INSERT IGNORE INTO $tbl_session_rel_course_rel_user (session_id, c_id, user_id, visibility, status)
1829
                            VALUES($id_session, $courseId, $enreg_user, $session_visibility, 0)";
1830
                    $result = Database::query($sql);
1831
1832
                    Event::addEvent(
1833
                        LOG_SESSION_ADD_USER_COURSE,
1834
                        LOG_USER_ID,
1835
                        $enreg_user,
1836
                        api_get_utc_datetime(),
1837
                        api_get_user_id(),
1838
                        $courseId,
1839
                        $id_session
1840
                    );
1841
1842
                    if (Database::affected_rows($result)) {
1843
1844
                        $nbr_users++;
1845
                    }
1846
                }
1847
            }
1848
1849
            // Count users in this session-course relation
1850
            $sql = "SELECT COUNT(user_id) as nbUsers
1851
                    FROM $tbl_session_rel_course_rel_user
1852
                    WHERE session_id = $id_session AND c_id = $courseId AND status<>2";
1853
            $rs = Database::query($sql);
1854
            list($nbr_users) = Database::fetch_array($rs);
0 ignored issues
show
Bug introduced by
It seems like $rs can be null; however, fetch_array() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
1855
            // update the session-course relation to add the users total
1856
            $sql = "UPDATE $tbl_session_rel_course SET nbr_users = $nbr_users
1857
                    WHERE session_id = $id_session AND c_id = $courseId";
1858
            Database::query($sql);
1859
        }
1860
1861
        // Delete users from the session
1862
        if ($empty_users === true) {
1863
            $sql = "DELETE FROM $tbl_session_rel_user
1864
                    WHERE session_id = $id_session AND relation_type<>" . SESSION_RELATION_TYPE_RRHH . "";
1865
            Database::query($sql);
1866
        }
1867
1868
        // Insert missing users into session
1869
        $nbr_users = 0;
1870
1871
        foreach ($user_list as $enreg_user) {
1872
            $enreg_user = Database::escape_string($enreg_user);
1873
            $nbr_users++;
1874
            $sql = "INSERT IGNORE INTO $tbl_session_rel_user (relation_type, session_id, user_id, registered_at)
1875
                    VALUES (0, $id_session, $enreg_user, '" . api_get_utc_datetime() . "')";
1876
            Database::query($sql);
1877
        }
1878
1879
        // update number of users in the session
1880
        $nbr_users = count($user_list);
1881
        if ($empty_users) {
1882
            // update number of users in the session
1883
            $sql = "UPDATE $tbl_session SET nbr_users= $nbr_users
1884
                    WHERE id = $id_session ";
1885
            Database::query($sql);
1886
        } else {
1887
            $sql = "UPDATE $tbl_session SET nbr_users = nbr_users + $nbr_users
1888
                    WHERE id = $id_session";
1889
            Database::query($sql);
1890
        }
1891
    }
1892
1893
    /**
1894
     * Returns user list of the current users subscribed in the course-session
1895
     * @param int $sessionId
1896
     * @param array $courseInfo
1897
     * @param int $status
1898
     *
1899
     * @return array
1900
     */
1901
    public static function getUsersByCourseSession(
1902
        $sessionId,
1903
        $courseInfo,
1904
        $status = null
1905
    ) {
1906
        $sessionId = intval($sessionId);
1907
        $courseCode = $courseInfo['code'];
1908
        $courseId = $courseInfo['real_id'];
1909
1910
        if (empty($sessionId) || empty($courseCode)) {
1911
            return array();
1912
        }
1913
1914
        $statusCondition = null;
1915 View Code Duplication
        if (isset($status) && !is_null($status)) {
1916
            $status = intval($status);
1917
            $statusCondition = " AND status = $status";
1918
        }
1919
1920
        $table = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
1921
1922
        $sql = "SELECT DISTINCT user_id
1923
                FROM $table
1924
                WHERE
1925
                    session_id = $sessionId AND
1926
                    c_id = $courseId
1927
                    $statusCondition
1928
                ";
1929
        $result = Database::query($sql);
1930
        $existingUsers = array();
1931
        while ($row = Database::fetch_array($result)) {
1932
            $existingUsers[] = $row['user_id'];
1933
        }
1934
1935
        return $existingUsers;
1936
    }
1937
1938
    /**
1939
     * Remove a list of users from a course-session
1940
     * @param array $userList
1941
     * @param int $sessionId
1942
     * @param array $courseInfo
1943
     * @param int $status
1944
     * @param bool $updateTotal
1945
     * @return bool
1946
     */
1947
    public static function removeUsersFromCourseSession(
1948
        $userList,
1949
        $sessionId,
1950
        $courseInfo,
1951
        $status = null,
1952
        $updateTotal = true
1953
    ) {
1954
        $table = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
1955
        $tableSessionCourse = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
1956
        $sessionId = intval($sessionId);
1957
1958
        if (empty($sessionId) || empty($userList) || empty($courseInfo)) {
1959
            return false;
1960
        }
1961
1962
        is_array($courseInfo) ? $courseId = $courseInfo['real_id'] : $courseId = $courseInfo;
1963
1964
        $statusCondition = null;
1965 View Code Duplication
        if (isset($status) && !is_null($status)) {
1966
            $status = intval($status);
1967
            $statusCondition  = " AND status = $status";
1968
        }
1969
1970
        foreach ($userList as $userId) {
1971
            $userId = intval($userId);
1972
            $sql = "DELETE FROM $table
1973
                    WHERE
1974
                        session_id = $sessionId AND
1975
                        c_id = $courseId AND
1976
                        user_id = $userId
1977
                        $statusCondition
1978
                    ";
1979
            Database::query($sql);
1980
        }
1981
1982
        if ($updateTotal) {
1983
            // Count users in this session-course relation
1984
            $sql = "SELECT COUNT(user_id) as nbUsers
1985
                    FROM $table
1986
                    WHERE
1987
                        session_id = $sessionId AND
1988
                        c_id = $courseId AND
1989
                        status <> 2";
1990
            $result = Database::query($sql);
1991
            list($userCount) = Database::fetch_array($result);
0 ignored issues
show
Bug introduced by
It seems like $result can be null; however, fetch_array() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
1992
1993
            // update the session-course relation to add the users total
1994
            $sql = "UPDATE $tableSessionCourse
1995
                    SET nbr_users = $userCount
1996
                    WHERE
1997
                        session_id = $sessionId AND
1998
                        c_id = $courseId";
1999
            Database::query($sql);
2000
        }
2001
    }
2002
2003
    /**
2004
     * Subscribe a user to an specific course inside a session.
2005
     *
2006
     * @param array $user_list
2007
     * @param int $session_id
2008
     * @param string $course_code
2009
     * @param int $session_visibility
2010
     * @param bool $removeUsersNotInList
2011
     * @return bool
2012
     */
2013
    public static function subscribe_users_to_session_course(
2014
        $user_list,
2015
        $session_id,
2016
        $course_code,
2017
        $session_visibility = SESSION_VISIBLE_READ_ONLY,
2018
        $removeUsersNotInList = false
2019
    ) {
2020
        $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
2021
        $tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
2022
        $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
2023
        $tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
2024
2025
        if (empty($session_id) || empty($course_code)) {
2026
            return false;
2027
        }
2028
2029
        $session_id = intval($session_id);
2030
        $course_code = Database::escape_string($course_code);
2031
        $courseInfo = api_get_course_info($course_code);
2032
        $courseId = $courseInfo['real_id'];
2033
2034
        $session_visibility = intval($session_visibility);
2035
2036
        if ($removeUsersNotInList) {
2037
2038
            $currentUsers = self::getUsersByCourseSession($session_id, $courseInfo, 0);
2039
2040
            if (!empty($user_list)) {
2041
                $userToDelete = array_diff($currentUsers, $user_list);
2042
            } else {
2043
                $userToDelete = $currentUsers;
2044
            }
2045
2046
            if (!empty($userToDelete)) {
2047
                self::removeUsersFromCourseSession(
2048
                    $userToDelete,
2049
                    $session_id,
2050
                    $courseInfo,
2051
                    0,
2052
                    true
2053
                );
2054
            }
2055
        }
2056
2057
        $nbr_users = 0;
2058
        foreach ($user_list as $enreg_user) {
2059
            $enreg_user = intval($enreg_user);
2060
            // Checking if user exists in session - course - user table.
2061
            $sql = "SELECT count(user_id) as count
2062
                    FROM $tbl_session_rel_course_rel_user
2063
                    WHERE
2064
                        session_id = $session_id AND
2065
                        c_id = $courseId and
2066
                        user_id = $enreg_user ";
2067
            $result = Database::query($sql);
2068
            $count = 0;
2069
2070
            if (Database::num_rows($result) > 0) {
2071
                $row = Database::fetch_array($result, 'ASSOC');
2072
                $count = $row['count'];
2073
            }
2074
2075
            if ($count == 0) {
2076
                $sql = "INSERT IGNORE INTO $tbl_session_rel_course_rel_user (session_id, c_id, user_id, visibility)
2077
                        VALUES ($session_id, $courseId, $enreg_user, $session_visibility)";
2078
                $result = Database::query($sql);
2079
                if (Database::affected_rows($result)) {
2080
                    $nbr_users++;
2081
                }
2082
            }
2083
2084
            // Checking if user exists in session - user table.
2085
            $sql = "SELECT count(user_id) as count
2086
                    FROM $tbl_session_rel_user
2087
                    WHERE session_id = $session_id AND user_id = $enreg_user ";
2088
            $result = Database::query($sql);
2089
            $count = 0;
2090
2091
            if (Database::num_rows($result) > 0) {
2092
                $row = Database::fetch_array($result, 'ASSOC');
2093
                $count = $row['count'];
2094
            }
2095
2096 View Code Duplication
            if (empty($count)) {
2097
                // If user is not registered to a session then add it.
2098
                $sql = "INSERT IGNORE INTO $tbl_session_rel_user (session_id, user_id, registered_at)
2099
                        VALUES ($session_id, $enreg_user, '" . api_get_utc_datetime() . "')";
2100
                Database::query($sql);
2101
2102
                $sql = "UPDATE $tbl_session SET nbr_users = nbr_users + 1
2103
                        WHERE id = $session_id ";
2104
                Database::query($sql);
2105
            }
2106
        }
2107
2108
        // count users in this session-course relation
2109
        $sql = "SELECT COUNT(user_id) as nbUsers
2110
                FROM $tbl_session_rel_course_rel_user
2111
                WHERE session_id = $session_id AND c_id = $courseId AND status <> 2";
2112
        $rs = Database::query($sql);
2113
        list($nbr_users) = Database::fetch_array($rs);
0 ignored issues
show
Bug introduced by
It seems like $rs can be null; however, fetch_array() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
2114
        // update the session-course relation to add the users total
2115
        $sql = "UPDATE $tbl_session_rel_course
2116
                SET nbr_users = $nbr_users
2117
                WHERE session_id = $session_id AND c_id = $courseId";
2118
        Database::query($sql);
2119
    }
2120
2121
    /**
2122
     * Unsubscribe user from session
2123
     *
2124
     * @param int Session id
2125
     * @param int User id
2126
     * @return bool True in case of success, false in case of error
2127
     */
2128
    public static function unsubscribe_user_from_session($session_id, $user_id)
2129
    {
2130
        $session_id = (int) $session_id;
2131
        $user_id = (int) $user_id;
2132
2133
        $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
2134
        $tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
2135
        $tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
2136
        $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
2137
2138
        $sql = "DELETE FROM $tbl_session_rel_user
2139
                WHERE
2140
                    session_id = $session_id AND
2141
                    user_id = $user_id AND
2142
                    relation_type <> " . SESSION_RELATION_TYPE_RRHH . "";
2143
        $result = Database::query($sql);
2144
        $return = Database::affected_rows($result);
2145
2146
        // Update number of users
2147
        $sql = "UPDATE $tbl_session
2148
                SET nbr_users = nbr_users - $return
2149
                WHERE id = $session_id ";
2150
        Database::query($sql);
2151
2152
        // Get the list of courses related to this session
2153
        $course_list = SessionManager::get_course_list_by_session_id($session_id);
2154
2155
        if (!empty($course_list)) {
2156
            foreach ($course_list as $course) {
0 ignored issues
show
Bug introduced by
The expression $course_list of type integer|array is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
2157
                $courseId = $course['id'];
2158
                // Delete user from course
2159
                $sql = "DELETE FROM $tbl_session_rel_course_rel_user
2160
                        WHERE session_id = $session_id AND c_id = $courseId AND user_id = $user_id";
2161
                $result = Database::query($sql);
2162
2163
                Event::addEvent(
2164
                    LOG_SESSION_DELETE_USER_COURSE,
2165
                    LOG_USER_ID,
2166
                    $user_id,
2167
                    api_get_utc_datetime(),
2168
                    api_get_user_id(),
2169
                    $courseId,
2170
                    $session_id
2171
                );
2172
2173
                if (Database::affected_rows($result)) {
2174
                    // Update number of users in this relation
2175
                    $sql = "UPDATE $tbl_session_rel_course SET 
2176
                            nbr_users = nbr_users - 1
2177
                            WHERE session_id = $session_id AND c_id = $courseId";
2178
                    Database::query($sql);
2179
                }
2180
            }
2181
        }
2182
2183
        return true;
2184
    }
2185
2186
    /**
2187
     * Subscribes courses to the given session and optionally (default)
2188
     * unsubscribes previous users
2189
     * @author Carlos Vargas from existing code
2190
     * @param	int		$sessionId
2191
     * @param	array	$courseList List of courses int ids
2192
     * @param	bool	$removeExistingCoursesWithUsers Whether to unsubscribe
2193
     * existing courses and users (true, default) or not (false)
2194
     * @param $copyEvaluation from base course to session course
2195
     * @return	void	Nothing, or false on error
2196
     * */
2197
    public static function add_courses_to_session(
2198
        $sessionId,
2199
        $courseList,
2200
        $removeExistingCoursesWithUsers = true,
2201
        $copyEvaluation = false
2202
    ) {
2203
        $sessionId = intval($sessionId);
2204
2205
        if (empty($sessionId) || empty($courseList)) {
2206
            return false;
2207
        }
2208
2209
        $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
2210
        $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
2211
        $tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
2212
        $tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
2213
2214
        // Get list of courses subscribed to this session
2215
        $sql = "SELECT c_id
2216
                FROM $tbl_session_rel_course
2217
                WHERE session_id = $sessionId";
2218
        $rs = Database::query($sql);
2219
        $existingCourses = Database::store_result($rs);
2220
        $nbr_courses = count($existingCourses);
2221
2222
        // Get list of users subscribed to this session
2223
        $sql = "SELECT user_id
2224
                FROM $tbl_session_rel_user
2225
                WHERE
2226
                    session_id = $sessionId AND
2227
                    relation_type<>" . SESSION_RELATION_TYPE_RRHH;
2228
        $result = Database::query($sql);
2229
        $user_list = Database::store_result($result);
2230
2231
        // Remove existing courses from the session.
2232
        if ($removeExistingCoursesWithUsers === true && !empty($existingCourses)) {
2233
            foreach ($existingCourses as $existingCourse) {
2234
                if (!in_array($existingCourse['c_id'], $courseList)) {
2235
2236
                    $sql = "DELETE FROM $tbl_session_rel_course
2237
                            WHERE
2238
                                c_id = " . $existingCourse['c_id'] . " AND
2239
                                session_id = $sessionId";
2240
                    Database::query($sql);
2241
2242
                    $sql = "DELETE FROM $tbl_session_rel_course_rel_user
2243
                            WHERE
2244
                                c_id = ".$existingCourse['c_id']." AND
2245
                                session_id = $sessionId";
2246
                    Database::query($sql);
2247
2248
                    Event::addEvent(
2249
                        LOG_SESSION_DELETE_COURSE,
2250
                        LOG_COURSE_ID,
2251
                        $existingCourse['c_id'],
2252
                        api_get_utc_datetime(),
2253
                        api_get_user_id(),
2254
                        $existingCourse['c_id'],
2255
                        $sessionId
2256
                    );
2257
2258
                    CourseManager::remove_course_ranking(
2259
                        $existingCourse['c_id'],
2260
                        $sessionId
2261
                    );
2262
2263
                    $nbr_courses--;
2264
                }
2265
            }
2266
        }
2267
2268
        // Pass through the courses list we want to add to the session
2269
        foreach ($courseList as $courseId) {
2270
            $courseInfo = api_get_course_info_by_id($courseId);
2271
2272
            // If course doesn't exists continue!
2273
            if (empty($courseInfo)) {
2274
                continue;
2275
            }
2276
2277
            $exists = false;
2278
            // check if the course we want to add is already subscribed
2279
            foreach ($existingCourses as $existingCourse) {
2280
                if ($courseId == $existingCourse['c_id']) {
2281
                    $exists = true;
2282
                }
2283
            }
2284
2285
            if (!$exists) {
2286
                // Copy gradebook categories and links (from base course)
2287
                // to the new course session
2288
                if ($copyEvaluation) {
2289
                    $cats = Category::load(null, null, $courseInfo['code']);
2290
                    if (!empty($cats)) {
2291
                        $categoryIdList = [];
2292
                        /** @var Category $cat */
2293
                        foreach ($cats as $cat) {
2294
                            $categoryIdList[$cat->get_id()] = $cat->get_id();
2295
                        }
2296
                        $newCategoryIdList = [];
2297
                        foreach ($cats as $cat) {
2298
                            $links = $cat->get_links(null, false, $courseInfo['code'], 0);
2299
2300
                            $cat->set_session_id($sessionId);
2301
                            $oldCategoryId= $cat->get_id();
2302
                            $newId = $cat->add();
2303
                            $newCategoryIdList[$oldCategoryId] = $newId;
2304
                            $parentId = $cat->get_parent_id();
2305
2306
                            if (!empty($parentId)) {
2307
                                $newParentId = $newCategoryIdList[$parentId];
2308
                                $cat->set_parent_id($newParentId);
2309
                                $cat->save();
2310
                            }
2311
2312
                            /** @var AbstractLink $link */
2313
                            foreach ($links as $link) {
2314
                                $newCategoryId = $newCategoryIdList[$link->get_category_id()];
2315
                                $link->set_category_id($newCategoryId);
2316
                                $link->add();
2317
                            }
2318
                        }
2319
2320
                        // Create
2321
                        DocumentManager::generateDefaultCertificate(
2322
                            $courseInfo,
2323
                            true,
2324
                            $sessionId
2325
                        );
2326
                    }
2327
                }
2328
2329
                // If the course isn't subscribed yet
2330
                $sql = "INSERT INTO $tbl_session_rel_course (session_id, c_id, nbr_users, position)
2331
                        VALUES ($sessionId, $courseId, 0, 0)";
2332
                Database::query($sql);
2333
2334
                Event::addEvent(
2335
                    LOG_SESSION_ADD_COURSE,
2336
                    LOG_COURSE_ID,
2337
                    $courseId,
2338
                    api_get_utc_datetime(),
2339
                    api_get_user_id(),
2340
                    $courseId,
2341
                    $sessionId
2342
                );
2343
2344
                // We add the current course in the existing courses array,
2345
                // to avoid adding another time the current course
2346
                $existingCourses[] = array('c_id' => $courseId);
2347
                $nbr_courses++;
2348
2349
                // subscribe all the users from the session to this course inside the session
2350
                $nbr_users = 0;
2351
                foreach ($user_list as $enreg_user) {
2352
                    $enreg_user_id = intval($enreg_user['user_id']);
2353
                    $sql = "INSERT IGNORE INTO $tbl_session_rel_course_rel_user (session_id, c_id, user_id)
2354
                            VALUES ($sessionId, $courseId, $enreg_user_id)";
2355
                    $result = Database::query($sql);
2356
2357
                    Event::addEvent(
2358
                        LOG_SESSION_ADD_USER_COURSE,
2359
                        LOG_USER_ID,
2360
                        $enreg_user_id,
2361
                        api_get_utc_datetime(),
2362
                        api_get_user_id(),
2363
                        $courseId,
2364
                        $sessionId
2365
                    );
2366
2367
                    if (Database::affected_rows($result)) {
2368
                        $nbr_users++;
2369
                    }
2370
                }
2371
                $sql = "UPDATE $tbl_session_rel_course
2372
                        SET nbr_users = $nbr_users
2373
                        WHERE session_id = $sessionId AND c_id = $courseId";
2374
                Database::query($sql);
2375
            }
2376
        }
2377
2378
        $sql = "UPDATE $tbl_session
2379
                SET nbr_courses = $nbr_courses
2380
                WHERE id = $sessionId";
2381
        Database::query($sql);
2382
    }
2383
2384
    /**
2385
     * Unsubscribe course from a session
2386
     *
2387
     * @param int $session_id
2388
     * @param int $course_id
2389
     * @return bool True in case of success, false otherwise
2390
     */
2391
    public static function unsubscribe_course_from_session($session_id, $course_id)
2392
    {
2393
        $session_id = (int) $session_id;
2394
        $course_id = (int) $course_id;
2395
2396
        $tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
2397
        $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
2398
        $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
2399
2400
        // Get course code
2401
        $course_code = CourseManager::get_course_code_from_course_id($course_id);
2402
        $course_id = intval($course_id);
2403
2404
        if (empty($course_code)) {
2405
            return false;
2406
        }
2407
2408
        // Unsubscribe course
2409
        $sql = "DELETE FROM $tbl_session_rel_course
2410
                WHERE c_id = $course_id AND session_id = $session_id";
2411
        $result = Database::query($sql);
2412
        $nb_affected = Database::affected_rows($result);
2413
2414
        $sql = "DELETE FROM $tbl_session_rel_course_rel_user
2415
                WHERE c_id = $course_id AND session_id = $session_id";
2416
        Database::query($sql);
2417
2418
        Event::addEvent(
2419
            LOG_SESSION_DELETE_COURSE,
2420
            LOG_COURSE_ID,
2421
            $course_id,
2422
            api_get_utc_datetime(),
2423
            api_get_user_id(),
2424
            $course_id,
2425
            $session_id
2426
        );
2427
2428
        if ($nb_affected > 0) {
2429
            // Update number of courses in the session
2430
            $sql = "UPDATE $tbl_session SET nbr_courses= nbr_courses - $nb_affected
2431
                    WHERE id = $session_id";
2432
            Database::query($sql);
2433
            return true;
2434
        } else {
2435
            return false;
2436
        }
2437
    }
2438
2439
    /**
2440
     * Creates a new extra field for a given session
2441
     * @param	string	$variable Field's internal variable name
2442
     * @param	int		$fieldType Field's type
2443
     * @param	string	$displayText Field's language var name
2444
     * @return int     new extra field id
2445
     */
2446 View Code Duplication
    public static function create_session_extra_field($variable, $fieldType, $displayText)
2447
    {
2448
        $extraField = new ExtraFieldModel('session');
2449
        $params = [
2450
            'variable' => $variable,
2451
            'field_type' => $fieldType,
2452
            'display_text' => $displayText,
2453
        ];
2454
2455
        return $extraField->save($params);
2456
    }
2457
2458
    /**
2459
     * Update an extra field value for a given session
2460
     * @param	integer	Course ID
2461
     * @param	string	Field variable name
2462
     * @param	string	Field value
2463
     * @return	boolean	true if field updated, false otherwise
2464
     */
2465 View Code Duplication
    public static function update_session_extra_field_value($sessionId, $variable, $value = '')
2466
    {
2467
        $extraFieldValue = new ExtraFieldValue('session');
2468
        $params = [
2469
            'item_id' => $sessionId,
2470
            'variable' => $variable,
2471
            'value' => $value,
2472
        ];
2473
        return $extraFieldValue->save($params);
2474
    }
2475
2476
    /**
2477
     * Checks the relationship between a session and a course.
2478
     * @param int $session_id
2479
     * @param int $courseId
2480
     * @return bool Returns TRUE if the session and the course are related, FALSE otherwise.
2481
     * */
2482
    public static function relation_session_course_exist($session_id, $courseId)
2483
    {
2484
        $tbl_session_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
2485
        $return_value = false;
2486
        $sql = "SELECT c_id FROM $tbl_session_course
2487
                WHERE
2488
                  session_id = " . intval($session_id) . " AND
2489
                  c_id = " . intval($courseId);
2490
        $result = Database::query($sql);
2491
        $num = Database::num_rows($result);
2492
        if ($num > 0) {
2493
            $return_value = true;
2494
        }
2495
        return $return_value;
2496
    }
2497
2498
    /**
2499
     * Get the session information by name
2500
     * @param string $session_name
2501
     * @return mixed false if the session does not exist, array if the session exist
2502
     * */
2503
    public static function get_session_by_name($session_name)
2504
    {
2505
        $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
2506
        $session_name = trim($session_name);
2507
        if (empty($session_name)) {
2508
            return false;
2509
        }
2510
2511
        $sql = 'SELECT *
2512
		        FROM ' . $tbl_session . '
2513
		        WHERE name = "' . Database::escape_string($session_name) . '"';
2514
        $result = Database::query($sql);
2515
        $num = Database::num_rows($result);
2516
        if ($num > 0) {
2517
            return Database::fetch_array($result);
2518
        } else {
2519
            return false;
2520
        }
2521
    }
2522
2523
    /**
2524
     * Create a session category
2525
     * @author Jhon Hinojosa <[email protected]>, from existing code
2526
     * @param	string 		name
2527
     * @param 	integer		year_start
2528
     * @param 	integer		month_start
2529
     * @param 	integer		day_start
2530
     * @param 	integer		year_end
2531
     * @param 	integer		month_end
2532
     * @param 	integer		day_end
2533
     * @return $id_session;
0 ignored issues
show
Documentation introduced by
The doc-type $id_session; could not be parsed: Unknown type name "$id_session" at position 0. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
2534
     * */
2535
    public static function create_category_session(
2536
        $sname,
2537
        $syear_start,
2538
        $smonth_start,
2539
        $sday_start,
2540
        $syear_end,
2541
        $smonth_end,
2542
        $sday_end
2543
    ) {
2544
        $tbl_session_category = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
2545
        $name = trim($sname);
2546
        $year_start = intval($syear_start);
2547
        $month_start = intval($smonth_start);
2548
        $day_start = intval($sday_start);
2549
        $year_end = intval($syear_end);
2550
        $month_end = intval($smonth_end);
2551
        $day_end = intval($sday_end);
2552
2553
        $date_start = "$year_start-" . (($month_start < 10) ? "0$month_start" : $month_start) . "-" . (($day_start < 10) ? "0$day_start" : $day_start);
2554
        $date_end = "$year_end-" . (($month_end < 10) ? "0$month_end" : $month_end) . "-" . (($day_end < 10) ? "0$day_end" : $day_end);
2555
2556 View Code Duplication
        if (empty($name)) {
2557
            $msg = get_lang('SessionCategoryNameIsRequired');
2558
            return $msg;
2559
        } elseif (!$month_start || !$day_start || !$year_start || !checkdate($month_start, $day_start, $year_start)) {
2560
            $msg = get_lang('InvalidStartDate');
2561
            return $msg;
2562
        } elseif (!$month_end && !$day_end && !$year_end) {
2563
            $date_end = '';
2564
        } elseif (!$month_end || !$day_end || !$year_end || !checkdate($month_end, $day_end, $year_end)) {
2565
            $msg = get_lang('InvalidEndDate');
2566
            return $msg;
2567
        } elseif ($date_start >= $date_end) {
2568
            $msg = get_lang('StartDateShouldBeBeforeEndDate');
2569
            return $msg;
2570
        }
2571
2572
        $access_url_id = api_get_current_access_url_id();
2573
        $params = [
2574
            'name' => $name,
2575
            'date_start' => $date_start,
2576
            'access_url_id' => $access_url_id
2577
        ];
2578
2579
        if (!empty($date_end)) {
2580
            $params['date_end'] = $date_end;
2581
        }
2582
2583
        $id = Database::insert($tbl_session_category, $params);
2584
2585
        // Add event to system log
2586
        $user_id = api_get_user_id();
2587
        Event::addEvent(
2588
            LOG_SESSION_CATEGORY_CREATE,
2589
            LOG_SESSION_CATEGORY_ID,
2590
            $id,
0 ignored issues
show
Security Bug introduced by
It seems like $id defined by \Database::insert($tbl_session_category, $params) on line 2583 can also be of type false; however, Event::addEvent() does only seem to accept string, did you maybe forget to handle an error condition?

This check looks for type mismatches where the missing type is false. This is usually indicative of an error condtion.

Consider the follow example

<?php

function getDate($date)
{
    if ($date !== null) {
        return new DateTime($date);
    }

    return false;
}

This function either returns a new DateTime object or false, if there was an error. This is a typical pattern in PHP programming to show that an error has occurred without raising an exception. The calling code should check for this returned false before passing on the value to another function or method that may not be able to handle a false.

Loading history...
2591
            api_get_utc_datetime(),
2592
            $user_id
2593
        );
2594
2595
        return $id;
2596
    }
2597
2598
    /**
2599
     * Edit a sessions categories
2600
     * @author Jhon Hinojosa <[email protected]>,from existing code
2601
     * @param	integer		id
2602
     * @param	string 		name
2603
     * @param 	integer		year_start
2604
     * @param 	integer		month_start
2605
     * @param 	integer		day_start
2606
     * @param 	integer		year_end
2607
     * @param 	integer		month_end
2608
     * @param 	integer		day_end
2609
     * @return $id;
0 ignored issues
show
Documentation introduced by
The doc-type $id; could not be parsed: Unknown type name "$id" at position 0. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
2610
     * The parameter id is a primary key
2611
     * */
2612
    public static function edit_category_session(
2613
        $id,
2614
        $sname,
2615
        $syear_start,
2616
        $smonth_start,
2617
        $sday_start,
2618
        $syear_end,
2619
        $smonth_end,
2620
        $sday_end
2621
    ) {
2622
        $tbl_session_category = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
2623
        $name = trim($sname);
2624
        $year_start = intval($syear_start);
2625
        $month_start = intval($smonth_start);
2626
        $day_start = intval($sday_start);
2627
        $year_end = intval($syear_end);
2628
        $month_end = intval($smonth_end);
2629
        $day_end = intval($sday_end);
2630
        $id = intval($id);
2631
        $date_start = "$year_start-" . (($month_start < 10) ? "0$month_start" : $month_start) . "-" . (($day_start < 10) ? "0$day_start" : $day_start);
2632
        $date_end = "$year_end-" . (($month_end < 10) ? "0$month_end" : $month_end) . "-" . (($day_end < 10) ? "0$day_end" : $day_end);
2633
2634 View Code Duplication
        if (empty($name)) {
2635
            $msg = get_lang('SessionCategoryNameIsRequired');
2636
            return $msg;
2637
        } elseif (!$month_start || !$day_start || !$year_start || !checkdate($month_start, $day_start, $year_start)) {
2638
            $msg = get_lang('InvalidStartDate');
2639
            return $msg;
2640
        } elseif (!$month_end && !$day_end && !$year_end) {
2641
            $date_end = null;
2642
        } elseif (!$month_end || !$day_end || !$year_end || !checkdate($month_end, $day_end, $year_end)) {
2643
            $msg = get_lang('InvalidEndDate');
2644
            return $msg;
2645
        } elseif ($date_start >= $date_end) {
2646
            $msg = get_lang('StartDateShouldBeBeforeEndDate');
2647
            return $msg;
2648
        }
2649
        if ($date_end <> null) {
0 ignored issues
show
Bug introduced by
It seems like you are loosely comparing $date_end of type null|string against null; this is ambiguous if the string can be empty. Consider using a strict comparison !== instead.
Loading history...
2650
            $sql = "UPDATE $tbl_session_category
2651
                    SET
2652
                        name = '" . Database::escape_string($name) . "',
2653
                        date_start = '$date_start' ,
2654
                        date_end = '$date_end'
2655
                    WHERE id= $id";
2656
        } else {
2657
            $sql = "UPDATE $tbl_session_category SET
2658
                        name = '" . Database::escape_string($name) . "',
2659
                        date_start = '$date_start',
2660
                        date_end = NULL
2661
                    WHERE id= $id";
2662
        }
2663
        $result = Database::query($sql);
2664
        return ($result ? true : false);
2665
    }
2666
2667
    /**
2668
     * Delete sessions categories
2669
     * @author Jhon Hinojosa <[email protected]>, from existing code
2670
     * @param	array	id_checked
2671
     * @param	bool	include delete session
2672
     * @param	bool	optional, true if the function is called by a webservice, false otherwise.
2673
     * @return	void	Nothing, or false on error
2674
     * The parameters is a array to delete sessions
2675
     * */
2676
    public static function delete_session_category($id_checked, $delete_session = false, $from_ws = false)
2677
    {
2678
        $tbl_session_category = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
2679
        $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
2680
        if (is_array($id_checked)) {
2681
            $id_checked = Database::escape_string(implode(',', $id_checked));
2682
        } else {
2683
            $id_checked = intval($id_checked);
2684
        }
2685
2686
        //Setting session_category_id to 0
2687
        $sql = "UPDATE $tbl_session SET session_category_id = 0
2688
                WHERE session_category_id IN (" . $id_checked . ")";
2689
        Database::query($sql);
2690
2691
        $sql = "SELECT id FROM $tbl_session WHERE session_category_id IN (" . $id_checked . ")";
2692
        $result = Database::query($sql);
2693
        while ($rows = Database::fetch_array($result)) {
2694
            $session_id = $rows['id'];
2695
            if ($delete_session) {
2696
                if ($from_ws) {
2697
                    SessionManager::delete($session_id, true);
2698
                } else {
2699
                    SessionManager::delete($session_id);
2700
                }
2701
            }
2702
        }
2703
        $sql = "DELETE FROM $tbl_session_category WHERE id IN (" . $id_checked . ")";
2704
        Database::query($sql);
2705
2706
        // Add event to system log
2707
        $user_id = api_get_user_id();
2708
        Event::addEvent(
2709
            LOG_SESSION_CATEGORY_DELETE,
2710
            LOG_SESSION_CATEGORY_ID,
2711
            $id_checked,
2712
            api_get_utc_datetime(),
2713
            $user_id
2714
        );
2715
2716
        return true;
2717
    }
2718
2719
    /**
2720
     * Get a list of sessions of which the given conditions match with an = 'cond'
2721
     * @param  array $conditions a list of condition example :
2722
     * array('status' => STUDENT) or
2723
     * array('s.name' => array('operator' => 'LIKE', value = '%$needle%'))
2724
     * @param  array $order_by a list of fields on which sort
2725
     * @return array An array with all sessions of the platform.
2726
     * @todo   optional course code parameter, optional sorting parameters...
2727
     */
2728
    public static function get_sessions_list($conditions = array(), $order_by = array(), $from = null, $to = null)
2729
    {
2730
        $session_table = Database::get_main_table(TABLE_MAIN_SESSION);
2731
        $session_category_table = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
2732
        $user_table = Database::get_main_table(TABLE_MAIN_USER);
2733
        $table_access_url_rel_session = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
2734
        $session_course_table = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
2735
        $course_table = Database::get_main_table(TABLE_MAIN_COURSE);
2736
        $access_url_id = api_get_current_access_url_id();
2737
        $return_array = array();
2738
2739
        $sql_query = " SELECT
2740
                    DISTINCT(s.id),
2741
                    s.name,
2742
                    s.nbr_courses,
2743
                    s.access_start_date,
2744
                    s.access_end_date,
2745
                    u.firstname,
2746
                    u.lastname,
2747
                    sc.name as category_name,
2748
                    s.promotion_id
2749
				FROM $session_table s
2750
				INNER JOIN $user_table u ON s.id_coach = u.user_id
2751
				INNER JOIN $table_access_url_rel_session ar ON ar.session_id = s.id
2752
				LEFT JOIN  $session_category_table sc ON s.session_category_id = sc.id
2753
				LEFT JOIN $session_course_table sco ON (sco.session_id = s.id)
2754
				INNER JOIN $course_table c ON sco.c_id = c.id
2755
				WHERE ar.access_url_id = $access_url_id ";
2756
2757
        $availableFields = array(
2758
            's.id',
2759
            's.name',
2760
            'c.id'
2761
        );
2762
2763
        $availableOperator = array(
2764
            'like',
2765
            '>=',
2766
            '<=',
2767
            '=',
2768
        );
2769
2770
        if (count($conditions) > 0) {
2771
            foreach ($conditions as $field => $options) {
2772
                $operator = strtolower($options['operator']);
2773
                $value = Database::escape_string($options['value']);
2774
                $sql_query .= ' AND ';
2775
                if (in_array($field, $availableFields) && in_array($operator, $availableOperator)) {
2776
                    $sql_query .= $field . " $operator '" . $value . "'";
2777
                }
2778
            }
2779
        }
2780
2781
        $orderAvailableList = array('name');
2782
2783
        if (count($order_by) > 0) {
2784
            $order = null;
2785
            $direction = null;
2786
            if (isset($order_by[0]) && in_array($order_by[0], $orderAvailableList)) {
2787
                $order = $order_by[0];
2788
            }
2789
            if (isset($order_by[1]) && in_array(strtolower($order_by[1]), array('desc', 'asc'))) {
2790
                $direction = $order_by[1];
2791
            }
2792
2793
            if (!empty($order)) {
2794
                $sql_query .= " ORDER BY $order $direction ";
2795
            }
2796
        }
2797
2798
        if (!is_null($from) && !is_null($to)) {
2799
            $to = intval($to);
2800
            $from = intval($from);
2801
            $sql_query .= "LIMIT $from, $to";
2802
        }
2803
2804
        $sql_result = Database::query($sql_query);
2805
        if (Database::num_rows($sql_result) > 0) {
2806
            while ($result = Database::fetch_array($sql_result)) {
2807
                $return_array[$result['id']] = $result;
2808
            }
2809
        }
2810
2811
        return $return_array;
2812
    }
2813
2814
    /**
2815
     * Get the session category information by id
2816
     * @param string session category ID
2817
     * @return mixed false if the session category does not exist, array if the session category exists
2818
     */
2819
    public static function get_session_category($id)
2820
    {
2821
        $tbl_session_category = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
2822
        $id = intval($id);
2823
        $sql = "SELECT id, name, date_start, date_end
2824
                FROM $tbl_session_category
2825
                WHERE id= $id";
2826
        $result = Database::query($sql);
2827
        $num = Database::num_rows($result);
2828
        if ($num > 0) {
2829
            return Database::fetch_array($result);
2830
        } else {
2831
            return false;
2832
        }
2833
    }
2834
2835
    /**
2836
     * Get all session categories (filter by access_url_id)
2837
     * @return mixed false if the session category does not exist, array if the session category exists
2838
     */
2839
    public static function get_all_session_category()
2840
    {
2841
        $tbl_session_category = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
2842
        $id = api_get_current_access_url_id();
2843
        $sql = 'SELECT * FROM ' . $tbl_session_category . '
2844
                WHERE access_url_id = ' . $id . '
2845
                ORDER BY name ASC';
2846
        $result = Database::query($sql);
2847
        if (Database::num_rows($result) > 0) {
2848
            $data = Database::store_result($result, 'ASSOC');
2849
            return $data;
2850
        } else {
2851
            return false;
2852
        }
2853
    }
2854
2855
    /**
2856
     * Assign a coach to course in session with status = 2
2857
     * @param int  $user_id
2858
     * @param int  $session_id
2859
     * @param int  $courseId
2860
     * @param bool $nocoach optional, if is true the user don't be a coach now,
2861
     * otherwise it'll assign a coach
2862
     * @return bool true if there are affected rows, otherwise false
2863
     */
2864
    public static function set_coach_to_course_session(
2865
        $user_id,
2866
        $session_id = 0,
2867
        $courseId = 0,
2868
        $nocoach = false
2869
    ) {
2870
        // Definition of variables
2871
        $user_id = intval($user_id);
2872
2873
        if (!empty($session_id)) {
2874
            $session_id = intval($session_id);
2875
        } else {
2876
            $session_id = api_get_session_id();
2877
        }
2878
2879
        if (!empty($courseId)) {
2880
            $courseId = intval($courseId);
2881
        } else {
2882
            $courseId = api_get_course_id();
2883
        }
2884
2885
        if (empty($session_id) || empty($courseId) || empty($user_id)) {
2886
            return false;
2887
        }
2888
2889
        // Table definition
2890
        $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
2891
        $tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
2892
        $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
2893
2894
        // check if user is a teacher
2895
        $sql = "SELECT * FROM $tbl_user
2896
                WHERE status = 1 AND user_id = $user_id";
2897
2898
        $rs_check_user = Database::query($sql);
2899
2900
        if (Database::num_rows($rs_check_user) > 0) {
2901
            if ($nocoach) {
2902
                // check if user_id exists in session_rel_user (if the user is
2903
                // subscribed to the session in any manner)
2904
                $sql = "SELECT user_id FROM $tbl_session_rel_user
2905
                        WHERE
2906
                            session_id = $session_id AND
2907
                            user_id = $user_id";
2908
                $res = Database::query($sql);
2909
2910 View Code Duplication
                if (Database::num_rows($res) > 0) {
2911
                    // The user is already subscribed to the session. Change the
2912
                    // record so the user is NOT a coach for this course anymore
2913
                    // and then exit
2914
                    $sql = "UPDATE $tbl_session_rel_course_rel_user
2915
                            SET status = 0
2916
                            WHERE
2917
                                session_id = $session_id AND
2918
                                c_id = $courseId AND
2919
                                user_id = $user_id ";
2920
                    $result = Database::query($sql);
2921
                    if (Database::affected_rows($result) > 0)
2922
                        return true;
2923
                    else
2924
                        return false;
2925
                } else {
2926
                    // The user is not subscribed to the session, so make sure
2927
                    // he isn't subscribed to a course in this session either
2928
                    // and then exit
2929
                    $sql = "DELETE FROM $tbl_session_rel_course_rel_user
2930
                            WHERE
2931
                                session_id = $session_id AND
2932
                                c_id = $courseId AND
2933
                                user_id = $user_id ";
2934
                    $result = Database::query($sql);
2935
                    if (Database::affected_rows($result) > 0) {
2936
                        return true;
2937
                    } else {
2938
                        return false;
2939
                    }
2940
                }
2941
            } else {
2942
                // Assign user as a coach to course
2943
                // First check if the user is registered to the course
2944
                $sql = "SELECT user_id FROM $tbl_session_rel_course_rel_user
2945
                        WHERE
2946
                            session_id = $session_id AND
2947
                            c_id = $courseId AND
2948
                            user_id = $user_id";
2949
                $rs_check = Database::query($sql);
2950
2951
                // Then update or insert.
2952 View Code Duplication
                if (Database::num_rows($rs_check) > 0) {
2953
                    $sql = "UPDATE $tbl_session_rel_course_rel_user SET status = 2
2954
					        WHERE
2955
					            session_id = $session_id AND
2956
					            c_id = $courseId AND
2957
					            user_id = $user_id ";
2958
                    $result = Database::query($sql);
2959
                    if (Database::affected_rows($result) > 0) {
2960
                        return true;
2961
                    } else {
2962
                        return false;
2963
                    }
2964
                } else {
2965
                    $sql = "INSERT INTO $tbl_session_rel_course_rel_user(session_id, c_id, user_id, status)
2966
                            VALUES($session_id, $courseId, $user_id, 2)";
2967
                    $result = Database::query($sql);
2968
                    if (Database::affected_rows($result) > 0) {
2969
                        return true;
2970
                    } else {
2971
                        return false;
2972
                    }
2973
                }
2974
            }
2975
        } else {
2976
            return false;
2977
        }
2978
    }
2979
2980
    /**
2981
     * @param int $sessionId
2982
     * @return bool
2983
     */
2984 View Code Duplication
    public static function removeAllDrhFromSession($sessionId)
2985
    {
2986
        $tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
2987
2988
        $sessionId = (int) $sessionId;
2989
2990
        if (empty($sessionId)) {
2991
            return false;
2992
        }
2993
2994
        $sql = "DELETE FROM $tbl_session_rel_user
2995
                WHERE
2996
                    session_id = $sessionId AND                            
2997
                    relation_type =" . SESSION_RELATION_TYPE_RRHH;
2998
        Database::query($sql);
2999
3000
        return true;
3001
    }
3002
3003
    /**
3004
     * Subscribes sessions to human resource manager (Dashboard feature)
3005
     * @param array $userInfo Human Resource Manager info
3006
     * @param array $sessions_list Sessions id
3007
     * @param bool $sendEmail
3008
     * @param bool $removeSessionsFromUser
3009
     * @return int
3010
     * */
3011
    public static function subscribeSessionsToDrh(
3012
        $userInfo,
3013
        $sessions_list,
3014
        $sendEmail = false,
3015
        $removeSessionsFromUser = true
3016
    ) {
3017
        // Database Table Definitions
3018
        $tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
3019
        $tbl_session_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
3020
3021
        if (empty($userInfo)) {
3022
3023
            return 0;
3024
        }
3025
3026
        $userId = $userInfo['user_id'];
3027
3028
        // Only subscribe DRH users.
3029
        $rolesAllowed = array(
3030
            DRH,
3031
            SESSIONADMIN,
3032
            PLATFORM_ADMIN,
3033
            COURSE_TUTOR
3034
        );
3035
        $isAdmin = api_is_platform_admin_by_id($userInfo['user_id']);
3036
        if (!$isAdmin && !in_array($userInfo['status'], $rolesAllowed)) {
3037
3038
            return 0;
3039
        }
3040
3041
        $affected_rows = 0;
3042
        // Deleting assigned sessions to hrm_id.
3043
        if ($removeSessionsFromUser) {
3044
            if (api_is_multiple_url_enabled()) {
3045
                $sql = "SELECT s.session_id
3046
                        FROM $tbl_session_rel_user s
3047
                        INNER JOIN $tbl_session_rel_access_url a 
3048
                        ON (a.session_id = s.session_id)
3049
                        WHERE
3050
                            s.user_id = $userId AND
3051
                            relation_type = " . SESSION_RELATION_TYPE_RRHH . " AND
3052
                            access_url_id = " . api_get_current_access_url_id();
3053
            } else {
3054
                $sql = "SELECT s.session_id 
3055
                        FROM $tbl_session_rel_user s
3056
                        WHERE user_id = $userId AND relation_type=" . SESSION_RELATION_TYPE_RRHH;
3057
            }
3058
            $result = Database::query($sql);
3059
3060 View Code Duplication
            if (Database::num_rows($result) > 0) {
3061
                while ($row = Database::fetch_array($result)) {
3062
                    $sql = "DELETE FROM $tbl_session_rel_user
3063
                            WHERE
3064
                                session_id = {$row['session_id']} AND
3065
                                user_id = $userId AND
3066
                                relation_type =" . SESSION_RELATION_TYPE_RRHH;
3067
                    Database::query($sql);
3068
                }
3069
            }
3070
        }
3071
3072
        // Inserting new sessions list.
3073
        if (!empty($sessions_list) && is_array($sessions_list)) {
3074
            foreach ($sessions_list as $session_id) {
3075
                $session_id = intval($session_id);
3076
                $sql = "SELECT session_id
3077
                        FROM $tbl_session_rel_user
3078
                        WHERE
3079
                            session_id = $session_id AND
3080
                            user_id = $userId AND
3081
                            relation_type = '" . SESSION_RELATION_TYPE_RRHH . "'";
3082
                $result = Database::query($sql);
3083
                if (Database::num_rows($result) == 0) {
3084
                    $sql = "INSERT IGNORE INTO $tbl_session_rel_user (session_id, user_id, relation_type, registered_at)
3085
                            VALUES (
3086
                                $session_id,
3087
                                $userId,
3088
                                '".SESSION_RELATION_TYPE_RRHH."',
3089
                                '".api_get_utc_datetime()."'
3090
                            )";
3091
                    Database::query($sql);
3092
                    $affected_rows++;
3093
                }
3094
            }
3095
        }
3096
3097
        return $affected_rows;
3098
    }
3099
3100
    /**
3101
     * @param int $sessionId
3102
     * @return array
3103
     */
3104
    public static function getDrhUsersInSession($sessionId)
3105
    {
3106
        return self::get_users_by_session($sessionId, SESSION_RELATION_TYPE_RRHH);
3107
    }
3108
3109
    /**
3110
     * @param int $userId
3111
     * @param int $sessionId
3112
     * @return array
3113
     */
3114
    public static function getSessionFollowedByDrh($userId, $sessionId)
3115
    {
3116
        $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
3117
        $tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
3118
        $tbl_session_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
3119
3120
        $userId = intval($userId);
3121
        $sessionId = intval($sessionId);
3122
3123
        $select = " SELECT * ";
3124
        if (api_is_multiple_url_enabled()) {
3125
            $sql = " $select FROM $tbl_session s
3126
                    INNER JOIN $tbl_session_rel_user sru ON (sru.session_id = s.id)
3127
                    LEFT JOIN $tbl_session_rel_access_url a ON (s.id = a.session_id)
3128
                    WHERE
3129
                        sru.user_id = '$userId' AND
3130
                        sru.session_id = '$sessionId' AND
3131
                        sru.relation_type = '" . SESSION_RELATION_TYPE_RRHH . "' AND
3132
                        access_url_id = " . api_get_current_access_url_id() . "
3133
                        ";
3134
        } else {
3135
            $sql = "$select FROM $tbl_session s
3136
                     INNER JOIN $tbl_session_rel_user sru
3137
                     ON
3138
                        sru.session_id = s.id AND
3139
                        sru.user_id = '$userId' AND
3140
                        sru.session_id = '$sessionId' AND
3141
                        sru.relation_type = '" . SESSION_RELATION_TYPE_RRHH . "'
3142
                    ";
3143
        }
3144
3145
        $result = Database::query($sql);
3146
        if (Database::num_rows($result)) {
3147
            $row = Database::fetch_array($result, 'ASSOC');
3148
            $row['course_list'] = self::get_course_list_by_session_id($sessionId);
3149
3150
            return $row;
3151
        }
3152
3153
        return array();
3154
    }
3155
3156
    /**
3157
     * Get sessions followed by human resources manager
3158
     * @param int $userId
3159
     * @param int $start
3160
     * @param int $limit
3161
     * @param bool $getCount
3162
     * @param bool $getOnlySessionId
3163
     * @param bool $getSql
3164
     * @param string $orderCondition
3165
     * @param string $keyword
3166
     * @param string $description
3167
     *
3168
     * @return array sessions
3169
     */
3170
    public static function get_sessions_followed_by_drh(
3171
        $userId,
3172
        $start = null,
3173
        $limit = null,
3174
        $getCount = false,
3175
        $getOnlySessionId = false,
3176
        $getSql = false,
3177
        $orderCondition = null,
3178
        $keyword = '',
3179
        $description = ''
3180
    ) {
3181
        return self::getSessionsFollowedByUser(
3182
            $userId,
3183
            DRH,
3184
            $start,
3185
            $limit,
3186
            $getCount,
3187
            $getOnlySessionId,
3188
            $getSql,
3189
            $orderCondition,
3190
            $keyword,
3191
            $description
3192
        );
3193
    }
3194
3195
    /**
3196
     * Get sessions followed by human resources manager
3197
     * @param int $userId
3198
     * @param int $status Optional
3199
     * @param int $start
3200
     * @param int $limit
3201
     * @param bool $getCount
3202
     * @param bool $getOnlySessionId
3203
     * @param bool $getSql
3204
     * @param string $orderCondition
3205
     * @param string $keyword
3206
     * @param string $description
3207
     * @return array sessions
3208
     */
3209
    public static function getSessionsFollowedByUser(
3210
        $userId,
3211
        $status = null,
3212
        $start = null,
3213
        $limit = null,
3214
        $getCount = false,
3215
        $getOnlySessionId = false,
3216
        $getSql = false,
3217
        $orderCondition = null,
3218
        $keyword = '',
3219
        $description = ''
3220
    ) {
3221
        // Database Table Definitions
3222
        $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
3223
        $tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
3224
        $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
3225
        $tbl_session_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
3226
3227
        $userId = intval($userId);
3228
3229
        $select = " SELECT DISTINCT * ";
3230
3231
        if ($getCount) {
3232
            $select = " SELECT count(DISTINCT(s.id)) as count ";
3233
        }
3234
3235
        if ($getOnlySessionId) {
3236
            $select = " SELECT DISTINCT(s.id) ";
3237
        }
3238
3239
        $limitCondition = null;
3240 View Code Duplication
        if (!empty($start) && !empty($limit)) {
3241
            $limitCondition = " LIMIT " . intval($start) . ", " . intval($limit);
3242
        }
3243
3244
        if (empty($orderCondition)) {
3245
            $orderCondition = " ORDER BY s.name ";
3246
        }
3247
3248
        $whereConditions = null;
3249
        $sessionCourseConditions = null;
3250
        $sessionConditions = null;
3251
        $sessionQuery = null;
3252
        $courseSessionQuery = null;
3253
3254
        switch ($status) {
3255
            case DRH:
3256
                $sessionQuery = "SELECT sru.session_id
3257
                                 FROM
3258
                                 $tbl_session_rel_user sru
3259
                                 WHERE
3260
                                    sru.relation_type = '".SESSION_RELATION_TYPE_RRHH."' AND
3261
                                    sru.user_id = $userId";
3262
                break;
3263
            case COURSEMANAGER:
3264
                $courseSessionQuery = "
3265
                    SELECT scu.session_id as id
3266
                    FROM $tbl_session_rel_course_rel_user scu
3267
                    WHERE (scu.status = 2 AND scu.user_id = $userId)";
3268
3269
                $whereConditions = " OR (s.id_coach = $userId) ";
3270
                break;
3271
            default:
3272
                $sessionQuery = "SELECT sru.session_id
3273
                                 FROM
3274
                                 $tbl_session_rel_user sru
3275
                                 WHERE
3276
                                    sru.user_id = $userId";
3277
                break;
3278
        }
3279
3280
        $keywordCondition = '';
3281 View Code Duplication
        if (!empty($keyword)) {
3282
            $keyword = Database::escape_string($keyword);
3283
            $keywordCondition = " AND (s.name LIKE '%$keyword%' ) ";
3284
3285
            if (!empty($description)) {
3286
                $description = Database::escape_string($description);
3287
                $keywordCondition = " AND (s.name LIKE '%$keyword%' OR s.description LIKE '%$description%' ) ";
3288
            }
3289
        }
3290
3291
        $whereConditions .= $keywordCondition;
3292
        $subQuery = $sessionQuery.$courseSessionQuery;
3293
3294
        $sql = " $select FROM $tbl_session s
3295
                INNER JOIN $tbl_session_rel_access_url a ON (s.id = a.session_id)
3296
                WHERE
3297
                    access_url_id = ".api_get_current_access_url_id()." AND
3298
                    s.id IN (
3299
                        $subQuery
3300
                    )
3301
                    $whereConditions
3302
                    $orderCondition
3303
                    $limitCondition";
3304
3305
        if ($getSql) {
3306
            return $sql;
3307
        }
3308
3309
        $result = Database::query($sql);
3310
3311
        if ($getCount) {
3312
            $row = Database::fetch_array($result);
3313
            return $row['count'];
3314
        }
3315
3316
        $sessions = array();
3317
        if (Database::num_rows($result) > 0) {
3318
            $sysUploadPath = api_get_path(SYS_UPLOAD_PATH). 'sessions/';
3319
            $webUploadPath = api_get_path(WEB_UPLOAD_PATH). 'sessions/';
3320
            $imgPath = Display::return_icon('session_default_small.png', null, null, null, null, true);
3321
3322
            $tableExtraFields = Database::get_main_table(TABLE_EXTRA_FIELD);
3323
            $sql = "SELECT id FROM " . $tableExtraFields . "
3324
                    WHERE extra_field_type = 3 AND variable='image'";
3325
            $resultField = Database::query($sql);
3326
            $imageFieldId = Database::fetch_assoc($resultField);
3327
3328
            while ($row = Database::fetch_array($result)) {
3329
3330
                $row['image'] =  null;
3331
                $sessionImage = $sysUploadPath . $imageFieldId['id'] . '_' . $row['id'] . '.png';
3332
3333
                if (is_file($sessionImage)) {
3334
                    $sessionImage = $webUploadPath . $imageFieldId['id'] . '_' . $row['id'] . '.png';
3335
                    $row['image'] = $sessionImage;
3336
                } else {
3337
                    $row['image'] =  $imgPath;
3338
                }
3339
3340
                if ($row['display_start_date'] == '0000-00-00 00:00:00' || $row['display_start_date'] == '0000-00-00') {
3341
                    $row['display_start_date'] = null;
3342
                }
3343
3344
                if ($row['display_end_date'] == '0000-00-00 00:00:00' || $row['display_end_date'] == '0000-00-00') {
3345
                    $row['display_end_date'] = null;
3346
                }
3347
3348
                if ($row['access_start_date'] == '0000-00-00 00:00:00' || $row['access_start_date'] == '0000-00-00') {
3349
                    $row['access_start_date'] = null;
3350
                }
3351
3352
                if ($row['access_end_date'] == '0000-00-00 00:00:00' || $row['access_end_date'] == '0000-00-00') {
3353
                    $row['access_end_date'] = null;
3354
                }
3355
3356
                if (
3357
                    $row['coach_access_start_date'] == '0000-00-00 00:00:00' ||
3358
                    $row['coach_access_start_date'] == '0000-00-00'
3359
                ) {
3360
                    $row['coach_access_start_date'] = null;
3361
                }
3362
3363
                if (
3364
                    $row['coach_access_end_date'] == '0000-00-00 00:00:00' ||
3365
                    $row['coach_access_end_date'] == '0000-00-00'
3366
                ) {
3367
                    $row['coach_access_end_date'] = null;
3368
                }
3369
3370
                $sessions[$row['id']] = $row;
3371
3372
            }
3373
        }
3374
3375
        return $sessions;
3376
    }
3377
3378
    /**
3379
     * Gets the list (or the count) of courses by session filtered by access_url
3380
     * @param int $session_id The session id
3381
     * @param string $course_name The course code
3382
     * @param string $orderBy Field to order the data
3383
     * @param boolean $getCount Optional. Count the session courses
3384
     * @return array|int List of courses. Whether $getCount is true, return the count
3385
     */
3386
    public static function get_course_list_by_session_id(
3387
        $session_id,
3388
        $course_name = '',
3389
        $orderBy = null,
3390
        $getCount = false
3391
    ) {
3392
        $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
3393
        $tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
3394
3395
        $session_id = intval($session_id);
3396
3397
        $sqlSelect = "*, c.id, c.id as real_id";
3398
3399
        if ($getCount) {
3400
            $sqlSelect = "COUNT(1) as count";
3401
        }
3402
3403
        // select the courses
3404
        $sql = "SELECT $sqlSelect
3405
                FROM $tbl_course c
3406
                INNER JOIN $tbl_session_rel_course src
3407
                ON (c.id = src.c_id)
3408
		        WHERE src.session_id = '$session_id' ";
3409
3410
        if (!empty($course_name)) {
3411
            $course_name = Database::escape_string($course_name);
3412
            $sql .= " AND c.title LIKE '%$course_name%' ";
3413
        }
3414
3415
        if (!empty($orderBy)) {
3416
            $orderBy = Database::escape_string($orderBy);
3417
            $orderBy = " ORDER BY $orderBy";
3418
        } else {
3419
            if (SessionManager::orderCourseIsEnabled()) {
3420
                $orderBy .= " ORDER BY position ";
3421
            } else {
3422
                $orderBy .= " ORDER BY title ";
3423
            }
3424
        }
3425
3426
        $sql .= Database::escape_string($orderBy);
3427
        $result = Database::query($sql);
3428
        $num_rows = Database::num_rows($result);
3429
        $courses = array();
3430
        if ($num_rows > 0) {
3431
            if ($getCount) {
3432
                $count = Database::fetch_assoc($result);
3433
3434
                return intval($count['count']);
3435
            }
3436
3437
            while ($row = Database::fetch_array($result,'ASSOC'))	{
3438
                $courses[$row['real_id']] = $row;
3439
            }
3440
        }
3441
3442
        return $courses;
3443
    }
3444
3445
    /**
3446
     * Gets the list of courses by session filtered by access_url
3447
     *
3448
     * @param $userId
3449
     * @param $sessionId
3450
     * @param null $from
3451
     * @param null $limit
3452
     * @param null $column
3453
     * @param null $direction
3454
     * @param bool $getCount
3455
     * @return array
3456
     */
3457
    public static function getAllCoursesFollowedByUser(
3458
        $userId,
3459
        $sessionId,
3460
        $from = null,
3461
        $limit = null,
3462
        $column = null,
3463
        $direction = null,
3464
        $getCount = false,
3465
        $keyword = null
3466
    ) {
3467
        if (empty($sessionId)) {
3468
            $sessionsSQL = SessionManager::get_sessions_followed_by_drh(
3469
                $userId,
3470
                null,
3471
                null,
3472
                null,
3473
                true,
3474
                true
3475
            );
3476
        } else {
3477
            $sessionsSQL = intval($sessionId);
3478
        }
3479
3480
        $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
3481
        $tbl_session_rel_course	= Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
3482
3483
        if ($getCount) {
3484
            $select = "SELECT COUNT(DISTINCT(c.code)) as count ";
3485
        } else {
3486
            $select = "SELECT DISTINCT c.* ";
3487
        }
3488
3489
        $keywordCondition = null;
3490
        if (!empty($keyword)) {
3491
            $keyword = Database::escape_string($keyword);
3492
            $keywordCondition = " AND (c.code LIKE '%$keyword%' OR c.title LIKE '%$keyword%' ) ";
3493
        }
3494
3495
        // Select the courses
3496
        $sql = "$select
3497
                FROM $tbl_course c
3498
                INNER JOIN $tbl_session_rel_course src
3499
                ON c.id = src.c_id
3500
		        WHERE
3501
		            src.session_id IN ($sessionsSQL)
3502
		            $keywordCondition
3503
		        ";
3504
        if ($getCount) {
3505
            $result = Database::query($sql);
3506
            $row = Database::fetch_array($result,'ASSOC');
3507
            return $row['count'];
3508
        }
3509
3510
        if (isset($from) && isset($limit)) {
3511
            $from = intval($from);
3512
            $limit = intval($limit);
3513
            $sql .= " LIMIT $from, $limit";
3514
        }
3515
3516
        $result = Database::query($sql);
3517
        $num_rows = Database::num_rows($result);
3518
        $courses = array();
3519
3520
        if ($num_rows > 0) {
3521
            while ($row = Database::fetch_array($result,'ASSOC'))	{
3522
                $courses[$row['id']] = $row;
3523
            }
3524
        }
3525
3526
        return $courses;
3527
    }
3528
3529
    /**
3530
     * Gets the list of courses by session filtered by access_url
3531
     * @param int $session_id
3532
     * @param string $course_name
3533
     * @return array list of courses
3534
     */
3535
    public static function get_course_list_by_session_id_like($session_id, $course_name = '')
3536
    {
3537
        $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
3538
        $tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
3539
3540
        $session_id = intval($session_id);
3541
        $course_name = Database::escape_string($course_name);
3542
3543
        // select the courses
3544
        $sql = "SELECT c.id, c.title FROM $tbl_course c
3545
                INNER JOIN $tbl_session_rel_course src
3546
                ON c.id = src.c_id
3547
		        WHERE ";
3548
3549
        if (!empty($session_id)) {
3550
            $sql .= "src.session_id LIKE '$session_id' AND ";
3551
        }
3552
3553
        if (!empty($course_name)) {
3554
            $sql .= "UPPER(c.title) LIKE UPPER('%$course_name%') ";
3555
        }
3556
3557
        $sql .= "ORDER BY title;";
3558
        $result = Database::query($sql);
3559
        $num_rows = Database::num_rows($result);
3560
        $courses = array();
3561
        if ($num_rows > 0) {
3562
            while ($row = Database::fetch_array($result, 'ASSOC')) {
3563
                $courses[$row['id']] = $row;
3564
            }
3565
        }
3566
3567
        return $courses;
3568
    }
3569
3570
3571
    /**
3572
     * Gets the count of courses by session filtered by access_url
3573
     * @param int session id
3574
     * @return array list of courses
3575
     */
3576
    public static function getCourseCountBySessionId($session_id, $keyword = null)
3577
    {
3578
        $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
3579
        $tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
3580
        $session_id = intval($session_id);
3581
3582
        // select the courses
3583
        $sql = "SELECT COUNT(c.code) count
3584
                FROM $tbl_course c
3585
                INNER JOIN $tbl_session_rel_course src
3586
                ON c.id = src.c_id
3587
		        WHERE src.session_id = '$session_id' ";
3588
3589
        $keywordCondition = null;
3590
        if (!empty($keyword)) {
3591
            $keyword = Database::escape_string($keyword);
3592
            $keywordCondition = " AND (c.code LIKE '%$keyword%' OR c.title LIKE '%$keyword%' ) ";
3593
        }
3594
        $sql .= $keywordCondition;
3595
3596
        $result = Database::query($sql);
3597
        $num_rows = Database::num_rows($result);
3598
        if ($num_rows > 0) {
3599
            $row = Database::fetch_array($result,'ASSOC');
3600
            return $row['count'];
3601
        }
3602
3603
        return null;
3604
    }
3605
3606
    /**
3607
     * Get the session id based on the original id and field name in the extra fields.
3608
     * Returns 0 if session was not found
3609
     *
3610
     * @param string $value Original session id
3611
     * @param string $variable Original field name
3612
     * @return int Session id
3613
     */
3614
    public static function getSessionIdFromOriginalId($value, $variable)
3615
    {
3616
        $extraFieldValue = new ExtraFieldValue('session');
3617
        $result = $extraFieldValue->get_item_id_from_field_variable_and_field_value(
3618
            $variable,
3619
            $value
3620
        );
3621
3622
        if (!empty($result)) {
3623
            return $result['item_id'];
3624
        }
3625
3626
        return 0;
3627
    }
3628
3629
    /**
3630
     * Get users by session
3631
     * @param  int $id session id
3632
     * @param    int $status filter by status coach = 2
3633
     * @param bool $getCount Optional. Allow get the number of rows from the result
3634
     * @return array|int A list with an user list. If $getCount is true then return a the count of registers
3635
     */
3636
    public static function get_users_by_session($id, $status = null, $getCount = false)
3637
    {
3638
        if (empty($id)) {
3639
            return array();
3640
        }
3641
        $id = intval($id);
3642
        $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
3643
        $tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
3644
        $table_access_url_user = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
3645
3646
        $selectedField = 'u.user_id,lastname, firstname, username, relation_type, access_url_id';
3647
3648
        if ($getCount) {
3649
            $selectedField = 'count(1) AS count';
3650
        }
3651
3652
        $sql = "SELECT $selectedField
3653
                FROM $tbl_user u
3654
                INNER JOIN $tbl_session_rel_user
3655
                ON u.user_id = $tbl_session_rel_user.user_id AND
3656
                $tbl_session_rel_user.session_id = $id
3657
                LEFT OUTER JOIN $table_access_url_user uu
3658
                ON (uu.user_id = u.user_id)
3659
                ";
3660
3661
        $urlId = api_get_current_access_url_id();
3662
        if (isset($status) && $status != '') {
3663
            $status = intval($status);
3664
            $sql .= " WHERE relation_type = $status AND (access_url_id = $urlId OR access_url_id is null )";
3665
        } else {
3666
            $sql .= " WHERE (access_url_id = $urlId OR access_url_id is null )";
3667
        }
3668
3669
        $sql .= " ORDER BY relation_type, ";
3670
        $sql .= api_sort_by_first_name() ? ' firstname, lastname' : '  lastname, firstname';
3671
3672
        $result = Database::query($sql);
3673
3674
        if ($getCount) {
3675
            $count = Database::fetch_assoc($result);
3676
3677
            return $count['count'];
3678
        }
3679
3680
        $return = array();
3681
        while ($row = Database::fetch_array($result, 'ASSOC')) {
3682
            $return[] = $row;
3683
        }
3684
3685
        return $return;
3686
    }
3687
3688
    /**
3689
     * The general coach (field: session.id_coach)
3690
     * @param int $user_id user id
3691
     * @param boolean   $asPlatformAdmin The user is platform admin, return everything
3692
     * @return array
3693
     */
3694
    public static function get_sessions_by_general_coach($user_id, $asPlatformAdmin = false)
3695
    {
3696
        $session_table = Database::get_main_table(TABLE_MAIN_SESSION);
3697
        $user_id = intval($user_id);
3698
3699
        // Session where we are general coach
3700
        $sql = "SELECT DISTINCT *
3701
                FROM $session_table";
3702
3703
        if (!$asPlatformAdmin) {
3704
            $sql .= " WHERE id_coach = $user_id";
3705
        }
3706
3707
        if (api_is_multiple_url_enabled()) {
3708
            $tbl_session_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
3709
            $access_url_id = api_get_current_access_url_id();
3710
3711
            $sqlCoach = '';
3712
            if (!$asPlatformAdmin) {
3713
                $sqlCoach = " id_coach = $user_id AND ";
3714
            }
3715
3716
            if ($access_url_id != -1) {
3717
                $sql = 'SELECT DISTINCT session.*
3718
                    FROM ' . $session_table . ' session INNER JOIN ' . $tbl_session_rel_access_url . ' session_rel_url
3719
                    ON (session.id = session_rel_url.session_id)
3720
                    WHERE '.$sqlCoach.' access_url_id = ' . $access_url_id;
3721
            }
3722
        }
3723
        $sql .= ' ORDER by name';
3724
        $result = Database::query($sql);
3725
3726
        return Database::store_result($result, 'ASSOC');
3727
    }
3728
3729
    /**
3730
     * @param int $user_id
3731
     * @return array
3732
     * @deprecated use get_sessions_by_general_coach()
3733
     */
3734
    public static function get_sessions_by_coach($user_id)
3735
    {
3736
        $session_table = Database::get_main_table(TABLE_MAIN_SESSION);
3737
        return Database::select('*', $session_table, array('where' => array('id_coach = ?' => $user_id)));
3738
    }
3739
3740
    /**
3741
     * @param int $user_id
3742
     * @param int $courseId
3743
     * @param int $session_id
3744
     * @return array|bool
3745
     */
3746 View Code Duplication
    public static function get_user_status_in_course_session($user_id, $courseId, $session_id)
3747
    {
3748
        $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
3749
        $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
3750
        $sql = "SELECT session_rcru.status
3751
                FROM $tbl_session_rel_course_rel_user session_rcru, $tbl_user user
3752
                WHERE
3753
                    session_rcru.user_id = user.user_id AND
3754
                    session_rcru.session_id = '" . intval($session_id) . "' AND
3755
                    session_rcru.c_id ='" . intval($courseId) . "' AND
3756
                    user.user_id = " . intval($user_id);
3757
3758
        $result = Database::query($sql);
3759
        $status = false;
3760
        if (Database::num_rows($result)) {
3761
            $status = Database::fetch_row($result);
3762
            $status = $status['0'];
3763
        }
3764
3765
        return $status;
3766
    }
3767
3768
    /**
3769
     * Gets user status within a session
3770
     * @param int $user_id
3771
     * @param int $courseId
3772
     * @param $session_id
3773
     * @return int
3774
     * @assert (null,null,null) === false
3775
     */
3776
    public static function get_user_status_in_session($user_id, $courseId, $session_id)
3777
    {
3778
        if (empty($user_id) or empty($courseId) or empty($session_id)) {
3779
            return false;
3780
        }
3781
        $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
3782
        $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
3783
        $sql = "SELECT session_rcru.status
3784
                FROM $tbl_session_rel_course_rel_user session_rcru, $tbl_user user
3785
                WHERE session_rcru.user_id = user.user_id AND
3786
                    session_rcru.session_id = '" . intval($session_id) . "' AND
3787
                    session_rcru.c_id ='" . intval($courseId) . "' AND
3788
                    user.user_id = " . intval($user_id);
3789
        $result = Database::query($sql);
3790
        $status = false;
3791
        if (Database::num_rows($result)) {
3792
            $status = Database::fetch_row($result);
3793
            $status = $status['0'];
3794
        }
3795
        return $status;
3796
    }
3797
3798
    /**
3799
     * @param int $id
3800
     * @return array
3801
     */
3802
    public static function get_all_sessions_by_promotion($id)
3803
    {
3804
        $t = Database::get_main_table(TABLE_MAIN_SESSION);
3805
        return Database::select('*', $t, array('where' => array('promotion_id = ?' => $id)));
3806
    }
3807
3808
    /**
3809
     * @param int $promotion_id
3810
     * @param array $list
3811
     */
3812
    public static function subscribe_sessions_to_promotion($promotion_id, $list)
3813
    {
3814
        $t = Database::get_main_table(TABLE_MAIN_SESSION);
3815
        $params = array();
3816
        $params['promotion_id'] = 0;
3817
        Database::update($t, $params, array('promotion_id = ?' => $promotion_id));
3818
3819
        $params['promotion_id'] = $promotion_id;
3820
        if (!empty($list)) {
3821
            foreach ($list as $session_id) {
3822
                $session_id = intval($session_id);
3823
                Database::update($t, $params, array('id = ?' => $session_id));
3824
            }
3825
        }
3826
    }
3827
3828
    /**
3829
     * Updates a session status
3830
     * @param	int 	session id
3831
     * @param	int 	status
3832
     */
3833
    public static function set_session_status($session_id, $status)
3834
    {
3835
        $t = Database::get_main_table(TABLE_MAIN_SESSION);
3836
        $params['visibility'] = $status;
3837
        Database::update($t, $params, array('id = ?' => $session_id));
3838
    }
3839
3840
    /**
3841
     * Copies a session with the same data to a new session.
3842
     * The new copy is not assigned to the same promotion. @see subscribe_sessions_to_promotions() for that
3843
     * @param   int     Session ID
3844
     * @param   bool    Whether to copy the relationship with courses
3845
     * @param   bool    Whether to copy the relationship with users
3846
     * @param   bool    New courses will be created
3847
     * @param   bool    Whether to set exercises and learning paths in the new session to invisible by default
3848
     * @return  int     The new session ID on success, 0 otherwise
3849
     * @todo make sure the extra session fields are copied too
3850
     */
3851
    public static function copy(
3852
        $id,
3853
        $copy_courses = true,
3854
        $copy_users = true,
3855
        $create_new_courses = false,
3856
        $set_exercises_lp_invisible = false
3857
    ) {
3858
        $id = intval($id);
3859
        $s = self::fetch($id);
3860
        // Check all dates before copying
3861
        // Get timestamp for now in UTC - see http://php.net/manual/es/function.time.php#117251
3862
        $now = time() - date('Z');
3863
        // Timestamp in one month
3864
        $inOneMonth = $now + (30*24*3600);
3865
        $inOneMonth = api_get_local_time($inOneMonth);
3866
        if (api_strtotime($s['access_start_date']) < $now) {
3867
            $s['access_start_date'] = api_get_local_time($now);
3868
        }
3869
        if (api_strtotime($s['display_start_date']) < $now) {
3870
            $s['display_start_date'] = api_get_local_time($now);
3871
        }
3872
        if (api_strtotime($s['coach_access_start_date']) < $now) {
3873
            $s['coach_access_start_date'] = api_get_local_time($now);
3874
        }
3875
        if (api_strtotime($s['access_end_date']) < $now) {
3876
            $s['access_end_date'] = $inOneMonth;
3877
        }
3878
        if (api_strtotime($s['display_end_date']) < $now) {
3879
            $s['display_end_date'] = $inOneMonth;
3880
        }
3881
        if (api_strtotime($s['coach_access_end_date']) < $now) {
3882
            $s['coach_access_end_date'] = $inOneMonth;
3883
        }
3884
        // Now try to create the session
3885
        $sid = self::create_session(
3886
            $s['name'] . ' ' . get_lang('CopyLabelSuffix'),
3887
            $s['access_start_date'],
3888
            $s['access_end_date'],
3889
            $s['display_start_date'],
3890
            $s['display_end_date'],
3891
            $s['coach_access_start_date'],
3892
            $s['coach_access_end_date'],
3893
            (int)$s['id_coach'],
3894
            $s['session_category_id'],
3895
            (int)$s['visibility'],
3896
            true
3897
        );
3898
3899
        if (!is_numeric($sid) || empty($sid)) {
3900
            return false;
3901
        }
3902
3903
        if ($copy_courses) {
3904
            // Register courses from the original session to the new session
3905
            $courses = self::get_course_list_by_session_id($id);
3906
3907
            $short_courses = $new_short_courses = array();
3908
            if (is_array($courses) && count($courses) > 0) {
3909
                foreach ($courses as $course) {
3910
                    $short_courses[] = $course;
3911
                }
3912
            }
3913
3914
            $courses = null;
3915
3916
            //We will copy the current courses of the session to new courses
3917
            if (!empty($short_courses)) {
3918
                if ($create_new_courses) {
3919
                    //Just in case
3920
                    if (function_exists('ini_set')) {
3921
                        api_set_memory_limit('256M');
3922
                        ini_set('max_execution_time', 0);
3923
                    }
3924
                    $params = array();
3925
                    $params['skip_lp_dates'] = true;
3926
3927
                    foreach ($short_courses as $course_data) {
3928
                        $course_info = CourseManager::copy_course_simple(
3929
                            $course_data['title'].' '.get_lang(
3930
                                'CopyLabelSuffix'
3931
                            ),
3932
                            $course_data['course_code'],
3933
                            $id,
3934
                            $sid,
3935
                            $params
3936
                        );
3937
3938
                        if ($course_info) {
3939
                            //By default new elements are invisible
3940
                            if ($set_exercises_lp_invisible) {
3941
                                $list = new LearnpathList('', $course_info['code'], $sid);
3942
                                $flat_list = $list->get_flat_list();
3943
                                if (!empty($flat_list)) {
3944
                                    foreach ($flat_list as $lp_id => $data) {
3945
                                        api_item_property_update(
3946
                                            $course_info,
3947
                                            TOOL_LEARNPATH,
3948
                                            $lp_id,
3949
                                            'invisible',
3950
                                            api_get_user_id(),
3951
                                            0,
3952
                                            0,
3953
                                            0,
3954
                                            0,
3955
                                            $sid
3956
                                        );
3957
                                    }
3958
                                }
3959
                                $quiz_table = Database::get_course_table(TABLE_QUIZ_TEST);
3960
                                $course_id = $course_info['real_id'];
3961
                                //@todo check this query
3962
                                $sql = "UPDATE $quiz_table SET active = 0
3963
                                        WHERE c_id = $course_id AND session_id = $sid";
3964
                                Database::query($sql);
3965
                            }
3966
                            $new_short_courses[] = $course_info['real_id'];
3967
                        }
3968
                    }
3969
                } else {
3970
                    foreach ($short_courses as $course_data) {
3971
                        $new_short_courses[] = $course_data['id'];
3972
                    }
3973
                }
3974
3975
                $short_courses = $new_short_courses;
3976
                self::add_courses_to_session($sid, $short_courses, true);
3977
                $short_courses = null;
3978
            }
3979
        }
3980
        if ($copy_users) {
3981
            // Register users from the original session to the new session
3982
            $users = self::get_users_by_session($id);
3983
            $short_users = array();
3984
            if (is_array($users) && count($users) > 0) {
3985
                foreach ($users as $user) {
3986
                    $short_users[] = $user['user_id'];
3987
                }
3988
            }
3989
            $users = null;
3990
            //Subscribing in read only mode
3991
            self::subscribe_users_to_session($sid, $short_users, SESSION_VISIBLE_READ_ONLY, true);
3992
            $short_users = null;
3993
        }
3994
        return $sid;
3995
    }
3996
3997
    /**
3998
     * @param int $user_id
3999
     * @param int $session_id
4000
     * @return bool
4001
     */
4002
    static function user_is_general_coach($user_id, $session_id)
4003
    {
4004
        $session_id = intval($session_id);
4005
        $user_id = intval($user_id);
4006
        $session_table = Database::get_main_table(TABLE_MAIN_SESSION);
4007
        $sql = "SELECT DISTINCT id
4008
	         	FROM $session_table
4009
	         	WHERE session.id_coach =  '" . $user_id . "' AND id = '$session_id'";
4010
        $result = Database::query($sql);
4011
        if ($result && Database::num_rows($result)) {
4012
            return true;
4013
        }
4014
        return false;
4015
    }
4016
4017
    /**
4018
     * Get the number of sessions
4019
     * @param  int ID of the URL we want to filter on (optional)
4020
     * @return int Number of sessions
4021
     */
4022 View Code Duplication
    public static function count_sessions($access_url_id = null)
4023
    {
4024
        $session_table = Database::get_main_table(TABLE_MAIN_SESSION);
4025
        $access_url_rel_session_table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
4026
        $sql = "SELECT count(id) FROM $session_table s";
4027
        if (!empty($access_url_id) && $access_url_id == intval($access_url_id)) {
4028
            $sql .= ", $access_url_rel_session_table u " .
4029
                " WHERE s.id = u.session_id AND u.access_url_id = $access_url_id";
4030
        }
4031
        $res = Database::query($sql);
4032
        $row = Database::fetch_row($res);
4033
        return $row[0];
4034
    }
4035
4036
    /**
4037
     * Protect a session to be edited.
4038
     * @param int $id
4039
     * @param bool $checkSession
4040
     * @return mixed | bool true if pass the check, api_not_allowed otherwise
4041
     */
4042
    public static function protectSession($id, $checkSession = true)
4043
    {
4044
        // api_protect_admin_script(true);
4045
        if (self::allowToManageSessions()) {
4046
4047
            if (api_is_platform_admin()) {
4048
                return true;
4049
            }
4050
4051
            if ($checkSession) {
4052
                if (self::allowed($id)) {
4053
                    return true;
4054
                } else {
4055
                    api_not_allowed(true);
4056
                }
4057
            }
4058
        } else {
4059
            api_not_allowed(true);
4060
        }
4061
    }
4062
4063
    /**
4064
     * @param int $id
4065
     * @return bool
4066
     */
4067
    private static function allowed($id)
4068
    {
4069
        $sessionInfo = self::fetch($id);
4070
4071
        if (empty($sessionInfo)) {
4072
            return false;
4073
        }
4074
4075
        if (api_is_platform_admin()) {
4076
            return true;
4077
        }
4078
4079
        $userId = api_get_user_id();
4080
4081
        if (api_is_session_admin() &&
4082
            api_get_setting('allow_session_admins_to_manage_all_sessions') != 'true'
4083
        ) {
4084
            if ($sessionInfo['session_admin_id'] != $userId) {
4085
                return false;
4086
            }
4087
        }
4088
4089
        if (api_is_teacher() &&
4090
            api_get_setting('allow_teachers_to_create_sessions') == 'true'
4091
        ) {
4092
            if ($sessionInfo['id_coach'] != $userId) {
4093
                return false;
4094
            }
4095
        }
4096
4097
        return true;
4098
    }
4099
4100
    /**
4101
     * @return bool
4102
     */
4103
    public static function allowToManageSessions()
4104
    {
4105
        if (self::allowManageAllSessions()) {
4106
            return true;
4107
        }
4108
4109
        $setting = api_get_setting('allow_teachers_to_create_sessions');
4110
4111
        if (api_is_teacher() && $setting == 'true') {
4112
4113
            return true;
4114
        }
4115
4116
        return false;
4117
    }
4118
4119
    /**
4120
     * @return bool
4121
     */
4122
    public static function allowOnlyMySessions()
4123
    {
4124
        if (self::allowToManageSessions() &&
4125
            !api_is_platform_admin() &&
4126
            api_is_teacher()
4127
        ) {
4128
            return true;
4129
        }
4130
4131
        return false;
4132
    }
4133
4134
    /**
4135
     * @return bool
4136
     */
4137
    public static function allowManageAllSessions()
4138
    {
4139
        if (api_is_platform_admin() || api_is_session_admin()) {
4140
            return true;
4141
        }
4142
4143
        return false;
4144
    }
4145
4146
    /**
4147
     * @param $id
4148
     * @return bool
4149
     */
4150
    public static function protect_teacher_session_edit($id)
4151
    {
4152
        if (!api_is_coach($id) && !api_is_platform_admin()) {
4153
            api_not_allowed(true);
4154
        } else {
4155
            return true;
4156
        }
4157
    }
4158
4159
    /**
4160
     * @param int $courseId
4161
     * @return array
4162
     */
4163
    public static function get_session_by_course($courseId)
4164
    {
4165
        $table_session_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
4166
        $table_session = Database::get_main_table(TABLE_MAIN_SESSION);
4167
        $courseId = intval($courseId);
4168
        $sql = "SELECT name, s.id
4169
                FROM $table_session_course sc
4170
                INNER JOIN $table_session s ON (sc.session_id = s.id)
4171
                WHERE sc.c_id = '$courseId' ";
4172
        $result = Database::query($sql);
4173
4174
        return Database::store_result($result);
4175
    }
4176
4177
    /**
4178
     * @param int $user_id
4179
     * @param bool $ignoreVisibilityForAdmins
4180
     * @param bool $ignoreTimeLimit
4181
     *
4182
     * @return array
4183
     */
4184
    public static function get_sessions_by_user($user_id, $ignoreVisibilityForAdmins = false, $ignoreTimeLimit = false)
4185
    {
4186
        $sessionCategories = UserManager::get_sessions_by_category(
4187
            $user_id,
4188
            false,
4189
            $ignoreVisibilityForAdmins,
4190
            $ignoreTimeLimit
4191
        );
4192
4193
        $sessionArray = array();
4194
        if (!empty($sessionCategories)) {
4195
            foreach ($sessionCategories as $category) {
4196
                if (isset($category['sessions'])) {
4197
                    foreach ($category['sessions'] as $session) {
4198
                        $sessionArray[] = $session;
4199
                    }
4200
                }
4201
            }
4202
        }
4203
4204
        return $sessionArray;
4205
    }
4206
4207
    /**
4208
     * @param string $file
4209
     * @param bool $updateSession options:
4210
     *  true: if the session exists it will be updated.
4211
     *  false: if session exists a new session will be created adding a counter session1, session2, etc
4212
     * @param int $defaultUserId
4213
     * @param mixed $logger
4214
     * @param array $extraFields convert a file row to an extra field. Example in CSV file there's a SessionID then it will
4215
     * converted to extra_external_session_id if you set this: array('SessionId' => 'extra_external_session_id')
4216
     * @param string $extraFieldId
4217
     * @param int $daysCoachAccessBeforeBeginning
4218
     * @param int $daysCoachAccessAfterBeginning
4219
     * @param int $sessionVisibility
4220
     * @param array $fieldsToAvoidUpdate
4221
     * @param bool $deleteUsersNotInList
4222
     * @param bool $updateCourseCoaches
4223
     * @param bool $sessionWithCoursesModifier
4224
     * @param int $showDescription
4225
     * @param array $teacherBackupList
4226
     * @param array $groupBackup
4227
     * @return array
4228
     */
4229
    public static function importCSV(
4230
        $file,
4231
        $updateSession,
4232
        $defaultUserId = null,
4233
        $logger = null,
4234
        $extraFields = array(),
4235
        $extraFieldId = null,
4236
        $daysCoachAccessBeforeBeginning = null,
4237
        $daysCoachAccessAfterBeginning = null,
4238
        $sessionVisibility = 1,
4239
        $fieldsToAvoidUpdate = array(),
4240
        $deleteUsersNotInList = false,
4241
        $updateCourseCoaches = false,
4242
        $sessionWithCoursesModifier = false,
4243
        $addOriginalCourseTeachersAsCourseSessionCoaches = true,
4244
        $removeAllTeachersFromCourse = true,
4245
        $showDescription = null,
4246
        &$teacherBackupList = array(),
4247
        &$groupBackup = array()
4248
    ) {
4249
        $content = file($file);
4250
4251
        $error_message = null;
4252
        $session_counter = 0;
4253
        $defaultUserId = empty($defaultUserId) ? api_get_user_id() : (int) $defaultUserId;
4254
4255
        $eol = PHP_EOL;
4256
        if (PHP_SAPI != 'cli') {
4257
            $eol = '<br />';
4258
        }
4259
4260
        $debug = false;
4261
        if (isset($logger)) {
4262
            $debug = true;
4263
        }
4264
4265
        $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
4266
        $tbl_session_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
4267
        $tbl_session_course  = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
4268
        $tbl_session_course_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
4269
4270
        $sessions = array();
4271
4272
        if (!api_strstr($content[0], ';')) {
4273
            $error_message = get_lang('NotCSV');
4274
        } else {
4275
            $tag_names = array();
4276
4277
            foreach ($content as $key => $enreg) {
4278
                $enreg = explode(';', trim($enreg));
4279 View Code Duplication
                if ($key) {
4280
                    foreach ($tag_names as $tag_key => $tag_name) {
4281
                        if (isset($enreg[$tag_key])) {
4282
                            $sessions[$key - 1][$tag_name] = $enreg[$tag_key];
4283
                        }
4284
                    }
4285
                } else {
4286
                    foreach ($enreg as $tag_name) {
4287
                        $tag_names[] = api_preg_replace('/[^a-zA-Z0-9_\-]/', '', $tag_name);
4288
                    }
4289
                    if (!in_array('SessionName', $tag_names) ||
4290
                        !in_array('DateStart', $tag_names) ||
4291
                        !in_array('DateEnd', $tag_names)
4292
                    ) {
4293
                        $error_message = get_lang('NoNeededData');
4294
                        break;
4295
                    }
4296
                }
4297
            }
4298
4299
            $sessionList = array();
4300
            // Looping the sessions.
4301
            foreach ($sessions as $enreg) {
4302
                $user_counter = 0;
4303
                $course_counter = 0;
4304
4305
                if (isset($extraFields) && !empty($extraFields)) {
4306
                    foreach ($extraFields as $original => $to) {
4307
                        $enreg[$to] = isset($enreg[$original]) ? $enreg[$original] : null;
4308
                    }
4309
                }
4310
4311
                $session_name = $enreg['SessionName'];
4312
                // Default visibility
4313
                $visibilityAfterExpirationPerSession = $sessionVisibility;
4314
4315
                if (isset($enreg['VisibilityAfterExpiration'])) {
4316
                    $visibility = $enreg['VisibilityAfterExpiration'];
4317
                    switch ($visibility) {
4318
                        case 'read_only':
4319
                            $visibilityAfterExpirationPerSession = SESSION_VISIBLE_READ_ONLY;
4320
                            break;
4321
                        case 'accessible':
4322
                            $visibilityAfterExpirationPerSession = SESSION_VISIBLE;
4323
                            break;
4324
                        case 'not_accessible':
4325
                            $visibilityAfterExpirationPerSession = SESSION_INVISIBLE;
4326
                            break;
4327
                    }
4328
                }
4329
4330
                if (empty($session_name)) {
4331
                    continue;
4332
                }
4333
4334
                // We assume the dates are already in UTC
4335
                $dateStart = explode('/', $enreg['DateStart']);
4336
                $dateEnd = explode('/', $enreg['DateEnd']);
4337
                $dateStart = $dateStart[0].'-'.$dateStart[1].'-'.$dateStart[2].' 00:00:00';
4338
                $dateEnd = $dateEnd[0].'-'.$dateEnd[1].'-'.$dateEnd[2].' 23:59:59';
4339
4340
                $session_category_id = isset($enreg['SessionCategory']) ? $enreg['SessionCategory'] : null;
4341
                $sessionDescription = isset($enreg['SessionDescription']) ? $enreg['SessionDescription'] : null;
4342
4343
                $extraParameters = null;
4344
                if (!is_null($showDescription)) {
4345
                    $extraParameters .= ' , show_description = '.intval($showDescription);
4346
                }
4347
4348
                $coachBefore = '';
4349
                $coachAfter = '';
4350
4351
                if (!empty($daysCoachAccessBeforeBeginning) && !empty($daysCoachAccessAfterBeginning)) {
4352
                    $date = new \DateTime($dateStart);
4353
                    $interval = new DateInterval(
4354
                        'P'.$daysCoachAccessBeforeBeginning.'D'
4355
                    );
4356
                    $date->sub($interval);
4357
                    $coachBefore = $date->format('Y-m-d h:i');
4358
                    $coachBefore = api_get_utc_datetime($coachBefore);
4359
4360
                    $extraParameters .= " , coach_access_start_date = '$coachBefore'";
4361
4362
                    $date = new \DateTime($dateEnd);
4363
                    $interval = new DateInterval('P'.$daysCoachAccessAfterBeginning.'D');
4364
                    $date->add($interval);
4365
                    $coachAfter = $date->format('Y-m-d h:i');
4366
4367
                    $coachAfter = api_get_utc_datetime($coachAfter);
4368
                    $extraParameters .= " , coach_access_end_date = '$coachAfter'";
4369
                }
4370
4371
                $dateStart = api_get_utc_datetime($dateStart);
4372
                $dateEnd = api_get_utc_datetime($dateEnd);
4373
4374
                $extraSessionParameters = null;
4375
                if (!empty($sessionDescription)) {
4376
                    $extraSessionParameters = " , description = '".Database::escape_string($sessionDescription)."'";
4377
                }
4378
4379
                $sessionCondition = '';
4380
                if (!empty($session_category_id)) {
4381
                    $sessionCondition = " , session_category_id = '$session_category_id' ";
4382
                }
4383
4384
                // Searching a general coach.
4385
                if (!empty($enreg['Coach'])) {
4386
                    $coach_id = UserManager::get_user_id_from_username($enreg['Coach']);
4387
                    if ($coach_id === false) {
4388
                        // If the coach-user does not exist - I'm the coach.
4389
                        $coach_id = $defaultUserId;
4390
                    }
4391
                } else {
4392
                    $coach_id = $defaultUserId;
4393
                }
4394
4395
                if (!$updateSession) {
4396
                    // Always create a session.
4397
                    $unique_name = false;
4398
                    $i = 0;
4399
                    // Change session name, verify that session doesn't exist.
4400
                    $suffix = null;
4401 View Code Duplication
                    while (!$unique_name) {
4402
                        if ($i > 1) {
4403
                            $suffix = ' - ' . $i;
4404
                        }
4405
                        $sql = 'SELECT 1 FROM ' . $tbl_session . '
4406
                                WHERE name="' . Database::escape_string($session_name). $suffix . '"';
4407
                        $rs = Database::query($sql);
4408
4409
                        if (Database::result($rs, 0, 0)) {
4410
                            $i++;
4411
                        } else {
4412
                            $unique_name = true;
4413
                            $session_name .= $suffix;
4414
                        }
4415
                    }
4416
4417
                    // Creating the session.
4418
                    $sql = "INSERT IGNORE INTO $tbl_session SET
4419
                            name = '" . Database::escape_string($session_name). "',
4420
                            id_coach = '$coach_id',
4421
                            access_start_date = '$dateStart',
4422
                            access_end_date = '$dateEnd',
4423
                            display_start_date = '$dateStart',
4424
                            display_end_date = '$dateEnd',
4425
                            visibility = '$visibilityAfterExpirationPerSession',                            
4426
                            session_admin_id = " . $defaultUserId . " 
4427
                            $sessionCondition $extraParameters $extraSessionParameters";
4428
                    Database::query($sql);
4429
4430
                    $session_id = Database::insert_id();
4431
                    if ($debug) {
4432
                        if ($session_id) {
4433 View Code Duplication
                            foreach ($enreg as $key => $value) {
4434
                                if (substr($key, 0, 6) == 'extra_') { //an extra field
4435
                                    self::update_session_extra_field_value($session_id, substr($key, 6), $value);
4436
                                }
4437
                            }
4438
4439
                            $logger->addInfo("Sessions - Session created: #$session_id - $session_name");
4440
                        } else {
4441
                            $logger->addError("Sessions - Session NOT created: $session_name");
4442
                        }
4443
                    }
4444
                    $session_counter++;
4445
                } else {
4446
                    $sessionId = null;
4447
                    if (isset($extraFields) && !empty($extraFields) && !empty($enreg['extra_'.$extraFieldId])) {
4448
                        $sessionId = self::getSessionIdFromOriginalId($enreg['extra_'.$extraFieldId], $extraFieldId);
4449
                        if (empty($sessionId)) {
4450
                            $my_session_result = false;
4451
                        } else {
4452
                            $my_session_result = true;
4453
                        }
4454
                    } else {
4455
                        $my_session_result = self::get_session_by_name($enreg['SessionName']);
4456
                    }
4457
4458
                    if ($my_session_result === false) {
4459
4460
                        // Creating a session.
4461
                        $sql = "INSERT IGNORE INTO $tbl_session SET
4462
                                name = '$session_name',
4463
                                id_coach = '$coach_id',
4464
                                access_start_date = '$dateStart',
4465
                                access_end_date = '$dateEnd',
4466
                                display_start_date = '$dateStart',
4467
                                display_end_date = '$dateEnd',
4468
                                visibility = '$visibilityAfterExpirationPerSession' 
4469
                                $extraParameters 
4470
                                $extraSessionParameters
4471
                                $sessionCondition
4472
                                ";
4473
4474
                        Database::query($sql);
4475
4476
                        // We get the last insert id.
4477
                        $my_session_result = SessionManager::get_session_by_name($enreg['SessionName']);
4478
                        $session_id = $my_session_result['id'];
4479
4480
                        if ($session_id) {
4481 View Code Duplication
                            foreach ($enreg as $key => $value) {
4482
                                if (substr($key, 0, 6) == 'extra_') { //an extra field
4483
                                    self::update_session_extra_field_value($session_id, substr($key, 6), $value);
4484
                                }
4485
                            }
4486
                            if ($debug) {
4487
                                $logger->addInfo("Sessions - #$session_id created: $session_name");
4488
                            }
4489
4490
                            // Delete session-user relation only for students
4491
                            $sql = "DELETE FROM $tbl_session_user
4492
                                    WHERE session_id = '$session_id' AND relation_type <> " . SESSION_RELATION_TYPE_RRHH;
4493
                            Database::query($sql);
4494
4495
                            $sql = "DELETE FROM $tbl_session_course WHERE session_id = '$session_id'";
4496
                            Database::query($sql);
4497
4498
                            // Delete session-course-user relationships students and coaches.
4499 View Code Duplication
                            if ($updateCourseCoaches) {
4500
                                $sql = "DELETE FROM $tbl_session_course_user
4501
                                        WHERE session_id = '$session_id' AND status in ('0', '2')";
4502
                                Database::query($sql);
4503
                            } else {
4504
                                // Delete session-course-user relation ships *only* for students.
4505
                                $sql = "DELETE FROM $tbl_session_course_user
4506
                                        WHERE session_id = '$session_id' AND status <> 2";
4507
                                Database::query($sql);
4508
                            }
4509
                        }
4510
                    } else {
4511
                        // Updating the session.
4512
                        $params = array(
4513
                            'id_coach' => $coach_id,
4514
                            'access_start_date' => $dateStart,
4515
                            'access_end_date' => $dateEnd,
4516
                            'display_start_date' => $dateStart,
4517
                            'display_end_date' => $dateEnd,
4518
                            'visibility' => $visibilityAfterExpirationPerSession,
4519
                            'session_category_id' => $session_category_id
4520
                        );
4521
4522
                        if (!empty($sessionDescription)) {
4523
                            $params['description'] = $sessionDescription;
4524
                        }
4525
4526
                        if (!empty($fieldsToAvoidUpdate)) {
4527
                            foreach ($fieldsToAvoidUpdate as $field) {
4528
                                unset($params[$field]);
4529
                            }
4530
                        }
4531
4532
                        if (isset($sessionId) && !empty($sessionId)) {
4533
                            $session_id = $sessionId;
4534 View Code Duplication
                            if (!empty($enreg['SessionName'])) {
4535
                                ///$params['name'] = $enreg['SessionName'];
4536
                                $sessionName = Database::escape_string($enreg['SessionName']);
4537
                                $sql = "UPDATE $tbl_session SET name = '$sessionName' WHERE id = $session_id";
4538
                                Database::query($sql);
4539
                            }
4540
                        } else {
4541
                            $my_session_result = SessionManager::get_session_by_name($session_name);
4542
                            $session_id = $my_session_result['id'];
4543
                        }
4544
4545
                        if ($debug) {
4546
                            $logger->addError("Sessions - Session #$session_id to be updated: '$session_name'");
4547
                        }
4548
4549
                        if ($session_id) {
4550
                            if ($debug) {
4551
                                $logger->addError("Sessions - Session to be updated #$session_id");
4552
                            }
4553
4554
                            $sessionInfo = api_get_session_info($session_id);
4555
                            $params['show_description'] = isset($sessionInfo['show_description']) ? $sessionInfo['show_description'] : intval($showDescription);
4556
4557
                            if (!empty($daysCoachAccessBeforeBeginning) && !empty($daysCoachAccessAfterBeginning)) {
4558 View Code Duplication
                                if (empty($sessionInfo['nb_days_access_before_beginning']) ||
4559
                                    (!empty($sessionInfo['nb_days_access_before_beginning']) &&
4560
                                        $sessionInfo['nb_days_access_before_beginning'] < $daysCoachAccessBeforeBeginning)
4561
                                ) {
4562
                                    $params['coach_access_start_date'] = $coachBefore;
4563
                                }
4564
4565 View Code Duplication
                                if (empty($sessionInfo['nb_days_access_after_end']) ||
4566
                                    (!empty($sessionInfo['nb_days_access_after_end']) &&
4567
                                        $sessionInfo['nb_days_access_after_end'] < $daysCoachAccessAfterBeginning)
4568
                                ) {
4569
                                    $params['coach_access_end_date'] = $coachAfter;
4570
                                }
4571
                            }
4572
4573
                            Database::update($tbl_session, $params, array('id = ?' => $session_id));
4574
4575 View Code Duplication
                            foreach ($enreg as $key => $value) {
4576
                                if (substr($key, 0, 6) == 'extra_') { //an extra field
4577
                                    self::update_session_extra_field_value($session_id, substr($key, 6), $value);
4578
                                }
4579
                            }
4580
4581
                            // Delete session-user relation only for students
4582
                            $sql = "DELETE FROM $tbl_session_user
4583
                                    WHERE session_id = '$session_id' AND relation_type <> " . SESSION_RELATION_TYPE_RRHH;
4584
                            Database::query($sql);
4585
4586
                            $sql = "DELETE FROM $tbl_session_course WHERE session_id = '$session_id'";
4587
                            Database::query($sql);
4588
4589
                            // Delete session-course-user relationships students and coaches.
4590 View Code Duplication
                            if ($updateCourseCoaches) {
4591
                                $sql = "DELETE FROM $tbl_session_course_user
4592
                                        WHERE session_id = '$session_id' AND status in ('0', '2')";
4593
                                Database::query($sql);
4594
                            } else {
4595
                                // Delete session-course-user relation ships *only* for students.
4596
                                $sql = "DELETE FROM $tbl_session_course_user
4597
                                        WHERE session_id = '$session_id' AND status <> 2";
4598
                                Database::query($sql);
4599
                            }
4600
                        } else {
4601
                            if ($debug) {
4602
                                $logger->addError(
4603
                                    "Sessions - Session not found"
4604
                                );
4605
                            }
4606
                        }
4607
                    }
4608
                    $session_counter++;
4609
                }
4610
4611
                $sessionList[] = $session_id;
4612
                $users = explode('|', $enreg['Users']);
4613
4614
                // Adding the relationship "Session - User" for students
4615
                $userList = array();
4616
4617
                if (is_array($users)) {
4618
                    foreach ($users as $user) {
4619
                        $user_id = UserManager::get_user_id_from_username($user);
4620
                        if ($user_id !== false) {
4621
                            $userList[] = $user_id;
4622
                            // Insert new users.
4623
                            $sql = "INSERT IGNORE INTO $tbl_session_user SET
4624
                                    user_id = '$user_id',
4625
                                    session_id = '$session_id',
4626
                                    registered_at = '" . api_get_utc_datetime() . "'";
4627
                            Database::query($sql);
4628
                            if ($debug) {
4629
                                $logger->addInfo("Sessions - Adding User #$user_id ($user) to session #$session_id");
4630
                            }
4631
                            $user_counter++;
4632
                        }
4633
                    }
4634
                }
4635
4636
                if ($deleteUsersNotInList) {
4637
                    // Getting user in DB in order to compare to the new list.
4638
                    $usersListInDatabase = self::get_users_by_session($session_id, 0);
4639
4640
                    if (!empty($usersListInDatabase)) {
4641
                        if (empty($userList)) {
4642
                            foreach ($usersListInDatabase as $userInfo) {
0 ignored issues
show
Bug introduced by
The expression $usersListInDatabase of type array|integer is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
4643
                                self::unsubscribe_user_from_session($session_id, $userInfo['user_id']);
4644
                            }
4645
                        } else {
4646
                            foreach ($usersListInDatabase as $userInfo) {
0 ignored issues
show
Bug introduced by
The expression $usersListInDatabase of type array|integer is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
4647
                                if (!in_array($userInfo['user_id'], $userList)) {
4648
                                    self::unsubscribe_user_from_session($session_id, $userInfo['user_id']);
4649
                                }
4650
                            }
4651
                        }
4652
                    }
4653
                }
4654
4655
                $courses = explode('|', $enreg['Courses']);
4656
4657
                // See BT#6449
4658
                $onlyAddFirstCoachOrTeacher = false;
4659
4660
                if ($sessionWithCoursesModifier) {
4661
                    if (count($courses) >= 2) {
4662
                        // Only first teacher in course session;
4663
                        $onlyAddFirstCoachOrTeacher = true;
4664
4665
                        // Remove all teachers from course.
4666
                        $removeAllTeachersFromCourse = false;
4667
                    }
4668
                }
4669
4670
                foreach ($courses as $course) {
4671
                    $courseArray = bracketsToArray($course);
4672
                    $course_code = $courseArray[0];
4673
4674
                    if (CourseManager::course_exists($course_code)) {
4675
4676
                        $courseInfo = api_get_course_info($course_code);
4677
                        $courseId = $courseInfo['real_id'];
4678
4679
                        // Adding the course to a session.
4680
                        $sql = "INSERT IGNORE INTO $tbl_session_course
4681
                                SET c_id = '$courseId', session_id='$session_id'";
4682
                        Database::query($sql);
4683
4684
                        SessionManager::installCourse($session_id, $courseInfo['real_id']);
4685
4686
                        if ($debug) {
4687
                            $logger->addInfo("Sessions - Adding course '$course_code' to session #$session_id");
4688
                        }
4689
4690
                        $course_counter++;
4691
4692
                        $course_coaches = isset($courseArray[1]) ? $courseArray[1] : null;
4693
                        $course_users   = isset($courseArray[2]) ? $courseArray[2] : null;
4694
4695
                        $course_users   = explode(',', $course_users);
4696
                        $course_coaches = explode(',', $course_coaches);
4697
4698
                        // Checking if the flag is set TeachersWillBeAddedAsCoachInAllCourseSessions (course_edit.php)
4699
                        $addTeachersToSession = true;
4700
4701
                        if (array_key_exists('add_teachers_to_sessions_courses', $courseInfo)) {
4702
                            $addTeachersToSession = $courseInfo['add_teachers_to_sessions_courses'];
4703
                        }
4704
4705
                        // If any user provided for a course, use the users array.
4706
                        if (empty($course_users)) {
4707
                            if (!empty($userList)) {
4708
                                SessionManager::subscribe_users_to_session_course(
4709
                                    $userList,
4710
                                    $session_id,
4711
                                    $course_code
4712
                                );
4713
                                if ($debug) {
4714
                                    $msg = "Sessions - Adding student list ".implode(', #', $userList)." to course: '$course_code' and session #$session_id";
4715
                                    $logger->addInfo($msg);
4716
                                }
4717
                            }
4718
                        }
4719
4720
                        // Adding coaches to session course user.
4721
                        if (!empty($course_coaches)) {
4722
                            $savedCoaches = array();
4723
                            // only edit if add_teachers_to_sessions_courses is set.
4724
                            if ($addTeachersToSession) {
4725
                                if ($addOriginalCourseTeachersAsCourseSessionCoaches) {
4726
                                    // Adding course teachers as course session teachers.
4727
                                    $alreadyAddedTeachers = CourseManager::get_teacher_list_from_course_code(
4728
                                        $course_code
4729
                                    );
4730
4731
                                    if (!empty($alreadyAddedTeachers)) {
4732
                                        $teachersToAdd = array();
4733
                                        foreach ($alreadyAddedTeachers as $user) {
4734
                                            $teachersToAdd[] = $user['username'];
4735
                                        }
4736
                                        $course_coaches = array_merge(
4737
                                            $course_coaches,
4738
                                            $teachersToAdd
4739
                                        );
4740
                                    }
4741
                                }
4742
4743 View Code Duplication
                                foreach ($course_coaches as $course_coach) {
4744
                                    $coach_id = UserManager::get_user_id_from_username($course_coach);
4745
                                    if ($coach_id !== false) {
4746
                                        // Just insert new coaches
4747
                                        SessionManager::updateCoaches(
4748
                                            $session_id,
4749
                                            $courseId,
4750
                                            array($coach_id),
4751
                                            false
4752
                                        );
4753
4754
                                        if ($debug) {
4755
                                            $logger->addInfo("Sessions - Adding course coach: user #$coach_id ($course_coach) to course: '$course_code' and session #$session_id");
4756
                                        }
4757
                                        $savedCoaches[] = $coach_id;
4758
                                    } else {
4759
                                        $error_message .= get_lang('UserDoesNotExist').' : '.$course_coach.$eol;
4760
                                    }
4761
                                }
4762
                            }
4763
4764
                            // Custom courses/session coaches
4765
                            $teacherToAdd = null;
4766
                            // Only one coach is added.
4767
                            if ($onlyAddFirstCoachOrTeacher == true) {
4768
                                if ($debug) {
4769
                                    $logger->addInfo("onlyAddFirstCoachOrTeacher : true");
4770
                                }
4771
4772 View Code Duplication
                                foreach ($course_coaches as $course_coach) {
4773
                                    $coach_id = UserManager::get_user_id_from_username($course_coach);
4774
                                    if ($coach_id !== false) {
4775
                                        $teacherToAdd = $coach_id;
4776
                                        break;
4777
                                    }
4778
                                }
4779
4780
                                // Un subscribe everyone that's not in the list.
4781
                                $teacherList = CourseManager::get_teacher_list_from_course_code($course_code);
4782 View Code Duplication
                                if (!empty($teacherList)) {
4783
                                    foreach ($teacherList as $teacher) {
4784
                                        if ($teacherToAdd != $teacher['user_id']) {
4785
                                            $sql = "SELECT * FROM ".Database::get_main_table(TABLE_MAIN_COURSE_USER)."
4786
                                                    WHERE
4787
                                                        user_id = ".$teacher['user_id']." AND
4788
                                                        course_code = '".$course_code."'
4789
                                                    ";
4790
4791
                                            $result = Database::query($sql);
4792
                                            $userCourseData = Database::fetch_array($result, 'ASSOC');
4793
                                            $teacherBackupList[$teacher['user_id']][$course_code] = $userCourseData;
4794
4795
                                            $sql = "SELECT * FROM ".Database::get_course_table(TABLE_GROUP_USER)."
4796
                                                    WHERE
4797
                                                        user_id = ".$teacher['user_id']." AND
4798
                                                        c_id = '".$courseInfo['real_id']."'
4799
                                                    ";
4800
4801
                                            $result = Database::query($sql);
4802
                                            while ($groupData = Database::fetch_array($result, 'ASSOC')) {
4803
                                                $groupBackup['user'][$teacher['user_id']][$course_code][$groupData['group_id']] = $groupData;
4804
                                            }
4805
4806
                                            $sql = "SELECT * FROM ".Database::get_course_table(TABLE_GROUP_TUTOR)."
4807
                                                    WHERE
4808
                                                        user_id = ".$teacher['user_id']." AND
4809
                                                        c_id = '".$courseInfo['real_id']."'
4810
                                                    ";
4811
4812
                                            $result = Database::query($sql);
4813
                                            while ($groupData = Database::fetch_array($result, 'ASSOC')) {
4814
                                                $groupBackup['tutor'][$teacher['user_id']][$course_code][$groupData['group_id']] = $groupData;
4815
                                            }
4816
4817
                                            CourseManager::unsubscribe_user(
4818
                                                $teacher['user_id'],
4819
                                                $course_code
4820
                                            );
4821
4822
                                            if ($debug) {
4823
                                                $logger->addInfo("Delete user #".$teacher['user_id']." from base course: $course_code");
4824
                                            }
4825
                                        }
4826
                                    }
4827
                                }
4828
4829
                                if (!empty($teacherToAdd)) {
4830
                                    SessionManager::updateCoaches(
4831
                                        $session_id,
4832
                                        $courseId,
4833
                                        array($teacherToAdd),
4834
                                        true
4835
                                    );
4836
4837
                                    if ($debug) {
4838
                                        $logger->addInfo("Add coach #$teacherToAdd to course $courseId and session $session_id");
4839
                                    }
4840
4841
                                    $userCourseCategory = '';
4842 View Code Duplication
                                    if (isset($teacherBackupList[$teacherToAdd]) &&
4843
                                        isset($teacherBackupList[$teacherToAdd][$course_code])
4844
                                    ) {
4845
                                        $courseUserData = $teacherBackupList[$teacherToAdd][$course_code];
4846
                                        $userCourseCategory = $courseUserData['user_course_cat'];
4847
                                    }
4848
4849
                                    CourseManager::subscribe_user(
4850
                                        $teacherToAdd,
4851
                                        $course_code,
4852
                                        COURSEMANAGER,
4853
                                        0,
4854
                                        $userCourseCategory
4855
                                    );
4856
4857
                                    if ($debug) {
4858
                                        $logger->addInfo("Subscribe user #$teacherToAdd as teacher in course $course_code ");
4859
                                    }
4860
4861 View Code Duplication
                                    if (isset($groupBackup['user'][$teacherToAdd]) &&
4862
                                        isset($groupBackup['user'][$teacherToAdd][$course_code]) &&
4863
                                        !empty($groupBackup['user'][$teacherToAdd][$course_code])
4864
                                    ) {
4865
                                        foreach ($groupBackup['user'][$teacherToAdd][$course_code] as $data) {
4866
                                            GroupManager::subscribe_users(
4867
                                                $teacherToAdd,
4868
                                                $data['group_id'],
4869
                                                $data['c_id']
4870
                                            );
4871
                                        }
4872
                                    }
4873
4874 View Code Duplication
                                    if (isset($groupBackup['tutor'][$teacherToAdd]) &&
4875
                                        isset($groupBackup['tutor'][$teacherToAdd][$course_code]) &&
4876
                                        !empty($groupBackup['tutor'][$teacherToAdd][$course_code])
4877
                                    ) {
4878
                                        foreach ($groupBackup['tutor'][$teacherToAdd][$course_code] as $data) {
4879
                                            GroupManager::subscribe_tutors(
4880
                                                $teacherToAdd,
4881
                                                $data['group_id'],
4882
                                                $data['c_id']
4883
                                            );
4884
                                        }
4885
                                    }
4886
                                }
4887
                            }
4888
4889
                            // See BT#6449#note-195
4890
                            // All coaches are added.
4891
                            if ($removeAllTeachersFromCourse) {
4892
                                if ($debug) {
4893
                                    $logger->addInfo("removeAllTeachersFromCourse true");
4894
                                }
4895
                                $teacherToAdd = null;
4896 View Code Duplication
                                foreach ($course_coaches as $course_coach) {
4897
                                    $coach_id = UserManager::get_user_id_from_username(
4898
                                        $course_coach
4899
                                    );
4900
                                    if ($coach_id !== false) {
4901
                                        $teacherToAdd[] = $coach_id;
4902
                                    }
4903
                                }
4904
4905
                                if (!empty($teacherToAdd)) {
4906
                                    // Deleting all course teachers and adding the only coach as teacher.
4907
                                    $teacherList = CourseManager::get_teacher_list_from_course_code($course_code);
4908
4909 View Code Duplication
                                    if (!empty($teacherList)) {
4910
                                        foreach ($teacherList as $teacher) {
4911
                                            if (!in_array($teacher['user_id'], $teacherToAdd)) {
4912
4913
                                                $sql = "SELECT * FROM ".Database::get_main_table(TABLE_MAIN_COURSE_USER)."
4914
                                                        WHERE
4915
                                                            user_id = ".$teacher['user_id']." AND
4916
                                                            course_code = '".$course_code."'
4917
                                                        ";
4918
4919
                                                $result = Database::query($sql);
4920
                                                $userCourseData = Database::fetch_array($result, 'ASSOC');
4921
                                                $teacherBackupList[$teacher['user_id']][$course_code] = $userCourseData;
4922
4923
                                                $sql = "SELECT * FROM ".Database::get_course_table(TABLE_GROUP_USER)."
4924
                                                    WHERE
4925
                                                        user_id = ".$teacher['user_id']." AND
4926
                                                        c_id = '".$courseInfo['real_id']."'
4927
                                                    ";
4928
4929
                                                $result = Database::query($sql);
4930
                                                while ($groupData = Database::fetch_array($result, 'ASSOC')) {
4931
                                                    $groupBackup['user'][$teacher['user_id']][$course_code][$groupData['group_id']] = $groupData;
4932
                                                }
4933
4934
                                                $sql = "SELECT * FROM ".Database::get_course_table(TABLE_GROUP_TUTOR)."
4935
                                                        WHERE
4936
                                                            user_id = ".$teacher['user_id']." AND
4937
                                                            c_id = '".$courseInfo['real_id']."'
4938
                                                        ";
4939
4940
                                                $result = Database::query($sql);
4941
                                                while ($groupData = Database::fetch_array($result, 'ASSOC')) {
4942
                                                    $groupBackup['tutor'][$teacher['user_id']][$course_code][$groupData['group_id']] = $groupData;
4943
                                                }
4944
4945
                                                CourseManager::unsubscribe_user(
4946
                                                    $teacher['user_id'],
4947
                                                    $course_code
4948
                                                );
4949
4950
                                                if ($debug) {
4951
                                                    $logger->addInfo("Delete user #".$teacher['user_id']." from base course: $course_code");
4952
                                                }
4953
                                            }
4954
                                        }
4955
                                    }
4956
4957
                                    foreach ($teacherToAdd as $teacherId) {
4958
                                        $userCourseCategory = '';
4959 View Code Duplication
                                        if (isset($teacherBackupList[$teacherId]) &&
4960
                                            isset($teacherBackupList[$teacherId][$course_code])
4961
                                        ) {
4962
                                            $courseUserData = $teacherBackupList[$teacherId][$course_code];
4963
                                            $userCourseCategory = $courseUserData['user_course_cat'];
4964
                                        }
4965
4966
                                        CourseManager::subscribe_user(
4967
                                            $teacherId,
4968
                                            $course_code,
4969
                                            COURSEMANAGER,
4970
                                            0,
4971
                                            $userCourseCategory
4972
                                        );
4973
4974
                                        if ($debug) {
4975
                                            $logger->addInfo("Add user as teacher #".$teacherId." in base course: $course_code");
4976
                                        }
4977
4978 View Code Duplication
                                        if (isset($groupBackup['user'][$teacherId]) &&
4979
                                            isset($groupBackup['user'][$teacherId][$course_code]) &&
4980
                                            !empty($groupBackup['user'][$teacherId][$course_code])
4981
                                        ) {
4982
                                            foreach ($groupBackup['user'][$teacherId][$course_code] as $data) {
4983
                                                GroupManager::subscribe_users(
4984
                                                    $teacherId,
4985
                                                    $data['group_id'],
4986
                                                    $data['c_id']
4987
                                                );
4988
                                            }
4989
                                        }
4990
4991 View Code Duplication
                                        if (isset($groupBackup['tutor'][$teacherId]) &&
4992
                                            isset($groupBackup['tutor'][$teacherId][$course_code]) &&
4993
                                            !empty($groupBackup['tutor'][$teacherId][$course_code])
4994
                                        ) {
4995
                                            foreach ($groupBackup['tutor'][$teacherId][$course_code] as $data) {
4996
                                                GroupManager::subscribe_tutors(
4997
                                                    $teacherId,
4998
                                                    $data['group_id'],
4999
                                                    $data['c_id']
5000
                                                );
5001
                                            }
5002
                                        }
5003
                                    }
5004
                                }
5005
                            }
5006
5007
                            // Continue default behaviour.
5008
                            if ($onlyAddFirstCoachOrTeacher == false) {
5009
                                // Checking one more time see BT#6449#note-149
5010
                                $coaches = SessionManager::getCoachesByCourseSession($session_id, $courseId);
5011
                                // Update coaches if only there's 1 course see BT#6449#note-189
5012
                                if (empty($coaches) || count($courses) == 1) {
5013 View Code Duplication
                                    foreach ($course_coaches as $course_coach) {
5014
                                        $course_coach = trim($course_coach);
5015
                                        $coach_id = UserManager::get_user_id_from_username($course_coach);
5016
                                        if ($coach_id !== false) {
5017
                                            // Just insert new coaches
5018
                                            SessionManager::updateCoaches(
5019
                                                $session_id,
5020
                                                $courseId,
5021
                                                array($coach_id),
5022
                                                false
5023
                                            );
5024
5025
                                            if ($debug) {
5026
                                                $logger->addInfo("Sessions - Adding course coach: user #$coach_id ($course_coach) to course: '$course_code' and session #$session_id");
5027
                                            }
5028
                                            $savedCoaches[] = $coach_id;
5029
                                        } else {
5030
                                            $error_message .= get_lang('UserDoesNotExist').' : '.$course_coach.$eol;
5031
                                        }
5032
                                    }
5033
                                }
5034
                            }
5035
                        }
5036
5037
                        // Adding Students, updating relationship "Session - Course - User".
5038
                        $course_users = array_filter($course_users);
5039
5040
                        if (!empty($course_users)) {
5041 View Code Duplication
                            foreach ($course_users as $user) {
5042
                                $user_id = UserManager::get_user_id_from_username($user);
5043
5044
                                if ($user_id !== false) {
5045
                                    SessionManager::subscribe_users_to_session_course(
5046
                                        array($user_id),
5047
                                        $session_id,
5048
                                        $course_code
5049
                                    );
5050
                                    if ($debug) {
5051
                                        $logger->addInfo("Sessions - Adding student: user #$user_id ($user) to course: '$course_code' and session #$session_id");
5052
                                    }
5053
                                } else {
5054
                                    $error_message .= get_lang('UserDoesNotExist').': '.$user.$eol;
5055
                                }
5056
                            }
5057
                        }
5058
5059
                        $inserted_in_course[$course_code] = $courseInfo['title'];
5060
                    }
5061
                }
5062
                $access_url_id = api_get_current_access_url_id();
5063
                UrlManager::add_session_to_url($session_id, $access_url_id);
5064
                $sql = "UPDATE $tbl_session SET nbr_users = '$user_counter', nbr_courses = '$course_counter' WHERE id = '$session_id'";
5065
                Database::query($sql);
5066
            }
5067
        }
5068
5069
        return array(
5070
            'error_message' => $error_message,
5071
            'session_counter' => $session_counter,
5072
            'session_list' => $sessionList,
5073
        );
5074
    }
5075
5076
    /**
5077
     * @param int $sessionId
5078
     * @param int $courseId
5079
     * @return array
5080
     */
5081 View Code Duplication
    public static function getCoachesByCourseSession($sessionId, $courseId)
5082
    {
5083
        $table = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
5084
        $sessionId = intval($sessionId);
5085
        $courseId = intval($courseId);
5086
5087
        $sql = "SELECT user_id FROM $table
5088
                WHERE
5089
                    session_id = '$sessionId' AND
5090
                    c_id = '$courseId' AND
5091
                    status = 2";
5092
        $result = Database::query($sql);
5093
5094
        $coaches = array();
5095
        if (Database::num_rows($result) > 0) {
5096
            while ($row = Database::fetch_row($result)) {
5097
                $coaches[] = $row['user_id'];
5098
            }
5099
        }
5100
5101
        return $coaches;
5102
    }
5103
5104
    /**
5105
     * @param int $sessionId
5106
     * @param int $courseId
5107
     * @return string
5108
     */
5109
    public static function getCoachesByCourseSessionToString(
5110
        $sessionId,
5111
        $courseId
5112
    ) {
5113
        $coaches = self::getCoachesByCourseSession($sessionId, $courseId);
5114
        $list = array();
5115 View Code Duplication
        if (!empty($coaches)) {
5116
            foreach ($coaches as $coachId) {
5117
                $userInfo = api_get_user_info($coachId);
5118
                $list[] = api_get_person_name(
5119
                    $userInfo['firstname'],
5120
                    $userInfo['lastname']
5121
                );
5122
            }
5123
        }
5124
5125
        return array_to_string($list, CourseManager::USER_SEPARATOR);
5126
    }
5127
5128
    /**
5129
     * Get all coaches added in the session - course relationship
5130
     * @param int $sessionId
5131
     * @return array
5132
     */
5133
    public static function getCoachesBySession($sessionId)
5134
    {
5135
        $table = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
5136
        $sessionId = intval($sessionId);
5137
5138
        $sql = "SELECT DISTINCT user_id
5139
                FROM $table
5140
                WHERE session_id = '$sessionId' AND status = 2";
5141
        $result = Database::query($sql);
5142
5143
        $coaches = array();
5144
        if (Database::num_rows($result) > 0) {
5145
            while ($row = Database::fetch_array($result)) {
5146
                $coaches[] = $row['user_id'];
5147
            }
5148
        }
5149
5150
        return $coaches;
5151
    }
5152
5153
    /**
5154
     * @param int $userId
5155
     * @return array
5156
     */
5157
    public static function getAllCoursesFromAllSessionFromDrh($userId)
5158
    {
5159
        $sessions = SessionManager::get_sessions_followed_by_drh($userId);
5160
        $coursesFromSession = array();
5161
        if (!empty($sessions)) {
5162
            foreach ($sessions as $session) {
5163
                $courseList = SessionManager::get_course_list_by_session_id($session['id']);
5164
                foreach ($courseList as $course) {
0 ignored issues
show
Bug introduced by
The expression $courseList of type integer|array is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
5165
                    $coursesFromSession[] = $course['code'];
5166
                }
5167
            }
5168
        }
5169
        return $coursesFromSession;
5170
    }
5171
5172
    /**
5173
     * getAllCoursesFromAllSessions
5174
     *
5175
     * @return array
5176
     */
5177
    public static function getAllCoursesFromAllSessions()
5178
    {
5179
        $sessions = SessionManager::get_sessions_list();
5180
        $coursesFromSession = array();
5181
        if (!empty($sessions)) {
5182
            foreach ($sessions as $session) {
5183
                $courseList = SessionManager::get_course_list_by_session_id($session['id']);
5184
                foreach ($courseList as $course) {
0 ignored issues
show
Bug introduced by
The expression $courseList of type integer|array is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
5185
                    $coursesFromSession[$course['code'].':'.$session['id']] = $course['visual_code'] . ' - ' . $course['title'] . ' (' . $session['name'] . ')';
5186
                }
5187
            }
5188
        }
5189
        return $coursesFromSession;
5190
    }
5191
5192
    /**
5193
     * @param string $status
5194
     * @param int $userId
5195
     * @param bool $getCount
5196
     * @param int  $from
5197
     * @param int  $numberItems
5198
     * @param int $column
5199
     * @param string $direction
5200
     * @param string $keyword
5201
     * @param string $active
5202
     * @param string $lastConnectionDate
5203
     * @param array $sessionIdList
5204
     * @param array $studentIdList
5205
     * @param int $filterByStatus
5206
     * @return array|int
5207
     */
5208
    public static function getAllUsersFromCoursesFromAllSessionFromStatus(
5209
        $status,
5210
        $userId,
5211
        $getCount = false,
5212
        $from = null,
5213
        $numberItems = null,
5214
        $column = 1,
5215
        $direction = 'asc',
5216
        $keyword = null,
5217
        $active = null,
5218
        $lastConnectionDate = null,
5219
        $sessionIdList = array(),
5220
        $studentIdList = array(),
5221
        $filterByStatus = null
5222
    ) {
5223
        $filterByStatus = intval($filterByStatus);
5224
5225
        $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
5226
        $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
5227
        $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
5228
        $tbl_course_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
5229
        $tbl_user_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
5230
        $tbl_course_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
5231
        $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
5232
        $tbl_session_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
5233
5234
        $direction = in_array(strtolower($direction), array('asc', 'desc')) ? $direction : 'asc';
5235
        $column = Database::escape_string($column);
5236
        $userId = intval($userId);
5237
5238
        $limitCondition = null;
5239
5240 View Code Duplication
        if (isset($from) && isset($numberItems)) {
5241
            $from = intval($from);
5242
            $numberItems = intval($numberItems);
5243
            $limitCondition = "LIMIT $from, $numberItems";
5244
        }
5245
5246
        $urlId = api_get_current_access_url_id();
5247
5248
        $sessionConditions = null;
5249
        $courseConditions = null;
5250
        $userConditions = null;
5251
5252
        if (isset($active)) {
5253
            $active = intval($active);
5254
            $userConditions .= " AND active = $active";
5255
        }
5256
5257
        $courseList = CourseManager::get_courses_followed_by_drh($userId, DRH);
5258
        $courseConditions = ' AND 1 <> 1';
5259
        if (!empty($courseList)) {
5260
            $courseIdList = array_column($courseList, 'id');
5261
            $courseConditions = ' AND c.id IN ("'.implode('","', $courseIdList).'")';
5262
        }
5263
5264
        $userConditionsFromDrh = '';
5265
5266
        // Classic DRH
5267
        if (empty($studentIdList)) {
5268
            $studentListSql = UserManager::get_users_followed_by_drh(
5269
                $userId,
5270
                $filterByStatus,
5271
                true,
5272
                false
5273
            );
5274
            $studentIdList = array_keys($studentListSql);
5275
            $studentListSql = "'".implode("','", $studentIdList)."'";
5276
        } else {
5277
            $studentIdList = array_map('intval', $studentIdList);
5278
            $studentListSql = "'".implode("','", $studentIdList)."'";
5279
        }
5280
        if (!empty($studentListSql)) {
5281
            $userConditionsFromDrh = " AND u.user_id IN (".$studentListSql.") ";
5282
        }
5283
5284
        switch ($status) {
5285
            case 'drh':
5286
                break;
5287
            case 'drh_all':
5288
                // Show all by DRH
5289
                if (empty($sessionIdList)) {
5290
                    $sessionsListSql = SessionManager::get_sessions_followed_by_drh(
5291
                        $userId,
5292
                        null,
5293
                        null,
5294
                        false,
5295
                        true,
5296
                        true
5297
                    );
5298
                } else {
5299
                    $sessionIdList = array_map('intval', $sessionIdList);
5300
                    $sessionsListSql = "'".implode("','", $sessionIdList)."'";
5301
                }
5302
                if (!empty($sessionsListSql)) {
5303
                    $sessionConditions = " AND s.id IN (".$sessionsListSql.") ";
5304
                }
5305
                break;
5306
            case 'session_admin':
5307
                $sessionConditions = " AND s.id_coach = $userId ";
5308
                $userConditionsFromDrh = '';
5309
                break;
5310
            case 'admin':
5311
                break;
5312
            case 'teacher':
5313
                $sessionConditions = " AND s.id_coach = $userId ";
5314
                $userConditionsFromDrh = '';
5315
                break;
5316
        }
5317
5318
        $select = "SELECT DISTINCT u.* ";
5319
        $masterSelect = "SELECT DISTINCT * FROM ";
5320
5321
        if ($getCount) {
5322
            $select = "SELECT DISTINCT u.user_id ";
5323
            $masterSelect = "SELECT COUNT(DISTINCT(user_id)) as count FROM ";
5324
        }
5325
5326
        if (!empty($filterByStatus)) {
5327
            $userConditions .= " AND u.status = ".$filterByStatus;
5328
        }
5329
5330
        if (!empty($lastConnectionDate)) {
5331
            $lastConnectionDate = Database::escape_string($lastConnectionDate);
5332
            $userConditions .=  " AND u.last_login <= '$lastConnectionDate' ";
5333
        }
5334
5335 View Code Duplication
        if (!empty($keyword)) {
5336
            $keyword = Database::escape_string($keyword);
5337
            $userConditions .= " AND (
5338
                u.username LIKE '%$keyword%' OR
5339
                u.firstname LIKE '%$keyword%' OR
5340
                u.lastname LIKE '%$keyword%' OR
5341
                u.official_code LIKE '%$keyword%' OR
5342
                u.email LIKE '%$keyword%'
5343
            )";
5344
        }
5345
5346
        $where = " WHERE
5347
                   access_url_id = $urlId
5348
                   $userConditions
5349
        ";
5350
5351
        $userUnion = '';
5352
        if (!empty($userConditionsFromDrh)) {
5353
            $userUnion = "
5354
            UNION (
5355
                $select                    
5356
                FROM $tbl_user u
5357
                INNER JOIN $tbl_user_rel_access_url url ON (url.user_id = u.id)
5358
                $where
5359
                $userConditionsFromDrh
5360
            )";
5361
        }
5362
5363
        $sql = "$masterSelect (
5364
                ($select
5365
                FROM $tbl_session s
5366
                    INNER JOIN $tbl_session_rel_course_rel_user su ON (s.id = su.session_id)
5367
                    INNER JOIN $tbl_user u ON (u.user_id = su.user_id)
5368
                    INNER JOIN $tbl_session_rel_access_url url ON (url.session_id = s.id)
5369
                    $where
5370
                    $sessionConditions
5371
                ) UNION (
5372
                    $select
5373
                    FROM $tbl_course c
5374
                    INNER JOIN $tbl_course_user cu ON (cu.c_id = c.id)
5375
                    INNER JOIN $tbl_user u ON (u.user_id = cu.user_id)
5376
                    INNER JOIN $tbl_course_rel_access_url url ON (url.c_id = c.id)
5377
                    $where
5378
                    $courseConditions
5379
                ) $userUnion
5380
                ) as t1
5381
                ";
5382
5383 View Code Duplication
        if ($getCount) {
5384
            $result = Database::query($sql);
5385
            $count = 0;
5386
            if (Database::num_rows($result)) {
5387
                $rows = Database::fetch_array($result);
5388
                $count = $rows['count'];
5389
            }
5390
            return $count;
5391
        }
5392
5393 View Code Duplication
        if (!empty($column) && !empty($direction)) {
5394
            $column = str_replace('u.', '', $column);
5395
            $sql .= " ORDER BY $column $direction ";
5396
        }
5397
5398
        $sql .= $limitCondition;
5399
        $result = Database::query($sql);
5400
        $result = Database::store_result($result);
0 ignored issues
show
Bug introduced by
It seems like $result can be null; however, store_result() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
5401
5402
        return $result ;
5403
    }
5404
5405
    /**
5406
     * @param int $sessionId
5407
     * @param int $courseId
5408
     * @param array $coachList
5409
     * @param bool $deleteCoachesNotInList
5410
     */
5411
    public static function updateCoaches(
5412
        $sessionId,
5413
        $courseId,
5414
        $coachList,
5415
        $deleteCoachesNotInList = false
5416
    ) {
5417
        $currentCoaches = self::getCoachesByCourseSession($sessionId, $courseId);
5418
5419
        if (!empty($coachList)) {
5420
            foreach ($coachList as $userId) {
5421
                self::set_coach_to_course_session($userId, $sessionId, $courseId);
5422
            }
5423
        }
5424
5425
        if ($deleteCoachesNotInList) {
5426
            if (!empty($coachList)) {
5427
                $coachesToDelete = array_diff($currentCoaches, $coachList);
5428
            } else {
5429
                $coachesToDelete = $currentCoaches;
5430
            }
5431
5432
            if (!empty($coachesToDelete)) {
5433
                foreach ($coachesToDelete as $userId) {
5434
                    self::set_coach_to_course_session(
5435
                        $userId,
5436
                        $sessionId,
5437
                        $courseId,
5438
                        true
5439
                    );
5440
                }
5441
            }
5442
        }
5443
    }
5444
5445
    /**
5446
     * @param array $sessions
5447
     * @param array $sessionsDestination
5448
     * @return string
5449
     */
5450
    public static function copyStudentsFromSession($sessions, $sessionsDestination)
5451
    {
5452
        $messages = array();
5453
        if (!empty($sessions)) {
5454
            foreach ($sessions as $sessionId) {
5455
                $sessionInfo = self::fetch($sessionId);
5456
                $userList = self::get_users_by_session($sessionId, 0);
5457
                if (!empty($userList)) {
5458
                    $newUserList = array();
5459
                    $userToString = null;
5460
                    foreach ($userList as $userInfo) {
0 ignored issues
show
Bug introduced by
The expression $userList of type array|integer is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
5461
                        $newUserList[] = $userInfo['user_id'];
5462
                        $userToString .= $userInfo['firstname'] . ' ' . $userInfo['lastname'] . '<br />';
5463
                    }
5464
5465
                    if (!empty($sessionsDestination)) {
5466
                        foreach ($sessionsDestination as $sessionDestinationId) {
5467
                            $sessionDestinationInfo = self::fetch($sessionDestinationId);
5468
                            $messages[] = Display::return_message(
5469
                                sprintf(get_lang('AddingStudentsFromSessionXToSessionY'), $sessionInfo['name'], $sessionDestinationInfo['name']), 'info', false
5470
                            );
5471
                            if ($sessionId == $sessionDestinationId) {
5472
                                $messages[] = Display::return_message(sprintf(get_lang('SessionXSkipped'), $sessionDestinationId), 'warning', false);
5473
                                continue;
5474
                            }
5475
                            $messages[] = Display::return_message(get_lang('StudentList') . '<br />' . $userToString, 'info', false);
5476
                            SessionManager::subscribe_users_to_session(
5477
                                $sessionDestinationId,
5478
                                $newUserList,
5479
                                SESSION_VISIBLE_READ_ONLY,
5480
                                false
5481
                            );
5482
                        }
5483
                    } else {
5484
                        $messages[] = Display::return_message(get_lang('NoDestinationSessionProvided'), 'warning');
5485
                    }
5486
                } else {
5487
                    $messages[] = Display::return_message(
5488
                        get_lang('NoStudentsFoundForSession').' #'.$sessionInfo['name'],
5489
                        'warning'
5490
                    );
5491
                }
5492
            }
5493
        } else {
5494
            $messages[] = Display::return_message(get_lang('NoData'), 'warning');
5495
        }
5496
        return $messages;
5497
    }
5498
5499
    /**
5500
     * Assign coaches of a session(s) as teachers to a given course (or courses)
5501
     * @param array A list of session IDs
5502
     * @param array A list of course IDs
5503
     * @return string
5504
     */
5505
    public static function copyCoachesFromSessionToCourse($sessions, $courses)
5506
    {
5507
        $coachesPerSession = array();
5508
        foreach ($sessions as $sessionId) {
5509
            $coaches = self::getCoachesBySession($sessionId);
5510
            $coachesPerSession[$sessionId] = $coaches;
5511
        }
5512
5513
        $result = array();
5514
5515
        if (!empty($courses)) {
5516
            foreach ($courses as $courseId) {
5517
                $courseInfo = api_get_course_info_by_id($courseId);
5518
                foreach ($coachesPerSession as $sessionId => $coachList) {
5519
                    CourseManager::updateTeachers(
5520
                        $courseInfo,
5521
                        $coachList,
5522
                        false,
5523
                        false,
5524
                        false
5525
                    );
5526
                    $result[$courseInfo['code']][$sessionId] = $coachList;
5527
                }
5528
            }
5529
        }
5530
        $sessionUrl = api_get_path(WEB_CODE_PATH) . 'admin/resume_session.php?id_session=';
5531
5532
        $htmlResult = null;
5533
5534
        if (!empty($result)) {
5535
            foreach ($result as $courseCode => $data) {
5536
                $url = api_get_course_url($courseCode);
5537
                $htmlResult .= sprintf(
5538
                    get_lang('CoachesSubscribedAsATeacherInCourseX'),
5539
                    Display::url($courseCode, $url, array('target' => '_blank'))
5540
                );
5541
                foreach ($data as $sessionId => $coachList) {
5542
                    $sessionInfo = self::fetch($sessionId);
5543
                    $htmlResult .= '<br />';
5544
                    $htmlResult .= Display::url(
5545
                        get_lang('Session') . ': ' . $sessionInfo['name'] . ' <br />', $sessionUrl . $sessionId, array('target' => '_blank')
5546
                    );
5547
                    $teacherList = array();
5548
                    foreach ($coachList as $coachId) {
5549
                        $userInfo = api_get_user_info($coachId);
5550
                        $teacherList[] = $userInfo['complete_name'];
5551
                    }
5552
                    if (!empty($teacherList)) {
5553
                        $htmlResult .= implode(', ', $teacherList);
5554
                    } else {
5555
                        $htmlResult .= get_lang('NothingToAdd');
5556
                    }
5557
                }
5558
                $htmlResult .= '<br />';
5559
            }
5560
            $htmlResult = Display::return_message($htmlResult, 'normal', false);
5561
        }
5562
        return $htmlResult;
5563
    }
5564
5565
    /**
5566
     * @param string $keyword
5567
     * @param string $active
5568
     * @param string $lastConnectionDate
5569
     * @param array $sessionIdList
5570
     * @param array $studentIdList
5571
     * @param int $userStatus STUDENT|COURSEMANAGER constants
0 ignored issues
show
Documentation introduced by
There is no parameter named $userStatus. Did you maybe mean $filterUserStatus?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function. It has, however, found a similar but not annotated parameter which might be a good fit.

Consider the following example. The parameter $ireland is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $ireland
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was changed, but the annotation was not.

Loading history...
5572
     *
5573
     * @return array|int
5574
     */
5575
    public static function getCountUserTracking(
5576
        $keyword = null,
5577
        $active = null,
5578
        $lastConnectionDate = null,
5579
        $sessionIdList = array(),
5580
        $studentIdList = array(),
5581
        $filterUserStatus = null
5582
    ) {
5583
        $userId = api_get_user_id();
5584
        $drhLoaded = false;
5585
5586
        if (api_is_drh()) {
5587
            if (api_drh_can_access_all_session_content()) {
5588
                $count = self::getAllUsersFromCoursesFromAllSessionFromStatus(
5589
                    'drh_all',
5590
                    $userId,
5591
                    true,
5592
                    null,
5593
                    null,
5594
                    null,
5595
                    null,
5596
                    $keyword,
5597
                    $active,
5598
                    $lastConnectionDate,
5599
                    $sessionIdList,
5600
                    $studentIdList,
5601
                    $filterUserStatus
5602
                );
5603
                $drhLoaded = true;
5604
            }
5605
        }
5606
5607
        if ($drhLoaded == false) {
5608
            $count = UserManager::getUsersFollowedByUser(
5609
                $userId,
5610
                $filterUserStatus,
5611
                false,
5612
                false,
5613
                true,
5614
                null,
5615
                null,
5616
                null,
5617
                null,
5618
                $active,
5619
                $lastConnectionDate,
5620
                api_is_student_boss() ? STUDENT_BOSS : COURSEMANAGER,
5621
                $keyword
5622
            );
5623
        }
5624
5625
        return $count;
5626
    }
5627
5628
    /**
5629
     * Get teachers followed by a user
5630
     * @param int $userId
5631
     * @param int $active
5632
     * @param string $lastConnectionDate
5633
     * @param bool $getCount
5634
     * @param array $sessionIdList
5635
     * @return array|int
5636
     */
5637
    public static function getTeacherTracking(
5638
        $userId,
5639
        $active = 1,
5640
        $lastConnectionDate = null,
5641
        $getCount = false,
5642
        $sessionIdList = array()
5643
    ) {
5644
        $teacherListId = array();
5645
5646
        if (api_is_drh() || api_is_platform_admin()) {
5647
            // Followed teachers by drh
5648
            if (api_drh_can_access_all_session_content()) {
5649
                if (empty($sessionIdList)) {
5650
                    $sessions = SessionManager::get_sessions_followed_by_drh($userId);
5651
                    $sessionIdList = array();
5652
                    foreach ($sessions as $session) {
5653
                        $sessionIdList[] = $session['id'];
5654
                    }
5655
                }
5656
5657
                $sessionIdList = array_map('intval', $sessionIdList);
5658
                $sessionToString = implode("', '",  $sessionIdList);
5659
5660
                $course = Database::get_main_table(TABLE_MAIN_COURSE);
5661
                $sessionCourse = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
5662
                $courseUser = Database::get_main_table(TABLE_MAIN_COURSE_USER);
5663
5664
                // Select the teachers.
5665
                $sql = "SELECT DISTINCT(cu.user_id) FROM $course c
5666
                        INNER JOIN $sessionCourse src ON c.id = src.c_id
5667
                        INNER JOIN $courseUser cu ON (cu.c_id = c.id)
5668
		                WHERE src.session_id IN ('$sessionToString') AND cu.status = 1";
5669
                $result = Database::query($sql);
5670
                while($row = Database::fetch_array($result, 'ASSOC')) {
5671
                    $teacherListId[$row['user_id']] = $row['user_id'];
5672
                }
5673
            } else {
5674
                $teacherResult = UserManager::get_users_followed_by_drh($userId, COURSEMANAGER);
5675
                foreach ($teacherResult as $userInfo) {
5676
                    $teacherListId[] = $userInfo['user_id'];
5677
                }
5678
            }
5679
        }
5680
5681
        if (!empty($teacherListId)) {
5682
            $tableUser = Database::get_main_table(TABLE_MAIN_USER);
5683
5684
            $select = "SELECT DISTINCT u.* ";
5685
            if ($getCount) {
5686
                $select = "SELECT count(DISTINCT(u.user_id)) as count";
5687
            }
5688
5689
            $sql = "$select FROM $tableUser u";
5690
5691
            if (!empty($lastConnectionDate)) {
5692
                $tableLogin = Database::get_main_table(TABLE_STATISTIC_TRACK_E_LOGIN);
5693
                //$sql .= " INNER JOIN $tableLogin l ON (l.login_user_id = u.user_id) ";
5694
            }
5695
            $active = intval($active);
5696
            $teacherListId = implode("','", $teacherListId);
5697
            $where = " WHERE u.active = $active AND u.user_id IN ('$teacherListId') ";
5698
5699
            if (!empty($lastConnectionDate)) {
5700
                $lastConnectionDate = Database::escape_string($lastConnectionDate);
5701
                //$where .= " AND l.login_date <= '$lastConnectionDate' ";
5702
            }
5703
5704
            $sql .= $where;
5705
            $result = Database::query($sql);
5706 View Code Duplication
            if (Database::num_rows($result)) {
5707
                if ($getCount) {
5708
                    $row = Database::fetch_array($result);
5709
                    return $row['count'];
5710
                } else {
5711
5712
                    return Database::store_result($result, 'ASSOC');
5713
                }
5714
            }
5715
        }
5716
5717
        return 0;
5718
    }
5719
5720
    /**
5721
     * Get the list of course tools that have to be dealt with in case of
5722
     * registering any course to a session
5723
     * @return array The list of tools to be dealt with (literal names)
5724
     */
5725
    public static function getCourseToolToBeManaged()
5726
    {
5727
        return array(
5728
            'courseDescription',
5729
            'courseIntroduction',
5730
        );
5731
    }
5732
5733
    /**
5734
     * Calls the methods bound to each tool when a course is registered into a session
5735
     * @param int $sessionId
5736
     * @param int $courseId
5737
     * @return void
5738
     */
5739 View Code Duplication
    public static function installCourse($sessionId, $courseId)
5740
    {
5741
        return true;
5742
        $toolList = self::getCourseToolToBeManaged();
0 ignored issues
show
Unused Code introduced by
$toolList = self::getCourseToolToBeManaged(); does not seem to be 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...
5743
5744
        foreach ($toolList as $tool) {
5745
            $method = 'add' . $tool;
5746
            if (method_exists(get_class(), $method)) {
5747
                self::$method($sessionId, $courseId);
5748
            }
5749
        }
5750
    }
5751
5752
    /**
5753
     * Calls the methods bound to each tool when a course is unregistered from
5754
     * a session
5755
     * @param int $sessionId
5756
     * @param int $courseId
5757
     */
5758 View Code Duplication
    public static function unInstallCourse($sessionId, $courseId)
5759
    {
5760
        return true;
5761
        $toolList = self::getCourseToolToBeManaged();
0 ignored issues
show
Unused Code introduced by
$toolList = self::getCourseToolToBeManaged(); does not seem to be 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...
5762
5763
        foreach ($toolList as $tool) {
5764
            $method = 'remove' . $tool;
5765
            if (method_exists(get_class(), $method)) {
5766
                self::$method($sessionId, $courseId);
5767
            }
5768
        }
5769
    }
5770
5771
    /**
5772
     * @param int $sessionId
5773
     * @param int $courseId
5774
     */
5775 View Code Duplication
    public static function addCourseIntroduction($sessionId, $courseId)
5776
    {
5777
        // @todo create a tool intro lib
5778
        $sessionId = intval($sessionId);
5779
        $courseId = intval($courseId);
5780
5781
        $TBL_INTRODUCTION = Database::get_course_table(TABLE_TOOL_INTRO);
5782
        $sql = "SELECT * FROM $TBL_INTRODUCTION WHERE c_id = $courseId";
5783
        $result = Database::query($sql);
5784
        $result = Database::store_result($result, 'ASSOC');
0 ignored issues
show
Bug introduced by
It seems like $result can be null; however, store_result() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
5785
5786
        if (!empty($result)) {
5787
            foreach ($result as $result) {
5788
                // @todo check if relation exits.
5789
                $result['session_id'] = $sessionId;
5790
                Database::insert($TBL_INTRODUCTION, $result);
5791
            }
5792
        }
5793
    }
5794
5795
    /**
5796
     * @param int $sessionId
5797
     * @param int $courseId
5798
     */
5799
    public static function removeCourseIntroduction($sessionId, $courseId)
5800
    {
5801
        $sessionId = intval($sessionId);
5802
        $courseId = intval($courseId);
5803
        $TBL_INTRODUCTION = Database::get_course_table(TABLE_TOOL_INTRO);
5804
        $sql = "DELETE FROM $TBL_INTRODUCTION
5805
                WHERE c_id = $courseId AND session_id = $sessionId";
5806
        Database::query($sql);
5807
    }
5808
5809
    /**
5810
     * @param int $sessionId
5811
     * @param int $courseId
5812
     */
5813
    public static function addCourseDescription($sessionId, $courseId)
5814
    {
5815
        /* $description = new CourseDescription();
5816
          $descriptions = $description->get_descriptions($courseId);
5817
          foreach ($descriptions as $description) {
5818
          } */
5819
    }
5820
5821
    /**
5822
     * @param int $sessionId
5823
     * @param int $courseId
5824
     */
5825
    public static function removeCourseDescription($sessionId, $courseId)
5826
    {
5827
5828
    }
5829
5830
    /**
5831
     * @param array $userSessionList format see self::importSessionDrhCSV()
5832
     * @param bool $sendEmail
5833
     * @param bool $removeOldRelationShips
5834
     * @return string
5835
     */
5836
    public static function subscribeDrhToSessionList($userSessionList, $sendEmail, $removeOldRelationShips)
5837
    {
5838
        if (!empty($userSessionList)) {
5839
            foreach ($userSessionList as $userId => $data) {
5840
                $sessionList = array();
5841
                foreach ($data['session_list'] as $sessionInfo) {
5842
                    $sessionList[] = $sessionInfo['session_id'];
5843
                }
5844
                $userInfo = $data['user_info'];
5845
                self::subscribeSessionsToDrh(
5846
                    $userInfo,
5847
                    $sessionList,
5848
                    $sendEmail,
5849
                    $removeOldRelationShips
5850
                );
5851
            }
5852
        }
5853
    }
5854
5855
    /**
5856
     * @param array $userSessionList format see self::importSessionDrhCSV()
5857
     *
5858
     * @return string
5859
     */
5860
    public static function checkSubscribeDrhToSessionList($userSessionList)
5861
    {
5862
        $message = null;
5863
        if (!empty($userSessionList)) {
5864
            if (!empty($userSessionList)) {
5865
                foreach ($userSessionList as $userId => $data) {
5866
                    $userInfo = $data['user_info'];
5867
5868
                    $sessionListSubscribed = self::get_sessions_followed_by_drh($userId);
5869
                    if (!empty($sessionListSubscribed)) {
5870
                        $sessionListSubscribed = array_keys($sessionListSubscribed);
5871
                    }
5872
5873
                    $sessionList = array();
5874
                    if (!empty($data['session_list'])) {
5875
                        foreach ($data['session_list'] as $sessionInfo) {
5876
                            if (in_array($sessionInfo['session_id'], $sessionListSubscribed)) {
5877
                                $sessionList[] = $sessionInfo['session_info']['name'];
5878
                            }
5879
                        }
5880
                    }
5881
5882
                    $message .= '<strong>' . get_lang('User') . '</strong> ' . $userInfo['complete_name'] . ' <br />';
5883
5884
                    if (!in_array($userInfo['status'], array(DRH)) && !api_is_platform_admin_by_id($userInfo['user_id'])) {
5885
                        $message .= get_lang('UserMustHaveTheDrhRole') . '<br />';
5886
                        continue;
5887
                    }
5888
5889
                    if (!empty($sessionList)) {
5890
                        $message .= '<strong>' . get_lang('Sessions') . ':</strong> <br />';
5891
                        $message .= implode(', ', $sessionList) . '<br /><br />';
5892
                    } else {
5893
                        $message .= get_lang('NoSessionProvided') . ' <br /><br />';
5894
                    }
5895
                }
5896
            }
5897
        }
5898
5899
        return $message;
5900
    }
5901
5902
    /**
5903
     * @param string $file
5904
     * @param bool $sendEmail
5905
     * @param bool $removeOldRelationShips
5906
     *
5907
     * @return string
5908
     */
5909
    public static function importSessionDrhCSV($file, $sendEmail, $removeOldRelationShips)
5910
    {
5911
        $list = Import::csv_reader($file);
5912
5913
        if (!empty($list)) {
5914
            $userSessionList = array();
5915
            foreach ($list as $data) {
5916
                $userInfo = api_get_user_info_from_username($data['Username']);
5917
                $sessionInfo = self::get_session_by_name($data['SessionName']);
5918
5919
                if (!empty($userInfo) && !empty($sessionInfo)) {
5920
                    $userSessionList[$userInfo['user_id']]['session_list'][] = array(
5921
                        'session_id' => $sessionInfo['id'],
5922
                        'session_info' => $sessionInfo,
5923
                    );
5924
                    $userSessionList[$userInfo['user_id']]['user_info'] = $userInfo;
5925
                }
5926
            }
5927
5928
            self::subscribeDrhToSessionList($userSessionList, $sendEmail, $removeOldRelationShips);
5929
            return self::checkSubscribeDrhToSessionList($userSessionList);
5930
        }
5931
    }
5932
5933
    /**
5934
     * Courses re-ordering in resume_session.php flag see BT#8316
5935
     */
5936
    public static function orderCourseIsEnabled()
5937
    {
5938
        $sessionCourseOrder = api_get_setting('session_course_ordering');
5939
        if ($sessionCourseOrder === 'true') {
5940
            return true;
5941
        }
5942
5943
        return false;
5944
    }
5945
5946
    /**
5947
     * @param string $direction (up/down)
5948
     * @param int $sessionId
5949
     * @param int $courseId
5950
     * @return bool
5951
     */
5952
    public static function move($direction, $sessionId, $courseId)
5953
    {
5954
        if (!self::orderCourseIsEnabled()) {
5955
            return false;
5956
        }
5957
5958
        $sessionId = intval($sessionId);
5959
        $courseId = intval($courseId);
5960
5961
        $table = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
5962
        $courseList = self::get_course_list_by_session_id($sessionId, null, 'position');
5963
5964
        $position = array();
5965
        $count = 0;
5966
        foreach ($courseList as $course) {
0 ignored issues
show
Bug introduced by
The expression $courseList of type integer|array is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
5967
            if ($course['position'] == '') {
5968
                $course['position'] = $count;
5969
            }
5970
            $position[$course['code']] = $course['position'];
5971
            // Saving current order.
5972
            $sql = "UPDATE $table SET position = $count
5973
                    WHERE session_id = $sessionId AND c_id = '".$course['real_id']."'";
5974
            Database::query($sql);
5975
            $count++;
5976
        }
5977
5978
        // Loading new positions.
5979
        $courseList = self::get_course_list_by_session_id($sessionId, null, 'position');
5980
5981
        $found = false;
5982
5983
        switch ($direction) {
5984
            case 'up':
5985
                $courseList = array_reverse($courseList);
5986
                break;
5987
            case 'down':
5988
                break;
5989
        }
5990
5991
        foreach ($courseList as $course) {
0 ignored issues
show
Bug introduced by
The expression $courseList of type integer|array is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
5992
            if ($found) {
5993
                $nextId = $course['real_id'];
5994
                $nextOrder = $course['position'];
5995
                break;
5996
            }
5997
5998
            if ($courseId == $course['real_id']) {
5999
                $thisCourseCode = $course['real_id'];
6000
                $thisOrder = $course['position'];
6001
                $found = true;
6002
            }
6003
        }
6004
6005
        $sql1 = "UPDATE $table SET position = '".intval($nextOrder)."'
6006
                 WHERE session_id = $sessionId AND c_id =  $thisCourseCode";
6007
        Database::query($sql1);
6008
6009
        $sql2 = "UPDATE $table SET position = '".intval($thisOrder)."'
6010
                 WHERE session_id = $sessionId AND c_id = $nextId";
6011
        Database::query($sql2);
6012
6013
        return true;
6014
    }
6015
6016
    /**
6017
     * @param int $sessionId
6018
     * @param int $courseId
6019
     * @return bool
6020
     */
6021
    public static function moveUp($sessionId, $courseId)
6022
    {
6023
        return self::move('up', $sessionId, $courseId);
6024
    }
6025
6026
    /**
6027
     * @param int $sessionId
6028
     * @param string $courseCode
6029
     * @return bool
6030
     */
6031
    public static function moveDown($sessionId, $courseCode)
6032
    {
6033
        return self::move('down', $sessionId, $courseCode);
6034
    }
6035
6036
    /**
6037
     * Use the session duration to allow/block user access see BT#8317
6038
     * Needs these DB changes
6039
     * ALTER TABLE session ADD COLUMN duration int;
6040
     * ALTER TABLE session_rel_user ADD COLUMN duration int;
6041
     */
6042
    public static function durationPerUserIsEnabled()
6043
    {
6044
        return api_get_configuration_value('session_duration_feature');
6045
    }
6046
6047
    /**
6048
     * Returns the number of days the student has left in a session when using
6049
     * sessions durations
6050
     * @param int $userId
6051
     * @param int $sessionId
6052
     * @param int $duration in days
6053
     * @return int
6054
     */
6055
    public static function getDayLeftInSession($sessionId, $userId, $duration)
6056
    {
6057
        // Get an array with the details of the first access of the student to
6058
        // this session
6059
        $courseAccess = CourseManager::getFirstCourseAccessPerSessionAndUser(
6060
            $sessionId,
6061
            $userId
6062
        );
6063
6064
        $currentTime = time();
6065
6066
        // If no previous access, return false
6067
        if (count($courseAccess) == 0) {
6068
            return false;
6069
        }
6070
6071
        $firstAccess = api_strtotime($courseAccess['login_course_date'], 'UTC');
6072
6073
        $endDateInSeconds = $firstAccess + $duration*24*60*60;
6074
        $leftDays = round(($endDateInSeconds- $currentTime) / 60 / 60 / 24);
6075
6076
        return $leftDays;
6077
    }
6078
6079
    /**
6080
     * @param int $duration
6081
     * @param int $userId
6082
     * @param int $sessionId
6083
     */
6084
    public static function editUserSessionDuration($duration, $userId, $sessionId)
6085
    {
6086
        $duration = intval($duration);
6087
        $userId = intval($userId);
6088
        $sessionId = intval($sessionId);
6089
6090
        if (empty($userId) || empty($sessionId)) {
6091
            return false;
6092
        }
6093
6094
        $table = Database::get_main_table(TABLE_MAIN_SESSION_USER);
6095
        $parameters = array('duration' => $duration);
6096
        $where = array('session_id = ? AND user_id = ? ' => array($sessionId, $userId));
6097
        Database::update($table, $parameters, $where);
6098
    }
6099
6100
    /**
6101
     * Gets one row from the session_rel_user table
6102
     * @param int $userId
6103
     * @param int $sessionId
6104
     *
6105
     * @return array
6106
     */
6107 View Code Duplication
    public static function getUserSession($userId, $sessionId)
6108
    {
6109
        $userId = intval($userId);
6110
        $sessionId = intval($sessionId);
6111
6112
        if (empty($userId) || empty($sessionId)) {
6113
            return false;
6114
        }
6115
6116
        $table = Database::get_main_table(TABLE_MAIN_SESSION_USER);
6117
        $sql = "SELECT * FROM $table
6118
                WHERE session_id = $sessionId AND user_id = $userId";
6119
        $result = Database::query($sql);
6120
        $values = array();
6121
        if (Database::num_rows($result)) {
6122
            $values = Database::fetch_array($result, 'ASSOC');
6123
        }
6124
6125
        return $values;
6126
    }
6127
6128
    /**
6129
     * Check if user is subscribed inside a session as student
6130
     * @param int $sessionId The session id
6131
     * @param int $userId The user id
6132
     * @return boolean Whether is subscribed
6133
     */
6134
    public static function isUserSubscribedAsStudent($sessionId, $userId)
6135
    {
6136
        $sessionRelUserTable = Database::get_main_table(TABLE_MAIN_SESSION_USER);
6137
6138
        $sessionId = intval($sessionId);
6139
        $userId = intval($userId);
6140
6141
        // COUNT(1) actually returns the number of rows from the table (as if
6142
        // counting the results from the first column)
6143
        $sql = "SELECT COUNT(1) AS qty FROM $sessionRelUserTable
6144
                WHERE
6145
                    session_id = $sessionId AND
6146
                    user_id = $userId AND
6147
                    relation_type = 0";
6148
6149
        $result = Database::fetch_assoc(Database::query($sql));
0 ignored issues
show
Bug introduced by
It seems like \Database::query($sql) can be null; however, fetch_assoc() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
6150
6151
        if (!empty($result) && $result['qty'] > 0) {
6152
            return true;
6153
        }
6154
6155
        return false;
6156
    }
6157
6158
    /**
6159
     * Get the session coached by a user (general coach and course-session coach)
6160
     * @param int $coachId The coach id
6161
     * @param boolean $checkSessionRelUserVisibility Check the session visibility
6162
     * @param boolean $asPlatformAdmin The user is a platform admin and we want all sessions
6163
     * @return array The session list
6164
     */
6165
    public static function getSessionsCoachedByUser($coachId, $checkSessionRelUserVisibility = false, $asPlatformAdmin = false)
6166
    {
6167
        // Get all sessions where $coachId is the general coach
6168
        $sessions = self::get_sessions_by_general_coach($coachId, $asPlatformAdmin);
6169
        // Get all sessions where $coachId is the course - session coach
6170
        $courseSessionList = self::getCoursesListByCourseCoach($coachId);
6171
        $sessionsByCoach = array();
6172
        if (!empty($courseSessionList)) {
6173
            foreach ($courseSessionList as $userCourseSubscription) {
6174
                $session = $userCourseSubscription->getSession();
6175
                $sessionsByCoach[$session->getId()] = api_get_session_info(
6176
                    $session->getId()
6177
                );
6178
            }
6179
        }
6180
6181
        if (!empty($sessionsByCoach)) {
6182
            $sessions = array_merge($sessions, $sessionsByCoach);
6183
        }
6184
6185
        // Remove repeated sessions
6186
        if (!empty($sessions)) {
6187
            $cleanSessions = array();
6188
            foreach ($sessions as $session) {
6189
                $cleanSessions[$session['id']] = $session;
6190
            }
6191
            $sessions = $cleanSessions;
6192
        }
6193
6194
        if ($checkSessionRelUserVisibility) {
6195
            if (!empty($sessions)) {
6196
                $newSessions = array();
6197
                foreach ($sessions as $session) {
6198
                    $visibility = api_get_session_visibility($session['id']);
6199
                    if ($visibility == SESSION_INVISIBLE) {
6200
                        continue;
6201
                    }
6202
                    $newSessions[] = $session;
6203
                }
6204
                $sessions = $newSessions;
6205
            }
6206
        }
6207
6208
        return $sessions;
6209
    }
6210
6211
    /**
6212
     * Check if the course belongs to the session
6213
     * @param int $sessionId The session id
6214
     * @param string $courseCode The course code
6215
     *
6216
     * @return bool
6217
     */
6218
    public static function sessionHasCourse($sessionId, $courseCode)
6219
    {
6220
        $sessionId = intval($sessionId);
6221
        $courseCode = Database::escape_string($courseCode);
6222
6223
        $courseTable = Database::get_main_table(TABLE_MAIN_COURSE);
6224
        $sessionRelCourseTable = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
6225
6226
        $sql = "SELECT COUNT(1) AS qty
6227
                FROM $courseTable c
6228
                INNER JOIN $sessionRelCourseTable src
6229
                ON c.id = src.c_id
6230
                WHERE src.session_id = $sessionId
6231
                AND c.code = '$courseCode'  ";
6232
6233
        $result = Database::query($sql);
6234
6235
        if ($result !== false) {
6236
            $data = Database::fetch_assoc($result);
6237
6238
            if ($data['qty'] > 0) {
6239
                return true;
6240
            }
6241
        }
6242
6243
        return false;
6244
    }
6245
6246
    /**
6247
     * Get the list of course coaches
6248
     * @return array The list
6249
     */
6250
    public static function getAllCourseCoaches()
6251
    {
6252
        $coaches = array();
6253
6254
        $scuTable = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
6255
        $userTable = Database::get_main_table(TABLE_MAIN_USER);
6256
6257
        $idResult = Database::select('DISTINCT user_id', $scuTable, array(
6258
            'where' => array(
6259
                'status = ?' => 2,
6260
            ),
6261
        ));
6262
6263
        if ($idResult != false) {
6264
            foreach ($idResult as $idData) {
6265
                $userResult = Database::select('user_id, lastname, firstname, username', $userTable, array(
6266
                    'where' => array(
6267
                        'user_id = ?' => $idData['user_id'],
6268
                    ),
6269
                ), 'first');
6270
6271
                if ($userResult != false) {
6272
                    $coaches[] = array(
6273
                        'id' => $userResult['user_id'],
6274
                        'lastname' => $userResult['lastname'],
6275
                        'firstname' => $userResult['firstname'],
6276
                        'username' => $userResult['username'],
6277
                        'completeName' => api_get_person_name(
6278
                            $userResult['firstname'],
6279
                            $userResult['lastname']
6280
                        ),
6281
                    );
6282
                }
6283
            }
6284
        }
6285
6286
        return $coaches;
6287
    }
6288
6289
    /**
6290
     * Calculate the total user time in the platform
6291
     * @param int $userId The user id
6292
     * @param string $from Optional. From date
6293
     * @param string $until Optional. Until date
6294
     * @return string The time (hh:mm:ss)
6295
     */
6296
    public static function getTotalUserTimeInPlatform($userId, $from = '', $until = '')
6297
    {
6298
        $userId = intval($userId);
6299
6300
        $trackLoginTable = Database::get_main_table(TABLE_STATISTIC_TRACK_E_LOGIN);
6301
6302
        $whereConditions = array(
6303
            'login_user_id = ? ' => $userId,
6304
        );
6305
6306 View Code Duplication
        if (!empty($from) && !empty($until)) {
6307
            $whereConditions["AND (login_date >= '?' "] = $from;
6308
            $whereConditions["AND logout_date <= DATE_ADD('?', INTERVAL 1 DAY)) "] = $until;
6309
        }
6310
6311
        $trackResult = Database::select(
6312
            'SEC_TO_TIME(SUM(UNIX_TIMESTAMP(logout_date) - UNIX_TIMESTAMP(login_date))) as total_time',
6313
            $trackLoginTable,
6314
            array(
6315
                'where' => $whereConditions,
6316
            ), 'first'
6317
        );
6318
6319
        if ($trackResult != false) {
6320
            return $trackResult['total_time'] ? $trackResult['total_time'] : '00:00:00';
6321
        }
6322
6323
        return '00:00:00';
6324
    }
6325
6326
    /**
6327
     * Get the courses list by a course coach
6328
     * @param int $coachId The coach id
6329
     * @return array (id, user_id, session_id, c_id, visibility, status, legal_agreement)
6330
     */
6331
    public static function getCoursesListByCourseCoach($coachId)
6332
    {
6333
        $entityManager = Database::getManager();
6334
        $scuRepo = $entityManager->getRepository(
6335
            'ChamiloCoreBundle:SessionRelCourseRelUser'
6336
        );
6337
6338
        return $scuRepo->findBy([
6339
            'user' => $coachId,
6340
            'status' => SessionRelCourseRelUser::STATUS_COURSE_COACH
6341
        ]);
6342
    }
6343
6344
	/**
6345
     * Get the count of user courses in session
6346
     * @param int $sessionId The session id
6347
     * @return array
6348
     */
6349 View Code Duplication
    public static function getTotalUserCoursesInSession($sessionId)
6350
    {
6351
        $tableUser = Database::get_main_table(TABLE_MAIN_USER);
6352
        $table = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
6353
6354
        if (empty($sessionId)) {
6355
            return [];
6356
        }
6357
6358
        $sql = "SELECT 
6359
                    COUNT(u.id) as count, 
6360
                    u.id, 
6361
                    scu.status status_in_session, 
6362
                    u.status user_status
6363
                FROM $table scu
6364
                INNER JOIN $tableUser u 
6365
                ON scu.user_id = u.id
6366
                WHERE scu.session_id = " . intval($sessionId) ."
6367
                GROUP BY u.id";
6368
6369
        $result = Database::query($sql);
6370
6371
        $list = array();
6372
        while ($data = Database::fetch_assoc($result)) {
6373
            $list[] = $data;
6374
        }
6375
6376
        return $list;
6377
    }
6378
6379
6380
    /**
6381
     * Returns list of a few data from session (name, short description, start
6382
     * date, end date) and the given extra fields if defined based on a
6383
     * session category Id.
6384
     * @param int $categoryId The internal ID of the session category
6385
     * @param string $target Value to search for in the session field values
6386
     * @param array $extraFields A list of fields to be scanned and returned
6387
     * @return mixed
6388
     */
6389
    public static function getShortSessionListAndExtraByCategory(
6390
        $categoryId,
6391
        $target,
6392
        $extraFields = null,
6393
        $publicationDate = null
6394
    ) {
6395
        $categoryId = (int) $categoryId;
6396
        $sessionList = array();
6397
        // Check if categoryId is valid
6398
        if ($categoryId > 0) {
6399
            $target = Database::escape_string($target);
6400
            $sTable = Database::get_main_table(TABLE_MAIN_SESSION);
6401
            $sfTable = Database::get_main_table(TABLE_EXTRA_FIELD);
6402
            $sfvTable = Database::get_main_table(TABLE_EXTRA_FIELD_VALUES);
6403
            // Join session field and session field values tables
6404
            $joinTable = $sfTable . ' sf INNER JOIN ' . $sfvTable . ' sfv ON sf.id = sfv.field_id';
6405
            $fieldsArray = array();
6406
            foreach ($extraFields as $field) {
0 ignored issues
show
Bug introduced by
The expression $extraFields of type array|null is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
6407
                $fieldsArray[] = Database::escape_string($field);
6408
            }
6409
            $extraFieldType = ExtraField::SESSION_FIELD_TYPE;
6410
            if (isset ($publicationDate)) {
6411
                $publicationDateString = $publicationDate->format('Y-m-d H:i:s');
6412
                $wherePublication = " AND id NOT IN (
6413
                    SELECT sfv.item_id FROM $joinTable
6414
                    WHERE
6415
                        sf.extra_field_type = $extraFieldType AND
6416
                        ((sf.variable = 'publication_start_date' AND sfv.value > '$publicationDateString' and sfv.value != '') OR
6417
                        (sf.variable = 'publication_end_date' AND sfv.value < '$publicationDateString' and sfv.value != ''))
6418
                )";
6419
            }
6420
            // Get the session list from session category and target
6421
            $sessionList = Database::select(
6422
                'id, name, access_start_date, access_end_date',
6423
                $sTable,
6424
                array(
6425
                    'where' => array(
6426
                        "session_category_id = ? AND id IN (
6427
                            SELECT sfv.item_id FROM $joinTable
6428
                            WHERE
6429
                                sf.extra_field_type = $extraFieldType AND
6430
                                sfv.item_id = session.id AND
6431
                                sf.variable = 'target' AND
6432
                                sfv.value = ?
6433
                        ) $wherePublication" => array($categoryId, $target),
6434
                    ),
6435
                )
6436
            );
6437
            $whereFieldVariables = array();
6438
            $whereFieldIds = array();
6439
            if (
6440
                is_array($fieldsArray) &&
6441
                count($fieldsArray) > 0
6442
            ) {
6443
                $whereParams = '?';
6444
                for ($i = 1; $i < count($fieldsArray); $i++) {
6445
                    $whereParams .= ', ?';
6446
                }
6447
                $whereFieldVariables = ' variable IN ( ' . $whereParams .' )';
6448
                $whereFieldIds = 'field_id IN ( ' . $whereParams .  ' )';
6449
            }
6450
            // Get session fields
6451
            $extraField = new ExtraFieldModel('session');
6452
            $questionMarks = substr(str_repeat('?, ', count($fieldsArray)), 0, -2);
6453
            $fieldsList = $extraField->get_all(array(
6454
                ' variable IN ( ' . $questionMarks . ' )' => $fieldsArray,
6455
            ));
6456
            // Index session fields
6457
            foreach ($fieldsList as $field) {
6458
                $fields[$field['id']] = $field['variable'];
6459
            }
6460
            // Get session field values
6461
            $extra = new ExtraFieldValue('session');
6462
            $questionMarksFields = substr(str_repeat('?, ', count($fields)), 0, -2);
6463
            $sessionFieldValueList = $extra->get_all(array ('where' => array('field_id IN ( ' . $questionMarksFields . ' )' => array_keys($fields))));
6464
            // Add session fields values to session list
6465
            foreach ($sessionList as $id => &$session) {
6466
                foreach ($sessionFieldValueList as $sessionFieldValue) {
6467
                    // Match session field values to session
6468
                    if ($sessionFieldValue['item_id'] == $id) {
6469
                        // Check if session field value is set in session field list
6470
                        if (isset($fields[$sessionFieldValue['field_id']])) {
6471
                            // Avoid overwriting the session's ID field
6472
                            if ($fields[$sessionFieldValue['field_id']] != 'id') {
6473
                                $var = $fields[$sessionFieldValue['field_id']];
6474
                                $val = $sessionFieldValue['value'];
6475
                                // Assign session field value to session
6476
                                $session[$var] = $val;
6477
                            }
6478
                        }
6479
                    }
6480
                }
6481
            }
6482
        }
6483
6484
        return $sessionList;
6485
    }
6486
6487
    /**
6488
     * Return the Session Category id searched by name
6489
     * @param string $categoryName Name attribute of session category used for search query
6490
     * @param bool $force boolean used to get even if something is wrong (e.g not unique name)
6491
     * @return int|array If success, return category id (int), else it will return an array
6492
     * with the next structure:
6493
     * array('error' => true, 'errorMessage' => ERROR_MESSAGE)
6494
     */
6495
    public static function getSessionCategoryIdByName($categoryName, $force = false)
6496
    {
6497
        // Start error result
6498
        $errorResult = array('error' => true, 'errorMessage' => get_lang('ThereWasAnError'));
6499
        $categoryName = Database::escape_string($categoryName);
6500
        // Check if is not empty category name
6501
        if (!empty($categoryName)) {
6502
            $sessionCategoryTable = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
6503
            // Get all session category with same name
6504
            $result = Database::select(
6505
                'id',
6506
                $sessionCategoryTable,
6507
                array(
6508
                    'where' => array(
6509
                        'name = ?' => $categoryName,
6510
                    ),
6511
                )
6512
            );
6513
            // Check the result
6514
            if ($result < 1) {
6515
                // If not found any result, update error message
6516
                $errorResult['errorMessage'] = 'Not found any session category name ' . $categoryName;
6517
            } elseif (count($result) > 1 && !$force) {
6518
                // If found more than one result and force is disabled, update error message
6519
                $errorResult['errorMessage'] = 'Found many session categories';
6520
            } elseif (count($result) == 1 || $force) {
6521
                // If found just one session category or force option is enabled
6522
6523
                return key($result);
6524
            }
6525
        } else {
6526
            // category name is empty, update error message
6527
            $errorResult['errorMessage'] = 'Not valid category name';
6528
        }
6529
6530
        return $errorResult;
6531
    }
6532
6533
    /**
6534
     * Return all data from sessions (plus extra field, course and coach data) by category id
6535
     * @param int $sessionCategoryId session category id used to search sessions
6536
     * @return array If success, return session list and more session related data, else it will return an array
6537
     * with the next structure:
6538
     * array('error' => true, 'errorMessage' => ERROR_MESSAGE)
6539
     */
6540
    public static function getSessionListAndExtraByCategoryId($sessionCategoryId)
6541
    {
6542
        // Start error result
6543
        $errorResult = array(
6544
            'error' => true,
6545
            'errorMessage' => get_lang('ThereWasAnError'),
6546
        );
6547
6548
        $sessionCategoryId = intval($sessionCategoryId);
6549
        // Check if session category id is valid
6550
        if ($sessionCategoryId > 0) {
6551
            // Get table names
6552
            $sessionTable = Database::get_main_table(TABLE_MAIN_SESSION);
6553
            $sessionFieldTable = Database::get_main_table(TABLE_EXTRA_FIELD);
6554
            $sessionFieldValueTable = Database::get_main_table(TABLE_EXTRA_FIELD_VALUES);
6555
            $sessionCourseUserTable = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
6556
            $userTable = Database::get_main_table(TABLE_MAIN_USER);
6557
            $courseTable = Database::get_main_table(TABLE_MAIN_COURSE);
6558
6559
            // Get all data from all sessions whit the session category specified
6560
            $sessionList = Database::select(
6561
                '*',
6562
                $sessionTable,
6563
                array(
6564
                    'where' => array(
6565
                        'session_category_id = ?' => $sessionCategoryId,
6566
                    ),
6567
                )
6568
            );
6569
6570
            $extraFieldType = ExtraField::SESSION_FIELD_TYPE;
6571
6572
            // Check if session list query had result
6573
            if (!empty($sessionList)) {
6574
                // implode all session id
6575
                $sessionIdsString = '(' . implode(', ', array_keys($sessionList)) . ')';
6576
                // Get all field variables
6577
                $sessionFieldList = Database::select(
6578
                    'id, variable',
6579
                    $sessionFieldTable,
6580
                    array('extra_field_type = ? ' => array($extraFieldType))
6581
                );
6582
6583
                // Get all field values
6584
                $sql = "SELECT item_id, field_id, value FROM
6585
                        $sessionFieldValueTable v INNER JOIN $sessionFieldTable f
6586
                        ON (f.id = v.field_id)
6587
                        WHERE
6588
                            item_id IN $sessionIdsString AND
6589
                            extra_field_type = $extraFieldType
6590
                ";
6591
                $result = Database::query($sql);
6592
                $sessionFieldValueList = Database::store_result($result, 'ASSOC');
6593
6594
                // Check if session field values had result
6595
                if (!empty($sessionFieldValueList)) {
6596
                    $sessionFieldValueListBySession = array();
6597
                    foreach ($sessionFieldValueList as $key => $sessionFieldValue) {
6598
                        // Create an array to index ids to session id
6599
                        $sessionFieldValueListBySession[$sessionFieldValue['item_id']][] = $key;
6600
                    }
6601
                }
6602
                // Query used to find course-coaches from sessions
6603
                $sql = "SELECT
6604
                            scu.session_id,
6605
                            c.id AS course_id,
6606
                            c.code AS course_code,
6607
                            c.title AS course_title,
6608
                            u.username AS coach_username,
6609
                            u.firstname AS coach_firstname,
6610
                            u.lastname AS coach_lastname
6611
                        FROM $courseTable c
6612
                        INNER JOIN $sessionCourseUserTable scu ON c.id = scu.c_id
6613
                        INNER JOIN $userTable u ON scu.user_id = u.user_id
6614
                        WHERE scu.status = 2 AND scu.session_id IN $sessionIdsString
6615
                        ORDER BY scu.session_id ASC ";
6616
                $res = Database::query($sql);
6617
                $sessionCourseList = Database::store_result($res, 'ASSOC');
6618
                // Check if course list had result
6619
                if (!empty($sessionCourseList)) {
6620
                    foreach ($sessionCourseList as $key => $sessionCourse) {
6621
                        // Create an array to index ids to session_id
6622
                        $sessionCourseListBySession[$sessionCourse['session_id']][] = $key;
6623
                    }
6624
                }
6625
                // Join lists
6626
                if (is_array($sessionList)) {
6627
                    foreach ($sessionList as $id => &$row) {
6628
                        if (
6629
                            !empty($sessionFieldValueListBySession) &&
6630
                            is_array($sessionFieldValueListBySession[$id])
6631
                        ) {
6632
                            // If have an index array for session extra fields, use it to join arrays
6633
                            foreach ($sessionFieldValueListBySession[$id] as $key) {
6634
                                $row['extra'][$key] = array(
6635
                                    'field_name' => $sessionFieldList[$sessionFieldValueList[$key]['field_id']]['variable'],
6636
                                    'value' => $sessionFieldValueList[$key]['value'],
6637
                                );
6638
                            }
6639
                        }
6640
                        if (
6641
                            !empty($sessionCourseListBySession) &&
6642
                            is_array($sessionCourseListBySession[$id])
6643
                        ) {
6644
                            // If have an index array for session course coach, use it to join arrays
6645
                            foreach ($sessionCourseListBySession[$id] as $key) {
6646
                                $row['course'][$key] = array(
6647
                                    'course_id' => $sessionCourseList[$key]['course_id'],
6648
                                    'course_code' => $sessionCourseList[$key]['course_code'],
6649
                                    'course_title' => $sessionCourseList[$key]['course_title'],
6650
                                    'coach_username' => $sessionCourseList[$key]['coach_username'],
6651
                                    'coach_firstname' => $sessionCourseList[$key]['coach_firstname'],
6652
                                    'coach_lastname' => $sessionCourseList[$key]['coach_lastname'],
6653
                                );
6654
                            }
6655
                        }
6656
                    }
6657
                }
6658
6659
                return $sessionList;
6660
            } else {
6661
                // Not found result, update error message
6662
                $errorResult['errorMessage'] = 'Not found any session for session category id ' . $sessionCategoryId;
6663
            }
6664
        }
6665
6666
        return $errorResult;
6667
    }
6668
6669
    /**
6670
     * Return session description from session id
6671
     * @param int $sessionId
6672
     * @return string
6673
     */
6674
    public static function getDescriptionFromSessionId($sessionId)
6675
    {
6676
        // Init variables
6677
        $sessionId = intval($sessionId);
6678
        $description = '';
6679
        // Check if session id is valid
6680
        if ($sessionId > 0) {
6681
            // Select query from session id
6682
            $rows = Database::select(
6683
                'description',
6684
                Database::get_main_table(TABLE_MAIN_SESSION),
6685
                array(
6686
                    'where' => array(
6687
                        'id = ?' => $sessionId,
6688
                    ),
6689
                )
6690
            );
6691
6692
            // Check if select query result is not empty
6693
            if (!empty($rows)) {
6694
                // Get session description
6695
                $description = $rows[0]['description'];
6696
            }
6697
        }
6698
6699
        return $description;
6700
    }
6701
6702
    /**
6703
     * Get a session list filtered by name, description or any of the given extra fields
6704
     * @param string $term The term to search
6705
     * @param array $extraFieldsToInclude Extra fields to include in the session data
6706
     * @return array The list
6707
     */
6708
    public static function searchSession($term, $extraFieldsToInclude = array())
6709
    {
6710
        $sTable = Database::get_main_table(TABLE_MAIN_SESSION);
6711
        $extraFieldTable = Database::get_main_table(TABLE_EXTRA_FIELD);
6712
        $sfvTable = Database::get_main_table(TABLE_EXTRA_FIELD_VALUES);
6713
6714
        $term = Database::escape_string($term);
6715
        $extraFieldType = ExtraField::SESSION_FIELD_TYPE;
6716
        if (is_array($extraFieldsToInclude) && count($extraFieldsToInclude) > 0) {
6717
            $resultData = Database::select('*', $sTable, array(
6718
                'where' => array(
6719
                    "name LIKE %?% " => $term,
6720
                    " OR description LIKE %?% " => $term,
6721
                    " OR id IN (
6722
                    SELECT item_id
6723
                    FROM $sfvTable v INNER JOIN $extraFieldTable e
6724
                    ON (v.field_id = e.id)
6725
                    WHERE value LIKE %?% AND extra_field_type = $extraFieldType
6726
                ) " => $term,
6727
                ),
6728
            ));
6729
        } else {
6730
            $resultData = Database::select('*', $sTable, array(
6731
                'where' => array(
6732
                    "name LIKE %?% " => $term,
6733
                    "OR description LIKE %?% " => $term,
6734
                ),
6735
            ));
6736
6737
            return $resultData;
6738
        }
6739
6740
        foreach ($resultData as $id => &$session) {
6741
            $session['extra'] = self::getFilteredExtraFields($id, $extraFieldsToInclude);
6742
        }
6743
6744
        return $resultData;
6745
    }
6746
6747
    /**
6748
     * @param $sessionId
6749
     * @param array $extraFieldsToInclude
6750
     * @return array
6751
     */
6752
    public static function getFilteredExtraFields($sessionId, $extraFieldsToInclude = array())
6753
    {
6754
        $extraData = array();
6755
6756
        $variables = array();
6757
        $variablePlaceHolders = array();
6758
6759
        foreach ($extraFieldsToInclude as $sessionExtraField) {
6760
            $variablePlaceHolders[] = "?";
6761
            $variables[] = Database::escape_string($sessionExtraField);
6762
        }
6763
6764
        $sessionExtraField = new ExtraFieldModel('session');
6765
        $fieldList = $sessionExtraField->get_all(array(
6766
            "variable IN ( " . implode(", ", $variablePlaceHolders) . " ) " => $variables,
6767
        ));
6768
6769
        $fields = array();
6770
6771
        // Index session fields
6772
        foreach ($fieldList as $field) {
6773
            $fields[$field['id']] = $field['variable'];
6774
        }
6775
6776
        // Get session field values
6777
        $extra = new ExtraFieldValue('session');
6778
        $sessionFieldValueList = $extra->get_all(
6779
            array(
6780
                "field_id IN ( " . implode(", ", $variablePlaceHolders) . " )" => array_keys($fields),
6781
            )
6782
        );
6783
6784
        foreach ($sessionFieldValueList as $sessionFieldValue) {
6785
            // Match session field values to session
6786
            if ($sessionFieldValue['item_id'] != $sessionId) {
6787
                continue;
6788
            }
6789
6790
            // Check if session field value is set in session field list
6791
            if (!isset($fields[$sessionFieldValue['field_id']])) {
6792
                continue;
6793
            }
6794
6795
            $extrafieldVariable = $fields[$sessionFieldValue['field_id']];
6796
            $extrafieldValue = $sessionFieldValue['value'];
6797
6798
            $extraData[] = array(
6799
                'variable' => $extrafieldVariable,
6800
                'value' => $extrafieldValue,
6801
            );
6802
        }
6803
6804
        return $extraData;
6805
    }
6806
6807
    /**
6808
     * @param int $sessionId
6809
     *
6810
     * @return bool
6811
     */
6812
    public static function isValidId($sessionId)
6813
    {
6814
        $sessionId = intval($sessionId);
6815
        if ($sessionId > 0) {
6816
            $rows = Database::select(
6817
                'id',
6818
                Database::get_main_table(TABLE_MAIN_SESSION),
6819
                array('where' => array('id = ?' => $sessionId))
6820
            );
6821
            if (!empty($rows)) {
6822
6823
                return true;
6824
            }
6825
        }
6826
6827
        return false;
6828
    }
6829
6830
    /**
6831
     * Get list of sessions based on users of a group for a group admin
6832
     * @param int $userId The user id
6833
     * @return array
6834
     */
6835 View Code Duplication
    public static function getSessionsFollowedForGroupAdmin($userId)
6836
    {
6837
        $sessionList = array();
6838
        $sessionTable = Database::get_main_table(TABLE_MAIN_SESSION);
6839
        $sessionUserTable = Database::get_main_table(TABLE_MAIN_SESSION_USER);
6840
        $userGroup = new UserGroup();
6841
        $userIdList = $userGroup->getGroupUsersByUser($userId);
6842
6843
        if (empty($userIdList)) {
6844
            return [];
6845
        }
6846
6847
        $sql = "SELECT DISTINCT s.*
6848
                FROM $sessionTable s
6849
                INNER JOIN $sessionUserTable sru 
6850
                ON s.id = sru.id_session
6851
                WHERE
6852
                    (sru.id_user IN (" . implode(', ', $userIdList) . ")
6853
                    AND sru.relation_type = 0
6854
                )";
6855
6856
        if (api_is_multiple_url_enabled()) {
6857
            $sessionAccessUrlTable = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
6858
            $accessUrlId = api_get_current_access_url_id();
6859
6860
            if ($accessUrlId != -1) {
6861
                $sql = "SELECT DISTINCT s.*
6862
                        FROM $sessionTable s
6863
                        INNER JOIN $sessionUserTable sru ON s.id = sru.id_session
6864
                        INNER JOIN $sessionAccessUrlTable srau ON s.id = srau.session_id
6865
                        WHERE
6866
                            srau.access_url_id = $accessUrlId
6867
                            AND (
6868
                                sru.id_user IN (" . implode(', ', $userIdList) . ")
6869
                                AND sru.relation_type = 0
6870
                            )";
6871
            }
6872
        }
6873
6874
        $result = Database::query($sql);
6875
6876
        while ($row = Database::fetch_assoc($result)) {
6877
            $sessionList[] = $row;
6878
        }
6879
6880
        return $sessionList;
6881
    }
6882
6883
    /**
6884
     * @param array $sessionInfo
6885
     * @return string
6886
     */
6887
    public static function getSessionVisibility($sessionInfo)
6888
    {
6889
        switch ($sessionInfo['visibility']) {
6890
            case 1:
6891
                return get_lang('ReadOnly');
6892
            case 2:
6893
               return get_lang('Visible');
6894
            case 3:
6895
                return api_ucfirst(get_lang('Invisible'));
6896
        }
6897
    }
6898
6899
    /**
6900
     * Converts "start date" and "end date" to "From start date to end date" string
6901
     * @param string $startDate
6902
     * @param string $endDate
6903
     * @param bool $showTime
6904
     * @param bool $dateHuman
6905
     *
6906
     * @return string
6907
     */
6908
    private static function convertSessionDateToString($startDate, $endDate, $showTime, $dateHuman)
6909
    {
6910
        // api_get_local_time returns empty if date is invalid like 0000-00-00 00:00:00
6911
        $startDateToLocal = api_get_local_time(
6912
            $startDate,
6913
            null,
6914
            null,
6915
            true,
6916
            $showTime,
6917
            $dateHuman
6918
        );
6919
        $endDateToLocal = api_get_local_time(
6920
            $endDate,
6921
            null,
6922
            null,
6923
            true,
6924
            $showTime,
6925
            $dateHuman
6926
        );
6927
6928
        $result = '';
6929
        if (!empty($startDateToLocal) && !empty($endDateToLocal)) {
6930
            $result = sprintf(
6931
                get_lang('FromDateXToDateY'),
6932
                api_format_date($startDateToLocal, DATE_TIME_FORMAT_LONG_24H),
6933
                api_format_date($endDateToLocal, DATE_TIME_FORMAT_LONG_24H)
6934
            );
6935
        } else {
6936
            if (!empty($startDateToLocal)) {
6937
                $result = get_lang('From').' '.api_format_date($startDateToLocal, DATE_TIME_FORMAT_LONG_24H);
6938
            }
6939
            if (!empty($endDateToLocal)) {
6940
                $result = get_lang('Until').' '.api_format_date($endDateToLocal, DATE_TIME_FORMAT_LONG_24H);
6941
            }
6942
        }
6943
        if (empty($result)) {
6944
            $result = get_lang('NoTimeLimits');
6945
        }
6946
6947
        return $result;
6948
    }
6949
6950
    /**
6951
     * Returns a human readable string
6952
     * @params array $sessionInfo An array with all the session dates
6953
     * @return string
6954
     */
6955
    public static function parseSessionDates($sessionInfo, $showTime = false)
6956
    {
6957
        $displayDates = self::convertSessionDateToString(
6958
            $sessionInfo['display_start_date'],
6959
            $sessionInfo['display_end_date'],
6960
            $showTime,
6961
            true
6962
        );
6963
        $accessDates = self::convertSessionDateToString(
6964
            $sessionInfo['access_start_date'],
6965
            $sessionInfo['access_end_date'],
6966
            $showTime,
6967
            true
6968
        );
6969
6970
        $coachDates = self::convertSessionDateToString(
6971
            $sessionInfo['coach_access_start_date'],
6972
            $sessionInfo['coach_access_end_date'],
6973
            $showTime,
6974
            true
6975
        );
6976
6977
        $result = [
6978
            'access' => $accessDates,
6979
            'display' => $displayDates,
6980
            'coach' => $coachDates
6981
        ];
6982
6983
        return $result;
6984
    }
6985
6986
    /**
6987
     * @param FormValidator $form
6988
     * @param array $sessionInfo Optional
6989
     * @return array
6990
     */
6991
    public static function setForm(FormValidator $form, array $sessionInfo = [])
6992
    {
6993
        $sessionId = 0;
6994
        $coachInfo = [];
6995
6996
        if (!empty($sessionInfo)) {
6997
            $sessionId = intval($sessionInfo['id']);
6998
            $coachInfo = api_get_user_info($sessionInfo['id_coach']);
6999
        };
7000
7001
        $categoriesList = SessionManager::get_all_session_category();
7002
        $userInfo = api_get_user_info();
7003
7004
        $categoriesOptions = array(
7005
            '0' => get_lang('None')
7006
        );
7007
7008
        if ($categoriesList != false) {
7009
            foreach ($categoriesList as $categoryItem) {
7010
                $categoriesOptions[$categoryItem['id']] = $categoryItem['name'];
7011
            }
7012
        }
7013
7014
        // Database Table Definitions
7015
        $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
7016
7017
        $form->addElement('text', 'name', get_lang('SessionName'), array(
7018
            'maxlength' => 150,
7019
        ));
7020
        $form->addRule('name', get_lang('ThisFieldIsRequired'), 'required');
7021
        $form->addRule('name', get_lang('SessionNameAlreadyExists'), 'callback', 'check_session_name');
7022
7023
        if (!api_is_platform_admin() && api_is_teacher()) {
7024
            $form->addElement(
7025
                'select',
7026
                'coach_username',
7027
                get_lang('CoachName'),
7028
                [api_get_user_id() => $userInfo['complete_name']],
7029
                array(
7030
                    'id' => 'coach_username',
7031
                    'style' => 'width:370px;',
7032
                )
7033
            );
7034
        } else {
7035
            $sql = "SELECT COUNT(1) FROM $tbl_user WHERE status = 1";
7036
            $rs = Database::query($sql);
7037
            $countUsers = Database::result($rs, 0, 0);
7038
7039
            if (intval($countUsers) < 50) {
7040
                $orderClause = "ORDER BY ";
7041
                $orderClause .= api_sort_by_first_name() ? "firstname, lastname, username" : "lastname, firstname, username";
7042
7043
                $sql = "SELECT user_id, lastname, firstname, username
7044
                        FROM $tbl_user
7045
                        WHERE status = '1' ".
7046
                        $orderClause;
7047
7048
                if (api_is_multiple_url_enabled()) {
7049
                    $userRelAccessUrlTable = Database::get_main_table(
7050
                        TABLE_MAIN_ACCESS_URL_REL_USER
7051
                    );
7052
                    $accessUrlId = api_get_current_access_url_id();
7053
7054
                    if ($accessUrlId != -1) {
7055
                        $sql = "SELECT user.user_id, username, lastname, firstname
7056
                        FROM $tbl_user user
7057
                        INNER JOIN $userRelAccessUrlTable url_user
7058
                        ON (url_user.user_id = user.user_id)
7059
                        WHERE
7060
                            access_url_id = $accessUrlId AND
7061
                            status = 1 "
7062
                            .$orderClause;
7063
                    }
7064
                }
7065
7066
                $result = Database::query($sql);
7067
                $coachesList = Database::store_result($result);
7068
7069
                $coachesOptions = array();
7070 View Code Duplication
                foreach ($coachesList as $coachItem) {
7071
                    $coachesOptions[$coachItem['user_id']] =
7072
                        api_get_person_name($coachItem['firstname'], $coachItem['lastname']).' ('.$coachItem['username'].')';
7073
                }
7074
7075
                $form->addElement(
7076
                    'select',
7077
                    'coach_username',
7078
                    get_lang('CoachName'),
7079
                    $coachesOptions
7080
                );
7081
            } else {
7082
                $form->addElement(
7083
                    'select_ajax',
7084
                    'coach_username',
7085
                    get_lang('CoachName'),
7086
                    $coachInfo ? [$coachInfo['id'] => $coachInfo['complete_name_with_username']] : [],
7087
                    [
7088
                        'url' => api_get_path(WEB_AJAX_PATH) . 'session.ajax.php?a=search_general_coach',
7089
                        'width' => '100%',
7090
                    ]
7091
                );
7092
            }
7093
        }
7094
7095
        $form->addRule('coach_username', get_lang('ThisFieldIsRequired'), 'required');
7096
        $form->addHtml('<div id="ajax_list_coachs"></div>');
7097
7098
        $form->addButtonAdvancedSettings('advanced_params');
7099
        $form->addElement('html','<div id="advanced_params_options" style="display:none">');
7100
7101
        $form->addSelect(
7102
            'session_category',
7103
            get_lang('SessionCategory'),
7104
            $categoriesOptions,
7105
            array(
7106
                'id' => 'session_category',
7107
            )
7108
        );
7109
7110
        $form->addHtmlEditor(
7111
            'description',
7112
            get_lang('Description'),
7113
            false,
7114
            false,
7115
            array(
7116
                'ToolbarSet' => 'Minimal',
7117
            )
7118
        );
7119
7120
        $form->addElement('checkbox', 'show_description', null, get_lang('ShowDescription'));
7121
7122
        $visibilityGroup = array();
7123
        $visibilityGroup[] = $form->createElement('select', 'session_visibility', null, array(
7124
            SESSION_VISIBLE_READ_ONLY => get_lang('SessionReadOnly'),
7125
            SESSION_VISIBLE => get_lang('SessionAccessible'),
7126
            SESSION_INVISIBLE => api_ucfirst(get_lang('SessionNotAccessible')),
7127
        ));
7128
        $form->addGroup($visibilityGroup, 'visibility_group', get_lang('SessionVisibility'), null, false);
7129
7130
        $options = [
7131
            0 => get_lang('ByDuration'),
7132
            1 => get_lang('ByDates')
7133
        ];
7134
7135
        $form->addSelect('access', get_lang('Access'), $options, array(
7136
            'onchange' => 'accessSwitcher()',
7137
            'id' => 'access'
7138
        ));
7139
7140
        $form->addElement('html', '<div id="duration" style="display:none">');
7141
7142
        $form->addElement(
7143
            'number',
7144
            'duration',
7145
            array(
7146
                get_lang('SessionDurationTitle'),
7147
                get_lang('SessionDurationDescription'),
7148
            ),
7149
            array(
7150
                'maxlength' => 50,
7151
            )
7152
        );
7153
7154
        $form->addElement('html', '</div>');
7155
        $form->addElement('html', '<div id="date_fields" style="display:none">');
7156
7157
        // Dates
7158
        $form->addDateTimePicker(
7159
            'access_start_date',
7160
            array(get_lang('SessionStartDate'), get_lang('SessionStartDateComment')),
7161
            array('id' => 'access_start_date')
7162
        );
7163
7164
        $form->addDateTimePicker(
7165
            'access_end_date',
7166
            array(get_lang('SessionEndDate'), get_lang('SessionEndDateComment')),
7167
            array('id' => 'access_end_date')
7168
        );
7169
7170
        $form->addRule(
7171
            array('access_start_date', 'access_end_date'),
7172
            get_lang('StartDateMustBeBeforeTheEndDate'),
7173
            'compare_datetime_text',
7174
            '< allow_empty'
7175
        );
7176
7177
        $form->addDateTimePicker(
7178
            'display_start_date',
7179
            array(
7180
                get_lang('SessionDisplayStartDate'),
7181
                get_lang('SessionDisplayStartDateComment'),
7182
            ),
7183
            array('id' => 'display_start_date')
7184
        );
7185
        $form->addDateTimePicker(
7186
            'display_end_date',
7187
            array(
7188
                get_lang('SessionDisplayEndDate'),
7189
                get_lang('SessionDisplayEndDateComment'),
7190
            ),
7191
            array('id' => 'display_end_date')
7192
        );
7193
7194
        $form->addRule(
7195
            array('display_start_date', 'display_end_date'),
7196
            get_lang('StartDateMustBeBeforeTheEndDate'),
7197
            'compare_datetime_text',
7198
            '< allow_empty'
7199
        );
7200
7201
        $form->addDateTimePicker(
7202
            'coach_access_start_date',
7203
            array(
7204
                get_lang('SessionCoachStartDate'),
7205
                get_lang('SessionCoachStartDateComment'),
7206
            ),
7207
            array('id' => 'coach_access_start_date')
7208
        );
7209
7210
        $form->addDateTimePicker(
7211
            'coach_access_end_date',
7212
            array(
7213
                get_lang('SessionCoachEndDate'),
7214
                get_lang('SessionCoachEndDateComment'),
7215
            ),
7216
            array('id' => 'coach_access_end_date')
7217
        );
7218
7219
        $form->addRule(
7220
            array('coach_access_start_date', 'coach_access_end_date'),
7221
            get_lang('StartDateMustBeBeforeTheEndDate'),
7222
            'compare_datetime_text',
7223
            '< allow_empty'
7224
        );
7225
7226
        $form->addElement('html', '</div>');
7227
7228
        $form->addCheckBox(
7229
            'send_subscription_notification',
7230
            [
7231
                get_lang('SendSubscriptionNotification'),
7232
                get_lang('SendAnEmailWhenAUserBeingSubscribed')
7233
            ]
7234
        );
7235
7236
        // Extra fields
7237
        $extra_field = new ExtraFieldModel('session');
7238
        $extra = $extra_field->addElements($form, $sessionId);
7239
7240
        $form->addElement('html', '</div>');
7241
7242
        $js = $extra['jquery_ready_content'];
7243
7244
        return ['js' => $js];
7245
    }
7246
7247
    /**
7248
     * Gets the number of rows in the session table filtered through the given
7249
     * array of parameters
7250
     * @param array Array of options/filters/keys
7251
     * @return integer The number of rows, or false on wrong param
7252
     * @assert ('a') === false
7253
     */
7254
    static function get_count_admin_complete($options = array())
7255
    {
7256
        if (!is_array($options)) {
7257
            return false;
7258
        }
7259
        $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
7260
        $tbl_session_category = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
7261
        $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
7262
        $sessionCourseUserTable = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
7263
        $courseTable = Database::get_main_table(TABLE_MAIN_COURSE);
7264
7265
        $where = 'WHERE 1 = 1 ';
7266
        $user_id = api_get_user_id();
7267
7268
        if (api_is_session_admin() &&
7269
            api_get_setting('allow_session_admins_to_see_all_sessions') == 'false'
7270
        ) {
7271
            $where.=" WHERE s.session_admin_id = $user_id ";
7272
        }
7273
7274 View Code Duplication
        if (!empty($options['where'])) {
7275
            $options['where'] = str_replace('course_title', 'c.title', $options['where']);
7276
            $options['where'] = str_replace("( session_active = '0' )", '1=1',  $options['where']);
7277
7278
            $options['where'] = str_replace(
7279
                array("AND session_active = '1'  )", " AND (  session_active = '1'  )"),
7280
                array(') GROUP BY s.name HAVING session_active = 1 ', " GROUP BY s.name HAVING session_active = 1 " )
7281
                , $options['where']
7282
            );
7283
7284
            $options['where'] = str_replace(
7285
                array("AND session_active = '0'  )", " AND (  session_active = '0'  )"),
7286
                array(') GROUP BY s.name HAVING session_active = 0 ', " GROUP BY s.name HAVING session_active = '0' "),
7287
                $options['where']
7288
            );
7289
7290
            if (!empty($options['extra'])) {
7291
                $options['where'] = str_replace(' 1 = 1  AND', '', $options['where']);
7292
                $options['where'] = str_replace('AND', 'OR', $options['where']);
7293
7294
                foreach ($options['extra'] as $extra) {
7295
                    $options['where'] = str_replace($extra['field'], 'fv.field_id = '.$extra['id'].' AND fvo.option_value', $options['where']);
7296
                }
7297
            }
7298
            $where .= ' AND '.$options['where'];
7299
        }
7300
7301
        $today = api_get_utc_datetime();
7302
        $query_rows = "SELECT count(*) as total_rows, c.title as course_title, s.name,
7303
                        IF (
7304
                            (s.access_start_date <= '$today' AND '$today' < s.access_end_date) OR
7305
                            (s.access_start_date = '0000-00-00 00:00:00' AND s.access_end_date = '0000-00-00 00:00:00' ) OR
7306
                            (s.access_start_date IS NULL AND s.access_end_date IS NULL) OR
7307
                            (s.access_start_date <= '$today' AND ('0000-00-00 00:00:00' = s.access_end_date OR s.access_end_date IS NULL )) OR
7308
                            ('$today' < s.access_end_date AND ('0000-00-00 00:00:00' = s.access_start_date OR s.access_start_date IS NULL) )
7309
                        , 1, 0) as session_active
7310
                       FROM $tbl_session s
7311
                       LEFT JOIN  $tbl_session_category sc
7312
                       ON s.session_category_id = sc.id
7313
                       INNER JOIN $tbl_user u
7314
                       ON s.id_coach = u.user_id
7315
                       INNER JOIN $sessionCourseUserTable scu
7316
                       ON s.id = scu.session_id
7317
                       INNER JOIN $courseTable c
7318
                       ON c.id = scu.c_id
7319
                       $where ";
7320
7321 View Code Duplication
        if (api_is_multiple_url_enabled()) {
7322
            $table_access_url_rel_session= Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
7323
            $access_url_id = api_get_current_access_url_id();
7324
            if ($access_url_id != -1) {
7325
                $where.= " AND ar.access_url_id = $access_url_id ";
7326
7327
                $query_rows = "SELECT count(*) as total_rows
7328
                               FROM $tbl_session s
7329
                               LEFT JOIN  $tbl_session_category sc
7330
                               ON s.session_category_id = sc.id
7331
                               INNER JOIN $tbl_user u
7332
                               ON s.id_coach = u.user_id
7333
                               INNER JOIN $table_access_url_rel_session ar
7334
                               ON ar.session_id = s.id $where ";
7335
            }
7336
        }
7337
7338
        $result = Database::query($query_rows);
7339
        $num = 0;
7340
        if (Database::num_rows($result)) {
7341
            $rows = Database::fetch_array($result);
7342
            $num = $rows['total_rows'];
7343
        }
7344
7345
        return $num;
7346
    }
7347
7348
    /**
7349
     * @param string $list_type
7350
     * @return array
7351
     */
7352
    public static function getGridColumns($list_type = 'simple')
7353
    {
7354
        // Column config
7355
        $operators = array('cn', 'nc');
7356
        $date_operators = array('gt', 'ge', 'lt', 'le');
7357
7358
        switch ($list_type) {
7359
            case 'simple':
7360
                $columns = array(
7361
                    get_lang('Name'),
7362
                    get_lang('Category'),
7363
                    get_lang('SessionDisplayStartDate'),
7364
                    get_lang('SessionDisplayEndDate'),
7365
                    //get_lang('Coach'),
7366
                    //get_lang('Status'),
7367
                    //get_lang('CourseTitle'),
7368
                    get_lang('Visibility'),
7369
                );
7370
                $column_model = array (
7371
                    array('name'=>'name', 'index'=>'s.name', 'width'=>'160',  'align'=>'left', 'search' => 'true', 'searchoptions' => array('sopt' => $operators)),
7372
                    array('name'=>'category_name', 'index'=>'category_name', 'width'=>'40',  'align'=>'left', 'search' => 'true', 'searchoptions' => array('sopt' => $operators)),
7373
                    array('name'=>'display_start_date', 'index'=>'display_start_date', 'width'=>'50',   'align'=>'left', 'search' => 'true', 'searchoptions' => array('dataInit' => 'date_pick_today', 'sopt' => $date_operators)),
7374
                    array('name'=>'display_end_date', 'index'=>'display_end_date', 'width'=>'50',   'align'=>'left', 'search' => 'true', 'searchoptions' => array('dataInit' => 'date_pick_one_month', 'sopt' => $date_operators)),
7375
                    array('name'=>'visibility', 'index'=>'visibility',      'width'=>'40',   'align'=>'left', 'search' => 'false'),
7376
                );
7377
                break;
7378
            case 'complete':
7379
                $columns = array(
7380
                    get_lang('Name'),
7381
                    get_lang('SessionDisplayStartDate'),
7382
                    get_lang('SessionDisplayEndDate'),
7383
                    get_lang('Coach'),
7384
                    get_lang('Status'),
7385
                    get_lang('Visibility'),
7386
                    get_lang('CourseTitle'),
7387
                );
7388
                $column_model = array (
7389
                    array('name'=>'name', 'index'=>'s.name', 'width'=>'200',  'align'=>'left', 'search' => 'true', 'searchoptions' => array('sopt' => $operators)),
7390
                    array('name'=>'display_start_date', 'index'=>'display_start_date', 'width'=>'70',   'align'=>'left', 'search' => 'true', 'searchoptions' => array('dataInit' => 'date_pick_today', 'sopt' => $date_operators)),
7391
                    array('name'=>'display_end_date', 'index'=>'display_end_date', 'width'=>'70',   'align'=>'left', 'search' => 'true', 'searchoptions' => array('dataInit' => 'date_pick_one_month', 'sopt' => $date_operators)),
7392
                    array('name'=>'coach_name', 'index'=>'coach_name',     'width'=>'70',   'align'=>'left', 'search' => 'false', 'searchoptions' => array('sopt' => $operators)),
7393
                    array('name'=>'session_active', 'index'=>'session_active', 'width'=>'25',   'align'=>'left', 'search' => 'true', 'stype'=>'select',
7394
                        // for the bottom bar
7395
                        'searchoptions' => array(
7396
                            'defaultValue'  => '1',
7397
                            'value'         => '1:'.get_lang('Active').';0:'.get_lang('Inactive')),
7398
                        // for the top bar
7399
                        'editoptions' => array('value' => '" ":'.get_lang('All').';1:'.get_lang('Active').';0:'.get_lang('Inactive')),
7400
                    ),
7401
                    array('name'=>'visibility',     'index'=>'visibility',      'width'=>'40',   'align'=>'left', 'search' => 'false'),
7402
                    array('name'=>'course_title',    'index'=>'course_title',   'width'=>'50',   'hidden' => 'true', 'search' => 'true', 'searchoptions' => array('searchhidden' =>'true','sopt' => $operators)),
7403
                );
7404
                break;
7405
        }
7406
7407
        // Inject extra session fields
7408
        $session_field = new ExtraFieldModel('session');
7409
        $rules = $session_field->getRules($columns, $column_model);
7410
7411
        $column_model[] = array('name'=>'actions', 'index'=>'actions', 'width'=>'80',  'align'=>'left','formatter'=>'action_formatter','sortable'=>'false', 'search' => 'false');
7412
        $columns[] = get_lang('Actions');
7413
7414
        foreach ($column_model as $col_model) {
7415
            $simple_column_name[] = $col_model['name'];
7416
        }
7417
7418
        $return_array =  array(
7419
            'columns' => $columns,
7420
            'column_model' => $column_model,
7421
            'rules' => $rules,
7422
            'simple_column_name' => $simple_column_name,
7423
        );
7424
7425
        return $return_array;
7426
    }
7427
7428
    /**
7429
     * Converts all dates sent through the param array (given form) to correct dates with timezones
7430
     * @param array The dates The same array, with times converted
7431
     * @param boolean $applyFormat Whether apply the DATE_TIME_FORMAT_SHORT format for sessions
7432
     * @return array The same array, with times converted
7433
     */
7434
    static function convert_dates_to_local($params, $applyFormat = false)
7435
    {
7436
        if (!is_array($params)) {
7437
            return false;
7438
        }
7439
        $params['display_start_date'] = api_get_local_time($params['display_start_date'], null, null, true);
7440
        $params['display_end_date'] = api_get_local_time($params['display_end_date'], null, null, true);
7441
7442
        $params['access_start_date'] = api_get_local_time($params['access_start_date'], null, null, true);
7443
        $params['access_end_date'] = api_get_local_time($params['access_end_date'], null, null, true);
7444
7445
        $params['coach_access_start_date'] = isset($params['coach_access_start_date']) ? api_get_local_time($params['coach_access_start_date'], null, null, true) : null;
7446
        $params['coach_access_end_date'] = isset($params['coach_access_end_date']) ? api_get_local_time($params['coach_access_end_date'], null, null, true) : null;
7447
7448
        if ($applyFormat) {
7449 View Code Duplication
            if (isset($params['display_start_date'])) {
7450
                $params['display_start_date'] = api_format_date($params['display_start_date'], DATE_TIME_FORMAT_SHORT);
7451
            }
7452
7453 View Code Duplication
            if (isset($params['display_end_date'])) {
7454
                $params['display_end_date'] = api_format_date($params['display_end_date'], DATE_TIME_FORMAT_SHORT);
7455
            }
7456
7457 View Code Duplication
            if (isset($params['access_start_date'])) {
7458
                $params[''] = api_format_date($params['access_start_date'], DATE_TIME_FORMAT_SHORT);
7459
            }
7460
7461 View Code Duplication
            if (isset($params['access_end_date'])) {
7462
                $params['access_end_date'] = api_format_date($params['access_end_date'], DATE_TIME_FORMAT_SHORT);
7463
            }
7464
7465 View Code Duplication
            if (isset($params['coach_access_start_date'])) {
7466
                $params['coach_access_start_date'] = api_format_date($params['coach_access_start_date'], DATE_TIME_FORMAT_SHORT);
7467
            }
7468
7469 View Code Duplication
            if (isset($params['coach_access_end_date'])) {
7470
                $params['coach_access_end_date'] = api_format_date($params['coach_access_end_date'], DATE_TIME_FORMAT_SHORT);
7471
            }
7472
        }
7473
7474
        return $params;
7475
    }
7476
7477
    /**
7478
     * Gets the admin session list callback of the session/session_list.php
7479
     * page with all user/details in the right fomat
7480
     * @param array
7481
     * @result array Array of rows results
7482
     * @asset ('a') === false
7483
     */
7484
    public static function get_sessions_admin_complete($options = array())
7485
    {
7486
        if (!is_array($options)) {
7487
            return false;
7488
        }
7489
7490
        $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
7491
        $tbl_session_category = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
7492
        $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
7493
        $tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
7494
        $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
7495
7496
        $extraFieldTable = Database::get_main_table(TABLE_EXTRA_FIELD);
7497
        $tbl_session_field_values = Database::get_main_table(TABLE_EXTRA_FIELD_VALUES);
7498
        $tbl_session_field_options = Database::get_main_table(TABLE_EXTRA_FIELD_OPTIONS);
7499
7500
        $where = 'WHERE 1 = 1 ';
7501
        $user_id = api_get_user_id();
7502
7503 View Code Duplication
        if (!api_is_platform_admin()) {
7504
            if (api_is_session_admin() &&
7505
                api_get_setting('allow_session_admins_to_manage_all_sessions') == 'false'
7506
            ) {
7507
                $where.=" AND s.session_admin_id = $user_id ";
7508
            }
7509
        }
7510
7511
        $coach_name = " CONCAT(u.lastname , ' ', u.firstname) as coach_name ";
7512
        if (api_is_western_name_order()) {
7513
            $coach_name = " CONCAT(u.firstname, ' ', u.lastname) as coach_name ";
7514
        }
7515
7516
        $today = api_get_utc_datetime();
7517
        $inject_extra_fields = null;
7518
        $extra_fields = array();
7519
        $extra_fields_info = array();
7520
7521
        //for now only sessions
7522
        $extra_field = new ExtraFieldModel('session');
7523
        $double_fields = array();
7524
        $extra_field_option = new ExtraFieldOption('session');
7525
7526
        if (isset($options['extra'])) {
7527
            $extra_fields = $options['extra'];
7528
            if (!empty($extra_fields)) {
7529
                foreach ($extra_fields as $extra) {
7530
                    $inject_extra_fields .= " IF (fv.field_id = {$extra['id']}, fvo.option_display_text, NULL ) as {$extra['field']} , ";
7531 View Code Duplication
                    if (isset($extra_fields_info[$extra['id']])) {
7532
                        $info = $extra_fields_info[$extra['id']];
7533
                    } else {
7534
                        $info = $extra_field->get($extra['id']);
7535
                        $extra_fields_info[$extra['id']] = $info;
7536
                    }
7537
7538
                    if ($info['field_type'] == ExtraField::FIELD_TYPE_DOUBLE_SELECT) {
7539
                        $double_fields[$info['id']] = $info;
7540
                    }
7541
                }
7542
            }
7543
        }
7544
7545
        $options_by_double = array();
7546 View Code Duplication
        foreach ($double_fields as $double) {
7547
            $my_options = $extra_field_option->get_field_options_by_field(
7548
                $double['id'],
7549
                true
7550
            );
7551
            $options_by_double['extra_'.$double['field_variable']] = $my_options;
7552
        }
7553
7554
        //sc.name as category_name,
7555
        $select = "
7556
                SELECT * FROM (
7557
                    SELECT DISTINCT
7558
                         IF (
7559
                            (s.access_start_date <= '$today' AND '$today' < s.access_end_date) OR
7560
                            (s.access_start_date = '0000-00-00 00:00:00' AND s.access_end_date = '0000-00-00 00:00:00' ) OR
7561
                            (s.access_start_date IS NULL AND s.access_end_date IS NULL) OR
7562
                            (s.access_start_date <= '$today' AND ('0000-00-00 00:00:00' = s.access_end_date OR s.access_end_date IS NULL )) OR
7563
                            ('$today' < s.access_end_date AND ('0000-00-00 00:00:00' = s.access_start_date OR s.access_start_date IS NULL) )
7564
                        , 1, 0) as session_active,
7565
                s.name,
7566
                s.nbr_courses,
7567
                s.nbr_users,
7568
                s.display_start_date,
7569
                s.display_end_date,
7570
                $coach_name,
7571
                access_start_date,
7572
                access_end_date,
7573
                s.visibility,
7574
                u.user_id,
7575
                $inject_extra_fields
7576
                c.title as course_title,
7577
                s.id ";
7578
7579 View Code Duplication
        if (!empty($options['where'])) {
7580
            if (!empty($options['extra'])) {
7581
                $options['where'] = str_replace(' 1 = 1  AND', '', $options['where']);
7582
                $options['where'] = str_replace('AND', 'OR', $options['where']);
7583
                foreach ($options['extra'] as $extra) {
7584
                    $options['where'] = str_replace($extra['field'], 'fv.field_id = '.$extra['id'].' AND fvo.option_value', $options['where']);
7585
                }
7586
            }
7587
            $options['where'] = str_replace('course_title', 'c.title', $options['where']);
7588
7589
            $options['where'] = str_replace("( session_active = '0' )", '1=1',  $options['where']);
7590
7591
            $options['where'] = str_replace(
7592
                array("AND session_active = '1'  )", " AND (  session_active = '1'  )"),
7593
                array(') GROUP BY s.name HAVING session_active = 1 ', " GROUP BY s.name HAVING session_active = 1 " )
7594
                , $options['where']
7595
            );
7596
7597
            $options['where'] = str_replace(
7598
                array("AND session_active = '0'  )", " AND (  session_active = '0'  )"),
7599
                array(') GROUP BY s.name HAVING session_active = 0 ', " GROUP BY s.name HAVING session_active = '0' "),
7600
                $options['where']
7601
            );
7602
7603
7604
            $where .= ' AND '.$options['where'];
7605
        }
7606
7607
        if (!empty($options['limit'])) {
7608
            $where .= " LIMIT ".$options['limit'];
7609
        }
7610
        $query = "$select FROM $tbl_session s
7611
                    LEFT JOIN $tbl_session_field_values fv
7612
                    ON (fv.item_id = s.id)
7613
                    LEFT JOIN $extraFieldTable f
7614
                    ON f.id = fv.field_id
7615
                    LEFT JOIN $tbl_session_field_options fvo
7616
                    ON (fv.field_id = fvo.field_id)
7617
                    LEFT JOIN $tbl_session_rel_course src
7618
                    ON (src.session_id = s.id)
7619
                    LEFT JOIN $tbl_course c
7620
                    ON (src.c_id = c.id)
7621
                    LEFT JOIN $tbl_session_category sc
7622
                    ON (s.session_category_id = sc.id)
7623
                    INNER JOIN $tbl_user u
7624
                    ON (s.id_coach = u.user_id) ".
7625
            $where;
7626
7627 View Code Duplication
        if (api_is_multiple_url_enabled()) {
7628
            $table_access_url_rel_session= Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
7629
            $access_url_id = api_get_current_access_url_id();
7630
            if ($access_url_id != -1) {
7631
                $where.= " AND ar.access_url_id = $access_url_id ";
7632
                $query = "$select
7633
                    FROM $tbl_session s
7634
                    LEFT JOIN $tbl_session_field_values fv ON (fv.session_id = s.id)
7635
                    LEFT JOIN $tbl_session_field_options fvo ON (fv.field_id = fvo.field_id)
7636
                    LEFT JOIN $tbl_session_rel_course src ON (src.id_session = s.id)
7637
                    LEFT JOIN $tbl_course c ON (src.c_id = c.id)
7638
                    LEFT JOIN $tbl_session_category sc ON (s.session_category_id = sc.id)
7639
                    INNER JOIN $tbl_user u ON (s.id_coach = u.user_id)
7640
                    INNER JOIN $table_access_url_rel_session ar ON (ar.session_id = s.id)
7641
                    $where";
7642
            }
7643
        }
7644
7645
        $query .= ") AS session_table";
7646
7647
        if (!empty($options['order'])) {
7648
            $query .= " ORDER BY ".$options['order'];
7649
        }
7650
7651
        $result = Database::query($query);
7652
        $formatted_sessions = array();
7653
7654
        if (Database::num_rows($result)) {
7655
            $sessions   = Database::store_result($result, 'ASSOC');
7656
            foreach ($sessions as $session) {
7657
                $session_id = $session['id'];
7658
                $session['name'] = Display::url($session['name'], "resume_session.php?id_session=".$session['id']);
7659
                $session['coach_name'] = Display::url($session['coach_name'], "user_information.php?user_id=".$session['user_id']);
7660 View Code Duplication
                if ($session['session_active'] == 1) {
7661
                    $session['session_active'] = Display::return_icon('accept.png', get_lang('Active'), array(), ICON_SIZE_SMALL);
7662
                } else {
7663
                    $session['session_active'] = Display::return_icon('error.png', get_lang('Inactive'), array(), ICON_SIZE_SMALL);
7664
                }
7665
7666
                $session = self::convert_dates_to_local($session);
7667
7668 View Code Duplication
                switch ($session['visibility']) {
7669
                    case SESSION_VISIBLE_READ_ONLY: //1
7670
                        $session['visibility'] =  get_lang('ReadOnly');
7671
                        break;
7672
                    case SESSION_VISIBLE:           //2
7673
                    case SESSION_AVAILABLE:         //4
7674
                        $session['visibility'] =  get_lang('Visible');
7675
                        break;
7676
                    case SESSION_INVISIBLE:         //3
7677
                        $session['visibility'] =  api_ucfirst(get_lang('Invisible'));
7678
                        break;
7679
                }
7680
7681
                // Cleaning double selects
7682 View Code Duplication
                foreach ($session as $key => &$value) {
0 ignored issues
show
Bug introduced by
The expression $session of type false|array<string,strin...d_date":"string|null"}> is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
7683
                    if (isset($options_by_double[$key]) || isset($options_by_double[$key.'_second'])) {
7684
                        $options = explode('::', $value);
7685
                    }
7686
                    $original_key = $key;
7687
7688
                    if (strpos($key, '_second') === false) {
0 ignored issues
show
Unused Code introduced by
This if statement is empty and can be removed.

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

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

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

could be turned into

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

This is much more concise to read.

Loading history...
7689
                    } else {
7690
                        $key = str_replace('_second', '', $key);
7691
                    }
7692
7693
                    if (isset($options_by_double[$key])) {
7694
                        if (isset($options[0])) {
7695
                            if (isset($options_by_double[$key][$options[0]])) {
7696
                                if (strpos($original_key, '_second') === false) {
7697
                                    $value = $options_by_double[$key][$options[0]]['option_display_text'];
7698
                                } else {
7699
                                    $value = $options_by_double[$key][$options[1]]['option_display_text'];
7700
                                }
7701
                            }
7702
                        }
7703
                    }
7704
                }
7705
7706
                // Magic filter
7707
                if (isset($formatted_sessions[$session_id])) {
7708
                    $formatted_sessions[$session_id] = self::compareArraysToMerge($formatted_sessions[$session_id], $session);
0 ignored issues
show
Security Bug introduced by
It seems like $session defined by self::convert_dates_to_local($session) on line 7666 can also be of type false; however, SessionManager::compareArraysToMerge() does only seem to accept array, did you maybe forget to handle an error condition?

This check looks for type mismatches where the missing type is false. This is usually indicative of an error condtion.

Consider the follow example

<?php

function getDate($date)
{
    if ($date !== null) {
        return new DateTime($date);
    }

    return false;
}

This function either returns a new DateTime object or false, if there was an error. This is a typical pattern in PHP programming to show that an error has occurred without raising an exception. The calling code should check for this returned false before passing on the value to another function or method that may not be able to handle a false.

Loading history...
7709
                } else {
7710
                    $formatted_sessions[$session_id] = $session;
7711
                }
7712
            }
7713
        }
7714
7715
        return $formatted_sessions;
7716
    }
7717
7718
    /**
7719
     * Compare two arrays
7720
     * @param array $array1
7721
     * @param array $array2
7722
     *
7723
     * @return array
7724
     */
7725
    static function compareArraysToMerge($array1, $array2)
7726
    {
7727
        if (empty($array2)) {
7728
            return $array1;
7729
        }
7730
        foreach ($array1 as $key => $item) {
7731
            if (!isset($array1[$key])) {
7732
                //My string is empty try the other one
7733
                if (isset($array2[$key]) && !empty($array2[$key])) {
7734
                    $array1[$key] = $array2[$key];
7735
                }
7736
            }
7737
        }
7738
        return $array1;
7739
    }
7740
7741
    /**
7742
     * Get link to the admin page for this session
7743
     * @param   int $id Session ID
7744
     * @return mixed    URL to the admin page to manage the session, or false on error
7745
     */
7746
    public static function getAdminPath($id)
7747
    {
7748
        $id = intval($id);
7749
        $session = self::fetch($id);
7750
        if (empty($session)) {
7751
            return false;
7752
        }
7753
        return api_get_path(WEB_CODE_PATH) . 'session/resume_session.php?id_session=' . $id;
7754
    }
7755
7756
    /**
7757
     * Get link to the user page for this session.
7758
     * If a course is provided, build the link to the course
7759
     * @param   int $id Session ID
7760
     * @param   int $courseId Course ID (optional) in case the link has to send straight to the course
7761
     * @return mixed    URL to the page to use the session, or false on error
7762
     */
7763
    public static function getPath($id, $courseId = 0)
7764
    {
7765
        $id = intval($id);
7766
        $session = self::fetch($id);
7767
        if (empty($session)) {
7768
            return false;
7769
        }
7770
        if (empty($courseId)) {
7771
            return api_get_path(WEB_CODE_PATH) . 'session/index.php?session_id=' . $id;
7772
        } else {
7773
            $courseInfo = api_get_course_info_by_id($courseId);
7774
            if ($courseInfo) {
7775
                return $courseInfo['course_public_url'].'?id_session='.$id;
7776
            }
7777
        }
7778
7779
        return false;
7780
    }
7781
7782
    /**
7783
     * Return an associative array 'id_course' => [id_session1, id_session2...]
7784
     * where course id_course is in sessions id_session1, id_session2
7785
     * for course where user is coach
7786
     * i.e. coach for the course or
7787
     * main coach for a session the course is in
7788
     * for a session category (or woth no session category if empty)
7789
     *
7790
     * @param $userId
7791
     *
7792
     * @return array
7793
     */
7794
    public static function getSessionCourseForUser($userId)
7795
    {
7796
        // list of COURSES where user is COURSE session coach
7797
        $listCourseCourseCoachSession = self::getCoursesForCourseSessionCoach($userId);
7798
7799
        // list of courses where user is MAIN session coach
7800
        $listCourseMainCoachSession = self::getCoursesForMainSessionCoach($userId);
7801
7802
        // merge these 2 array
7803
        $listResCourseSession = $listCourseCourseCoachSession;
7804
        foreach ($listCourseMainCoachSession as $courseId2 => $listSessionId2) {
7805
            if (isset($listResCourseSession[$courseId2])) {
7806
                // if sessionId array exists for this course
7807
                // same courseId, merge the list of session
7808
                foreach ($listCourseMainCoachSession[$courseId2] as $i => $sessionId2) {
7809
                    if (!in_array($sessionId2, $listResCourseSession[$courseId2])) {
7810
                        $listResCourseSession[$courseId2][] = $sessionId2;
7811
                    }
7812
                }
7813
            } else {
7814
                $listResCourseSession[$courseId2] = $listSessionId2;
7815
            }
7816
        }
7817
7818
        return $listResCourseSession;
7819
    }
7820
7821
    /**
7822
     * Return an associative array 'id_course' => [id_session1, id_session2...]
7823
     * where course id_course is in sessions id_session1, id_session2
7824
     * @param $userId
7825
     *
7826
     * @return array
7827
     */
7828
    public static function getCoursesForCourseSessionCoach($userId)
7829
    {
7830
        $listResCourseSession = array();
7831
        $tblCourse = Database::get_main_table(TABLE_MAIN_COURSE);
7832
        $tblSessionRelCourseRelUser = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
7833
7834
        $sql = "SELECT session_id, c_id, c.id
7835
                FROM $tblSessionRelCourseRelUser srcru
7836
                LEFT JOIN $tblCourse c
7837
                ON c.id = srcru.c_id
7838
                WHERE
7839
                    srcru.user_id =".intval($userId)." AND
7840
                    srcru.status = 2";
7841
7842
        $res = Database::query($sql);
7843
7844
        while ($data = Database::fetch_assoc($res)) {
7845
            if (api_get_session_visibility($data['session_id'])) {
7846
                if (!isset($listResCourseSession[$data['id']])) {
7847
                    $listResCourseSession[$data['id']] = array();
7848
                }
7849
                $listResCourseSession[$data['id']][] = $data['session_id'];
7850
            }
7851
        }
7852
7853
        return $listResCourseSession;
7854
    }
7855
7856
    /**
7857
     * Return an associative array 'id_course' => [id_session1, id_session2...]
7858
     * where course id_course is in sessions id_session1, id_session2
7859
     * @param $userId
7860
     *
7861
     * @return array
7862
     */
7863
    public static function getCoursesForMainSessionCoach($userId)
7864
    {
7865
        $listResCourseSession = array();
7866
        $tblSession = Database::get_main_table(TABLE_MAIN_SESSION);
7867
7868
        // list of SESSION where user is session coach
7869
        $sql = "SELECT id FROM $tblSession
7870
                WHERE id_coach = ".intval($userId);
7871
        $res = Database::query($sql);
7872
7873
        while ($data = Database::fetch_assoc($res)) {
7874
            $sessionId = $data['id'];
7875
            $listCoursesInSession = self::getCoursesInSession($sessionId);
7876
            foreach ($listCoursesInSession as $i => $courseId) {
7877
                if (api_get_session_visibility($sessionId)) {
7878
                    if (!isset($listResCourseSession[$courseId])) {
7879
                        $listResCourseSession[$courseId] = array();
7880
                    }
7881
                    $listResCourseSession[$courseId][] = $sessionId;
7882
                }
7883
            }
7884
        }
7885
7886
        return $listResCourseSession;
7887
    }
7888
7889
    /**
7890
     * Return an array of course_id used in session $sessionId
7891
     * @param $sessionId
7892
     *
7893
     * @return array
7894
     */
7895 View Code Duplication
    public static function getCoursesInSession($sessionId)
7896
    {
7897
        if (empty($sessionId)) {
7898
            return [];
7899
        }
7900
7901
        $tblSessionRelCourse = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
7902
        $tblCourse = Database::get_main_table(TABLE_MAIN_COURSE);
7903
7904
        // list of course in this session
7905
        $sql = "SELECT session_id, c.id
7906
                FROM $tblSessionRelCourse src
7907
                LEFT JOIN $tblCourse c
7908
                ON c.id = src.c_id
7909
                WHERE session_id = ".intval($sessionId);
7910
        $res = Database::query($sql);
7911
7912
        $listResultsCourseId = array();
7913
        while ($data = Database::fetch_assoc($res)) {
7914
            $listResultsCourseId[] = $data['id'];
7915
        }
7916
7917
        return $listResultsCourseId;
7918
    }
7919
7920
    /**
7921
     * Return an array of courses in session for user
7922
     * and for each courses the list of session that use this course for user
7923
     *
7924
     * [0] => array
7925
     *      userCatId
7926
     *      userCatTitle
7927
     *      courseInUserCatList
7928
     *          [0] => array
7929
     *              courseId
7930
     *              title
7931
     *              courseCode
7932
     *              sessionCatList
7933
     *                  [0] => array
7934
     *                      catSessionId
7935
     *                      catSessionName
7936
     *                      sessionList
7937
     *                          [0] => array
7938
     *                              sessionId
7939
     *                              sessionName
7940
     *
7941
     * @param $userId
7942
     *
7943
     * @return array
7944
     *
7945
     */
7946
    public static function getNamedSessionCourseForCoach($userId)
7947
    {
7948
        $listResults = array();
7949
        $listCourseSession = self::getSessionCourseForUser($userId);
7950
        foreach ($listCourseSession as $courseId => $listSessionId) {
7951
            // Course info
7952
            $courseInfo = api_get_course_info_by_id($courseId);
7953
            $listOneCourse = array();
7954
            $listOneCourse['courseId'] = $courseId;
7955
            $listOneCourse['title'] = $courseInfo['title'];
7956
            //$listOneCourse['courseCode'] = $courseInfo['code'];
7957
            $listOneCourse['course'] = $courseInfo;
7958
            $listOneCourse['sessionCatList'] = array();
7959
            $listCat = array();
7960
            foreach ($listSessionId as $i => $sessionId) {
7961
                // here we got all session for this course
7962
                // lets check there session categories
7963
                $sessionInfo = SessionManager::fetch($sessionId);
7964
                $catId = $sessionInfo['session_category_id'];
7965
                if (!isset($listCat[$catId])) {
7966
                    $listCatInfo = self::get_session_category($catId);
7967
                    $listCat[$catId] = array();
7968
                    $listCat[$catId]['catSessionId'] = $catId;
7969
                    $listCat[$catId]['catSessionName'] = $listCatInfo['name'];
7970
                    $listCat[$catId]['sessionList'] = array();
7971
                }
7972
                $listSessionInfo = SessionManager::fetch($sessionId);
7973
                $listSessionIdName = array(
7974
                    "sessionId" => $sessionId,
7975
                    "sessionName" => $listSessionInfo['name'],
7976
                );
7977
                $listCat[$catId]['sessionList'][] = $listSessionIdName;
7978
            }
7979
            // sort $listCat by catSessionName
7980
            usort($listCat, 'self::compareBySessionName');
7981
            // in each catSession sort sessionList by sessionName
7982
            foreach($listCat as $i => $listCatSessionInfo) {
7983
                $listSessionList = $listCatSessionInfo['sessionList'];
7984
                usort($listSessionList, 'self::compareCatSessionInfo');
7985
                $listCat[$i]['sessionList'] = $listSessionList;
7986
            }
7987
7988
            $listOneCourse['sessionCatList'] = $listCat;
7989
7990
            // user course category
7991
            list($userCatId, $userCatTitle) = CourseManager::getUserCourseCategoryForCourse(
7992
                $userId,
7993
                $courseId
7994
            );
7995
7996
            $userCatId = intval($userCatId);
7997
            $listResults[$userCatId]['courseInUserCategoryId'] =  $userCatId;
7998
            $listResults[$userCatId]['courseInUserCategoryTitle'] =  $userCatTitle;
7999
            $listResults[$userCatId]['courseInUserCatList'][] = $listOneCourse;
8000
        }
8001
8002
        // sort by user course cat
8003
        uasort($listResults, 'self::compareByUserCourseCat');
8004
8005
        // sort by course title
8006
        foreach ($listResults as $userCourseCatId => $tabCoursesInCat) {
8007
            $courseInUserCatList = $tabCoursesInCat['courseInUserCatList'];
8008
            uasort($courseInUserCatList, 'self::compareByCourse');
8009
            $listResults[$userCourseCatId]['courseInUserCatList'] = $courseInUserCatList;
8010
        }
8011
8012
        return $listResults;
8013
    }
8014
8015
    /**
8016
     * @param array $listA
8017
     * @param array $listB
8018
     * @return int
8019
     */
8020 View Code Duplication
    private static function compareCatSessionInfo($listA, $listB)
8021
    {
8022
        if ($listA['sessionName'] == $listB['sessionName']) {
8023
            return 0;
8024
        } else if($listA['sessionName'] > $listB['sessionName']) {
8025
            return 1;
8026
        } else {
8027
            return -1;
8028
        }
8029
    }
8030
8031
    /**
8032
     * @param array $listA
8033
     * @param array $listB
8034
     * @return int
8035
     */
8036
    private static function compareBySessionName($listA, $listB)
8037
    {
8038
        if ($listB['catSessionName'] == '') {
8039
            return -1;
8040
        } else if ($listA['catSessionName'] == '') {
8041
            return 1;
8042
        } else if ($listA['catSessionName'] == $listB['catSessionName']) {
8043
            return 0;
8044
        } else if($listA['catSessionName'] > $listB['catSessionName']) {
8045
            return 1;
8046
        } else {
8047
            return -1;
8048
        }
8049
    }
8050
8051
    /**
8052
     * @param array $listA
8053
     * @param array $listB
8054
     * @return int
8055
     */
8056 View Code Duplication
    private static function compareByUserCourseCat($listA, $listB)
8057
    {
8058
        if ($listA['courseInUserCategoryTitle'] == $listB['courseInUserCategoryTitle']) {
8059
            return 0;
8060
        } else if($listA['courseInUserCategoryTitle'] > $listB['courseInUserCategoryTitle']) {
8061
            return 1;
8062
        } else {
8063
            return -1;
8064
        }
8065
    }
8066
8067
    /**
8068
     * @param array $listA
8069
     * @param array $listB
8070
     * @return int
8071
     */
8072 View Code Duplication
    private static function compareByCourse($listA, $listB)
8073
    {
8074
        if ($listA['title'] == $listB['title']) {
8075
            return 0;
8076
        } else if($listA['title'] > $listB['title']) {
8077
            return 1;
8078
        } else {
8079
            return -1;
8080
        }
8081
    }
8082
8083
    /**
8084
     * Return HTML code for displaying session_course_for_coach
8085
     * @param $userId
8086
     * @return string
8087
     */
8088
    public static function getHtmlNamedSessionCourseForCoach($userId)
8089
    {
8090
        $htmlRes = '';
8091
8092
        $listInfo = self::getNamedSessionCourseForCoach($userId);
8093
        foreach ($listInfo as $i => $listCoursesInfo) {
8094
            $courseInfo = $listCoursesInfo['course'];
8095
            $courseCode = $listCoursesInfo['course']['code'];
8096
8097
            $listParamsCourse = array();
8098
            $listParamsCourse['icon'] = '<div style="float:left">
8099
                <input style="border:none;" type="button" onclick="$(\'#course-'.$courseCode.'\').toggle(\'fast\')" value="+" /></div>'.
8100
                Display::return_icon('blackboard.png', $courseInfo['title'], array(), ICON_SIZE_LARGE);
8101
            $listParamsCourse['link'] = '';
8102
            $listParamsCourse['title'] = Display::tag(
8103
                'a',
8104
                $courseInfo['title'],
8105
                array('href' => $listParamsCourse['link'])
8106
            );
8107
            $htmlCourse = '<div class="well" style="border-color:#27587D">'.
8108
                CourseManager::course_item_html($listParamsCourse, true);
0 ignored issues
show
Bug introduced by
The method course_item_html() does not exist on CourseManager. Did you maybe mean course_item_html_no_icon()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
8109
            // for each category of session
8110
            $htmlCatSessions = '';
8111
            foreach ($listCoursesInfo['sessionCatList'] as $j => $listCatSessionsInfo) {
8112
                // we got an array of session categories
8113
                $catSessionId = $listCoursesInfo['sessionCatList'][$j]['catSessionId'];
8114
                $catSessionName = $listCoursesInfo['sessionCatList'][$j]['catSessionName'];
8115
8116
                $listParamsCatSession['icon'] = Display::return_icon('folder_blue.png', $catSessionName, array(), ICON_SIZE_LARGE);
8117
                $listParamsCatSession['link'] = '';
8118
                $listParamsCatSession['title'] = $catSessionName;
8119
8120
                $marginShift = 20;
8121
                if ($catSessionName != '') {
8122
                    $htmlCatSessions .= '<div style="margin-left:'.$marginShift.'px;">' .
8123
                        CourseManager::course_item_html($listParamsCatSession, true) . '</div>';
0 ignored issues
show
Bug introduced by
The method course_item_html() does not exist on CourseManager. Did you maybe mean course_item_html_no_icon()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
8124
                    $marginShift = 40;
8125
                }
8126
8127
                // for each sessions
8128
                $listCatSessionSessionList = $listCoursesInfo['sessionCatList'][$j]['sessionList'];
8129
                $htmlSession = '';
8130
                foreach ($listCatSessionSessionList as $k => $listSessionInfo) {
8131
                    // we got an array of session info
8132
                    $sessionId = $listSessionInfo['sessionId'];
8133
                    $sessionName = $listSessionInfo['sessionName'];
8134
8135
                    $listParamsSession['icon'] = Display::return_icon('blackboard_blue.png', $sessionName, array(), ICON_SIZE_LARGE);
8136
                    $listParamsSession['link'] = '';
8137
                    $linkToCourseSession = $courseInfo['course_public_url'].'?id_session='.$sessionId;
8138
                    $listParamsSession['title'] =
8139
                        $sessionName.'<div style="font-weight:normal; font-style:italic">
8140
                            <a href="'.$linkToCourseSession.'">'.get_lang('GoToCourseInsideSession').'</a>
8141
                            </div>';
8142
                    $htmlSession .= '<div style="margin-left:'.$marginShift.'px;">'.
8143
                        CourseManager::course_item_html($listParamsSession, true).'</div>';
0 ignored issues
show
Bug introduced by
The method course_item_html() does not exist on CourseManager. Did you maybe mean course_item_html_no_icon()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
8144
                }
8145
                $htmlCatSessions .= $htmlSession;
8146
            }
8147
            $htmlRes .= $htmlCourse.'<div style="display:none" id="course-'.$courseCode.'">'.$htmlCatSessions.'</div></div>';
8148
        }
8149
8150
        return $htmlRes;
8151
    }
8152
8153
    /**
8154
     * @param int $userId
8155
     * @param int $courseId
8156
     *
8157
     * @return array
8158
     */
8159 View Code Duplication
    public static function searchCourseInSessionsFromUser($userId, $courseId)
8160
    {
8161
        $table = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
8162
        $userId = (int) $userId;
8163
        $courseId = (int) $courseId;
8164
        if (empty($userId) || empty($courseId)) {
8165
            return [];
8166
        }
8167
8168
        $sql = "SELECT * FROM $table 
8169
                WHERE c_id = $courseId AND user_id = $userId";
8170
        $result = Database::query($sql);
8171
8172
        return Database::store_result($result, 'ASSOC');
8173
    }
8174
8175
    /**
8176
     * subsscribe and redirect to session after inscription
8177
     */
8178
    public static function redirectToSession()
8179
    {
8180
        $sessionId = isset($_SESSION['session_redirect']) ? $_SESSION['session_redirect'] : null;
8181
        $onlyOneCourseSessionToRedirect = isset($_SESSION['only_one_course_session_redirect']) ? $_SESSION['only_one_course_session_redirect'] : null;
8182
        $userId = api_get_user_id();
8183
        $sessionInfo = api_get_session_info($sessionId);
8184
8185
        if (!empty($sessionInfo)) {
8186
8187
            $response = self::isUserSubscribedAsStudent($sessionId, $userId);
8188
8189
            if ($response) {
8190
8191
                $urlToRedirect = api_get_path(WEB_CODE_PATH) . 'session/index.php?session_id=' . $sessionId;
8192
8193
                if (!empty($onlyOneCourseSessionToRedirect)) {
8194
8195
                        $urlToRedirect = api_get_path(WEB_PATH) . 'courses/' . $onlyOneCourseSessionToRedirect . '/index.php?id_session=' . $sessionId;
8196
                }
8197
8198
                header('Location: ' . $urlToRedirect);
8199
                exit;
8200
            }
8201
        }
8202
    }
8203
}
8204