Project

General

Profile

1 1367 Luisehahne
<?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 1374 Luisehahne
 * @requirements    PHP 5.2.2 and higher
13 1367 Luisehahne
 * @version         $Id$
14
 * @filesource		$HeadURL$
15
 * @lastmodified    $Date$
16
 *
17
 */
18
19 1420 Luisehahne
// Must include code to stop this file being access directly
20
if(defined('WB_PATH') == false) { die("Cannot access this file directly"); }
21 1367 Luisehahne
22
define('LOGIN_CLASS_LOADED', true);
23
24
// Load the other required class files if they are not already loaded
25
require_once(WB_PATH."/framework/class.admin.php");
26
// Get WB version
27
require_once(ADMIN_PATH.'/interface/version.php');
28
29
class login extends admin {
30 1378 Luisehahne
	public function __construct($config_array) {
31 1367 Luisehahne
		// Get language vars
32
		global $MESSAGE, $database;
33 1378 Luisehahne
		parent::__construct();
34 1367 Luisehahne
		// Get configuration values
35
		$this->USERS_TABLE = $config_array['USERS_TABLE'];
36
		$this->GROUPS_TABLE = $config_array['GROUPS_TABLE'];
37
		$this->username_fieldname = $config_array['USERNAME_FIELDNAME'];
38
		$this->password_fieldname = $config_array['PASSWORD_FIELDNAME'];
39
		$this->remember_me_option = $config_array['REMEMBER_ME_OPTION'];
40
		$this->max_attemps = $config_array['MAX_ATTEMPS'];
41
		$this->warning_url = $config_array['WARNING_URL'];
42
		$this->login_url = $config_array['LOGIN_URL'];
43
		$this->template_dir = $config_array['TEMPLATE_DIR'];
44
		$this->template_file = $config_array['TEMPLATE_FILE'];
45
		$this->frontend = $config_array['FRONTEND'];
46
		$this->forgotten_details_app = $config_array['FORGOTTEN_DETAILS_APP'];
47
		$this->max_username_len = $config_array['MAX_USERNAME_LEN'];
48
		$this->max_password_len = $config_array['MAX_PASSWORD_LEN'];
49
		if (array_key_exists('REDIRECT_URL',$config_array))
50
			$this->redirect_url = $config_array['REDIRECT_URL'];
51
		else
52
			$this->redirect_url = '';
53
		// Get the supplied username and password
54
		if ($this->get_post('username_fieldname') != ''){
55
			$username_fieldname = $this->get_post('username_fieldname');
56
			$password_fieldname = $this->get_post('password_fieldname');
57
		} else {
58
			$username_fieldname = 'username';
59
			$password_fieldname = 'password';
60
		}
61
		$this->username = htmlspecialchars (strtolower($this->get_post($username_fieldname)), ENT_QUOTES);
62
63
		$this->password = $this->get_post($password_fieldname);
64
		// Figure out if the "remember me" option has been checked
65
		if($this->get_post('remember') == 'true') {
66
			$this->remember = $this->get_post('remember');
67
		} else {
68
			$this->remember = false;
69
		}
70
		// Get the length of the supplied username and password
71
		if($this->get_post($username_fieldname) != '') {
72
			$this->username_len = strlen($this->username);
73
			$this->password_len = strlen($this->password);
74
		}
75
		// If the url is blank, set it to the default url
76
		$this->url = $this->get_post('url');
77
		if ($this->redirect_url!='') {
78
			$this->url = $this->redirect_url;
79
		}
80
		if(strlen($this->url) < 2) {
81
			$this->url = $config_array['DEFAULT_URL'];
82
		}
83
		if($this->is_authenticated() == true) {
84
			// User already logged-in, so redirect to default url
85
			header('Location: '.$this->url);
86
			exit();
87
		} elseif($this->is_remembered() == true) {
88
			// User has been "remembered"
89
			// Get the users password
90
			// $database = new database();
91
			$query_details = $database->query("SELECT * FROM ".$this->USERS_TABLE." WHERE user_id = '".$this->get_safe_remember_key()."' LIMIT 1");
92
			$fetch_details = $query_details->fetchRow();
93
			$this->username = $fetch_details['username'];
94
			$this->password = $fetch_details['password'];
95
			// Check if the user exists (authenticate them)
96
			if($this->authenticate()) {
97
				// Authentication successful
98
				header("Location: ".$this->url);
99
				exit(0);
100
			} else {
101
				$this->message = $MESSAGE['LOGIN']['AUTHENTICATION_FAILED'];
102
				$this->increase_attemps();
103
			}
104
		} elseif($this->username == '' AND $this->password == '') {
105
			$this->message = $MESSAGE['LOGIN']['BOTH_BLANK'];
106
			$this->increase_attemps();
107
		} elseif($this->username == '') {
108
			$this->message = $MESSAGE['LOGIN']['USERNAME_BLANK'];
109
			$this->increase_attemps();
110
		} elseif($this->password == '') {
111
			$this->message = $MESSAGE['LOGIN']['PASSWORD_BLANK'];
112
			$this->increase_attemps();
113
		} elseif($this->username_len < $config_array['MIN_USERNAME_LEN']) {
114
			$this->message = $MESSAGE['LOGIN']['USERNAME_TOO_SHORT'];
115
			$this->increase_attemps();
116
		} elseif($this->password_len < $config_array['MIN_PASSWORD_LEN']) {
117
			$this->message = $MESSAGE['LOGIN']['PASSWORD_TOO_SHORT'];
118
			$this->increase_attemps();
119
		} elseif($this->username_len > $config_array['MAX_USERNAME_LEN']) {
120
			$this->message = $MESSAGE['LOGIN']['USERNAME_TOO_LONG'];
121
			$this->increase_attemps();
122
		} elseif($this->password_len > $config_array['MAX_PASSWORD_LEN']) {
123
			$this->message = $MESSAGE['LOGIN']['PASSWORD_TOO_LONG'];
124
			$this->increase_attemps();
125
		} else {
126
			// Check if the user exists (authenticate them)
127
			$this->password = md5($this->password);
128
			if($this->authenticate()) {
129
				// Authentication successful
130
				//echo $this->url;exit();
131
				header("Location: ".$this->url);
132
				exit(0);
133
			} else {
134
				$this->message = $MESSAGE['LOGIN']['AUTHENTICATION_FAILED'];
135
				$this->increase_attemps();
136
			}
137
		}
138
	}
139
140
	// Authenticate the user (check if they exist in the database)
141
	function authenticate() {
142
		global $database;
143
		// Get user information
144
		// $database = new database();
145
		// $query = 'SELECT * FROM `'.$this->USERS_TABLE.'` WHERE MD5(`username`) = "'.md5($this->username).'" AND `password` = "'.$this->password.'" AND `active` = 1';
146
 		$loginname = ( preg_match('/[\;\=\&\|\<\> ]/',$this->username) ? '' : $this->username );
147
		$query = 'SELECT * FROM `'.$this->USERS_TABLE.'` WHERE `username` = "'.$loginname.'" 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 == 1) {
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
		}else {
233
		  $num_rows = 0;
234
		}
235
		// Return if the user exists or not
236
		return $num_rows;
237
	}
