Project

General

Profile

1
<?php
2
/**
3
 *
4
 * @category        framework
5
 * @package         backend login
6
 * @author          Ryan Djurovich, WebsiteBaker Project
7
 * @copyright       2009-2011, Website Baker Org. e.V.
8
 * @link			http://www.websitebaker2.org/
9
 * @license         http://www.gnu.org/licenses/gpl.html
10
 * @platform        WebsiteBaker 2.8.x
11
 * @requirements    PHP 5.2.2 and higher
12
 * @version         $Id: class.login.php 1625 2012-02-29 00:50:57Z Luisehahne $
13
 * @filesource		$HeadURL: svn://isteam.dynxs.de/wb-archiv/branches/2.8.x/wb/framework/class.login.php $
14
 * @lastmodified    $Date: 2012-02-29 01:50:57 +0100 (Wed, 29 Feb 2012) $
15
 *
16
 */
17
/* -------------------------------------------------------- */
18
// Must include code to stop this file being accessed directly
19
if(!defined('WB_PATH')) {
20
	require_once(dirname(__FILE__).'/globalExceptionHandler.php');
21
	throw new IllegalFileException();
22
}
23
/* -------------------------------------------------------- */
24
define('LOGIN_CLASS_LOADED', true);
25

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

    
31
class login extends admin {
32
	public function __construct($config_array) {
33
		// Get language vars
34
		global $MESSAGE, $database;
35
		parent::__construct();
36
		// Get configuration values
37
		while(list($key, $value) = each($config_array)) {
38
			$this->{(strtolower($key))} = $value;
39
		}
40
		if(!isset($this->redirect_url)) { $this->redirect_url = ''; }
41
		// Get the supplied username and password
42
		if ($this->get_post('username_fieldname') != ''){
43
			$username_fieldname = $this->get_post('username_fieldname');
44
			$password_fieldname = $this->get_post('password_fieldname');
45
		} else {
46
			$username_fieldname = 'username';
47
			$password_fieldname = 'password';
48
		}
49
		$this->username = htmlspecialchars (strtolower($this->get_post($username_fieldname)), ENT_QUOTES);
50

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

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

    
182
			// Get group information
183
			$_SESSION['SYSTEM_PERMISSIONS'] = array();
184
			$_SESSION['MODULE_PERMISSIONS'] = array();
185
			$_SESSION['TEMPLATE_PERMISSIONS'] = array();
186
			$_SESSION['GROUP_NAME'] = array();
187

    
188
			$first_group = true;
189
			foreach (explode(",", $this->get_session('GROUPS_ID')) as $cur_group_id)
190
            {
191
				$sql = 'SELECT * FROM `'.$this->groups_table.'` WHERE `group_id`=\''.$cur_group_id.'\'';
192
				$results = $database->query($sql);
193
				$results_array = $results->fetchRow();
194
				$_SESSION['GROUP_NAME'][$cur_group_id] = $results_array['name'];
195
				// Set system permissions
196
				if($results_array['system_permissions'] != '') {
197
					$_SESSION['SYSTEM_PERMISSIONS'] = array_merge($_SESSION['SYSTEM_PERMISSIONS'], explode(',', $results_array['system_permissions']));
198
				}
199
				// Set module permissions
200
				if($results_array['module_permissions'] != '') {
201
					if ($first_group) {
202
          	$_SESSION['MODULE_PERMISSIONS'] = explode(',', $results_array['module_permissions']);
203
          } else {
204
          	$_SESSION['MODULE_PERMISSIONS'] = array_intersect($_SESSION['MODULE_PERMISSIONS'], explode(',', $results_array['module_permissions']));
205
					}
206
				}
207
				// Set template permissions
208
				if($results_array['template_permissions'] != '') {
209
					if ($first_group) {
210
          	$_SESSION['TEMPLATE_PERMISSIONS'] = explode(',', $results_array['template_permissions']);
211
          } else {
212
          	$_SESSION['TEMPLATE_PERMISSIONS'] = array_intersect($_SESSION['TEMPLATE_PERMISSIONS'], explode(',', $results_array['template_permissions']));
213
					}
214
				}
215
				$first_group = false;
216
			}	
217

    
218
			// Update the users table with current ip and timestamp
219
			$get_ts = time();
220
			$get_ip = $_SERVER['REMOTE_ADDR'];
221
			$sql  = 'UPDATE `'.$this->users_table.'` ';
222
			$sql .= 'SET `login_when`=\''.$get_ts.'\', `login_ip`=\''.$get_ip.'\' ';
223
			$sql .= 'WHERE `user_id`=\''.$user_id.'\'';
224
			$database->query($sql);
225
		}else {
226
		  $num_rows = 0;
227
		}
228
		// Return if the user exists or not
229
		return $num_rows;
230
	}
231

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

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

    
386
			$template->parse('main', 'mainBlock', false);
387
			$template->pparse('output', 'page');
388
		}
389
	}
390

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

    
407
?>
(12-12/23)