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 1499 2011-08-12 11:21:25Z DarkViper $
14
 * @filesource		$HeadURL: svn://isteam.dynxs.de/wb-archiv/branches/2.8.x/wb/framework/class.login.php $
15
 * @lastmodified    $Date: 2011-08-12 13:21:25 +0200 (Fri, 12 Aug 2011) $
16
 *
17
 */
18
/* -------------------------------------------------------- */
19
// Must include code to stop this file being accessed directly
20
if(!defined('WB_PATH')) {
21
	require_once(dirname(__FILE__).'/globalExceptionHandler.php');
22
	throw new IllegalFileException();
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
	public function __construct($config_array) {
34
		// Get language vars
35
		global $MESSAGE, $database;
36
		parent::__construct();
37
		// Get configuration values
38
		while(list($key, $value) = each($config_array)) {
39
			$this->{(strtolower($key))} = $value;
40
		}
41
		if(!isset($this->redirect_url)) { $this->redirect_url = ''; }
42
		// Get the supplied username and password
43
		if ($this->get_post('username_fieldname') != ''){
44
			$username_fieldname = $this->get_post('username_fieldname');
45
			$password_fieldname = $this->get_post('password_fieldname');
46
		} else {
47
			$username_fieldname = 'username';
48
			$password_fieldname = 'password';
49
		}
50
		$this->username = htmlspecialchars (strtolower($this->get_post($username_fieldname)), ENT_QUOTES);
51

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

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

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

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

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

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

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