Passed
Push — 1.10.x ( 44706e...767d99 )
by
unknown
56:54
created

SessionManager::edit_session()   F

Complexity

Conditions 22
Paths 1544

Size

Total Lines 115
Code Lines 80

Duplication

Lines 0
Ratio 0 %
Metric Value
dl 0
loc 115
rs 2
cc 22
eloc 80
nc 1544
nop 17

How to fix   Long Method    Complexity    Many Parameters   

Long Method

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

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

Commonly applied refactorings include:

Many Parameters

Methods with many parameters are not only hard to understand, but their parameters also often become inconsistent when you need more, or different data.

There are several approaches to avoid long parameter lists:

1
<?php
2
/* For licensing terms, see /license.txt */
3
4
use Chamilo\CoreBundle\Entity\SessionRelCourseRelUser;
5
6
/**
7
 * Class SessionManager
8
 *
9
 * This is the session library for Chamilo.
10
 * All main sessions functions should be placed here.
11
 * This class provides methods for sessions management.
12
 * Include/require it in your code to use its features.
13
 *
14
 * @package chamilo.library
15
 *
16
 */
17
class SessionManager
18
{
19
    public static $_debug = false;
20
21
    /**
22
     * Constructor
23
     */
24
    public function __construct()
25
    {
26
    }
27
28
    /**
29
     * Fetches a session from the database
30
     * @param  int $id Session Id
31
     *
32
     * @return  array   Session details
33
     */
34
    public static function fetch($id)
35
    {
36
        $t = Database::get_main_table(TABLE_MAIN_SESSION);
37
        if ($id != strval(intval($id))) {
38
            return array();
39
        }
40
        $s = "SELECT * FROM $t WHERE id = $id";
41
        $r = Database::query($s);
42
        if (Database::num_rows($r) != 1) {
43
            return array();
44
        }
45
46
        return Database::fetch_array($r, 'ASSOC');
47
    }
48
49
    /**
50
     * Create a session
51
     * @author Carlos Vargas <[email protected]>, from existing code
52
     * @param   string  $name
53
     * @param   string  $startDate (YYYY-MM-DD hh:mm:ss)
54
     * @param   string  $endDate (YYYY-MM-DD hh:mm:ss)
55
     * @param   string  $displayStartDate (YYYY-MM-DD hh:mm:ss)
56
     * @param   string  $displayEndDate (YYYY-MM-DD hh:mm:ss)
57
     * @param   string  $coachStartDate (YYYY-MM-DD hh:mm:ss)
58
     * @param   string  $coachEndDate (YYYY-MM-DD hh:mm:ss)
59
     * @param   mixed   $coachId If integer, this is the session coach id, if string, the coach ID will be looked for from the user table
60
     * @param   integer $sessionCategoryId ID of the session category in which this session is registered
61
     * @param   integer $visibility Visibility after end date (0 = read-only, 1 = invisible, 2 = accessible)
62
     * @param   bool    $fixSessionNameIfExists
63
     * @param   string  $duration
64
     * @param   string  $description Optional. The session description
65
     * @param   int     $showDescription Optional. Whether show the session description
66
     * @param   array   $extraFields
67
     * @param   int     $sessionAdminId Optional. If this sessions was created by a session admin, assign it to him
68
     * @param boolean $sendSubscritionNotification Optional.
69
     *          Whether send a mail notification to users being subscribed
70
     * @todo use an array to replace all this parameters or use the model.lib.php ...
71
     * @return mixed       Session ID on success, error message otherwise
72
     * */
73
    public static function create_session(
74
        $name,
75
        $startDate,
76
        $endDate,
77
        $displayStartDate,
78
        $displayEndDate,
79
        $coachStartDate,
80
        $coachEndDate,
81
        $coachId,
82
        $sessionCategoryId,
83
        $visibility = 1,
84
        $fixSessionNameIfExists = false,
85
        $duration = null,
86
        $description = null,
87
        $showDescription = 0,
88
        $extraFields = array(),
89
        $sessionAdminId = 0,
90
        $sendSubscritionNotification = false
91
    ) {
92
        global $_configuration;
93
94
        //Check portal limits
95
        $access_url_id = 1;
96
97
        if (api_get_multiple_access_url()) {
98
            $access_url_id = api_get_current_access_url_id();
99
        }
100
101 View Code Duplication
        if (is_array($_configuration[$access_url_id]) &&
102
            isset($_configuration[$access_url_id]['hosting_limit_sessions']) &&
103
            $_configuration[$access_url_id]['hosting_limit_sessions'] > 0
104
        ) {
105
            $num = self::count_sessions();
106
            if ($num >= $_configuration[$access_url_id]['hosting_limit_sessions']) {
107
                api_warn_hosting_contact('hosting_limit_sessions');
108
                return get_lang('PortalSessionsLimitReached');
109
            }
110
        }
111
112
        $name = Database::escape_string(trim($name));
113
        $sessionCategoryId = intval($sessionCategoryId);
114
        $visibility = intval($visibility);
115
        $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
116
117
        $startDate = Database::escape_string($startDate);
118
        $endDate = Database::escape_string($endDate);
119
120
        if (empty($name)) {
121
            $msg = get_lang('SessionNameIsRequired');
122
            return $msg;
123
        } elseif (empty($coachId)) {
124
            $msg = get_lang('CoachIsRequired');
125
            return $msg;
126
        } elseif (!empty($startDate) && !api_is_valid_date($startDate, 'Y-m-d H:i') && !api_is_valid_date($startDate, 'Y-m-d H:i:s')) {
127
            $msg = get_lang('InvalidStartDate');
128
            return $msg;
129
        } elseif (!empty($endDate) && !api_is_valid_date($endDate, 'Y-m-d H:i') && !api_is_valid_date($endDate, 'Y-m-d H:i:s')) {
130
            $msg = get_lang('InvalidEndDate');
131
            return $msg;
132
        } elseif (!empty($startDate) && !empty($endDate) && $startDate >= $endDate) {
133
            $msg = get_lang('StartDateShouldBeBeforeEndDate');
134
            return $msg;
135
        } else {
136
            $ready_to_create = false;
137
            if ($fixSessionNameIfExists) {
138
                $name = self::generateNextSessionName($name);
139
                if ($name) {
140
                    $ready_to_create = true;
141
                } else {
142
                    $msg = get_lang('SessionNameAlreadyExists');
143
                    return $msg;
144
                }
145
            } else {
146
                $rs = Database::query("SELECT 1 FROM $tbl_session WHERE name='" . $name . "'");
147
                if (Database::num_rows($rs)) {
148
                    $msg = get_lang('SessionNameAlreadyExists');
149
                    return $msg;
150
                }
151
                $ready_to_create = true;
152
            }
153
154
            if ($ready_to_create) {
155
                $sessionAdminId = !empty($sessionAdminId) ? $sessionAdminId : api_get_user_id();
156
                $values = array(
157
                    'name' => $name,
158
                    'id_coach' => $coachId,
159
                    'session_admin_id' => $sessionAdminId,
160
                    'visibility' => $visibility,
161
                    'description' => $description,
162
                    'show_description' => intval($showDescription),
163
                    'send_subscription_notification' => $sendSubscritionNotification
164
                );
165
166
                if (!empty($startDate)) {
167
                    $values['access_start_date'] = api_get_utc_datetime($startDate);
168
                }
169
170
                if (!empty($endDate)) {
171
                    $values['access_end_date'] = api_get_utc_datetime($endDate);
172
                }
173
174
                if (!empty($displayStartDate)) {
175
                    $values['display_start_date'] = api_get_utc_datetime($displayStartDate);
176
                }
177
178
                if (!empty($displayEndDate)) {
179
                    $values['display_end_date'] = api_get_utc_datetime($displayEndDate);
180
                }
181
182
                if (!empty($coachStartDate)) {
183
                    $values['coach_access_start_date'] = api_get_utc_datetime($coachStartDate);
184
                }
185
                if (!empty($coachEndDate)) {
186
                    $values['coach_access_end_date'] = api_get_utc_datetime($coachEndDate);
187
                }
188
189
                if (!empty($sessionCategoryId)) {
190
                    $values['session_category_id'] = $sessionCategoryId;
191
                }
192
193
                $session_id = Database::insert($tbl_session, $values);
194
195
                $duration = intval($duration);
196
197 View Code Duplication
                if (!empty($duration)) {
198
                    $sql = "UPDATE $tbl_session SET
199
                        access_start_date = NULL,
200
                        access_end_date = NULL,
201
                        display_start_date = NULL,
202
                        display_end_date = NULL,
203
                        coach_access_start_date = NULL,
204
                        coach_access_end_date = NULL,
205
                        duration = $duration
206
                    WHERE id = $session_id";
207
                    Database::query($sql);
208
                } else {
209
                    $sql = "UPDATE $tbl_session
210
                        SET duration = 0
211
                        WHERE id = $session_id";
212
                    Database::query($sql);
213
                }
214
215
                if (!empty($session_id)) {
216
                    $extraFields['item_id'] = $session_id;
217
218
                    $sessionFieldValue = new ExtraFieldValue('session');
219
                    $sessionFieldValue->saveFieldValues($extraFields);
220
221
                    /*
222
                      Sends a message to the user_id = 1
223
224
                      $user_info = api_get_user_info(1);
225
                      $complete_name = $user_info['firstname'].' '.$user_info['lastname'];
226
                      $subject = api_get_setting('siteName').' - '.get_lang('ANewSessionWasCreated');
227
                      $message = get_lang('ANewSessionWasCreated')." <br /> ".get_lang('NameOfTheSession').' : '.$name;
228
                      api_mail_html($complete_name, $user_info['email'], $subject, $message);
229
                     *
230
                     */
231
                    //Adding to the correct URL
232
                    $access_url_id = api_get_current_access_url_id();
233
                    UrlManager::add_session_to_url($session_id, $access_url_id);
234
235
                    // add event to system log
236
                    $user_id = api_get_user_id();
237
                    Event::addEvent(
238
                        LOG_SESSION_CREATE,
239
                        LOG_SESSION_ID,
240
                        $session_id,
241
                        api_get_utc_datetime(),
242
                        $user_id
243
                    );
244
                }
245
246
                return $session_id;
247
            }
248
        }
249
    }
250
251
    /**
252
     * @param string $name
253
     *
254
     * @return bool
255
     */
256
    public static function session_name_exists($name)
257
    {
258
        $name = Database::escape_string($name);
259
        $sql = "SELECT COUNT(*) as count FROM " . Database::get_main_table(TABLE_MAIN_SESSION) . "
260
                WHERE name = '$name'";
261
        $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...
262
263
        return $result['count'] > 0;
264
    }
265
266
    /**
267
     * @param string $where_condition
268
     *
269
     * @return mixed
270
     */
271
    public static function get_count_admin($where_condition = '')
272
    {
273
        $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
274
        $tbl_session_category = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
275
        $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
276
        $table_access_url_rel_session = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
277
        $tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
278
279
        $where = 'WHERE 1=1 ';
280
        $user_id = api_get_user_id();
281
282
        $extraJoin = '';
283
284
        if (api_is_session_admin() &&
285
            api_get_setting('allow_session_admins_to_manage_all_sessions') == 'false'
286
        ) {
287
            $where .= " AND (
288
                            s.session_admin_id = $user_id  OR
289
                            sru.user_id = '$user_id' AND
290
                            sru.relation_type = '" . SESSION_RELATION_TYPE_RRHH . "'
291
                            )
292
                      ";
293
294
            $extraJoin = " INNER JOIN $tbl_session_rel_user sru
295
                           ON sru.session_id = s.id ";
296
        }
297
298
        $today = api_get_utc_datetime();
299
        $today = api_strtotime($today, 'UTC');
300
        $today = date('Y-m-d', $today);
301
302
        if (!empty($where_condition)) {
303
            $where_condition = str_replace("(  session_active = ':'  )", '1=1', $where_condition);
304
305
            $where_condition = str_replace('category_name', 'sc.name', $where_condition);
306
            $where_condition = str_replace(
307
                array("AND session_active = '1'  )", " AND (  session_active = '1'  )"),
308
                array(') GROUP BY s.name HAVING session_active = 1 ', " GROUP BY s.name HAVING session_active = 1 " )
309
                , $where_condition
310
            );
311
            $where_condition = str_replace(
312
                array("AND session_active = '0'  )", " AND (  session_active = '0'  )"),
313
                array(') GROUP BY s.name HAVING session_active = 0 ', " GROUP BY s.name HAVING session_active = '0' "),
314
                $where_condition
315
            );
316
        } else {
317
            $where_condition = " AND 1 = 1";
318
        }
319
320
        $courseCondition = null;
321
        if (strpos($where_condition, 'c.id')) {
322
            $table = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
323
            $tableCourse = Database::get_main_table(TABLE_MAIN_COURSE);
324
            $courseCondition = " INNER JOIN $table course_rel_session
325
                                 ON (s.id = course_rel_session.session_id)
326
                                 INNER JOIN $tableCourse c
327
                                 ON (course_rel_session.c_id = c.id)
328
                                ";
329
        }
330
331
        $sql = "SELECT COUNT(id) as total_rows FROM (
332
                SELECT DISTINCT
333
                 IF (
334
					(s.access_start_date <= '$today' AND '$today' <= s.access_end_date) OR
335
                    (s.access_start_date IS NULL AND s.access_end_date  = IS NULL ) OR
336
					(s.access_start_date <= '$today' AND s.access_end_date IS NULL) OR
337
					('$today' <= s.access_end_date AND s.access_start_date IS NULL)
338
				, 1, 0) as session_active,
339
                s.id
340
                FROM $tbl_session s
341
                LEFT JOIN $tbl_session_category sc
342
                ON s.session_category_id = sc.id
343
                INNER JOIN $tbl_user u
344
                ON s.id_coach = u.user_id
345
                $courseCondition
346
                $extraJoin
347
                $where $where_condition ) as session_table";
348
349
        if (api_is_multiple_url_enabled()) {
350
351
            $access_url_id = api_get_current_access_url_id();
352
            if ($access_url_id != -1) {
353
                $where.= " AND ar.access_url_id = $access_url_id ";
354
355
                $sql = "SELECT count(id) as total_rows FROM (
356
                SELECT DISTINCT
357
                  IF (
358
					(s.access_start_date <= '$today' AND '$today' <= s.access_end_date) OR
359
                    (s.access_start_date IS NULL AND s.access_end_date IS NULL) OR
360
					(s.access_start_date <= '$today' AND s.access_end_date IS NULL) OR
361
					('$today' <= s.access_end_date AND s.access_start_date IS NULL)
362
				, 1, 0)
363
				as session_active,
364
				s.id
365
                FROM $tbl_session s
366
                    LEFT JOIN  $tbl_session_category sc
367
                    ON s.session_category_id = sc.id
368
                    INNER JOIN $tbl_user u ON s.id_coach = u.user_id
369
                    INNER JOIN $table_access_url_rel_session ar
370
                    ON ar.session_id = s.id
371
                    $courseCondition
372
                    $extraJoin
373
                $where $where_condition) as session_table";
374
            }
375
        }
376
377
        $result_rows = Database::query($sql);
378
        $row = Database::fetch_array($result_rows);
379
        $num = $row['total_rows'];
380
381
        return $num;
382
    }
383
384
    /**
385
     * Gets the admin session list callback of the session/session_list.php page
386
     * @param array $options order and limit keys
387
     * @param boolean $get_count Whether to get all the results or only the count
388
     * @return mixed Integer for number of rows, or array of results
389
     * @assert (array(),true) !== false
390
     */
391
    public static function get_sessions_admin($options = array(), $get_count = false)
392
    {
393
        $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
394
        $sessionCategoryTable = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
395
396
        $where = 'WHERE 1 = 1 ';
397
        $user_id = api_get_user_id();
398
399 View Code Duplication
        if (!api_is_platform_admin()) {
400
            if (api_is_session_admin() &&
401
                api_get_setting('allow_session_admins_to_manage_all_sessions') == 'false'
402
            ) {
403
                $where .=" AND s.session_admin_id = $user_id ";
404
            }
405
        }
406
407
        if (!api_is_platform_admin() && api_is_teacher() &&
408
            api_get_setting('allow_teachers_to_create_sessions') == 'true'
409
        ) {
410
            $where .=" AND s.id_coach = $user_id ";
411
        }
412
413
        $extra_field = new ExtraField('session');
414
        $conditions = $extra_field->parseConditions($options);
415
        $inject_joins = $conditions['inject_joins'];
416
        $where .= $conditions['where'];
417
        $inject_where = $conditions['inject_where'];
418
        $inject_extra_fields = $conditions['inject_extra_fields'];
419
420
        $order = $conditions['order'];
421
        $limit = $conditions['limit'];
422
423
        $isMakingOrder = false;
424
425
        if ($get_count == true) {
426
            $select = " SELECT count(*) as total_rows";
427
        } else {
428
            $select =
429
                "SELECT DISTINCT ".
430
                " s.name, ".
431
                " s.display_start_date, ".
432
                " s.display_end_date, ".
433
                " access_start_date, ".
434
                " access_end_date, ".
435
                " s.visibility, ".
436
                " s.session_category_id, ".
437
                " $inject_extra_fields ".
438
                " s.id ";
439
440
            $isMakingOrder = strpos($options['order'], 'category_name') === 0;
441
        }
442
443
        $isFilteringSessionCategory = strpos($where, 'category_name') !== false;
444
445
        if ($isMakingOrder || $isFilteringSessionCategory) {
446
            $inject_joins .= " LEFT JOIN $sessionCategoryTable sc ON s.session_category_id = sc.id ";
447
448
            if ($isFilteringSessionCategory) {
449
                $where = str_replace('category_name', 'sc.name', $where);
450
            }
451
452
            if ($isMakingOrder) {
453
                $order = str_replace('category_name', 'sc.name', $order);
454
            }
455
        }
456
457
        $query = "$select FROM $tbl_session s $inject_joins $where $inject_where";
458
459
        if (api_is_multiple_url_enabled()) {
460
            $table_access_url_rel_session= Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
461
            $access_url_id = api_get_current_access_url_id();
462
            if ($access_url_id != -1) {
463
                $where.= " AND ar.access_url_id = $access_url_id ";
464
                $query = "$select
465
                        FROM $tbl_session s $inject_joins
466
                        INNER JOIN $table_access_url_rel_session ar
467
                        ON (ar.session_id = s.id) $where";
468
            }
469
        }
470
471
        $query .= $order;
472
        $query .= $limit;
473
        $result = Database::query($query);
474
475
        $categories = self::get_all_session_category();
476
        $orderedCategories = array();
477
        if (!empty($categories)) {
478
            foreach ($categories as $category) {
479
                $orderedCategories[$category['id']] = $category['name'];
480
            }
481
        }
482
483
        $formatted_sessions = array();
484
485
        if (Database::num_rows($result)) {
486
            $sessions = Database::store_result($result, 'ASSOC');
487
            if ($get_count) {
488
                return $sessions[0]['total_rows'];
489
            }
490
491
            foreach ($sessions as $session) {
492
                $session_id = $session['id'];
493
                $session['name'] = Display::url($session['name'], "resume_session.php?id_session=".$session['id']);
494
495 View Code Duplication
                if (isset($session['session_active']) && $session['session_active'] == 1) {
496
                    $session['session_active'] = Display::return_icon('accept.png', get_lang('Active'), array(), ICON_SIZE_SMALL);
497
                } else {
498
                    $session['session_active'] = Display::return_icon('error.png', get_lang('Inactive'), array(), ICON_SIZE_SMALL);
499
                }
500
501
                $session = self::convert_dates_to_local($session, true);
502
503 View Code Duplication
                switch ($session['visibility']) {
504
                    case SESSION_VISIBLE_READ_ONLY: //1
505
                        $session['visibility'] = get_lang('ReadOnly');
506
                        break;
507
                    case SESSION_VISIBLE:           //2
508
                    case SESSION_AVAILABLE:         //4
509
                        $session['visibility'] = get_lang('Visible');
510
                        break;
511
                    case SESSION_INVISIBLE:         //3
512
                        $session['visibility'] = api_ucfirst(get_lang('Invisible'));
513
                        break;
514
                }
515
516
                // Cleaning double selects.
517 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...
518
                    if (isset($options_by_double[$key]) || isset($options_by_double[$key.'_second'])) {
519
                        $options = explode('::', $value);
520
                    }
521
                    $original_key = $key;
522
523
                    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...
524
                    } else {
525
                        $key = str_replace('_second', '', $key);
526
                    }
527
528
                    if (isset($options_by_double[$key])) {
529
                        if (isset($options[0])) {
530
                            if (isset($options_by_double[$key][$options[0]])) {
531
                                if (strpos($original_key, '_second') === false) {
532
                                    $value = $options_by_double[$key][$options[0]]['option_display_text'];
533
                                } else {
534
                                    $value = $options_by_double[$key][$options[1]]['option_display_text'];
535
                                }
536
                            }
537
                        }
538
                    }
539
                }
540
                $formatted_sessions[$session_id] = $session;
541
                $categoryName = isset($orderedCategories[$session['session_category_id']]) ? $orderedCategories[$session['session_category_id']] : '';
542
                $formatted_sessions[$session_id]['category_name'] = $categoryName;
543
            }
544
        }
545
        return $formatted_sessions;
546
    }
547
548
    /**
549
     *  Get total of records for progress of learning paths in the given session
550
     *  @param int session id
551
     *  @return int
552
     */
553
    public static function get_count_session_lp_progress($sessionId = 0)
554
    {
555
        $tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
556
        $tbl_lp_view = Database::get_course_table(TABLE_LP_VIEW);
557
        $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
558
        $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
559
560
        $sessionId = intval($sessionId);
561
562
        $sql = "SELECT  count(*) as total_rows
563
                FROM $tbl_lp_view v
564
                INNER JOIN $tbl_lp l ON l.id = v.lp_id
565
                INNER JOIN $tbl_user u ON u.user_id = v.user_id
566
                INNER JOIN $tbl_course c
567
                WHERE v.session_id = " . $sessionId;
568
        $result_rows = Database::query($sql);
569
        $row = Database::fetch_array($result_rows);
570
        $num = $row['total_rows'];
571
572
        return $num;
573
    }
574
575
    /**
576
     * Gets the progress of learning paths in the given session
577
     * @param int   $sessionId
578
     * @param int $courseId
579
     * @param string $date_from
580
     * @param string $date_to
581
     * @param array options order and limit keys
582
     * @return array table with user name, lp name, progress
583
     */
584
    public static function get_session_lp_progress($sessionId = 0, $courseId = 0, $date_from, $date_to, $options)
585
    {
586
        //escaping vars
587
        $sessionId = $sessionId == 'T' ? 'T' : intval($sessionId);
588
        $courseId = intval($courseId);
589
        $date_from = Database :: escape_string($date_from);
590
        $date_to = Database :: escape_string($date_to);
591
592
        //tables
593
        $session_course_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
594
        $user = Database::get_main_table(TABLE_MAIN_USER);
595
        $tbl_course_lp_view = Database::get_course_table(TABLE_LP_VIEW);
596
597
        $course = api_get_course_info_by_id($courseId);
598
599
        //getting all the students of the course
600
        //we are not using this because it only returns user ids
601
        /* if (empty($sessionId)
602
          {
603
          // Registered students in a course outside session.
604
          $users = CourseManager :: get_student_list_from_course_code($course_code);
605
          } else {
606
          // Registered students in session.
607
          $users = CourseManager :: get_student_list_from_course_code($course_code, true, $sessionId);
608
          } */
609
610
        $sessionCond = 'and session_id = %s';
611
        if ($sessionId == 'T') {
612
            $sessionCond = "";
613
        }
614
615
        $where = " WHERE c_id = '%s' AND s.status <> 2 $sessionCond";
616
617
        $limit = null;
618
        if (!empty($options['limit'])) {
619
            $limit = " LIMIT " . $options['limit'];
620
        }
621
622
        if (!empty($options['where'])) {
623
            $where .= ' '.$options['where'];
624
        }
625
626
        $order = null;
627
        if (!empty($options['order'])) {
628
            $order = " ORDER BY " . $options['order'];
629
        }
630
631
        $sql = "SELECT u.user_id, u.lastname, u.firstname, u.username, u.email, s.c_id
632
                FROM $session_course_user s
633
                INNER JOIN $user u ON u.user_id = s.user_id
634
                $where
635
                $order
636
                $limit";
637
638
        $sql_query = sprintf($sql, Database::escape_string($course['real_id']), $sessionId);
639
640
        $rs = Database::query($sql_query);
641
        while ($user = Database::fetch_array($rs)) {
642
            $users[$user['user_id']] = $user;
643
        }
644
645
        //Get lessons
646
        $lessons = LearnpathList::get_course_lessons($course['code'], $sessionId);
647
648
        $table = array();
649
        foreach ($users as $user) {
650
            $data = array(
651
                'lastname' => $user[1],
652
                'firstname' => $user[2],
653
                'username' => $user[3],
654
            );
655
656
            $sessionCond = 'AND v.session_id = %d';
657
            if ($sessionId == 'T') {
658
                $sessionCond = "";
659
            }
660
661
            //Get lessons progress by user
662
            $sql = "SELECT v.lp_id as id, v.progress
663
                    FROM  $tbl_course_lp_view v
664
                    WHERE v.c_id = %d
665
                    AND v.user_id = %d
666
            $sessionCond";
667
668
            $sql_query = sprintf($sql,
669
                intval($courseId),
670
                intval($user['user_id']),
671
                $sessionId
672
            );
673
674
            $result = Database::query($sql_query);
675
676
            $user_lessons = array();
677
            while ($row = Database::fetch_array($result)) {
678
                $user_lessons[$row['id']] = $row;
679
            }
680
681
            //Match course lessons with user progress
682
            $progress = 0;
683
            $count = 0;
684
            foreach ($lessons as $lesson) {
685
                $data[$lesson['id']] = (!empty($user_lessons[$lesson['id']]['progress'])) ? $user_lessons[$lesson['id']]['progress'] : 0;
686
                $progress += $data[$lesson['id']];
687
                $data[$lesson['id']] = $data[$lesson['id']] . '%';
688
                $count++;
689
            }
690
            if ($count == 0) {
691
                $data['total'] = 0;
692
            } else {
693
                $data['total'] = round($progress / $count, 2) . '%';
694
            }
695
            $table[] = $data;
696
        }
697
698
        return $table;
699
    }
700
701
    /**
702
     * Gets the survey answers
703
     * @param int   $sessionId
704
     * @param int   $courseId
705
     * @param int   $surveyId
706
     * @param array options order and limit keys
707
     * @todo fix the query
708
     * @return array table with user name, lp name, progress
709
     */
710
    public static function get_survey_overview($sessionId = 0, $courseId = 0, $surveyId = 0, $date_from, $date_to, $options)
711
    {
712
        //escaping vars
713
        $sessionId = intval($sessionId);
714
        $courseId = intval($courseId);
715
        $surveyId = intval($surveyId);
716
        $date_from = Database::escape_string($date_from);
717
        $date_to = Database::escape_string($date_to);
718
719
        //tables
720
        $session_course_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
721
        $user = Database::get_main_table(TABLE_MAIN_USER);
722
        $tbl_course_lp_view = Database::get_course_table(TABLE_LP_VIEW);
723
        $c_survey = Database::get_course_table(TABLE_SURVEY);
724
        $c_survey_answer = Database::get_course_table(TABLE_SURVEY_ANSWER);
725
        $c_survey_question = Database::get_course_table(TABLE_SURVEY_QUESTION);
726
        $c_survey_question_option = Database::get_course_table(TABLE_SURVEY_QUESTION_OPTION);
727
728
        $course = api_get_course_info_by_id($courseId);
729
730
        $where = " WHERE c_id = '%s' AND s.status <> 2 AND session_id = %s";
731
732
        $limit = null;
733
        if (!empty($options['limit'])) {
734
            $limit = " LIMIT " . $options['limit'];
735
        }
736
737
        if (!empty($options['where'])) {
738
            $where .= ' '.$options['where'];
739
        }
740
741
        $order = null;
742
        if (!empty($options['order'])) {
743
            $order = " ORDER BY " . $options['order'];
744
        }
745
746
        $sql = "SELECT u.user_id, u.lastname, u.firstname, u.username, u.email, s.c_id
747
                FROM $session_course_user s
748
                INNER JOIN $user u ON u.user_id = s.user_id
749
                $where $order $limit";
750
751
        $sql_query = sprintf($sql, intval($course['real_id']), $sessionId);
752
        $rs = Database::query($sql_query);
753
        while ($user = Database::fetch_array($rs)) {
754
            $users[$user['user_id']] = $user;
755
        }
756
757
        //Get survey questions
758
        $questions = SurveyManager::get_questions($surveyId, $courseId);
759
760
        //Survey is anonymous?
761
        $result = Database::query(sprintf("SELECT anonymous FROM $c_survey WHERE survey_id = %d", $surveyId));
762
        $row = Database::fetch_array($result);
763
        $anonymous = ($row['anonymous'] == 1) ? true : false;
764
765
        $table = array();
766
        foreach ($users as $user) {
767
            $data = array(
768
                'lastname' => ($anonymous ? '***' : $user[1]),
769
                'firstname' => ($anonymous ? '***' : $user[2]),
770
                'username' => ($anonymous ? '***' : $user[3]),
771
            );
772
773
            //Get questions by user
774
            $sql = "SELECT sa.question_id, sa.option_id, sqo.option_text, sq.type
775
                    FROM $c_survey_answer sa
776
                    INNER JOIN $c_survey_question sq
777
                    ON sq.question_id = sa.question_id
778
                    LEFT JOIN $c_survey_question_option sqo
779
                    ON
780
                      sqo.c_id = sa.c_id AND
781
                      sqo.question_id = sq.question_id AND
782
                      sqo.question_option_id = sa.option_id AND
783
                      sqo.survey_id = sq.survey_id
784
                    WHERE
785
                      sa.survey_id = %d AND
786
                      sa.c_id = %d AND
787
                      sa.user = %d
788
            "; //. $where_survey;
789
            $sql_query = sprintf($sql, $surveyId, $courseId, $user['user_id']);
790
791
            $result = Database::query($sql_query);
792
793
            $user_questions = array();
794
            while ($row = Database::fetch_array($result)) {
795
                $user_questions[$row['question_id']] = $row;
796
            }
797
798
            //Match course lessons with user progress
799
            foreach ($questions as $question_id => $question) {
800
                $option_text = 'option_text';
801
                if ($user_questions[$question_id]['type'] == 'open') {
802
                    $option_text = 'option_id';
803
                }
804
                $data[$question_id] = $user_questions[$question_id][$option_text];
805
            }
806
807
            $table[] = $data;
808
        }
809
        return $table;
810
    }
811
812
    /**
813
     * Gets the progress of the given session
814
     * @param int   $sessionId
815
     * @param int   $courseId
816
     * @param array options order and limit keys
817
     *
818
     * @return array table with user name, lp name, progress
819
     */
820
    public static function get_session_progress($sessionId, $courseId, $date_from, $date_to, $options)
821
    {
822
        $sessionId = intval($sessionId);
823
824
        $getAllSessions = false;
825
        if (empty($sessionId)) {
826
            $sessionId = 0;
827
            $getAllSessions = true;
828
        }
829
830
        //tables
831
        $session_course_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
832
        $user = Database::get_main_table(TABLE_MAIN_USER);
833
        $workTable = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
834
        $workTableAssignment = Database::get_course_table(TABLE_STUDENT_PUBLICATION_ASSIGNMENT);
835
        $tbl_course_lp = Database::get_course_table(TABLE_LP_MAIN);
836
        $wiki = Database::get_course_table(TABLE_WIKI);
837
        $table_stats_default = Database::get_main_table(TABLE_STATISTIC_TRACK_E_DEFAULT);
838
        $table_stats_access = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ACCESS);
839
840
        $course = api_get_course_info_by_id($courseId);
841
        $where = " WHERE c_id = '%s' AND s.status <> 2 ";
842
843
        $limit = null;
844
        if (!empty($options['limit'])) {
845
            $limit = " LIMIT " . $options['limit'];
846
        }
847
848
        if (!empty($options['where'])) {
849
            $where .= ' '.$options['where'];
850
        }
851
852
        $order = null;
853
        if (!empty($options['order'])) {
854
            $order = " ORDER BY " . $options['order'];
855
        }
856
857
        //TODO, fix create report without session
858
        $queryVariables = array($course['real_id']);
859
        if (!empty($sessionId)) {
860
            $where .= ' AND session_id = %s';
861
            $queryVariables[] = $sessionId;
862
            $sql = "SELECT
863
                        u.user_id, u.lastname, u.firstname, u.username,
864
                        u.email, s.c_id, s.session_id
865
                    FROM $session_course_user s
866
                    INNER JOIN $user u
867
                    ON u.user_id = s.user_id
868
                    $where $order $limit";
869
        } else {
870
            $sql = "SELECT
871
                        u.user_id, u.lastname, u.firstname, u.username,
872
                        u.email, s.c_id, s.session_id
873
                    FROM $session_course_user s
874
                    INNER JOIN $user u ON u.user_id = s.user_id
875
                    $where $order $limit";
876
        }
877
878
        $sql_query = vsprintf($sql, $queryVariables);
879
        $rs = Database::query($sql_query);
880
        while ($user = Database::fetch_array($rs)) {
881
            $users[$user['user_id']] = $user;
882
        }
883
884
        /**
885
         *  Lessons
886
         */
887
        $sql = "SELECT * FROM $tbl_course_lp WHERE c_id = %s ";  //AND session_id = %s
888
        $sql_query = sprintf($sql, $course['real_id']);
889
        $result = Database::query($sql_query);
890
        $arrLesson = array(array());
891 View Code Duplication
        while ($row = Database::fetch_array($result)) {
892
            if (empty($arrLesson[$row['session_id']]['lessons_total'])) {
893
                $arrLesson[$row['session_id']]['lessons_total'] = 1;
894
            } else {
895
                $arrLesson[$row['session_id']]['lessons_total'] ++;
896
            }
897
        }
898
899
        /**
900
         *  Exercises
901
         */
902
        $exercises = ExerciseLib::get_all_exercises($course, $sessionId, false, '', $getAllSessions);
903
        $exercises_total = count($exercises);
904
905
        /**
906
         *  Assignments
907
         */
908
        //total
909
        if ($getAllSessions) {
910
            $sql = "SELECT count(w.id) as count
911
                    FROM $workTable w
912
                    LEFT JOIN $workTableAssignment a
913
                    ON (a.publication_id = w.id AND a.c_id = w.c_id)
914
                    WHERE w.c_id = %s
915
                    AND parent_id = 0
916
                    AND active IN (1, 0)";
917
        } else {
918
            $sql = "SELECT count(w.id) as count
919
                    FROM $workTable w
920
                    LEFT JOIN $workTableAssignment a
921
                    ON (a.publication_id = w.id AND a.c_id = w.c_id)
922
                    WHERE w.c_id = %s
923
                    AND parent_id = 0
924
                    AND active IN (1, 0)
925
                    AND  session_id = %s";
926
        }
927
928
        $sql_query = sprintf($sql, $course['real_id'], $sessionId);
929
        $result = Database::query($sql_query);
930
        $row = Database::fetch_array($result);
931
        $assignments_total = $row['count'];
932
933
        /**
934
         * Wiki
935
         */
936
        if ($getAllSessions) {
937
            $sql = "SELECT count(distinct page_id)  as count FROM $wiki
938
                    WHERE c_id = %s";
939
        } else {
940
            $sql = "SELECT count(distinct page_id)  as count FROM $wiki
941
                    WHERE c_id = %s and session_id = %s";
942
        }
943
        $sql_query = sprintf($sql, $course['real_id'], $sessionId);
944
        $result = Database::query($sql_query);
945
        $row = Database::fetch_array($result);
946
        $wiki_total = $row['count'];
947
948
        /**
949
         * Surveys
950
         */
951
        $survey_user_list = array();
952
        $survey_list = SurveyManager::get_surveys($course['code'], $sessionId);
953
954
        $surveys_total = count($survey_list);
955 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...
956
            $user_list = SurveyManager::get_people_who_filled_survey(
957
                $survey['survey_id'],
958
                false,
959
                $course['real_id']
960
            );
961
            foreach ($user_list as $user_id) {
962
                isset($survey_user_list[$user_id]) ? $survey_user_list[$user_id] ++ : $survey_user_list[$user_id] = 1;
963
            }
964
        }
965
966
        /**
967
         * Forums
968
         */
969
        $forums_total = CourseManager::getCountForum(
970
            $course['real_id'],
971
            $sessionId,
972
            $getAllSessions
973
        );
974
975
        //process table info
