Project

General

Profile

1
<?php
2
/****************************************************************************
3
* SVN Version information:
4
*
5
* $Id: class.login.php 1235 2010-01-10 14:11:00Z Luisehahne $
6
*
7
*
8
*
9
*****************************************************************************
10
*                          WebsiteBaker
11
*
12
* WebsiteBaker Project <http://www.websitebaker2.org/>
13
* Copyright (C) 2009, Website Baker Org. e.V.
14
*         http://start.websitebaker2.org/impressum-datenschutz.php
15
* Copyright (C) 2004-2009, Ryan Djurovich
16
*
17
*                        About WebsiteBaker
18
*
19
* Website Baker is a PHP-based Content Management System (CMS)
20
* designed with one goal in mind: to enable its users to produce websites
21
* with ease.
22
*
23
*****************************************************************************
24
*
25
*****************************************************************************
26
*                        LICENSE INFORMATION
27
*
28
* WebsiteBaker is free software; you can redistribute it and/or
29
* modify it under the terms of the GNU General Public License
30
* as published by the Free Software Foundation; either version 2
31
* of the License, or (at your option) any later version.
32
*
33
* WebsiteBaker is distributed in the hope that it will be useful,
34
* but WITHOUT ANY WARRANTY; without even the implied warranty of
35
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
36
* See the GNU General Public License for more details.
37
*
38
* You should have received a copy of the GNU General Public License
39
* along with this program; if not, write to the Free Software
40
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
41
****************************************************************************
42
*
43
*                   WebsiteBaker Extra Information
44
*
45
* This class will be used to with the login application
46
*
47
*
48
*
49
*
50
*
51
*****************************************************************************/
52
/**
53
 *
54
 * @category     backend
55
 * @package      login
56
 * @author       Ryan Djurovich
57
 * @copyright    2004-2009, Ryan Djurovich
58
 * @copyright    2009-2010, Website Baker Org. e.V.
59
 * @version      $Id: class.login.php 1235 2010-01-10 14:11:00Z Luisehahne $
60
 * @platform     WebsiteBaker 2.8.x
61
 * @requirements >= PHP 4.3.4
62
 * @license      http://www.gnu.org/licenses/gpl.html
63
 *
64
 */
65

    
66
// Stop this file from being accessed directly
67
if(!defined('WB_URL')) {
68
	header('Location: ../index.php');
69
	exit(0);
70
}
71

    
72
define('LOGIN_CLASS_LOADED', true);
73

    
74
// Load the other required class files if they are not already loaded
75
require_once(WB_PATH."/framework/class.admin.php");
76

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

    
258
			$_SESSION['SYSTEM_PERMISSIONS'] = array();
259
			$_SESSION['MODULE_PERMISSIONS'] = array();
260
			$_SESSION['TEMPLATE_PERMISSIONS'] = array();
261
			$_SESSION['GROUP_NAME'] = array();
262

    
263
			$first_group = true;
264
			foreach (explode(",", $this->get_session('GROUPS_ID')) as $cur_group_id)
265
            {
266
				$query = "SELECT * FROM ".$this->GROUPS_TABLE." WHERE group_id = '".$cur_group_id."'";
267
				$results = $database->query($query);
268
				$results_array = $results->fetchRow();
269
				$_SESSION['GROUP_NAME'][$cur_group_id] = $results_array['name'];
270
				// Set system permissions
271
				if($results_array['system_permissions'] != '') {
272
					$_SESSION['SYSTEM_PERMISSIONS'] = array_merge($_SESSION['SYSTEM_PERMISSIONS'], explode(',', $results_array['system_permissions']));
273
				}
274
				// Set module permissions
275
				if($results_array['module_permissions'] != '') {
276
					if ($first_group) {
277
          	$_SESSION['MODULE_PERMISSIONS'] = explode(',', $results_array['module_permissions']);
278
          } else {
279
          	$_SESSION['MODULE_PERMISSIONS'] = array_intersect($_SESSION['MODULE_PERMISSIONS'], explode(',', $results_array['module_permissions']));
280
					}
281
				}
282
				// Set template permissions
283
				if($results_array['template_permissions'] != '') {
284
					if ($first_group) {
285
          	$_SESSION['TEMPLATE_PERMISSIONS'] = explode(',', $results_array['template_permissions']);
286
          } else {
287
          	$_SESSION['TEMPLATE_PERMISSIONS'] = array_intersect($_SESSION['TEMPLATE_PERMISSIONS'], explode(',', $results_array['template_permissions']));
288
					}
289
				}
290
				$first_group = false;
291
			}	
