Project

General

Profile

1 1189 Luisehahne
<?php
2 1235 Luisehahne
/**
3
 *
4 1269 Luisehahne
 * @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$
14 1270 Luisehahne
 * @filesource		$HeadURL$
15
 * @lastmodified    $Date$
16 1235 Luisehahne
 *
17 1277 Luisehahne
 */
18 1189 Luisehahne
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 1277 Luisehahne
// Get WB version
30
require_once(ADMIN_PATH.'/interface/version.php');
31 1189 Luisehahne
32
class login extends admin {
33
	function login($config_array) {
34
		// Get language vars
35 1323 Luisehahne
		global $MESSAGE, $database;
36 1189 Luisehahne
		$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 1323 Luisehahne
		$this->username = htmlspecialchars (strtolower($this->get_post($username_fieldname)), ENT_QUOTES);
65 1310 Luisehahne
66 1189 Luisehahne
		$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 1323 Luisehahne
			// $database = new database();
94 1189 Luisehahne
			$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 1323 Luisehahne
		global $database;
146 1189 Luisehahne
		// Get user information
147 1323 Luisehahne
		// $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 1189 Luisehahne
		$results = $database->query($query);
152
		$results_array = $results->fetchRow();
153
		$num_rows = $results->numRows();
154
		if($num_rows) {
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 1322 Luisehahne
194 1189 Luisehahne
			// 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 1192 Luisehahne
			foreach (explode(",", $this->get_session('GROUPS_ID')) as $cur_group_id)
202
            {
203 1189 Luisehahne
				$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
		}
236
		// Return if the user exists or not
237
		return $num_rows;
238
	}
239
240
	// Increase the count for login attemps
241
	function increase_attemps() {
242
		if(!isset($_SESSION['ATTEMPS'])) {
243
			$_SESSION['ATTEMPS'] = 0;
244
		} else {
245
			$_SESSION['ATTEMPS'] = $this->get_session('ATTEMPS')+1;
246
		}
247
		$this->display_login();
248
	}
249
250
	// Function to set a "remembering" cookie for the user
251
	function remember($user_id) {
252 1323 Luisehahne
		global $database;
253 1189 Luisehahne
		$remember_key = '';
254
		// Generate user id to append to the remember key
255
		$length = 11-strlen($user_id);
256
		if($length > 0) {
257
			for($i = 1; $i <= $length; $i++) {
258
				$remember_key .= '0';
259
			}
260
		}
261
		// Generate remember key
262
		$remember_key .= $user_id.'_';
263
		$salt = "abchefghjkmnpqrstuvwxyz0123456789";
264
		srand((double)microtime()*1000000);
265
		$i = 0;
266
		while ($i <= 10) {
267
			$num = rand() % 33;
268
			$tmp = substr($salt, $num, 1);
269
			$remember_key = $remember_key . $tmp;
270
			$i++;
271
		}
272
		$remember_key = $remember_key;
273
		// Update the remember key in the db
274 1323 Luisehahne
		// $database = new database();
275 1189 Luisehahne
		$database->query("UPDATE ".$this->USERS_TABLE." SET remember_key = '$remember_key' WHERE user_id = '$user_id' LIMIT 1");
276
		if($database->is_error()) {
277
			return false;
278
		} else {
279
			// Workout options for the cookie
280
			$cookie_name = 'REMEMBER_KEY';
281
			$cookie_value = $remember_key;
282
			$cookie_expire = time()+60*60*24*30;
283
			// Set the cookie
284
			if(setcookie($cookie_name, $cookie_value, $cookie_expire, '/')) {
285
				return true;
286
			} else {
287
				return false;
288
			}
289
		}
290
	}
291
292
	// Function to check if a user has been remembered
293
	function is_remembered() {
294 1323 Luisehahne
		global $database;
295 1189 Luisehahne
		if(isset($_COOKIE['REMEMBER_KEY']) AND $_COOKIE['REMEMBER_KEY'] != '') {
296
			// Check if the remember key is correct
297 1323 Luisehahne
			// $database = new database();
298 1189 Luisehahne
			$sql = "SELECT `user_id` FROM `" . $this->USERS_TABLE . "` WHERE `remember_key` = '";
299
			$sql .= $this->get_safe_remember_key() . "' LIMIT 1";
300
			$check_query = $database->query($sql);
301
302
			if($check_query->numRows() > 0) {
303
				$check_fetch = $check_query->fetchRow();
304
				$user_id = $check_fetch['user_id'];
305
				// Check the remember key prefix
306
				$remember_key_prefix = '';
307
				$length = 11-strlen($user_id);
308
				if($length > 0) {
309
					for($i = 1; $i <= $length; $i++) {
310
						$remember_key_prefix .= '0';
311
					}
312
				}
313
				$remember_key_prefix .= $user_id.'_';
314
				$length = strlen($remember_key_prefix);
315
				if(substr($_COOKIE['REMEMBER_KEY'], 0, $length) == $remember_key_prefix) {
316
					return true;
317
				} else {
318
					return false;
319
				}
320
			} else {
321
				return false;
322
			}
323
		} else {
324
			return false;
325
		}
326
	}
327 1310 Luisehahne
328 1189 Luisehahne
	// Display the login screen
329
	function display_login() {
330
		// Get language vars
331
		global $MESSAGE;
332
		global $MENU;
333
		global $TEXT;
334
		// If attemps more than allowed, warn the user
335
		if($this->get_session('ATTEMPS') > $this->max_attemps) {
336
			$this->warn();
337
		}
338
		// Show the login form
339
		if($this->frontend != true) {
340
			require_once(WB_PATH.'/include/phplib/template.inc');
341
			$template = new Template($this->template_dir);
342
			$template->set_file('page', $this->template_file);
343
			$template->set_block('page', 'mainBlock', 'main');
344
			if($this->remember_me_option != true) {
345 1235 Luisehahne
				$template->set_var('DISPLAY_REMEMBER_ME', 'display: none;');
346 1189 Luisehahne
			} else {
347
				$template->set_var('DISPLAY_REMEMBER_ME', '');
348
			}
349
			$template->set_var(array(
350
											'ACTION_URL' => $this->login_url,
351
											'ATTEMPS' => $this->get_session('ATTEMPS'),
352
											'USERNAME' => $this->username,
353
											'USERNAME_FIELDNAME' => $this->username_fieldname,
354
											'PASSWORD_FIELDNAME' => $this->password_fieldname,
355
											'MESSAGE' => $this->message,
356
											'INTERFACE_DIR_URL' =>  ADMIN_URL.'/interface',
357
											'MAX_USERNAME_LEN' => $this->max_username_len,
358
											'MAX_PASSWORD_LEN' => $this->max_password_len,
359
											'WB_URL' => WB_URL,
360
											'THEME_URL' => THEME_URL,
361 1277 Luisehahne
                                            'VERSION' => VERSION,
362
                                            'REVISION' => REVISION,
363 1189 Luisehahne
											'LANGUAGE' => strtolower(LANGUAGE),
364
											'FORGOTTEN_DETAILS_APP' => $this->forgotten_details_app,
365
											'TEXT_FORGOTTEN_DETAILS' => $TEXT['FORGOTTEN_DETAILS'],
366
											'TEXT_USERNAME' => $TEXT['USERNAME'],
367
											'TEXT_PASSWORD' => $TEXT['PASSWORD'],
368
											'TEXT_REMEMBER_ME' => $TEXT['REMEMBER_ME'],
369
											'TEXT_LOGIN' => $TEXT['LOGIN'],
370
											'TEXT_HOME' => $TEXT['HOME'],
371
											'PAGES_DIRECTORY' => PAGES_DIRECTORY,
372
											'SECTION_LOGIN' => $MENU['LOGIN']
373
											)
374
									);
375
			if(defined('DEFAULT_CHARSET')) {
376
				$charset=DEFAULT_CHARSET;
377
			} else {
378
				$charset='utf-8';
379
			}
380
381
			$template->set_var('CHARSET', $charset);
382
383
384
			$template->parse('main', 'mainBlock', false);
385
			$template->pparse('output', 'page');
386
		}
387
	}
388
389
	// sanities the REMEMBER_KEY cookie to avoid SQL injection
390
	function get_safe_remember_key() {
391
		if (!((strlen($_COOKIE['REMEMBER_KEY']) == 23) && (substr($_COOKIE['REMEMBER_KEY'], 11, 1) == '_'))) return '';
392
		// create a clean cookie (XXXXXXXXXXX_YYYYYYYYYYY) where X:= numeric, Y:= hash
393
		$clean_cookie = sprintf('%011d', (int) substr($_COOKIE['REMEMBER_KEY'], 0, 11)) . substr($_COOKIE['REMEMBER_KEY'], 11);
394
		return ($clean_cookie == $_COOKIE['REMEMBER_KEY']) ? $this->add_slashes($clean_cookie) : '';
395
	}
396
397
	// Warn user that they have had to many login attemps
398
	function warn() {
399
		header('Location: '.$this->warning_url);
400
		exit(0);
401
	}
402
403
}
404
405 239 stefan
?>