Completed
Push — 1.11.x ( e2faf7...35c30d )
by José
57:41 queued 29:07
created

SessionManager::redirectToSession()   B

Complexity

Conditions 5
Paths 5

Size

Total Lines 21
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

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