Test Setup Failed
Push — master ( 4e700f...c7183e )
by Julito
63:12
created

online.inc.php ➔ courseLogout()   C

Complexity

Conditions 9
Paths 11

Size

Total Lines 48
Code Lines 32

Duplication

Lines 14
Ratio 29.17 %

Importance

Changes 0
Metric Value
cc 9
eloc 32
nc 11
nop 1
dl 14
loc 48
rs 5.5102
c 0
b 0
f 0
1
<?php
2
/* For licensing terms, see /license.txt */
3
4
use ChamiloSession as Session;
5
6
/**
7
*	Code library for showing Who is online
8
*
9
*	@author Istvan Mandak, principal author
10
*	@author Denes Nagy, principal author
11
*	@author Bart Mollet
12
*	@author Roan Embrechts, cleaning and bugfixing
13
*	@package chamilo.whoisonline
14
*/
15
16
/**
17
 * Insert a login reference for the current user into the track_e_online stats table.
18
 * This table keeps trace of the last login. Nothing else matters (we don't keep traces of anything older)
19
 * @param int user id
20
 * @return void
21
 */
22
23
function LoginCheck($uid)
24
{
25
    $_course = api_get_course_info();
26
    $uid = (int) $uid;
27
    $online_table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ONLINE);
28
    if (!empty($uid)) {
29
        $user_ip = '';
30
        if (!empty($_SERVER['REMOTE_ADDR'])) {
31
            $user_ip = Database::escape_string(api_get_real_ip());
32
        }
33
34
        $login_date = api_get_utc_datetime();
35
        $access_url_id = 1;
36
        if (api_get_multiple_access_url() && api_get_current_access_url_id() != -1) {
37
            $access_url_id = api_get_current_access_url_id();
38
        }
39
        $session_id = api_get_session_id();
40
        // if the $_course array exists this means we are in a course and we have to store this in the who's online table also
41
        // to have the x users in this course feature working
42
        if (is_array($_course) && count($_course) > 0 && !empty($_course['id'])) {
43
            $query = "REPLACE INTO ".$online_table." (login_id,login_user_id,login_date,user_ip, c_id, session_id, access_url_id)
44
                      VALUES ($uid,$uid,'$login_date','$user_ip', '".$_course['real_id']."' , '$session_id' , '$access_url_id' )";
45
        } else {
46
            $query = "REPLACE INTO ".$online_table." (login_id,login_user_id,login_date,user_ip, c_id, session_id, access_url_id)
47
                      VALUES ($uid,$uid,'$login_date','$user_ip', 0, '$session_id', '$access_url_id')";
48
        }
49
        Database::query($query);
50
    }
51
}
52
53
/**
54
 * @param int $userId
55
 */
56
function preventMultipleLogin($userId)
57
{
58
    $table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ONLINE);
59
    $userId = intval($userId);
60
    if (api_get_setting('prevent_multiple_simultaneous_login') === 'true') {
61
        if (!empty($userId) && !api_is_anonymous()) {
62
            $isFirstLogin = Session::read('first_user_login');
63
            if (empty($isFirstLogin)) {
64
                $sql = "SELECT login_id FROM $table
65
                        WHERE login_user_id = $userId 
66
                        LIMIT 1";
67
68
                $result = Database::query($sql);
69
                $loginData = array();
70
                if (Database::num_rows($result)) {
71
                    $loginData = Database::fetch_array($result);
72
                }
73
74
                $userIsReallyOnline = user_is_online($userId);
75
76
                // Trying double login.
77 View Code Duplication
                if (!empty($loginData) && $userIsReallyOnline == true) {
78
                    session_regenerate_id();
79
                    Session::destroy();
80
                    header('Location: '.api_get_path(WEB_PATH).'index.php?loginFailed=1&error=multiple_connection_not_allowed');
81
                    exit;
82
                } else {
83
                    // First time
84
                    Session::write('first_user_login', 1);
85
                }
86
            }
87
        }
88
    }
89
}
90
91
/**
92
 * This function handles the logout and is called whenever there is a $_GET['logout']
93
 * @param int $user_id
94
 * @param bool $logout_redirect
95
 * @return void  Directly redirects the user or leaves him where he is, but doesn't return anything
96
 * @author Fernando P. García <[email protected]>
97
 */