976
        foreach ($users as $user) {
977
            //Course description
978
            $sql = "SELECT count(*) as count
979
                    FROM $table_stats_access
980
                    WHERE access_tool = 'course_description'
981
                    AND c_id = '%s'
982
                    AND access_session_id = %s
983
                    AND access_user_id = %s ";
984
            $sql_query = sprintf($sql, $course['real_id'], $user['id_session'], $user['user_id']);
985
986
            $result = Database::query($sql_query);
987
            $row = Database::fetch_array($result);
988
            $course_description_progress = ($row['count'] > 0) ? 100 : 0;
989
990
            if (!empty($arrLesson[$user['id_session']]['lessons_total'])) {
991
                $lessons_total = $arrLesson[$user['id_session']]['lessons_total'];
992
            } else {
993
                $lessons_total = !empty($arrLesson[0]['lessons_total']) ? $arrLesson[0]['lessons_total'] : 0;
994
            }
995
996
            //Lessons
997
            //TODO: Lessons done and left is calculated by progress per item in lesson, maybe we should calculate it only per completed lesson?
998
            $lessons_progress = Tracking::get_avg_student_progress(
999
                $user['user_id'],
1000
                $course['code'],
1001
                array(),
1002
                $user['id_session']
1003
            );
1004
            $lessons_done = ($lessons_progress * $lessons_total) / 100;
1005
            $lessons_left = $lessons_total - $lessons_done;
1006
1007
            //Exercises
1008
            $exercises_progress = str_replace('%', '', Tracking::get_exercise_student_progress($exercises, $user['user_id'], $course['real_id'], $user['id_session']));
1009
            $exercises_done = round(($exercises_progress * $exercises_total) / 100);
1010
            $exercises_left = $exercises_total - $exercises_done;
1011
1012
            //Assignments
1013
            $assignments_done = Tracking::count_student_assignments($user['user_id'], $course['code'], $user['id_session']);
1014
            $assignments_left = $assignments_total - $assignments_done;
1015
            if (!empty($assignments_total)) {
1016
                $assignments_progress = round((( $assignments_done * 100 ) / $assignments_total), 2);
1017
            } else {
1018
                $assignments_progress = 0;
1019
            }
1020
1021
            //Wiki
1022
            //total revisions per user
1023
            $sql = "SELECT count(*) as count
1024
                    FROM $wiki
1025
                    WHERE c_id = %s and session_id = %s and user_id = %s";
1026
            $sql_query = sprintf($sql, $course['real_id'], $user['id_session'], $user['user_id']);
1027
            $result = Database::query($sql_query);
1028
            $row = Database::fetch_array($result);
1029
            $wiki_revisions = $row['count'];
1030
            //count visited wiki pages
1031
            $sql = "SELECT count(distinct default_value) as count
1032
                    FROM $table_stats_default
1033
                    WHERE
1034
                        default_user_id = %s AND
1035
                        default_event_type = 'wiki_page_view' AND
1036
                        default_value_type = 'wiki_page_id' AND
1037
                        c_id = %s
1038
                    ";
1039
            $sql_query = sprintf($sql, $user['user_id'], $course['real_id']);
1040
            $result = Database::query($sql_query);
1041
            $row = Database::fetch_array($result);
1042
1043
            $wiki_read = $row['count'];
1044
            $wiki_unread = $wiki_total - $wiki_read;
1045
            if (!empty($wiki_total)) {
1046
                $wiki_progress = round((( $wiki_read * 100 ) / $wiki_total), 2);
1047
            } else {
1048
                $wiki_progress = 0;
1049
            }
1050
1051
            //Surveys
1052
            $surveys_done = (isset($survey_user_list[$user['user_id']]) ? $survey_user_list[$user['user_id']] : 0);
1053
            $surveys_left = $surveys_total - $surveys_done;
1054
            if (!empty($surveys_total)) {
1055
                $surveys_progress = round((( $surveys_done * 100 ) / $surveys_total), 2);
1056
            } else {
1057
                $surveys_progress = 0;
1058
            }
1059
1060
            //Forums
1061
            $forums_done = CourseManager::getCountForumPerUser(
1062
                $user['user_id'],
1063
                $course['real_id'],
1064
                $user['id_session']
1065
            );
1066
            $forums_left = $forums_total - $forums_done;
1067
            if (!empty($forums_total)) {
1068
                $forums_progress = round((( $forums_done * 100 ) / $forums_total), 2);
1069
            } else {
1070
                $forums_progress = 0;
1071
            }
1072
1073
            //Overall Total
1074
            $overall_total = ($course_description_progress + $exercises_progress + $forums_progress + $assignments_progress + $wiki_progress + $surveys_progress) / 6;
1075
1076
            $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>';
1077
            $linkForum = '<a href="' . api_get_path(WEB_CODE_PATH) . 'forum/index.php?cidReq=' . $course['code'] . '&id_session=' . $user['id_session'] . '"> %s </a>';
1078
            $linkWork = '<a href="' . api_get_path(WEB_CODE_PATH) . 'work/work.php?cidReq=' . $course['code'] . '&id_session=' . $user['id_session'] . '"> %s </a>';
1079
            $linkWiki = '<a href="' . api_get_path(WEB_CODE_PATH) . 'wiki/index.php?cidReq=' . $course['code'] . '&session_id=' . $user['id_session'] . '&action=statistics"> %s </a>';
1080
            $linkSurvey = '<a href="' . api_get_path(WEB_CODE_PATH) . 'survey/survey_list.php?cidReq=' . $course['code'] . '&id_session=' . $user['id_session'] . '"> %s </a>';
1081
1082
            $table[] = array(
1083
                'lastname' => $user[1],
1084
                'firstname' => $user[2],
1085
                'username' => $user[3],
1086
                #'profile'   => '',
1087
                'total' => round($overall_total, 2) . '%',
1088
                'courses' => sprintf($link, $course_description_progress . '%'),
1089
                'lessons' => sprintf($link, $lessons_progress . '%'),
1090
                'exercises' => sprintf($link, $exercises_progress . '%'),
1091
                'forums' => sprintf($link, $forums_progress . '%'),
1092
                'homeworks' => sprintf($link, $assignments_progress . '%'),
1093
                'wikis' => sprintf($link, $wiki_progress . '%'),
1094
                'surveys' => sprintf($link, $surveys_progress . '%'),
1095
                //course description
1096
                'course_description_progress' => $course_description_progress . '%',
1097
                //lessons
1098
                'lessons_total' => sprintf($link, $lessons_total),
1099
                'lessons_done' => sprintf($link, $lessons_done),
1100
                'lessons_left' => sprintf($link, $lessons_left),
1101
                'lessons_progress' => sprintf($link, $lessons_progress . '%'),
1102
                //exercises
1103
                'exercises_total' => sprintf($link, $exercises_total),
1104
                'exercises_done' => sprintf($link, $exercises_done),
1105
                'exercises_left' => sprintf($link, $exercises_left),
1106
                'exercises_progress' => sprintf($link, $exercises_progress . '%'),
1107
                //forums
1108
                'forums_total' => sprintf($linkForum, $forums_total),
1109
                'forums_done' => sprintf($linkForum, $forums_done),
1110
                'forums_left' => sprintf($linkForum, $forums_left),
1111
                'forums_progress' => sprintf($linkForum, $forums_progress . '%'),
1112
                //assignments
1113
                'assignments_total' => sprintf($linkWork, $assignments_total),
1114
                'assignments_done' => sprintf($linkWork, $assignments_done),
1115
                'assignments_left' => sprintf($linkWork, $assignments_left),
1116
                'assignments_progress' => sprintf($linkWork, $assignments_progress . '%'),
1117
                //wiki
1118
                'wiki_total' => sprintf($linkWiki, $wiki_total),
1119
                'wiki_revisions' => sprintf($linkWiki, $wiki_revisions),
1120
                'wiki_read' => sprintf($linkWiki, $wiki_read),
1121
                'wiki_unread' => sprintf($linkWiki, $wiki_unread),
1122
                'wiki_progress' => sprintf($linkWiki, $wiki_progress . '%'),
1123
                //survey
1124
                'surveys_total' => sprintf($linkSurvey, $surveys_total),
1125
                'surveys_done' => sprintf($linkSurvey, $surveys_done),
1126
                'surveys_left' => sprintf($linkSurvey, $surveys_left),
1127
                'surveys_progress' => sprintf($linkSurvey, $surveys_progress . '%'),
1128
            );
1129
        }
1130
1131
        return $table;
1132
    }
1133
1134
    /**
1135
     * @return int
1136
     */
1137
    public static function get_number_of_tracking_access_overview()
1138
    {
1139
        // database table definition
1140
        $track_e_course_access = Database :: get_main_table(TABLE_STATISTIC_TRACK_E_COURSE_ACCESS);
1141
1142
        return Database::count_rows($track_e_course_access);
0 ignored issues
show
Deprecated Code introduced by
The method Database::count_rows() has been deprecated.

This method has been deprecated.

Loading history...
1143
    }
1144
1145
    /**
1146
     * Get the ip, total of clicks, login date and time logged in for all user, in one session
1147
     * @todo track_e_course_access table should have ip so we dont have to look for it in track_e_login
1148
     *
1149
     * @author César Perales <[email protected]>, Beeznest Team
1150
     * @version 1.9.6
1151
     */
1152
    public static function get_user_data_access_tracking_overview(
1153
        $sessionId,
1154
        $courseId,
1155
        $studentId = 0,
1156
        $profile = '',
1157
        $date_from = '',
1158
        $date_to = '',
1159
        $options
1160
    ) {
1161
        //escaping variables
1162
        $sessionId = intval($sessionId);
1163
        $courseId = intval($courseId);
1164
        $studentId = intval($studentId);
1165
        $profile = intval($profile);
1166
        $date_from = Database::escape_string($date_from);
1167
        $date_to = Database::escape_string($date_to);
1168
1169
        // database table definition
1170
        $user = Database :: get_main_table(TABLE_MAIN_USER);
1171
        $course = Database :: get_main_table(TABLE_MAIN_COURSE);
1172
        $track_e_login = Database :: get_main_table(TABLE_STATISTIC_TRACK_E_LOGIN);
1173
        $track_e_course_access = Database :: get_main_table(TABLE_STATISTIC_TRACK_E_COURSE_ACCESS);
1174
        $sessionTable = Database :: get_main_table(TABLE_MAIN_SESSION);
1175
1176
        global $export_csv;
1177
        if ($export_csv) {
1178
            $is_western_name_order = api_is_western_name_order(PERSON_NAME_DATA_EXPORT);
1179
        } else {
1180
            $is_western_name_order = api_is_western_name_order();
1181
        }
1182
1183
        $where = null;
1184
        if (isset($sessionId) && !empty($sessionId)) {
1185
            $where = sprintf(" WHERE a.session_id = %d", $sessionId);
1186
        }
1187
        if (isset($courseId) && !empty($courseId)) {
1188
            $where .= sprintf(" AND c.id = %d", $courseId);
1189
        }
1190
        if (isset($studentId) && !empty($studentId)) {
1191
            $where .= sprintf(" AND u.user_id = %d", $studentId);
1192
        }
1193
        if (isset($profile) && !empty($profile)) {
1194
            $where .= sprintf(" AND u.status = %d", $profile);
1195
        }
1196
        if (!empty($date_to) && !empty($date_from)) {
1197
            $where .= sprintf(
1198
                " AND a.login_course_date >= '%s 00:00:00'
1199
                 AND a.login_course_date <= '%s 23:59:59'",
1200
                $date_from,
1201
                $date_to
1202
            );
1203
        }
1204
1205
        $limit = null;
1206
        if (!empty($options['limit'])) {
1207
            $limit = " LIMIT " . $options['limit'];
1208
        }
1209
1210
        if (!empty($options['where'])) {
1211
            $where .= ' '.$options['where'];
1212
        }
1213
1214
        $order = null;
1215
        if (!empty($options['order'])) {
1216
            $order = " ORDER BY " . $options['order'];
1217
        }
1218
1219
        //TODO add course name
1220
        $sql = "SELECT
1221
                a.login_course_date ,
1222
                u.username ,
1223
                " . ($is_western_name_order ? "
1224
                    u.firstname,
1225
                    u.lastname,
1226
                    " : "
1227
                    u.lastname,
1228
                    u.firstname,
1229
                ") . "
1230
                a.logout_course_date,
1231
                a.counter,
1232
                c.title,
1233
                c.code,
1234
                u.user_id,
1235
                a.session_id
1236
            FROM $track_e_course_access a
1237
            INNER JOIN $user u ON a.user_id = u.user_id
1238
            INNER JOIN $course c ON a.c_id = c.id
1239
            $where $order $limit";
1240
        $result = Database::query(sprintf($sql, $sessionId, $courseId));
1241
1242
        $data = array();
1243
        while ($user = Database::fetch_assoc($result)) {
1244
            $data[] = $user;
1245
        }
1246
1247
        //foreach
1248
        foreach ($data as $key => $info) {
1249
1250
            $sql = "SELECT
1251
                    name
1252
                    FROM $sessionTable
1253
                    WHERE
1254
                    id = {$info['session_id']}";
1255
            $result = Database::query($sql);
1256
            $session = Database::fetch_assoc($result);
1257
1258
            //We are not using this becaouse the range its to small and no other date match the condition of this function
1259
            //$clicks = Tracking::get_total_clicks($info['user_id'], $courseId, $sessionId, $info['login_course_date'], $info['logout_course_date']);
1260
            #building array to display
1261
            $return[] = array(
1262
                'user_id' => $info['user_id'],
1263
                'logindate' => $info['login_course_date'],
1264
                'username' => $info['username'],
1265
                'firstname' => $info['firstname'],
1266
                'lastname' => $info['lastname'],
1267
                'clicks' => $info['counter'], //+ $clicks[$info['user_id']],
1268
                'ip' => '',
1269
                'timeLoggedIn' => gmdate("H:i:s", strtotime($info['logout_course_date']) - strtotime($info['login_course_date'])),
1270
                'session' => $session['name']
1271
            );
1272
        }
1273
1274
        foreach ($return as $key => $info) {
1275
            //Search for ip, we do less querys if we iterate the final array
1276
            $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
1277
            $result = Database::query($sql);
1278
            $ip = Database::fetch_assoc($result);
1279
            //if no ip founded, we search the closest higher ip
1280
            if (empty($ip['user_ip'])) {
1281
                $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
1282
                $result = Database::query($sql);
1283
                $ip = Database::fetch_assoc($result);
1284
            }
1285
            #add ip to final array
1286
            $return[$key]['ip'] = $ip['user_ip'];
1287
        }
1288
        return $return;
1289
    }
1290
1291
    /**
1292
     * Creates a new course code based in given code
1293
     *
1294
     * @param string	$session_name
1295
     * <code>
1296
     * $wanted_code = 'curse' if there are in the DB codes like curse1 curse2 the function will return: course3
1297
     * if the course code doest not exist in the DB the same course code will be returned
1298
     * </code>
1299
     * @return string	wanted unused code
1300
     */
1301 View Code Duplication
    public static function generateNextSessionName($session_name)
1302
    {
1303
        $session_name_ok = !self::session_name_exists($session_name);
1304
        if (!$session_name_ok) {
1305
            $table = Database::get_main_table(TABLE_MAIN_SESSION);
1306
            $session_name = Database::escape_string($session_name);
1307
            $sql = "SELECT count(*) as count FROM $table
1308
                    WHERE name LIKE '$session_name%'";
1309
            $result = Database::query($sql);
1310
            if (Database::num_rows($result) > 0) {
1311
                $row = Database::fetch_array($result);
1312
                $count = $row['count'] + 1;
1313
                $session_name = $session_name . '_' . $count;
1314
                $result = self::session_name_exists($session_name);
1315
                if (!$result) {
1316
                    return $session_name;
1317
                }
1318
            }
1319
            return false;
1320
        }
1321
        return $session_name;
1322
    }
1323
1324
    /**
1325
     * Edit a session
1326
     * @author Carlos Vargas from existing code
1327
     * @param integer   $id Session primary key
1328
     * @param string    $name
1329
     * @param string    $startDate
1330
     * @param string    $endDate
1331
     * @param string    $displayStartDate
1332
     * @param string    $displayEndDate
1333
     * @param string    $coachStartDate
1334
     * @param string    $coachEndDate
1335
     * @param integer   $coachId
1336
     * @param integer   $sessionCategoryId
1337
     * @param int       $visibility
1338
     * @param string    $description
1339
     * @param bool      $showDescription
1340
     * @param int       $duration
1341
     * @param array     $extraFields
1342
     * @param int       $sessionAdminId
1343
     * @param boolean $sendSubscriptionNotification Optional.
1344
     *          Whether send a mail notification to users being subscribed
1345
     * @return mixed
1346
     */
1347
    public static function edit_session(
1348
        $id,
1349
        $name,
1350
        $startDate,
1351
        $endDate,
1352
        $displayStartDate,
1353
        $displayEndDate,
1354
        $coachStartDate,
1355
        $coachEndDate,
1356
        $coachId,
1357
        $sessionCategoryId,
1358
        $visibility,
1359
        $description = null,
1360
        $showDescription = 0,
1361
        $duration = null,
1362
        $extraFields = array(),
1363
        $sessionAdminId = 0,
1364
        $sendSubscriptionNotification = false
1365
    ) {
1366
        $name = trim(stripslashes($name));
1367
        $coachId = intval($coachId);
1368
        $sessionCategoryId = intval($sessionCategoryId);
1369
        $visibility = intval($visibility);
1370
        $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
1371
1372
        if (empty($name)) {
1373
            Display::return_message(get_lang('SessionNameIsRequired'), 'warning');
1374
1375
            return false;
1376
        } elseif (empty($coachId)) {
1377
            Display::return_message(get_lang('CoachIsRequired'), 'warning');
1378
1379
            return false;
1380
        } elseif (!empty($startDate) && !api_is_valid_date($startDate, 'Y-m-d H:i')) {
1381
            Display::return_message(get_lang('InvalidStartDate'), 'warning');
1382
1383
            return false;
1384
        } elseif (!empty($endDate) && !api_is_valid_date($endDate, 'Y-m-d H:i')) {
1385
            Display::return_message(get_lang('InvalidEndDate'), 'warning');
1386
1387
            return false;
1388
        } elseif (!empty($startDate) && !empty($endDate) && $startDate >= $endDate) {
1389
            Display::return_message(get_lang('StartDateShouldBeBeforeEndDate'), 'warning');
1390
1391
            return false;
1392
        } else {
1393
            $sql = "SELECT id FROM $tbl_session WHERE name='" . Database::escape_string($name) . "'";
1394
            $rs = Database::query($sql);
1395
            $exists = false;
1396
            while ($row = Database::fetch_array($rs)) {
1397
                if ($row['id'] != $id) {
1398
                    $exists = true;
1399
                }
1400
            }
1401
1402
            if ($exists) {
1403
                Display::return_message(get_lang('SessionNameAlreadyExists'), 'warning');
1404
1405
                return false;
1406
            } else {
1407
                $values = [
1408
                    'name' => $name,
1409
                    'duration' => $duration,
1410
                    'id_coach' => $coachId,
1411
                    'description'=> $description,
1412
                    'show_description' => intval($showDescription),
1413
                    'visibility' => $visibility,
1414
                    'send_subscription_notification' => $sendSubscriptionNotification
1415
                ];
1416
1417
                if (!empty($sessionAdminId)) {
1418
                    $values['session_admin_id'] = $sessionAdminId;
1419
                }
1420
1421
                if (!empty($startDate)) {
1422
                    $values['access_start_date'] = api_get_utc_datetime($startDate);
1423
                }
1424
1425
                if (!empty($endDate)) {
1426
                    $values['access_end_date'] = api_get_utc_datetime($endDate);
1427
                }
1428
1429
                if (!empty($displayStartDate)) {
1430
                    $values['display_start_date'] = api_get_utc_datetime($displayStartDate);
1431
                }
1432
1433
                if (!empty($displayEndDate)) {
1434
                    $values['display_end_date'] = api_get_utc_datetime($displayEndDate);
1435
                }
1436
1437
                if (!empty($coachStartDate)) {
1438
                    $values['coach_access_start_date'] = api_get_utc_datetime($coachStartDate);
1439
                }
1440
                if (!empty($coachEndDate)) {
1441
                    $values['coach_access_end_date'] = api_get_utc_datetime($coachEndDate);
1442
                }
1443
1444
                if (!empty($sessionCategoryId)) {
1445
                    $values['session_category_id'] = $sessionCategoryId;
1446
                }
1447
1448
                Database::update($tbl_session, $values, array(
1449
                    'id = ?' => $id
1450
                ));
1451
1452
                if (!empty($extraFields)) {
1453
                    $extraFields['item_id'] = $id;
1454
                    $sessionFieldValue = new ExtraFieldValue('session');
1455
                    $sessionFieldValue->saveFieldValues($extraFields);
1456
                }
1457
1458
                return $id;
1459
            }
1460
        }
1461
    }
1462
1463
    /**
1464
     * Delete session
1465
     * @author Carlos Vargas  from existing code
1466
     * @param	array	$id_checked an array to delete sessions
1467
     * @param   boolean  $from_ws optional, true if the function is called
1468
     * by a webservice, false otherwise.
1469
     * @return	void	Nothing, or false on error
1470
     * */
1471
    public static function delete($id_checked, $from_ws = false)
1472
    {
1473
        $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
1474
        $tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
1475
        $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
1476
        $tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
1477
        $tbl_url_session = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
1478
        $tbl_item_properties = Database::get_course_table(TABLE_ITEM_PROPERTY);
1479
1480
        $userId = api_get_user_id();
1481
1482
        if (is_array($id_checked)) {
1483
            foreach ($id_checked as $sessionId) {
1484
                self::delete($sessionId);
1485
            }
1486
        } else {
1487
            $id_checked = intval($id_checked);
1488
        }
1489
1490
        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 1471 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...
1491
            $sql = 'SELECT session_admin_id FROM ' . $tbl_session. '
1492
                    WHERE id IN (' . $id_checked.')';
1493
            $rs = Database::query($sql);
1494
            if (Database::result($rs, 0, 0) != $userId) {
1495
                api_not_allowed(true);
1496
            }
1497
        }
1498
1499
        // Delete documents inside a session
1500
        $courses = SessionManager::getCoursesInSession($id_checked);
1501
        foreach ($courses as $courseId) {
1502
            $courseInfo = api_get_course_info_by_id($courseId);
1503
            DocumentManager::deleteDocumentsFromSession($courseInfo, $id_checked);
0 ignored issues
show
Bug introduced by
It seems like $id_checked defined by parameter $id_checked on line 1471 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...
1504
        }
1505
1506
        Database::query("DELETE FROM $tbl_session_rel_course WHERE session_id IN($id_checked)");
1507
        Database::query("DELETE FROM $tbl_session_rel_course_rel_user WHERE session_id IN($id_checked)");
1508
        Database::query("DELETE FROM $tbl_session_rel_user WHERE session_id IN($id_checked)");
1509
        Database::query("DELETE FROM $tbl_item_properties WHERE session_id IN ($id_checked)");
1510
        Database::query("DELETE FROM $tbl_url_session WHERE session_id IN($id_checked)");
1511
1512
        Database::query("DELETE FROM $tbl_session WHERE id IN ($id_checked)");
1513
1514
        $extraFieldValue = new ExtraFieldValue('session');
1515
        $extraFieldValue->deleteValuesByItem($id_checked);
0 ignored issues
show
Bug introduced by
It seems like $id_checked defined by parameter $id_checked on line 1471 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...
1516
1517
        /** @var \Chamilo\CoreBundle\Entity\Repository\SequenceRepository $repo */
1518
        $repo = Database::getManager()->getRepository('ChamiloCoreBundle:SequenceResource');
1519
        $repo->deleteResource(
1520
            $id_checked,
0 ignored issues
show
Bug introduced by
It seems like $id_checked defined by parameter $id_checked on line 1471 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...
1521
            \Chamilo\CoreBundle\Entity\SequenceResource::SESSION_TYPE
1522
        );
1523
1524
        // Add event to system log
1525
        Event::addEvent(
1526
            LOG_SESSION_DELETE,
1527
            LOG_SESSION_ID,
1528
            $id_checked,
1529
            api_get_utc_datetime(),
1530
            $userId
1531
        );
1532
    }
1533
1534
    /**
1535
     * @param int $id_promotion
1536
     *
1537
     * @return bool
1538
     */
1539 View Code Duplication
    public static function clear_session_ref_promotion($id_promotion)
1540
    {
1541
        $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
1542
        $id_promotion = intval($id_promotion);
1543
        $sql = "UPDATE $tbl_session SET promotion_id=0
1544
                WHERE promotion_id = $id_promotion";
1545
        if (Database::query($sql)) {
1546
            return true;
1547
        } else {
1548
            return false;
1549
        }
1550
    }
1551
1552
    /**
1553
     * Subscribes students to the given session and optionally (default) unsubscribes previous users
1554
     *
1555
     * @author Carlos Vargas from existing code
1556
     * @author Julio Montoya. Cleaning code.
1557
     * @param int $id_session
1558
     * @param array $user_list
1559
     * @param int $session_visibility
1560
     * @param bool $empty_users
1561
     * @return bool
1562
     */
1563
    public static function suscribe_users_to_session(
1564
        $id_session,
1565
        $user_list,
1566
        $session_visibility = SESSION_VISIBLE_READ_ONLY,
1567
        $empty_users = true
1568
    ) {
1569
        if ($id_session != strval(intval($id_session))) {
1570
            return false;
1571
        }
1572
1573
        foreach ($user_list as $intUser) {
1574
            if ($intUser != strval(intval($intUser))) {
1575
                return false;
1576
            }
1577
        }
1578
1579
        $tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
1580
        $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
1581
        $tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
1582
        $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
1583
1584
        $entityManager = Database::getManager();
1585
        $session = $entityManager->find('ChamiloCoreBundle:Session', $id_session);
1586
1587
        // from function parameter
1588
        if (empty($session_visibility)) {
1589
            $session_visibility = $session->getVisibility();
1590
            //default status loaded if empty
1591
            if (empty($session_visibility))
1592
                $session_visibility = SESSION_VISIBLE_READ_ONLY; // by default readonly 1
1593
        } else {
1594
            if (!in_array($session_visibility, array(SESSION_VISIBLE_READ_ONLY, SESSION_VISIBLE, SESSION_INVISIBLE))) {
1595
                $session_visibility = SESSION_VISIBLE_READ_ONLY;
1596
            }
1597
        }
1598
1599
        $sql = "SELECT user_id FROM $tbl_session_rel_course_rel_user
1600
                WHERE session_id = $id_session AND status = 0";
1601
        $result = Database::query($sql);
1602
        $existingUsers = array();
1603
        while ($row = Database::fetch_array($result)) {
1604
            $existingUsers[] = $row['user_id'];
1605
        }
1606
1607
        $sql = "SELECT c_id FROM $tbl_session_rel_course
1608
                WHERE session_id = $id_session";
1609
        $result = Database::query($sql);
1610
        $course_list = array();
1611
        while ($row = Database::fetch_array($result)) {
1612
            $course_list[] = $row['c_id'];
1613
        }
1614
1615
        if (
1616
            $session->getSendSubscriptionNotification() &&
1617
            is_array($user_list)
1618
        ) {
1619
            // Sending emails only
1620
            foreach ($user_list as $user_id) {
1621
                if (in_array($user_id, $existingUsers)) {
1622
                    continue;
1623
                }
1624
1625
                $tplSubject = new Template(null, false, false, false, false, false);
1626
                $layoutSubject = $tplSubject->get_template(
1627
                    'mail/subject_subscription_to_session_confirmation.tpl'
1628
                );
1629
                $subject = $tplSubject->fetch($layoutSubject);
1630
1631
                $user_info = api_get_user_info($user_id);
1632
1633
                $tplContent = new Template(null, false, false, false, false, false);
1634
                // Variables for default template
1635
                $tplContent->assign(
1636
                    'complete_name',
1637
                    stripslashes($user_info['complete_name'])
1638
                );
1639
                $tplContent->assign('session_name', $session->getName());
1640
                $tplContent->assign(
1641
                    'session_coach',
1642
                    $session->getGeneralCoach()->getCompleteName()
1643
                );
1644
                $layoutContent = $tplContent->get_template(
1645
                    'mail/content_subscription_to_session_confirmation.tpl'
1646
                );
1647
                $content = $tplContent->fetch($layoutContent);
1648
1649
                api_mail_html(
1650
                    $user_info['complete_name'],
1651
                    $user_info['mail'],
1652
                    $subject,
1653
                    $content,
1654
                    api_get_person_name(
1655
                        api_get_setting('administratorName'),
1656
                        api_get_setting('administratorSurname')
1657
                    ),
1658
                    api_get_setting('emailAdministrator')
1659
                );
1660
            }
1661
        }
1662
1663
        foreach ($course_list as $courseId) {
1664
            // for each course in the session
1665
            $nbr_users = 0;
1666
            $courseId = intval($courseId);
1667
1668
            $sql = "SELECT DISTINCT user_id
1669
                    FROM $tbl_session_rel_course_rel_user
1670
                    WHERE
1671
                        session_id = $id_session AND
1672
                        c_id = $courseId AND
1673
                        status = 0
1674
                    ";
1675
            $result = Database::query($sql);
1676
            $existingUsers = array();
1677
            while ($row = Database::fetch_array($result)) {
1678
                $existingUsers[] = $row['user_id'];
1679
            }
1680
1681
            // Delete existing users
1682 View Code Duplication
            if ($empty_users) {
1683
                foreach ($existingUsers as $existing_user) {
1684
                    if (!in_array($existing_user, $user_list)) {
1685
                        $sql = "DELETE FROM $tbl_session_rel_course_rel_user
1686
                                WHERE
1687
                                    session_id = $id_session AND
1688
                                    c_id = $courseId AND
1689
                                    user_id = $existing_user AND
1690
                                    status = 0 ";
1691
                        $result = Database::query($sql);
1692
1693
                        Event::addEvent(
1694
                            LOG_SESSION_DELETE_USER_COURSE,
1695
                            LOG_USER_ID,
1696
                            $existing_user,
1697
                            api_get_utc_datetime(),
1698
                            api_get_user_id(),
1699
                            $courseId,
1700
                            $id_session
1701
                        );
1702
1703
                        if (Database::affected_rows($result)) {
1704
                            $nbr_users--;
1705
                        }
1706
                    }
1707
                }
1708
            }
1709
1710
            // Replace with this new function
1711
            // insert new users into session_rel_course_rel_user and ignore if they already exist
1712
1713
            foreach ($user_list as $enreg_user) {
1714 View Code Duplication
                if (!in_array($enreg_user, $existingUsers)) {
1715
                    $enreg_user = Database::escape_string($enreg_user);
1716
                    $sql = "INSERT IGNORE INTO $tbl_session_rel_course_rel_user (session_id, c_id, user_id, visibility, status)
1717
                            VALUES($id_session, $courseId, $enreg_user, $session_visibility, 0)";
1718
                    $result = Database::query($sql);
1719
1720
                    Event::addEvent(
1721
                        LOG_SESSION_ADD_USER_COURSE,
1722
                        LOG_USER_ID,
1723
                        $enreg_user,
1724
                        api_get_utc_datetime(),
1725
                        api_get_user_id(),
1726
                        $courseId,
1727
                        $id_session
1728
                    );
1729
1730
                    if (Database::affected_rows($result)) {
1731
1732
                        $nbr_users++;
1733
                    }
1734
                }
1735
            }
1736
1737
            // Count users in this session-course relation
1738
            $sql = "SELECT COUNT(user_id) as nbUsers
1739
                    FROM $tbl_session_rel_course_rel_user
1740
                    WHERE session_id = $id_session AND c_id = $courseId AND status<>2";
1741
            $rs = Database::query($sql);
1742
            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...
1743
            // update the session-course relation to add the users total
1744
            $sql = "UPDATE $tbl_session_rel_course SET nbr_users = $nbr_users
1745
                    WHERE session_id = $id_session AND c_id = $courseId";
1746
            Database::query($sql);
1747
        }
1748
1749
        // Delete users from the session
1750
        if ($empty_users === true) {
1751
            $sql = "DELETE FROM $tbl_session_rel_user
1752
                    WHERE session_id = $id_session AND relation_type<>" . SESSION_RELATION_TYPE_RRHH . "";
1753
            Database::query($sql);
1754
        }
1755
1756
        // Insert missing users into session
1757
        $nbr_users = 0;
1758
1759
        foreach ($user_list as $enreg_user) {
1760
            $enreg_user = Database::escape_string($enreg_user);
1761
            $nbr_users++;
1762
            $sql = "INSERT IGNORE INTO $tbl_session_rel_user (relation_type, session_id, user_id, registered_at)
1763
                    VALUES (0, $id_session, $enreg_user, '" . api_get_utc_datetime() . "')";
1764
            Database::query($sql);
1765
        }
1766
1767
        // update number of users in the session
1768
        $nbr_users = count($user_list);
1769
        if ($empty_users) {
1770
            // update number of users in the session
1771
            $sql = "UPDATE $tbl_session SET nbr_users= $nbr_users
1772
                    WHERE id = $id_session ";
1773
            Database::query($sql);
1774
        } else {
1775
            $sql = "UPDATE $tbl_session SET nbr_users = nbr_users + $nbr_users
1776
                    WHERE id = $id_session";
1777
            Database::query($sql);
1778
        }
1779
    }
1780
1781
    /**
1782
     * Returns user list of the current users subscribed in the course-session
1783
     * @param int $sessionId
1784
     * @param array $courseInfo
1785
     * @param int $status
1786
     *
1787
     * @return array
1788
     */
1789
    public static function getUsersByCourseSession(
1790
        $sessionId,
1791
        $courseInfo,
1792
        $status = null
1793
    ) {
1794
        $sessionId = intval($sessionId);
1795
        $courseCode = $courseInfo['code'];
1796
        $courseId = $courseInfo['real_id'];
1797
1798
        if (empty($sessionId) || empty($courseCode)) {
1799
            return array();
1800
        }
1801
1802
        $statusCondition = null;
1803 View Code Duplication
        if (isset($status) && !is_null($status)) {
1804
            $status = intval($status);
1805
            $statusCondition = " AND status = $status";
1806
        }
1807
1808
        $table = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
1809
1810
        $sql = "SELECT DISTINCT user_id
1811
                FROM $table
1812
                WHERE
1813
                    session_id = $sessionId AND
1814
                    c_id = $courseId
1815
                    $statusCondition
1816
                ";
1817
        $result = Database::query($sql);
1818
        $existingUsers = array();
1819
        while ($row = Database::fetch_array($result)) {
1820
            $existingUsers[] = $row['user_id'];
1821
        }
1822
1823
        return $existingUsers;
1824
    }
1825
1826
    /**
1827
     * Remove a list of users from a course-session
1828
     * @param array $userList
1829
     * @param int $sessionId
1830
     * @param array $courseInfo
1831
     * @param int $status
1832
     * @param bool $updateTotal
1833
     * @return bool
1834
     */
1835
    public static function removeUsersFromCourseSession(
1836
        $userList,
1837
        $sessionId,
1838
        $courseInfo,
1839
        $status = null,
1840
        $updateTotal = true
1841
    ) {
1842
        $table = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
1843
        $tableSessionCourse = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
1844
        $sessionId = intval($sessionId);
1845
1846
        if (empty($sessionId) || empty($userList) || empty($courseInfo)) {
1847
            return false;
1848
        }
1849
1850
        is_array($courseInfo) ? $courseId = $courseInfo['real_id'] : $courseId = $courseInfo;
1851
1852
        $statusCondition = null;
1853 View Code Duplication
        if (isset($status) && !is_null($status))  {
1854
            $status = intval($status);
1855
            $statusCondition  = " AND status = $status";
1856
        }
1857
1858
        foreach ($userList as $userId) {
1859
            $userId = intval($userId);
1860
            $sql = "DELETE FROM $table
1861
                    WHERE
1862
                        session_id = $sessionId AND
1863
                        c_id = $courseId AND
1864
                        user_id = $userId
1865
                        $statusCondition
1866
                    ";
1867
            Database::query($sql);
1868
        }
1869
1870
        if ($updateTotal) {
1871
            // Count users in this session-course relation
1872
            $sql = "SELECT COUNT(user_id) as nbUsers
1873
                    FROM $table
1874
                    WHERE
1875
                        session_id = $sessionId AND
1876
                        c_id = $courseId AND
1877
                        status <> 2";
1878
            $result = Database::query($sql);
1879
            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...
1880
1881
            // update the session-course relation to add the users total
1882
            $sql = "UPDATE $tableSessionCourse
1883
                    SET nbr_users = $userCount
1884
                    WHERE
1885
                        session_id = $sessionId AND
1886
                        c_id = $courseId";
1887
            Database::query($sql);
1888
        }
1889
    }
1890
1891
    /**
1892
     * Subscribe a user to an specific course inside a session.
1893
     *
1894
     * @param array $user_list
1895
     * @param int $session_id
1896
     * @param string $course_code
1897
     * @param int $session_visibility
1898
     * @param bool $removeUsersNotInList
1899
     * @return bool
1900
     */
