Completed
Push — 1.10.x ( 8b7a4d...379b29 )
by Angel Fernando Quiroz
46:09 queued 14:30
created

main/inc/lib/online.inc.php (1 issue)

Severity

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
/* For licensing terms, see /license.txt */
3
/**
4
*	Code library for showing Who is online
5
*
6
*	@author Istvan Mandak, principal author
7
*	@author Denes Nagy, principal author
8
*	@author Bart Mollet
9
*	@author Roan Embrechts, cleaning and bugfixing
10
*	@package chamilo.whoisonline
11
*/
12
13
/**
14
 * Insert a login reference for the current user into the track_e_online stats table.
15
 * This table keeps trace of the last login. Nothing else matters (we don't keep traces of anything older)
16
 * @param int user id
17
 * @return void
18
 */
19
20
use ChamiloSession as Session;
21
22
function LoginCheck($uid)
23
{
24
    $_course = api_get_course_info();
25
    $uid = (int) $uid;
26
    $online_table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ONLINE);
27
    if (!empty($uid)) {
28
        $user_ip = '';
29
        if (!empty($_SERVER['REMOTE_ADDR'])) {
30
            $user_ip = Database::escape_string(api_get_real_ip());
31
        }
32
33
        $login_date = api_get_utc_datetime();
34
        $access_url_id = 1;
35
        if (api_get_multiple_access_url() && api_get_current_access_url_id()!=-1) {
36
            $access_url_id = api_get_current_access_url_id();
37
        }
38
        $session_id = api_get_session_id();
39
        // 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
40
        // to have the x users in this course feature working
41
        if (is_array($_course) && count($_course)>0 && !empty($_course['id'])) {
42
            $query = "REPLACE INTO ".$online_table ." (login_id,login_user_id,login_date,user_ip, c_id, session_id, access_url_id)
43
                      VALUES ($uid,$uid,'$login_date','$user_ip', '".$_course['real_id']."' , '$session_id' , '$access_url_id' )";
44
        } else {
45
            $query = "REPLACE INTO ".$online_table ." (login_id,login_user_id,login_date,user_ip, c_id, session_id, access_url_id)
46
                      VALUES ($uid,$uid,'$login_date','$user_ip', 0, '$session_id', '$access_url_id')";
47
        }
48
        Database::query($query);
49
    }
50
}
51
52
/**
53
 * @param int $userId
54
 */
55
function preventMultipleLogin($userId)
56
{
57
    $table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ONLINE);
58
    $userId = intval($userId);
