Project

General

Profile

« Previous | Next » 

Revision 1885

Added by Dietmar over 11 years ago

  1. protect magic setter to fix security issue in WbDatabase
    + additional arguments for Charset and TablePrefix in WbDatabase::doConnect
    + WbDatabase now can activate SET NAMES by doConnect argument
    + WbDatabase now provide TablePrefix property also (WbDatabase::TablePrefix)
    + initialize.php now also support Charset and TablePrefix settings from setup.ini.php
    ! in setup.ini.php some keys are renamed (WB_URL => AppUrl and ADMIN_DIRECTORY => AcpDir)

View differences:

branches/2.8.x/CHANGELOG
11 11
! = Update/Change
12 12
===============================================================================
13 13

  
14
11 Mar-2013 Build 1885 Dietmar Woellbrink (Luisehahne)
15
# protect magic setter to fix security issue in WbDatabase
16
+ additional arguments for Charset and TablePrefix in WbDatabase::doConnect
17
+ WbDatabase now can activate SET NAMES by doConnect argument
18
+ WbDatabase now provide TablePrefix property also (WbDatabase::TablePrefix)
19
+ initialize.php now also support Charset and TablePrefix settings from setup.ini.php
20
! in setup.ini.php some keys are renamed (WB_URL => AppUrl and ADMIN_DIRECTORY => AcpDir)
14 21
10 Mar-2013 Build 1884 Dietmar Woellbrink (Luisehahne)
15 22
! from security reasons the new installation has changed 
16 23
  from the old config.php into new setup.ini.php without 
branches/2.8.x/wb/admin/interface/version.php
51 51

  
52 52
// check if defined to avoid errors during installation (redirect to admin panel fails if PHP error/warnings are enabled)
53 53
if(!defined('VERSION')) define('VERSION', '2.8.3');
54
if(!defined('REVISION')) define('REVISION', '1884');
54
if(!defined('REVISION')) define('REVISION', '1885');
55 55
if(!defined('SP')) define('SP', '');
branches/2.8.x/wb/framework/WbDatabase.php
32 32
 */
