Project

General

Profile

Bug #5418 » online.inc.php

Yoselyn Castillo, 18/09/2012 21:42

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

    
252
function who_is_online_count($time_limit = null, $friends = false) {	
253
    if (empty($time_limit)) {
254
        $time_limit = api_get_setting('time_limit_whosonline');        
255
    } else {
256
        $time_limit = intval($time_limit);
257
    }
258
	$track_online_table = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ONLINE);
259
	$friend_user_table  = Database::get_main_table(TABLE_MAIN_USER_REL_USER);	
260
	$query = '';
261
    
262
   /*$current_date = api_get_utc_datetime();
263
   $current_date = api_strtotime($current_date, 'UTC');
264
   $current_date = date('Y-m-d H:i:s', $current_date);*/
265
   
266
    $online_time 		= time() - $time_limit*60;
267
	$current_date		= api_get_utc_datetime($online_time);
268
    
269
	if ($friends) {
270
		// 	who friends from social network is online
271
		$query = "SELECT DISTINCT count(login_user_id) as count
272
				  FROM $track_online_table INNER JOIN $friend_user_table ON (friend_user_id = login_user_id)
273
				  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()."' ";
274
	} else {
275
		// All users online
276
		$query = "SELECT count(login_id) as count  FROM $track_online_table 
277
                  WHERE login_user_id <> 2 AND login_date >= '$current_date'  ";
278
	}
279
    	
280
	if (api_get_multiple_access_url()) {		
281
		$access_url_id = api_get_current_access_url_id();
282
		if ($access_url_id != -1) {
283
			if ($friends) {
284
				// 	friends from social network is online
285
				$query = "SELECT DISTINCT count(login_user_id) as count
286
							FROM $track_online_table track
287
							INNER JOIN $friend_user_table ON (friend_user_id = login_user_id)
288
							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."'  ";
289
			} else {
290
				// all users online
291
				$query = "SELECT count(login_id) as count FROM $track_online_table  track
292
						  WHERE login_user_id <> 2 AND track.access_url_id =  $access_url_id AND login_date >= '$current_date' ";
293
			}
294
		}
295
	}
296
    
297
    //dev purposes show all users online
298
    
299
    /*$table_user = Database::get_main_table(TABLE_MAIN_USER);
300
    $query = "SELECT count(*)  as count FROM ".$table_user ."   ";*/
301
    
302
	$result = Database::query($query);
303
	if (Database::num_rows($result) > 0) {
304
		$row = Database::fetch_array($result);
305
		return $row['count'];
306
	} else {
307
		return false;
308
	}
309
}
310

    
311

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

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

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

    
359
function who_is_online_in_this_course_count($uid, $time_limit, $coursecode=null) {
360
	if(empty($coursecode)) return false;
361
	$track_online_table = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ONLINE);
362
	$coursecode = Database::escape_string($coursecode);
363
	$time_limit = Database::escape_string($time_limit);
364

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

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

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

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

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

    
425
	$time = api_get_utc_datetime($time);
426
	$minute_passed=5;  //within this limit, the chat call request is valid
427
	$limittime = mktime(date("H"),date("i")-$minute_passed,date("s"),date("m"),date("d"),date("Y"));
428

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

    
442
		return($message);
443
	} else {
444
		return false;
445
	}
446
}
(2-2/2)