Project

General

Profile

1
<?php
2

    
3
// $Id: class.login.php 1192 2009-11-27 19:37:05Z Luisehahne $
4

    
5
/*
6

    
7
 Website Baker Project <http://www.websitebaker.org/>
8
 Copyright (C) 2004-2009, Ryan Djurovich
9

    
10
 Website Baker is free software; you can redistribute it and/or modify
11
 it under the terms of the GNU General Public License as published by
12
 the Free Software Foundation; either version 2 of the License, or
13
 (at your option) any later version.
14

    
15
 Website Baker is distributed in the hope that it will be useful,
16
 but WITHOUT ANY WARRANTY; without even the implied warranty of
17
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18
 GNU General Public License for more details.
19

    
20
 You should have received a copy of the GNU General Public License
21
 along with Website Baker; if not, write to the Free Software
22
 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
23

    
24
*/
25

    
26
/*
27
 * @category   backend
28
 * @package    Login class
29
 * @author(s)  Dietmar W?llbrink <Luisehahne>, Dietrich Roland Pehlke <Aldus>
30
 * @platform   WB 2.8.x
31
 * @require    PHP 5.2.11
32
 * @license    http://www.gnu.org/licenses/gpl.html
33
 * @link       http://project.websitebaker2.org/browser/branches/2.8.x/wb/pages
34
 * @changeset  2009/11/27   fixed parse error ticket #878
35

    
36

    
37

    
38
This class will be used to with the login application
39

    
40
*/
41

    
42
// Stop this file from being accessed directly
43
if(!defined('WB_URL')) {
44
	header('Location: ../index.php');
45
	exit(0);
46
}
47

    
48
define('LOGIN_CLASS_LOADED', true);
49

    
50
// Load the other required class files if they are not already loaded
51
require_once(WB_PATH."/framework/class.admin.php");
52

    
53
class login extends admin {
54
	function login($config_array) {
55
		// Get language vars
56
		global $MESSAGE;
57
		$this->wb();
58
		// Get configuration values
59
		$this->USERS_TABLE = $config_array['USERS_TABLE'];
60
		$this->GROUPS_TABLE = $config_array['GROUPS_TABLE'];
61
		$this->username_fieldname = $config_array['USERNAME_FIELDNAME'];
62
		$this->password_fieldname = $config_array['PASSWORD_FIELDNAME'];
63
		$this->remember_me_option = $config_array['REMEMBER_ME_OPTION'];
64
		$this->max_attemps = $config_array['MAX_ATTEMPS'];
65
		$this->warning_url = $config_array['WARNING_URL'];
66
		$this->login_url = $config_array['LOGIN_URL'];
67
		$this->template_dir = $config_array['TEMPLATE_DIR'];
68
		$this->template_file = $config_array['TEMPLATE_FILE'];
69
		$this->frontend = $config_array['FRONTEND'];
70
		$this->forgotten_details_app = $config_array['FORGOTTEN_DETAILS_APP'];
71
		$this->max_username_len = $config_array['MAX_USERNAME_LEN'];
72
		$this->max_password_len = $config_array['MAX_PASSWORD_LEN'];
73
		if (array_key_exists('REDIRECT_URL',$config_array))
74
			$this->redirect_url = $config_array['REDIRECT_URL'];
75
		else
76
			$this->redirect_url = '';
77
		// Get the supplied username and password
78
		if ($this->get_post('username_fieldname') != ''){
79
			$username_fieldname = $this->get_post('username_fieldname');
80
			$password_fieldname = $this->get_post('password_fieldname');
81
		} else {
82
			$username_fieldname = 'username';
83
			$password_fieldname = 'password';
84
		}
85
		$this->username = $this->add_slashes(strtolower($this->get_post($username_fieldname)));
86
		$this->password = $this->get_post($password_fieldname);
87
		// Figure out if the "remember me" option has been checked
88
		if($this->get_post('remember') == 'true') {
89
			$this->remember = $this->get_post('remember');
90
		} else {
91
			$this->remember = false;
92
		}
93
		// Get the length of the supplied username and password
94
		if($this->get_post($username_fieldname) != '') {
95
			$this->username_len = strlen($this->username);
96
			$this->password_len = strlen($this->password);
97
		}
98
		// If the url is blank, set it to the default url
99
		$this->url = $this->get_post('url');
100
		if ($this->redirect_url!='') {
101
			$this->url = $this->redirect_url;
102
		}		
103
		if(strlen($this->url) < 2) {
104
			$this->url = $config_array['DEFAULT_URL'];
105
		}
106
		if($this->is_authenticated() == true) {
107
			// User already logged-in, so redirect to default url
108
			header('Location: '.$this->url);
109
			exit();
110
		} elseif($this->is_remembered() == true) {
111
			// User has been "remembered"
112
			// Get the users password
113
			$database = new database();
114
			$query_details = $database->query("SELECT * FROM ".$this->USERS_TABLE." WHERE user_id = '".$this->get_safe_remember_key()."' LIMIT 1");
115
			$fetch_details = $query_details->fetchRow();
116
			$this->username = $fetch_details['username'];
117
			$this->password = $fetch_details['password'];
118
			// Check if the user exists (authenticate them)
119
			if($this->authenticate()) {
120
				// Authentication successful
121
				header("Location: ".$this->url);
122
				exit(0);
123
			} else {
124
				$this->message = $MESSAGE['LOGIN']['AUTHENTICATION_FAILED'];
125
				$this->increase_attemps();
126
			}
127
		} elseif($this->username == '' AND $this->password == '') {
128
			$this->message = $MESSAGE['LOGIN']['BOTH_BLANK'];
129
			$this->increase_attemps();
130
		} elseif($this->username == '') {
131
			$this->message = $MESSAGE['LOGIN']['USERNAME_BLANK'];
132
			$this->increase_attemps();
133
		} elseif($this->password == '') {
134
			$this->message = $MESSAGE['LOGIN']['PASSWORD_BLANK'];
135
			$this->increase_attemps();
136
		} elseif($this->username_len < $config_array['MIN_USERNAME_LEN']) {
137
			$this->message = $MESSAGE['LOGIN']['USERNAME_TOO_SHORT'];
138
			$this->increase_attemps();
139
		} elseif($this->password_len < $config_array['MIN_PASSWORD_LEN']) {
140
			$this->message = $MESSAGE['LOGIN']['PASSWORD_TOO_SHORT'];
141
			$this->increase_attemps();
142
		} elseif($this->username_len > $config_array['MAX_USERNAME_LEN']) {
143
			$this->message = $MESSAGE['LOGIN']['USERNAME_TOO_LONG'];
144
			$this->increase_attemps();
145
		} elseif($this->password_len > $config_array['MAX_PASSWORD_LEN']) {
146
			$this->message = $MESSAGE['LOGIN']['PASSWORD_TOO_LONG'];
147
			$this->increase_attemps();
148
		} else {
149
			// Check if the user exists (authenticate them)
150
			$this->password = md5($this->password);
151
			if($this->authenticate()) {
152
				// Authentication successful
153
				//echo $this->url;exit();
154
				header("Location: ".$this->url);
155
				exit(0);
156
			} else {
157
				$this->message = $MESSAGE['LOGIN']['AUTHENTICATION_FAILED'];
158
				$this->increase_attemps();
159
			}
160
		}
161
	}
162
	
163
	// Authenticate the user (check if they exist in the database)
164
	function authenticate() {
165
		// Get user information
166
		$database = new database();
167
		$query = "SELECT * FROM ".$this->USERS_TABLE." WHERE username = '".$this->username."' AND password = '".$this->password."' AND active = '1'";
168
		$results = $database->query($query);
169
		$results_array = $results->fetchRow();
170
		$num_rows = $results->numRows();
171
		if($num_rows) {
172
			$user_id = $results_array['user_id'];
173
			$this->user_id = $user_id;
174
			$_SESSION['USER_ID'] = $user_id;
175
			$_SESSION['GROUP_ID'] = $results_array['group_id'];
176
			$_SESSION['GROUPS_ID'] = $results_array['groups_id'];
177
			$_SESSION['USERNAME'] = $results_array['username'];
178
			$_SESSION['DISPLAY_NAME'] = $results_array['display_name'];
179
			$_SESSION['EMAIL'] = $results_array['email'];
180
			$_SESSION['HOME_FOLDER'] = $results_array['home_folder'];
181
			// Run remember function if needed
182
			if($this->remember == true) {
183
				$this->remember($this->user_id);
184
			}
185
			// Set language
186
			if($results_array['language'] != '') {
187
				$_SESSION['LANGUAGE'] = $results_array['language'];
188
			}
189
			// Set timezone
190
			if($results_array['timezone'] != '-72000') {
191
				$_SESSION['TIMEZONE'] = $results_array['timezone'];
192
			} else {
193
				// Set a session var so apps can tell user is using default tz
194
				$_SESSION['USE_DEFAULT_TIMEZONE'] = true;
195
			}
196
			// Set date format
197
			if($results_array['date_format'] != '') {
198
				$_SESSION['DATE_FORMAT'] = $results_array['date_format'];
199
			} else {
200
				// Set a session var so apps can tell user is using default date format
201
				$_SESSION['USE_DEFAULT_DATE_FORMAT'] = true;
202
			}
203
			// Set time format
204
			if($results_array['time_format'] != '') {
205
				$_SESSION['TIME_FORMAT'] = $results_array['time_format'];
206
			} else {
207
				// Set a session var so apps can tell user is using default time format
208
				$_SESSION['USE_DEFAULT_TIME_FORMAT'] = true;
209
			}
210
			// Get group information
211
//			$query = "SELECT * FROM ".$this->GROUPS_TABLE." WHERE group_id = '".$this->get_session('GROUP_ID')."'";
212
//			$results = $database->query($query);
213
//			$results_array = $results->fetchRow();
214
//			$_SESSION['GROUP_NAME'] = $results_array['name'];
215
//			// Set system permissions
216
//			if($results_array['system_permissions'] != '') {
217
//				$_SESSION['SYSTEM_PERMISSIONS'] = explode(',', $results_array['system_permissions']);
218
//			} else {
219
//				$_SESSION['SYSTEM_PERMISSIONS'] = array();
220
//			}
221
//			// Set module permissions
222
//			if($results_array['module_permissions'] != '') {
223
//				$_SESSION['MODULE_PERMISSIONS'] = explode(',', $results_array['module_permissions']);
224
//			} else {
225
//				$_SESSION['MODULE_PERMISSIONS'] = array();
226
//			}
227
//			// Set template permissions
228
//			if($results_array['template_permissions'] != '') {
229
//				$_SESSION['TEMPLATE_PERMISSIONS'] = explode(',', $results_array['template_permissions']);
230
//			} else {
231
//				$_SESSION['TEMPLATE_PERMISSIONS'] = array();
232
//			}
233

    
234
			$_SESSION['SYSTEM_PERMISSIONS'] = array();
235
			$_SESSION['MODULE_PERMISSIONS'] = array();
236
			$_SESSION['TEMPLATE_PERMISSIONS'] = array();
237
			$_SESSION['GROUP_NAME'] = array();
238

    
239
			$first_group = true;
240
			foreach (explode(",", $this->get_session('GROUPS_ID')) as $cur_group_id)
241
            {
242
				$query = "SELECT * FROM ".$this->GROUPS_TABLE." WHERE group_id = '".$cur_group_id."'";
243
				$results = $database->query($query);
244
				$results_array = $results->fetchRow();
245
				$_SESSION['GROUP_NAME'][$cur_group_id] = $results_array['name'];
246
				// Set system permissions
247
				if($results_array['system_permissions'] != '') {
248
					$_SESSION['SYSTEM_PERMISSIONS'] = array_merge($_SESSION['SYSTEM_PERMISSIONS'], explode(',', $results_array['system_permissions']));
249
				}
250
				// Set module permissions
251
				if($results_array['module_permissions'] != '') {
252
					if ($first_group) {
253
          	$_SESSION['MODULE_PERMISSIONS'] = explode(',', $results_array['module_permissions']);
254
          } else {
255
          	$_SESSION['MODULE_PERMISSIONS'] = array_intersect($_SESSION['MODULE_PERMISSIONS'], explode(',', $results_array['module_permissions']));
256
					}
257
				}
258
				// Set template permissions
259
				if($results_array['template_permissions'] != '') {
260
					if ($first_group) {
261
          	$_SESSION['TEMPLATE_PERMISSIONS'] = explode(',', $results_array['template_permissions']);
262
          } else {
263
          	$_SESSION['TEMPLATE_PERMISSIONS'] = array_intersect($_SESSION['TEMPLATE_PERMISSIONS'], explode(',', $results_array['template_permissions']));
264
					}
265
				}
266
				$first_group = false;
267
			}	
268

    
269
			// Update the users table with current ip and timestamp
270
			$get_ts = time();
271
			$get_ip = $_SERVER['REMOTE_ADDR'];
272
			$query = "UPDATE ".$this->USERS_TABLE." SET login_when = '$get_ts', login_ip = '$get_ip' WHERE user_id = '$user_id'";
273
			$database->query($query);
274
		}
275
		// Return if the user exists or not
276
		return $num_rows;
277
	}
278
	
279
	// Increase the count for login attemps
280
	function increase_attemps() {
281
		if(!isset($_SESSION['ATTEMPS'])) {
282
			$_SESSION['ATTEMPS'] = 0;
283
		} else {
284
			$_SESSION['ATTEMPS'] = $this->get_session('ATTEMPS')+1;
285
		}
286
		$this->display_login();
287
	}
288
	
289
	// Function to set a "remembering" cookie for the user
290
	function remember($user_id) {
291
		$remember_key = '';
292
		// Generate user id to append to the remember key
293
		$length = 11-strlen($user_id);
294
		if($length > 0) {
295
			for($i = 1; $i <= $length; $i++) {
296
				$remember_key .= '0';
297
			}
298
		}
299
		// Generate remember key
300
		$remember_key .= $user_id.'_';
301
		$salt = "abchefghjkmnpqrstuvwxyz0123456789";
302
		srand((double)microtime()*1000000);
303
		$i = 0;
304
		while ($i <= 10) {
305
			$num = rand() % 33;
306
			$tmp = substr($salt, $num, 1);
307
			$remember_key = $remember_key . $tmp;
308
			$i++;
309
		}
310
		$remember_key = $remember_key;
311
		// Update the remember key in the db
312
		$database = new database();
313
		$database->query("UPDATE ".$this->USERS_TABLE." SET remember_key = '$remember_key' WHERE user_id = '$user_id' LIMIT 1");
314
		if($database->is_error()) {
315
			return false;
316
		} else {
317
			// Workout options for the cookie
318
			$cookie_name = 'REMEMBER_KEY';
319
			$cookie_value = $remember_key;
320
			$cookie_expire = time()+60*60*24*30;
321
			// Set the cookie
322
			if(setcookie($cookie_name, $cookie_value, $cookie_expire, '/')) {
323
				return true;
324
			} else {
325
				return false;
326
			}
327
		}
328
	}
329
	
330
	// Function to check if a user has been remembered
331
	function is_remembered() {
332
		if(isset($_COOKIE['REMEMBER_KEY']) AND $_COOKIE['REMEMBER_KEY'] != '') {
333
			// Check if the remember key is correct
334
			$database = new database();
335
			$sql = "SELECT `user_id` FROM `" . $this->USERS_TABLE . "` WHERE `remember_key` = '";
336
			$sql .= $this->get_safe_remember_key() . "' LIMIT 1";
337
			$check_query = $database->query($sql);
338

    
339
			if($check_query->numRows() > 0) {
340
				$check_fetch = $check_query->fetchRow();
341
				$user_id = $check_fetch['user_id'];
342
				// Check the remember key prefix
343
				$remember_key_prefix = '';
344
				$length = 11-strlen($user_id);
345
				if($length > 0) {
346
					for($i = 1; $i <= $length; $i++) {
347
						$remember_key_prefix .= '0';
348
					}
349
				}
350
				$remember_key_prefix .= $user_id.'_';
351
				$length = strlen($remember_key_prefix);
352
				if(substr($_COOKIE['REMEMBER_KEY'], 0, $length) == $remember_key_prefix) {
353
					return true;
354
				} else {
355
					return false;
356
				}
357
			} else {
358
				return false;
359
			}
360
		} else {
361
			return false;
362
		}
363
	}
364
	
365
	// Display the login screen
366
	function display_login() {
367
		// Get language vars
368
		global $MESSAGE;
369
		global $MENU;
370
		global $TEXT;
371
		// If attemps more than allowed, warn the user
372
		if($this->get_session('ATTEMPS') > $this->max_attemps) {
373
			$this->warn();
374
		}
375
		// Show the login form
376
		if($this->frontend != true) {
377
			require_once(WB_PATH.'/include/phplib/template.inc');
378
			$template = new Template($this->template_dir);
379
			$template->set_file('page', $this->template_file);
380
			$template->set_block('page', 'mainBlock', 'main');
381
			if($this->remember_me_option != true) {
382
				$template->set_var('DISPLAY_REMEMBER_ME', 'none');
383
			} else {
384
				$template->set_var('DISPLAY_REMEMBER_ME', '');
385
			}
386
			$template->set_var(array(
387
											'ACTION_URL' => $this->login_url,
388
											'ATTEMPS' => $this->get_session('ATTEMPS'),
389
											'USERNAME' => $this->username,
390
											'USERNAME_FIELDNAME' => $this->username_fieldname,
391
											'PASSWORD_FIELDNAME' => $this->password_fieldname,
392
											'MESSAGE' => $this->message,
393
											'INTERFACE_DIR_URL' =>  ADMIN_URL.'/interface',
394
											'MAX_USERNAME_LEN' => $this->max_username_len,
395
											'MAX_PASSWORD_LEN' => $this->max_password_len,
396
											'WB_URL' => WB_URL,
397
											'THEME_URL' => THEME_URL,
398
											'LANGUAGE' => strtolower(LANGUAGE),
399
											'FORGOTTEN_DETAILS_APP' => $this->forgotten_details_app,
400
											'TEXT_FORGOTTEN_DETAILS' => $TEXT['FORGOTTEN_DETAILS'],
401
											'TEXT_USERNAME' => $TEXT['USERNAME'],
402
											'TEXT_PASSWORD' => $TEXT['PASSWORD'],
403
											'TEXT_REMEMBER_ME' => $TEXT['REMEMBER_ME'],
404
											'TEXT_LOGIN' => $TEXT['LOGIN'],
405
											'TEXT_HOME' => $TEXT['HOME'],
406
											'PAGES_DIRECTORY' => PAGES_DIRECTORY,
407
											'SECTION_LOGIN' => $MENU['LOGIN']
408
											)
409
									);
410
			if(defined('DEFAULT_CHARSET')) {
411
				$charset=DEFAULT_CHARSET;
412
			} else {
413
				$charset='utf-8';
414
			}
415
			
416
			$template->set_var('CHARSET', $charset);	
417
									
418
									
419
			$template->parse('main', 'mainBlock', false);
420
			$template->pparse('output', 'page');
421
		}
422
	}
423

    
424
	// sanities the REMEMBER_KEY cookie to avoid SQL injection
425
	function get_safe_remember_key() {
426
		if (!((strlen($_COOKIE['REMEMBER_KEY']) == 23) && (substr($_COOKIE['REMEMBER_KEY'], 11, 1) == '_'))) return '';
427
		// create a clean cookie (XXXXXXXXXXX_YYYYYYYYYYY) where X:= numeric, Y:= hash
428
		$clean_cookie = sprintf('%011d', (int) substr($_COOKIE['REMEMBER_KEY'], 0, 11)) . substr($_COOKIE['REMEMBER_KEY'], 11);
429
		return ($clean_cookie == $_COOKIE['REMEMBER_KEY']) ? $this->add_slashes($clean_cookie) : '';
430
	}
431
	
432
	// Warn user that they have had to many login attemps
433
	function warn() {
434
		header('Location: '.$this->warning_url);
435
		exit(0);
436
	}
437
	
438
}
439

    
440
?>
(6-6/15)