Project

General

Profile

Bug #5418 » online.inc.php

Yoselyn Castillo, 12/09/2012 23:49

 
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
	global $_course, $_configuration;
24
	$uid = (int) $uid;
25
	$online_table = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ONLINE);
26
	if (!empty($uid)) {
27
        $login_ip = '';
28
        if(!empty($_SERVER['REMOTE_ADDR'])) {
29
		  $login_ip = Database::escape_string($_SERVER['REMOTE_ADDR']);
30
        }
31

    
32
		$login_date = api_get_utc_datetime();
33
		$access_url_id = 1;
34
		if (api_get_multiple_access_url() && api_get_current_access_url_id()!=-1) {
35
			$access_url_id = api_get_current_access_url_id();
36
		}
37
		$session_id = api_get_session_id();
38
		// 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
39
		// to have the x users in this course feature working
40
		if (is_array($_course) && count($_course)>0 && !empty($_course['id'])) {
41
            $query = "REPLACE INTO ".$online_table ." (login_id,login_user_id,login_date,login_ip, course, session_id, access_url_id) VALUES ($uid,$uid,'$login_date','$login_ip', '".$_course['id']."' , '$session_id' , '$access_url_id' )";
42
		} else {
43
            $query = "REPLACE INTO ".$online_table ." (login_id,login_user_id,login_date,login_ip, session_id, access_url_id) VALUES ($uid,$uid,'$login_date','$login_ip', '$session_id', '$access_url_id')";
44
		}
45
		@Database::query($query);
46
	}
47
}
48

    
49
/**
50
 * This function handles the logout and is called whenever there is a $_GET['logout']
51
 * @return void  Directly redirects the user or leaves him where he is, but doesn't return anything
52
 * @author Fernando P. García <fernando@develcuy.com>
53
 */
54
function online_logout($user_id = null, $logout_redirect = false) {
55
    global $_configuration, $extAuthSource;
56
  
57
    // Database table definition
58
    $tbl_track_login = Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_LOGIN);
59

    
60
    if (empty($user_id)) {
61
        $user_id = intval($_GET['uid']);    
62
    }
63
    
64
    //Changing global chat status to offline
65
    if (api_is_global_chat_enabled()) {
66
        $chat = new Chat();
67
        $chat->set_user_status(0);
68
    }
69
    
70
    // selecting the last login of the user    
71
    $sql_last_connection="SELECT login_id, login_date FROM $tbl_track_login WHERE login_user_id='$user_id' ORDER BY login_date DESC LIMIT 0,1";
72
    $q_last_connection=Database::query($sql_last_connection);
73
    if (Database::num_rows($q_last_connection)>0) {
74
        $i_id_last_connection=Database::result($q_last_connection,0,"login_id");
75
    }
76

    
77
    if (!isset($_SESSION['login_as'])) {
78
        $current_date = api_get_utc_datetime();
79
        $s_sql_update_logout_date="UPDATE $tbl_track_login SET logout_date='".$current_date."' WHERE login_id='$i_id_last_connection'";
80
        Database::query($s_sql_update_logout_date);
81
    }
82
    LoginDelete($user_id); //from inc/lib/online.inc.php - removes the "online" status
83

    
84
    //the following code enables the use of an external logout function.
85
    //example: define a $extAuthSource['ldap']['logout']="file.php" in configuration.php
86
    // then a function called ldap_logout() inside that file
87
    // (using *authent_name*_logout as the function name) and the following code
88
    // will find and execute it
89
    $uinfo = api_get_user_info($user_id);
90
    if (($uinfo['auth_source'] != PLATFORM_AUTH_SOURCE) && is_array($extAuthSource)) {
91
        if (is_array($extAuthSource[$uinfo['auth_source']])) {
92
            $subarray = $extAuthSource[$uinfo['auth_source']];
93
            if (!empty($subarray['logout']) && file_exists($subarray['logout'])) {
94
                require_once($subarray['logout']);
95
                $logout_function = $uinfo['auth_source'].'_logout';
96
                if (function_exists($logout_function)) {
97
                    $logout_function($uinfo);
98
                }
99
            }
100
        }
101
    }
102
    
103
    require_once api_get_path(SYS_PATH) . 'main/chat/chat_functions.lib.php';
104
    exit_of_chat($user_id);
105
    
106
    Session::destroy();        
107
    if ($logout_redirect) {
108
        header("Location: index.php");
109
        return;
110
    }
111
}
112

    
113
/**
114
 * Remove all login records from the track_e_online stats table, for the given user ID.
115
 * @param int User ID
116
 * @return void
117
 */
118
function LoginDelete($user_id) {
119
	$online_table = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ONLINE);
120
    $user_id = intval($user_id);
121
	$query = "DELETE FROM ".$online_table ." WHERE login_user_id = '".$user_id."'";
