Project

General

Profile

1
<?php
2
/**
3
 *
4
 * @category        backend
5
 * @package         login
6
 * @author          WebsiteBaker Project
7
 * @copyright       2004-2009, Ryan Djurovich
8
 * @copyright       2009-2011, Website Baker Org. e.V.
9
 * @link			http://www.websitebaker2.org/
10
 * @license         http://www.gnu.org/licenses/gpl.html
11
 * @platform        WebsiteBaker 2.8.x
12
 * @requirements    PHP 5.2.2 and higher
13
 * @version         $Id: class.login.php 1374 2011-01-10 12:21:47Z Luisehahne $
14
 * @filesource		$HeadURL: svn://isteam.dynxs.de/wb-archiv/branches/2.8.x/wb/framework/class.login.php $
15
 * @lastmodified    $Date: 2011-01-10 13:21:47 +0100 (Mon, 10 Jan 2011) $
16
 *
17
 */
18

    
19
// Stop this file from being accessed directly
20
if(!defined('WB_URL')) {
21
	header('Location: ../index.php');
22
	exit(0);
23
}
24

    
25
define('LOGIN_CLASS_LOADED', true);
26

    
27
// Load the other required class files if they are not already loaded
28
require_once(WB_PATH."/framework/class.admin.php");
29
// Get WB version
30
require_once(ADMIN_PATH.'/interface/version.php');
31

    
32
class login extends admin {
33
	function login($config_array) {
34
		// Get language vars
35
		global $MESSAGE, $database;
36
		$this->wb();
37
		// Get configuration values
38
		$this->USERS_TABLE = $config_array['USERS_TABLE'];
39
		$this->GROUPS_TABLE = $config_array['GROUPS_TABLE'];
40
		$this->username_fieldname = $config_array['USERNAME_FIELDNAME'];
41
		$this->password_fieldname = $config_array['PASSWORD_FIELDNAME'];
42
		$this->remember_me_option = $config_array['REMEMBER_ME_OPTION'];
43
		$this->max_attemps = $config_array['MAX_ATTEMPS'];
44
		$this->warning_url = $config_array['WARNING_URL'];
45
		$this->login_url = $config_array['LOGIN_URL'];
46
		$this->template_dir = $config_array['TEMPLATE_DIR'];
47
		$this->template_file = $config_array['TEMPLATE_FILE'];
48
		$this->frontend = $config_array['FRONTEND'];
49
		$this->forgotten_details_app = $config_array['FORGOTTEN_DETAILS_APP'];
50
		$this->max_username_len = $config_array['MAX_USERNAME_LEN'];
51
		$this->max_password_len = $config_array['MAX_PASSWORD_LEN'];
52
		if (array_key_exists('REDIRECT_URL',$config_array))
53
			$this->redirect_url = $config_array['REDIRECT_URL'];
54
		else
55
			$this->redirect_url = '';
56
		// Get the supplied username and password
57
		if ($this->get_post('username_fieldname') != ''){
58
			$username_fieldname = $this->get_post('username_fieldname');
59
			$password_fieldname = $this->get_post('password_fieldname');
60
		} else {
61
			$username_fieldname = 'username';
62
			$password_fieldname = 'password';
63
		}
64
		$this->username = htmlspecialchars (strtolower($this->get_post($username_fieldname)), ENT_QUOTES);
65

    
66
		$this->password = $this->get_post($password_fieldname);
67
		// Figure out if the "remember me" option has been checked
68
		if($this->get_post('remember') == 'true') {
69
			$this->remember = $this->get_post('remember');
70
		} else {
71
			$this->remember = false;
72
		}
73
		// Get the length of the supplied username and password
74
		if($this->get_post($username_fieldname) != '') {
75
			$this->username_len = strlen($this->username);
76
			$this->password_len = strlen($this->password);
77
		}
78
		// If the url is blank, set it to the default url
79
		$this->url = $this->get_post('url');
80
		if ($this->redirect_url!='') {
81
			$this->url = $this->redirect_url;
82
		}		
83
		if(strlen($this->url) < 2) {
84
			$this->url = $config_array['DEFAULT_URL'];
85
		}
86
		if($this->is_authenticated() == true) {
87
			// User already logged-in, so redirect to default url
88
			header('Location: '.$this->url);
89
			exit();
90
		} elseif($this->is_remembered() == true) {
91
			// User has been "remembered"
92
			// Get the users password
93
			// $database = new database();
94
			$query_details = $database->query("SELECT * FROM ".$this->USERS_TABLE." WHERE user_id = '".$this->get_safe_remember_key()."' LIMIT 1");
95
			$fetch_details = $query_details->fetchRow();
96
			$this->username = $fetch_details['username'];
97
			$this->password = $fetch_details['password'];
98
			// Check if the user exists (authenticate them)
99
			if($this->authenticate()) {
100
				// Authentication successful
101
				header("Location: ".$this->url);
102
				exit(0);
103
			} else {
104
				$this->message = $MESSAGE['LOGIN']['AUTHENTICATION_FAILED'];
105
				$this->increase_attemps();
106
			}
107
		} elseif($this->username == '' AND $this->password == '') {
108
			$this->message = $MESSAGE['LOGIN']['BOTH_BLANK'];
109
			$this->increase_attemps();
110
		} elseif($this->username == '') {
111
			$this->message = $MESSAGE['LOGIN']['USERNAME_BLANK'];
112
			$this->increase_attemps();
113
		} elseif($this->password == '') {
114
			$this->message = $MESSAGE['LOGIN']['PASSWORD_BLANK'];
115
			$this->increase_attemps();
116
		} elseif($this->username_len < $config_array['MIN_USERNAME_LEN']) {
117
			$this->message = $MESSAGE['LOGIN']['USERNAME_TOO_SHORT'];
118
			$this->increase_attemps();
119
		} elseif($this->password_len < $config_array['MIN_PASSWORD_LEN']) {
120
			$this->message = $MESSAGE['LOGIN']['PASSWORD_TOO_SHORT'];
121
			$this->increase_attemps();
122
		} elseif($this->username_len > $config_array['MAX_USERNAME_LEN']) {
123
			$this->message = $MESSAGE['LOGIN']['USERNAME_TOO_LONG'];
124
			$this->increase_attemps();
125
		} elseif($this->password_len > $config_array['MAX_PASSWORD_LEN']) {
126
			$this->message = $MESSAGE['LOGIN']['PASSWORD_TOO_LONG'];
127
			$this->increase_attemps();
128
		} else {
129
			// Check if the user exists (authenticate them)
130
			$this->password = md5($this->password);
131
			if($this->authenticate()) {
132
				// Authentication successful
133
				//echo $this->url;exit();
134
				header("Location: ".$this->url);
135
				exit(0);
136
			} else {
137
				$this->message = $MESSAGE['LOGIN']['AUTHENTICATION_FAILED'];
138
				$this->increase_attemps();
139
			}
140
		}
141
	}
142

    
143
	// Authenticate the user (check if they exist in the database)
144
	function authenticate() {
145
		global $database;
146
		// Get user information
147
		// $database = new database();
148
		// $query = 'SELECT * FROM `'.$this->USERS_TABLE.'` WHERE MD5(`username`) = "'.md5($this->username).'" AND `password` = "'.$this->password.'" AND `active` = 1';
149
 		$loginname = ( preg_match('/[\;\=\&\|\<\> ]/',$this->username) ? '' : $this->username );
150
		$query = 'SELECT * FROM `'.$this->USERS_TABLE.'` WHERE `username` = "'.$loginname.'" AND `password` = "'.$this->password.'" AND `active` = 1';
151
		$results = $database->query($query);
152
		$results_array = $results->fetchRow();
153
		$num_rows = $results->numRows();
154
		if($num_rows == 1) {
155
			$user_id = $results_array['user_id'];
156
			$this->user_id = $user_id;
157
			$_SESSION['USER_ID'] = $user_id;
158
			$_SESSION['GROUP_ID'] = $results_array['group_id'];
159
			$_SESSION['GROUPS_ID'] = $results_array['groups_id'];
160
			$_SESSION['USERNAME'] = $results_array['username'];
161
			$_SESSION['DISPLAY_NAME'] = $results_array['display_name'];
162
			$_SESSION['EMAIL'] = $results_array['email'];
163
			$_SESSION['HOME_FOLDER'] = $results_array['home_folder'];
164
			// Run remember function if needed
165
			if($this->remember == true) {
166
				$this->remember($this->user_id);
167
			}
168
			// Set language
169
			if($results_array['language'] != '') {
170
				$_SESSION['LANGUAGE'] = $results_array['language'];
171
			}
172
			// Set timezone
173
			if($results_array['timezone'] != '-72000') {
174
				$_SESSION['TIMEZONE'] = $results_array['timezone'];
175
			} else {
176
				// Set a session var so apps can tell user is using default tz
177
				$_SESSION['USE_DEFAULT_TIMEZONE'] = true;
178
			}
179
			// Set date format
180
			if($results_array['date_format'] != '') {
181
				$_SESSION['DATE_FORMAT'] = $results_array['date_format'];
182
			} else {
183
				// Set a session var so apps can tell user is using default date format
184
				$_SESSION['USE_DEFAULT_DATE_FORMAT'] = true;
185
			}
186
			// Set time format
187
			if($results_array['time_format'] != '') {
188
				$_SESSION['TIME_FORMAT'] = $results_array['time_format'];
189
			} else {
190
				// Set a session var so apps can tell user is using default time format
191
				$_SESSION['USE_DEFAULT_TIME_FORMAT'] = true;
192
			}
193

    
194
			// Get group information
195
			$_SESSION['SYSTEM_PERMISSIONS'] = array();
196
			$_SESSION['MODULE_PERMISSIONS'] = array();
197
			$_SESSION['TEMPLATE_PERMISSIONS'] = array();
198
			$_SESSION['GROUP_NAME'] = array();
199

    
200
			$first_group = true;
201
			foreach (explode(",", $this->get_session('GROUPS_ID')) as $cur_group_id)
202
            {
203
				$query = "SELECT * FROM ".$this->GROUPS_TABLE." WHERE group_id = '".$cur_group_id."'";
204
				$results = $database->query($query);
205
				$results_array = $results->fetchRow();
206
				$_SESSION['GROUP_NAME'][$cur_group_id] = $results_array['name'];
207
				// Set system permissions
208
				if($results_array['system_permissions'] != '') {
209
					$_SESSION['SYSTEM_PERMISSIONS'] = array_merge($_SESSION['SYSTEM_PERMISSIONS'], explode(',', $results_array['system_permissions']));
210
				}
211
				// Set module permissions
212
				if($results_array['module_permissions'] != '') {
213
					if ($first_group) {
214
          	$_SESSION['MODULE_PERMISSIONS'] = explode(',', $results_array['module_permissions']);
215
          } else {
216
          	$_SESSION['MODULE_PERMISSIONS'] = array_intersect($_SESSION['MODULE_PERMISSIONS'], explode(',', $results_array['module_permissions']));
217
					}
218
				}
219
				// Set template permissions
220
				if($results_array['template_permissions'] != '') {
221
					if ($first_group) {
222
          	$_SESSION['TEMPLATE_PERMISSIONS'] = explode(',', $results_array['template_permissions']);
223
          } else {
224
          	$_SESSION['TEMPLATE_PERMISSIONS'] = array_intersect($_SESSION['TEMPLATE_PERMISSIONS'], explode(',', $results_array['template_permissions']));
225
					}
226
				}
227
				$first_group = false;
228
			}	
229

    
230
			// Update the users table with current ip and timestamp
231
			$get_ts = time();
232
			$get_ip = $_SERVER['REMOTE_ADDR'];
233
			$query = "UPDATE ".$this->USERS_TABLE." SET login_when = '$get_ts', login_ip = '$get_ip' WHERE user_id = '$user_id'";
234
			$database->query($query);
235
		}else {
236
		  $num_rows = 0;
237
		}
238
		// Return if the user exists or not
239
		return $num_rows;
240
	}
241

    
242
	// Increase the count for login attemps
243
	function increase_attemps() {
244
		if(!isset($_SESSION['ATTEMPS'])) {
245
			$_SESSION['ATTEMPS'] = 0;
246
		} else {
247
			$_SESSION['ATTEMPS'] = $this->get_session('ATTEMPS')+1;
248
		}
249
		$this->display_login();
250
	}
251
	
252
	// Function to set a "remembering" cookie for the user
253
	function remember($user_id) {
254
		global $database;
255
		$remember_key = '';
256
		// Generate user id to append to the remember key
257
		$length = 11-strlen($user_id);
258
		if($length > 0) {
259
			for($i = 1; $i <= $length; $i++) {
260
				$remember_key .= '0';
261
			}
262
		}
263
		// Generate remember key
264
		$remember_key .= $user_id.'_';
265
		$salt = "abchefghjkmnpqrstuvwxyz0123456789";
266
		srand((double)microtime()*1000000);
267
		$i = 0;
268
		while ($i <= 10) {
269
			$num = rand() % 33;
270
			$tmp = substr($salt, $num, 1);
271
			$remember_key = $remember_key . $tmp;
272
			$i++;
273
		}
274
		$remember_key = $remember_key;
275
		// Update the remember key in the db
276
		// $database = new database();
277
		$database->query("UPDATE ".$this->USERS_TABLE." SET remember_key = '$remember_key' WHERE user_id = '$user_id' LIMIT 1");
278
		if($database->is_error()) {
279
			return false;
280
		} else {
281
			// Workout options for the cookie
282
			$cookie_name = 'REMEMBER_KEY';
283
			$cookie_value = $remember_key;
284
			$cookie_expire = time()+60*60*24*30;
285
			// Set the cookie
286
			if(setcookie($cookie_name, $cookie_value, $cookie_expire, '/')) {
287
				return true;
288
			} else {
289
				return false;
290
			}
291
		}
292
	}
293
	
294
	// Function to check if a user has been remembered
295
	function is_remembered()
296
	{
297
		global $database;
298
		// add if get_safe_remember_key not empty
299
		if(isset($_COOKIE['REMEMBER_KEY']) && ($_COOKIE['REMEMBER_KEY'] != '') && ($this->get_safe_remember_key() <> '' ) )
300
		{
301
			// Check if the remember key is correct
302
			// $database = new database();
303
			$sql = "SELECT `user_id` FROM `" . $this->USERS_TABLE . "` WHERE `remember_key` = '";
304
			$sql .= $this->get_safe_remember_key() . "' LIMIT 1";
305
			$check_query = $database->query($sql);
306

    
307
			if($check_query->numRows() > 0)
308
			{
309
				$check_fetch = $check_query->fetchRow();
310
				$user_id = $check_fetch['user_id'];
311
				// Check the remember key prefix
312
				$remember_key_prefix = '';
313
				$length = 11-strlen($user_id);
314
				if($length > 0)
315
				{
316
					for($i = 1; $i <= $length; $i++)
317
					{
318
						$remember_key_prefix .= '0';
319
					}
320
				}
321
				$remember_key_prefix .= $user_id.'_';
322
				$length = strlen($remember_key_prefix);
323
				if(substr($_COOKIE['REMEMBER_KEY'], 0, $length) == $remember_key_prefix)
324
				{
325
					return true;
326
				} else {
327
					return false;
328
				}
329
			} else {
330
				return false;
331
			}
332
		} else {
333
			return false;
334
		}
335
	}
336

    
337
	// Display the login screen
338
	function display_login() {
339
		// Get language vars
340
		global $MESSAGE;
341
		global $MENU;
342
		global $TEXT;
343
		// If attemps more than allowed, warn the user
344
		if($this->get_session('ATTEMPS') > $this->max_attemps) {
345
			$this->warn();
346
		}
347
		// Show the login form
348
		if($this->frontend != true) {
349
			require_once(WB_PATH.'/include/phplib/template.inc');
350
			$template = new Template($this->template_dir);
351
			$template->set_file('page', $this->template_file);
352
			$template->set_block('page', 'mainBlock', 'main');
353
			if($this->remember_me_option != true) {
354
				$template->set_var('DISPLAY_REMEMBER_ME', 'display: none;');
355
			} else {
356
				$template->set_var('DISPLAY_REMEMBER_ME', '');
357
			}
358
			$template->set_var(array(
359
											'ACTION_URL' => $this->login_url,
360
											'ATTEMPS' => $this->get_session('ATTEMPS'),
361
											'USERNAME' => $this->username,
362
											'USERNAME_FIELDNAME' => $this->username_fieldname,
363
											'PASSWORD_FIELDNAME' => $this->password_fieldname,
364
											'MESSAGE' => $this->message,
365
											'INTERFACE_DIR_URL' =>  ADMIN_URL.'/interface',
366
											'MAX_USERNAME_LEN' => $this->max_username_len,
367
											'MAX_PASSWORD_LEN' => $this->max_password_len,
368
											'WB_URL' => WB_URL,
369
											'THEME_URL' => THEME_URL,
370
                                            'VERSION' => VERSION,
371
                                            'REVISION' => REVISION,
372
											'LANGUAGE' => strtolower(LANGUAGE),
373
											'FORGOTTEN_DETAILS_APP' => $this->forgotten_details_app,
374
											'TEXT_FORGOTTEN_DETAILS' => $TEXT['FORGOTTEN_DETAILS'],
375
											'TEXT_USERNAME' => $TEXT['USERNAME'],
376
											'TEXT_PASSWORD' => $TEXT['PASSWORD'],
377
											'TEXT_REMEMBER_ME' => $TEXT['REMEMBER_ME'],
378
											'TEXT_LOGIN' => $TEXT['LOGIN'],
379
											'TEXT_HOME' => $TEXT['HOME'],
380
											'PAGES_DIRECTORY' => PAGES_DIRECTORY,
381
											'SECTION_LOGIN' => $MENU['LOGIN']
382
											)
383
									);
384
			if(defined('DEFAULT_CHARSET')) {
385
				$charset=DEFAULT_CHARSET;
386
			} else {
387
				$charset='utf-8';
388
			}
389
			
390
			$template->set_var('CHARSET', $charset);	
391
									
392
									
393
			$template->parse('main', 'mainBlock', false);
394
			$template->pparse('output', 'page');
395
		}
396
	}
397

    
398
	// sanities the REMEMBER_KEY cookie to avoid SQL injection
399
	function get_safe_remember_key() {
400
		if (!((strlen($_COOKIE['REMEMBER_KEY']) == 23) && (substr($_COOKIE['REMEMBER_KEY'], 11, 1) == '_'))) return '';
401
		// create a clean cookie (XXXXXXXXXXX_YYYYYYYYYYY) where X:= numeric, Y:= hash
402
		$clean_cookie = sprintf('%011d', (int) substr($_COOKIE['REMEMBER_KEY'], 0, 11)) . substr($_COOKIE['REMEMBER_KEY'], 11);
403
		return ($clean_cookie == $_COOKIE['REMEMBER_KEY']) ? $this->add_slashes($clean_cookie) : '';
404
	}
405
	
406
	// Warn user that they have had to many login attemps
407
	function warn() {
408
		header('Location: '.$this->warning_url);
409
		exit(0);
410
	}
411
	
412
}
413

    
414
?>
(7-7/16)