Passed
Push — 1.11.x ( bce6cd...c146d9 )
by Angel Fernando Quiroz
12:25
created

main/inc/lib/login.lib.php (4 issues)

1
<?php
2
/* For licensing terms, see /license.txt */
3
4
use Chamilo\UserBundle\Entity\User;
5
use ChamiloSession as Session;
6
7
/**
8
 * Class Login.
9
 *
10
 * @author Olivier Cauberghe <[email protected]>, Ghent University
11
 * @author Julio Montoya <[email protected]>
12
 *
13
 * @package chamilo.login
14
 */
15
class Login
16
{
17
    /**
18
     * Get user account list.
19
     *
20
     * @param array $user        array with keys: email, password, uid, loginName
21
     * @param bool  $reset
22
     * @param bool  $by_username
23
     *
24
     * @return string
25
     */
26
    public static function get_user_account_list($user, $reset = false, $by_username = false)
27
    {
28
        $portal_url = api_get_path(WEB_PATH);
29
30
        if (api_is_multiple_url_enabled()) {
31
            $access_url_id = api_get_current_access_url_id();
32
            if ($access_url_id != -1) {
33
                $url = api_get_access_url($access_url_id);
34
                $portal_url = $url['url'];
35
            }
36
        }
37
38
        if ($reset) {
39
            if ($by_username) {
40
                $secret_word = self::get_secret_word($user['email']);
41
                if ($reset) {
42
                    $reset_link = $portal_url."main/auth/lostPassword.php?reset=".$secret_word."&id=".$user['uid'];
43
                    $reset_link = Display::url($reset_link, $reset_link);
44
                } else {
45
                    $reset_link = get_lang('Pass')." : $user[password]";
46
                }
47
                $user_account_list = get_lang('YourRegistrationData')." : \n".
48
                    get_lang('UserName').' : '.$user['loginName']."\n".
49
                    get_lang('ResetLink').' : '.$reset_link;
50
51
                if ($user_account_list) {
52
                    $user_account_list = "\n-----------------------------------------------\n".$user_account_list;
53
                }
54
            } else {
55
                foreach ($user as $this_user) {
56
                    $secret_word = self::get_secret_word($this_user['email']);
57
                    if ($reset) {
58
                        $reset_link = $portal_url."main/auth/lostPassword.php?reset=".$secret_word."&id=".$this_user['uid'];
59
                        $reset_link = Display::url($reset_link, $reset_link);
60
                    } else {
61
                        $reset_link = get_lang('Pass')." : $this_user[password]";
62
                    }
63
                    $user_account_list[] =
64
                        get_lang('YourRegistrationData')." : \n".
65
                        get_lang('UserName').' : '.$this_user['loginName']."\n".
66
                        get_lang('ResetLink').' : '.$reset_link;
67
                }
68
                if ($user_account_list) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $user_account_list seems to be defined by a foreach iteration on line 55. Are you sure the iterator is never empty, otherwise this variable is not defined?
Loading history...
69
                    $user_account_list = implode("\n-----------------------------------------------\n", $user_account_list);
70
                }
71
            }
72
        } else {
73
            if (!$by_username) {
74
                $user = $user[0];
75
            }
76
            $reset_link = get_lang('Pass')." : $user[password]";
77
            $user_account_list =
78
                get_lang('YourRegistrationData')." : \n".
79
                get_lang('UserName').' : '.$user['loginName']."\n".
80
                $reset_link.'';
81
        }
82
83
        return $user_account_list;
84
    }
85
86
    /**
87
     * This function sends the actual password to the user.
88
     *
89
     * @param int $user
90
     *
91
     * @return string
92
     *
93
     * @author Olivier Cauberghe <[email protected]>, Ghent University
94
     */
95
    public static function send_password_to_user($user, $by_username = false)