1901
    public static function subscribe_users_to_session_course(
1902
        $user_list,
1903
        $session_id,
1904
        $course_code,
1905
        $session_visibility = SESSION_VISIBLE_READ_ONLY,
1906
        $removeUsersNotInList = false
1907
    ) {
1908
        $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
1909
        $tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
1910
        $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
1911
        $tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
1912
1913
        if (empty($session_id) || empty($course_code)) {
1914
            return false;
1915
        }
1916
1917
        $session_id = intval($session_id);
1918
        $course_code = Database::escape_string($course_code);
1919
        $courseInfo = api_get_course_info($course_code);
1920
        $courseId = $courseInfo['real_id'];
1921
1922
        $session_visibility = intval($session_visibility);
1923
1924
        if ($removeUsersNotInList) {
1925
1926
            $currentUsers = self::getUsersByCourseSession($session_id, $courseInfo, 0);
1927
1928
            if (!empty($user_list)) {
1929
                $userToDelete = array_diff($currentUsers, $user_list);
1930
            } else {
1931
                $userToDelete = $currentUsers;
1932
            }
1933
1934
            if (!empty($userToDelete)) {
1935
                self::removeUsersFromCourseSession(
1936
                    $userToDelete,
1937
                    $session_id,
1938
                    $courseInfo,
1939
                    0,
1940
                    true
1941
                );
1942
            }
1943
        }
1944
1945
        $nbr_users = 0;
1946
        foreach ($user_list as $enreg_user) {
1947
            $enreg_user = intval($enreg_user);
1948
            // Checking if user exists in session - course - user table.
1949
            $sql = "SELECT count(user_id) as count
1950
                    FROM $tbl_session_rel_course_rel_user
1951
                    WHERE
1952
                        session_id = $session_id AND
1953
                        c_id = $courseId and
1954
                        user_id = $enreg_user ";
1955
            $result = Database::query($sql);
1956
            $count = 0;
1957
1958
            if (Database::num_rows($result) > 0) {
1959
                $row = Database::fetch_array($result, 'ASSOC');
1960
                $count = $row['count'];
1961
            }
1962
1963
            if ($count == 0) {
1964
                $sql = "INSERT IGNORE INTO $tbl_session_rel_course_rel_user (session_id, c_id, user_id, visibility)
1965
                        VALUES ($session_id, $courseId, $enreg_user, $session_visibility)";
1966
                $result = Database::query($sql);
1967
                if (Database::affected_rows($result)) {
1968
                    $nbr_users++;
1969
                }
1970
            }
1971
1972
            // Checking if user exists in session - user table.
1973
            $sql = "SELECT count(user_id) as count
1974
                    FROM $tbl_session_rel_user
1975
                    WHERE session_id = $session_id AND user_id = $enreg_user ";
1976
            $result = Database::query($sql);
1977
            $count = 0;
1978
1979
            if (Database::num_rows($result) > 0) {
1980
                $row = Database::fetch_array($result, 'ASSOC');
1981
                $count = $row['count'];
1982
            }
1983
1984 View Code Duplication
            if (empty($count)) {
1985
                // If user is not registered to a session then add it.
1986
                $sql = "INSERT IGNORE INTO $tbl_session_rel_user (session_id, user_id, registered_at)
1987
                        VALUES ($session_id, $enreg_user, '" . api_get_utc_datetime() . "')";
1988
                Database::query($sql);
1989
1990
                $sql = "UPDATE $tbl_session SET nbr_users = nbr_users + 1
1991
                        WHERE id = $session_id ";
1992
                Database::query($sql);
1993
            }
1994
        }
1995
1996
        // count users in this session-course relation
1997
        $sql = "SELECT COUNT(user_id) as nbUsers
1998
                FROM $tbl_session_rel_course_rel_user
1999
                WHERE session_id = $session_id AND c_id = $courseId AND status <> 2";
2000
        $rs = Database::query($sql);
2001
        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...
2002
        // update the session-course relation to add the users total
2003
        $sql = "UPDATE $tbl_session_rel_course
2004
                SET nbr_users = $nbr_users
2005
                WHERE session_id = $session_id AND c_id = $courseId";
2006
        Database::query($sql);
2007
    }
2008
2009
    /**
2010
     * Unsubscribe user from session
2011
     *
2012
     * @param int Session id
2013
     * @param int User id
2014
     * @return bool True in case of success, false in case of error
2015
     */
2016
    public static function unsubscribe_user_from_session($session_id, $user_id)
2017
    {
2018
        $session_id = (int) $session_id;
2019
        $user_id = (int) $user_id;
2020
2021
        $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
2022
        $tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
2023
        $tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
2024
        $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
2025
2026
        $delete_sql = "DELETE FROM $tbl_session_rel_user
2027
		               WHERE
2028
                            session_id = $session_id AND
2029
		                    user_id = $user_id AND
2030
		                    relation_type <> " . SESSION_RELATION_TYPE_RRHH . "";
2031
        $result = Database::query($delete_sql);
2032
        $return = Database::affected_rows($result);
2033
2034
        // Update number of users
2035
        $sql = "UPDATE $tbl_session
2036
                SET nbr_users = nbr_users - $return
2037
                WHERE id = $session_id ";
2038
        Database::query($sql);
2039
2040
        // Get the list of courses related to this session
2041
        $course_list = SessionManager::get_course_list_by_session_id($session_id);
2042
2043
        if (!empty($course_list)) {
2044
            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...
2045
                $courseId = $course['id'];
2046
                // Delete user from course
2047
                $sql = "DELETE FROM $tbl_session_rel_course_rel_user
2048
                        WHERE session_id = $session_id AND c_id = $courseId AND user_id = $user_id";
2049
                $result = Database::query($sql);
2050
2051
                Event::addEvent(
2052
                    LOG_SESSION_DELETE_USER_COURSE,
2053
                    LOG_USER_ID,
2054
                    $user_id,
2055
                    api_get_utc_datetime(),
2056
                    api_get_user_id(),
2057
                    $courseId,
2058
                    $session_id
2059
                );
2060
2061
                if (Database::affected_rows($result)) {
2062
                    // Update number of users in this relation
2063
                    $sql = "UPDATE $tbl_session_rel_course SET nbr_users = nbr_users - 1
2064
                            WHERE session_id = $session_id AND c_id = $courseId";
2065
                    Database::query($sql);
2066
                }
2067
            }
2068
        }
2069
2070
        return true;
2071
    }
2072
2073
    /**
2074
     * Subscribes courses to the given session and optionally (default)
2075
     * unsubscribes previous users
2076
     * @author Carlos Vargas from existing code
2077
     * @param	int		$sessionId
2078
     * @param	array	$courseList List of courses int ids
2079
     * @param	bool	$removeExistingCoursesWithUsers Whether to unsubscribe
2080
     * existing courses and users (true, default) or not (false)
2081
     * @param $copyEvaluation from base course to session course
2082
     * @return	void	Nothing, or false on error
2083
     * */
2084
    public static function add_courses_to_session(
2085
        $sessionId,
2086
        $courseList,
2087
        $removeExistingCoursesWithUsers = true,
2088
        $copyEvaluation = false
2089
    ) {
2090
        $sessionId = intval($sessionId);
2091
2092
        if (empty($sessionId) || empty($courseList)) {
2093
            return false;
2094
        }
2095
2096
        $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
2097
        $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
2098
        $tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
2099
        $tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
2100
2101
        // Get list of courses subscribed to this session
2102
        $sql = "SELECT c_id
2103
                FROM $tbl_session_rel_course
2104
                WHERE session_id = $sessionId";
2105
        $rs = Database::query($sql);
2106
        $existingCourses = Database::store_result($rs);
2107
        $nbr_courses = count($existingCourses);
2108
2109
        // Get list of users subscribed to this session
2110
        $sql = "SELECT user_id
2111
                FROM $tbl_session_rel_user
2112
                WHERE
2113
                    session_id = $sessionId AND
2114
                    relation_type<>" . SESSION_RELATION_TYPE_RRHH;
2115
        $result = Database::query($sql);
2116
        $user_list = Database::store_result($result);
2117
2118
        // Remove existing courses from the session.
2119
        if ($removeExistingCoursesWithUsers === true && !empty($existingCourses)) {
2120
2121
            foreach ($existingCourses as $existingCourse) {
2122
                if (!in_array($existingCourse['c_id'], $courseList)) {
2123
2124
                    $sql = "DELETE FROM $tbl_session_rel_course
2125
                            WHERE
2126
                                c_id = " . $existingCourse['c_id'] . " AND
2127
                                session_id = $sessionId";
2128
                    Database::query($sql);
2129
2130
                    $sql = "DELETE FROM $tbl_session_rel_course_rel_user
2131
                            WHERE
2132
                                c_id = ".$existingCourse['c_id']." AND
2133
                                session_id = $sessionId";
2134
                    Database::query($sql);
2135
2136
                    Event::addEvent(
2137
                        LOG_SESSION_DELETE_COURSE,
2138
                        LOG_COURSE_ID,
2139
                        $existingCourse['c_id'],
2140
                        api_get_utc_datetime(),
2141
                        api_get_user_id(),
2142
                        $existingCourse['c_id'],
2143
                        $sessionId
2144
                    );
2145
2146
                    CourseManager::remove_course_ranking(
2147
                        $existingCourse['c_id'],
2148
                        $sessionId
2149
                    );
2150
2151
                    $nbr_courses--;
2152
                }
2153
            }
2154
        }
2155
2156
        // Pass through the courses list we want to add to the session
2157
        foreach ($courseList as $courseId) {
2158
            $courseInfo = api_get_course_info_by_id($courseId);
2159
2160
            // If course doesn't exists continue!
2161
            if (empty($courseInfo)) {
2162
                continue;
2163
            }
2164
2165
            $exists = false;
2166
            // check if the course we want to add is already subscribed
2167
            foreach ($existingCourses as $existingCourse) {
2168
                if ($courseId == $existingCourse['c_id']) {
2169
                    $exists = true;
2170
                }
2171
            }
2172
2173
            if (!$exists) {
2174
                // Copy gradebook categories and links (from base course)
2175
                // to the new course session
2176
                if ($copyEvaluation) {
2177
                    $cats = Category::load(null, null, $courseInfo['code']);
2178
                    if (!empty($cats)) {
2179
                        $categoryIdList = [];
2180
                        /** @var Category $cat */
2181
                        foreach ($cats as $cat) {
2182
                            $categoryIdList[$cat->get_id()] = $cat->get_id();
2183
                        }
2184
                        $newCategoryIdList = [];
2185
                        foreach ($cats as $cat) {
2186
                            $links = $cat->get_links(null, false, $courseInfo['code'], 0);
2187
2188
                            $cat->set_session_id($sessionId);
2189
                            $oldCategoryId= $cat->get_id();
2190
                            $newId = $cat->add();
2191
                            $newCategoryIdList[$oldCategoryId] = $newId;
2192
2193
                            $parentId = $cat->get_parent_id();
2194
2195
                            if (!empty($parentId)) {
2196
                                $newParentId = $newCategoryIdList[$parentId];
2197
                                $cat->set_parent_id($newParentId);
2198
                                $cat->save();
2199
                            }
2200
2201
                            /** @var AbstractLink $link */
2202
                            foreach ($links as $link) {
2203
                                $newCategoryId = $newCategoryIdList[$link->get_category_id()];
2204
                                $link->set_category_id($newCategoryId);
2205
                                $link->add();
2206
                            }
2207
                        }
2208
2209
                        // Create
2210
                        DocumentManager::generateDefaultCertificate(
2211
                            $courseInfo,
2212
                            true,
2213
                            $sessionId
2214
                        );
2215
                    }
2216
                }
2217
2218
                // If the course isn't subscribed yet
2219
                $sql = "INSERT INTO $tbl_session_rel_course (session_id, c_id)
2220
                        VALUES ($sessionId, $courseId)";
2221
                Database::query($sql);
2222
2223
                Event::addEvent(
2224
                    LOG_SESSION_ADD_COURSE,
2225
                    LOG_COURSE_ID,
2226
                    $courseId,
2227
                    api_get_utc_datetime(),
2228
                    api_get_user_id(),
2229
                    $courseId,
2230
                    $sessionId
2231
                );
2232
2233
                // We add the current course in the existing courses array,
2234
                // to avoid adding another time the current course
2235
                $existingCourses[] = array('c_id' => $courseId);
2236
                $nbr_courses++;
2237
2238
                // subscribe all the users from the session to this course inside the session
2239
                $nbr_users = 0;
2240 View Code Duplication
                foreach ($user_list as $enreg_user) {
2241
                    $enreg_user_id = intval($enreg_user['user_id']);
2242
                    $sql = "INSERT IGNORE INTO $tbl_session_rel_course_rel_user (session_id, c_id, user_id)
2243
                            VALUES ($sessionId, $courseId, $enreg_user_id)";
2244
                    $result = Database::query($sql);
2245
2246
                    Event::addEvent(
2247
                        LOG_SESSION_ADD_USER_COURSE,
2248
                        LOG_USER_ID,
2249
                        $enreg_user_id,
2250
                        api_get_utc_datetime(),
2251
                        api_get_user_id(),
2252
                        $courseId,
2253
                        $sessionId
2254
                    );
2255
2256
                    if (Database::affected_rows($result)) {
2257
                        $nbr_users++;
2258
                    }
2259
                }
2260
                $sql = "UPDATE $tbl_session_rel_course
2261
                        SET nbr_users = $nbr_users
2262
                        WHERE session_id = $sessionId AND c_id = $courseId";
2263
                Database::query($sql);
2264
            }
2265
        }
2266
2267
        $sql = "UPDATE $tbl_session
2268
                SET nbr_courses = $nbr_courses
2269
                WHERE id = $sessionId";
2270
        Database::query($sql);
2271
    }
2272
2273
    /**
2274
     * Unsubscribe course from a session
2275
     *
2276
     * @param int Session id
2277
     * @param int Course id
2278
     * @return bool True in case of success, false otherwise
2279
     */
2280
    public static function unsubscribe_course_from_session($session_id, $course_id)
2281
    {
2282
        $session_id = (int) $session_id;
2283
        $course_id = (int) $course_id;
2284
2285
        $tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
2286
        $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
2287
        $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
2288
2289
        // Get course code
2290
        $course_code = CourseManager::get_course_code_from_course_id($course_id);
2291
        $course_id = intval($course_id);
2292
2293
        if (empty($course_code)) {
2294
            return false;
2295
        }
2296
2297
        // Unsubscribe course
2298
        $sql = "DELETE FROM $tbl_session_rel_course
2299
                WHERE c_id = $course_id AND session_id = $session_id";
2300
        $result = Database::query($sql);
2301
        $nb_affected = Database::affected_rows($result);
2302
2303
        $sql = "DELETE FROM $tbl_session_rel_course_rel_user
2304
                WHERE c_id = $course_id AND session_id = $session_id";
2305
        Database::query($sql);
2306
2307
        Event::addEvent(
2308
            LOG_SESSION_DELETE_COURSE,
2309
            LOG_COURSE_ID,
2310
            $course_id,
2311
            api_get_utc_datetime(),
2312
            api_get_user_id(),
2313
            $course_id,
2314
            $session_id
2315
        );
2316
2317
        if ($nb_affected > 0) {
2318
            // Update number of courses in the session
2319
            $sql = "UPDATE $tbl_session SET nbr_courses= nbr_courses - $nb_affected
2320
                    WHERE id = $session_id";
2321
            Database::query($sql);
2322
            return true;
2323
        } else {
2324
            return false;
2325
        }
2326
    }
2327
2328
    /**
2329
     * Creates a new extra field for a given session
2330
     * @param	string	$variable Field's internal variable name
2331
     * @param	int		$fieldType Field's type
2332
     * @param	string	$displayText Field's language var name
2333
     * @return int     new extra field id
2334
     */
2335 View Code Duplication
    public static function create_session_extra_field($variable, $fieldType, $displayText)
2336
    {
2337
        $extraField = new ExtraField('session');
2338
        $params = [
2339
            'variable' => $variable,
2340
            'field_type' => $fieldType,
2341
            'display_text' => $displayText,
2342
        ];
2343
2344
        return $extraField->save($params);
2345
    }
2346
2347
    /**
2348
     * Update an extra field value for a given session
2349
     * @param	integer	Course ID
2350
     * @param	string	Field variable name
2351
     * @param	string	Field value
2352
     * @return	boolean	true if field updated, false otherwise
2353
     */
2354 View Code Duplication
    public static function update_session_extra_field_value($sessionId, $variable, $value = '')
2355
    {
2356
        $extraFieldValue = new ExtraFieldValue('session');
2357
        $params = [
2358
            'item_id' => $sessionId,
2359
            'variable' => $variable,
2360
            'value' => $value,
2361
        ];
2362
        $extraFieldValue->save($params);
2363
    }
2364
2365
    /**
2366
     * Checks the relationship between a session and a course.
2367
     * @param int $session_id
2368
     * @param int $courseId
2369
     * @return bool Returns TRUE if the session and the course are related, FALSE otherwise.
2370
     * */
2371 View Code Duplication
    public static function relation_session_course_exist($session_id, $courseId)
2372
    {
2373
        $tbl_session_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
2374
        $return_value = false;
2375
        $sql = "SELECT c_id FROM $tbl_session_course
2376
                WHERE
2377
                  session_id = " . intval($session_id) . " AND
2378
                  c_id = " . intval($courseId) . "";
2379
        $result = Database::query($sql);
2380
        $num = Database::num_rows($result);
2381
        if ($num > 0) {
2382
            $return_value = true;
2383
        }
2384
        return $return_value;
2385
    }
2386
2387
    /**
2388
     * Get the session information by name
2389
     * @param string session name
2390
     * @return mixed false if the session does not exist, array if the session exist
2391
     * */
2392
    public static function get_session_by_name($session_name)
2393
    {
2394
        $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
2395
        $session_name = trim($session_name);
2396
        if (empty($session_name)) {
2397
            return false;
2398
        }
2399
2400
        $sql = 'SELECT *
2401
		        FROM ' . $tbl_session . '
2402
		        WHERE name = "' . Database::escape_string($session_name) . '"';
2403
        $result = Database::query($sql);
2404
        $num = Database::num_rows($result);
2405
        if ($num > 0) {
2406
            return Database::fetch_array($result);
2407
        } else {
2408
            return false;
2409
        }
2410
    }
2411
2412
    /**
2413
     * Create a session category
2414
     * @author Jhon Hinojosa <[email protected]>, from existing code
2415
     * @param	string 		name
2416
     * @param 	integer		year_start
2417
     * @param 	integer		month_start
2418
     * @param 	integer		day_start
2419
     * @param 	integer		year_end
2420
     * @param 	integer		month_end
2421
     * @param 	integer		day_end
2422
     * @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...
2423
     * */
2424
    public static function create_category_session(
2425
        $sname,
2426
        $syear_start,
2427
        $smonth_start,
2428
        $sday_start,
2429
        $syear_end,
2430
        $smonth_end,
2431
        $sday_end
2432
    ) {
2433
        $tbl_session_category = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
2434
        $name = trim($sname);
2435
        $year_start = intval($syear_start);
2436
        $month_start = intval($smonth_start);
2437
        $day_start = intval($sday_start);
2438
        $year_end = intval($syear_end);
2439
        $month_end = intval($smonth_end);
2440
        $day_end = intval($sday_end);
2441
2442
        $date_start = "$year_start-" . (($month_start < 10) ? "0$month_start" : $month_start) . "-" . (($day_start < 10) ? "0$day_start" : $day_start);
2443
        $date_end = "$year_end-" . (($month_end < 10) ? "0$month_end" : $month_end) . "-" . (($day_end < 10) ? "0$day_end" : $day_end);
2444
2445 View Code Duplication
        if (empty($name)) {
2446
            $msg = get_lang('SessionCategoryNameIsRequired');
2447
            return $msg;
2448
        } elseif (!$month_start || !$day_start || !$year_start || !checkdate($month_start, $day_start, $year_start)) {
2449
            $msg = get_lang('InvalidStartDate');
2450
            return $msg;
2451
        } elseif (!$month_end && !$day_end && !$year_end) {
2452
            $date_end = "null";
2453
        } elseif (!$month_end || !$day_end || !$year_end || !checkdate($month_end, $day_end, $year_end)) {
2454
            $msg = get_lang('InvalidEndDate');
2455
            return $msg;
2456
        } elseif ($date_start >= $date_end) {
2457
            $msg = get_lang('StartDateShouldBeBeforeEndDate');
2458
            return $msg;
2459
        }
2460
2461
        $access_url_id = api_get_current_access_url_id();
2462
        $params = [
2463
            'name' => $name,
2464
            'date_start' => $date_start,
2465
            'date_end' => $date_end,
2466
            'access_url_id' => $access_url_id
2467
        ];
2468
        $id_session = Database::insert($tbl_session_category, $params);
2469
2470
        // Add event to system log
2471
        $user_id = api_get_user_id();
2472
        Event::addEvent(
2473
            LOG_SESSION_CATEGORY_CREATE,
2474
            LOG_SESSION_CATEGORY_ID,
2475
            $id_session,
0 ignored issues
show
Security Bug introduced by
It seems like $id_session defined by \Database::insert($tbl_session_category, $params) on line 2468 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...
2476
            api_get_utc_datetime(),
2477
            $user_id
2478
        );
2479
        return $id_session;
2480
    }
2481
2482
    /**
2483
     * Edit a sessions categories
2484
     * @author Jhon Hinojosa <[email protected]>,from existing code
2485
     * @param	integer		id
2486
     * @param	string 		name
2487
     * @param 	integer		year_start
2488
     * @param 	integer		month_start
2489
     * @param 	integer		day_start
2490
     * @param 	integer		year_end
2491
     * @param 	integer		month_end
2492
     * @param 	integer		day_end
2493
     * @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...
2494
     * The parameter id is a primary key
2495
     * */
2496
    public static function edit_category_session(
2497
        $id,
2498
        $sname,
2499
        $syear_start,
2500
        $smonth_start,
2501
        $sday_start,
2502
        $syear_end,
2503
        $smonth_end,
2504
        $sday_end
2505
    ) {
2506
        $tbl_session_category = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
2507
        $name = trim($sname);
2508
        $year_start = intval($syear_start);
2509
        $month_start = intval($smonth_start);
2510
        $day_start = intval($sday_start);
2511
        $year_end = intval($syear_end);
2512
        $month_end = intval($smonth_end);
2513
        $day_end = intval($sday_end);
2514
        $id = intval($id);
2515
        $date_start = "$year_start-" . (($month_start < 10) ? "0$month_start" : $month_start) . "-" . (($day_start < 10) ? "0$day_start" : $day_start);
2516
        $date_end = "$year_end-" . (($month_end < 10) ? "0$month_end" : $month_end) . "-" . (($day_end < 10) ? "0$day_end" : $day_end);
2517
2518 View Code Duplication
        if (empty($name)) {
2519
            $msg = get_lang('SessionCategoryNameIsRequired');
2520
            return $msg;
2521
        } elseif (!$month_start || !$day_start || !$year_start || !checkdate($month_start, $day_start, $year_start)) {
2522
            $msg = get_lang('InvalidStartDate');
2523
            return $msg;
2524
        } elseif (!$month_end && !$day_end && !$year_end) {
2525
            $date_end = null;
2526
        } elseif (!$month_end || !$day_end || !$year_end || !checkdate($month_end, $day_end, $year_end)) {
2527
            $msg = get_lang('InvalidEndDate');
2528
            return $msg;
2529
        } elseif ($date_start >= $date_end) {
2530
            $msg = get_lang('StartDateShouldBeBeforeEndDate');
2531
            return $msg;
2532
        }
2533
        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...
2534
            $sql = "UPDATE $tbl_session_category
2535
                    SET
2536
                        name = '" . Database::escape_string($name) . "',
2537
                        date_start = '$date_start' ,
2538
                        date_end = '$date_end'
2539
                    WHERE id= $id";
2540
        } else {
2541
            $sql = "UPDATE $tbl_session_category SET
2542
                        name = '" . Database::escape_string($name) . "',
2543
                        date_start = '$date_start',
2544
                        date_end = NULL
2545
                    WHERE id= $id";
2546
        }
2547
        $result = Database::query($sql);
2548
        return ($result ? true : false);
2549
    }
2550
2551
    /**
2552
     * Delete sessions categories
2553
     * @author Jhon Hinojosa <[email protected]>, from existing code
2554
     * @param	array	id_checked
2555
     * @param	bool	include delete session
2556
     * @param	bool	optional, true if the function is called by a webservice, false otherwise.
2557
     * @return	void	Nothing, or false on error
2558
     * The parameters is a array to delete sessions
2559
     * */
2560
    public static function delete_session_category($id_checked, $delete_session = false, $from_ws = false)
2561
    {
2562
        $tbl_session_category = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
2563
        $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
2564
        if (is_array($id_checked)) {
2565
            $id_checked = Database::escape_string(implode(',', $id_checked));
2566
        } else {
2567
            $id_checked = intval($id_checked);
2568
        }
2569
2570
        //Setting session_category_id to 0
2571
        $sql = "UPDATE $tbl_session SET session_category_id = 0
2572
                WHERE session_category_id IN (" . $id_checked . ")";
2573
        Database::query($sql);
2574
2575
        $sql = "SELECT id FROM $tbl_session WHERE session_category_id IN (" . $id_checked . ")";
2576
        $result = Database::query($sql);
2577
        while ($rows = Database::fetch_array($result)) {
2578
            $session_id = $rows['id'];
2579
            if ($delete_session) {
2580
                if ($from_ws) {
2581
                    SessionManager::delete($session_id, true);
2582
                } else {
2583
                    SessionManager::delete($session_id);
2584
                }
2585
            }
2586
        }
2587
        $sql = "DELETE FROM $tbl_session_category WHERE id IN (" . $id_checked . ")";
2588
        Database::query($sql);
2589
2590
        // Add event to system log
2591
        $user_id = api_get_user_id();
2592
        Event::addEvent(
2593
            LOG_SESSION_CATEGORY_DELETE,
2594
            LOG_SESSION_CATEGORY_ID,
2595
            $id_checked,
2596
            api_get_utc_datetime(),
2597
            $user_id
2598
        );
2599
2600
        return true;
2601
    }
2602
2603
    /**
2604
     * Get a list of sessions of which the given conditions match with an = 'cond'
2605
     * @param  array $conditions a list of condition example :
2606
     * array('status' => STUDENT) or
2607
     * array('s.name' => array('operator' => 'LIKE', value = '%$needle%'))
2608
     * @param  array $order_by a list of fields on which sort
2609
     * @return array An array with all sessions of the platform.
2610
     * @todo   optional course code parameter, optional sorting parameters...
2611
     */
2612
    public static function get_sessions_list($conditions = array(), $order_by = array(), $from = null, $to = null)
2613
    {
2614
        $session_table = Database::get_main_table(TABLE_MAIN_SESSION);
2615
        $session_category_table = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
2616
        $user_table = Database::get_main_table(TABLE_MAIN_USER);
2617
        $table_access_url_rel_session = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
2618
        $session_course_table = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
2619
        $course_table = Database::get_main_table(TABLE_MAIN_COURSE);
2620
        $access_url_id = api_get_current_access_url_id();
2621
        $return_array = array();
2622
2623
        $sql_query = " SELECT
2624
                    s.id,
2625
                    s.name,
2626
                    s.nbr_courses,
2627
                    s.access_start_date,
2628
                    s.access_end_date,
2629
                    u.firstname,
2630
                    u.lastname,
2631
                    sc.name as category_name,
2632
                    s.promotion_id
2633
				FROM $session_table s
2634
				INNER JOIN $user_table u ON s.id_coach = u.user_id
2635
				INNER JOIN $table_access_url_rel_session ar ON ar.session_id = s.id
2636
				LEFT JOIN  $session_category_table sc ON s.session_category_id = sc.id
2637
				LEFT JOIN $session_course_table sco ON (sco.session_id = s.id)
2638
				INNER JOIN $course_table c ON sco.c_id = c.id
2639
				WHERE ar.access_url_id = $access_url_id ";
2640
2641
        $availableFields = array(
2642
            's.id',
2643
            's.name',
2644
            'c.id'
2645
        );
2646
2647
        $availableOperator = array(
2648
            'like',
2649
            '>=',
2650
            '<=',
2651
            '=',
2652
        );
2653
2654
        if (count($conditions) > 0) {
2655
            foreach ($conditions as $field => $options) {
2656
                $operator = strtolower($options['operator']);
2657
                $value = Database::escape_string($options['value']);
2658
                $sql_query .= ' AND ';
2659
                if (in_array($field, $availableFields) && in_array($operator, $availableOperator)) {
2660
                    $sql_query .= $field . " $operator '" . $value . "'";
2661
                }
2662
            }
2663
        }
2664
2665
        $orderAvailableList = array('name');
2666
2667
        if (count($order_by) > 0) {
2668
            $order = null;
2669
            $direction = null;
2670
            if (isset($order_by[0]) && in_array($order_by[0], $orderAvailableList)) {
2671
                $order = $order_by[0];
2672
            }
2673
            if (isset($order_by[1]) && in_array(strtolower($order_by[1]), array('desc', 'asc'))) {
2674
                $direction = $order_by[1];
2675
            }
2676
2677
            if (!empty($order)) {
2678
                $sql_query .= " ORDER BY $order $direction ";
2679
            }
2680
        }
2681
2682
        if (!is_null($from) && !is_null($to)) {
2683
            $to = intval($to);
2684
            $from = intval($from);
2685
            $sql_query .= "LIMIT $from, $to";
2686
        }
2687
2688
        $sql_result = Database::query($sql_query);
2689
        if (Database::num_rows($sql_result) > 0) {
2690
            while ($result = Database::fetch_array($sql_result)) {
2691
                $return_array[$result['id']] = $result;
2692
            }
2693
        }
2694
2695
        return $return_array;
2696
    }
2697
2698
    /**
2699
     * Get the session category information by id
2700
     * @param string session category ID
2701
     * @return mixed false if the session category does not exist, array if the session category exists
2702
     */
2703 View Code Duplication
    public static function get_session_category($id)
2704
    {
2705
        $tbl_session_category = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
2706
        $id = intval($id);
2707
        $sql = "SELECT id, name, date_start, date_end
2708
                FROM $tbl_session_category
2709
                WHERE id= $id";
2710
        $result = Database::query($sql);
2711
        $num = Database::num_rows($result);
2712
        if ($num > 0) {
2713
            return Database::fetch_array($result);
2714
        } else {
2715
            return false;
2716
        }
2717
    }
2718
2719
    /**
2720
     * Get all session categories (filter by access_url_id)
2721
     * @return mixed false if the session category does not exist, array if the session category exists
2722
     */
2723
    public static function get_all_session_category()
2724
    {
2725
        $tbl_session_category = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
2726
        $id = api_get_current_access_url_id();
2727
        $sql = 'SELECT * FROM ' . $tbl_session_category . '
2728
                WHERE access_url_id = ' . $id . '
2729
                ORDER BY name ASC';
2730
        $result = Database::query($sql);
2731
        if (Database::num_rows($result) > 0) {
2732
            $data = Database::store_result($result, 'ASSOC');
2733
            return $data;
2734
        } else {
2735
            return false;
2736
        }
2737
    }
2738
2739
    /**
2740
     * Assign a coach to course in session with status = 2
2741
     * @param int  $user_id
2742
     * @param int  $session_id
2743
     * @param int  $courseId
2744
     * @param bool $nocoach optional, if is true the user don't be a coach now,
2745
     * otherwise it'll assign a coach
2746
     * @return bool true if there are affected rows, otherwise false
2747
     */
2748
    public static function set_coach_to_course_session(
2749
        $user_id,
2750
        $session_id = 0,
2751
        $courseId = 0,
2752
        $nocoach = false
2753
    ) {
2754
        // Definition of variables
2755
        $user_id = intval($user_id);
2756
2757
        if (!empty($session_id)) {
2758
            $session_id = intval($session_id);
2759
        } else {
2760
            $session_id = api_get_session_id();
2761
        }
2762
2763
        if (!empty($courseId)) {
2764
            $courseId = intval($courseId);
2765
        } else {
2766
            $courseId = api_get_course_id();
2767
        }
2768
2769
        // Table definition
2770
        $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
2771
        $tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
2772
        $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
2773
2774
        // check if user is a teacher
2775
        $sql = "SELECT * FROM $tbl_user
2776
                WHERE status = 1 AND user_id = $user_id";
2777
2778
        $rs_check_user = Database::query($sql);
2779
2780
        if (Database::num_rows($rs_check_user) > 0) {
2781
            if ($nocoach) {
2782
                // check if user_id exists in session_rel_user (if the user is
2783
                // subscribed to the session in any manner)
2784
                $sql = "SELECT user_id FROM $tbl_session_rel_user
2785
                        WHERE
2786
                            session_id = $session_id AND
2787
                            user_id = $user_id";
2788
                $res = Database::query($sql);
2789
2790 View Code Duplication
                if (Database::num_rows($res) > 0) {
2791
                    // The user is already subscribed to the session. Change the
2792
                    // record so the user is NOT a coach for this course anymore
2793
                    // and then exit
2794
                    $sql = "UPDATE $tbl_session_rel_course_rel_user
2795
                            SET status = 0
2796
                            WHERE
2797
                                session_id = $session_id AND
2798
                                c_id = $courseId AND
2799
                                user_id = $user_id ";
2800
                    $result = Database::query($sql);
2801
                    if (Database::affected_rows($result) > 0)
2802
                        return true;
2803
                    else
2804
                        return false;
2805
                } else {
2806
                    // The user is not subscribed to the session, so make sure
2807
                    // he isn't subscribed to a course in this session either
2808
                    // and then exit
2809
                    $sql = "DELETE FROM $tbl_session_rel_course_rel_user
2810
                            WHERE
2811
                                session_id = $session_id AND
2812
                                c_id = $courseId AND
2813
                                user_id = $user_id ";
2814
                    $result = Database::query($sql);
2815
                    if (Database::affected_rows($result) > 0)
2816
                        return true;
2817
                    else
2818
                        return false;
2819
                }
2820
            } else {
2821
                // Assign user as a coach to course
2822
                // First check if the user is registered to the course
2823
                $sql = "SELECT user_id FROM $tbl_session_rel_course_rel_user
2824
                        WHERE
2825
                            session_id = $session_id AND
2826
                            c_id = $courseId AND
2827
                            user_id = $user_id";
2828
                $rs_check = Database::query($sql);
2829
2830
                // Then update or insert.
2831 View Code Duplication
                if (Database::num_rows($rs_check) > 0) {
2832
                    $sql = "UPDATE $tbl_session_rel_course_rel_user SET status = 2
2833
					        WHERE
2834
					            session_id = $session_id AND
2835
					            c_id = $courseId AND
2836
					            user_id = $user_id ";
2837
                    $result = Database::query($sql);
2838
                    if (Database::affected_rows($result) > 0) {
2839
                        return true;
2840
                    } else {
2841
                        return false;
2842
                    }
2843
                } else {
2844
                    $sql = "INSERT INTO $tbl_session_rel_course_rel_user(session_id, c_id, user_id, status)
2845
                            VALUES($session_id, $courseId, $user_id, 2)";
2846
                    $result = Database::query($sql);
2847
                    if (Database::affected_rows($result) > 0) {
2848
                        return true;
2849
                    } else {
2850
                        return false;
2851
                    }
2852
                }
2853
            }
2854
        } else {
2855
            return false;
2856
        }
2857
    }
2858
2859
    /**
2860
     * Subscribes sessions to human resource manager (Dashboard feature)
2861
     * @param array $userInfo Human Resource Manager info
2862
     * @param array $sessions_list Sessions id
2863
     * @param bool $sendEmail
2864
     * @param bool $removeOldConnections
2865
     * @return int
2866
     * */
2867
    public static function suscribe_sessions_to_hr_manager(
2868
        $userInfo,
2869
        $sessions_list,
2870
        $sendEmail = false,
2871
        $removeOldConnections = true
2872
    ) {
2873
        // Database Table Definitions
2874
        $tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
2875
        $tbl_session_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
2876
2877
        if (empty($userInfo)) {
2878
2879
            return 0;
2880
        }
2881
2882
        $userId = $userInfo['user_id'];
2883
2884
        // Only subscribe DRH users.
2885
        $rolesAllowed = array(
2886
            DRH,
2887
            SESSIONADMIN,
2888
            PLATFORM_ADMIN,
2889
            COURSE_TUTOR
2890
        );
2891
        $isAdmin = api_is_platform_admin_by_id($userInfo['user_id']);
2892
        if (!$isAdmin && !in_array($userInfo['status'], $rolesAllowed)) {
2893
2894
            return 0;
2895
        }
2896
2897
        $affected_rows = 0;
2898
2899
        // Deleting assigned sessions to hrm_id.
2900
        if ($removeOldConnections) {
2901
            if (api_is_multiple_url_enabled()) {
2902
                $sql = "SELECT session_id
2903
                        FROM $tbl_session_rel_user s
2904
                        INNER JOIN $tbl_session_rel_access_url a ON (a.session_id = s.session_id)
2905
                        WHERE
2906
                            s.user_id = $userId AND
2907
                            relation_type=" . SESSION_RELATION_TYPE_RRHH . " AND
2908
                            access_url_id = " . api_get_current_access_url_id() . "";
2909
            } else {
2910
                $sql = "SELECT session_id FROM $tbl_session_rel_user s
2911
                        WHERE user_id = $userId AND relation_type=" . SESSION_RELATION_TYPE_RRHH . "";
2912
            }
2913
            $result = Database::query($sql);
2914
2915 View Code Duplication
            if (Database::num_rows($result) > 0) {
2916
                while ($row = Database::fetch_array($result)) {
2917
                    $sql = "DELETE FROM $tbl_session_rel_user
2918
                            WHERE
2919
                                session_id = {$row['session_id']} AND
2920
                                user_id = $userId AND
2921
                                relation_type=" . SESSION_RELATION_TYPE_RRHH . " ";
2922
                    Database::query($sql);
2923
                }
2924
            }
2925
        }
2926
        // Inserting new sessions list.
2927
        if (!empty($sessions_list) && is_array($sessions_list)) {
2928
2929
            foreach ($sessions_list as $session_id) {
2930
                $session_id = intval($session_id);
2931
                $sql = "INSERT IGNORE INTO $tbl_session_rel_user (session_id, user_id, relation_type, registered_at)
2932
                        VALUES (
2933
                            $session_id,
2934
                            $userId,
2935
                            '" . SESSION_RELATION_TYPE_RRHH . "',
2936
                            '" . api_get_utc_datetime() . "'
2937
                        )";
2938
2939
                Database::query($sql);
2940
                $affected_rows++;
2941
            }
2942
        }
2943
2944
        return $affected_rows;
2945
    }
2946
2947
    /**
2948
     * @param int $sessionId
2949
     * @return array
2950
     */
2951
    public static function getDrhUsersInSession($sessionId)
2952
    {
2953
        return self::get_users_by_session($sessionId, SESSION_RELATION_TYPE_RRHH);
2954
    }
2955
2956
    /**
2957
     * @param int $userId
2958
     * @param int $sessionId
2959
     * @return array
2960
     */
2961
    public static function getSessionFollowedByDrh($userId, $sessionId)