33 33

  
34 34
/* -------------------------------------------------------- */
35
define('DATABASE_CLASS_LOADED', true);
35
@define('DATABASE_CLASS_LOADED', true);
36 36

  
37 37
class WbDatabase {
38 38

  
39 39
	private static $_oInstances = array();
40 40

  
41
	private $_db_handle = null; // readonly from outside
42
	private $_db_name   = '';
43
	private $connected  = false;
44
	private $error      = '';
45
	private $error_type = '';
46
	private $iQueryCount= 0;
41
	private $_db_handle  = null; // readonly from outside
42
	private $_db_name    = '';
43
	protected $sTablePrefix = '';
44
	protected $sCharset     = 'utf8';
45
	protected $connected    = false;
46
	protected $error        = '';
47
	protected $error_type   = '';
48
	protected $iQueryCount  = 0;
47 49

  
48 50
/* prevent from public instancing */
49 51
	protected function  __construct() {}
......
81 83
 * Example for SQL-Url:  'mysql://user:password@demo.de[:3306]/datenbank'
82 84
 */
83 85
	public function doConnect($url = '') {
86
		$this->connected = false;
84 87
		if($url != '') {
85 88
			$aIni = parse_url($url);
86 89
			
......
91 94
			$hostport = isset($aIni['port']) ? $aIni['port'] : '3306';
92 95
			$hostport = $hostport == '3306' ? '' : ':'.$hostport;
93 96
			$db_name  = ltrim(isset($aIni['path']) ? $aIni['path'] : '', '/\\');
97
			$sTmp = isset($aIni['query']) ? $aIni['query'] : '';
98
			$aQuery = explode('&', $sTmp);
99
			foreach($aQuery as $sArgument) {
100
				$aArg = explode('=', $sArgument);
101
				switch(strtolower($aArg[0])) {
102
					case 'charset':
103
						$this->sCharset = strtolower(preg_replace('/[^a-z0-9]/i', '', $aArg[1]));
104
						break;
105
					case 'tableprefix':
106
						$this->sTablePrefix = $aArg[1];
107
						break;
108
					default:
109
						break;
110
				}
111
			}
94 112
			$this->_db_name = $db_name;
95 113
		}else {
96
			throw new RuntimeException('Missing parameter: unable to connect database');
114
			throw new WbDatabaseException('Missing parameter: unable to connect database');
97 115
		}
98
		$this->_db_handle = mysql_connect($hostname.$hostport,
116
		$this->_db_handle = @mysql_connect($hostname.$hostport,
99 117
		                                  $username,
100 118
		                                  $password);
101 119
		if(!$this->_db_handle) {
102
			throw new RuntimeException('unable to connect \''.$scheme.'://'.
120
			throw new WbDatabaseException('unable to connect \''.$scheme.'://'.
103 121
			                           $hostname.$hostport.'\'');
104 122
		} else {
105
			if(!mysql_select_db($db_name)) {
106
				throw new RuntimeException('unable to select database \''.$db_name.
123
			if(!@mysql_select_db($db_name)) {
124
				throw new WbDatabaseException('unable to select database \''.$db_name.
107 125
				                           '\' on \''.$scheme.'://'.
108 126
				                           $hostname.$hostport.'\'');
109 127
			} else {
128
				if($this->sCharset) {
129
					@mysql_query('SET NAMES \''.$this->sCharset.'\'');
130
				}
110 131
				$this->connected = true;
111 132
			}
112 133
		}
......
170 191
	public function get_error() {
171 192
		return $this->error;
172 193
	}
173

  
174
	// Return escape_string
175 194
/**
176
 * escape a string for use in DB
177
 * @param string 
178
 * @return string
195
 * Protect class from property injections
196
 * @param string name of property
197
 * @param mixed value
198
 * @throws WbDatabaseException
179 199
 */	
180
	public function escapeString($string) {
181
		return mysql_real_escape_string($string, $this->_db_handle);
200
	public function __set($name, $value) {
201
		throw new WbDatabaseException('tried to set a readonly or nonexisting property ['.$name.']!! ');
182 202
	}
183

  
184 203
/**
185 204
 * default Getter for some properties
186 205
 * @param string name of the Property
......
195 214
				$retval = $this->_db_handle;
196 215
				break;
197 216
			case 'LastInsertId':
217
			case 'getLastInsertId':
198 218
				$retval = mysql_insert_id($this->_db_handle);
199 219
				break;
200 220
			case 'db_name':
......
202 222
			case 'getDbName':
203 223
				$retval = $this->_db_name;
204 224
				break;
225
			case 'TablePrefix':
226
			case 'getTablePrefix':
227
				$retval = $this->sTablePrefix;			
228
				break;
205 229
			case 'getQueryCount':
206 230
				$retval = $this->iQueryCount;
207 231
				break;
......
211 235
		endswitch;
212 236
		return $retval;
213 237
	} // __get()
214

  
238
/**
239
 * Escapes special characters in a string for use in an SQL statement
240
 * @param string $unescaped_string
241
 * @return string
242
 */
243
	public function escapeString($unescaped_string)
244
	{
245
		return mysql_real_escape_string($unescaped_string, $this->_db_handle);
246
	}
247
/**
248
 * Last inserted Id
249
 * @return bool|int false on error, 0 if no record inserted
250
 */	
251
	public function getLastInsertId()
252
	{
253
		return mysql_insert_id($this->_db_handle);
254
	}
215 255
/*
216 256
 * @param string full name of the table (incl. TABLE_PREFIX)
217 257
 * @param string name of the field to seek for
......
223 263
		$query = $this->query($sql, $this->_db_handle);
224 264
		return ($query->numRows() != 0);
225 265
	}
226

  
227 266
/*
228 267
 * @param string full name of the table (incl. TABLE_PREFIX)
229 268
 * @param string name of the index to seek for
......
322 361
     public function index_add($table_name, $index_name, $field_list, $index_type = 'KEY')
323 362
     {
324 363
        $retval = false;
325
        $field_list = str_replace(' ', '', $field_list);
326
        $field_list = explode(',', $field_list);
364
        $field_list = explode(',', (str_replace(' ', '', $field_list)));
327 365
        $number_fields = sizeof($field_list);
328 366
        $field_list = '`'.implode('`,`', $field_list).'`';
329 367
        $index_name = $index_type == 'PRIMARY' ? $index_type : $index_name;
......
421 459

  
422 460

  
423 461
} /// end of class database
462
// //////////////////////////////////////////////////////////////////////////////////// //
463
/**
464
 * WbDatabaseException
465
 *
466
 * @category     Core
467
 * @package      Core_database
468
 * @author       Werner v.d.Decken <wkl@isteam.de>
469
 * @copyright    Werner v.d.Decken <wkl@isteam.de>
470
 * @license      http://www.gnu.org/licenses/gpl.html   GPL License
471
 * @version      2.9.0
472
 * @revision     $Revision$
473
 * @lastmodified $Date$
474
 * @description  Exceptionhandler for the WbDatabase and depending classes
475
 */
476
class WbDatabaseException extends AppException {}
424 477

  
425 478
define('MYSQL_SEEK_FIRST', 0);
426 479
define('MYSQL_SEEK_LAST', -1);
......
469 522
	}
470 523

  
471 524
}
472

  
525
// //////////////////////////////////////////////////////////////////////////////////// //
473 526
/* this function is placed inside this file temporarely until a better place is found */
474 527
/*  function to update a var/value-pair(s) in table ****************************
475 528
 *  nonexisting keys are inserted
branches/2.8.x/wb/framework/initialize.php
114 114
		if(is_readable($sSetupFile)) {
115 115
			$aCfg = parse_ini_file($sSetupFile, true);
116 116
			foreach($aCfg['Constants'] as $key=>$value) {
117
				if($key == 'debug') { $value = filter_var($value, FILTER_VALIDATE_BOOLEAN); }
118
				if(!defined(strtoupper($key))) { define(strtoupper($key), $value); }
117
				switch($key):
118
					case 'DEBUG':
119
						$value = filter_var($value, FILTER_VALIDATE_BOOLEAN);
120
						break;
121
					case 'WB_URL':
122
					case 'AppUrl':
123
						$value = trim(str_replace('\\', '/', $value), '/'); 
124
						if(!defined('WB_URL')) { define('WB_URL', $value); }
125
						break;
126
					case 'ADMIN_DIRECTORY':
127
					case 'AcpDir':
128
						$value = trim(str_replace('\\', '/', $value), '/'); 
129
						if(!defined('ADMIN_DIRECTORY')) { define('ADMIN_DIRECTORY', $value); }
130
						break;
131
					default:
132
						if(!defined($key)) { define($key, $value); }
133
						break;
134
				endswitch;
119 135
			}
120 136
			$db = $aCfg['DataBase'];
121 137
			$db['type'] = isset($db['type']) ? $db['type'] : 'mysql';
......
135 151
				$aRetval[2] = array( 'user' => $db['user'], 'pass' => $db['pass']);
136 152
			}else { // $sRetvalType == 'url'
137 153
				$aRetval[0] = $db['type'].'://'.$db['user'].':'.$db['pass'].'@'
138
				            . $db['host'].($db['port'] != '' ? ':'.$db['port'] : '').'/'.$db['name'];
154
				            . $db['host'].($db['port'] != '' ? ':'.$db['port'] : '').'/'.$db['name']
155
				            . '?Charset='.$db['charset'].'&TablePrefix='.$db['table_prefix'];
139 156
			}
140 157
			unset($db, $aCfg);
141 158
			return $aRetval;
......
159 176
	}
160 177
// load db configuration ---
161 178
	if(defined('DB_TYPE')) {
162
		$aSqlData = array( 0 => DB_TYPE.'://'.DB_USERNAME.':'.DB_PASSWORD.'@'.DB_HOST.'/'.DB_NAME);
179
		$sTmp = ($sTmp=((defined('DB_PORT') && DB_PORT !='') ? DB_PORT : '')) ? ':'.$sTmp : '';
180
		$sTmp = DB_TYPE.'://'.DB_USERNAME.':'.DB_PASSWORD.'@'.DB_HOST.$sTmp.'/'.DB_NAME.'?Charset=';
181
		$sTmp .= (defined('DB_CHARSET') ? DB_CHARSET : '').'&TablePrefix='.TABLE_PREFIX;
182
		$aSqlData = array( 0 => $sTmp);
163 183
	}else {
164 184
		$aSqlData = readConfiguration($sDbConnectType);
165 185
	}
......
193 213
	if($sDbConnectType == 'dsn') {
194 214
		$bTmp = $database->doConnect($aSqlData[0], $aSqlData[1]['user'], $aSqlData[1]['pass'], $aSqlData[2]);
195 215
	}else {
196
		$bTmp = $database->doConnect($aSqlData[0], TABLE_PREFIX);
216
		$bTmp = $database->doConnect($aSqlData[0]);
197 217
	}
198 218
	unset($aSqlData);
199 219
// load global settings from database and define global consts from ---
......
316 336
// load and activate new global translation table
317 337
	Translate::getInstance()->initialize('en',
318 338
										 (defined('DEFAULT_LANGUAGE') ? DEFAULT_LANGUAGE : ''), 
319
										 (defined('LANGUAGE') ? LANGUAGE : '') 
339
										 (defined('LANGUAGE') ? LANGUAGE : ''),
340
										 'WbOldStyle',
341
										 (DEBUG ? Translate::CACHE_DISABLED|Translate::KEEP_MISSING : 0)
320 342
										);
321 343
// *** END OF FILE ***********************************************************************
322 344
 
branches/2.8.x/wb/install/save.php
93 93
		if(is_readable($sSetupFile)) {
94 94
			$aCfg = parse_ini_file($sSetupFile, true);
95 95
			foreach($aCfg['Constants'] as $key=>$value) {
96
				if($key == 'debug') { $value = filter_var($value, FILTER_VALIDATE_BOOLEAN); }
97
				if(!defined(strtoupper($key))) { define(strtoupper($key), $value); }
96
				switch($key):
97
					case 'DEBUG':
98
						$value = filter_var($value, FILTER_VALIDATE_BOOLEAN);
99
						break;
100
					case 'WB_URL':
101
					case 'AppUrl':
102
						$value = trim(str_replace('\\', '/', $value), '/'); 
103
						if(!defined('WB_URL')) { define('WB_URL', $value); }
104
						break;
105
					case 'ADMIN_DIRECTORY':
106
					case 'AcpDir':
107
						$value = trim(str_replace('\\', '/', $value), '/'); 
108
						if(!defined('ADMIN_DIRECTORY')) { define('ADMIN_DIRECTORY', $value); }
109
						break;
110
					default:
111
						if(!defined($key)) { define($key, $value); }
112
						break;
113
				endswitch;
98 114
			}
99 115
			$db = $aCfg['DataBase'];
100 116
			$db['type'] = isset($db['type']) ? $db['type'] : 'mysql';
......
114 130
				$aRetval[2] = array( 'user' => $db['user'], 'pass' => $db['pass']);
115 131
			}else { // $sRetvalType == 'url'
116 132
				$aRetval[0] = $db['type'].'://'.$db['user'].':'.$db['pass'].'@'
117
				            . $db['host'].($db['port'] != '' ? ':'.$db['port'] : '').'/'.$db['name'];
133
				            . $db['host'].($db['port'] != '' ? ':'.$db['port'] : '').'/'.$db['name']
134
				            . '?Charset='.$db['charset'].'&TablePrefix='.$db['table_prefix'];
118 135
			}
119 136
			unset($db, $aCfg);
120 137
			return $aRetval;
......
243 260
	$wb_url = $_POST['wb_url'];
244 261
}
245 262
// Remove any slashes at the end of the URL
246
$wb_url = rtrim($wb_url,'/\\');
263
$wb_url = trim(str_replace('\\', '/', $wb_url), '/').'/';
247 264
// Get the default time zone
248 265
if(!isset($_POST['default_timezone']) OR !is_numeric($_POST['default_timezone'])) {
249 266
	set_error('Please select a valid default timezone', 'default_timezone');
......
378 395
."; auto generated ".date('Y-m-d h:i:s A e ')."\n"
379 396
.";################################################\n"
380 397
."[Constants]\n"
381
."debug     = false\n"
382
."wb_url    = ".$wb_url."\n"
383
."admin_directory = admin\n"
398
."DEBUG   = false\n"
399
."AppUrl  = ".$wb_url."\n"
400
."AcpDir  = admin/\n"
384 401
.";##########\n"
385 402
."[DataBase]\n"
386 403
."type    = \"mysql\"\n"
......
427 444
	}else {
428 445
		$bTmp = @$database->doConnect($aSqlData[0], TABLE_PREFIX);
429 446
	}
430
} catch (RuntimeException $e) {
447
} catch (WbDatabaseException $e) {
431 448
	if(!file_put_contents($sConfigFile,"<?php\n")) {
432 449
		set_error("Cannot write to the configuration file ($sSetupFile)");
433 450
	}
branches/2.8.x/wb/install/index.php
103 103
			if(is_writeable($sConfigFile))
104 104
			{
105 105
// already installed? it's not empty
106
				if ( filesize($sConfigFile) > 128)
106
				if ( filesize($sConfigFile) > 100)
107 107
				{
108 108
					$config = '<font class="bad">Already installed? Check!</font>';
109 109
// try to open and to write
......
277 277
	} else {
278 278
		$config = $sTmp;
279 279
	}
280
	$sConfigFile = preg_match('/(?:rename)/i',$config) ? $sConfigFile : 'setup.ini.php';
280
	$sConfigFile = preg_match('/(?:rename)/i',$config) ? $sConfigFile : 'config.php';
281 281
	$installFlag = $installFlag && ($sTmp == '');
282 282
?>
283 283
		<tr>

Also available in: Unified diff