96
    {
97
        $email_subject = "[".api_get_setting('siteName')."] ".get_lang('LoginRequest'); // SUBJECT
98
99
        if ($by_username) { // Show only for lost password
100
            $user_account_list = self::get_user_account_list($user, false, $by_username); // BODY
101
            $email_to = $user['email'];
102
        } else {
103
            $user_account_list = self::get_user_account_list($user); // BODY
104
            $email_to = $user[0]['email'];
105
        }
106
107
        $portal_url = api_get_path(WEB_PATH);
108
        if (api_is_multiple_url_enabled()) {
109
            $access_url_id = api_get_current_access_url_id();
110
            if ($access_url_id != -1) {
111
                $url = api_get_access_url($access_url_id);
112
                $portal_url = $url['url'];
113
            }
114
        }
115
116
        $email_body = get_lang('YourAccountParam')." ".$portal_url."\n\n$user_account_list";
117
        // SEND MESSAGE
118
        $sender_name = api_get_person_name(
119
            api_get_setting('administratorName'),
120
            api_get_setting('administratorSurname'),
121
            null,
122
            PERSON_NAME_EMAIL_ADDRESS
123
        );
124
        $email_body = nl2br($email_body);
125
126
        $email_admin = api_get_setting('emailAdministrator');
127
        $result = api_mail_html('', $email_to, $email_subject, $email_body, $sender_name, $email_admin);
128
        if ($result == 1) {
129
            return get_lang('YourPasswordHasBeenReset');
130
        } else {
131
            $mail = Display:: encrypted_mailto_link(
132
                api_get_setting('emailAdministrator'),
133
                api_get_person_name(
134
                    api_get_setting('administratorName'),
135
                    api_get_setting('administratorSurname')
136
                )
137
            );
138
139
            return sprintf(
140
                get_lang('ThisPlatformWasUnableToSendTheEmailPleaseContactXForMoreInformation'),
141
                $mail
142
            );
143
        }
144
    }
145
146
    /**
147
     * Handle encrypted password, send an email to a user with his password.
148
     *
149
     * @param int user id
150
     * @param bool $by_username
151
     *
152
     * @return string
153
     *
154
     * @author Olivier Cauberghe <[email protected]>, Ghent University
155
     */
156
    public static function handle_encrypted_password($user, $by_username = false)
157
    {
158
        $email_subject = "[".api_get_setting('siteName')."] ".get_lang('LoginRequest'); // SUBJECT
159
160
        if ($by_username) {
161
            // Show only for lost password
162
            $user_account_list = self::get_user_account_list($user, true, $by_username); // BODY
163
            $email_to = $user['email'];
164
        } else {
165
            $user_account_list = self::get_user_account_list($user, true); // BODY
166
            $email_to = $user[0]['email'];
167
        }
168
        $email_body = get_lang('DearUser')." :\n".get_lang('password_request')."\n";
169
        $email_body .= $user_account_list."\n-----------------------------------------------\n\n";
170
        $email_body .= get_lang('PasswordEncryptedForSecurity');
171
        $email_body .= "\n\n".
172
            get_lang('SignatureFormula').",\n".
173
            api_get_setting('administratorName')." ".
174
            api_get_setting('administratorSurname')."\n".
175
            get_lang('PlataformAdmin')." - ".
176
            api_get_setting('siteName');
177
178
        $sender_name = api_get_person_name(
179
            api_get_setting('administratorName'),
180
            api_get_setting('administratorSurname'),
181
            null,
182
            PERSON_NAME_EMAIL_ADDRESS
183
        );
184
        $email_admin = api_get_setting('emailAdministrator');
185
        $email_body = nl2br($email_body);
186
187
        $result = @api_mail_html(
188
            '',
189
            $email_to,
190
            $email_subject,
191
            $email_body,
192
            $sender_name,
193
            $email_admin
194
        );
195
196
        if ($result == 1) {
197
            $passwordEncryption = api_get_configuration_value('password_encryption');
198
            if ($passwordEncryption === 'none') {
199
                return get_lang('YourPasswordHasBeenEmailed');
200
            }
201
202
            return get_lang('AnEmailToResetYourPasswordHasBeenSent');
203
        } else {
204
            $admin_email = Display:: encrypted_mailto_link(
205
                api_get_setting('emailAdministrator'),
206
                api_get_person_name(
207
                    api_get_setting('administratorName'),
208
                    api_get_setting('administratorSurname')
209
                )
210
            );
211
            $message = sprintf(
212
                get_lang('ThisPlatformWasUnableToSendTheEmailPleaseContactXForMoreInformation'),
213
                $admin_email
214
            );
215
216
            return $message;
217
        }
218
    }