2962
    {
2963
        $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
2964
        $tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
2965
        $tbl_session_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
2966
2967
        $userId = intval($userId);
2968
        $sessionId = intval($sessionId);
2969
2970
        $select = " SELECT * ";
2971
        if (api_is_multiple_url_enabled()) {
2972
            $sql = " $select FROM $tbl_session s
2973
                    INNER JOIN $tbl_session_rel_user sru ON (sru.session_id = s.id)
2974
                    LEFT JOIN $tbl_session_rel_access_url a ON (s.id = a.session_id)
2975
                    WHERE
2976
                        sru.user_id = '$userId' AND
2977
                        sru.session_id = '$sessionId' AND
2978
                        sru.relation_type = '" . SESSION_RELATION_TYPE_RRHH . "' AND
2979
                        access_url_id = " . api_get_current_access_url_id() . "
2980
                        ";
2981
        } else {
2982
            $sql = "$select FROM $tbl_session s
2983
                     INNER JOIN $tbl_session_rel_user sru
2984
                     ON
2985
                        sru.session_id = s.id AND
2986
                        sru.user_id = '$userId' AND
2987
                        sru.session_id = '$sessionId' AND
2988
                        sru.relation_type = '" . SESSION_RELATION_TYPE_RRHH . "'
2989
                    ";
2990
        }
2991
2992
        $result = Database::query($sql);
2993
        if (Database::num_rows($result)) {
2994
            $row = Database::fetch_array($result, 'ASSOC');
2995
            $row['course_list'] = self::get_course_list_by_session_id($sessionId);
2996
2997
            return $row;
2998
        }
2999
3000
        return array();
3001
    }
3002
3003
    /**
3004
     * Get sessions followed by human resources manager
3005
     * @param int $userId
3006
     * @param int $start
3007
     * @param int $limit
3008
     * @param bool $getCount
3009
     * @param bool $getOnlySessionId
3010
     * @param bool $getSql
3011
     * @param string $orderCondition
3012
     * @param string $description
3013
     *
3014
     * @return array sessions
3015
     */
3016
    public static function get_sessions_followed_by_drh(
3017
        $userId,
3018
        $start = null,
3019
        $limit = null,
3020
        $getCount = false,
3021
        $getOnlySessionId = false,
3022
        $getSql = false,
3023
        $orderCondition = null,
3024
        $keyword = '',
3025
        $description = ''
3026
    ) {
3027
        return self::getSessionsFollowedByUser(
3028
            $userId,
3029
            DRH,
3030
            $start,
3031
            $limit,
3032
            $getCount,
3033
            $getOnlySessionId,
3034
            $getSql,
3035
            $orderCondition,
3036
            $keyword,
3037
            $description
3038
        );
3039
    }
3040
3041
    /**
3042
     * Get sessions followed by human resources manager
3043
     * @param int $userId
3044
     * @param int $start
3045
     * @param int $limit
3046
     * @param bool $getCount
3047
     * @param bool $getOnlySessionId
3048
     * @param bool $getSql
3049
     * @param string $orderCondition
3050
     * @param string $keyword
3051
     * @param string $description
3052
     * @return array sessions
3053
     */
3054
    public static function getSessionsFollowedByUser(
3055
        $userId,
3056
        $status = null,
3057
        $start = null,
3058
        $limit = null,
3059
        $getCount = false,
3060
        $getOnlySessionId = false,
3061
        $getSql = false,
3062
        $orderCondition = null,
3063
        $keyword = '',
3064
        $description = ''
3065
    ) {
3066
        // Database Table Definitions
3067
        $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
3068
        $tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
3069
        $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
3070
        $tbl_session_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
3071
3072
        $userId = intval($userId);
3073
3074
        $select = " SELECT DISTINCT * ";
3075
3076
        if ($getCount) {
3077
            $select = " SELECT count(DISTINCT(s.id)) as count ";
3078
        }
3079
3080
        if ($getOnlySessionId) {
3081
            $select = " SELECT DISTINCT(s.id) ";
3082
        }
3083
3084
        $limitCondition = null;
3085 View Code Duplication
        if (!empty($start) && !empty($limit)) {
3086
            $limitCondition = " LIMIT " . intval($start) . ", " . intval($limit);
3087
        }
3088
3089
        if (empty($orderCondition)) {
3090
            $orderCondition = " ORDER BY s.name ";
3091
        }
3092
3093
        $whereConditions = null;
3094
        $sessionCourseConditions = null;
3095
        $sessionConditions = null;
3096
        $sessionQuery = null;
3097
        $courseSessionQuery = null;
3098
3099
        switch ($status) {
3100
            case DRH:
3101
                $sessionQuery = "SELECT sru.session_id
3102
                                 FROM
3103
                                 $tbl_session_rel_user sru
3104
                                 WHERE
3105
                                    sru.relation_type = '".SESSION_RELATION_TYPE_RRHH."' AND
3106
                                    sru.user_id = $userId";
3107
                break;
3108
            case COURSEMANAGER:
3109
                $courseSessionQuery = "
3110
                    SELECT scu.session_id as id
3111
                    FROM $tbl_session_rel_course_rel_user scu
3112
                    WHERE (scu.status = 2 AND scu.user_id = $userId)";
3113
3114
                $whereConditions = " OR (s.id_coach = $userId) ";
3115
                break;
3116
            default:
3117
                $sessionQuery = "SELECT sru.session_id
3118
                                 FROM
3119
                                 $tbl_session_rel_user sru
3120
                                 WHERE
3121
                                    sru.user_id = $userId";
3122
                break;
3123
        }
3124
3125
        $keywordCondition = '';
3126 View Code Duplication
        if (!empty($keyword)) {
3127
            $keyword = Database::escape_string($keyword);
3128
            $keywordCondition = " AND (s.name LIKE '%$keyword%' ) ";
3129
3130
            if (!empty($description)) {
3131
                $description = Database::escape_string($description);
3132
                $keywordCondition = " AND (s.name LIKE '%$keyword%' OR s.description LIKE '%$description%' ) ";
3133
            }
3134
        }
3135
3136
        $whereConditions .= $keywordCondition;
3137
3138
        $subQuery = $sessionQuery.$courseSessionQuery;
3139
3140
        $sql = " $select FROM $tbl_session s
3141
                INNER JOIN $tbl_session_rel_access_url a ON (s.id = a.session_id)
3142
                WHERE
3143
                    access_url_id = ".api_get_current_access_url_id()." AND
3144
                    s.id IN (
3145
                        $subQuery
3146
                    )
3147
                    $whereConditions
3148
                    $orderCondition
3149
                    $limitCondition";
3150
3151
        if ($getSql) {
3152
            return $sql;
3153
        }
3154
3155
        $result = Database::query($sql);
3156
3157
        if ($getCount) {
3158
            $row = Database::fetch_array($result);
3159
            return $row['count'];
3160
        }
3161
3162
        $sessions = array();
3163
        if (Database::num_rows($result) > 0) {
3164
            $sysUploadPath = api_get_path(SYS_UPLOAD_PATH). 'sessions/';
3165
            $webUploadPath = api_get_path(WEB_UPLOAD_PATH). 'sessions/';
3166
            $imgPath = Display::returnIconPath('session_default_small.png');
3167
3168
            $tableExtraFields = Database::get_main_table(TABLE_EXTRA_FIELD);
3169
            $sql = "SELECT id FROM " . $tableExtraFields . "
3170
                    WHERE extra_field_type = 3 AND variable='image'";
3171
            $resultField = Database::query($sql);
3172
            $imageFieldId = Database::fetch_assoc($resultField);
3173
3174
            while ($row = Database::fetch_array($result)) {
3175
3176
                $row['image'] =  null;
3177
                $sessionImage = $sysUploadPath . $imageFieldId['id'] . '_' . $row['id'] . '.png';
3178
3179
                if (is_file($sessionImage)) {
3180
                    $sessionImage = $webUploadPath . $imageFieldId['id'] . '_' . $row['id'] . '.png';
3181
                    $row['image'] = $sessionImage;
3182
                } else {
3183
                    $row['image'] =  $imgPath;
3184
                }
3185
3186
                $sessions[$row['id']] = $row;
3187
3188
            }
3189
        }
3190
3191
        return $sessions;
3192
    }
3193
3194
    /**
3195
     * Gets the list (or the count) of courses by session filtered by access_url
3196
     * @param int $session_id The session id
3197
     * @param string $course_name The course code
3198
     * @param string $orderBy Field to order the data
3199
     * @param boolean $getCount Optional. Count the session courses
3200
     * @return array|int List of courses. Whether $getCount is true, return the count
3201
     */
3202
    public static function get_course_list_by_session_id(
3203
        $session_id,
3204
        $course_name = '',
3205
        $orderBy = null,
3206
        $getCount = false
3207
    ) {
3208
        $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
3209
        $tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
3210
3211
        $session_id = intval($session_id);
3212
3213
        $sqlSelect = "SELECT *";
3214
3215
        if ($getCount) {
3216
            $sqlSelect = "SELECT COUNT(1)";
3217
        }
3218
3219
        // select the courses
3220
        $sql = "SELECT *, c.id, c.id as real_id
3221
                FROM $tbl_course c
3222
                INNER JOIN $tbl_session_rel_course src
3223
                ON c.id = src.c_id
3224
		        WHERE src.session_id = '$session_id' ";
3225
3226
        if (!empty($course_name)) {
3227
            $course_name = Database::escape_string($course_name);
3228
            $sql .= " AND c.title LIKE '%$course_name%' ";
3229
        }
3230
3231
        if (!empty($orderBy)) {
3232
            $orderBy = Database::escape_string($orderBy);
3233
            $orderBy = " ORDER BY $orderBy";
3234
        } else {
3235
            if (SessionManager::orderCourseIsEnabled()) {
3236
                $orderBy .= " ORDER BY position ";
3237
            } else {
3238
                $orderBy .= " ORDER BY title ";
3239
            }
3240
        }
3241
3242
        $sql .= Database::escape_string($orderBy);
3243
        $result = Database::query($sql);
3244
        $num_rows = Database::num_rows($result);
3245
        $courses = array();
3246 View Code Duplication
        if ($num_rows > 0) {
3247
            if ($getCount) {
3248
                $count = Database::fetch_array($result);
3249
3250
                return intval($count[0]);
3251
            }
3252
3253
            while ($row = Database::fetch_array($result,'ASSOC'))	{
3254
                $courses[$row['real_id']] = $row;
3255
            }
3256
        }
3257
3258
        return $courses;
3259
    }
3260
3261
    /**
3262
     * Gets the list of courses by session filtered by access_url
3263
     *
3264
     * @param $userId
3265
     * @param $sessionId
3266
     * @param null $from
3267
     * @param null $limit
3268
     * @param null $column
3269
     * @param null $direction
3270
     * @param bool $getCount
3271
     * @return array
3272
     */
3273
    public static function getAllCoursesFollowedByUser(
3274
        $userId,
3275
        $sessionId,
3276
        $from = null,
3277
        $limit = null,
3278
        $column = null,
3279
        $direction = null,
3280
        $getCount = false,
3281
        $keyword = null
3282
    ) {
3283
        if (empty($sessionId)) {
3284
            $sessionsSQL = SessionManager::get_sessions_followed_by_drh(
3285
                $userId,
3286
                null,
3287
                null,
3288
                null,
3289
                true,
3290
                true
3291
            );
3292
        } else {
3293
            $sessionsSQL = intval($sessionId);
3294
        }
3295
3296
        $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
3297
        $tbl_session_rel_course	= Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
3298
3299
        if ($getCount) {
3300
            $select = "SELECT COUNT(DISTINCT(c.code)) as count ";
3301
        } else {
3302
            $select = "SELECT DISTINCT c.* ";
3303
        }
3304
3305
        $keywordCondition = null;
3306
        if (!empty($keyword)) {
3307
            $keyword = Database::escape_string($keyword);
3308
            $keywordCondition = " AND (c.code LIKE '%$keyword%' OR c.title LIKE '%$keyword%' ) ";
3309
        }
3310
3311
        // Select the courses
3312
        $sql = "$select
3313
                FROM $tbl_course c
3314
                INNER JOIN $tbl_session_rel_course src
3315
                ON c.id = src.c_id
3316
		        WHERE
3317
		            src.session_id IN ($sessionsSQL)
3318
		            $keywordCondition
3319
		        ";
3320
        if ($getCount) {
3321
            $result = Database::query($sql);
3322
            $row = Database::fetch_array($result,'ASSOC');
3323
            return $row['count'];
3324
        }
3325
3326 View Code Duplication
        if (isset($from) && isset($limit)) {
3327
            $from = intval($from);
3328
            $limit = intval($limit);
3329
            $sql .= " LIMIT $from, $limit";
3330
        }
3331
3332
        $result = Database::query($sql);
3333
        $num_rows = Database::num_rows($result);
3334
        $courses = array();
3335
3336
        if ($num_rows > 0) {
3337
            while ($row = Database::fetch_array($result,'ASSOC'))	{
3338
                $courses[$row['id']] = $row;
3339
            }
3340
        }
3341
3342
        return $courses;
3343
    }
3344
3345
    /**
3346
     * Gets the list of courses by session filtered by access_url
3347
     * @param int $session_id
3348
     * @param string $course_name
3349
     * @return array list of courses
3350
     */
3351
    public static function get_course_list_by_session_id_like($session_id, $course_name = '')
3352
    {
3353
        $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
3354
        $tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
3355
3356
        $session_id = intval($session_id);
3357
        $course_name = Database::escape_string($course_name);
3358
3359
        // select the courses
3360
        $sql = "SELECT c.id, c.title FROM $tbl_course c
3361
                INNER JOIN $tbl_session_rel_course src
3362
                ON c.id = src.c_id
3363
		        WHERE ";
3364
3365
        if (!empty($session_id)) {
3366
            $sql .= "src.session_id LIKE '$session_id' AND ";
3367
        }
3368
3369
        if (!empty($course_name)) {
3370
            $sql .= "UPPER(c.title) LIKE UPPER('%$course_name%') ";
3371
        }
3372
3373
        $sql .= "ORDER BY title;";
3374
        $result = Database::query($sql);
3375
        $num_rows = Database::num_rows($result);
3376
        $courses = array();
3377
        if ($num_rows > 0) {
3378
            while ($row = Database::fetch_array($result, 'ASSOC')) {
3379
                $courses[$row['id']] = $row;
3380
            }
3381
        }
3382
3383
        return $courses;
3384
    }
3385
3386
3387
    /**
3388
     * Gets the count of courses by session filtered by access_url
3389
     * @param int session id
3390
     * @return array list of courses
3391
     */
3392
    public static function getCourseCountBySessionId($session_id, $keyword = null)
3393
    {
3394
        $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
3395
        $tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
3396
        $session_id = intval($session_id);
3397
3398
        // select the courses
3399
        $sql = "SELECT COUNT(c.code) count
3400
                FROM $tbl_course c
3401
                INNER JOIN $tbl_session_rel_course src
3402
                ON c.id = src.c_id
3403
		        WHERE src.session_id = '$session_id' ";
3404
3405
        $keywordCondition = null;
3406
        if (!empty($keyword)) {
3407
            $keyword = Database::escape_string($keyword);
3408
            $keywordCondition = " AND (c.code LIKE '%$keyword%' OR c.title LIKE '%$keyword%' ) ";
3409
        }
3410
        $sql .= $keywordCondition;
3411
3412
        $result = Database::query($sql);
3413
        $num_rows = Database::num_rows($result);
3414
        if ($num_rows > 0) {
3415
            $row = Database::fetch_array($result,'ASSOC');
3416
            return $row['count'];
3417
        }
3418
3419
        return null;
3420
    }
3421
3422
    /**
3423
     * Get the session id based on the original id and field name in the extra fields.
3424
     * Returns 0 if session was not found
3425
     *
3426
     * @param string $value Original session id
3427
     * @param string $variable Original field name
3428
     * @return int Session id
3429
     */
3430
    public static function getSessionIdFromOriginalId($value, $variable)
3431
    {
3432
        $extraFieldValue = new ExtraFieldValue('session');
3433
        $result = $extraFieldValue->get_item_id_from_field_variable_and_field_value(
3434
            $variable,
3435
            $value
3436
        );
3437
3438
        if (!empty($result)) {
3439
            return $result['item_id'];
3440
        }
3441
3442
        return 0;
3443
    }
3444
3445
    /**
3446
     * Get users by session
3447
     * @param  int $id session id
3448
     * @param	int	$status filter by status coach = 2
3449
     * @return  array a list with an user list
3450
     */
3451
    public static function get_users_by_session($id, $status = null)
3452
    {
3453
        if (empty($id)) {
3454
            return array();
3455
        }
3456
        $id = intval($id);
3457
        $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
3458
        $tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
3459
        $table_access_url_user = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
3460
3461
        $sql = "SELECT
3462
                    u.user_id,
3463
                    lastname,
3464
                    firstname,
3465
                    username,
3466
                    relation_type,
3467
                    access_url_id
3468
                FROM $tbl_user u
3469
                INNER JOIN $tbl_session_rel_user
3470
                ON u.user_id = $tbl_session_rel_user.user_id AND
3471
                $tbl_session_rel_user.session_id = $id
3472
                LEFT OUTER JOIN $table_access_url_user uu
3473
                ON (uu.user_id = u.user_id)
3474
                ";
3475
3476
        $urlId = api_get_current_access_url_id();
3477
        if (isset($status) && $status != '') {
3478
            $status = intval($status);
3479
            $sql .= " WHERE relation_type = $status AND (access_url_id = $urlId OR access_url_id is null )";
3480
        } else {
3481
            $sql .= " WHERE (access_url_id = $urlId OR access_url_id is null )";
3482
        }
3483
3484
        $sql .= " ORDER BY relation_type, ";
3485
        $sql .= api_sort_by_first_name() ? ' firstname, lastname' : '  lastname, firstname';
3486
3487
        $result = Database::query($sql);
3488
3489
        $return = array();
3490
        while ($row = Database::fetch_array($result, 'ASSOC')) {
3491
            $return[] = $row;
3492
        }
3493
3494
        return $return;
3495
    }
3496
3497
    /**
3498
     * The general coach (field: session.id_coach)
3499
     * @param int $user_id user id
3500
     * @param boolean   $asPlatformAdmin The user is platform admin, return everything
3501
     * @return array
3502
     */
3503
    public static function get_sessions_by_general_coach($user_id, $asPlatformAdmin = false)
3504
    {
3505
        $session_table = Database::get_main_table(TABLE_MAIN_SESSION);
3506
        $user_id = intval($user_id);
3507
3508
        // Session where we are general coach
3509
        $sql = "SELECT DISTINCT *
3510
                FROM $session_table";
3511
3512
        if (!$asPlatformAdmin) {
3513
            $sql .= " WHERE id_coach = $user_id";
3514
        }
3515
3516
        if (api_is_multiple_url_enabled()) {
3517
            $tbl_session_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
3518
            $access_url_id = api_get_current_access_url_id();
3519
3520
            $sqlCoach = '';
3521
            if (!$asPlatformAdmin) {
3522
                $sqlCoach = " id_coach = $user_id AND ";
3523
            }
3524
3525
            if ($access_url_id != -1) {
3526
                $sql = 'SELECT DISTINCT session.*
3527
                    FROM ' . $session_table . ' session INNER JOIN ' . $tbl_session_rel_access_url . ' session_rel_url
3528
                    ON (session.id = session_rel_url.session_id)
3529
                    WHERE '.$sqlCoach.' access_url_id = ' . $access_url_id;
3530
            }
3531
        }
3532
        $sql .= ' ORDER by name';
3533
        $result = Database::query($sql);
3534
3535
        return Database::store_result($result, 'ASSOC');
3536
    }
3537
3538
    /**
3539
     * @param int $user_id
3540
     * @return array
3541
     * @deprecated use get_sessions_by_general_coach()
3542
     */
3543
    public static function get_sessions_by_coach($user_id)
3544
    {
3545
        $session_table = Database::get_main_table(TABLE_MAIN_SESSION);
3546
        return Database::select('*', $session_table, array('where' => array('id_coach = ?' => $user_id)));
3547
    }
3548
3549
    /**
3550
     * @param int $user_id
3551
     * @param int $courseId
3552
     * @param int $session_id
3553
     * @return array|bool
3554
     */
3555 View Code Duplication
    public static function get_user_status_in_course_session($user_id, $courseId, $session_id)
3556
    {
3557
        $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
3558
        $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
3559
        $sql = "SELECT session_rcru.status
3560
                FROM $tbl_session_rel_course_rel_user session_rcru, $tbl_user user
3561
                WHERE
3562
                    session_rcru.user_id = user.user_id AND
3563
                    session_rcru.session_id = '" . intval($session_id) . "' AND
3564
                    session_rcru.c_id ='" . intval($courseId) . "' AND
3565
                    user.user_id = " . intval($user_id);
3566
3567
        $result = Database::query($sql);
3568
        $status = false;
3569
        if (Database::num_rows($result)) {
3570
            $status = Database::fetch_row($result);
3571
            $status = $status['0'];
3572
        }
3573
3574
        return $status;
3575
    }
3576
3577
    /**
3578
     * Gets user status within a session
3579
     * @param int $user_id
3580
     * @param int $courseId
3581
     * @param $session_id
3582
     * @return int
3583
     * @assert (null,null,null) === false
3584
     */
3585
    public static function get_user_status_in_session($user_id, $courseId, $session_id)
3586
    {
3587
        if (empty($user_id) or empty($courseId) or empty($session_id)) {
3588
            return false;
3589
        }
3590
        $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
3591
        $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
3592
        $sql = "SELECT session_rcru.status
3593
                FROM $tbl_session_rel_course_rel_user session_rcru, $tbl_user user
3594
                WHERE session_rcru.user_id = user.user_id AND
3595
                    session_rcru.session_id = '" . intval($session_id) . "' AND
3596
                    session_rcru.c_id ='" . intval($courseId) . "' AND
3597
                    user.user_id = " . intval($user_id);
3598
        $result = Database::query($sql);
3599
        $status = false;
3600
        if (Database::num_rows($result)) {
3601
            $status = Database::fetch_row($result);
3602
            $status = $status['0'];
3603
        }
3604
        return $status;
3605
    }
3606
3607
    /**
3608
     * @param int $id
3609
     * @return array
3610
     */
3611
    public static function get_all_sessions_by_promotion($id)
3612
    {
3613
        $t = Database::get_main_table(TABLE_MAIN_SESSION);
3614
        return Database::select('*', $t, array('where' => array('promotion_id = ?' => $id)));
3615
    }
3616
3617
    /**
3618
     * @param int $promotion_id
3619
     * @param array $list
3620
     */
3621
    public static function suscribe_sessions_to_promotion($promotion_id, $list)
3622
    {
3623
        $t = Database::get_main_table(TABLE_MAIN_SESSION);
3624
        $params = array();
3625
        $params['promotion_id'] = 0;
3626
        Database::update($t, $params, array('promotion_id = ?' => $promotion_id));
3627
3628
        $params['promotion_id'] = $promotion_id;
3629
        if (!empty($list)) {
3630
            foreach ($list as $session_id) {
3631
                $session_id = intval($session_id);
3632
                Database::update($t, $params, array('id = ?' => $session_id));
3633
            }
3634
        }
3635
    }
3636
3637
    /**
3638
     * Updates a session status
3639
     * @param	int 	session id
3640
     * @param	int 	status
3641
     */
3642
    public static function set_session_status($session_id, $status)
3643
    {
3644
        $t = Database::get_main_table(TABLE_MAIN_SESSION);
3645
        $params['visibility'] = $status;
3646
        Database::update($t, $params, array('id = ?' => $session_id));
3647
    }
3648
3649
    /**
3650
     * Copies a session with the same data to a new session.
3651
     * The new copy is not assigned to the same promotion. @see suscribe_sessions_to_promotions() for that
3652
     * @param   int     Session ID
3653
     * @param   bool    Whether to copy the relationship with courses
3654
     * @param   bool    Whether to copy the relationship with users
3655
     * @param   bool    New courses will be created
3656
     * @param   bool    Whether to set exercises and learning paths in the new session to invisible by default
3657
     * @return  int     The new session ID on success, 0 otherwise
3658
     * @todo make sure the extra session fields are copied too
3659
     */
3660
    public static function copy(
3661
        $id,
3662
        $copy_courses = true,
3663
        $copy_users = true,
3664
        $create_new_courses = false,
3665
        $set_exercises_lp_invisible = false
3666
    ) {
3667
        $id = intval($id);
3668
        $s = self::fetch($id);
3669
        // Check all dates before copying
3670
        // Get timestamp for now in UTC - see http://php.net/manual/es/function.time.php#117251
3671
        $now = time() - date('Z');
3672
        // Timestamp in one month
3673
        $inOneMonth = $now + (30*24*3600);
3674
        $inOneMonth = api_get_local_time($inOneMonth);
3675
        if (api_strtotime($s['access_start_date']) < $now) {
3676
            $s['access_start_date'] = api_get_local_time($now);
3677
        }
3678
        if (api_strtotime($s['display_start_date']) < $now) {
3679
            $s['display_start_date'] = api_get_local_time($now);
3680
        }
3681
        if (api_strtotime($s['coach_access_start_date']) < $now) {
3682
            $s['coach_access_start_date'] = api_get_local_time($now);
3683
        }
3684
        if (api_strtotime($s['access_end_date']) < $now) {
3685
            $s['access_end_date'] = $inOneMonth;
3686
        }
3687
        if (api_strtotime($s['display_end_date']) < $now) {
3688
            $s['display_end_date'] = $inOneMonth;
3689
        }
3690
        if (api_strtotime($s['coach_access_end_date']) < $now) {
3691
            $s['coach_access_end_date'] = $inOneMonth;
3692
        }
3693
        // Now try to create the session
3694
        $sid = self::create_session(
3695
            $s['name'] . ' ' . get_lang('CopyLabelSuffix'),
3696
            $s['access_start_date'],
3697
            $s['access_end_date'],
3698
            $s['display_start_date'],
3699
            $s['display_end_date'],
3700
            $s['coach_access_start_date'],
3701
            $s['coach_access_end_date'],
3702
            (int)$s['id_coach'],
3703
            $s['session_category_id'],
3704
            (int)$s['visibility'],
3705
            true
3706
        );
3707
3708
        if (!is_numeric($sid) || empty($sid)) {
3709
            return false;
3710
        }
3711
3712
        if ($copy_courses) {
3713
            // Register courses from the original session to the new session
3714
            $courses = self::get_course_list_by_session_id($id);
3715
3716
            $short_courses = $new_short_courses = array();
3717
            if (is_array($courses) && count($courses) > 0) {
3718
                foreach ($courses as $course) {
3719
                    $short_courses[] = $course;
3720
                }
3721
            }
3722
3723
            $courses = null;
3724
3725
            //We will copy the current courses of the session to new courses
3726
            if (!empty($short_courses)) {
3727
                if ($create_new_courses) {
3728
                    //Just in case
3729
                    if (function_exists('ini_set')) {
3730
                        api_set_memory_limit('256M');
3731
                        ini_set('max_execution_time', 0);
3732
                    }
3733
                    $params = array();
3734
                    $params['skip_lp_dates'] = true;
3735
3736
                    foreach ($short_courses as $course_data) {
3737
                        $course_info = CourseManager::copy_course_simple(
3738
                            $course_data['title'].' '.get_lang(
3739
                                'CopyLabelSuffix'
3740
                            ),
3741
                            $course_data['course_code'],
3742
                            $id,
3743
                            $sid,
3744
                            $params
3745
                        );
3746
3747
                        if ($course_info) {
3748
                            //By default new elements are invisible
3749
                            if ($set_exercises_lp_invisible) {
3750
                                $list = new LearnpathList('', $course_info['code'], $sid);
3751
                                $flat_list = $list->get_flat_list();
3752
                                if (!empty($flat_list)) {
3753
                                    foreach ($flat_list as $lp_id => $data) {
3754
                                        api_item_property_update(
3755
                                            $course_info,
0 ignored issues
show
Bug introduced by
It seems like $course_info defined by \CourseManager::copy_cou...'], $id, $sid, $params) on line 3737 can also be of type boolean; however, api_item_property_update() does only seem to accept array, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
3756
                                            TOOL_LEARNPATH,
3757
                                            $lp_id,
3758
                                            'invisible',
3759
                                            api_get_user_id(),
3760
                                            0,
3761
                                            0,
3762
                                            0,
3763
                                            0,
3764
                                            $sid
3765
                                        );
3766
                                    }
3767
                                }
3768
                                $quiz_table = Database::get_course_table(TABLE_QUIZ_TEST);
3769
                                $course_id = $course_info['real_id'];
3770
                                //@todo check this query
3771
                                $sql = "UPDATE $quiz_table SET active = 0
3772
                                        WHERE c_id = $course_id AND session_id = $sid";
3773
                                Database::query($sql);
3774
                            }
3775
                            $new_short_courses[] = $course_info['real_id'];
3776
                        }
3777
                    }
3778
                } else {
3779
                    foreach ($short_courses as $course_data) {
3780
                        $new_short_courses[] = $course_data['id'];
3781
                    }
3782
                }
3783
3784
                $short_courses = $new_short_courses;
3785
                self::add_courses_to_session($sid, $short_courses, true);
3786
                $short_courses = null;
3787
            }
3788
        }
3789
        if ($copy_users) {
3790
            // Register users from the original session to the new session
3791
            $users = self::get_users_by_session($id);
3792
            $short_users = array();
3793
            if (is_array($users) && count($users) > 0) {
3794
                foreach ($users as $user) {
3795
                    $short_users[] = $user['user_id'];
3796
                }
3797
            }
3798
            $users = null;
3799
            //Subscribing in read only mode
3800
            self::suscribe_users_to_session($sid, $short_users, SESSION_VISIBLE_READ_ONLY, true);
3801
            $short_users = null;
3802
        }
3803
        return $sid;
3804
    }
3805
3806
    /**
3807
     * @param int $user_id
3808
     * @param int $session_id
3809
     * @return bool
3810
     */
3811
    static function user_is_general_coach($user_id, $session_id)
3812
    {
3813
        $session_id = intval($session_id);
3814
        $user_id = intval($user_id);
3815
        $session_table = Database::get_main_table(TABLE_MAIN_SESSION);
3816
        $sql = "SELECT DISTINCT id
3817
	         	FROM $session_table
3818
	         	WHERE session.id_coach =  '" . $user_id . "' AND id = '$session_id'";
3819
        $result = Database::query($sql);
3820
        if ($result && Database::num_rows($result)) {
3821
            return true;
3822
        }
3823
        return false;
3824
    }
3825
3826
    /**
3827
     * Get the number of sessions
3828
     * @param  int ID of the URL we want to filter on (optional)
3829
     * @return int Number of sessions
3830
     */
3831
    public static function count_sessions($access_url_id = null)
3832
    {
3833
        $session_table = Database::get_main_table(TABLE_MAIN_SESSION);
3834
        $access_url_rel_session_table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
3835
        $sql = "SELECT count(id) FROM $session_table s";
3836
        if (!empty($access_url_id) && $access_url_id == intval($access_url_id)) {
3837
            $sql .= ", $access_url_rel_session_table u " .
3838
                " WHERE s.id = u.session_id AND u.access_url_id = $access_url_id";
3839
        }
3840
        $res = Database::query($sql);
3841
        $row = Database::fetch_row($res);
3842
        return $row[0];
3843
    }
3844
3845
    /**
3846
     * Protect a session to be edited.
3847
     * @param int $id
3848
     * @param bool $checkSession
3849
     */
3850
    public static function protectSession($id, $checkSession = true)
3851
    {
3852
        // api_protect_admin_script(true);
3853
        if (self::allowToManageSessions()) {
3854
3855
            if (api_is_platform_admin()) {
3856
                return true;
3857
            }
3858
3859
            if ($checkSession) {
3860
                if (self::allowed($id)) {
3861
                    return true;
3862
                } else {
3863
                    api_not_allowed(true);
3864
                }
3865
            }
3866
        } else {
3867
            api_not_allowed(true);
3868
        }
3869
    }
3870
3871
    /**
3872
     * @param int $id
3873
     * @return bool
3874
     */
3875
    private static function allowed($id)
3876
    {
3877
        $sessionInfo = self::fetch($id);
3878
3879
        if (empty($sessionInfo)) {
3880
            return false;
3881
        }
3882
3883
        $userId = api_get_user_id();
3884
3885
        if (api_is_session_admin() &&
3886
            api_get_setting('allow_session_admins_to_manage_all_sessions') != 'true'
3887
        ) {
3888
            if ($sessionInfo['session_admin_id'] != $userId) {
3889
                return false;
3890
            }
3891
        }
3892
3893
        if (api_is_teacher() &&
3894
            api_get_setting('allow_teachers_to_create_sessions') == 'true'
3895
        ) {
3896
            if ($sessionInfo['id_coach'] != $userId) {
3897
                return false;
3898
            }
3899
        }
3900
3901
        return true;
3902
    }
3903
3904
    /**
3905
     * @return bool
3906
     */
3907
    public static function allowToManageSessions()
3908
    {
3909
        if (self::allowManageAllSessions()) {
3910
            return true;
3911
        }
3912
3913
        $setting = api_get_setting('allow_teachers_to_create_sessions');
3914
3915
        if (api_is_teacher() && $setting == 'true') {
3916
3917
            return true;
3918
        }
3919
3920
        return false;
3921
    }
3922
3923
    /**
3924
     * @return bool
3925
     */
3926
    public static function allowOnlyMySessions()
3927
    {
3928
        if (self::allowToManageSessions() &&
3929
            !api_is_platform_admin() &&
3930
            api_is_teacher()
3931
        ) {
3932
            return true;
3933
        }
3934
3935
        return false;
3936
    }
3937
3938
    /**
3939
     * @return bool
3940
     */
3941
    public static function allowManageAllSessions()
3942
    {
3943
        if (api_is_platform_admin()) {
3944
            return true;
3945
        }
3946
3947
        return false;
3948
    }
3949
3950
    /**
3951
     * @param $id
3952
     * @return bool
3953
     */
3954
    public static function protect_teacher_session_edit($id)
3955
    {
3956
        if (!api_is_coach($id) && !api_is_platform_admin()) {
3957
            api_not_allowed(true);
3958
        } else {
3959
            return true;
3960
        }
3961
    }
3962
3963
    /**
3964
     * @param int $courseId
3965
     * @return array
3966
     */
3967
    public static function get_session_by_course($courseId)
3968
    {
3969
        $table_session_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
3970
        $table_session = Database::get_main_table(TABLE_MAIN_SESSION);
3971
        $courseId = intval($courseId);
3972
        $sql = "SELECT name, s.id
3973
                FROM $table_session_course sc
3974
                INNER JOIN $table_session s ON (sc.session_id = s.id)
3975
                WHERE sc.c_id = '$courseId' ";
3976
        $result = Database::query($sql);
3977
3978
        return Database::store_result($result);
3979
    }
3980
3981
    /**
3982
     * @param int $user_id
3983
     * @param bool $ignore_visibility_for_admins
3984
     * @param bool $ignoreTimeLimit
3985
     *
3986
     * @return array
3987
     */
3988
    public static function get_sessions_by_user($user_id, $ignore_visibility_for_admins = false, $ignoreTimeLimit = false)
3989
    {
3990
        $sessionCategories = UserManager::get_sessions_by_category(
3991
            $user_id,
3992
            false,
3993
            $ignore_visibility_for_admins,
3994
            $ignoreTimeLimit
3995
        );
3996
        $sessionArray = array();
3997
        if (!empty($sessionCategories)) {
3998
            foreach ($sessionCategories as $category) {
3999
                if (isset($category['sessions'])) {
4000
                    foreach ($category['sessions'] as $session) {
4001
                        $sessionArray[] = $session;
4002
                    }
4003
                }
4004
            }
4005
        }
4006
4007
        return $sessionArray;
4008
    }
4009
4010
    /**
4011
     * @param string $file
4012
     * @param bool $updateSession options:
4013
     *  true: if the session exists it will be updated.
4014
     *  false: if session exists a new session will be created adding a counter session1, session2, etc
4015
     * @param int $defaultUserId
4016
     * @param mixed $logger
4017
     * @param array $extraFields convert a file row to an extra field. Example in CSV file there's a SessionID then it will
4018
     * converted to extra_external_session_id if you set this: array('SessionId' => 'extra_external_session_id')
4019
     * @param string $extraFieldId
4020
     * @param int $daysCoachAccessBeforeBeginning
4021
     * @param int $daysCoachAccessAfterBeginning
4022
     * @param int $sessionVisibility
4023
     * @param array $fieldsToAvoidUpdate
4024
     * @param bool $deleteUsersNotInList
4025
     * @param bool $updateCourseCoaches
4026
     * @param bool $sessionWithCoursesModifier
4027
     * @param int $showDescription
4028
     * @param array $teacherBackupList
4029
     * @param array $groupBackup
4030
     * @return array
4031
     */