122
	@Database::query($query);
123
}
124

    
125
function user_is_online($user_id) {
126
	$track_online_table = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ONLINE);	
127
	$table_user			= Database::get_main_table(TABLE_MAIN_USER);
128
	
129
	$current_date		= api_get_utc_datetime();	
130
	$access_url_id		= api_get_current_access_url_id();	
131
	$time_limit			= api_get_setting('time_limit_whosonline');
132
	//$time_limit = 1; changing this value there is no time limit 
133
	
134
	$query = " SELECT login_user_id,login_date FROM ".$track_online_table ." track INNER JOIN ".$table_user ." u ON (u.user_id=track.login_user_id)
135
               WHERE track.access_url_id =  $access_url_id AND 
136
                    DATE_ADD(login_date,INTERVAL $time_limit MINUTE) >= '".$current_date."'  AND 
137
                    u.user_id =  $user_id 
138
               LIMIT 1 ";
139
	
140
	$result = Database::query($query);
141
	if (Database::num_rows($result)) {
142
		return true;
143
	}
144
	return false;
145
	
146
}
147
/**
148
 * Gives a list of people online now (and in the last $valid minutes) 
149
 * @return  array       For each line, a list of user IDs and login dates, or FALSE on error or empty results
150
 */
151
function who_is_online($from, $number_of_items, $column = null, $direction = null, $time_limit = null, $friends = false) {
152
    
153
    // Time limit in seconds?
154
    if (empty($time_limit)) {
155
        $time_limit = api_get_setting('time_limit_whosonline');
156
    } else {
157
        $time_limit = intval($time_limit);
158
    }
159
    
160
    $from            = intval($from);
161
    $number_of_items = intval($number_of_items);
162
    
163
    if (empty($column)) {
164
        $column = 'picture_uri';
165
        if ($friends) {
166
            $column = 'login_date';    
167
        }        
168
    }
169
    
170
    if (empty($direction)) {
171
        $direction = 'DESC';
172
    } else {
173
        if (!in_array(strtolower($direction), array('asc', 'desc'))) {
174
            $direction = 'DESC';
175
        }
176
    }
177
    
178
    $online_time 		= time() - $time_limit*60;
179
	$current_date		= api_get_utc_datetime($online_time);	
180
	$track_online_table = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ONLINE);
181
	$friend_user_table  = Database::get_main_table(TABLE_MAIN_USER_REL_USER);
182
	$table_user			= Database::get_main_table(TABLE_MAIN_USER);
183
	$query              = '';    
184
    
185
	if ($friends) {
186
		// 	who friends from social network is online
187
		$query = "SELECT DISTINCT login_user_id, login_date
188
				  FROM $track_online_table INNER JOIN $friend_user_table ON (friend_user_id = login_user_id)
189
				  WHERE     login_date >= '".$current_date."' AND 
190
                            friend_user_id <> '".api_get_user_id()."' AND 
191
                            relation_type='".USER_RELATION_TYPE_FRIEND."' AND 
192
                            user_id = '".api_get_user_id()."' 
193
                  ORDER BY $column $direction 
194
                  LIMIT $from, $number_of_items";
195
	} else {		
196
		$query = "SELECT login_user_id, login_date FROM ".$track_online_table ." e INNER JOIN ".$table_user ." u ON (u.user_id=e.login_user_id)  
197
                  WHERE u.status != ".ANONYMOUS." AND login_date >= '".$current_date."' 
198
                  ORDER BY $column $direction 
199
                  LIMIT $from, $number_of_items";
200
	}
201
	
202
	if (api_get_multiple_access_url()) {		
203
		$access_url_id = api_get_current_access_url_id();
204
		if ($access_url_id != -1) {
205
			if ($friends) {
206
				// 	friends from social network is online
207
				$query = "SELECT distinct login_user_id,login_date
208
							FROM $track_online_table track INNER JOIN $friend_user_table ON (friend_user_id = login_user_id)
209
							WHERE   track.access_url_id =  $access_url_id AND 
210
                                    login_date >= '".$current_date."' AND 
211
                                    friend_user_id <> '".api_get_user_id()."' AND 
212
                                    relation_type='".USER_RELATION_TYPE_FRIEND."'  
213
                            ORDER BY $column $direction 
214
                            LIMIT $from, $number_of_items";                        
215
			} else {
216
				// all users online
217
				$query = "SELECT login_user_id, login_date FROM ".$track_online_table ." track INNER JOIN ".$table_user ." u 
218
                          ON (u.user_id=track.login_user_id)
219
						  WHERE u.status != ".ANONYMOUS." AND track.access_url_id =  $access_url_id AND 
220
                                login_date >= '".$current_date."' 
221
                          ORDER BY $column $direction  
222
                          LIMIT $from, $number_of_items";
223
			}
224
		}
225
	}	