219
220
    public static function sendResetEmail(User $user)
221
    {
222
        $uniqueId = api_get_unique_id();
223
        $user->setConfirmationToken($uniqueId);
224
        $user->setPasswordRequestedAt(new \DateTime());
225
226
        Database::getManager()->persist($user);
227
        Database::getManager()->flush();
228
229
        $url = api_get_path(WEB_CODE_PATH).'auth/reset.php?token='.$uniqueId;
230
        $mailSubject = get_lang('ResetPasswordInstructions');
231
        $mailBody = sprintf(
232
            get_lang('ResetPasswordCommentWithUrl'),
233
            $url
234
        );
235
236
        api_mail_html(
237
            UserManager::formatUserFullName($user),
238
            $user->getEmail(),
239
            $mailSubject,
240
            $mailBody
241
        );
242
        Display::addFlash(Display::return_message(get_lang('CheckYourEmailAndFollowInstructions')));
243
    }
244
245
    /**
246
     * Gets the secret word.
247
     *
248
     * @author Olivier Cauberghe <[email protected]>, Ghent University
249
     */
250
    public static function get_secret_word($add)
251
    {
252
        return $secret_word = sha1($add);
253
    }
254
255
    /**
256
     * Resets a password.
257
     *
258
     * @author Olivier Cauberghe <[email protected]>, Ghent University
259
     */
260
    public static function reset_password($secret, $id, $by_username = false)
261
    {
262
        $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
263
        $id = (int) $id;
264
        $sql = "SELECT
265
                    user_id AS uid,
266
                    lastname AS lastName,
267
                    firstname AS firstName,
268
                    username AS loginName,
269
                    password,
270
                    email,
271
                    auth_source
272
                FROM $tbl_user
273
                WHERE user_id = $id";
274
        $result = Database::query($sql);
275
        $num_rows = Database::num_rows($result);
276
277
        if ($result && $num_rows > 0) {
278
            $user = Database::fetch_array($result);
279
280
            if ($user['auth_source'] === 'extldap') {
281
                return get_lang('CouldNotResetPassword');
282
            }
283
        } else {
284
            return get_lang('CouldNotResetPassword');
285
        }
286
287
        if (self::get_secret_word($user['email']) == $secret) {
288
            // OK, secret word is good. Now change password and mail it.
289
            $user['password'] = api_generate_password();
290
            UserManager::updatePassword($id, $user['password']);
291
292
            return self::send_password_to_user($user, $by_username);
293
        }
294
295
        return get_lang('NotAllowed');
296
    }
297
298
    /**
299
     * @global bool   $is_platformAdmin
300
     * @global bool   $is_allowedCreateCourse
301
     * @global object $_user
302
     *
303
     * @param bool $reset
304
     */
305
    public static function init_user($user_id, $reset)