59
60
    if (api_get_setting('prevent_multiple_simultaneous_login') === 'true') {
61
        if (!empty($userId) && !api_is_anonymous()) {
62
63
            $isFirstLogin = Session::read('first_user_login');
64
            if (empty($isFirstLogin)) {
65
                $sql = "SELECT login_id FROM $table
66
                        WHERE login_user_id = " . $userId . " 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
                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
 * @return void  Directly redirects the user or leaves him where he is, but doesn't return anything
94
 * @author Fernando P. García <[email protected]>
95
 */
96
function online_logout($user_id = null, $logout_redirect = false)
97
{
98
    global $extAuthSource;
99
100
    // Database table definition
101
    $tbl_track_login = Database :: get_main_table(TABLE_STATISTIC_TRACK_E_LOGIN);
102
103 View Code Duplication
    if (empty($user_id)) {
104
        $user_id = isset($_GET['uid']) ? intval($_GET['uid']) : 0;
105
    }
106
107
    //Changing global chat status to offline
108
    if (api_is_global_chat_enabled()) {
109
        $chat = new Chat();
110
        $chat->setUserStatus(0);
111
    }
112
113
    // selecting the last login of the user
114
    $sql = "SELECT login_id, login_date
115
    		FROM $tbl_track_login
116
    		WHERE login_user_id = $user_id
117
    		ORDER BY login_date DESC
118
    		LIMIT 0,1";
119
    $q_last_connection = Database::query($sql);
120
    if (Database::num_rows($q_last_connection)>0) {
121
        $i_id_last_connection = Database::result($q_last_connection,0,"login_id");
122
    }
123
124 View Code Duplication
    if (!isset($_SESSION['login_as'])) {
125
        $current_date = api_get_utc_datetime();
126
        $sql = "UPDATE $tbl_track_login SET logout_date='".$current_date."'
127
        		WHERE login_id='$i_id_last_connection'";
128
        Database::query($sql);
129
    }
130
131
    LoginDelete($user_id); //from inc/lib/online.inc.php - removes the "online" status
132
133
    //the following code enables the use of an external logout function.
134
    //example: define a $extAuthSource['ldap']['logout']="file.php" in configuration.php
135
    // then a function called ldap_logout() inside that file
136
    // (using *authent_name*_logout as the function name) and the following code
137
    // will find and execute it
138
    $uinfo = api_get_user_info($user_id);
139
    if (($uinfo['auth_source'] != PLATFORM_AUTH_SOURCE) && is_array($extAuthSource)) {
140
        if (is_array($extAuthSource[$uinfo['auth_source']])) {
141
            $subarray = $extAuthSource[$uinfo['auth_source']];
142
            if (!empty($subarray['logout']) && file_exists($subarray['logout'])) {
143
                require_once($subarray['logout']);
144
                $logout_function = $uinfo['auth_source'].'_logout';
145
                if (function_exists($logout_function)) {
146
                    $logout_function($uinfo);
147
                }
148
            }
149
        }
150
    }
151
152
    CourseChatUtils::exitChat($user_id);
153
    session_regenerate_id();
154
    Session::destroy();
155
    if ($logout_redirect) {
156
        header("Location: index.php");
157
        return;
158
    }
159
}
160
161
/**
162
 * Remove all login records from the track_e_online stats table, for the given user ID.
163
 * @param int User ID
164
 * @return void
165
 */
166 View Code Duplication
function LoginDelete($user_id)
167
{
168
	$online_table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ONLINE);
169
    $user_id = intval($user_id);
170
	$query = "DELETE FROM " . $online_table . " WHERE login_user_id = $user_id";
171
	Database::query($query);
172
}
173
174
/**
175
 * @param int $user_id
176
 * @return bool
177
 */
178
function user_is_online($user_id)
179
{
180
	$track_online_table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ONLINE);
181
	$table_user = Database::get_main_table(TABLE_MAIN_USER);
182
183
	$access_url_id = api_get_current_access_url_id();
184
	$time_limit = api_get_setting('time_limit_whosonline');
185
186
    $online_time = time() - $time_limit*60;
187
    $limit_date = api_get_utc_datetime($online_time);
188
    $user_id = intval($user_id);
189
190
	$query = " SELECT login_user_id,login_date
191
               FROM $track_online_table track
192
               INNER JOIN $table_user u ON (u.id=track.login_user_id)
193
               WHERE
194
                    track.access_url_id =  $access_url_id AND
195
                    login_date >= '".$limit_date."'  AND
196
                    u.id =  $user_id
197
               LIMIT 1 ";
198
199
	$result = Database::query($query);
200
	if (Database::num_rows($result)) {
201
202
		return true;
203
	}
204
205
	return false;
206
207
}
208
/**
209
 * Gives a list of people online now (and in the last $valid minutes)
210
 * @return  array       For each line, a list of user IDs and login dates, or FALSE on error or empty results
211
 */
212
function who_is_online($from, $number_of_items, $column = null, $direction = null, $time_limit = null, $friends = false)
213
{
214
    // Time limit in seconds?
215
    if (empty($time_limit)) {
216
        $time_limit = api_get_setting('time_limit_whosonline');
217
    } else {
218
        $time_limit = intval($time_limit);
219
    }
220
221
    $from = intval($from);
222
    $number_of_items = intval($number_of_items);
223
224
    if (empty($column)) {
225
        $column = 'picture_uri';
226
        if ($friends) {
227
            $column = 'login_date';
228
        }
229
    }
230
231
    if (empty($direction)) {
232
        $direction = 'DESC';
233
    } else {
234
        if (!in_array(strtolower($direction), array('asc', 'desc'))) {
235
            $direction = 'DESC';
236
        }
237
    }
238
239
    $online_time = time() - $time_limit * 60;
240
    $current_date = api_get_utc_datetime($online_time);
241
	$track_online_table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ONLINE);
242
	$friend_user_table = Database::get_main_table(TABLE_MAIN_USER_REL_USER);
243
	$table_user	= Database::get_main_table(TABLE_MAIN_USER);
244
245
	if ($friends) {
246
		// 	who friends from social network is online
247
		$query = "SELECT DISTINCT login_user_id, login_date
248
				  FROM $track_online_table INNER JOIN $friend_user_table
249
				  ON (friend_user_id = login_user_id)
250
				  WHERE
251
				    login_date >= '".$current_date."' AND
252
                    friend_user_id <> '".api_get_user_id()."' AND
253
                    relation_type='".USER_RELATION_TYPE_FRIEND."' AND
254
                    user_id = '".api_get_user_id()."'
255
                  ORDER BY $column $direction
256
                  LIMIT $from, $number_of_items";
257 View Code Duplication
	} else {
258
		$query = "SELECT DISTINCT login_user_id, login_date
259
                    FROM ".$track_online_table ." e
260
		            INNER JOIN ".$table_user ." u ON (u.id = e.login_user_id)
261
                  WHERE u.status != ".ANONYMOUS." AND login_date >= '".$current_date."'
262
                  ORDER BY $column $direction
263
                  LIMIT $from, $number_of_items";
264
	}
265
266
	if (api_get_multiple_access_url()) {
267
		$access_url_id = api_get_current_access_url_id();
268
		if ($access_url_id != -1) {
269
			if ($friends) {
270
				// 	friends from social network is online
271
				$query = "SELECT distinct login_user_id, login_date
272
							FROM $track_online_table track INNER JOIN $friend_user_table
273
							ON (friend_user_id = login_user_id)
274
							WHERE   track.access_url_id =  $access_url_id AND
275
                                    login_date >= '".$current_date."' AND
276
                                    friend_user_id <> '".api_get_user_id()."' AND
277
                                    relation_type='".USER_RELATION_TYPE_FRIEND."'
278
                            ORDER BY $column $direction
279
                            LIMIT $from, $number_of_items";
280 View Code Duplication
			} else {
281
				// all users online
282
				$query = "SELECT login_user_id, login_date
283
						  FROM ".$track_online_table ." track
284
                          INNER JOIN ".$table_user ." u
285
                          ON (u.id=track.login_user_id)
286
						  WHERE u.status != ".ANONYMOUS." AND track.access_url_id =  $access_url_id AND
287
                                login_date >= '".$current_date."'
288
                          ORDER BY $column $direction
289
                          LIMIT $from, $number_of_items";
290
			}
291
		}
292
	}
293
294
	//This query will show all registered users. Only for dev purposes.
295
	/*$query = "SELECT DISTINCT u.id as login_user_id, login_date FROM ".$track_online_table ."  e , $table_user u
296
            GROUP by u.id
297
            ORDER BY $column $direction
298
            LIMIT $from, $number_of_items";*/
299
300
	$result = Database::query($query);
301 View Code Duplication
	if ($result) {
302
		$users_online = array();
303
		while (list($login_user_id, $login_date) = Database::fetch_row($result)) {
304
            $users_online[] = $login_user_id;
305
		}
306
		return $users_online;
307
	} else {
308
		return false;
309
	}
310
}
311
312
function who_is_online_count($time_limit = null, $friends = false)
313
{
314
    if (empty($time_limit)) {
315
        $time_limit = api_get_setting('time_limit_whosonline');
316
    } else {
317
        $time_limit = intval($time_limit);
318
    }
319
	$track_online_table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ONLINE);