238
239
	// Increase the count for login attemps
240
	function increase_attemps() {
241
		if(!isset($_SESSION['ATTEMPS'])) {
242
			$_SESSION['ATTEMPS'] = 0;
243
		} else {
244
			$_SESSION['ATTEMPS'] = $this->get_session('ATTEMPS')+1;
245
		}
246
		$this->display_login();
247
	}
248
249
	// Function to set a "remembering" cookie for the user
250
	function remember($user_id) {
251
		global $database;
252
		$remember_key = '';
253
		// Generate user id to append to the remember key
254
		$length = 11-strlen($user_id);
255
		if($length > 0) {
256
			for($i = 1; $i <= $length; $i++) {
257
				$remember_key .= '0';
258
			}
259
		}
260
		// Generate remember key
261
		$remember_key .= $user_id.'_';
262
		$salt = "abchefghjkmnpqrstuvwxyz0123456789";
263
		srand((double)microtime()*1000000);
264
		$i = 0;
265
		while ($i <= 10) {
266
			$num = rand() % 33;
267
			$tmp = substr($salt, $num, 1);
268
			$remember_key = $remember_key . $tmp;
269
			$i++;
270
		}
271
		$remember_key = $remember_key;
272
		// Update the remember key in the db
273
		// $database = new database();
274
		$database->query("UPDATE ".$this->USERS_TABLE." SET remember_key = '$remember_key' WHERE user_id = '$user_id' LIMIT 1");
275
		if($database->is_error()) {
276
			return false;
277
		} else {
278
			// Workout options for the cookie
279
			$cookie_name = 'REMEMBER_KEY';
280
			$cookie_value = $remember_key;
281
			$cookie_expire = time()+60*60*24*30;
282
			// Set the cookie
283
			if(setcookie($cookie_name, $cookie_value, $cookie_expire, '/')) {
284
				return true;
285
			} else {
286
				return false;
287
			}
288
		}
289
	}
290
291
	// Function to check if a user has been remembered
292
	function is_remembered()