306
    {
307
        global $is_platformAdmin;
308
        global $is_allowedCreateCourse;
309
        global $_user;
310
311
        if (isset($reset) && $reset) {    // session data refresh requested
312
            unset($_SESSION['_user']['uidReset']);
313
            $is_platformAdmin = false;
314
            $is_allowedCreateCourse = false;
315
            $_user['user_id'] = $user_id;
316
317
            if (isset($_user['user_id']) && $_user['user_id'] && !api_is_anonymous()) {
318
                // a uid is given (log in succeeded)
319
                $user_table = Database::get_main_table(TABLE_MAIN_USER);
320
                $admin_table = Database::get_main_table(TABLE_MAIN_ADMIN);
321
322
                $sql = "SELECT user.*, a.user_id is_admin
323
                        FROM $user_table
324
                        LEFT JOIN $admin_table a
325
                        ON user.user_id = a.user_id
326
                        WHERE user.user_id = ".$_user['user_id'];
327
328
                $result = Database::query($sql);
329
330
                if (Database::num_rows($result) > 0) {
331
                    // Extracting the user data
332
333
                    $uData = Database::fetch_array($result);
334
335
                    $_user['firstName'] = $uData['firstname'];
336
                    $_user['lastName'] = $uData['lastname'];
337
                    $_user['mail'] = $uData['email'];
338
                    $_user['official_code'] = $uData['official_code'];
339
                    $_user['picture_uri'] = $uData['picture_uri'];
340
                    $_user['user_id'] = $uData['user_id'];
341
                    $_user['language'] = $uData['language'];
342
                    $_user['auth_source'] = $uData['auth_source'];
343
                    $_user['theme'] = $uData['theme'];
344
                    $_user['status'] = $uData['status'];
345
346
                    $is_platformAdmin = (bool) (!is_null($uData['is_admin']));
347
                    $is_allowedCreateCourse = (bool) (($uData['status'] == 1) or (api_get_setting('drhCourseManagerRights') and $uData['status'] == 4));
348
                    ConditionalLogin::check_conditions($uData);
349
350
                    Session::write('_user', $_user);
351
                    UserManager::update_extra_field_value($_user['user_id'], 'already_logged_in', 'true');
352
                    Session::write('is_platformAdmin', $is_platformAdmin);
353
                    Session::write('is_allowedCreateCourse', $is_allowedCreateCourse);
354
                } else {
355
                    header('location:'.api_get_path(WEB_PATH));
356
                    //exit("WARNING UNDEFINED UID !! ");
357
                }
358
            } else { // no uid => logout or Anonymous
359
                Session::erase('_user');
360
                Session::erase('_uid');
361
            }
362
363
            Session::write('is_platformAdmin', $is_platformAdmin);
364
            Session::write('is_allowedCreateCourse', $is_allowedCreateCourse);
365
        } else { // continue with the previous values
366
            $_user = $_SESSION['_user'];
367
            $is_platformAdmin = $_SESSION['is_platformAdmin'];
368
            $is_allowedCreateCourse = $_SESSION['is_allowedCreateCourse'];
369
        }
370
    }
371
372
    /**
373
     * @deprecated
374
     *
375
     * @global bool $is_platformAdmin
376
     * @global bool $is_allowedCreateCourse
377
     * @global object $_user
378
     * @global int $_cid
379
     * @global array $_course
380
     * @global int $_real_cid
381
     * @global type $_courseUser
382
     * @global type $is_courseAdmin
383
     * @global type $is_courseTutor
384
     * @global type $is_session_general_coach
385
     * @global type $is_courseMember
386
     * @global type $is_sessionAdmin
387
     * @global type $is_allowed_in_course
388
     *
389
     * @param type $course_id
390
     * @param bool $reset
391
     */
392
    public static function init_course($course_id, $reset)