4032
    static function importCSV(
4033
        $file,
4034
        $updateSession,
4035
        $defaultUserId = null,
4036
        $logger = null,
4037
        $extraFields = array(),
4038
        $extraFieldId = null,
4039
        $daysCoachAccessBeforeBeginning = null,
4040
        $daysCoachAccessAfterBeginning = null,
4041
        $sessionVisibility = 1,
4042
        $fieldsToAvoidUpdate = array(),
4043
        $deleteUsersNotInList = false,
4044
        $updateCourseCoaches = false,
4045
        $sessionWithCoursesModifier = false,
4046
        $addOriginalCourseTeachersAsCourseSessionCoaches = true,
4047
        $removeAllTeachersFromCourse = true,
4048
        $showDescription = null,
4049
        &$teacherBackupList = array(),
4050
        &$groupBackup = array()
4051
    ) {
4052
        $content = file($file);
4053
4054
        $error_message = null;
4055
        $session_counter = 0;
4056
4057
        if (empty($defaultUserId)) {
4058
            $defaultUserId = api_get_user_id();
4059
        }
4060
4061
        $eol = PHP_EOL;
4062
        if (PHP_SAPI != 'cli') {
4063
            $eol = '<br />';
4064
        }
4065
4066
        $debug = false;
4067
        if (isset($logger)) {
4068
            $debug = true;
4069
        }
4070
4071
        $extraParameters = null;
4072
4073
        if (!empty($daysCoachAccessBeforeBeginning) && !empty($daysCoachAccessAfterBeginning)) {
4074
            $extraParameters .= ' , nb_days_access_before_beginning = '.intval($daysCoachAccessBeforeBeginning);
4075
            $extraParameters .= ' , nb_days_access_after_end = '.intval($daysCoachAccessAfterBeginning);
4076
        }
4077
4078
        if (!is_null($showDescription)) {
4079
            $extraParameters .= ' , show_description = '.intval($showDescription);
4080
        }
4081
4082
        $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
4083
        $tbl_session_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
4084
        $tbl_session_course  = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
4085
        $tbl_session_course_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
4086
4087
        $sessions = array();
4088
4089
        if (!api_strstr($content[0], ';')) {
4090
            $error_message = get_lang('NotCSV');
4091
        } else {
4092
            $tag_names = array();
4093
4094 View Code Duplication
            foreach ($content as $key => $enreg) {
4095
                $enreg = explode(';', trim($enreg));
4096
                if ($key) {
4097
                    foreach ($tag_names as $tag_key => $tag_name) {
4098
                        $sessions[$key - 1][$tag_name] = $enreg[$tag_key];
4099
                    }
4100
                } else {
4101
                    foreach ($enreg as $tag_name) {
4102
                        $tag_names[] = api_preg_replace('/[^a-zA-Z0-9_\-]/', '', $tag_name);
4103
                    }
4104
                    if (!in_array('SessionName', $tag_names) ||
4105
                        !in_array('DateStart', $tag_names) ||
4106
                        !in_array('DateEnd', $tag_names)
4107
                    ) {
4108
                        $error_message = get_lang('NoNeededData');
4109
                        break;
4110
                    }
4111
                }
4112
            }
4113
4114
            $sessionList = array();
4115
            // Looping the sessions.
4116
            foreach ($sessions as $enreg) {
4117
                $user_counter = 0;
4118
                $course_counter = 0;
4119
4120
                if (isset($extraFields) && !empty($extraFields)) {
4121
                    foreach ($extraFields as $original => $to) {
4122
                        $enreg[$to] = isset($enreg[$original]) ? $enreg[$original] : null;
4123
                    }
4124
                }
4125
4126
                $session_name = Database::escape_string($enreg['SessionName']);
4127
                // Default visibility
4128
                $visibilityAfterExpirationPerSession = $sessionVisibility;
4129
4130
                if (isset($enreg['VisibilityAfterExpiration'])) {
4131
                    $visibility = $enreg['VisibilityAfterExpiration'];
4132
                    switch ($visibility) {
4133
                        case 'read_only':
4134
                            $visibilityAfterExpirationPerSession = SESSION_VISIBLE_READ_ONLY;
4135
                            break;
4136
                        case 'accessible':
4137
                            $visibilityAfterExpirationPerSession = SESSION_VISIBLE;
4138
                            break;
4139
                        case 'not_accessible':
4140
                            $visibilityAfterExpirationPerSession = SESSION_INVISIBLE;
4141
                            break;
4142
                    }
4143
                }
4144
4145
                if (empty($session_name)) {
4146
                    continue;
4147
                }
4148
4149
                $date_start = $enreg['DateStart'];
4150
                $date_end = $enreg['DateEnd'];
4151
                $session_category_id = isset($enreg['SessionCategory']) ? $enreg['SessionCategory'] : null;
4152
                $sessionDescription = isset($enreg['SessionDescription']) ? $enreg['SessionDescription'] : null;
4153
4154
                $extraSessionParameters = null;
4155
                if (!empty($sessionDescription)) {
4156
                    $extraSessionParameters = " , description = '".Database::escape_string($sessionDescription)."'";
4157
                }
4158
4159
                // Searching a general coach.
4160
                if (!empty($enreg['Coach'])) {
4161
                    $coach_id = UserManager::get_user_id_from_username($enreg['Coach']);
4162
                    if ($coach_id === false) {
4163
                        // If the coach-user does not exist - I'm the coach.
4164
                        $coach_id = $defaultUserId;
4165
                    }
4166
                } else {
4167
                    $coach_id = $defaultUserId;
4168
                }
4169
4170
                if (!$updateSession) {
4171
                    // Always create a session.
4172
                    $unique_name = false;
4173
                    $i = 0;
4174
                    // Change session name, verify that session doesn't exist.
4175
                    $suffix = null;
4176 View Code Duplication
                    while (!$unique_name) {
4177
                        if ($i > 1) {
4178
                            $suffix = ' - ' . $i;
4179
                        }
4180
                        $sql = 'SELECT 1 FROM ' . $tbl_session . '
4181
                                WHERE name="' . $session_name . $suffix . '"';
4182
                        $rs = Database::query($sql);
4183
4184
                        if (Database::result($rs, 0, 0)) {
4185
                            $i++;
4186
                        } else {
4187
                            $unique_name = true;
4188
                            $session_name .= $suffix;
4189
                        }
4190
                    }
4191
4192
                    $sessionCondition = '';
4193
                    if (!empty($session_category_id)) {
4194
                        $sessionCondition = "session_category_id = '$session_category_id',";
4195
                    }
4196
4197
                    // Creating the session.
4198
                    $sql = "INSERT IGNORE INTO $tbl_session SET
4199
                            name = '" . $session_name . "',
4200
                            id_coach = '$coach_id',
4201
                            access_start_date = '$date_start',
4202
                            access_end_date = '$date_end',
4203
                            visibility = '$visibilityAfterExpirationPerSession',
4204
                            $sessionCondition
4205
                            session_admin_id = " . intval($defaultUserId) . $extraParameters . $extraSessionParameters;
4206
                    Database::query($sql);
4207
4208
                    $session_id = Database::insert_id();
4209
                    if ($debug) {
4210
                        if ($session_id) {
4211 View Code Duplication
                            foreach ($enreg as $key => $value) {
4212
                                if (substr($key, 0, 6) == 'extra_') { //an extra field
4213
                                    self::update_session_extra_field_value($session_id, substr($key, 6), $value);
4214
                                }
4215
                            }
4216
4217
                            $logger->addInfo("Sessions - Session created: #$session_id - $session_name");
4218
                        } else {
4219
                            $logger->addError("Sessions - Session NOT created: $session_name");
4220
                        }
4221
                    }
4222
                    $session_counter++;
4223
                } else {
4224
                    $sessionId = null;
4225
                    if (isset($extraFields) && !empty($extraFields) && !empty($enreg['extra_'.$extraFieldId])) {
4226
                        $sessionId = self::getSessionIdFromOriginalId($enreg['extra_'.$extraFieldId], $extraFieldId);
4227
                        if (empty($sessionId)) {
4228
                            $my_session_result = false;
4229
                        } else {
4230
                            $my_session_result = true;
4231
                        }
4232
                    } else {
4233
                        $my_session_result = self::get_session_by_name($enreg['SessionName']);
4234
                    }
4235
4236
                    if ($my_session_result === false) {
4237
4238
                        // Creating a session.
4239
                        $sql = "INSERT IGNORE INTO $tbl_session SET
4240
                                name = '$session_name',
4241
                                id_coach = '$coach_id',
4242
                                access_start_date = '$date_start',
4243
                                access_end_date = '$date_end',
4244
                                visibility = '$visibilityAfterExpirationPerSession',
4245
                                session_category_id = '$session_category_id' " . $extraParameters . $extraSessionParameters;
4246
4247
                        Database::query($sql);
4248
4249
                        // We get the last insert id.
4250
                        $my_session_result = SessionManager::get_session_by_name($enreg['SessionName']);
4251
                        $session_id = $my_session_result['id'];
4252
4253
                        if ($session_id) {
4254 View Code Duplication
                            foreach ($enreg as $key => $value) {
4255
                                if (substr($key, 0, 6) == 'extra_') { //an extra field
4256
                                    self::update_session_extra_field_value($session_id, substr($key, 6), $value);
4257
                                }
4258
                            }
4259
                            if ($debug) {
4260
                                $logger->addInfo("Sessions - #$session_id created: $session_name");
4261
                            }
4262
4263
                            // Delete session-user relation only for students
4264
                            $sql = "DELETE FROM $tbl_session_user
4265
                                    WHERE session_id = '$session_id' AND relation_type <> " . SESSION_RELATION_TYPE_RRHH;
4266
                            Database::query($sql);
4267
4268
                            $sql = "DELETE FROM $tbl_session_course WHERE session_id = '$session_id'";
4269
                            Database::query($sql);
4270
4271
                            // Delete session-course-user relationships students and coaches.
4272 View Code Duplication
                            if ($updateCourseCoaches) {
4273
                                $sql = "DELETE FROM $tbl_session_course_user
4274
                                        WHERE session_id = '$session_id' AND status in ('0', '2')";
4275
                                Database::query($sql);
4276
                            } else {
4277
                                // Delete session-course-user relation ships *only* for students.
4278
                                $sql = "DELETE FROM $tbl_session_course_user
4279
                                        WHERE session_id = '$session_id' AND status <> 2";
4280
                                Database::query($sql);
4281
                            }
4282
                        }
4283
                    } else {
4284
                        if ($debug) {
4285
                            $logger->addError("Sessions - Session to be updated: $session_name");
4286
                        }
4287
4288
                        // Updating the session.
4289
                        $params = array(
4290
                            'id_coach' => $coach_id,
4291
                            'access_start_date' => $date_start,
4292
                            'access_end_date' => $date_end,
4293
                            'visibility' => $visibilityAfterExpirationPerSession,
4294
                            'session_category_id' => $session_category_id,
4295
                        );
4296
4297
                        if (!empty($sessionDescription)) {
4298
                            $params['description'] = $sessionDescription;
4299
                        }
4300
4301
                        if (!empty($fieldsToAvoidUpdate)) {
4302
                            foreach ($fieldsToAvoidUpdate as $field) {
4303
                                unset($params[$field]);
4304
                            }
4305
                        }
4306
4307 View Code Duplication
                        if (isset($sessionId) && !empty($sessionId)) {
4308
                            if (!empty($enreg['SessionName'])) {
4309
                                $params['name'] = $enreg['SessionName'];
4310
                            }
4311
                            $session_id = $sessionId;
4312
                        } else {
4313
                            $row = Database::query("SELECT id FROM $tbl_session WHERE name = '$session_name'");
4314
                            list($session_id) = Database::fetch_array($row);
0 ignored issues
show
Bug introduced by
It seems like $row 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...
4315
                        }
4316
4317
                        if ($session_id) {
4318
4319
                            if ($debug) {
4320
                                $logger->addError("Sessions - Session to be updated #$session_id");
4321
                            }
4322
4323
                            $sessionInfo = api_get_session_info($session_id);
4324
4325
                            $params['show_description'] = isset($sessionInfo['show_description']) ? $sessionInfo['show_description'] : intval($showDescription);
4326
4327
                            if (!empty($daysCoachAccessBeforeBeginning) && !empty($daysCoachAccessAfterBeginning)) {
4328 View Code Duplication
                                if (empty($sessionInfo['nb_days_access_before_beginning']) ||
4329
                                    (!empty($sessionInfo['nb_days_access_before_beginning']) &&
4330
                                        $sessionInfo['nb_days_access_before_beginning'] < $daysCoachAccessBeforeBeginning)
4331
                                ) {
4332
                                    $params['nb_days_access_before_beginning'] = intval($daysCoachAccessBeforeBeginning);
4333
                                }
4334
4335 View Code Duplication
                                if (empty($sessionInfo['nb_days_access_after_end']) ||
4336
                                    (!empty($sessionInfo['nb_days_access_after_end']) &&
4337
                                        $sessionInfo['nb_days_access_after_end'] < $daysCoachAccessAfterBeginning)
4338
                                ) {
4339
                                    $params['nb_days_access_after_end'] = intval($daysCoachAccessAfterBeginning);
4340
                                }
4341
                            }
4342
4343
                            Database::update($tbl_session, $params, array('id = ?' => $session_id));
4344
4345 View Code Duplication
                            foreach ($enreg as $key => $value) {
4346
                                if (substr($key, 0, 6) == 'extra_') { //an extra field
4347
                                    self::update_session_extra_field_value($session_id, substr($key, 6), $value);
4348
                                }
4349
                            }
4350
4351
                            // Delete session-user relation only for students
4352
                            $sql = "DELETE FROM $tbl_session_user
4353
                                    WHERE session_id = '$session_id' AND relation_type <> " . SESSION_RELATION_TYPE_RRHH;
4354
                            Database::query($sql);
4355
4356
                            $sql = "DELETE FROM $tbl_session_course WHERE session_id = '$session_id'";
4357
                            Database::query($sql);
4358
4359
                            // Delete session-course-user relationships students and coaches.
4360 View Code Duplication
                            if ($updateCourseCoaches) {
4361
                                $sql = "DELETE FROM $tbl_session_course_user
4362
                                        WHERE session_id = '$session_id' AND status in ('0', '2')";
4363
                                Database::query($sql);
4364
                            } else {
4365
                                // Delete session-course-user relation ships *only* for students.
4366
                                $sql = "DELETE FROM $tbl_session_course_user
4367
                                        WHERE session_id = '$session_id' AND status <> 2";
4368
                                Database::query($sql);
4369
                            }
4370
                        } else {
4371
                            if ($debug) {
4372
                                $logger->addError(
4373
                                    "Sessions - Session not found"
4374
                                );
4375
                            }
4376
                        }
4377
                    }
4378
                    $session_counter++;
4379
                }
4380
4381
                $sessionList[] = $session_id;
4382
                $users = explode('|', $enreg['Users']);
4383
4384
                // Adding the relationship "Session - User" for students
4385
                $userList = array();
4386
4387
                if (is_array($users)) {
4388
                    foreach ($users as $user) {
4389
                        $user_id = UserManager::get_user_id_from_username($user);
4390
                        if ($user_id !== false) {
4391
                            $userList[] = $user_id;
4392
                            // Insert new users.
4393
                            $sql = "INSERT IGNORE INTO $tbl_session_user SET
4394
                                    user_id = '$user_id',
4395
                                    session_id = '$session_id',
4396
                                    registered_at = '" . api_get_utc_datetime() . "'";
4397
                            Database::query($sql);
4398
                            if ($debug) {
4399
                                $logger->addInfo("Sessions - Adding User #$user_id ($user) to session #$session_id");
4400
                            }
4401
                            $user_counter++;
4402
                        }
4403
                    }
4404
                }
4405
4406
                if ($deleteUsersNotInList) {
4407
                    // Getting user in DB in order to compare to the new list.
4408
                    $usersListInDatabase = self::get_users_by_session($session_id, 0);
4409
4410
                    if (!empty($usersListInDatabase)) {
4411
                        if (empty($userList)) {
4412
                            foreach ($usersListInDatabase as $userInfo) {
4413
                                self::unsubscribe_user_from_session($session_id, $userInfo['user_id']);
4414
                            }
4415
                        } else {
4416
                            foreach ($usersListInDatabase as $userInfo) {
4417
                                if (!in_array($userInfo['user_id'], $userList)) {
4418
                                    self::unsubscribe_user_from_session($session_id, $userInfo['user_id']);
4419
                                }
4420
                            }
4421
                        }
4422
                    }
4423
                }
4424
4425
                $courses = explode('|', $enreg['Courses']);
4426
4427
                // See BT#6449
4428
                $onlyAddFirstCoachOrTeacher = false;
4429
4430
                if ($sessionWithCoursesModifier) {
4431
                    if (count($courses) >= 2) {
4432
                        // Only first teacher in course session;
4433
                        $onlyAddFirstCoachOrTeacher = true;
4434
4435
                        // Remove all teachers from course.
4436
                        $removeAllTeachersFromCourse = false;
4437
                    }
4438
                }
4439
4440
                foreach ($courses as $course) {
4441
                    $courseArray = bracketsToArray($course);
4442
                    $course_code = $courseArray[0];
4443
4444
                    if (CourseManager::course_exists($course_code)) {
4445
4446
                        $courseInfo = api_get_course_info($course_code);
4447
                        $courseId = $courseInfo['real_id'];
4448
4449
                        // Adding the course to a session.
4450
                        $sql = "INSERT IGNORE INTO $tbl_session_course
4451
                                SET c_id = '$courseId', session_id='$session_id'";
4452
                        Database::query($sql);
4453
4454
                        SessionManager::installCourse($session_id, $courseInfo['real_id']);
4455
4456
                        if ($debug) {
4457
                            $logger->addInfo("Sessions - Adding course '$course_code' to session #$session_id");
4458
                        }
4459
4460
                        $course_counter++;
4461
4462
                        $course_coaches = isset($courseArray[1]) ? $courseArray[1] : null;
4463
                        $course_users   = isset($courseArray[2]) ? $courseArray[2] : null;
4464
4465
                        $course_users   = explode(',', $course_users);
4466
                        $course_coaches = explode(',', $course_coaches);
4467
4468
                        // Checking if the flag is set TeachersWillBeAddedAsCoachInAllCourseSessions (course_edit.php)
4469
                        $addTeachersToSession = true;
4470
4471
                        if (array_key_exists('add_teachers_to_sessions_courses', $courseInfo)) {
4472
                            $addTeachersToSession = $courseInfo['add_teachers_to_sessions_courses'];
4473
                        }
4474
4475
                        // If any user provided for a course, use the users array.
4476
                        if (empty($course_users)) {
4477
                            if (!empty($userList)) {
4478
                                SessionManager::subscribe_users_to_session_course(
4479
                                    $userList,
4480
                                    $session_id,
4481
                                    $course_code
4482
                                );
4483
                                if ($debug) {
4484
                                    $msg = "Sessions - Adding student list ".implode(', #', $userList)." to course: '$course_code' and session #$session_id";
4485
                                    $logger->addInfo($msg);
4486
                                }
4487
                            }
4488
                        }
4489
4490
                        // Adding coaches to session course user.
4491
                        if (!empty($course_coaches)) {
4492
                            $savedCoaches = array();
4493
                            // only edit if add_teachers_to_sessions_courses is set.
4494
                            if ($addTeachersToSession) {
4495
                                if ($addOriginalCourseTeachersAsCourseSessionCoaches) {
4496
                                    // Adding course teachers as course session teachers.
4497
                                    $alreadyAddedTeachers = CourseManager::get_teacher_list_from_course_code(
4498
                                        $course_code
4499
                                    );
4500
4501
                                    if (!empty($alreadyAddedTeachers)) {
4502
                                        $teachersToAdd = array();
4503
                                        foreach ($alreadyAddedTeachers as $user) {
4504
                                            $teachersToAdd[] = $user['username'];
4505
                                        }
4506
                                        $course_coaches = array_merge(
4507
                                            $course_coaches,
4508
                                            $teachersToAdd
4509
                                        );
4510
                                    }
4511
                                }
4512
4513 View Code Duplication
                                foreach ($course_coaches as $course_coach) {
4514
                                    $coach_id = UserManager::get_user_id_from_username($course_coach);
4515
                                    if ($coach_id !== false) {
4516
                                        // Just insert new coaches
4517
                                        SessionManager::updateCoaches($session_id, $courseId, array($coach_id), false);
4518
4519
                                        if ($debug) {
4520
                                            $logger->addInfo("Sessions - Adding course coach: user #$coach_id ($course_coach) to course: '$course_code' and session #$session_id");
4521
                                        }
4522
                                        $savedCoaches[] = $coach_id;
4523
                                    } else {
4524
                                        $error_message .= get_lang('UserDoesNotExist').' : '.$course_coach.$eol;
4525
                                    }
4526
                                }
4527
                            }
4528
4529
                            // Custom courses/session coaches
4530
                            $teacherToAdd = null;
4531
                            // Only one coach is added.
4532
                            if ($onlyAddFirstCoachOrTeacher == true) {
4533
4534 View Code Duplication
                                foreach ($course_coaches as $course_coach) {
4535
                                    $coach_id = UserManager::get_user_id_from_username($course_coach);
4536
                                    if ($coach_id !== false) {
4537
                                        $teacherToAdd = $coach_id;
4538
                                        break;
4539
                                    }
4540
                                }
4541
4542
                                // Un subscribe everyone that's not in the list.
4543
                                $teacherList = CourseManager::get_teacher_list_from_course_code($course_code);
4544 View Code Duplication
                                if (!empty($teacherList)) {
4545
                                    foreach ($teacherList as $teacher) {
4546
                                        if ($teacherToAdd != $teacher['user_id']) {
4547
4548
                                            $sql = "SELECT * FROM ".Database::get_main_table(TABLE_MAIN_COURSE_USER)."
4549
                                                    WHERE
4550
                                                        user_id = ".$teacher['user_id']." AND
4551
                                                        course_code = '".$course_code."'
4552
                                                    ";
4553
4554
                                            $result = Database::query($sql);
4555
                                            $userCourseData = Database::fetch_array($result, 'ASSOC');
4556
                                            $teacherBackupList[$teacher['user_id']][$course_code] = $userCourseData;
4557
4558
                                            $sql = "SELECT * FROM ".Database::get_course_table(TABLE_GROUP_USER)."
4559
                                                    WHERE
4560
                                                        user_id = ".$teacher['user_id']." AND
4561
                                                        c_id = '".$courseInfo['real_id']."'
4562
                                                    ";
4563
4564
                                            $result = Database::query($sql);
4565
                                            while ($groupData = Database::fetch_array($result, 'ASSOC')) {
4566
                                                $groupBackup['user'][$teacher['user_id']][$course_code][$groupData['group_id']] = $groupData;
4567
                                            }
4568
4569
                                            $sql = "SELECT * FROM ".Database::get_course_table(TABLE_GROUP_TUTOR)."
4570
                                                    WHERE
4571
                                                        user_id = ".$teacher['user_id']." AND
4572
                                                        c_id = '".$courseInfo['real_id']."'
4573
                                                    ";
4574
4575
                                            $result = Database::query($sql);
4576
                                            while ($groupData = Database::fetch_array($result, 'ASSOC')) {
4577
                                                $groupBackup['tutor'][$teacher['user_id']][$course_code][$groupData['group_id']] = $groupData;
4578
                                            }
4579
4580
                                            CourseManager::unsubscribe_user(
4581
                                                $teacher['user_id'],
4582
                                                $course_code
4583
                                            );
4584
                                        }
4585
                                    }
4586
                                }
4587
4588
                                if (!empty($teacherToAdd)) {
4589
                                    SessionManager::updateCoaches($session_id, $courseId, array($teacherToAdd), true);
4590
4591
                                    $userCourseCategory = '';
4592 View Code Duplication
                                    if (isset($teacherBackupList[$teacherToAdd]) &&
4593
                                        isset($teacherBackupList[$teacherToAdd][$course_code])
4594
                                    ) {
4595
                                        $courseUserData = $teacherBackupList[$teacherToAdd][$course_code];
4596
                                        $userCourseCategory = $courseUserData['user_course_cat'];
4597
                                    }
4598
4599
                                    CourseManager::subscribe_user(
4600
                                        $teacherToAdd,
4601
                                        $course_code,
4602
                                        COURSEMANAGER,
4603
                                        0,
4604
                                        $userCourseCategory
4605
                                    );
4606
4607 View Code Duplication
                                    if (isset($groupBackup['user'][$teacherToAdd]) &&
4608
                                        isset($groupBackup['user'][$teacherToAdd][$course_code]) &&
4609
                                        !empty($groupBackup['user'][$teacherToAdd][$course_code])
4610
                                    ) {
4611
                                        foreach ($groupBackup['user'][$teacherToAdd][$course_code] as $data) {
4612
                                            GroupManager::subscribe_users(
4613
                                                $teacherToAdd,
4614
                                                $data['group_id'],
4615
                                                $data['c_id']
4616
                                            );
4617
                                        }
4618
                                    }
4619
4620 View Code Duplication
                                    if (isset($groupBackup['tutor'][$teacherToAdd]) &&
4621
                                        isset($groupBackup['tutor'][$teacherToAdd][$course_code]) &&
4622
                                        !empty($groupBackup['tutor'][$teacherToAdd][$course_code])
4623
                                    ) {
4624
                                        foreach ($groupBackup['tutor'][$teacherToAdd][$course_code] as $data) {
4625
                                            GroupManager::subscribe_tutors(
4626
                                                $teacherToAdd,
4627
                                                $data['group_id'],
4628
                                                $data['c_id']
4629
                                            );
4630
                                        }
4631
                                    }
4632
                                }
4633
                            }
4634
4635
                            // See BT#6449#note-195
4636
                            // All coaches are added.
4637
                            if ($removeAllTeachersFromCourse) {
4638
                                $teacherToAdd = null;
4639 View Code Duplication
                                foreach ($course_coaches as $course_coach) {
4640
                                    $coach_id = UserManager::get_user_id_from_username(
4641
                                        $course_coach
4642
                                    );
4643
                                    if ($coach_id !== false) {
4644
                                        $teacherToAdd[] = $coach_id;
4645
                                    }
4646
                                }
4647
4648
                                if (!empty($teacherToAdd)) {
4649
                                    // Deleting all course teachers and adding the only coach as teacher.
4650
                                    $teacherList = CourseManager::get_teacher_list_from_course_code($course_code);
4651
4652 View Code Duplication
                                    if (!empty($teacherList)) {
4653
                                        foreach ($teacherList as $teacher) {
4654
                                            if (!in_array($teacher['user_id'], $teacherToAdd)) {
4655
4656
                                                $sql = "SELECT * FROM ".Database::get_main_table(TABLE_MAIN_COURSE_USER)."
4657
                                                        WHERE
4658
                                                            user_id = ".$teacher['user_id']." AND
4659
                                                            course_code = '".$course_code."'
4660
                                                        ";
4661
4662
                                                $result = Database::query($sql);
4663
                                                $userCourseData = Database::fetch_array($result, 'ASSOC');
4664
                                                $teacherBackupList[$teacher['user_id']][$course_code] = $userCourseData;
4665
4666
                                                $sql = "SELECT * FROM ".Database::get_course_table(TABLE_GROUP_USER)."
4667
                                                    WHERE
4668
                                                        user_id = ".$teacher['user_id']." AND
4669
                                                        c_id = '".$courseInfo['real_id']."'
4670
                                                    ";
4671
4672
                                                $result = Database::query($sql);
4673
                                                while ($groupData = Database::fetch_array($result, 'ASSOC')) {
4674
                                                    $groupBackup['user'][$teacher['user_id']][$course_code][$groupData['group_id']] = $groupData;
4675
                                                }
4676
4677
                                                $sql = "SELECT * FROM ".Database::get_course_table(TABLE_GROUP_TUTOR)."
4678
                                                        WHERE
4679
                                                            user_id = ".$teacher['user_id']." AND
4680
                                                            c_id = '".$courseInfo['real_id']."'
4681
                                                        ";
4682
4683
                                                $result = Database::query($sql);
4684
                                                while ($groupData = Database::fetch_array($result, 'ASSOC')) {
4685
                                                    $groupBackup['tutor'][$teacher['user_id']][$course_code][$groupData['group_id']] = $groupData;
4686
                                                }
4687
4688
                                                CourseManager::unsubscribe_user(
4689
                                                    $teacher['user_id'],
4690
                                                    $course_code
4691
                                                );
4692
                                            }
4693
                                        }
4694
                                    }
4695
4696
                                    foreach ($teacherToAdd as $teacherId) {
4697
                                        $userCourseCategory = '';
4698 View Code Duplication
                                        if (isset($teacherBackupList[$teacherId]) &&
4699
                                            isset($teacherBackupList[$teacherId][$course_code])
4700
                                        ) {
4701
                                            $courseUserData = $teacherBackupList[$teacherId][$course_code];
4702
                                            $userCourseCategory = $courseUserData['user_course_cat'];
4703
                                        }
4704
4705
                                        CourseManager::subscribe_user(
4706
                                            $teacherId,
4707
                                            $course_code,
4708
                                            COURSEMANAGER,
4709
                                            0,
4710
                                            $userCourseCategory
4711
                                        );
4712
4713 View Code Duplication
                                        if (isset($groupBackup['user'][$teacherId]) &&
4714
                                            isset($groupBackup['user'][$teacherId][$course_code]) &&
4715
                                            !empty($groupBackup['user'][$teacherId][$course_code])
4716
                                        ) {
4717
                                            foreach ($groupBackup['user'][$teacherId][$course_code] as $data) {
4718
                                                GroupManager::subscribe_users(
4719
                                                    $teacherId,
4720
                                                    $data['group_id'],
4721
                                                    $data['c_id']
4722
                                                );
4723
                                            }
4724
                                        }
4725
4726 View Code Duplication
                                        if (isset($groupBackup['tutor'][$teacherId]) &&
4727
                                            isset($groupBackup['tutor'][$teacherId][$course_code]) &&
4728
                                            !empty($groupBackup['tutor'][$teacherId][$course_code])
4729
                                        ) {
4730
                                            foreach ($groupBackup['tutor'][$teacherId][$course_code] as $data) {
4731
                                                GroupManager::subscribe_tutors(
4732
                                                    $teacherId,
4733
                                                    $data['group_id'],
4734
                                                    $data['c_id']
4735
                                                );
4736
                                            }
4737
                                        }
4738
                                    }
4739
                                }
4740
                            }
4741
4742
                            // Continue default behaviour.
4743
                            if ($onlyAddFirstCoachOrTeacher == false) {
4744
                                // Checking one more time see BT#6449#note-149
4745
                                $coaches = SessionManager::getCoachesByCourseSession($session_id, $courseId);
4746
                                // Update coaches if only there's 1 course see BT#6449#note-189
4747
                                if (empty($coaches) || count($courses) == 1) {
4748 View Code Duplication
                                    foreach ($course_coaches as $course_coach) {
4749
                                        $course_coach = trim($course_coach);
4750
                                        $coach_id = UserManager::get_user_id_from_username($course_coach);
4751
                                        if ($coach_id !== false) {
4752
                                            // Just insert new coaches
4753
                                            SessionManager::updateCoaches(
4754
                                                $session_id,
4755
                                                $courseId,
4756
                                                array($coach_id),
4757
                                                false
4758
                                            );
4759
4760
                                            if ($debug) {
4761
                                                $logger->addInfo("Sessions - Adding course coach: user #$coach_id ($course_coach) to course: '$course_code' and session #$session_id");
4762
                                            }
4763
                                            $savedCoaches[] = $coach_id;
4764
                                        } else {
4765
                                            $error_message .= get_lang('UserDoesNotExist').' : '.$course_coach.$eol;
4766
                                        }
4767
                                    }
4768
                                }
4769
                            }
4770
                        }
4771
4772
                        // Adding Students, updating relationship "Session - Course - User".
4773
                        $course_users = array_filter($course_users);
4774
4775
                        if (!empty($course_users)) {
4776 View Code Duplication
                            foreach ($course_users as $user) {
4777
                                $user_id = UserManager::get_user_id_from_username($user);
4778
4779
                                if ($user_id !== false) {
4780
                                    SessionManager::subscribe_users_to_session_course(
4781
                                        array($user_id),
4782
                                        $session_id,
4783
                                        $course_code
4784
                                    );
4785
                                    if ($debug) {
4786
                                        $logger->addInfo("Sessions - Adding student: user #$user_id ($user) to course: '$course_code' and session #$session_id");
4787
                                    }
4788
                                } else {
4789
                                    $error_message .= get_lang('UserDoesNotExist').': '.$user.$eol;
4790
                                }
4791
                            }
4792
                        }
4793
4794
                        $inserted_in_course[$course_code] = $courseInfo['title'];
4795
                    }
4796
                }
4797
                $access_url_id = api_get_current_access_url_id();
4798
                UrlManager::add_session_to_url($session_id, $access_url_id);
4799
                $sql = "UPDATE $tbl_session SET nbr_users = '$user_counter', nbr_courses = '$course_counter' WHERE id = '$session_id'";
4800
                Database::query($sql);
4801
            }
4802
        }
4803
4804
        return array(
4805
            'error_message' => $error_message,
4806
            'session_counter' => $session_counter,
4807
            'session_list' => $sessionList,
4808
        );
4809
    }
4810
4811
    /**
4812
     * @param int $sessionId
4813
     * @param int $courseId
4814
     * @return array
4815
     */
4816 View Code Duplication
    public static function getCoachesByCourseSession($sessionId, $courseId)
4817
    {
4818
        $table = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
4819
        $sessionId = intval($sessionId);
4820
        $courseId = intval($courseId);
4821
4822
        $sql = "SELECT user_id FROM $table
4823
                WHERE
4824
                    session_id = '$sessionId' AND
4825
                    c_id = '$courseId' AND
4826
                    status = 2";
4827
        $result = Database::query($sql);
4828
4829
        $coaches = array();
4830
        if (Database::num_rows($result) > 0) {
4831
            while ($row = Database::fetch_row($result)) {
4832
                $coaches[] = $row[0];
4833
            }
4834
        }
4835
4836
        return $coaches;
4837
    }
4838
4839
    /**
4840
     * @param int $sessionId
4841
     * @param int $courseId
4842
     * @return string
4843
     */
4844
    public static function getCoachesByCourseSessionToString(
4845
        $sessionId,
4846
        $courseId
4847
    ) {
4848
        $coaches = self::getCoachesByCourseSession($sessionId, $courseId);
4849
        $list = array();
4850 View Code Duplication
        if (!empty($coaches)) {
4851
            foreach ($coaches as $coachId) {
4852
                $userInfo = api_get_user_info($coachId);
4853
                $list[] = api_get_person_name(
4854
                    $userInfo['firstname'],
4855
                    $userInfo['lastname']
4856
                );
4857
            }
4858
        }
4859
4860
        return array_to_string($list, CourseManager::USER_SEPARATOR);
4861
    }
4862
4863
    /**
4864
     * Get all coaches added in the session - course relationship
4865
     * @param int $sessionId
4866
     * @return array
4867
     */
4868
    public static function getCoachesBySession($sessionId)
4869
    {
4870
        $table = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
4871
        $sessionId = intval($sessionId);
4872
4873
        $sql = "SELECT DISTINCT user_id
4874
                FROM $table
4875
                WHERE session_id = '$sessionId' AND status = 2";
4876
        $result = Database::query($sql);
4877
4878
        $coaches = array();
4879
        if (Database::num_rows($result) > 0) {
4880
            while ($row = Database::fetch_array($result)) {
4881
                $coaches[] = $row['user_id'];
4882
            }
4883
        }
4884
4885
        return $coaches;
4886
    }
4887
4888
    /**
4889
     * @param int $userId
4890
     * @return array
4891
     */
4892
    public static function getAllCoursesFromAllSessionFromDrh($userId)
4893
    {
4894
        $sessions = SessionManager::get_sessions_followed_by_drh($userId);
4895
        $coursesFromSession = array();
4896
        if (!empty($sessions)) {
4897
            foreach ($sessions as $session) {
4898
                $courseList = SessionManager::get_course_list_by_session_id($session['id']);
4899
                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...
4900
                    $coursesFromSession[] = $course['code'];
4901
                }
4902
            }
4903
        }
4904
        return $coursesFromSession;
4905
    }
4906
4907
    /**
4908
     * @param string $status
4909
     * @param int $userId
4910
     * @param bool $getCount
4911
     * @param int  $from
4912
     * @param int  $numberItems
4913
     * @param int $column
4914
     * @param string $direction
4915
     * @param string $keyword
4916
     * @param string $active
4917
     * @param string $lastConnectionDate
4918
     * @param array $sessionIdList
4919
     * @param array $studentIdList
4920
     * @param int $filterByStatus
4921
     * @return array|int
4922
     */