226
	
227
	//This query will show all registered users. Only for dev purposes.
228
	/*$query = "SELECT DISTINCT u.user_id as login_user_id, login_date FROM ".$track_online_table ."  e , $table_user u             
229
            GROUP by u.user_id  
230
            ORDER BY $column $direction  
231
            LIMIT $from, $number_of_items"; */
232
    
233
	$result = Database::query($query);
234
	if ($result) {		
235
        $valid_date_time = new DateTime();        
236
        $diff = "PT".$time_limit.'M';
237
        $valid_date_time->sub(new DateInterval($diff));        
238
		$users_online = array();
239
		while(list($login_user_id, $login_date) = Database::fetch_row($result)) {
240
            $user_login_date = new DateTime($login_date);                       
241
			if ($user_login_date > $valid_date_time->format('Y-m-d H:i:s')) {
242
				$users_online[] = $login_user_id;
243
			}            
244
		}        
245
		return $users_online;
246
	} else {
247
		return false;
248
	}
249
}
250

    
251
function who_is_online_count($time_limit = null, $friends = false) {	
252
    if (empty($time_limit)) {
253
        $time_limit = api_get_setting('time_limit_whosonline');        
254
    } else {
255
        $time_limit = intval($time_limit);
256
    }
257
	$track_online_table = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ONLINE);
258
	$friend_user_table  = Database::get_main_table(TABLE_MAIN_USER_REL_USER);	
259
	$query = '';
260
    
261
    $current_date	= api_get_utc_datetime();
262
    $current_date = api_strtotime($current_date, 'UTC');
263
    $current_date = date('Y-m-d h:i:s', $current_date);
264

    
265
	if ($friends) {
266
		// 	who friends from social network is online
267
		$query = "SELECT DISTINCT count(login_user_id) as count
268
				  FROM $track_online_table INNER JOIN $friend_user_table ON (friend_user_id = login_user_id)
269
				  WHERE login_date >= '$current_date' AND friend_user_id <> '".api_get_user_id()."' AND relation_type='".USER_RELATION_TYPE_FRIEND."' AND user_id = '".api_get_user_id()."' ";
270
	} else {
271
		// All users online
272
		$query = "SELECT count(login_id) as count  FROM $track_online_table 
273
                  WHERE login_user_id <> 2 AND login_date >= '$current_date' ";
274
	}
275
    	
276
	if (api_get_multiple_access_url()) {		
277
		$access_url_id = api_get_current_access_url_id();
278
		if ($access_url_id != -1) {
279
			if ($friends) {
280
				// 	friends from social network is online
281
				$query = "SELECT DISTINCT count(login_user_id) as count
282
							FROM $track_online_table track
283
							INNER JOIN $friend_user_table ON (friend_user_id = login_user_id)
284
							WHERE track.access_url_id =  $access_url_id AND login_date >= '".$current_date."' AND friend_user_id <> '".api_get_user_id()."' AND relation_type='".USER_RELATION_TYPE_FRIEND."'  ";
285
			} else {
286
				// all users online
287
				$query = "SELECT count(login_id) as count FROM $track_online_table  track
288
				  		WHERE login_user_id <> 2 AND track.access_url_id =  $access_url_id AND login_date >= '$current_date' ";
289
			}
290
		}
291
	}
292
    
293
    //dev purposes show all users online
294
    
295
    /*$table_user = Database::get_main_table(TABLE_MAIN_USER);
296
    $query = "SELECT count(*)  as count FROM ".$table_user ."   ";*/
297
    
298
	$result = Database::query($query);
299
	if (Database::num_rows($result) > 0) {
300
		$row = Database::fetch_array($result);
301
		return $row['count'];
302
	} else {
303
		return false;
304
	}
305
}
306

    
307

    
308
/**
309
* Returns a list (array) of users who are online and in this course.
310
* @param    int User ID
311
* @param    int Number of minutes
312
* @param    string  Course code (could be empty, but then the function returns false)
313
* @return   array   Each line gives a user id and a login time
314
*/
315
function who_is_online_in_this_course($from, $number_of_items, $uid, $time_limit, $course_code) {    
316
	if (empty($course_code)) return false;
317
    
318
    if (empty($time_limit)) {
319
        $time_limit = api_get_setting('time_limit_whosonline');
320
    } else {
321
        $time_limit = intval($time_limit);
322
    }
323
    
324
    $online_time 		= time() - $time_limit*60;
325
    $current_date		= api_get_utc_datetime($online_time);	
326
    $track_online_table = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ONLINE);
327
    $course_code         = Database::escape_string($course_code);
328
    
329
    $from            = intval($from);
330
    $number_of_items = intval($number_of_items);
331

    
332
	$query = "SELECT login_user_id, login_date FROM $track_online_table 