393
    {
394
        global $is_platformAdmin;
395
        global $_user;
396
397
        global $_cid;
398
        global $_course;
399
        global $_real_cid;
400
401
        global $is_courseAdmin; //course teacher
402
        global $is_courseTutor; //course teacher - some rights
403
        global $is_session_general_coach; //course coach
404
        global $is_courseMember; //course student
405
        global $is_sessionAdmin;
406
        global $is_allowed_in_course;
407
408
        if ($reset) {
409
            // Course session data refresh requested or empty data
410
            if ($course_id) {
0 ignored issues
show
$course_id is of type type, thus it always evaluated to true.
Loading history...
411
                $course_table = Database::get_main_table(TABLE_MAIN_COURSE);
412
                $course_cat_table = Database::get_main_table(TABLE_MAIN_CATEGORY);
413
                $sql = "SELECT course.*, course_category.code faCode, course_category.name faName
414
                        FROM $course_table
415
                        LEFT JOIN $course_cat_table
416
                        ON course.category_code = course_category.code
417
                        WHERE course.code = '$course_id'";
418
                $result = Database::query($sql);
419
420
                if (Database::num_rows($result) > 0) {
421
                    $course_data = Database::fetch_array($result);
422
                    //@TODO real_cid should be cid, for working with numeric course id
423
                    $_real_cid = $course_data['id'];
424
425
                    $_cid = $course_data['code'];
426
                    $_course = [];
427
                    $_course['real_id'] = $course_data['id'];
428
                    $_course['id'] = $course_data['code']; //auto-assigned integer
429
                    $_course['code'] = $course_data['code'];
430
                    $_course['name'] = $course_data['title'];
431
                    $_course['title'] = $course_data['title'];
432
                    $_course['official_code'] = $course_data['visual_code']; // use in echo
433
                    $_course['sysCode'] = $course_data['code']; // use as key in db
434
                    $_course['path'] = $course_data['directory']; // use as key in path
435
                    $_course['titular'] = $course_data['tutor_name']; // this should be deprecated and use the table course_rel_user
436
                    $_course['language'] = $course_data['course_language'];
437
                    $_course['extLink']['url'] = $course_data['department_url'];
438
                    $_course['extLink']['name'] = $course_data['department_name'];
439
                    $_course['categoryCode'] = $course_data['faCode'];
440
                    $_course['categoryName'] = $course_data['faName'];
441
                    $_course['visibility'] = $course_data['visibility'];
442
                    $_course['subscribe_allowed'] = $course_data['subscribe'];
443
                    $_course['unsubscribe'] = $course_data['unsubscribe'];
444
                    $_course['activate_legal'] = $course_data['activate_legal'];
445
                    $_course['show_score'] = $course_data['show_score']; //used in the work tool
446
447
                    Session::write('_cid', $_cid);
448
                    Session::write('_course', $_course);
449
450
                    //@TODO real_cid should be cid, for working with numeric course id
451
                    Session::write('_real_cid', $_real_cid);
452
453
                    // if a session id has been given in url, we store the session
454
455
                    // Database Table Definitions
456
                    $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
457
458
                    if (!empty($_GET['id_session'])) {
459
                        $_SESSION['id_session'] = intval($_GET['id_session']);
460
                        $sql = 'SELECT name FROM '.$tbl_session.' WHERE id="'.intval($_SESSION['id_session']).'"';
461
                        $rs = Database::query($sql);
462
                        if ($rs != null) {
463
                            list($_SESSION['session_name']) = Database::fetch_array($rs);
464
                        }
465
                    } else {
466
                        Session::erase('session_name');
467
                        Session::erase('id_session');
468
                    }
469
470
                    if (!isset($_SESSION['login_as'])) {
471
                        // Course login
472
                        if (isset($_user['user_id'])) {
473
                            Event::eventCourseLogin(
474
                                api_get_course_int_id(),
475
                                $_user['user_id'],
476
                                api_get_session_id()
477
                            );
478
                        }
479
                    }
480
                } else {
481
                    //exit("WARNING UNDEFINED CID !! ");
482
                    header('location:'.api_get_path(WEB_PATH));
483
                }
484
            } else {
485
                Session::erase('_cid');
486
                Session::erase('_real_cid');
487
                Session::erase('_course');
488
489
                if (!empty($_SESSION)) {
490
                    foreach ($_SESSION as $key => $session_item) {
491
                        if (strpos($key, 'lp_autolaunch_') === false) {
492
                            continue;
493
                        } else {
494
                            if (isset($_SESSION[$key])) {
495
                                Session::erase($key);
496
                            }
497
                        }
498
                    }
499
                }
500
                //Deleting session info
501
                if (api_get_session_id()) {
502
                    Session::erase('id_session');
503
                    Session::erase('session_name');
504
                }
505
            }
506
        } else {
507
            // Continue with the previous values
508
            if (empty($_SESSION['_course']) or empty($_SESSION['_cid'])) { //no previous values...
509
                $_cid = -1; //set default values that will be caracteristic of being unset
510
                $_course = -1;
511
            } else {
512
                $_cid = $_SESSION['_cid'];
513
                $_course = $_SESSION['_course'];
514
515
                // these lines are usefull for tracking. Indeed we can have lost the id_session and not the cid.
516
                // Moreover, if we want to track a course with another session it can be usefull
517
                if (!empty($_GET['id_session'])) {
518
                    $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
519
                    $sql = 'SELECT name FROM '.$tbl_session.' WHERE id="'.intval($_SESSION['id_session']).'"';
520
                    $rs = Database::query($sql);
521
                    if ($rs != null) {
522
                        list($_SESSION['session_name']) = Database::fetch_array($rs);
523
                    }
524
                    $_SESSION['id_session'] = intval($_GET['id_session']);
525
                }
526
527
                if (!isset($_SESSION['login_as'])) {
528
                    $save_course_access = true;
529
530
                    //The value  $_dont_save_user_course_access should be added before the call of global.inc.php see the main/inc/chat.ajax.php file
531
                    //Disables the updates in the TRACK_E_COURSE_ACCESS table
532
                    global $_dont_save_user_course_access;
533
                    if (isset($_dont_save_user_course_access) && $_dont_save_user_course_access == true) {
534
                        $save_course_access = false;
535
                    } else {
536
                        Event::courseLogout(
537
                            [
538
                                'uid' => intval($_user['user_id']),
539
                                'cid' => api_get_course_int_id(),
540
                                'sid' => api_get_session_id(),
541
                            ]
542
                        );
543
                    }
544
                }
545
            }
546
        }
547
        /*  COURSE / USER REL. INIT */
548
549
        $session_id = api_get_session_id();
550
        $user_id = isset($_user['user_id']) ? $_user['user_id'] : null;
551
552
        //Course permissions
553
        $is_courseAdmin = false; //course teacher
554
        $is_courseTutor = false; //course teacher - some rights
555
        $is_courseMember = false; //course student
556
        //Course - User permissions
557
        $is_sessionAdmin = false;
558
559
        if ($reset) {
560
            if (isset($user_id) && $user_id && isset($_cid) && $_cid) {
561
                //Check if user is subscribed in a course
562
                $course_user_table = Database::get_main_table(TABLE_MAIN_COURSE_USER);
563
                $sql = "SELECT * FROM $course_user_table
564
                       WHERE
565
                        user_id  = '".$user_id."' AND
566
                        relation_type <> ".COURSE_RELATION_TYPE_RRHH." AND
567
                        c_id = '".$_real_cid."'";
568
                $result = Database::query($sql);
569
570
                $cuData = null;
571
                if (Database::num_rows($result) > 0) {
572
                    // this  user have a recorded state for this course
573
                    $cuData = Database::fetch_array($result, 'ASSOC');
574
                    $is_courseAdmin = (bool) $cuData['status'] == 1;
575
                    $is_courseTutor = (bool) $cuData['is_tutor'] == 1;
576
                    $is_courseMember = true;
577
578
                    // Checking if the user filled the course legal agreement
579
                    if ($_course['activate_legal'] == 1 && !api_is_platform_admin()) {
580
                        $user_is_subscribed = CourseManager::is_user_accepted_legal(
581
                            $user_id,
582
                            $_course['id'],
583
                            $session_id
584
                        );
585
586
                        if (!$user_is_subscribed) {
587
                            $url = api_get_path(WEB_CODE_PATH).'course_info/legal.php?course_code='.$_course['code'].'&session_id='.$session_id;
588
                            header('Location: '.$url);
589
                            exit;
590
                        }
591
                    }
592
                }
593
594
                //We are in a session course? Check session permissions
595
                if (!empty($session_id)) {
596
                    //I'm not the teacher of the course
597
                    if ($is_courseAdmin == false) {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
598
                        // this user has no status related to this course
599
                        // The user is subscribed in a session? The user is a Session coach a Session admin ?
600
601
                        $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
602
                        $tbl_session_course_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
603
604
                        //Session coach, session admin, course coach admin
605
                        $sql = "SELECT session.id_coach, session_admin_id, session_rcru.user_id
606
                                FROM $tbl_session session, $tbl_session_course_user session_rcru
607
                                WHERE
608
                                   session_rcru.session_id = session.id AND
609
                                   session_rcru.c_id = '$_real_cid' AND
610
                                   session_rcru.user_id = '$user_id' AND
611
                                   session_rcru.session_id  = $session_id AND
612
                                   session_rcru.status = 2";
613
614
                        $result = Database::query($sql);
615
                        $row = Database::store_result($result);
616
617
                        //I'm a session admin?
618
                        if (isset($row) && isset($row[0]) && $row[0]['session_admin_id'] == $user_id) {
619
                            $is_courseMember = false;
620
                            $is_courseTutor = false;
621
                            $is_courseAdmin = false;
622
                            $is_session_general_coach = false;
623
                            $is_sessionAdmin = true;
624
                        } else {
625
                            //Im a coach or a student?
626
                            $sql = "SELECT user_id, status
627
                                    FROM ".$tbl_session_course_user."
628
                                    WHERE
629
                                        c_id = '$_cid' AND
630
                                        user_id = '".$user_id."' AND
631
                                        session_id = '".$session_id."'
632
                                    LIMIT 1";
633
                            $result = Database::query($sql);
634
635
                            if (Database::num_rows($result)) {
636
                                $row = Database::fetch_array($result, 'ASSOC');
637
                                $session_course_status = $row['status'];
638
639
                                switch ($session_course_status) {
640
                                    case '2': // coach - teacher
641
                                        $is_courseMember = true;
642
                                        $is_courseTutor = true;
643
                                        $is_session_general_coach = true;
644
                                        $is_sessionAdmin = false;
645
646
                                        if (api_get_setting('extend_rights_for_coach') == 'true') {
647
                                            $is_courseAdmin = true;
648
                                        } else {
649
                                            $is_courseAdmin = false;
650
                                        }
651
                                        break;
652
                                    case '0': //student
653
                                        $is_courseMember = true;
654
                                        $is_courseTutor = false;
655
                                        $is_courseAdmin = false;
656
                                        $is_sessionAdmin = false;
657
                                        break;
658
                                    default:
659
                                        //unregister user
660
                                        $is_courseMember = false;
661
                                        $is_courseTutor = false;
662
                                        $is_courseAdmin = false;
663
                                        $is_sessionAdmin = false;
664
                                        break;
665
                                }
666
                            } else {
667
                                //unregister user
668
                                $is_courseMember = false;
669
                                $is_courseTutor = false;
670
                                $is_courseAdmin = false;
671
                                $is_sessionAdmin = false;
672
                            }
673
                        }
674
                    }
675
676
                    //If I'm the admin platform i'm a teacher of the course
677
                    if ($is_platformAdmin) {
678
                        $is_courseAdmin = true;
679
                    }
680
                }
681
            } else { // keys missing => not anymore in the course - user relation
682
                // course
683
                $is_courseMember = false;
684
                $is_courseAdmin = false;
685
                $is_courseTutor = false;
686
                $is_session_general_coach = false;
687
                $is_sessionAdmin = false;
688
            }
689
690
            //Checking the course access
691
            $is_allowed_in_course = false;
692
693
            if (isset($_course)) {
694
                switch ($_course['visibility']) {
695
                    case COURSE_VISIBILITY_OPEN_WORLD: //3
696
                        $is_allowed_in_course = true;
697
                        break;
698
                    case COURSE_VISIBILITY_OPEN_PLATFORM: //2
699
                        if (isset($user_id) && !api_is_anonymous($user_id)) {
700
                            $is_allowed_in_course = true;
701
                        }
702
                        break;
703
                    case COURSE_VISIBILITY_REGISTERED: //1
704
                        if ($is_platformAdmin || $is_courseMember) {
705
                            $is_allowed_in_course = true;
706
                        }
707
                        break;
708
                    case COURSE_VISIBILITY_CLOSED: //0
709
                        if ($is_platformAdmin || $is_courseAdmin) {
710
                            $is_allowed_in_course = true;
711
                        }
712
                        break;
713
                    case COURSE_VISIBILITY_HIDDEN: //4
714
                        if ($is_platformAdmin) {
715
                            $is_allowed_in_course = true;
716
                        }
717
                        break;
718
                }
719
            }
720
721
            // check the session visibility
722
            if ($is_allowed_in_course == true) {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
723
                //if I'm in a session
724
725
                if ($session_id != 0) {
726
                    if (!$is_platformAdmin) {
727
                        // admin and session coach are *not* affected to the invisible session mode
728
                        // the coach is not affected because he can log in some days after the end date of a session
729
                        $session_visibility = api_get_session_visibility($session_id);
730
731
                        switch ($session_visibility) {
732
                            case SESSION_INVISIBLE:
733
                                $is_allowed_in_course = false;
734
                                break;
735
                        }
736
                        //checking date
737
                    }
738
                }
739
            }
740
741
            // save the states
742
            Session::write('is_courseAdmin', $is_courseAdmin);
743
            Session::write('is_courseMember', $is_courseMember);
744
            Session::write('is_courseTutor', $is_courseTutor);
745
            Session::write('is_session_general_coach', $is_session_general_coach);
746
            Session::write('is_allowed_in_course', $is_allowed_in_course);
747
            Session::write('is_sessionAdmin', $is_sessionAdmin);
748
        } else {
749
            // continue with the previous values
750
            $is_courseAdmin = Session::read('is_courseAdmin');
751
            $is_courseTutor = Session::read('is_courseTutor');
752
            $is_session_general_coach = Session::read('is_session_general_coach');
753
            $is_courseMember = Session::read('is_courseMember');
754
            $is_allowed_in_course = Session::read('is_allowed_in_course');
755
        }
756
    }
