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 1486 2011-08-08 12:03:20Z DarkViper $
14
 * @filesource		$HeadURL: svn://isteam.dynxs.de/wb-archiv/branches/2.8.x/wb/framework/class.login.php $
15
 * @lastmodified    $Date: 2011-08-08 14:03:20 +0200 (Mon, 08 Aug 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
			$sql  = 'SELECT * FROM `'.$this->users_table.'` ';
78
			$sql .= 'WHERE `user_id`=\''.$this->get_safe_remember_key().'\'';
79
			$query_details = $database->query($sql);
80
			$fetch_details = $query_details->fetchRow();
81
			$this->username = $fetch_details['username'];
82
			$this->password = $fetch_details['password'];
83
			// Check if the user exists (authenticate them)
84
			if($this->authenticate()) {
85
				// Authentication successful
86
				header("Location: ".$this->url);
87
				exit(0);
88
			} else {
89
				$this->message = $MESSAGE['LOGIN']['AUTHENTICATION_FAILED'];
90
				$this->increase_attemps();
91
			}
92
		} elseif($this->username == '' AND $this->password == '') {
93
			$this->message = $MESSAGE['LOGIN']['BOTH_BLANK'];
94
			$this->increase_attemps();
95
		} elseif($this->username == '') {
96
			$this->message = $MESSAGE['LOGIN']['USERNAME_BLANK'];
97
			$this->increase_attemps();
98
		} elseif($this->password == '') {
99
			$this->message = $MESSAGE['LOGIN']['PASSWORD_BLANK'];
100
			$this->increase_attemps();
101
		} elseif($this->username_len < $config_array['MIN_USERNAME_LEN']) {
102
			$this->message = $MESSAGE['LOGIN']['USERNAME_TOO_SHORT'];
103
			$this->increase_attemps();
104
		} elseif($this->password_len < $config_array['MIN_PASSWORD_LEN']) {
105
			$this->message = $MESSAGE['LOGIN']['PASSWORD_TOO_SHORT'];
106
			$this->increase_attemps();
107
		} elseif($this->username_len > $config_array['MAX_USERNAME_LEN']) {
108
			$this->message = $MESSAGE['LOGIN']['USERNAME_TOO_LONG'];
109
			$this->increase_attemps();
110
		} elseif($this->password_len > $config_array['MAX_PASSWORD_LEN']) {
111
			$this->message = $MESSAGE['LOGIN']['PASSWORD_TOO_LONG'];
112
			$this->increase_attemps();
113
		} else {
114
			// Check if the user exists (authenticate them)
115
			$this->password = md5($this->password);
116
			if($this->authenticate()) {
117
				// Authentication successful
118
				//echo $this->url;exit();
119
				header("Location: ".$this->url);
120
				exit(0);
121
			} else {
122
				$this->message = $MESSAGE['LOGIN']['AUTHENTICATION_FAILED'];
123
				$this->increase_attemps();
124
			}
125
		}
126
	}
127

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

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

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

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

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

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

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

    
404
?>
(9-9/18)