293
	{
294
		global $database;
295
		// add if get_safe_remember_key not empty
296
		if(isset($_COOKIE['REMEMBER_KEY']) && ($_COOKIE['REMEMBER_KEY'] != '') && ($this->get_safe_remember_key() <> '' ) )
297
		{
298
			// Check if the remember key is correct
299
			// $database = new database();
300
			$sql = "SELECT `user_id` FROM `" . $this->USERS_TABLE . "` WHERE `remember_key` = '";
301
			$sql .= $this->get_safe_remember_key() . "' LIMIT 1";
302
			$check_query = $database->query($sql);
303
304
			if($check_query->numRows() > 0)
305
			{
306
				$check_fetch = $check_query->fetchRow();
307
				$user_id = $check_fetch['user_id'];
308
				// Check the remember key prefix
309
				$remember_key_prefix = '';
310
				$length = 11-strlen($user_id);
311
				if($length > 0)
312
				{
313
					for($i = 1; $i <= $length; $i++)
314
					{
315
						$remember_key_prefix .= '0';
316
					}
317
				}
318
				$remember_key_prefix .= $user_id.'_';
319
				$length = strlen($remember_key_prefix);
320
				if(substr($_COOKIE['REMEMBER_KEY'], 0, $length) == $remember_key_prefix)
321
				{
322
					return true;
323
				} else {
324
					return false;
325
				}
326
			} else {
327
				return false;
328
			}
329
		} else {
330
			return false;
331
		}
332
	}
333
334
	// Display the login screen
335
	function display_login() {
336
		// Get language vars
337
		global $MESSAGE;
338
		global $MENU;
339
		global $TEXT;
340
		// If attemps more than allowed, warn the user
341
		if($this->get_session('ATTEMPS') > $this->max_attemps) {
342
			$this->warn();
343
		}
344
		// Show the login form
345
		if($this->frontend != true) {
346
			require_once(WB_PATH.'/include/phplib/template.inc');
347
			$template = new Template($this->template_dir);
348
			$template->set_file('page', $this->template_file);
349
			$template->set_block('page', 'mainBlock', 'main');
350
			if($this->remember_me_option != true) {
351
				$template->set_var('DISPLAY_REMEMBER_ME', 'display: none;');
352
			} else {
353
				$template->set_var('DISPLAY_REMEMBER_ME', '');
354
			}
355
			$template->set_var(array(
356
											'ACTION_URL' => $this->login_url,
357
											'ATTEMPS' => $this->get_session('ATTEMPS'),
358
											'USERNAME' => $this->username,
359
											'USERNAME_FIELDNAME' => $this->username_fieldname,
360
											'PASSWORD_FIELDNAME' => $this->password_fieldname,
361
											'MESSAGE' => $this->message,
362
											'INTERFACE_DIR_URL' =>  ADMIN_URL.'/interface',
363
											'MAX_USERNAME_LEN' => $this->max_username_len,
364
											'MAX_PASSWORD_LEN' => $this->max_password_len,
365
											'WB_URL' => WB_URL,
366
											'THEME_URL' => THEME_URL,
367
                                            'VERSION' => VERSION,
368
                                            'REVISION' => REVISION,
369
											'LANGUAGE' => strtolower(LANGUAGE),
370
											'FORGOTTEN_DETAILS_APP' => $this->forgotten_details_app,
371
											'TEXT_FORGOTTEN_DETAILS' => $TEXT['FORGOTTEN_DETAILS'],
372
											'TEXT_USERNAME' => $TEXT['USERNAME'],
373
											'TEXT_PASSWORD' => $TEXT['PASSWORD'],
374
											'TEXT_REMEMBER_ME' => $TEXT['REMEMBER_ME'],
375
											'TEXT_LOGIN' => $TEXT['LOGIN'],
376
											'TEXT_HOME' => $TEXT['HOME'],
377
											'PAGES_DIRECTORY' => PAGES_DIRECTORY,
378
											'SECTION_LOGIN' => $MENU['LOGIN']
379
											)
380
									);
381
			if(defined('DEFAULT_CHARSET')) {
382
				$charset=DEFAULT_CHARSET;
383
			} else {
384
				$charset='utf-8';
385
			}
386
387
			$template->set_var('CHARSET', $charset);
388
389
390
			$template->parse('main', 'mainBlock', false);
391
			$template->pparse('output', 'page');
392
		}
393
	}
394
395
	// sanities the REMEMBER_KEY cookie to avoid SQL injection
396
	function get_safe_remember_key() {
397
		if (!((strlen($_COOKIE['REMEMBER_KEY']) == 23) && (substr($_COOKIE['REMEMBER_KEY'], 11, 1) == '_'))) return '';
398
		// create a clean cookie (XXXXXXXXXXX_YYYYYYYYYYY) where X:= numeric, Y:= hash
399
		$clean_cookie = sprintf('%011d', (int) substr($_COOKIE['REMEMBER_KEY'], 0, 11)) . substr($_COOKIE['REMEMBER_KEY'], 11);
400
		return ($clean_cookie == $_COOKIE['REMEMBER_KEY']) ? $this->add_slashes($clean_cookie) : '';
401
	}
402
403
	// Warn user that they have had to many login attemps
404
	function warn() {
405
		header('Location: '.$this->warning_url);
406
		exit(0);
407
	}
408
409
}
410
411 239 stefan
?>