757
758
    /**
759
     * @global int $_cid
760
     * @global array $_course
761
     * @global int $_gid
762
     *
763
     * @param int  $group_id
764
     * @param bool $reset
765
     */
766
    public static function init_group($group_id, $reset)
767
    {
768
        global $_cid;
769
        global $_course;
770
        global $_gid;
771
772
        if ($reset) { // session data refresh requested
773
            if ($group_id && $_cid && !empty($_course['real_id'])) { // have keys to search data
774
                $group_table = Database::get_course_table(TABLE_GROUP);
775
                $sql = "SELECT * FROM $group_table WHERE c_id = ".$_course['real_id']." AND id = '$group_id'";
776
                $result = Database::query($sql);
777
                if (Database::num_rows($result) > 0) { // This group has recorded status related to this course
778
                    $gpData = Database::fetch_array($result);
779
                    $_gid = $gpData['id'];
780
                    Session::write('_gid', $_gid);
781
                } else {
782
                    Session::erase('_gid');
783
                }
784
            } elseif (isset($_SESSION['_gid']) || isset($_gid)) {
785
                // Keys missing => not anymore in the group - course relation
786
                Session::erase('_gid');
787
            }
788
        } elseif (isset($_SESSION['_gid'])) { // continue with the previous values
789
            $_gid = $_SESSION['_gid'];
790
        } else { //if no previous value, assign caracteristic undefined value
791
            $_gid = -1;
792
        }
793
794
        //set variable according to student_view_enabled choices
795
        if (api_get_setting('student_view_enabled') == "true") {
796
            if (isset($_GET['isStudentView'])) {
797
                if ($_GET['isStudentView'] == 'true') {
798
                    if (isset($_SESSION['studentview'])) {
799
                        if (!empty($_SESSION['studentview'])) {
800
                            // switching to studentview
801
                            $_SESSION['studentview'] = 'studentview';
802
                        }
803
                    }
804
                } elseif ($_GET['isStudentView'] == 'false') {
805
                    if (isset($_SESSION['studentview'])) {
806
                        if (!empty($_SESSION['studentview'])) {
807
                            // switching to teacherview
808
                            $_SESSION['studentview'] = 'teacherview';
809
                        }
810
                    }
811
                }
812
                //} elseif (!empty($_SESSION['studentview'])) {
813
                //all is fine, no change to that, obviously
814
            } elseif (empty($_SESSION['studentview'])) {
815
                // We are in teacherview here
816
                $_SESSION['studentview'] = 'teacherview';
817
            }
818
        }
819
    }
