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 1474 2011-07-12 08:27:18Z DarkViper $
14
 * @filesource		$HeadURL: svn://isteam.dynxs.de/wb-archiv/branches/2.8.x/wb/framework/class.login.php $
15
 * @lastmodified    $Date: 2011-07-12 10:27:18 +0200 (Tue, 12 Jul 2011) $
16
 *
17
 */
18

    
19
// Must include code to stop this file being access directly
20
if(defined('WB_PATH') == false) { die("Cannot access this file directly"); }
21

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

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

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

    
177
			// Get group information
178
			$_SESSION['SYSTEM_PERMISSIONS'] = array();
179
			$_SESSION['MODULE_PERMISSIONS'] = array();
180
			$_SESSION['TEMPLATE_PERMISSIONS'] = array();
181
			$_SESSION['GROUP_NAME'] = array();
182

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

    
213
			// Update the users table with current ip and timestamp
214
			$get_ts = time();
215
			$get_ip = $_SERVER['REMOTE_ADDR'];
216
			$query = "UPDATE ".$this->users_table." SET login_when = '$get_ts', login_ip = '$get_ip' WHERE user_id = '$user_id'";
217
			$database->query($query);
218
		}else {
219
		  $num_rows = 0;
220
		}
221
		// Return if the user exists or not
222
		return $num_rows;
223
	}
224

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

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

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

    
399
?>
(9-9/18)