4923
    public static function getAllUsersFromCoursesFromAllSessionFromStatus(
4924
        $status,
4925
        $userId,
4926
        $getCount = false,
4927
        $from = null,
4928
        $numberItems = null,
4929
        $column = 1,
4930
        $direction = 'asc',
4931
        $keyword = null,
4932
        $active = null,
4933
        $lastConnectionDate = null,
4934
        $sessionIdList = array(),
4935
        $studentIdList = array(),
4936
        $filterByStatus = null
4937
    ) {
4938
        $filterByStatus = intval($filterByStatus);
4939
4940
        $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
4941
        $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
4942
        $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
4943
        $tbl_course_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
4944
        $tbl_course_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
4945
        $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
4946
        $tbl_session_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
4947
4948
        $direction = in_array(strtolower($direction), array('asc', 'desc')) ? $direction : 'asc';
4949
        $column = Database::escape_string($column);
4950
        $userId = intval($userId);
4951
4952
        $limitCondition = null;
4953
4954 View Code Duplication
        if (isset($from) && isset($numberItems)) {
4955
            $from = intval($from);
4956
            $numberItems = intval($numberItems);
4957
            $limitCondition = "LIMIT $from, $numberItems";
4958
        }
4959
4960
        $urlId = api_get_current_access_url_id();
4961
4962
        $sessionConditions = null;
4963
        $courseConditions = null;
4964
        $userConditions = null;
4965
4966
        if (isset($active)) {
4967
            $active = intval($active);
4968
            $userConditions .= " AND active = $active";
4969
        }
4970
4971
        switch ($status) {
4972
            case 'drh':
4973
                // Classic DRH
4974
                if (empty($studentIdList)) {
4975
                    $studentListSql = UserManager::get_users_followed_by_drh(
4976
                        $userId,
4977
                        $filterByStatus,
4978
                        true,
4979
                        false
4980
                    );
4981
                    $studentIdList = array_keys($studentListSql);
4982
                    $studentListSql = "'".implode("','", $studentIdList)."'";
4983
                } else {
4984
                    $studentIdList = array_map('intval', $studentIdList);
4985
                    $studentListSql = "'".implode("','", $studentIdList)."'";
4986
                }
4987
                if (!empty($studentListSql)) {
4988
                    $userConditions = " AND u.user_id IN (".$studentListSql.") ";
4989
                }
4990
                break;
4991
            case 'drh_all':
4992
                // Show all by DRH
4993
                if (empty($sessionIdList)) {
4994
                    $sessionsListSql = SessionManager::get_sessions_followed_by_drh(
4995
                        $userId,
4996
                        null,
4997
                        null,
4998
                        false,
4999
                        true,
5000
                        true
5001
                    );
5002
                } else {
5003
                    $sessionIdList = array_map('intval', $sessionIdList);
5004
                    $sessionsListSql = "'".implode("','", $sessionIdList)."'";
5005
                }
5006
                if (!empty($sessionsListSql)) {
5007
                    $sessionConditions = " AND s.id IN (".$sessionsListSql.") ";
5008
                }
5009
                break;
5010
            case 'session_admin';
0 ignored issues
show
Coding Style introduced by
case statements should be defined using a colon.

As per the PSR-2 coding standard, case statements should not be wrapped in curly braces. There is no need for braces, since each case is terminated by the next break.

There is also the option to use a semicolon instead of a colon, this is discouraged because many programmers do not even know it works and the colon is universal between programming languages.

switch ($expr) {
    case "A": { //wrong
        doSomething();
        break;
    }
    case "B"; //wrong
        doSomething();
        break;
    case "C": //right
        doSomething();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
5011
                $sessionConditions = " AND s.id_coach = $userId ";
5012
                break;
5013
            case 'admin':
5014
                break;
5015
            case 'teacher':
5016
                $sessionConditions = " AND s.id_coach = $userId ";
5017
                break;
5018
        }
5019
5020
        $select = "SELECT DISTINCT u.* ";
5021
        $masterSelect = "SELECT DISTINCT * FROM ";
5022
5023
        if ($getCount) {
5024
            $select = "SELECT DISTINCT u.user_id ";
5025
            $masterSelect = "SELECT COUNT(DISTINCT(user_id)) as count FROM ";
5026
        }
5027
5028
        if (!empty($filterByStatus)) {
5029
            $userConditions .= " AND u.status = ".$filterByStatus;
5030
        }
5031
5032
        if (!empty($lastConnectionDate)) {
5033
            $lastConnectionDate = Database::escape_string($lastConnectionDate);
5034
            $userConditions .=  " AND u.last_login <= '$lastConnectionDate' ";
5035
        }
5036
5037 View Code Duplication
        if (!empty($keyword)) {
5038
            $keyword = Database::escape_string($keyword);
5039
            $userConditions .= " AND (
5040
                u.username LIKE '%$keyword%' OR
5041
                u.firstname LIKE '%$keyword%' OR
5042
                u.lastname LIKE '%$keyword%' OR
5043
                u.official_code LIKE '%$keyword%' OR
5044
                u.email LIKE '%$keyword%'
5045
            )";
5046
        }
5047
5048
        $where = " WHERE
5049
                   access_url_id = $urlId
5050
                   $userConditions
5051
        ";
5052
5053
        $sql = "$masterSelect (
5054
                ($select
5055
                FROM $tbl_session s
5056
                    INNER JOIN $tbl_session_rel_course_rel_user su ON (s.id = su.session_id)
5057
                    INNER JOIN $tbl_user u ON (u.user_id = su.user_id)
5058
                    INNER JOIN $tbl_session_rel_access_url url ON (url.session_id = s.id)
5059
                    $where
5060
                    $sessionConditions
5061
                )
5062
                UNION (
5063
                    $select
5064
                    FROM $tbl_course c
5065
                    INNER JOIN $tbl_course_user cu ON (cu.c_id = c.id)
5066
                    INNER JOIN $tbl_user u ON (u.user_id = cu.user_id)
5067
                    INNER JOIN $tbl_course_rel_access_url url ON (url.c_id = c.id)
5068
                    $where
5069
                    $courseConditions
5070
                )
5071
                ) as t1
5072
                ";
5073
5074
        if ($getCount) {
5075
            $result = Database::query($sql);
5076
            $count = 0;
5077
            if (Database::num_rows($result)) {
5078
                $rows = Database::fetch_array($result);
5079
                $count = $rows['count'];
5080
            }
5081
            return $count;
5082
        }
5083
5084 View Code Duplication
        if (!empty($column) && !empty($direction)) {
5085
            $column = str_replace('u.', '', $column);
5086
            $sql .= " ORDER BY $column $direction ";
5087
        }
5088
5089
        $sql .= $limitCondition;
5090
        $result = Database::query($sql);
5091
        $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...
5092
5093
        return $result ;
5094
    }
5095
5096
    /**
5097
     * @param int $sessionId
5098
     * @param int $courseId
5099
     * @param array $coachList
5100
     * @param bool $deleteCoachesNotInList
5101
     */
5102
    public static function updateCoaches(
5103
        $sessionId,
5104
        $courseId,
5105
        $coachList,
5106
        $deleteCoachesNotInList = false
5107
    ) {
5108
        $currentCoaches = self::getCoachesByCourseSession($sessionId, $courseId);
5109
5110
        if (!empty($coachList)) {
5111
            foreach ($coachList as $userId) {
5112
                self::set_coach_to_course_session($userId, $sessionId, $courseId);
5113
            }
5114
        }
5115
5116
        if ($deleteCoachesNotInList) {
5117
            if (!empty($coachList)) {
5118
                $coachesToDelete = array_diff($currentCoaches, $coachList);
5119
            } else {
5120
                $coachesToDelete = $currentCoaches;
5121
            }
5122
5123
            if (!empty($coachesToDelete)) {
5124
                foreach ($coachesToDelete as $userId) {
5125
                    self::set_coach_to_course_session(
5126
                        $userId,
5127
                        $sessionId,
5128
                        $courseId,
5129
                        true
5130
                    );
5131
                }
5132
            }
5133
        }
5134
    }
5135
5136
    /**
5137
     * @param array $sessions
5138
     * @param array $sessionsDestination
5139
     * @return string
5140
     */
5141
    public static function copyStudentsFromSession($sessions, $sessionsDestination)
5142
    {
5143
        $messages = array();
5144
        if (!empty($sessions)) {
5145
            foreach ($sessions as $sessionId) {
5146
                $sessionInfo = self::fetch($sessionId);
5147
                $userList = self::get_users_by_session($sessionId, 0);
5148
                if (!empty($userList)) {
5149
                    $newUserList = array();
5150
                    $userToString = null;
5151
                    foreach ($userList as $userInfo) {
5152
                        $newUserList[] = $userInfo['user_id'];
5153
                        $userToString .= $userInfo['firstname'] . ' ' . $userInfo['lastname'] . '<br />';
5154
                    }
5155
5156
                    if (!empty($sessionsDestination)) {
5157
                        foreach ($sessionsDestination as $sessionDestinationId) {
5158
                            $sessionDestinationInfo = self::fetch($sessionDestinationId);
5159
                            $messages[] = Display::return_message(
5160
                                sprintf(get_lang('AddingStudentsFromSessionXToSessionY'), $sessionInfo['name'], $sessionDestinationInfo['name']), 'info', false
5161
                            );
5162
                            if ($sessionId == $sessionDestinationId) {
5163
                                $messages[] = Display::return_message(sprintf(get_lang('SessionXSkipped'), $sessionDestinationId), 'warning', false);
5164
                                continue;
5165
                            }
5166
                            $messages[] = Display::return_message(get_lang('StudentList') . '<br />' . $userToString, 'info', false);
5167
                            SessionManager::suscribe_users_to_session(
5168
                                $sessionDestinationId,
5169
                                $newUserList,
5170
                                SESSION_VISIBLE_READ_ONLY,
5171
                                false
5172
                            );
5173
                        }
5174
                    } else {
5175
                        $messages[] = Display::return_message(get_lang('NoDestinationSessionProvided'), 'warning');
5176
                    }
5177
                } else {
5178
                    $messages[] = Display::return_message(
5179
                        get_lang('NoStudentsFoundForSession').' #'.$sessionInfo['name'],
5180
                        'warning'
5181
                    );
5182
                }
5183
            }
5184
        } else {
5185
            $messages[] = Display::return_message(get_lang('NoData'), 'warning');
5186
        }
5187
        return $messages;
5188
    }
5189
5190
    /**
5191
     * Assign coaches of a session(s) as teachers to a given course (or courses)
5192
     * @param array A list of session IDs
5193
     * @param array A list of course IDs
5194
     * @return string
5195
     */
5196
    public static function copyCoachesFromSessionToCourse($sessions, $courses)
5197
    {
5198
        $coachesPerSession = array();
5199
        foreach ($sessions as $sessionId) {
5200
            $coaches = self::getCoachesBySession($sessionId);
5201
            $coachesPerSession[$sessionId] = $coaches;
5202
        }
5203
5204
        $result = array();
5205
5206
        if (!empty($courses)) {
5207
            foreach ($courses as $courseId) {
5208
                $courseInfo = api_get_course_info_by_id($courseId);
5209
                foreach ($coachesPerSession as $sessionId => $coachList) {
5210
                    CourseManager::updateTeachers(
5211
                        $courseInfo['real_id'], $coachList, false, false, false
5212
                    );
5213
                    $result[$courseInfo['code']][$sessionId] = $coachList;
5214
                }
5215
            }
5216
        }
5217
        $sessionUrl = api_get_path(WEB_CODE_PATH) . 'admin/resume_session.php?id_session=';
5218
5219
        $htmlResult = null;
5220
5221
        if (!empty($result)) {
5222
            foreach ($result as $courseCode => $data) {
5223
                $url = api_get_course_url($courseCode);
5224
                $htmlResult .= sprintf(
5225
                    get_lang('CoachesSubscribedAsATeacherInCourseX'),
5226
                    Display::url($courseCode, $url, array('target' => '_blank'))
5227
                );
5228
                foreach ($data as $sessionId => $coachList) {
5229
                    $sessionInfo = self::fetch($sessionId);
5230
                    $htmlResult .= '<br />';
5231
                    $htmlResult .= Display::url(
5232
                        get_lang('Session') . ': ' . $sessionInfo['name'] . ' <br />', $sessionUrl . $sessionId, array('target' => '_blank')
5233
                    );
5234
                    $teacherList = array();
5235
                    foreach ($coachList as $coachId) {
5236
                        $userInfo = api_get_user_info($coachId);
5237
                        $teacherList[] = $userInfo['complete_name'];
5238
                    }
5239
                    if (!empty($teacherList)) {
5240
                        $htmlResult .= implode(', ', $teacherList);
5241
                    } else {
5242
                        $htmlResult .= get_lang('NothingToAdd');
5243
                    }
5244
                }
5245
                $htmlResult .= '<br />';
5246
            }
5247
            $htmlResult = Display::return_message($htmlResult, 'normal', false);
5248
        }
5249
        return $htmlResult;
5250
    }
5251
5252
    /**
5253
     * @param string $keyword
5254
     * @param string $active
5255
     * @param string $lastConnectionDate
5256
     * @param array $sessionIdList
5257
     * @param array $studentIdList
5258
     * @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...
5259
     *
5260
     * @return array|int
5261
     */
5262
    public static function getCountUserTracking(
5263
        $keyword = null,
5264
        $active = null,
5265
        $lastConnectionDate = null,
5266
        $sessionIdList = array(),
5267
        $studentIdList = array(),
5268
        $filterUserStatus = null
5269
    ) {
5270
        $userId = api_get_user_id();
5271
        $drhLoaded = false;
5272
5273
        if (api_is_drh()) {
5274
            if (api_drh_can_access_all_session_content()) {
5275
                $count = self::getAllUsersFromCoursesFromAllSessionFromStatus(
5276
                    'drh_all',
5277
                    $userId,
5278
                    true,
5279
                    null,
5280
                    null,
5281
                    null,
5282
                    null,
5283
                    $keyword,
5284
                    $active,
5285
                    $lastConnectionDate,
5286
                    $sessionIdList,
5287
                    $studentIdList,
5288
                    $filterUserStatus
5289
                );
5290
                $drhLoaded = true;
5291
            }
5292
        }
5293
5294
        if ($drhLoaded == false) {
5295
            $count = UserManager::getUsersFollowedByUser(
5296
                $userId,
5297
                $filterUserStatus,
5298
                false,
5299
                false,
5300
                true,
5301
                null,
5302
                null,
5303
                null,
5304
                null,
5305
                $active,
5306
                $lastConnectionDate,
5307
                api_is_student_boss() ? STUDENT_BOSS : COURSEMANAGER,
5308
                $keyword
5309
            );
5310
        }
5311
5312
        return $count;
5313
    }
5314
5315
    /**
5316
     * Get teachers followed by a user
5317
     * @param int $userId
5318
     * @param int $active
5319
     * @param string $lastConnectionDate
5320
     * @param bool $getCount
5321
     * @param array $sessionIdList
5322
     * @return array|int
5323
     */
5324
    public static function getTeacherTracking(
5325
        $userId,
5326
        $active = 1,
5327
        $lastConnectionDate = null,
5328
        $getCount = false,
5329
        $sessionIdList = array()
5330
    ) {
5331
        $teacherListId = array();
5332
5333
        if (api_is_drh() || api_is_platform_admin()) {
5334
            // Followed teachers by drh
5335
            if (api_drh_can_access_all_session_content()) {
5336
                if (empty($sessionIdList)) {
5337
                    $sessions = SessionManager::get_sessions_followed_by_drh($userId);
5338
                    $sessionIdList = array();
5339
                    foreach ($sessions as $session) {
5340
                        $sessionIdList[] = $session['id'];
5341
                    }
5342
                }
5343
5344
                $sessionIdList = array_map('intval', $sessionIdList);
5345
                $sessionToString = implode("', '",  $sessionIdList);
5346
5347
                $course = Database::get_main_table(TABLE_MAIN_COURSE);
5348
                $sessionCourse = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
5349
                $courseUser = Database::get_main_table(TABLE_MAIN_COURSE_USER);
5350
5351
                // Select the teachers.
5352
                $sql = "SELECT DISTINCT(cu.user_id) FROM $course c
5353
                        INNER JOIN $sessionCourse src ON c.id = src.c_id
5354
                        INNER JOIN $courseUser cu ON (cu.c_id = c.id)
5355
		                WHERE src.session_id IN ('$sessionToString') AND cu.status = 1";
5356
                $result = Database::query($sql);
5357
                while($row = Database::fetch_array($result, 'ASSOC')) {
5358
                    $teacherListId[$row['user_id']] = $row['user_id'];
5359
                }
5360
            } else {
5361
                $teacherResult = UserManager::get_users_followed_by_drh($userId, COURSEMANAGER);
5362
                foreach ($teacherResult as $userInfo) {
5363
                    $teacherListId[] = $userInfo['user_id'];
5364
                }
5365
            }
5366
        }
5367
5368
        if (!empty($teacherListId)) {
5369
            $tableUser = Database::get_main_table(TABLE_MAIN_USER);
5370
5371
            $select = "SELECT DISTINCT u.* ";
5372
            if ($getCount) {
5373
                $select = "SELECT count(DISTINCT(u.user_id)) as count";
5374
            }
5375
5376
            $sql = "$select FROM $tableUser u";
5377
5378
            if (!empty($lastConnectionDate)) {
5379
                $tableLogin = Database::get_main_table(TABLE_STATISTIC_TRACK_E_LOGIN);
5380
                //$sql .= " INNER JOIN $tableLogin l ON (l.login_user_id = u.user_id) ";
5381
            }
5382
            $active = intval($active);
5383
            $teacherListId = implode("','", $teacherListId);
5384
            $where = " WHERE u.active = $active AND u.user_id IN ('$teacherListId') ";
5385
5386
            if (!empty($lastConnectionDate)) {
5387
                $lastConnectionDate = Database::escape_string($lastConnectionDate);
5388
                //$where .= " AND l.login_date <= '$lastConnectionDate' ";
5389
            }
5390
5391
            $sql .= $where;
5392
            $result = Database::query($sql);
5393
            if (Database::num_rows($result)) {
5394
                if ($getCount) {
5395
                    $row = Database::fetch_array($result);
5396
                    return $row['count'];
5397
                } else {
5398
5399
                    return Database::store_result($result, 'ASSOC');
5400
                }
5401
            }
5402
        }
5403
5404
        return 0;
5405
    }
5406
5407
    /**
5408
     * Get the list of course tools that have to be dealt with in case of
5409
     * registering any course to a session
5410
     * @return array The list of tools to be dealt with (literal names)
5411
     */
5412
    public static function getCourseToolToBeManaged()
5413
    {
5414
        return array(
5415
            'courseDescription',
5416
            'courseIntroduction',
5417
        );
5418
    }
5419
5420
    /**
5421
     * Calls the methods bound to each tool when a course is registered into a session
5422
     * @param int $sessionId
5423
     * @param int $courseId
5424
     * @return void
5425
     */
5426 View Code Duplication
    public static function installCourse($sessionId, $courseId)
5427
    {
5428
        return true;
5429
        $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...
5430
5431
        foreach ($toolList as $tool) {
5432
            $method = 'add' . $tool;
5433
            if (method_exists(get_class(), $method)) {
0 ignored issues
show
Bug introduced by
The variable $method seems only to be defined at a later point. Did you maybe move this code here without moving the variable definition?

This error can happen if you refactor code and forget to move the variable initialization.

Let’s take a look at a simple example:

function someFunction() {
    $x = 5;
    echo $x;
}

The above code is perfectly fine. Now imagine that we re-order the statements:

function someFunction() {
    echo $x;
    $x = 5;
}

In that case, $x would be read before it is initialized. This was a very basic example, however the principle is the same for the found issue.

Loading history...
5434
                self::$method($sessionId, $courseId);
5435
            }
5436
        }
5437
    }
5438
5439
    /**
5440
     * Calls the methods bound to each tool when a course is unregistered from
5441
     * a session
5442
     * @param int $sessionId
5443
     * @param int $courseId
5444
     */
5445 View Code Duplication
    public static function unInstallCourse($sessionId, $courseId)
5446
    {
5447
        return true;
5448
        $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...
5449
5450
        foreach ($toolList as $tool) {
5451
            $method = 'remove' . $tool;
5452
            if (method_exists(get_class(), $method)) {
0 ignored issues
show
Bug introduced by
The variable $method seems only to be defined at a later point. Did you maybe move this code here without moving the variable definition?

This error can happen if you refactor code and forget to move the variable initialization.

Let’s take a look at a simple example:

function someFunction() {
    $x = 5;
    echo $x;
}

The above code is perfectly fine. Now imagine that we re-order the statements:

function someFunction() {
    echo $x;
    $x = 5;
}

In that case, $x would be read before it is initialized. This was a very basic example, however the principle is the same for the found issue.

Loading history...
5453
                self::$method($sessionId, $courseId);
5454
            }
5455
        }
5456
    }
5457
5458
    /**
5459
     * @param int $sessionId
5460
     * @param int $courseId
5461
     */
5462
    public static function addCourseIntroduction($sessionId, $courseId)
5463
    {
5464
        // @todo create a tool intro lib
5465
        $sessionId = intval($sessionId);
5466
        $courseId = intval($courseId);
5467
5468
        $TBL_INTRODUCTION = Database::get_course_table(TABLE_TOOL_INTRO);
5469
        $sql = "SELECT * FROM $TBL_INTRODUCTION WHERE c_id = $courseId";
5470
        $result = Database::query($sql);
5471
        $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...
5472
5473
        if (!empty($result)) {
5474
            foreach ($result as $result) {
5475
                // @todo check if relation exits.
5476
                $result['session_id'] = $sessionId;
5477
                Database::insert($TBL_INTRODUCTION, $result);
5478
            }
5479
        }
5480
    }
5481
5482
    /**
5483
     * @param int $sessionId
5484
     * @param int $courseId
5485
     */
5486
    public static function removeCourseIntroduction($sessionId, $courseId)
5487
    {
5488
        $sessionId = intval($sessionId);
5489
        $courseId = intval($courseId);
5490
        $TBL_INTRODUCTION = Database::get_course_table(TABLE_TOOL_INTRO);
5491
        $sql = "DELETE FROM $TBL_INTRODUCTION
5492
                WHERE c_id = $courseId AND session_id = $sessionId";
5493
        Database::query($sql);
5494
    }
5495
5496
    /**
5497
     * @param int $sessionId
5498
     * @param int $courseId
5499
     */
5500
    public static function addCourseDescription($sessionId, $courseId)
5501
    {
5502
        /* $description = new CourseDescription();
5503
          $descriptions = $description->get_descriptions($courseId);
5504
          foreach ($descriptions as $description) {
5505
          } */
5506
    }
5507
5508
    /**
5509
     * @param int $sessionId
5510
     * @param int $courseId
5511
     */
5512
    public static function removeCourseDescription($sessionId, $courseId)
5513
    {
5514
5515
    }
5516
5517
    /**
5518
     * @param array $userSessionList format see self::importSessionDrhCSV()
5519
     * @param bool $sendEmail
5520
     * @param bool $removeOldRelationShips
5521
     * @return string
5522
     */
5523
    public static function subscribeDrhToSessionList($userSessionList, $sendEmail, $removeOldRelationShips)
5524
    {
5525
        if (!empty($userSessionList)) {
5526
            foreach ($userSessionList as $userId => $data) {
5527
                $sessionList = array();
5528
                foreach ($data['session_list'] as $sessionInfo) {
5529
                    $sessionList[] = $sessionInfo['session_id'];
5530
                }
5531
                $userInfo = $data['user_info'];
5532
                self::suscribe_sessions_to_hr_manager(
5533
                    $userInfo,
5534
                    $sessionList,
5535
                    $sendEmail,
5536
                    $removeOldRelationShips
5537
                );
5538
            }
5539
        }
5540
    }
5541
5542
    /**
5543
     * @param array $userSessionList format see self::importSessionDrhCSV()
5544
     *
5545
     * @return string
5546
     */
5547
    public static function checkSubscribeDrhToSessionList($userSessionList)
5548
    {
5549
        $message = null;
5550
        if (!empty($userSessionList)) {
5551
            if (!empty($userSessionList)) {
5552
                foreach ($userSessionList as $userId => $data) {
5553
                    $userInfo = $data['user_info'];
5554
5555
                    $sessionListSubscribed = self::get_sessions_followed_by_drh($userId);
5556
                    if (!empty($sessionListSubscribed)) {
5557
                        $sessionListSubscribed = array_keys($sessionListSubscribed);
5558
                    }
5559
5560
                    $sessionList = array();
5561
                    if (!empty($data['session_list'])) {
5562
                        foreach ($data['session_list'] as $sessionInfo) {
5563
                            if (in_array($sessionInfo['session_id'], $sessionListSubscribed)) {
5564
                                $sessionList[] = $sessionInfo['session_info']['name'];
5565
                            }
5566
                        }
5567
                    }
5568
5569
                    $message .= '<strong>' . get_lang('User') . '</strong> ' . $userInfo['complete_name'] . ' <br />';
5570
5571
                    if (!in_array($userInfo['status'], array(DRH)) && !api_is_platform_admin_by_id($userInfo['user_id'])) {
5572
                        $message .= get_lang('UserMustHaveTheDrhRole') . '<br />';
5573
                        continue;
5574
                    }
5575
5576
                    if (!empty($sessionList)) {
5577
                        $message .= '<strong>' . get_lang('Sessions') . ':</strong> <br />';
5578
                        $message .= implode(', ', $sessionList) . '<br /><br />';
5579
                    } else {
5580
                        $message .= get_lang('NoSessionProvided') . ' <br /><br />';
5581
                    }
5582
                }
5583
            }
5584
        }
5585
5586
        return $message;
5587
    }
5588
5589
    /**
5590
     * @param string $file
5591
     * @param bool $sendEmail
5592
     * @param bool $removeOldRelationShips
5593
     *
5594
     * @return string
5595
     */
5596
    public static function importSessionDrhCSV($file, $sendEmail, $removeOldRelationShips)
5597
    {
5598
        $list = Import::csv_reader($file);
5599
5600
        if (!empty($list)) {
5601
            $userSessionList = array();
5602
            foreach ($list as $data) {
5603
                $userInfo = api_get_user_info_from_username($data['Username']);
5604
                $sessionInfo = self::get_session_by_name($data['SessionName']);
5605
5606
                if (!empty($userInfo) && !empty($sessionInfo)) {
5607
                    $userSessionList[$userInfo['user_id']]['session_list'][] = array(
5608
                        'session_id' => $sessionInfo['id'],
5609
                        'session_info' => $sessionInfo,
5610
                    );
5611
                    $userSessionList[$userInfo['user_id']]['user_info'] = $userInfo;
5612
                }
5613
            }
5614
5615
            self::subscribeDrhToSessionList($userSessionList, $sendEmail, $removeOldRelationShips);
5616
            return self::checkSubscribeDrhToSessionList($userSessionList);
5617
        }
5618
    }
5619
5620
    /**
5621
     * Courses re-ordering in resume_session.php flag see BT#8316
5622
     */
5623
    public static function orderCourseIsEnabled()
5624
    {
5625
        $sessionCourseOrder = api_get_setting('session_course_ordering');
5626
        if ($sessionCourseOrder === 'true') {
5627
            return true;
5628
        }
5629
5630
        return false;
5631
    }
5632
5633
    /**
5634
     * @param string $direction (up/down)
5635
     * @param int $sessionId
5636
     * @param int $courseId
5637
     * @return bool
5638
     */
5639
    public static function move($direction, $sessionId, $courseId)
5640
    {
5641
        if (!self::orderCourseIsEnabled()) {
5642
            return false;
5643
        }
5644
5645
        $sessionId = intval($sessionId);
5646
        $courseId = intval($courseId);
5647
5648
        $table = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
5649
        $courseList = self::get_course_list_by_session_id($sessionId, null, 'position');
5650
5651
        $position = array();
5652
        $count = 0;
5653
        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...
5654
            if ($course['position'] == '') {
5655
                $course['position'] = $count;
5656
            }
5657
            $position[$course['code']] = $course['position'];
5658
            // Saving current order.
5659
            $sql = "UPDATE $table SET position = $count
5660
                    WHERE session_id = $sessionId AND c_id = '".$course['real_id']."'";
5661
            Database::query($sql);
5662
            $count++;
5663
        }
5664
5665
        // Loading new positions.
5666
        $courseList = self::get_course_list_by_session_id($sessionId, null, 'position');
5667
5668
        $found = false;
5669
5670
        switch ($direction) {
5671
            case 'up':
5672
                $courseList = array_reverse($courseList);
5673
                break;
5674
            case 'down':
5675
                break;
5676
        }
5677
5678
        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...
5679
            if ($found) {
5680
                $nextId = $course['real_id'];
5681
                $nextOrder = $course['position'];
5682
                break;
5683
            }
5684
5685
            if ($courseId == $course['real_id']) {
5686
                $thisCourseCode = $course['real_id'];
5687
                $thisOrder = $course['position'];
5688
                $found = true;
5689
            }
5690
        }
5691
5692
        $sql1 = "UPDATE $table SET position = '".intval($nextOrder)."'
5693
                 WHERE session_id = $sessionId AND c_id =  $thisCourseCode";
5694
        Database::query($sql1);
5695
5696
        $sql2 = "UPDATE $table SET position = '".intval($thisOrder)."'
5697
                 WHERE session_id = $sessionId AND c_id = $nextId";
5698
        Database::query($sql2);
5699
5700
        return true;
5701
    }
5702
5703
    /**
5704
     * @param int $sessionId
5705
     * @param int $courseId
5706
     * @return bool
5707
     */
5708
    public static function moveUp($sessionId, $courseId)
5709
    {
5710
        return self::move('up', $sessionId, $courseId);
5711
    }
5712
5713
    /**
5714
     * @param int $sessionId
5715
     * @param string $courseCode
5716
     * @return bool
5717
     */
5718
    public static function moveDown($sessionId, $courseCode)
5719
    {
5720
        return self::move('down', $sessionId, $courseCode);
5721
    }
5722
5723
    /**
5724
     * Use the session duration to allow/block user access see BT#8317
5725
     * Needs these DB changes
5726
     * ALTER TABLE session ADD COLUMN duration int;
5727
     * ALTER TABLE session_rel_user ADD COLUMN duration int;
5728
     */
5729
    public static function durationPerUserIsEnabled()
5730
    {
5731
        return api_get_configuration_value('session_duration_feature');
5732
    }
5733
5734
    /**
5735
     * Returns the number of days the student has left in a session when using
5736
     * sessions durations
5737
     * @param int $userId
5738
     * @param int $sessionId
5739
     * @param int $duration in days
5740
     * @return int
5741
     */
5742
    public static function getDayLeftInSession($sessionId, $userId, $duration)
5743
    {
5744
        // Get an array with the details of the first access of the student to
5745
        // this session
5746
        $courseAccess = CourseManager::getFirstCourseAccessPerSessionAndUser(
5747
            $sessionId,
5748
            $userId
5749
        );
5750
5751
        $currentTime = time();
5752
5753
        // If no previous access, return false
5754
        if (count($courseAccess) == 0) {
5755
            return false;
5756
        }
5757
5758
        $firstAccess = api_strtotime($courseAccess['login_course_date'], 'UTC');
5759
5760
        $endDateInSeconds = $firstAccess + $duration*24*60*60;
5761
        $leftDays = round(($endDateInSeconds- $currentTime) / 60 / 60 / 24);
5762
5763
        return $leftDays;
5764
    }
5765
5766
    /**
5767
     * @param int $duration
5768
     * @param int $userId
5769
     * @param int $sessionId
5770
     */
5771
    public static function editUserSessionDuration($duration, $userId, $sessionId)
5772
    {
5773
        $duration = intval($duration);
5774
        $userId = intval($userId);
5775
        $sessionId = intval($sessionId);
5776
5777
        if (empty($userId) || empty($sessionId)) {
5778
            return false;
5779
        }
5780
5781
        $table = Database::get_main_table(TABLE_MAIN_SESSION_USER);
5782
        $parameters = array('duration' => $duration);
5783
        $where = array('session_id = ? AND user_id = ? ' => array($sessionId, $userId));
5784
        Database::update($table, $parameters, $where);
5785
    }
5786
5787
    /**
5788
     * Gets one row from the session_rel_user table
5789
     * @param int $userId
5790
     * @param int $sessionId
5791
     *
5792
     * @return array
5793
     */
5794
    public static function getUserSession($userId, $sessionId)
5795
    {
5796
        $userId = intval($userId);
5797
        $sessionId = intval($sessionId);
5798
5799
        if (empty($userId) || empty($sessionId)) {
5800
            return false;
5801
        }
5802
5803
        $table = Database::get_main_table(TABLE_MAIN_SESSION_USER);
5804
        $sql = "SELECT * FROM $table
5805
                WHERE session_id = $sessionId AND user_id = $userId";
5806
        $result = Database::query($sql);
5807
        $values = array();
5808
        if (Database::num_rows($result)) {
5809
            $values = Database::fetch_array($result, 'ASSOC');
5810
        }
5811
5812
        return $values;
5813
    }
5814
5815
    /**
5816
     * Check if user is subscribed inside a session as student
5817
     * @param int $sessionId The session id
5818
     * @param int $userId The user id
5819
     * @return boolean Whether is subscribed
5820
     */
5821
    public static function isUserSubscribedAsStudent($sessionId, $userId)
5822
    {
5823
        $sessionRelUserTable = Database::get_main_table(TABLE_MAIN_SESSION_USER);
5824
5825
        $sessionId = intval($sessionId);
5826
        $userId = intval($userId);
5827
5828
        // COUNT(1) actually returns the number of rows from the table (as if
5829
        // counting the results from the first column)
5830
        $sql = "SELECT COUNT(1) AS qty FROM $sessionRelUserTable
5831
                WHERE
5832
                    session_id = $sessionId AND
5833
                    user_id = $userId AND
5834
                    relation_type = 0";
5835
5836
        $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...
5837
5838
        if (!empty($result) && $result['qty'] > 0) {
5839
            return true;
5840
        }
5841
5842
        return false;
5843
    }
5844
5845
    /**
5846
     * Get the session coached by a user (general coach and course-session coach)
5847
     * @param int $coachId The coach id
5848
     * @param boolean $checkSessionRelUserVisibility Check the session visibility
5849
     * @param boolean $asPlatformAdmin The user is a platform admin and we want all sessions
5850
     * @return array The session list
5851
     */
5852
    public static function getSessionsCoachedByUser($coachId, $checkSessionRelUserVisibility = false, $asPlatformAdmin = false)
5853
    {
5854
        // Get all sessions where $coachId is the general coach
5855
        $sessions = self::get_sessions_by_general_coach($coachId, $asPlatformAdmin);
5856
        // Get all sessions where $coachId is the course - session coach
5857
        $courseSessionList = self::getCoursesListByCourseCoach($coachId);
5858
        $sessionsByCoach = array();
5859
        if (!empty($courseSessionList)) {
5860
            foreach ($courseSessionList as $userCourseSubscription) {
5861
                $session = $userCourseSubscription->getSession();
5862
                $sessionsByCoach[$session->getId()] = api_get_session_info(
5863
                    $session->getId()
5864
                );
5865
            }
5866
        }
5867
5868
        if (!empty($sessionsByCoach)) {
5869
            $sessions = array_merge($sessions, $sessionsByCoach);
5870
        }
5871
5872
        // Remove repeated sessions
5873
        if (!empty($sessions)) {
5874
            $cleanSessions = array();
5875
            foreach ($sessions as $session) {
5876
                $cleanSessions[$session['id']] = $session;
5877
            }
5878
            $sessions = $cleanSessions;
5879
        }
5880
5881
        if ($checkSessionRelUserVisibility) {
5882
            if (!empty($sessions)) {
5883
                $newSessions = array();
5884
                foreach ($sessions as $session) {
5885
                    $visibility = api_get_session_visibility($session['id']);
5886
                    if ($visibility == SESSION_INVISIBLE) {
5887
                        continue;
5888
                    }
5889
                    $newSessions[] = $session;
5890
                }
5891
                $sessions = $newSessions;
5892
            }
5893
        }
5894
5895
        return $sessions;
5896
    }
5897
5898
    /**
5899
     * Check if the course belongs to the session
5900
     * @param int $sessionId The session id
5901
     * @param string $courseCode The course code
5902
     *
5903
     * @return bool
5904
     */
5905
    public static function sessionHasCourse($sessionId, $courseCode)
5906
    {
5907
        $sessionId = intval($sessionId);
5908
        $courseCode = Database::escape_string($courseCode);
5909
5910
        $courseTable = Database::get_main_table(TABLE_MAIN_COURSE);
5911
        $sessionRelCourseTable = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
5912
5913
        $sql = "SELECT COUNT(1) AS qty
5914
                FROM $courseTable c
5915
                INNER JOIN $sessionRelCourseTable src
5916
                ON c.id = src.c_id
5917
                WHERE src.session_id = $sessionId
5918
                AND c.code = '$courseCode'  ";
5919
5920
        $result = Database::query($sql);
5921
5922
        if ($result !== false) {
5923
            $data = Database::fetch_assoc($result);
5924
5925
            if ($data['qty'] > 0) {
5926
                return true;
5927
            }
5928
        }
5929
5930
        return false;
5931
    }
5932
5933
    /**
5934
     * Get the list of course coaches
5935
     * @return array The list
5936
     */
5937
    public static function getAllCourseCoaches()
5938
    {
5939
        $coaches = array();
5940
5941
        $scuTable = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
5942
        $userTable = Database::get_main_table(TABLE_MAIN_USER);
5943
5944
        $idResult = Database::select('DISTINCT user_id', $scuTable, array(
5945
            'where' => array(
5946
                'status = ?' => 2,
5947
            ),
5948
        ));
5949
5950
        if ($idResult != false) {
5951
            foreach ($idResult as $idData) {
5952
                $userResult = Database::select('user_id, lastname, firstname, username', $userTable, array(
5953
                    'where' => array(
5954
                        'user_id = ?' => $idData['user_id'],
5955
                    ),
5956
                ), 'first');
5957
5958
                if ($userResult != false) {
5959
                    $coaches[] = array(
5960
                        'id' => $userResult['user_id'],
5961
                        'lastname' => $userResult['lastname'],
5962
                        'firstname' => $userResult['firstname'],
5963
                        'username' => $userResult['username'],
5964
                        'completeName' => api_get_person_name(
5965
                            $userResult['firstname'],
5966
                            $userResult['lastname']
5967
                        ),
5968
                    );
5969
                }
5970
            }
5971
        }
5972
5973
        return $coaches;
5974
    }
5975
5976
    /**
5977
     * Calculate the total user time in the platform
5978
     * @param int $userId The user id
5979
     * @param string $from Optional. From date
5980
     * @param string $until Optional. Until date
5981
     * @return string The time (hh:mm:ss)
5982
     */
5983
    public static function getTotalUserTimeInPlatform($userId, $from = '', $until = '')