333
              WHERE login_user_id <> 2 AND course='$course_code' AND login_date >= '$current_date'
334
              LIMIT $from, $number_of_items ";
335
              
336
	$result = Database::query($query);
337
	if ($result) {
338
        $valid_date_time = new DateTime();
339
        $diff = "PT".$time_limit.'M';
340
        $valid_date_time->sub(new DateInterval($diff));
341
		$users_online = array();
342

    
343
		while(list($login_user_id, $login_date) = Database::fetch_row($result)) {
344
            $user_login_date = new DateTime($login_date);            
345
			if ($user_login_date > $valid_date_time->format('Y-m-d H:i:s')) {
346
				$users_online[] = $login_user_id;
347
			}            
348
		}
349
		return $users_online;
350
	} else {
351
		return false;
352
	}
353
}
354

    
355
function who_is_online_in_this_course_count($uid, $time_limit, $coursecode=null) {
356
	if(empty($coursecode)) return false;
357
	$track_online_table = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ONLINE);
358
	$coursecode = Database::escape_string($coursecode);
359
	$time_limit = Database::escape_string($time_limit);
360

    
361
    $online_time 		= time() - $time_limit*60;
362
	$current_date		= api_get_utc_datetime($online_time);	
363
    
364
	$query = "SELECT count(login_user_id) as count FROM ".$track_online_table ." 
365
              WHERE login_user_id <> 2 AND course='".$coursecode."' AND login_date >= '$current_date' ";	
366
	$result = Database::query($query);
367
	if (Database::num_rows($result) > 0) {
368
		$row = Database::fetch_array($result);
369
		return $row['count'];
370
	} else {
371
		return false;
372
	}
373
}
374

    
375
/**
376
 * Gets the full user name for a given user ID
377
 * @param   int User ID
378
 * @return  string  The full username, elements separated by an HTML space
379
 * @deprecated user api_get_user_info($user_id)
380
 */
381
function GetFullUserName($uid) {
382
	$uid = (int) $uid;
383
	$uid = Database::escape_string($uid);
384
	$user_table = Database::get_main_table(TABLE_MAIN_USER);
385
	$query = "SELECT firstname, lastname FROM ".$user_table." WHERE user_id='$uid'";
386
	$result = @Database::query($query);
387
	if (count($result)>0) {
388
		$str = '';
389
		while(list($firstname,$lastname)= Database::fetch_array($result)) {
390
			$str = str_replace(' ', '&nbsp;', api_get_person_name($firstname, $lastname));
391
			return $str;
392
		}
393
	}
394
}
395

    
396
/**
397
 * Gets a list of chat calls made by others to the current user (info kept in main.user table)
398
 * @param   none - taken from global space
399
 * @return  string  An HTML-formatted message
400
 */
401
function chatcall() {
402
	global $_user, $_cid;
403

    
404
	if (!$_user['user_id']) {
405
		return (false);
406
	}
407
	$track_user_table = Database::get_main_table(TABLE_MAIN_USER);
408
	$sql="select chatcall_user_id, chatcall_date from $track_user_table where ( user_id = '".$_user['user_id']."' )";
409
	$result=Database::query($sql);
410
	$row=Database::fetch_array($result);
411

    
412
	$login_date=$row['chatcall_date'];
413
	$hour = substr($login_date,11,2);
414
	$minute = substr($login_date,14,2);
415
	$secund = substr($login_date,17,2);
416
	$month = substr($login_date,5,2);
417
	$day = substr($login_date,8,2);
418
	$year = substr($login_date,0,4);
419
	$calltime = mktime($hour,$minute,$secund,$month,$day,$year);
420

    
421
	$time = api_get_utc_datetime($time);
422
	$minute_passed=5;  //within this limit, the chat call request is valid
423
	$limittime = mktime(date("H"),date("i")-$minute_passed,date("s"),date("m"),date("d"),date("Y"));
424

    
425
	if (($row['chatcall_user_id']) and ($calltime>$limittime)) {
426
		$webpath=api_get_path(WEB_CODE_PATH);
427
		$message=get_lang('YouWereCalled').' : '.GetFullUserName($row['chatcall_user_id'],'').'<br>'.get_lang('DoYouAccept')
428
							."<p>"
429
				."<a href=\"".$webpath."chat/chat.php?cidReq=".$_cid."&origin=whoisonlinejoin\">"
430
				. get_lang("Yes")
431
				."</a>"
432
				."&nbsp;&nbsp;|&nbsp;&nbsp;"
433
				."<a href=\"".api_get_path(WEB_PATH)."webchatdeny.php\">"
434
				. get_lang("No")
435
				."</a>"
436
				."</p>";
437

    
438
		return($message);
439
	} else {
440
		return false;
441
	}
442
}
(1-1/2)