292

    
293
			// Update the users table with current ip and timestamp
294
			$get_ts = time();
295
			$get_ip = $_SERVER['REMOTE_ADDR'];
296
			$query = "UPDATE ".$this->USERS_TABLE." SET login_when = '$get_ts', login_ip = '$get_ip' WHERE user_id = '$user_id'";
297
			$database->query($query);
298
		}
299
		// Return if the user exists or not
300
		return $num_rows;
301
	}
302
	
303
	// Increase the count for login attemps
304
	function increase_attemps() {
305
		if(!isset($_SESSION['ATTEMPS'])) {
306
			$_SESSION['ATTEMPS'] = 0;
307
		} else {
308
			$_SESSION['ATTEMPS'] = $this->get_session('ATTEMPS')+1;
309
		}
310
		$this->display_login();
311
	}
312
	
313
	// Function to set a "remembering" cookie for the user
314
	function remember($user_id) {
315
		$remember_key = '';
316
		// Generate user id to append to the remember key
317
		$length = 11-strlen($user_id);
318
		if($length > 0) {
319
			for($i = 1; $i <= $length; $i++) {
320
				$remember_key .= '0';
321
			}
322
		}
323
		// Generate remember key
324
		$remember_key .= $user_id.'_';
325
		$salt = "abchefghjkmnpqrstuvwxyz0123456789";
326
		srand((double)microtime()*1000000);
327
		$i = 0;
328
		while ($i <= 10) {
329
			$num = rand() % 33;
330
			$tmp = substr($salt, $num, 1);
331
			$remember_key = $remember_key . $tmp;
332
			$i++;
333
		}
334
		$remember_key = $remember_key;
335
		// Update the remember key in the db
336
		$database = new database();
337
		$database->query("UPDATE ".$this->USERS_TABLE." SET remember_key = '$remember_key' WHERE user_id = '$user_id' LIMIT 1");
338
		if($database->is_error()) {
339
			return false;
340
		} else {
341
			// Workout options for the cookie
342
			$cookie_name = 'REMEMBER_KEY';
343
			$cookie_value = $remember_key;
344
			$cookie_expire = time()+60*60*24*30;
345
			// Set the cookie
346
			if(setcookie($cookie_name, $cookie_value, $cookie_expire, '/')) {
347
				return true;
348
			} else {
349
				return false;
350
			}
351
		}
352
	}
353
	
354
	// Function to check if a user has been remembered
355
	function is_remembered() {
356
		if(isset($_COOKIE['REMEMBER_KEY']) AND $_COOKIE['REMEMBER_KEY'] != '') {
357
			// Check if the remember key is correct
358
			$database = new database();
359
			$sql = "SELECT `user_id` FROM `" . $this->USERS_TABLE . "` WHERE `remember_key` = '";
360
			$sql .= $this->get_safe_remember_key() . "' LIMIT 1";
361
			$check_query = $database->query($sql);
362

    
363
			if($check_query->numRows() > 0) {
364
				$check_fetch = $check_query->fetchRow();
365
				$user_id = $check_fetch['user_id'];
366
				// Check the remember key prefix
367
				$remember_key_prefix = '';
368
				$length = 11-strlen($user_id);
369
				if($length > 0) {
370
					for($i = 1; $i <= $length; $i++) {
371
						$remember_key_prefix .= '0';
372
					}
373
				}
374
				$remember_key_prefix .= $user_id.'_';
375
				$length = strlen($remember_key_prefix);
376
				if(substr($_COOKIE['REMEMBER_KEY'], 0, $length) == $remember_key_prefix) {
377
					return true;
378
				} else {
379
					return false;
380
				}
381
			} else {
382
				return false;
383
			}
384
		} else {
385
			return false;
386
		}
387
	}