5984
    {
5985
        $userId = intval($userId);
5986
5987
        $trackLoginTable = Database::get_main_table(TABLE_STATISTIC_TRACK_E_LOGIN);
5988
5989
        $whereConditions = array(
5990
            'login_user_id = ? ' => $userId,
5991
        );
5992
5993 View Code Duplication
        if (!empty($from) && !empty($until)) {
5994
            $whereConditions["AND (login_date >= '?' "] = $from;
5995
            $whereConditions["AND logout_date <= DATE_ADD('?', INTERVAL 1 DAY)) "] = $until;
5996
        }
5997
5998
        $trackResult = Database::select(
5999
            'SEC_TO_TIME(SUM(UNIX_TIMESTAMP(logout_date) - UNIX_TIMESTAMP(login_date))) as total_time',
6000
            $trackLoginTable,
6001
            array(
6002
                'where' => $whereConditions,
6003
            ), 'first'
6004
        );
6005
6006
        if ($trackResult != false) {
6007
            return $trackResult['total_time'] ? $trackResult['total_time'] : '00:00:00';
6008
        }
6009
6010
        return '00:00:00';
6011
    }
6012
6013
    /**
6014
     * Get the courses list by a course coach
6015
     * @param int $coachId The coach id
6016
     * @return array (id, user_id, session_id, c_id, visibility, status, legal_agreement)
6017
     */
6018
    public static function getCoursesListByCourseCoach($coachId)
6019
    {
6020
        $entityManager = Database::getManager();
6021
        $scuRepo = $entityManager->getRepository(
6022
            'ChamiloCoreBundle:SessionRelCourseRelUser'
6023
        );
6024
6025
        return $scuRepo->findBy([
6026
            'user' => $coachId,
6027
            'status' => SessionRelCourseRelUser::STATUS_COURSE_COACH
6028
        ]);
6029
    }
6030
6031
	/**
6032
     * Get the count of user courses in session
6033
     * @param int $sessionId The session id
6034
     * @return array
6035
     */
6036
    public static function getTotalUserCoursesInSession($sessionId)
6037
    {
6038
        $tableUser = Database::get_main_table(TABLE_MAIN_USER);
6039
        $tableSessionRelCourseRelUser = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
6040
        $sql = "SELECT COUNT(1) as count, u.id, scu.status status_in_session, u.status user_status
6041
                FROM $tableSessionRelCourseRelUser scu
6042
                INNER JOIN $tableUser u ON scu.user_id = u.id
6043
                WHERE scu.session_id = " . intval($sessionId) ."
6044
                GROUP BY u.id";
6045
6046
        $result = Database::query($sql);
6047
6048
        $list = array();
6049
        while ($data = Database::fetch_assoc($result)) {
6050
            $list[] = $data;
6051
        }
6052
6053
        return $list;
6054
    }
6055
6056
6057
    /**
6058
     * Returns list of a few data from session (name, short description, start
6059
     * date, end date) and the given extra fields if defined based on a
6060
     * session category Id.
6061
     * @param int $categoryId The internal ID of the session category
6062
     * @param string $target Value to search for in the session field values
6063
     * @param array $extraFields A list of fields to be scanned and returned
6064
     * @return mixed
6065
     */
6066
    public static function getShortSessionListAndExtraByCategory($categoryId, $target, $extraFields = null, $publicationDate = null)
6067
    {
6068
        // Init variables
6069
        $categoryId = (int) $categoryId;
6070
        $sessionList = array();
6071
        // Check if categoryId is valid
6072
        if ($categoryId > 0) {
6073
            $target = Database::escape_string($target);
6074
            $sTable = Database::get_main_table(TABLE_MAIN_SESSION);
6075
            $sfTable = Database::get_main_table(TABLE_EXTRA_FIELD);
6076
            $sfvTable = Database::get_main_table(TABLE_EXTRA_FIELD_VALUES);
6077
            // Join session field and session field values tables
6078
            $joinTable = $sfTable . ' sf INNER JOIN ' . $sfvTable . ' sfv ON sf.id = sfv.field_id';
6079
            $fieldsArray = array();
6080
            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...
6081
                $fieldsArray[] = Database::escape_string($field);
6082
            }
6083
            $extraFieldType = \Chamilo\CoreBundle\Entity\ExtraField::SESSION_FIELD_TYPE;
6084
            if (isset ($publicationDate)) {
6085
                $publicationDateString = $publicationDate->format('Y-m-d H:i:s');
6086
                $wherePublication = " AND id NOT IN (
6087
                    SELECT sfv.item_id FROM $joinTable
6088
                    WHERE
6089
                        sf.extra_field_type = $extraFieldType AND
6090
                        ((sf.variable = 'publication_start_date' AND sfv.value > '$publicationDateString' and sfv.value != '') OR
6091
                        (sf.variable = 'publication_end_date' AND sfv.value < '$publicationDateString' and sfv.value != ''))
6092
                )";
6093
            }
6094
            // Get the session list from session category and target
6095
            $sessionList = Database::select(
6096
                'id, name, access_start_date, access_end_date',
6097
                $sTable,
6098
                array(
6099
                    'where' => array(
6100
                        "session_category_id = ? AND id IN (
6101
                            SELECT sfv.item_id FROM $joinTable
6102
                            WHERE
6103
                                sf.extra_field_type = $extraFieldType AND
6104
                                sfv.item_id = session.id AND
6105
                                sf.variable = 'target' AND
6106
                                sfv.value = ?
6107
                        ) $wherePublication" => array($categoryId, $target),
6108
                    ),
6109
                )
6110
            );
6111
            $whereFieldVariables = array();
6112
            $whereFieldIds = array();
6113
            if (
6114
                is_array($fieldsArray) &&
6115
                count($fieldsArray) > 0
6116
            ) {
6117
                $whereParams = '?';
6118
                for ($i = 1; $i < count($fieldsArray); $i++) {
6119
                    $whereParams .= ', ?';
6120
                }
6121
                $whereFieldVariables = ' variable IN ( ' . $whereParams .' )';
6122
                $whereFieldIds = 'field_id IN ( ' . $whereParams .  ' )';
6123
            }
6124
            // Get session fields
6125
            $extraField = new ExtraField('session');
6126
            $questionMarks = substr(str_repeat('?, ', count($fieldsArray)), 0, -2);
6127
            $fieldsList = $extraField->get_all(array(
6128
                ' variable IN ( ' . $questionMarks . ' )' => $fieldsArray,
6129
            ));
6130
            // Index session fields
6131
            foreach ($fieldsList as $field) {
6132
                $fields[$field['id']] = $field['variable'];
6133
            }
6134
            // Get session field values
6135
            $extra = new ExtraFieldValue('session');
6136
            $questionMarksFields = substr(str_repeat('?, ', count($fields)), 0, -2);
6137
            $sessionFieldValueList = $extra->get_all(array ('where' => array('field_id IN ( ' . $questionMarksFields . ' )' => array_keys($fields))));
6138
            // Add session fields values to session list
6139
            foreach ($sessionList as $id => &$session) {
6140
                foreach ($sessionFieldValueList as $sessionFieldValue) {
6141
                    // Match session field values to session
6142
                    if ($sessionFieldValue['item_id'] == $id) {
6143
                        // Check if session field value is set in session field list
6144
                        if (isset($fields[$sessionFieldValue['field_id']])) {
6145
                            // Avoid overwriting the session's ID field
6146
                            if ($fields[$sessionFieldValue['field_id']] != 'id') {
6147
                                $var = $fields[$sessionFieldValue['field_id']];
6148
                                $val = $sessionFieldValue['value'];
6149
                                // Assign session field value to session
6150
                                $session[$var] = $val;
6151
                            }
6152
                        }
6153
                    }
6154
                }
6155
            }
6156
        }
6157
6158
        return $sessionList;
6159
    }
6160
6161
    /**
6162
     * Return the Session Category id searched by name
6163
     * @param string $categoryName Name attribute of session category used for search query
6164
     * @param bool $force boolean used to get even if something is wrong (e.g not unique name)
6165
     * @return int|array If success, return category id (int), else it will return an array
6166
     * with the next structure:
6167
     * array('error' => true, 'errorMessage' => ERROR_MESSAGE)
6168
     */
6169
    public static function getSessionCategoryIdByName($categoryName, $force = false)
6170
    {
6171
        // Start error result
6172
        $errorResult = array('error' => true, 'errorMessage' => get_lang('ThereWasAnError'));
6173
        $categoryName = Database::escape_string($categoryName);
6174
        // Check if is not empty category name
6175
        if (!empty($categoryName)) {
6176
            $sessionCategoryTable = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
6177
            // Get all session category with same name
6178
            $result = Database::select(
6179
                'id',
6180
                $sessionCategoryTable,
6181
                array(
6182
                    'where' => array(
6183
                        'name = ?' => $categoryName,
6184
                    ),
6185
                )
6186
            );
6187
            // Check the result
6188
            if ($result < 1) {
6189
                // If not found any result, update error message
6190
                $errorResult['errorMessage'] = 'Not found any session category name ' . $categoryName;
6191
            } elseif (count($result) > 1 && !$force) {
6192
                // If found more than one result and force is disabled, update error message
6193
                $errorResult['errorMessage'] = 'Found many session categories';
6194
            } elseif (count($result) == 1 || $force) {
6195
                // If found just one session category or force option is enabled
6196
6197
                return key($result);
6198
            }
6199
        } else {
6200
            // category name is empty, update error message
6201
            $errorResult['errorMessage'] = 'Not valid category name';
6202
        }
6203
6204
        return $errorResult;
6205
    }
6206
6207
    /**
6208
     * Return all data from sessions (plus extra field, course and coach data) by category id
6209
     * @param int $sessionCategoryId session category id used to search sessions
6210
     * @return array If success, return session list and more session related data, else it will return an array
6211
     * with the next structure:
6212
     * array('error' => true, 'errorMessage' => ERROR_MESSAGE)
6213
     */
6214
    public static function getSessionListAndExtraByCategoryId($sessionCategoryId)
6215
    {
6216
        // Start error result
6217
        $errorResult = array(
6218
            'error' => true,
6219
            'errorMessage' => get_lang('ThereWasAnError'),
6220
        );
6221
6222
        $sessionCategoryId = intval($sessionCategoryId);
6223
        // Check if session category id is valid
6224
        if ($sessionCategoryId > 0) {
6225
            // Get table names
6226
            $sessionTable = Database::get_main_table(TABLE_MAIN_SESSION);
6227
            $sessionFieldTable = Database::get_main_table(TABLE_EXTRA_FIELD);
6228
            $sessionFieldValueTable = Database::get_main_table(TABLE_EXTRA_FIELD_VALUES);
6229
            $sessionCourseUserTable = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
6230
            $userTable = Database::get_main_table(TABLE_MAIN_USER);
6231
            $courseTable = Database::get_main_table(TABLE_MAIN_COURSE);
6232
6233
            // Get all data from all sessions whit the session category specified
6234
            $sessionList = Database::select(
6235
                '*',
6236
                $sessionTable,
6237
                array(
6238
                    'where' => array(
6239
                        'session_category_id = ?' => $sessionCategoryId,
6240
                    ),
6241
                )
6242
            );
6243
6244
            $extraFieldType = \Chamilo\CoreBundle\Entity\ExtraField::SESSION_FIELD_TYPE;
6245
6246
            // Check if session list query had result
6247
            if (!empty($sessionList)) {
6248
                // implode all session id
6249
                $sessionIdsString = '(' . implode(', ', array_keys($sessionList)) . ')';
6250
                // Get all field variables
6251
                $sessionFieldList = Database::select(
6252
                    'id, variable',
6253
                    $sessionFieldTable,
6254
                    array('extra_field_type = ? ' => array($extraFieldType))
6255
                );
6256
6257
                // Get all field values
6258
                $sql = "SELECT item_id, field_id, value FROM
6259
                        $sessionFieldValueTable v INNER JOIN $sessionFieldTable f
6260
                        ON (f.id = v.field_id)
6261
                        WHERE
6262
                            item_id IN $sessionIdsString AND
6263
                            extra_field_type = $extraFieldType
6264
                ";
6265
                $result = Database::query($sql);
6266
                $sessionFieldValueList = Database::store_result($result, 'ASSOC');
6267
6268
                // Check if session field values had result
6269
                if (!empty($sessionFieldValueList)) {
6270
                    $sessionFieldValueListBySession = array();
6271
                    foreach ($sessionFieldValueList as $key => $sessionFieldValue) {
6272
                        // Create an array to index ids to session id
6273
                        $sessionFieldValueListBySession[$sessionFieldValue['item_id']][] = $key;
6274
                    }
6275
                }
6276
                // Query used to find course-coaches from sessions
6277
                $sql = "SELECT
6278
                        scu.session_id,
6279
                        c.id AS course_id,
6280
                        c.code AS course_code,
6281
                        c.title AS course_title,
6282
                        u.username AS coach_username,
6283
                        u.firstname AS coach_firstname,
6284
                        u.lastname AS coach_lastname
6285
                        FROM $courseTable c
6286
                        INNER JOIN $sessionCourseUserTable scu ON c.id = scu.c_id
6287
                        INNER JOIN $userTable u ON scu.user_id = u.user_id
6288
                        WHERE scu.status = 2 AND scu.session_id IN $sessionIdsString
6289
                        ORDER BY scu.session_id ASC ";
6290
                $res = Database::query($sql);
6291
                $sessionCourseList = Database::store_result($res, 'ASSOC');
6292
                // Check if course list had result
6293
                if (!empty($sessionCourseList)) {
6294
                    foreach ($sessionCourseList as $key => $sessionCourse) {
6295
                        // Create an array to index ids to session_id
6296
                        $sessionCourseListBySession[$sessionCourse['session_id']][] = $key;
6297
                    }
6298
                }
6299
                // Join lists
6300
                if (is_array($sessionList)) {
6301
                    foreach ($sessionList as $id => &$row) {
6302
                        if (
6303
                            !empty($sessionFieldValueListBySession) &&
6304
                            is_array($sessionFieldValueListBySession[$id])
6305
                        ) {
6306
                            // If have an index array for session extra fields, use it to join arrays
6307
                            foreach ($sessionFieldValueListBySession[$id] as $key) {
6308
                                $row['extra'][$key] = array(
6309
                                    'field_name' => $sessionFieldList[$sessionFieldValueList[$key]['field_id']]['variable'],
6310
                                    'value' => $sessionFieldValueList[$key]['value'],
6311
                                );
6312
                            }
6313
                        }
6314
                        if (
6315
                            !empty($sessionCourseListBySession) &&
6316
                            is_array($sessionCourseListBySession[$id])
6317
                        ) {
6318
                            // If have an index array for session course coach, use it to join arrays
6319
                            foreach ($sessionCourseListBySession[$id] as $key) {
6320
                                $row['course'][$key] = array(
6321
                                    'course_id' => $sessionCourseList[$key]['course_id'],
6322
                                    'course_code' => $sessionCourseList[$key]['course_code'],
6323
                                    'course_title' => $sessionCourseList[$key]['course_title'],
6324
                                    'coach_username' => $sessionCourseList[$key]['coach_username'],
6325
                                    'coach_firstname' => $sessionCourseList[$key]['coach_firstname'],
6326
                                    'coach_lastname' => $sessionCourseList[$key]['coach_lastname'],
6327
                                );
6328
                            }
6329
                        }
6330
                    }
6331
                }
6332
6333
                return $sessionList;
6334
            } else {
6335
                // Not found result, update error message
6336
                $errorResult['errorMessage'] = 'Not found any session for session category id ' . $sessionCategoryId;
6337
            }
6338
        }
6339
6340
        return $errorResult;
6341
    }
6342
6343
    /**
6344
     * Return session description from session id
6345
     * @param int $sessionId
6346
     * @return string
6347
     */
6348
    public static function getDescriptionFromSessionId($sessionId)
6349
    {
6350
        // Init variables
6351
        $sessionId = intval($sessionId);
6352
        $description = '';
6353
        // Check if session id is valid
6354
        if ($sessionId > 0) {
6355
            // Select query from session id
6356
            $rows = Database::select(
6357
                'description',
6358
                Database::get_main_table(TABLE_MAIN_SESSION),
6359
                array(
6360
                    'where' => array(
6361
                        'id = ?' => $sessionId,
6362
                    ),
6363
                )
6364
            );
6365
6366
            // Check if select query result is not empty
6367
            if (!empty($rows)) {
6368
                // Get session description
6369
                $description = $rows[0]['description'];
6370
            }
6371
        }
6372
6373
        return $description;
6374
    }
6375
6376
    /**
6377
     * Get a session list filtered by name, description or any of the given extra fields
6378
     * @param string $term The term to search
6379
     * @param array $extraFieldsToInclude Extra fields to include in the session data
6380
     * @return array The list
6381
     */
6382
    public static function searchSession($term, $extraFieldsToInclude = array())
6383
    {
6384
        $sTable = Database::get_main_table(TABLE_MAIN_SESSION);
6385
        $extraFieldTable = Database::get_main_table(TABLE_EXTRA_FIELD);
6386
        $sfvTable = Database::get_main_table(TABLE_EXTRA_FIELD_VALUES);
6387
6388
        $term = Database::escape_string($term);
6389
        $extraFieldType = \Chamilo\CoreBundle\Entity\ExtraField::SESSION_FIELD_TYPE;
6390
        if (is_array($extraFieldsToInclude) && count($extraFieldsToInclude) > 0) {
6391
            $resultData = Database::select('*', $sTable, array(
6392
                'where' => array(
6393
                    "name LIKE %?% " => $term,
6394
                    " OR description LIKE %?% " => $term,
6395
                    " OR id IN (
6396
                    SELECT item_id
6397
                    FROM $sfvTable v INNER JOIN $extraFieldTable e
6398
                    ON (v.field_id = e.id)
6399
                    WHERE value LIKE %?% AND extra_field_type = $extraFieldType
6400
                ) " => $term,
6401
                ),
6402
            ));
6403
        } else {
6404
            $resultData = Database::select('*', $sTable, array(
6405
                'where' => array(
6406
                    "name LIKE %?% " => $term,
6407
                    "OR description LIKE %?% " => $term,
6408
                ),
6409
            ));
6410
6411
            return $resultData;
6412
        }
6413
6414
        foreach ($resultData as $id => &$session) {
6415
            $session['extra'] = self::getFilteredExtraFields($id, $extraFieldsToInclude);
6416
        }
6417
6418
        return $resultData;
6419
    }
6420
6421
    /**
6422
     * @param $sessionId
6423
     * @param array $extraFieldsToInclude
6424
     * @return array
6425
     */
6426
    public static function getFilteredExtraFields($sessionId, $extraFieldsToInclude = array())
6427
    {
6428
        $extraData = array();
6429
6430
        $variables = array();
6431
        $variablePlaceHolders = array();
6432
6433
        foreach ($extraFieldsToInclude as $sessionExtraField) {
6434
            $variablePlaceHolders[] = "?";
6435
            $variables[] = Database::escape_string($sessionExtraField);
6436
        }
6437
6438
        $sessionExtraField = new ExtraField('session');
6439
        $fieldList = $sessionExtraField->get_all(array(
6440
            "variable IN ( " . implode(", ", $variablePlaceHolders) . " ) " => $variables,
6441
        ));
6442
6443
        $fields = array();
6444
6445
        // Index session fields
6446
        foreach ($fieldList as $field) {
6447
            $fields[$field['id']] = $field['variable'];
6448
        }
6449
6450
        // Get session field values
6451
        $extra = new ExtraFieldValue('session');
6452
        $sessionFieldValueList = $extra->get_all(
6453
            array(
6454
                "field_id IN ( " . implode(", ", $variablePlaceHolders) . " )" => array_keys($fields),
6455
            )
6456
        );
6457
6458
        foreach ($sessionFieldValueList as $sessionFieldValue) {
6459
            // Match session field values to session
6460
            if ($sessionFieldValue['item_id'] != $sessionId) {
6461
                continue;
6462
            }
6463
6464
            // Check if session field value is set in session field list
6465
            if (!isset($fields[$sessionFieldValue['field_id']])) {
6466
                continue;
6467
            }
6468
6469
            $extrafieldVariable = $fields[$sessionFieldValue['field_id']];
6470
            $extrafieldValue = $sessionFieldValue['value'];
6471
6472
            $extraData[] = array(
6473
                'variable' => $extrafieldVariable,
6474
                'value' => $extrafieldValue,
6475
            );
6476
        }
6477
6478
        return $extraData;
6479
    }
6480
6481
    /**
6482
     * @param int $sessionId
6483
     *
6484
     * @return bool
6485
     */
6486
    public static function isValidId($sessionId)
6487
    {
6488
        $sessionId = intval($sessionId);
6489
        if ($sessionId > 0) {
6490
            $rows = Database::select(
6491
                'id',
6492
                Database::get_main_table(TABLE_MAIN_SESSION),
6493
                array('where' => array('id = ?' => $sessionId))
6494
            );
6495
            if (!empty($rows)) {
6496
6497
                return true;
6498
            }
6499
        }
6500
6501
        return false;
6502
    }
6503
6504
    /**
6505
     * Get list of sessions based on users of a group for a group admin
6506
     * @param int $userId The user id
6507
     * @return array
6508
     */
6509 View Code Duplication
    public static function getSessionsFollowedForGroupAdmin($userId)
6510
    {
6511
        $sessionList = array();
6512
        $sessionTable = Database::get_main_table(TABLE_MAIN_SESSION);
6513
        $sessionUserTable = Database::get_main_table(TABLE_MAIN_SESSION_USER);
6514
        $userGroup = new UserGroup();
6515
        $userIdList = $userGroup->getGroupUsersByUser($userId);
6516
6517
        if (empty($userIdList)) {
6518
            return [];
6519
        }
6520
6521
        $sql = "SELECT DISTINCT s.*
6522
                FROM $sessionTable s
6523
                INNER JOIN $sessionUserTable sru ON s.id = sru.id_session
6524
                WHERE
6525
                    (sru.id_user IN (" . implode(', ', $userIdList) . ")
6526
                    AND sru.relation_type = 0
6527
                )";
6528
6529
        if (api_is_multiple_url_enabled()) {
6530
            $sessionAccessUrlTable = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
6531
            $accessUrlId = api_get_current_access_url_id();
6532
6533
            if ($accessUrlId != -1) {
6534
                $sql = "SELECT DISTINCT s.*
6535
                        FROM $sessionTable s
6536
                        INNER JOIN $sessionUserTable sru ON s.id = sru.id_session
6537
                        INNER JOIN $sessionAccessUrlTable srau ON s.id = srau.session_id
6538
                        WHERE
6539
                            srau.access_url_id = $accessUrlId
6540
                            AND (
6541
                                sru.id_user IN (" . implode(', ', $userIdList) . ")
6542
                                AND sru.relation_type = 0
6543
                            )";
6544
            }
6545
        }
6546
6547
        $result = Database::query($sql);
6548
6549
        while ($row = Database::fetch_assoc($result)) {
6550
            $sessionList[] = $row;
6551
        }
6552
6553
        return $sessionList;
6554
    }
6555
6556
    /**
6557
     * @param array $sessionInfo
6558
     * @return string
6559
     */
6560
    public static function getSessionVisibility($sessionInfo)
6561
    {
6562
        switch($sessionInfo['visibility']) {
6563
            case 1:
6564
                return get_lang('ReadOnly');
6565
            case 2:
6566
               return get_lang('Visible');
6567
            case 3:
6568
                return api_ucfirst(get_lang('Invisible'));
6569
        }
6570
    }
6571
6572
    /**
6573
     * Converts "start date" and "end date" to "From start date to end date" string
6574
     * @param string $startDate
6575
     * @param string $endDate
6576
     *
6577
     * @return string
6578
     */
6579
    private static function convertSessionDateToString($startDate, $endDate)
6580
    {
6581
        $startDateToLocal = '';
6582
        $endDateToLocal = '';
6583
        // This will clean the variables if 0000-00-00 00:00:00 the variable will be empty
6584
        if (isset($startDateToLocal)) {
6585
            $startDateToLocal = api_get_local_time($startDate, null, null, true);
6586
        }
6587
        if (isset($endDateToLocal)) {
6588
            $endDateToLocal = api_get_local_time($endDate, null, null, true);
6589
        }
6590
6591
        $result = '';
6592
        if (!empty($startDateToLocal) && !empty($endDateToLocal)) {
6593
            $result =  sprintf(get_lang('FromDateXToDateY'), $startDateToLocal, $endDateToLocal);
6594
        } else {
6595
            if (!empty($startDateToLocal)) {
6596
                $result = get_lang('From').' '.$startDateToLocal;
6597
            }
6598
            if (!empty($endDateToLocal)) {
6599
                $result = get_lang('Until').' '.$endDateToLocal;
6600
            }
6601
        }
6602
6603
        if (empty($result)) {
6604
            $result = get_lang('NoTimeLimits');
6605
        }
6606
6607
        return $result;
6608
    }
6609
6610
    /**
6611
     * Returns a human readable string
6612
     * @params array $sessionInfo An array with all the session dates
6613
     * @return string
6614
     */
6615
    public static function parseSessionDates($sessionInfo)
6616
    {
6617
        $displayDates = self::convertSessionDateToString(
6618
            $sessionInfo['display_start_date'],
6619
            $sessionInfo['display_end_date']
6620
        );
6621
6622
        $accessDates = self::convertSessionDateToString(
6623
            $sessionInfo['access_start_date'],
6624
            $sessionInfo['access_end_date']
6625
        );
6626
6627
        $coachDates = self::convertSessionDateToString(
6628
            $sessionInfo['coach_access_start_date'],
6629
            $sessionInfo['coach_access_end_date']
6630
        );
6631
6632
        $result = [
6633
            'access' => $accessDates,
6634
            'display' => $displayDates,
6635
            'coach' => $coachDates,
6636
        ];
6637
6638
        return $result;
6639
    }
6640
6641
    /**
6642
     * @param FormValidator $form
6643
     *
6644
     * @return array
6645
     */
6646
    public static function setForm(FormValidator & $form, $sessionId = 0)
6647
    {
6648
        $categoriesList = SessionManager::get_all_session_category();
6649
        $userInfo = api_get_user_info();
6650
6651
        $categoriesOptions = array(
6652
            '0' => get_lang('None'),
6653
        );
6654
6655
        if ($categoriesList != false) {
6656
            foreach ($categoriesList as $categoryItem) {
6657
                $categoriesOptions[$categoryItem['id']] = $categoryItem['name'];
6658
            }
6659
        }
6660
6661
        // Database Table Definitions
6662
        $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
6663
6664
        $form->addElement('text', 'name', get_lang('SessionName'), array(
6665
            'maxlength' => 50,
6666
        ));
6667
        $form->addRule('name', get_lang('ThisFieldIsRequired'), 'required');
6668
        $form->addRule('name', get_lang('SessionNameAlreadyExists'), 'callback', 'check_session_name');
6669
6670
        if (!api_is_platform_admin() && api_is_teacher()) {
6671
            $form->addElement(
6672
                'select',
6673
                'coach_username',
6674
                get_lang('CoachName'),
6675
                [api_get_user_id() => $userInfo['complete_name']],
6676
                array(
6677
                    'id' => 'coach_username',
6678
                    'style' => 'width:370px;',
6679
                )
6680
            );
6681
        } else {
6682
6683
            $sql = "SELECT COUNT(1) FROM $tbl_user WHERE status = 1";
6684
            $rs = Database::query($sql);
6685
            $countUsers = Database::result($rs, 0, 0);
6686
6687
            if (intval($countUsers) < 50) {
6688
                $orderClause = "ORDER BY ";
6689
                $orderClause .= api_sort_by_first_name() ? "firstname, lastname, username" : "lastname, firstname, username";
6690
6691
                $sql = "SELECT user_id, lastname, firstname, username
6692
                        FROM $tbl_user
6693
                        WHERE status = '1' ".
6694
                        $orderClause;
6695
6696 View Code Duplication
                if (api_is_multiple_url_enabled()) {
6697
                    $userRelAccessUrlTable = Database::get_main_table(
6698
                        TABLE_MAIN_ACCESS_URL_REL_USER
6699
                    );
6700
                    $accessUrlId = api_get_current_access_url_id();
6701
6702
                    if ($accessUrlId != -1) {
6703
                        $sql = "SELECT user.user_id, username, lastname, firstname
6704
                        FROM $tbl_user user
6705
                        INNER JOIN $userRelAccessUrlTable url_user
6706
                        ON (url_user.user_id = user.user_id)
6707
                        WHERE
6708
                            access_url_id = $accessUrlId AND
6709
                            status = 1 "
6710
                            .$orderClause;
6711
                    }
6712
                }
6713
6714
                $result = Database::query($sql);
6715
                $coachesList = Database::store_result($result);
6716
6717
                $coachesOptions = array();
6718 View Code Duplication
                foreach ($coachesList as $coachItem) {
6719
                    $coachesOptions[$coachItem['user_id']] =
6720
                        api_get_person_name($coachItem['firstname'], $coachItem['lastname']).' ('.$coachItem['username'].')';
6721
                }
6722
6723
                $form->addElement(
6724
                    'select',
6725
                    'coach_username',
6726
                    get_lang('CoachName'),
6727
                    $coachesOptions
6728
                );
6729
            } else {
6730
                $form->addElement(
6731
                    'select_ajax',
6732
                    'coach_username',
6733
                    get_lang('CoachName'),
6734
                    null,
6735
                    [
6736
                        'url' => api_get_path(WEB_AJAX_PATH) . 'session.ajax.php?a=search_general_coach',
6737
                        'width' => '100%',
6738
                    ]
6739
                );
6740
            }
6741
        }
6742
6743
        $form->addRule('coach_username', get_lang('ThisFieldIsRequired'), 'required');
6744
        $form->addHtml('<div id="ajax_list_coachs"></div>');
6745
6746
        $form->addButtonAdvancedSettings('advanced_params');
6747
        $form->addElement('html','<div id="advanced_params_options" style="display:none">');
6748
6749
        $form->addSelect('session_category', get_lang('SessionCategory'), $categoriesOptions, array(
6750
            'id' => 'session_category'
6751
        ));
6752
6753
        $form->addHtmlEditor(
6754
            'description',
6755
            get_lang('Description'),
6756
            false,
6757
            false,
6758
            array(
6759
                'ToolbarSet' => 'Minimal',
6760
            )
6761
        );
6762
6763
        $form->addElement('checkbox', 'show_description', null, get_lang('ShowDescription'));
6764
6765
        $visibilityGroup = array();
6766
        $visibilityGroup[] = $form->createElement('select', 'session_visibility', null, array(
6767
            SESSION_VISIBLE_READ_ONLY => get_lang('SessionReadOnly'),
6768
            SESSION_VISIBLE => get_lang('SessionAccessible'),
6769
            SESSION_INVISIBLE => api_ucfirst(get_lang('SessionNotAccessible')),
6770
        ));
6771
        $form->addGroup($visibilityGroup, 'visibility_group', get_lang('SessionVisibility'), null, false);
6772
6773
        $options = [
6774
            0 => get_lang('ByDuration'),
6775
            1 => get_lang('ByDates'),
6776
        ];
6777
6778
        $form->addSelect('access', get_lang('Access'), $options, array(
6779
            'onchange' => 'accessSwitcher()',
6780
            'id' => 'access',
6781
        ));
6782
6783
        $form->addElement('html', '<div id="duration" style="display:none">');
6784
6785
        $form->addElement(
6786
            'number',
6787
            'duration',
6788
            array(
6789
                get_lang('SessionDurationTitle'),
6790
                get_lang('SessionDurationDescription'),
6791
            ),
6792
            array(
6793
                'maxlength' => 50,
6794
            )
6795
        );
6796
6797
        $form->addElement('html', '</div>');
6798
6799
        $form->addElement('html', '<div id="date_fields" style="display:none">');
6800
6801
        // Dates
6802
6803
        $form->addDateTimePicker(
6804
            'access_start_date',
6805
            array(get_lang('SessionStartDate'), get_lang('SessionStartDateComment')),
6806
            array('id' => 'access_start_date')
6807
        );
6808
6809
        $form->addDateTimePicker(
6810
            'access_end_date',
6811
            array(get_lang('SessionEndDate'), get_lang('SessionEndDateComment')),
6812
            array('id' => 'access_end_date')
6813
        );
6814
6815
        $form->addRule(
6816
            array('access_start_date', 'access_end_date'),
6817
            get_lang('StartDateMustBeBeforeTheEndDate'),
6818
            'compare_datetime_text',
6819
            '< allow_empty'
6820
        );
6821
6822
        $form->addDateTimePicker(
6823
            'display_start_date',
6824
            array(
6825
                get_lang('SessionDisplayStartDate'),
6826
                get_lang('SessionDisplayStartDateComment'),
6827
            ),
6828
            array('id' => 'display_start_date')
6829
        );
6830
        $form->addDateTimePicker(
6831
            'display_end_date',
6832
            array(
6833
                get_lang('SessionDisplayEndDate'),
6834
                get_lang('SessionDisplayEndDateComment'),
6835
            ),
6836
            array('id' => 'display_end_date')
6837
        );
6838
6839
        $form->addRule(
6840
            array('display_start_date', 'display_end_date'),
6841
            get_lang('StartDateMustBeBeforeTheEndDate'),
6842
            'compare_datetime_text',
6843
            '< allow_empty'
6844
        );
6845
6846
        $form->addDateTimePicker(
6847
            'coach_access_start_date',
6848
            array(
6849
                get_lang('SessionCoachStartDate'),
6850
                get_lang('SessionCoachStartDateComment'),
6851
            ),
6852
            array('id' => 'coach_access_start_date')
6853
        );
6854
6855
        $form->addDateTimePicker(
6856
            'coach_access_end_date',
6857
            array(
6858
                get_lang('SessionCoachEndDate'),
6859
                get_lang('SessionCoachEndDateComment'),
6860
            ),
6861
            array('id' => 'coach_access_end_date')
6862
        );
6863
6864
        $form->addRule(
6865
            array('coach_access_start_date', 'coach_access_end_date'),
6866
            get_lang('StartDateMustBeBeforeTheEndDate'),
6867
            'compare_datetime_text',
6868
            '< allow_empty'
6869
        );
6870
6871
        $form->addElement('html', '</div>');
6872
6873
        $form->addCheckBox(
6874
            'send_subscription_notification',
6875
            [
6876
                get_lang('SendSubscriptionNotification'),
6877
                get_lang('SendAnEmailWhenAUserBeingSubscribed')
6878
            ]
6879
        );
6880
6881
        // Extra fields
6882
        $extra_field = new ExtraField('session');
6883
        $extra = $extra_field->addElements($form, $sessionId);
6884
6885
        $form->addElement('html','</div>');
6886
6887
        $js = $extra['jquery_ready_content'];
6888
6889
        return ['js' => $js];
6890
    }
6891
6892
    /**
6893
     * Gets the number of rows in the session table filtered through the given
6894
     * array of parameters
6895
     * @param array Array of options/filters/keys
6896
     * @return integer The number of rows, or false on wrong param
6897
     * @assert ('a') === false
6898
     */
6899
    static function get_count_admin_complete($options = array())
6900
    {
6901
        if (!is_array($options)) {
6902
            return false;
6903
        }
6904
        $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
6905
        $tbl_session_category = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
6906
        $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
6907
        $sessionCourseUserTable = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
6908
        $courseTable = Database::get_main_table(TABLE_MAIN_COURSE);
6909
6910
        $where = 'WHERE 1 = 1 ';
6911
        $user_id = api_get_user_id();
6912
6913
        if (api_is_session_admin() &&
6914
            api_get_setting('allow_session_admins_to_see_all_sessions') == 'false'
6915
        ) {
6916
            $where.=" WHERE s.session_admin_id = $user_id ";
6917
        }
6918
6919 View Code Duplication
        if (!empty($options['where'])) {
6920
            $options['where'] = str_replace('course_title', 'c.title', $options['where']);
6921
            $options['where'] = str_replace("( session_active = '0' )", '1=1',  $options['where']);
6922
6923
            $options['where'] = str_replace(
6924
                array("AND session_active = '1'  )", " AND (  session_active = '1'  )"),
6925
                array(') GROUP BY s.name HAVING session_active = 1 ', " GROUP BY s.name HAVING session_active = 1 " )
6926
                , $options['where']
6927
            );
6928
6929
            $options['where'] = str_replace(
6930
                array("AND session_active = '0'  )", " AND (  session_active = '0'  )"),
6931
                array(') GROUP BY s.name HAVING session_active = 0 ', " GROUP BY s.name HAVING session_active = '0' "),
6932
                $options['where']
6933
            );
6934
6935
            if (!empty($options['extra'])) {
6936
                $options['where'] = str_replace(' 1 = 1  AND', '', $options['where']);
6937
                $options['where'] = str_replace('AND', 'OR', $options['where']);
6938
6939
                foreach ($options['extra'] as $extra) {
6940
                    $options['where'] = str_replace($extra['field'], 'fv.field_id = '.$extra['id'].' AND fvo.option_value', $options['where']);
6941
                }
6942
            }
6943
            $where .= ' AND '.$options['where'];
6944
        }
6945
6946
        $today = api_get_utc_datetime();
6947
        $query_rows = "SELECT count(*) as total_rows, c.title as course_title, s.name,
6948
                        IF (
6949
                            (s.access_start_date <= '$today' AND '$today' < s.access_end_date) OR
6950
                            (s.access_start_date = '0000-00-00 00:00:00' AND s.access_end_date = '0000-00-00 00:00:00' ) OR
6951
                            (s.access_start_date IS NULL AND s.access_end_date IS NULL) OR
6952
                            (s.access_start_date <= '$today' AND ('0000-00-00 00:00:00' = s.access_end_date OR s.access_end_date IS NULL )) OR
6953
                            ('$today' < s.access_end_date AND ('0000-00-00 00:00:00' = s.access_start_date OR s.access_start_date IS NULL) )
6954
                        , 1, 0) as session_active
6955
                       FROM $tbl_session s
6956
                       LEFT JOIN  $tbl_session_category sc
6957
                       ON s.session_category_id = sc.id
6958
                       INNER JOIN $tbl_user u
6959
                       ON s.id_coach = u.user_id
6960
                       INNER JOIN $sessionCourseUserTable scu
6961
                       ON s.id = scu.session_id
6962
                       INNER JOIN $courseTable c
6963
                       ON c.id = scu.c_id
6964
                       $where ";
6965
6966
        if (api_is_multiple_url_enabled()) {
6967
            $table_access_url_rel_session= Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
6968
            $access_url_id = api_get_current_access_url_id();
6969
            if ($access_url_id != -1) {
6970
                $where.= " AND ar.access_url_id = $access_url_id ";
6971
6972
                $query_rows = "SELECT count(*) as total_rows
6973
                               FROM $tbl_session s
6974
                               LEFT JOIN  $tbl_session_category sc
6975
                               ON s.session_category_id = sc.id
6976
                               INNER JOIN $tbl_user u
6977
                               ON s.id_coach = u.user_id
6978
                               INNER JOIN $table_access_url_rel_session ar
6979
                               ON ar.session_id = s.id $where ";
6980
            }
6981
        }
6982
6983
        $result = Database::query($query_rows);
6984
        $num = 0;
6985
        if (Database::num_rows($result)) {
6986
            $rows = Database::fetch_array($result);
6987
            $num = $rows['total_rows'];
6988
        }
6989
6990
        return $num;
6991
    }
