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-2010, 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 4.3.4 and higher
13
 * @version         $Id: class.login.php 1322 2010-04-14 08:03:35Z Luisehahne $
14
 * @filesource		$HeadURL: svn://isteam.dynxs.de/wb-archiv/branches/2.8.x/wb/framework/class.login.php $
15
 * @lastmodified    $Date: 2010-04-14 10:03:35 +0200 (Wed, 14 Apr 2010) $
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;
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

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

    
191
			// Get group information
192
			$_SESSION['SYSTEM_PERMISSIONS'] = array();
193
			$_SESSION['MODULE_PERMISSIONS'] = array();
194
			$_SESSION['TEMPLATE_PERMISSIONS'] = array();
195
			$_SESSION['GROUP_NAME'] = array();
196

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

    
227
			// Update the users table with current ip and timestamp
228
			$get_ts = time();
229
			$get_ip = $_SERVER['REMOTE_ADDR'];
230
			$query = "UPDATE ".$this->USERS_TABLE." SET login_when = '$get_ts', login_ip = '$get_ip' WHERE user_id = '$user_id'";
231
			$database->query($query);
232
		}
233
		// Return if the user exists or not
234
		return $num_rows;
235
	}
236
	
237
	// Increase the count for login attemps
238
	function increase_attemps() {
239
		if(!isset($_SESSION['ATTEMPS'])) {
240
			$_SESSION['ATTEMPS'] = 0;
241
		} else {
242
			$_SESSION['ATTEMPS'] = $this->get_session('ATTEMPS')+1;
243
		}
244
		$this->display_login();
245
	}
246
	
247
	// Function to set a "remembering" cookie for the user
248
	function remember($user_id) {
249
		$remember_key = '';
250
		// Generate user id to append to the remember key
251
		$length = 11-strlen($user_id);
252
		if($length > 0) {
253
			for($i = 1; $i <= $length; $i++) {
254
				$remember_key .= '0';
255
			}
256
		}
257
		// Generate remember key
258
		$remember_key .= $user_id.'_';
259
		$salt = "abchefghjkmnpqrstuvwxyz0123456789";
260
		srand((double)microtime()*1000000);
261
		$i = 0;
262
		while ($i <= 10) {
263
			$num = rand() % 33;
264
			$tmp = substr($salt, $num, 1);
265
			$remember_key = $remember_key . $tmp;
266
			$i++;
267
		}
268
		$remember_key = $remember_key;
269
		// Update the remember key in the db
270
		$database = new database();
271
		$database->query("UPDATE ".$this->USERS_TABLE." SET remember_key = '$remember_key' WHERE user_id = '$user_id' LIMIT 1");
272
		if($database->is_error()) {
273
			return false;
274
		} else {
275
			// Workout options for the cookie
276
			$cookie_name = 'REMEMBER_KEY';
277
			$cookie_value = $remember_key;
278
			$cookie_expire = time()+60*60*24*30;
279
			// Set the cookie
280
			if(setcookie($cookie_name, $cookie_value, $cookie_expire, '/')) {
281
				return true;
282
			} else {
283
				return false;
284
			}
285
		}
286
	}
287
	
288
	// Function to check if a user has been remembered
289
	function is_remembered() {
290
		if(isset($_COOKIE['REMEMBER_KEY']) AND $_COOKIE['REMEMBER_KEY'] != '') {
291
			// Check if the remember key is correct
292
			$database = new database();
293
			$sql = "SELECT `user_id` FROM `" . $this->USERS_TABLE . "` WHERE `remember_key` = '";
294
			$sql .= $this->get_safe_remember_key() . "' LIMIT 1";
295
			$check_query = $database->query($sql);
296

    
297
			if($check_query->numRows() > 0) {
298
				$check_fetch = $check_query->fetchRow();
299
				$user_id = $check_fetch['user_id'];
300
				// Check the remember key prefix
301
				$remember_key_prefix = '';
302
				$length = 11-strlen($user_id);
303
				if($length > 0) {
304
					for($i = 1; $i <= $length; $i++) {
305
						$remember_key_prefix .= '0';
306
					}
307
				}
308
				$remember_key_prefix .= $user_id.'_';
309
				$length = strlen($remember_key_prefix);
310
				if(substr($_COOKIE['REMEMBER_KEY'], 0, $length) == $remember_key_prefix) {
311
					return true;
312
				} else {
313
					return false;
314
				}
315
			} else {
316
				return false;
317
			}
318
		} else {
319
			return false;
320
		}
321
	}
322

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

    
384
	// sanities the REMEMBER_KEY cookie to avoid SQL injection
385
	function get_safe_remember_key() {
386
		if (!((strlen($_COOKIE['REMEMBER_KEY']) == 23) && (substr($_COOKIE['REMEMBER_KEY'], 11, 1) == '_'))) return '';
387
		// create a clean cookie (XXXXXXXXXXX_YYYYYYYYYYY) where X:= numeric, Y:= hash
388
		$clean_cookie = sprintf('%011d', (int) substr($_COOKIE['REMEMBER_KEY'], 0, 11)) . substr($_COOKIE['REMEMBER_KEY'], 11);
389
		return ($clean_cookie == $_COOKIE['REMEMBER_KEY']) ? $this->add_slashes($clean_cookie) : '';
390
	}
391
	
392
	// Warn user that they have had to many login attemps
393
	function warn() {
394
		header('Location: '.$this->warning_url);
395
		exit(0);
396
	}
397
	
398
}
399

    
400
?>
(6-6/15)