98
function online_logout($user_id = null, $logout_redirect = false)
99
{
100
    global $extAuthSource;
101
102
    // Database table definition
103
    $tbl_track_login = Database::get_main_table(TABLE_STATISTIC_TRACK_E_LOGIN);
104
105 View Code Duplication
    if (empty($user_id)) {
106
        $user_id = isset($_GET['uid']) ? intval($_GET['uid']) : 0;
107
    }
108
109
    //Changing global chat status to offline
110
    if (api_is_global_chat_enabled()) {
111
        $chat = new Chat();
112
        $chat->setUserStatus(0);
113
    }
114
115
    // selecting the last login of the user
116
    $sql = "SELECT login_id, login_date
117
    		FROM $tbl_track_login
118
    		WHERE login_user_id = $user_id
119
    		ORDER BY login_date DESC
120
    		LIMIT 0,1";
121
    $q_last_connection = Database::query($sql);
122
    if (Database::num_rows($q_last_connection) > 0) {
123
        $i_id_last_connection = Database::result($q_last_connection, 0, "login_id");
124
    }
125
126
    if (!isset($_SESSION['login_as'])) {
127
        $current_date = api_get_utc_datetime();
128
        $sql = "UPDATE $tbl_track_login SET logout_date='".$current_date."'
129
        		WHERE login_id='$i_id_last_connection'";
130
        Database::query($sql);
131
    }
132
133
    LoginDelete($user_id); //from inc/lib/online.inc.php - removes the "online" status
134
135
    //the following code enables the use of an external logout function.
136
    //example: define a $extAuthSource['ldap']['logout']="file.php" in configuration.php
137
    // then a function called ldap_logout() inside that file
138
    // (using *authent_name*_logout as the function name) and the following code
139
    // will find and execute it
140
    $uinfo = api_get_user_info($user_id);
141
    if (($uinfo['auth_source'] != PLATFORM_AUTH_SOURCE) && is_array($extAuthSource)) {
142
        if (is_array($extAuthSource[$uinfo['auth_source']])) {
143
            $subarray = $extAuthSource[$uinfo['auth_source']];
144
            if (!empty($subarray['logout']) && file_exists($subarray['logout'])) {
145
                require_once($subarray['logout']);
146
                $logout_function = $uinfo['auth_source'].'_logout';
147
                if (function_exists($logout_function)) {
148
                    $logout_function($uinfo);
149
                }
150
            }
151
        }
152
    }
153
154
    CourseChatUtils::exitChat($user_id);
155
    session_regenerate_id();
156
    Session::destroy();
157
    if ($logout_redirect) {
158
        header("Location: ".api_get_path(WEB_PATH)."index.php");
159
        exit;
160
    }
161
}
162
163
/**
164
 * Remove all login records from the track_e_online stats table, for the given user ID.
165
 * @param int User ID
166
 * @param integer $user_id
167
 * @return void
168
 */
169 View Code Duplication
function LoginDelete($user_id)
170
{
171
    $online_table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ONLINE);
172
    $user_id = intval($user_id);
173
    $query = "DELETE FROM ".$online_table." WHERE login_user_id = $user_id";
174
    Database::query($query);
175
}
176
177
/**
178
 * @param int $user_id
179
 * @return bool
180
 */
181 View Code Duplication
function user_is_online($user_id)
182
{
183
    $track_online_table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ONLINE);
184
    $table_user = Database::get_main_table(TABLE_MAIN_USER);
185
186
    $access_url_id = api_get_current_access_url_id();
187
    $time_limit = api_get_setting('time_limit_whosonline');
188
189
    $online_time = time() - $time_limit * 60;
190
    $limit_date = api_get_utc_datetime($online_time);
191
    $user_id = intval($user_id);
192
193
    $query = " SELECT login_user_id, login_date
194
               FROM $track_online_table track
195
               INNER JOIN $table_user u 
196
               ON (u.id=track.login_user_id)
197
               WHERE
198
                    track.access_url_id =  $access_url_id AND
199
                    login_date >= '".$limit_date."'  AND
200
                    u.id =  $user_id
201
               LIMIT 1 ";
202
203
    $result = Database::query($query);
204
    if (Database::num_rows($result)) {
205
        return true;
206
    }
207
208
    return false;
209
210
}
211
212
/**
213
 * Gives a list of people online now (and in the last $valid minutes)
214
 *
215
 * @param $from
216
 * @param $number_of_items
217
 * @param null $column
218
 * @param null $direction
219
 * @param null $time_limit
220
 * @param bool $friends
221
 * @return  array|bool For each line, a list of user IDs and login dates, or FALSE on error or empty results
222
 */