6992
6993
    /**
6994
     * @param string $list_type
6995
     * @return array
6996
     */
6997
    public static function getGridColumns($list_type = 'simple')
6998
    {
6999
        // Column config
7000
        $operators = array('cn', 'nc');
7001
        $date_operators = array('gt', 'ge', 'lt', 'le');
7002
7003
        switch ($list_type) {
7004
            case 'simple':
7005
                $columns = array(
7006
                    get_lang('Name'),
7007
                    get_lang('Category'),
7008
                    get_lang('SessionDisplayStartDate'),
7009
                    get_lang('SessionDisplayEndDate'),
7010
                    //get_lang('Coach'),
7011
                    //get_lang('Status'),
7012
                    //get_lang('CourseTitle'),
7013
                    get_lang('Visibility'),
7014
                );
7015
                $column_model = array (
7016
                    array('name'=>'name', 'index'=>'s.name', 'width'=>'160',  'align'=>'left', 'search' => 'true', 'searchoptions' => array('sopt' => $operators)),
7017
                    array('name'=>'category_name', 'index'=>'category_name', 'width'=>'40',  'align'=>'left', 'search' => 'true', 'searchoptions' => array('sopt' => $operators)),
7018
                    array('name'=>'display_start_date', 'index'=>'display_start_date', 'width'=>'50',   'align'=>'left', 'search' => 'true', 'searchoptions' => array('dataInit' => 'date_pick_today', 'sopt' => $date_operators)),
7019
                    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)),
7020
                    array('name'=>'visibility', 'index'=>'visibility',      'width'=>'40',   'align'=>'left', 'search' => 'false'),
7021
                );
7022
                break;
7023
            case 'complete':
7024
                $columns = array(
7025
                    get_lang('Name'),
7026
                    get_lang('SessionDisplayStartDate'),
7027
                    get_lang('SessionDisplayEndDate'),
7028
                    get_lang('Coach'),
7029
                    get_lang('Status'),
7030
                    get_lang('Visibility'),
7031
                    get_lang('CourseTitle'),
7032
                );
7033
                $column_model = array (
7034
                    array('name'=>'name', 'index'=>'s.name', 'width'=>'200',  'align'=>'left', 'search' => 'true', 'searchoptions' => array('sopt' => $operators)),
7035
                    array('name'=>'display_start_date', 'index'=>'display_start_date', 'width'=>'70',   'align'=>'left', 'search' => 'true', 'searchoptions' => array('dataInit' => 'date_pick_today', 'sopt' => $date_operators)),
7036
                    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)),
7037
                    array('name'=>'coach_name', 'index'=>'coach_name',     'width'=>'70',   'align'=>'left', 'search' => 'false', 'searchoptions' => array('sopt' => $operators)),
7038
                    array('name'=>'session_active', 'index'=>'session_active', 'width'=>'25',   'align'=>'left', 'search' => 'true', 'stype'=>'select',
7039
                        // for the bottom bar
7040
                        'searchoptions' => array(
7041
                            'defaultValue'  => '1',
7042
                            'value'         => '1:'.get_lang('Active').';0:'.get_lang('Inactive')),
7043
                        // for the top bar
7044
                        'editoptions' => array('value' => '" ":'.get_lang('All').';1:'.get_lang('Active').';0:'.get_lang('Inactive')),
7045
                    ),
7046
                    array('name'=>'visibility',     'index'=>'visibility',      'width'=>'40',   'align'=>'left', 'search' => 'false'),
7047
                    array('name'=>'course_title',    'index'=>'course_title',   'width'=>'50',   'hidden' => 'true', 'search' => 'true', 'searchoptions' => array('searchhidden' =>'true','sopt' => $operators)),
7048
                );
7049
                break;
7050
        }
7051
7052
        // Inject extra session fields
7053
        $session_field = new ExtraField('session');
7054
        $rules = $session_field->getRules($columns, $column_model);
7055
7056
        $column_model[] = array('name'=>'actions', 'index'=>'actions', 'width'=>'80',  'align'=>'left','formatter'=>'action_formatter','sortable'=>'false', 'search' => 'false');
7057
        $columns[] = get_lang('Actions');
7058
7059
        foreach ($column_model as $col_model) {
7060
            $simple_column_name[] = $col_model['name'];
7061
        }
7062
7063
        $return_array =  array(
7064
            'columns' => $columns,
7065
            'column_model' => $column_model,
7066
            'rules' => $rules,
7067
            'simple_column_name' => $simple_column_name,
7068
        );
7069
7070
        return $return_array;
7071
    }
7072
7073
    /**
7074
     * Converts all dates sent through the param array (given form) to correct dates with timezones
7075
     * @param array The dates The same array, with times converted
7076
     * @param boolean $applyFormat Whether apply the DATE_TIME_FORMAT_SHORT format for sessions
7077
     * @return array The same array, with times converted
7078
     */
7079
    static function convert_dates_to_local($params, $applyFormat = false)
7080
    {
7081
        if (!is_array($params)) {
7082
            return false;
7083
        }
7084
        $params['display_start_date'] = api_get_local_time($params['display_start_date'], null, null, true);
7085
        $params['display_end_date'] = api_get_local_time($params['display_end_date'], null, null, true);
7086
7087
        $params['access_start_date'] = api_get_local_time($params['access_start_date'], null, null, true);
7088
        $params['access_end_date'] = api_get_local_time($params['access_end_date'], null, null, true);
7089
7090
        $params['coach_access_start_date'] = isset($params['coach_access_start_date']) ? api_get_local_time($params['coach_access_start_date'], null, null, true) : null;
7091
        $params['coach_access_end_date'] = isset($params['coach_access_end_date']) ? api_get_local_time($params['coach_access_end_date'], null, null, true) : null;
7092
7093
        if ($applyFormat) {
7094 View Code Duplication
            if (isset($params['display_start_date'])) {
7095
                $params['display_start_date'] = api_format_date($params['display_start_date'], DATE_TIME_FORMAT_SHORT);
7096
            }
7097
7098 View Code Duplication
            if (isset($params['display_end_date'])) {
7099
                $params['display_end_date'] = api_format_date($params['display_end_date'], DATE_TIME_FORMAT_SHORT);
7100
            }
7101
7102 View Code Duplication
            if (isset($params['access_start_date'])) {
7103
                $params[''] = api_format_date($params['access_start_date'], DATE_TIME_FORMAT_SHORT);
7104
            }
7105
7106 View Code Duplication
            if (isset($params['access_end_date'])) {
7107
                $params['access_end_date'] = api_format_date($params['access_end_date'], DATE_TIME_FORMAT_SHORT);
7108
            }
7109
7110 View Code Duplication
            if (isset($params['coach_access_start_date'])) {
7111
                $params['coach_access_start_date'] = api_format_date($params['coach_access_start_date'], DATE_TIME_FORMAT_SHORT);
7112
            }
7113
7114 View Code Duplication
            if (isset($params['coach_access_end_date'])) {
7115
                $params['coach_access_end_date'] = api_format_date($params['coach_access_end_date'], DATE_TIME_FORMAT_SHORT);
7116
            }
7117
        }
7118
7119
        return $params;
7120
    }
7121
7122
    /**
7123
     * Gets the admin session list callback of the session/session_list.php
7124
     * page with all user/details in the right fomat
7125
     * @param array
7126
     * @result array Array of rows results
7127
     * @asset ('a') === false
7128
     */
7129
    public static function get_sessions_admin_complete($options = array())
7130
    {
7131
        if (!is_array($options)) {
7132
            return false;
7133
        }
7134
7135
        $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
7136
        $tbl_session_category = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
7137
        $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
7138
        $tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
7139
        $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
7140
7141
        $extraFieldTable = Database::get_main_table(TABLE_EXTRA_FIELD);
7142
        $tbl_session_field_values = Database::get_main_table(TABLE_EXTRA_FIELD_VALUES);
7143
        $tbl_session_field_options = Database::get_main_table(TABLE_EXTRA_FIELD_OPTIONS);
7144
7145
        $where = 'WHERE 1 = 1 ';
7146
        $user_id = api_get_user_id();
7147
7148 View Code Duplication
        if (!api_is_platform_admin()) {
7149
            if (api_is_session_admin() &&
7150
                api_get_setting('allow_session_admins_to_manage_all_sessions') == 'false'
7151
            ) {
7152
                $where.=" AND s.session_admin_id = $user_id ";
7153
            }
7154
        }
7155
7156
        $coach_name = " CONCAT(u.lastname , ' ', u.firstname) as coach_name ";
7157
        if (api_is_western_name_order()) {
7158
            $coach_name = " CONCAT(u.firstname, ' ', u.lastname) as coach_name ";
7159
        }
7160
7161
        $today = api_get_utc_datetime();
7162
        $inject_extra_fields = null;
7163
        $extra_fields = array();
7164
        $extra_fields_info = array();
7165
7166
        //for now only sessions
7167
        $extra_field = new ExtraField('session');
7168
        $double_fields = array();
7169
7170
        $extra_field_option = new ExtraFieldOption('session');
7171
7172
        if (isset($options['extra'])) {
7173
            $extra_fields = $options['extra'];
7174
            if (!empty($extra_fields)) {
7175
                foreach ($extra_fields as $extra) {
7176
                    $inject_extra_fields .= " IF (fv.field_id = {$extra['id']}, fvo.option_display_text, NULL ) as {$extra['field']} , ";
7177 View Code Duplication
                    if (isset($extra_fields_info[$extra['id']])) {
7178
                        $info = $extra_fields_info[$extra['id']];
7179
                    } else {
7180
                        $info = $extra_field->get($extra['id']);
7181
                        $extra_fields_info[$extra['id']] = $info;
7182
                    }
7183
7184
                    if ($info['field_type'] == ExtraField::FIELD_TYPE_DOUBLE_SELECT) {
7185
                        $double_fields[$info['id']] = $info;
7186
                    }
7187
                }
7188
            }
7189
        }
7190
7191
        $options_by_double = array();
7192 View Code Duplication
        foreach ($double_fields as $double) {
7193
            $my_options = $extra_field_option->get_field_options_by_field(
7194
                $double['id'],
7195
                true
7196
            );
7197
            $options_by_double['extra_'.$double['field_variable']] = $my_options;
7198
        }
7199
7200
        //sc.name as category_name,
7201
        $select = "
7202
                SELECT * FROM (
7203
                    SELECT DISTINCT
7204
                         IF (
7205
                            (s.access_start_date <= '$today' AND '$today' < s.access_end_date) OR
7206
                            (s.access_start_date = '0000-00-00 00:00:00' AND s.access_end_date = '0000-00-00 00:00:00' ) OR
7207
                            (s.access_start_date IS NULL AND s.access_end_date IS NULL) OR
7208
                            (s.access_start_date <= '$today' AND ('0000-00-00 00:00:00' = s.access_end_date OR s.access_end_date IS NULL )) OR
7209
                            ('$today' < s.access_end_date AND ('0000-00-00 00:00:00' = s.access_start_date OR s.access_start_date IS NULL) )
7210
                        , 1, 0) as session_active,
7211
                s.name,
7212
                s.nbr_courses,
7213
                s.nbr_users,
7214
                s.display_start_date,
7215
                s.display_end_date,
7216
                $coach_name,
7217
                access_start_date,
7218
                access_end_date,
7219
                s.visibility,
7220
                u.user_id,
7221
                $inject_extra_fields
7222
                c.title as course_title,
7223
                s.id ";
7224
7225 View Code Duplication
        if (!empty($options['where'])) {
7226
            if (!empty($options['extra'])) {
7227
                $options['where'] = str_replace(' 1 = 1  AND', '', $options['where']);
7228
                $options['where'] = str_replace('AND', 'OR', $options['where']);
7229
                foreach ($options['extra'] as $extra) {
7230
                    $options['where'] = str_replace($extra['field'], 'fv.field_id = '.$extra['id'].' AND fvo.option_value', $options['where']);
7231
                }
7232
            }
7233
            $options['where'] = str_replace('course_title', 'c.title', $options['where']);
7234
7235
            $options['where'] = str_replace("( session_active = '0' )", '1=1',  $options['where']);
7236
7237
            $options['where'] = str_replace(
7238
                array("AND session_active = '1'  )", " AND (  session_active = '1'  )"),
7239
                array(') GROUP BY s.name HAVING session_active = 1 ', " GROUP BY s.name HAVING session_active = 1 " )
7240
                , $options['where']
7241
            );
7242
7243
            $options['where'] = str_replace(
7244
                array("AND session_active = '0'  )", " AND (  session_active = '0'  )"),
7245
                array(') GROUP BY s.name HAVING session_active = 0 ', " GROUP BY s.name HAVING session_active = '0' "),
7246
                $options['where']
7247
            );
7248
7249
7250
            $where .= ' AND '.$options['where'];
7251
        }
7252
7253
        if (!empty($options['limit'])) {
7254
            $where .= " LIMIT ".$options['limit'];
7255
        }
7256
        $query = "$select FROM $tbl_session s
7257
                    LEFT JOIN $tbl_session_field_values fv
7258
                    ON (fv.item_id = s.id)
7259
                    LEFT JOIN $extraFieldTable f
7260
                    ON f.id = fv.field_id
7261
                    LEFT JOIN $tbl_session_field_options fvo
7262
                    ON (fv.field_id = fvo.field_id)
7263
                    LEFT JOIN $tbl_session_rel_course src
7264
                    ON (src.session_id = s.id)
7265
                    LEFT JOIN $tbl_course c
7266
                    ON (src.c_id = c.id)
7267
                    LEFT JOIN $tbl_session_category sc
7268
                    ON (s.session_category_id = sc.id)
7269
                    INNER JOIN $tbl_user u
7270
                    ON (s.id_coach = u.user_id) ".
7271
            $where;
7272
7273 View Code Duplication
        if (api_is_multiple_url_enabled()) {
7274
            $table_access_url_rel_session= Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
7275
            $access_url_id = api_get_current_access_url_id();
7276
            if ($access_url_id != -1) {
7277
                $where.= " AND ar.access_url_id = $access_url_id ";
7278
                $query = "$select
7279
                    FROM $tbl_session s
7280
                    LEFT JOIN $tbl_session_field_values fv ON (fv.session_id = s.id)
7281
                    LEFT JOIN $tbl_session_field_options fvo ON (fv.field_id = fvo.field_id)
7282
                    LEFT JOIN $tbl_session_rel_course src ON (src.id_session = s.id)
7283
                    LEFT JOIN $tbl_course c ON (src.c_id = c.id)
7284
                    LEFT JOIN $tbl_session_category sc ON (s.session_category_id = sc.id)
7285
                    INNER JOIN $tbl_user u ON (s.id_coach = u.user_id)
7286
                    INNER JOIN $table_access_url_rel_session ar ON (ar.session_id = s.id)
7287
                    $where";
7288
            }
7289
        }
7290
7291
        $query .= ") AS session_table";
7292
7293
        if (!empty($options['order'])) {
7294
            $query .= " ORDER BY ".$options['order'];
7295
        }
7296
7297
        //error_log($query);
7298
        //echo $query;
7299
7300
        $result = Database::query($query);
7301
        $formatted_sessions = array();
7302
7303
        if (Database::num_rows($result)) {
7304
            $sessions   = Database::store_result($result, 'ASSOC');
7305
            foreach ($sessions as $session) {
7306
                $session_id = $session['id'];
7307
                $session['name'] = Display::url($session['name'], "resume_session.php?id_session=".$session['id']);
7308
                $session['coach_name'] = Display::url($session['coach_name'], "user_information.php?user_id=".$session['user_id']);
7309 View Code Duplication
                if ($session['session_active'] == 1) {
7310
                    $session['session_active'] = Display::return_icon('accept.png', get_lang('Active'), array(), ICON_SIZE_SMALL);
7311
                } else {
7312
                    $session['session_active'] = Display::return_icon('error.png', get_lang('Inactive'), array(), ICON_SIZE_SMALL);
7313
                }
7314
7315
                $session = self::convert_dates_to_local($session);
7316
7317 View Code Duplication
                switch ($session['visibility']) {
7318
                    case SESSION_VISIBLE_READ_ONLY: //1
7319
                        $session['visibility'] =  get_lang('ReadOnly');
7320
                        break;
7321
                    case SESSION_VISIBLE:           //2
7322
                    case SESSION_AVAILABLE:         //4
7323
                        $session['visibility'] =  get_lang('Visible');
7324
                        break;
7325
                    case SESSION_INVISIBLE:         //3
7326
                        $session['visibility'] =  api_ucfirst(get_lang('Invisible'));
7327
                        break;
7328
                }
7329
7330
                // Cleaning double selects
7331 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...
7332
                    if (isset($options_by_double[$key]) || isset($options_by_double[$key.'_second'])) {
7333
                        $options = explode('::', $value);
7334
                    }
7335
                    $original_key = $key;
7336
7337
                    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...
7338
                    } else {
7339
                        $key = str_replace('_second', '', $key);
7340
                    }
7341
7342
                    if (isset($options_by_double[$key])) {
7343
                        if (isset($options[0])) {
7344
                            if (isset($options_by_double[$key][$options[0]])) {
7345
                                if (strpos($original_key, '_second') === false) {
7346
                                    $value = $options_by_double[$key][$options[0]]['option_display_text'];
7347
                                } else {
7348
                                    $value = $options_by_double[$key][$options[1]]['option_display_text'];
7349
                                }
7350
                            }
7351
                        }
7352
                    }
7353
                }
7354
7355
                // Magic filter
7356
                if (isset($formatted_sessions[$session_id])) {
7357
                    $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 7315 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...
7358
                } else {
7359
                    $formatted_sessions[$session_id] = $session;
7360
                }
7361
            }
7362
        }
7363
7364
        return $formatted_sessions;
7365
    }
7366
7367
    /**
7368
     * Compare two arrays
7369
     * @param array $array1
7370
     * @param array $array2
7371
     *
7372
     * @return array
7373
     */
7374
    static function compareArraysToMerge($array1, $array2)
7375
    {
7376
        if (empty($array2)) {
7377
            return $array1;
7378
        }
7379
        foreach ($array1 as $key => $item) {
7380
            if (!isset($array1[$key])) {
7381
                //My string is empty try the other one
7382
                if (isset($array2[$key]) && !empty($array2[$key])) {
7383
                    $array1[$key] = $array2[$key];
7384
                }
7385
            }
7386
        }
7387
        return $array1;
7388
    }
7389
7390
    /**
7391
     * Get link to the admin page for this session
7392
     * @param   int $id Session ID
7393
     * @return mixed    URL to the admin page to manage the session, or false on error
7394
     */
7395
    public static function getAdminPath($id)
7396
    {
7397
        $id = intval($id);
7398
        $session = self::fetch($id);
7399
        if (empty($session)) {
7400
            return false;
7401
        }
7402
        return api_get_path(WEB_CODE_PATH) . 'session/resume_session.php?id_session=' . $id;
7403
    }
7404
7405
    /**
7406
     * Get link to the user page for this session.
7407
     * If a course is provided, build the link to the course
7408
     * @param   int $id Session ID
7409
     * @param   int $courseId Course ID (optional) in case the link has to send straight to the course
7410
     * @return mixed    URL to the page to use the session, or false on error
7411
     */
7412
    public static function getPath($id, $courseId = 0)
7413
    {
7414
        $id = intval($id);
7415
        $session = self::fetch($id);
7416
        if (empty($session)) {
7417
            return false;
7418
        }
7419
        if (empty($courseId)) {
7420
            return api_get_path(WEB_CODE_PATH) . 'session/index.php?session_id=' . $id;
7421
        } else {
7422
            $courseInfo = api_get_course_info_by_id($courseId);
7423
            if ($courseInfo) {
7424
                return $courseInfo['course_public_url'].'?id_session='.$id;
7425
            }
7426
        }
7427
7428
        return false;
7429
    }
7430
7431
    /**
7432
     * Return an associative array 'id_course' => [id_session1, id_session2...]
7433
     * where course id_course is in sessions id_session1, id_session2
7434
     * for course where user is coach
7435
     * i.e. coach for the course or
7436
     * main coach for a session the course is in
7437
     * for a session category (or woth no session category if empty)
7438
     *
7439
     * @param $userId
7440
     *
7441
     * @return array
7442
     */
7443
    public static function getSessionCourseForUser($userId)
7444
    {
7445
        // list of COURSES where user is COURSE session coach
7446
        $listCourseCourseCoachSession = self::getCoursesForCourseSessionCoach($userId);
7447
7448
        // list of courses where user is MAIN session coach
7449
        $listCourseMainCoachSession = self::getCoursesForMainSessionCoach($userId);
7450
7451
        // merge these 2 array
7452
        $listResCourseSession = $listCourseCourseCoachSession;
7453
        foreach ($listCourseMainCoachSession as $courseId2 => $listSessionId2) {
7454
            if (isset($listResCourseSession[$courseId2])) {
7455
                // if sessionId array exists for this course
7456
                // same courseId, merge the list of session
7457
                foreach ($listCourseMainCoachSession[$courseId2] as $i => $sessionId2) {
7458
                    if (!in_array($sessionId2, $listResCourseSession[$courseId2])) {
7459
                        $listResCourseSession[$courseId2][] = $sessionId2;
7460
                    }
7461
                }
7462
            } else {
7463
                $listResCourseSession[$courseId2] = $listSessionId2;
7464
            }
7465
        }
7466
7467
        return $listResCourseSession;
7468
    }
7469
7470
    /**
7471
     * Return an associative array 'id_course' => [id_session1, id_session2...]
7472
     * where course id_course is in sessions id_session1, id_session2
7473
     * @param $userId
7474
     *
7475
     * @return array
7476
     */
7477
    public static function getCoursesForCourseSessionCoach($userId)
7478
    {
7479
        $listResCourseSession = array();
7480
        $tblCourse = Database::get_main_table(TABLE_MAIN_COURSE);
7481
        $tblSessionRelCourseRelUser = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
7482
7483
        $sql = "SELECT session_id, c_id, c.id
7484
                FROM $tblSessionRelCourseRelUser srcru
7485
                LEFT JOIN $tblCourse c
7486
                ON c.id = srcru.c_id
7487
                WHERE
7488
                    srcru.user_id =".intval($userId)." AND
7489
                    srcru.status = 2";
7490
7491
        $res = Database::query($sql);
7492
7493
        while ($data = Database::fetch_assoc($res)) {
7494
            if (self::isSessionDateOkForCoach($data['session_id'])) {
7495
                if (!isset($listResCourseSession[$data['id']])) {
7496
                    $listResCourseSession[$data['id']] = array();
7497
                }
7498
                $listResCourseSession[$data['id']][] = $data['session_id'];
7499
            }
7500
        }
7501
7502
        return $listResCourseSession;
7503
    }
7504
7505
    /**
7506
     * Return true if coach is allowed to access this session
7507
     * @param int $sessionId
7508
     * @return bool
7509
     */
7510
    public static function isSessionDateOkForCoach($sessionId)
7511
    {
7512
        return api_get_session_visibility($sessionId);
7513
        /*
7514
        $listSessionInfo = api_get_session_info($sessionId);
7515
        $dateStart = $listSessionInfo['date_start'];
7516
        $dateEnd = $listSessionInfo['date_end'];
7517
        $nbDaysAccessBeforeBeginning = $listSessionInfo['nb_days_access_before_beginning'];
7518
        $nbDaysAccessAfterEnd = $listSessionInfo['nb_days_access_after_end'];
7519
7520
        // no start date
7521
        if ($dateStart == '0000-00-00') {
7522
            return true;
7523
        }
7524
7525
        $now = time();
7526
7527
        $dateStartForCoach = api_strtotime($dateStart.' 00:00:00') - ($nbDaysAccessBeforeBeginning * 86400);
7528
        $dateEndForCoach = api_strtotime($dateEnd.' 00:00:00') + ($nbDaysAccessAfterEnd * 86400);
7529
7530
        if ($dateEnd == '0000-00-00') {
7531
            // start date but no end date
7532
            if ($dateStartForCoach <= $now) {
7533
                return true;
7534
            }
7535
        } else {
7536
            // start date and end date
7537
            if ($dateStartForCoach <= $now && $now <= $dateEndForCoach) {
7538
                return true;
7539
            }
7540
        }
7541
7542
        return false;*/
7543
    }
7544
7545
    /**
7546
     * Return an associative array 'id_course' => [id_session1, id_session2...]
7547
     * where course id_course is in sessions id_session1, id_session2
7548
     * @param $userId
7549
     *
7550
     * @return array
7551
     */
7552
    public static function getCoursesForMainSessionCoach($userId)
7553
    {
7554
        $listResCourseSession = array();
7555
        $tblSession = Database::get_main_table(TABLE_MAIN_SESSION);
7556
7557
        // list of SESSION where user is session coach
7558
        $sql = "SELECT id FROM $tblSession
7559
                WHERE id_coach = ".intval($userId);
7560
        $res = Database::query($sql);
7561
7562
        while ($data = Database::fetch_assoc($res)) {
7563
            $sessionId = $data['id'];
7564
            $listCoursesInSession = self::getCoursesInSession($sessionId);
7565
            foreach ($listCoursesInSession as $i => $courseId) {
7566
                if (self::isSessionDateOkForCoach($sessionId)) {
7567
                    if (!isset($listResCourseSession[$courseId])) {
7568
                        $listResCourseSession[$courseId] = array();
7569
                    }
7570
                    $listResCourseSession[$courseId][] = $sessionId;
7571
                }
7572
            }
7573
        }
7574
7575
        return $listResCourseSession;
7576
    }
7577
7578
    /**
7579
     * Return an array of course_id used in session $sessionId
7580
     * @param $sessionId
7581
     *
7582
     * @return array
7583
     */
7584
    public static function getCoursesInSession($sessionId)
7585
    {
7586
        $listResultsCourseId = array();
7587
        $tblSessionRelCourse = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
7588
        $tblCourse = Database::get_main_table(TABLE_MAIN_COURSE);
7589
7590
        // list of course in this session
7591
        $sql = "SELECT session_id, c.id
7592
                FROM $tblSessionRelCourse src
7593
                LEFT JOIN $tblCourse c
7594
                ON c.id = src.c_id
7595
                WHERE session_id = ".intval($sessionId);
7596
        $res = Database::query($sql);
7597
        while ($data = Database::fetch_assoc($res)) {
7598
            $listResultsCourseId[] = $data['id'];
7599
        }
7600
7601
        return $listResultsCourseId;
7602
    }
7603
7604
    /**
7605
     * Return an array of courses in session for user
7606
     * and for each courses the list of session that use this course for user
7607
     *
7608
     * [0] => array
7609
     *      userCatId
7610
     *      userCatTitle
7611
     *      courseInUserCatList
7612
     *          [0] => array
7613
     *              courseId
7614
     *              title
7615
     *              courseCode
7616
     *              sessionCatList
7617
     *                  [0] => array
7618
     *                      catSessionId
7619
     *                      catSessionName
7620
     *                      sessionList
7621
     *                          [0] => array
7622
     *                              sessionId
7623
     *                              sessionName
7624
     *
7625
     * @param $userId
7626
     *
7627
     * @return array
7628
     *
7629
     */
7630
    public static function getNamedSessionCourseForCoach($userId)
7631
    {
7632
        $listResults = array();
7633
        $listCourseSession = self::getSessionCourseForUser($userId);
7634
        foreach ($listCourseSession as $courseId => $listSessionId) {
7635
            // Course info
7636
            $courseInfo = api_get_course_info_by_id($courseId);
7637
            $listOneCourse = array();
7638
            $listOneCourse['courseId'] = $courseId;
7639
            $listOneCourse['title'] = $courseInfo['title'];
7640
            //$listOneCourse['courseCode'] = $courseInfo['code'];
7641
            $listOneCourse['course'] = $courseInfo;
7642
            $listOneCourse['sessionCatList'] = array();
7643
            $listCat = array();
7644
            foreach ($listSessionId as $i => $sessionId) {
7645
                // here we got all session for this course
7646
                // lets check there session categories
7647
                $sessionInfo = SessionManager::fetch($sessionId);
7648
                $catId = $sessionInfo['session_category_id'];
7649
                if (!isset($listCat[$catId])) {
7650
                    $listCatInfo = self::get_session_category($catId);
7651
                    $listCat[$catId] = array();
7652
                    $listCat[$catId]['catSessionId'] = $catId;
7653
                    $listCat[$catId]['catSessionName'] = $listCatInfo['name'];
7654
                    $listCat[$catId]['sessionList'] = array();
7655
                }
7656
                $listSessionInfo = SessionManager::fetch($sessionId);
7657
                $listSessionIdName = array(
7658
                    "sessionId" => $sessionId,
7659
                    "sessionName" => $listSessionInfo['name'],
7660
                );
7661
                $listCat[$catId]['sessionList'][] = $listSessionIdName;
7662
            }
7663
            // sort $listCat by catSessionName
7664
            usort($listCat, 'self::compareBySessionName');
7665
            // in each catSession sort sessionList by sessionName
7666
            foreach($listCat as $i => $listCatSessionInfo) {
7667
                $listSessionList = $listCatSessionInfo['sessionList'];
7668
                usort($listSessionList, 'self::compareCatSessionInfo');
7669
                $listCat[$i]['sessionList'] = $listSessionList;
7670
            }
7671
7672
            $listOneCourse['sessionCatList'] = $listCat;
7673
7674
            // user course category
7675
            list($userCatId, $userCatTitle) = CourseManager::getUserCourseCategoryForCourse(
7676
                $userId,
7677
                $courseId
7678
            );
7679
7680
            $userCatId = intval($userCatId);
7681
            $listResults[$userCatId]['courseInUserCategoryId'] =  $userCatId;
7682
            $listResults[$userCatId]['courseInUserCategoryTitle'] =  $userCatTitle;
7683
            $listResults[$userCatId]['courseInUserCatList'][] = $listOneCourse;
7684
        }
7685
7686
        // sort by user course cat
7687
        uasort($listResults, 'self::compareByUserCourseCat');
7688
7689
        // sort by course title
7690
        foreach ($listResults as $userCourseCatId => $tabCoursesInCat) {
7691
            $courseInUserCatList = $tabCoursesInCat['courseInUserCatList'];
7692
            uasort($courseInUserCatList, 'self::compareByCourse');
7693
            $listResults[$userCourseCatId]['courseInUserCatList'] = $courseInUserCatList;
7694
        }
7695
7696
        return $listResults;
7697
    }
7698
7699
    /**
7700
     * @param array $listA
7701
     * @param array $listB
7702
     * @return int
7703
     */
7704 View Code Duplication
    private static function compareCatSessionInfo($listA, $listB)
7705
    {
7706
        if ($listA['sessionName'] == $listB['sessionName']) {
7707
            return 0;
7708
        } else if($listA['sessionName'] > $listB['sessionName']) {
7709
            return 1;
7710
        } else {
7711
            return -1;
7712
        }
7713
    }
7714
7715
    /**
7716
     * @param array $listA
7717
     * @param array $listB
7718
     * @return int
7719
     */
7720
    private static function compareBySessionName($listA, $listB)
7721
    {
7722
        if ($listB['catSessionName'] == '') {
7723
            return -1;
7724
        } else if ($listA['catSessionName'] == '') {
7725
            return 1;
7726
        } else if ($listA['catSessionName'] == $listB['catSessionName']) {
7727
            return 0;
7728
        } else if($listA['catSessionName'] > $listB['catSessionName']) {
7729
            return 1;
7730
        } else {
7731
            return -1;
7732
        }
7733
    }
7734
7735
    /**
7736
     * @param array $listA
7737
     * @param array $listB
7738
     * @return int
7739
     */
7740 View Code Duplication
    private static function compareByUserCourseCat($listA, $listB)
7741
    {
7742
        if ($listA['courseInUserCategoryTitle'] == $listB['courseInUserCategoryTitle']) {
7743
            return 0;
7744
        } else if($listA['courseInUserCategoryTitle'] > $listB['courseInUserCategoryTitle']) {
7745
            return 1;
7746
        } else {
7747
            return -1;
7748
        }
7749
    }
7750
7751
    /**
7752
     * @param array $listA
7753
     * @param array $listB
7754
     * @return int
7755
     */
7756 View Code Duplication
    private static function compareByCourse($listA, $listB)
7757
    {
7758
        if ($listA['title'] == $listB['title']) {
7759
            return 0;
7760
        } else if($listA['title'] > $listB['title']) {
7761
            return 1;
7762
        } else {
7763
            return -1;
7764
        }
7765
    }
7766
7767
    /**
7768
     * Return HTML code for displaying session_course_for_coach
7769
     * @param $userId
7770
     * @return string
7771
     */
7772
    public static function getHtmlNamedSessionCourseForCoach($userId)
7773
    {
7774
        $htmlRes = '';
7775
7776
        $listInfo = self::getNamedSessionCourseForCoach($userId);
7777
        foreach ($listInfo as $i => $listCoursesInfo) {
7778
            $courseInfo = $listCoursesInfo['course'];
7779
            $courseCode = $listCoursesInfo['course']['code'];
7780
7781
            $listParamsCourse = array();
7782
            $listParamsCourse['icon'] = '<div style="float:left">
7783
                <input style="border:none;" type="button" onclick="$(\'#course-'.$courseCode.'\').toggle(\'fast\')" value="+" /></div>'.
7784
                Display::return_icon('blackboard.png', $courseInfo['title'], array(), ICON_SIZE_LARGE);
7785
            $listParamsCourse['link'] = '';
7786
            $listParamsCourse['title'] = Display::tag(
7787
                'a',
7788
                $courseInfo['title'],
7789
                array('href' => $listParamsCourse['link'])
7790
            );
7791
            $htmlCourse = '<div class="well" style="border-color:#27587D">'.
7792
                CourseManager::course_item_html($listParamsCourse, true);
7793
            // for each category of session
7794
            $htmlCatSessions = '';
7795
            foreach ($listCoursesInfo['sessionCatList'] as $j => $listCatSessionsInfo) {
7796
                // we got an array of session categories
7797
                $catSessionId = $listCoursesInfo['sessionCatList'][$j]['catSessionId'];
7798
                $catSessionName = $listCoursesInfo['sessionCatList'][$j]['catSessionName'];
7799
7800
                $listParamsCatSession['icon'] = Display::return_icon('folder_blue.png', $catSessionName, array(), ICON_SIZE_LARGE);
7801
                $listParamsCatSession['link'] = '';
7802
                $listParamsCatSession['title'] = $catSessionName;
7803
7804
                $marginShift = 20;
7805
                if ($catSessionName != '') {
7806
                    $htmlCatSessions .= '<div style="margin-left:'.$marginShift.'px;">' .
7807
                        CourseManager::course_item_html($listParamsCatSession, true) . '</div>';
7808
                    $marginShift = 40;
7809
                }
7810
7811
                // for each sessions
7812
                $listCatSessionSessionList = $listCoursesInfo['sessionCatList'][$j]['sessionList'];
7813
                $htmlSession = '';
7814
                foreach ($listCatSessionSessionList as $k => $listSessionInfo) {
7815
                    // we got an array of session info
7816
                    $sessionId = $listSessionInfo['sessionId'];
7817
                    $sessionName = $listSessionInfo['sessionName'];
7818
7819
                    $listParamsSession['icon'] = Display::return_icon('blackboard_blue.png', $sessionName, array(), ICON_SIZE_LARGE);
7820
                    $listParamsSession['link'] = '';
7821
                    $linkToCourseSession = $courseInfo['course_public_url'].'?id_session='.$sessionId;
7822
                    $listParamsSession['title'] =
7823
                        $sessionName.'<div style="font-weight:normal; font-style:italic">
7824
                            <a href="'.$linkToCourseSession.'">'.get_lang('GoToCourseInsideSession').'</a>
7825
                            </div>';
7826
                    $htmlSession .= '<div style="margin-left:'.$marginShift.'px;">'.
7827
                        CourseManager::course_item_html($listParamsSession, true).'</div>';
7828
                }
7829
                $htmlCatSessions .= $htmlSession;
7830
            }
7831
            $htmlRes .= $htmlCourse.'<div style="display:none" id="course-'.$courseCode.'">'.$htmlCatSessions.'</div></div>';
7832
        }
7833
7834
7835
7836
        return $htmlRes;
7837
    }
7838
}
7839