320
	$friend_user_table = Database::get_main_table(TABLE_MAIN_USER_REL_USER);
321
	$table_user = Database::get_main_table(TABLE_MAIN_USER);
322
	$online_time = time() - $time_limit * 60;
323
	$current_date = api_get_utc_datetime($online_time);
324
325 View Code Duplication
	if ($friends) {
326
		// 	who friends from social network is online
327
		$query = "SELECT DISTINCT count(login_user_id) as count
328
				  FROM $track_online_table INNER JOIN $friend_user_table
329
                  ON (friend_user_id = login_user_id)
330
				  WHERE
331
				        login_date >= '$current_date' AND
332
				        friend_user_id <> '".api_get_user_id()."' AND
333
				        relation_type='".USER_RELATION_TYPE_FRIEND."' AND
334
				        user_id = '".api_get_user_id()."' ";
335
	} else {
336
		// All users online
337
		$query = "SELECT count(login_id) as count
338
                  FROM $track_online_table track INNER JOIN $table_user u
339
                  ON (u.id=track.login_user_id)
340
                  WHERE u.status != ".ANONYMOUS." AND login_date >= '$current_date'  ";
341
	}
342
343
	if (api_get_multiple_access_url()) {
344
		$access_url_id = api_get_current_access_url_id();
345
		if ($access_url_id != -1) {
346 View Code Duplication
			if ($friends) {
347
				// 	friends from social network is online
348
				$query = "SELECT DISTINCT count(login_user_id) as count
349
							FROM $track_online_table track
350
							INNER JOIN $friend_user_table ON (friend_user_id = login_user_id)
351
							WHERE
352
							    track.access_url_id = $access_url_id AND
353
							    login_date >= '".$current_date."' AND
354
							    friend_user_id <> '".api_get_user_id()."' AND
355
							    relation_type='".USER_RELATION_TYPE_FRIEND."'  ";
356
			} else {
357
				// all users online
358
				$query = "SELECT count(login_id) as count FROM $track_online_table  track
359
                          INNER JOIN $table_user u ON (u.id=track.login_user_id)
360
						  WHERE
361
						    u.status != ".ANONYMOUS." AND
362
						    track.access_url_id =  $access_url_id AND
363
						    login_date >= '$current_date' ";
364
			}
365
		}
366
	}