820
821
    /**
822
     * Returns true if user exists in the platform when asking the password.
823
     *
824
     * @param string $username (email or username)
825
     *
826
     * @return array|bool
827
     */
828
    public static function get_user_accounts_by_username($username)
829
    {
830
        if (strpos($username, '@')) {
831
            $username = api_strtolower($username);
832
            $email = true;
833
        } else {
834
            $username = api_strtolower($username);
835
            $email = false;
836
        }
837
838
        if ($email) {
839
            $condition = "LOWER(email) = '".Database::escape_string($username)."' ";
840
        } else {
841
            $condition = "LOWER(username) = '".Database::escape_string($username)."'";
842
        }
843
844
        $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
845
        $query = "SELECT
846
                    user_id AS uid,
847
		            lastname AS lastName,
848
		            firstname AS firstName,
849
		            username AS loginName,
850
		            password,
851
		            email,
852
                    status AS status,
853
                    official_code,
854
                    phone,
855
                    picture_uri,
856
                    creator_id,
857
                    auth_source
858
				 FROM $tbl_user
859
				 WHERE ( $condition AND active = 1) ";
860
        $result = Database::query($query);
861
        $num_rows = Database::num_rows($result);
862
        if ($result && $num_rows > 0) {
863
            return Database::fetch_assoc($result);
864
        }
865
866
        return false;
867
    }
868
}
869