223
function who_is_online($from, $number_of_items, $column = null, $direction = null, $time_limit = null, $friends = false)
224
{
225
    // Time limit in seconds?
226
    if (empty($time_limit)) {
227
        $time_limit = api_get_setting('time_limit_whosonline');
228
    } else {
229
        $time_limit = intval($time_limit);
230
    }
231
232
    $from = intval($from);
233
    $number_of_items = intval($number_of_items);
234
235
    if (empty($column)) {
236
        $column = 'picture_uri';
237
        if ($friends) {
238
            $column = 'login_date';
239
        }
240
    }
241
242
    if (empty($direction)) {
243
        $direction = 'DESC';
244
    } else {
245
        if (!in_array(strtolower($direction), array('asc', 'desc'))) {
246
            $direction = 'DESC';
247
        }
248
    }
249
250
    $online_time = time() - $time_limit * 60;
251
    $current_date = api_get_utc_datetime($online_time);
252
    $track_online_table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ONLINE);
253
    $friend_user_table = Database::get_main_table(TABLE_MAIN_USER_REL_USER);
254
    $table_user = Database::get_main_table(TABLE_MAIN_USER);
255
256
    if ($friends) {
257
        // 	who friends from social network is online
258
        $query = "SELECT DISTINCT login_user_id, login_date
259
                  FROM $track_online_table INNER JOIN $friend_user_table
260
                  ON (friend_user_id = login_user_id)
261
                  WHERE
262
                    login_date >= '".$current_date."' AND
263
                    friend_user_id <> '".api_get_user_id()."' AND
264
                    relation_type='".USER_RELATION_TYPE_FRIEND."' AND
265
                    user_id = '".api_get_user_id()."'
266
                  ORDER BY $column $direction
267
                  LIMIT $from, $number_of_items";
268
    } else {
269
        $query = "SELECT DISTINCT login_user_id, login_date
270
                    FROM ".$track_online_table." e
271
                    INNER JOIN ".$table_user." u ON (u.id = e.login_user_id)
272
                  WHERE u.status != ".ANONYMOUS." AND login_date >= '".$current_date."'
273
                  ORDER BY $column $direction
274
                  LIMIT $from, $number_of_items";
275
    }
276
277
    if (api_get_multiple_access_url()) {
278
        $access_url_id = api_get_current_access_url_id();
279
        if ($access_url_id != -1) {
280
            if ($friends) {
281
                // 	friends from social network is online
282
                $query = "SELECT distinct login_user_id, login_date
283
                            FROM $track_online_table track INNER JOIN $friend_user_table
284
                            ON (friend_user_id = login_user_id)
285
                            WHERE   track.access_url_id =  $access_url_id AND
286
                                    login_date >= '".$current_date."' AND
287
                                    friend_user_id <> '".api_get_user_id()."' AND
288
                                    relation_type='".USER_RELATION_TYPE_FRIEND."'
289
                            ORDER BY $column $direction
290
                            LIMIT $from, $number_of_items";
291
            } else {
292
                // all users online
293
                $query = "SELECT login_user_id, login_date
294
                          FROM ".$track_online_table." track
295
                          INNER JOIN ".$table_user." u
296
                          ON (u.id=track.login_user_id)
297
                          WHERE u.status != ".ANONYMOUS." AND track.access_url_id =  $access_url_id AND
298
                                login_date >= '".$current_date."'
299
                          ORDER BY $column $direction
300
                          LIMIT $from, $number_of_items";
301
            }
302
        }
303
    }
304
305
	//This query will show all registered users. Only for dev purposes.
306
	/*$query = "SELECT DISTINCT u.id as login_user_id, login_date
307
	        FROM $track_online_table e, $table_user u
308
            GROUP by u.id
309
            ORDER BY $column $direction
310
            LIMIT $from, $number_of_items";*/
311
312
    $result = Database::query($query);
313
    if ($result) {
314
        $users_online = array();
315
        while (list($login_user_id, $login_date) = Database::fetch_row($result)) {
0 ignored issues
show
Unused Code introduced by
The assignment to $login_date is unused. Consider omitting it like so list($first,,$third).

This checks looks for assignemnts to variables using the list(...) function, where not all assigned variables are subsequently used.

Consider the following code example.

<?php

function returnThreeValues() {
    return array('a', 'b', 'c');
}

list($a, $b, $c) = returnThreeValues();

print $a . " - " . $c;

Only the variables $a and $c are used. There was no need to assign $b.

Instead, the list call could have been.

list($a,, $c) = returnThreeValues();
Loading history...
316
            $users_online[] = $login_user_id;
317
        }
318
319
        return $users_online;
320
    } else {
321
322
        return false;
323
    }