367
368
    // Dev purposes show all users online
369
    /*$table_user = Database::get_main_table(TABLE_MAIN_USER);
370
    $query = "SELECT count(*)  as count FROM ".$table_user;*/
371
372
	$result = Database::query($query);
373
	if (Database::num_rows($result) > 0) {
374
		$row = Database::fetch_array($result);
375
		return $row['count'];
376
	} else {
377
		return false;
378
	}
379
}
380
381
382
/**
383
* Returns a list (array) of users who are online and in this course.
384
* @param    int User ID
385
* @param    int Number of minutes
386
* @param    string  Course code (could be empty, but then the function returns false)
387
* @return   array   Each line gives a user id and a login time
388
*/
389
function who_is_online_in_this_course($from, $number_of_items, $uid, $time_limit, $course_code)
390
{
391
	if (empty($course_code)) return false;
392
393
    if (empty($time_limit)) {
394
        $time_limit = api_get_setting('time_limit_whosonline');
395
    } else {
396
        $time_limit = intval($time_limit);
397
    }
398
399
    $online_time 		= time() - $time_limit*60;
400
    $current_date		= api_get_utc_datetime($online_time);
401
    $track_online_table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ONLINE);
402
    $course_code         = Database::escape_string($course_code);
403
	$courseInfo = api_get_course_info($course_code);
404
	$courseId = $courseInfo['real_id'];
405
406
    $from = intval($from);
407
    $number_of_items = intval($number_of_items);
408
409
	$query = "SELECT login_user_id, login_date FROM $track_online_table
410
              WHERE login_user_id <> 2 AND c_id = $courseId AND login_date >= '$current_date'
411
              LIMIT $from, $number_of_items ";
412
413
	$result = Database::query($query);
414 View Code Duplication
	if ($result) {
415
		$users_online = array();
416
417
		while(list($login_user_id, $login_date) = Database::fetch_row($result)) {
0 ignored issues
show
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...
418
            $users_online[] = $login_user_id;
419
		}
420
		return $users_online;
421
	} else {
422
		return false;
423
	}