388
	
389
	// Display the login screen
390
	function display_login() {
391
		// Get language vars
392
		global $MESSAGE;
393
		global $MENU;
394
		global $TEXT;
395
		// If attemps more than allowed, warn the user
396
		if($this->get_session('ATTEMPS') > $this->max_attemps) {
397
			$this->warn();
398
		}
399
		// Show the login form
400
		if($this->frontend != true) {
401
			require_once(WB_PATH.'/include/phplib/template.inc');
402
			$template = new Template($this->template_dir);
403
			$template->set_file('page', $this->template_file);
404
			$template->set_block('page', 'mainBlock', 'main');
405
			if($this->remember_me_option != true) {
406
				$template->set_var('DISPLAY_REMEMBER_ME', 'display: none;');
407
			} else {
408
				$template->set_var('DISPLAY_REMEMBER_ME', '');
409
			}
410
			$template->set_var(array(
411
											'ACTION_URL' => $this->login_url,
412
											'ATTEMPS' => $this->get_session('ATTEMPS'),
413
											'USERNAME' => $this->username,
414
											'USERNAME_FIELDNAME' => $this->username_fieldname,
415
											'PASSWORD_FIELDNAME' => $this->password_fieldname,
416
											'MESSAGE' => $this->message,
417
											'INTERFACE_DIR_URL' =>  ADMIN_URL.'/interface',
418
											'MAX_USERNAME_LEN' => $this->max_username_len,
419
											'MAX_PASSWORD_LEN' => $this->max_password_len,
420
											'WB_URL' => WB_URL,
421
											'THEME_URL' => THEME_URL,
422
											'LANGUAGE' => strtolower(LANGUAGE),
423
											'FORGOTTEN_DETAILS_APP' => $this->forgotten_details_app,
424
											'TEXT_FORGOTTEN_DETAILS' => $TEXT['FORGOTTEN_DETAILS'],
425
											'TEXT_USERNAME' => $TEXT['USERNAME'],
426
											'TEXT_PASSWORD' => $TEXT['PASSWORD'],
427
											'TEXT_REMEMBER_ME' => $TEXT['REMEMBER_ME'],
428
											'TEXT_LOGIN' => $TEXT['LOGIN'],
429
											'TEXT_HOME' => $TEXT['HOME'],
430
											'PAGES_DIRECTORY' => PAGES_DIRECTORY,
431
											'SECTION_LOGIN' => $MENU['LOGIN']
432
											)
433
									);
434
			if(defined('DEFAULT_CHARSET')) {
435
				$charset=DEFAULT_CHARSET;
436
			} else {
437
				$charset='utf-8';
438
			}
439
			
440
			$template->set_var('CHARSET', $charset);	
441
									
442
									
443
			$template->parse('main', 'mainBlock', false);
444
			$template->pparse('output', 'page');
445
		}
446
	}
447

    
448
	// sanities the REMEMBER_KEY cookie to avoid SQL injection
449
	function get_safe_remember_key() {
450
		if (!((strlen($_COOKIE['REMEMBER_KEY']) == 23) && (substr($_COOKIE['REMEMBER_KEY'], 11, 1) == '_'))) return '';
451
		// create a clean cookie (XXXXXXXXXXX_YYYYYYYYYYY) where X:= numeric, Y:= hash
452
		$clean_cookie = sprintf('%011d', (int) substr($_COOKIE['REMEMBER_KEY'], 0, 11)) . substr($_COOKIE['REMEMBER_KEY'], 11);
453
		return ($clean_cookie == $_COOKIE['REMEMBER_KEY']) ? $this->add_slashes($clean_cookie) : '';
454
	}
455
	
456
	// Warn user that they have had to many login attemps
457
	function warn() {
458
		header('Location: '.$this->warning_url);
459
		exit(0);
460
	}
461
	
462
}
463

    
464
?>
(6-6/15)