324
}
325
326
/**
327
 * @param string $time_limit
328
 */
329
function who_is_online_count($time_limit = null, $friends = false)
330
{
331
    if (empty($time_limit)) {
332
        $time_limit = api_get_setting('time_limit_whosonline');
333
    } else {
334
        $time_limit = intval($time_limit);
335
    }
336
	$track_online_table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ONLINE);
337
	$friend_user_table = Database::get_main_table(TABLE_MAIN_USER_REL_USER);
338
	$table_user = Database::get_main_table(TABLE_MAIN_USER);
339
	$online_time = time() - $time_limit * 60;
340
	$current_date = api_get_utc_datetime($online_time);
341
342
	if ($friends) {
343
		// 	who friends from social network is online
344
		$query = "SELECT DISTINCT count(login_user_id) as count
345
				  FROM $track_online_table INNER JOIN $friend_user_table
346
                  ON (friend_user_id = login_user_id)
347
				  WHERE
348
				        login_date >= '$current_date' AND
349
				        friend_user_id <> '".api_get_user_id()."' AND
350
				        relation_type='".USER_RELATION_TYPE_FRIEND."' AND
351
				        user_id = '".api_get_user_id()."' ";
352
	} else {
353
		// All users online
354
		$query = "SELECT count(login_id) as count
355
                  FROM $track_online_table track INNER JOIN $table_user u
356
                  ON (u.id=track.login_user_id)
357
                  WHERE u.status != ".ANONYMOUS." AND login_date >= '$current_date'  ";
358
	}
359
360
	if (api_get_multiple_access_url()) {
361
		$access_url_id = api_get_current_access_url_id();
362
		if ($access_url_id != -1) {
363
			if ($friends) {
364
				// 	friends from social network is online
365
				$query = "SELECT DISTINCT count(login_user_id) as count
366
							FROM $track_online_table track
367
							INNER JOIN $friend_user_table ON (friend_user_id = login_user_id)
368
							WHERE
369
							    track.access_url_id = $access_url_id AND
370
							    login_date >= '".$current_date."' AND
371
							    friend_user_id <> '".api_get_user_id()."' AND
372
							    relation_type='".USER_RELATION_TYPE_FRIEND."'  ";
373
			} else {
374
				// all users online
375
				$query = "SELECT count(login_id) as count FROM $track_online_table  track
376
                          INNER JOIN $table_user u ON (u.id=track.login_user_id)
377
						  WHERE
378
						    u.status != ".ANONYMOUS." AND
379
						    track.access_url_id =  $access_url_id AND
380
						    login_date >= '$current_date' ";
381
			}
382
		}
383
	}
384
385
    // Dev purposes show all users online
386
    /*$table_user = Database::get_main_table(TABLE_MAIN_USER);
387
    $query = "SELECT count(*)  as count FROM ".$table_user;*/
388
389
	$result = Database::query($query);
390
	if (Database::num_rows($result) > 0) {
391
		$row = Database::fetch_array($result);
392
		return $row['count'];
393
	} else {
394
		return false;
395
	}
396
}
397
398
399
/**
400
* Returns a list (array) of users who are online and in this course.
401
* @param    int User ID
402
* @param    int Number of minutes
403
* @param    string  Course code (could be empty, but then the function returns false)
404
* @return   array   Each line gives a user id and a login time
405
*/
406
function who_is_online_in_this_course($from, $number_of_items, $uid, $time_limit, $course_code)
407
{
408
    if (empty($course_code)) {
409
        return false;
410
    }
411
412
    if (empty($time_limit)) {
413
        $time_limit = api_get_setting('time_limit_whosonline');
414
    } else {
415
        $time_limit = intval($time_limit);
416
    }
417
418
    $online_time = time() - $time_limit * 60;
419
    $current_date = api_get_utc_datetime($online_time);
420
    $track_online_table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ONLINE);
421
    $course_code = Database::escape_string($course_code);
422
    $courseInfo = api_get_course_info($course_code);
423
	$courseId = $courseInfo['real_id'];
424
425
    $from = intval($from);
426
    $number_of_items = intval($number_of_items);
427
428
	$query = "SELECT login_user_id, login_date FROM $track_online_table
429
              WHERE login_user_id <> 2 AND c_id = $courseId AND login_date >= '$current_date'
430
              LIMIT $from, $number_of_items ";
431
432
	$result = Database::query($query);