424
}
425
426
function who_is_online_in_this_course_count($uid, $time_limit, $coursecode=null)
427
{
428
	if (empty($coursecode)) {
429
		return false;
430
	}
431
	$track_online_table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ONLINE);
432
	$coursecode = Database::escape_string($coursecode);
433
	$time_limit = Database::escape_string($time_limit);
434
435
    $online_time = time() - $time_limit * 60;
436
    $current_date = api_get_utc_datetime($online_time);
437
	$courseId = api_get_course_int_id($coursecode);
438
439
	if (empty($courseId)) {
440
		return false;
441
	}
442
443
	$query = "SELECT count(login_user_id) as count
444
              FROM $track_online_table
445
              WHERE login_user_id <> 2 AND c_id = $courseId AND login_date >= '$current_date' ";
446
	$result = Database::query($query);
447
	if (Database::num_rows($result) > 0) {
448
		$row = Database::fetch_array($result);
449
		return $row['count'];
450
	} else {
451
		return false;
452
	}
453
}
454
455
/**
456
 * Gets the full user name for a given user ID
457
 * @param   int User ID
458
 * @return  string  The full username, elements separated by an HTML space
459
 * @deprecated user api_get_user_info($user_id)
460
 */
461
function GetFullUserName($uid) {
462
	$uid = (int) $uid;
463
	$uid = intval($uid);
464
	$user_table = Database::get_main_table(TABLE_MAIN_USER);
465
	$query = "SELECT firstname, lastname FROM ".$user_table." WHERE id=$uid";
466
	$result = @Database::query($query);
467
	if (count($result)>0) {
468
		while(list($firstname,$lastname)= Database::fetch_array($result)) {
469
			$str = str_replace(' ', '&nbsp;', api_get_person_name($firstname, $lastname));
470
			return $str;
471
		}
472
	}
473
}
474
475
/**
476
 * Gets a list of chat calls made by others to the current user (info kept in main.user table)
477
 * @param   none - taken from global space
478
 * @return  string  An HTML-formatted message
479
 */
480
function chatcall() {
481
    $_cid = api_get_course_id();
482
    $_user = api_get_user_info();
483
484
	if (!$_user['user_id']) {
485
		return (false);
486
	}
487
    $userId = intval($_user['user_id']);
488
	$track_user_table = Database::get_main_table(TABLE_MAIN_USER);
489
	$sql="SELECT chatcall_user_id, chatcall_date FROM $track_user_table
490
	      WHERE ( id = $userId )";
491
	$result=Database::query($sql);
492
	$row=Database::fetch_array($result);
493
494
	$login_date=$row['chatcall_date'];
495
	$hour = substr($login_date,11,2);
496
	$minute = substr($login_date,14,2);
497
	$second = substr($login_date,17,2);
498
	$month = substr($login_date,5,2);
499
	$day = substr($login_date,8,2);
500
	$year = substr($login_date,0,4);
501
	$calltime = mktime($hour,$minute,$second,$month,$day,$year);
502
503
	$time = api_get_utc_datetime();
504
	$minute_passed=5;  //within this limit, the chat call request is valid
505
	$limittime = mktime(date("H"),date("i")-$minute_passed,date("s"),date("m"),date("d"),date("Y"));
506
507
	if (($row['chatcall_user_id']) and ($calltime>$limittime)) {
508
		$webpath=api_get_path(WEB_CODE_PATH);
509
		$message=get_lang('YouWereCalled').' : '.GetFullUserName($row['chatcall_user_id'],'').'<br>'.get_lang('DoYouAccept')
510
							."<p>"
511
				."<a href=\"".$webpath."chat/chat.php?cidReq=".$_cid."&origin=whoisonlinejoin\">"
512
				. get_lang("Yes")
513
				."</a>"
514
				."&nbsp;&nbsp;|&nbsp;&nbsp;"
515
				."<a href=\"".api_get_path(WEB_PATH)."webchatdeny.php\">"
516
				. get_lang("No")
517
				."</a>"
518
				."</p>";
519
520
		return($message);
521
	} else {
522
		return false;
523
	}
524
}
525