433
	if ($result) {
434
		$users_online = array();
435
436
		while (list($login_user_id, $login_date) = Database::fetch_row($result)) {
0 ignored issues
show
Unused Code introduced by
The assignment to $login_date is unused. Consider omitting it like so list($first,,$third).

This checks looks for assignemnts to variables using the list(...) function, where not all assigned variables are subsequently used.

Consider the following code example.

<?php

function returnThreeValues() {
    return array('a', 'b', 'c');
}

list($a, $b, $c) = returnThreeValues();

print $a . " - " . $c;

Only the variables $a and $c are used. There was no need to assign $b.

Instead, the list call could have been.

list($a,, $c) = returnThreeValues();
Loading history...
437
            $users_online[] = $login_user_id;
438
		}
439
		return $users_online;
440
	} else {
441
		return false;
442
	}
443
}
444
445
/**
446
 * @param integer $uid
447
 * @param string $time_limit
448
 */
449
function who_is_online_in_this_course_count($uid, $time_limit, $coursecode = null)
450
{
451
	if (empty($coursecode)) {
452
		return false;
453
	}
454
	$track_online_table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ONLINE);
455
	$time_limit = Database::escape_string($time_limit);
456
457
    $online_time = time() - $time_limit * 60;
458
    $current_date = api_get_utc_datetime($online_time);
459
	$courseId = api_get_course_int_id($coursecode);
460
461
	if (empty($courseId)) {
462
		return false;
463
	}
464
465
	$query = "SELECT count(login_user_id) as count
466
              FROM $track_online_table
467
              WHERE login_user_id <> 2 AND c_id = $courseId AND login_date >= '$current_date' ";
468
	$result = Database::query($query);
469
	if (Database::num_rows($result) > 0) {
470
		$row = Database::fetch_array($result);
471
		return $row['count'];
472
	} else {
473
		return false;
474
	}
475
}
476
477
/**
478
 * Register the logout of the course (usually when logging out of the platform)
479
 * from the track_e_course_access table
480
 * @param   array $logoutInfo Information stored by local.inc.php before new context ['uid'=> x, 'cid'=>y, 'sid'=>z]
481
 * @return  void
482
 */
483
function courseLogout($logoutInfo)
484
{
485
    if (empty($logoutInfo['uid']) || empty($logoutInfo['cid'])) {
486
        return;
487
    }
488
    $sessionLifetime = api_get_configuration_value('session_lifetime');
489
    /*
490
     * When $_configuration['session_lifetime'] is larger than ~100 hours (in order to let users take exercises with no problems)
491
     * the function Tracking::get_time_spent_on_the_course() returns larger values (200h) due the condition:
492
     * login_course_date > now() - INTERVAL $session_lifetime SECOND
493
     */
494
    if (empty($sessionLifetime) || $sessionLifetime > 86400) {
495
        $sessionLifetime    = 3600; // 1 hour
496
    }
497
    if (!empty($logoutInfo) && !empty($logoutInfo['cid'])) {
498
        $tableCourseAccess = Database::get_main_table(TABLE_STATISTIC_TRACK_E_COURSE_ACCESS);
499
        $userId = intval($logoutInfo['uid']);
500
        $courseId = intval($logoutInfo['cid']);
501
        $sessionId = 0;
502
        if (!empty($logoutInfo['sid'])) {
503
            $sessionId = intval($logoutInfo['sid']);
504
        }
505
        $currentDate = api_get_utc_datetime();
506
        $sql = "SELECT course_access_id
507
            FROM $tableCourseAccess
508
            WHERE user_id = $userId AND
509
                c_id = $courseId  AND
510
                session_id  = $sessionId AND
511
                login_course_date > '$currentDate' - INTERVAL $sessionLifetime SECOND
512
            ORDER BY login_course_date DESC LIMIT 1";
513
        $result = Database::query($sql);
514
515 View Code Duplication
        if (Database::num_rows($result) > 0) {
516
            $courseAccessId = Database::result($result, 0, 0);
517
            $sql = "UPDATE $tableCourseAccess
518
                SET logout_course_date = '$currentDate', counter = counter+1
519
                WHERE course_access_id = $courseAccessId";
520
            Database::query($sql);
521
        } else {
522
            $ip = api_get_real_ip();
523
            $sql = "INSERT INTO $tableCourseAccess 
524
                      (c_id, user_ip, user_id, login_course_date, logout_course_date, counter, session_id)
525
                    VALUES 
526
                      ($courseId, '$ip', $userId, '$currentDate', '$currentDate', 1, $sessionId)";
527
            Database::query($sql);
528
        }
529
    }
530
}
531