Project

General

Profile

« Previous | Next » 

Revision 1680

Added by darkviper over 12 years ago

renamed file class.database.php to Database.php
renamed class database into Database
classes SecurityException and SecDirectoryTraversalException added in globalExceptionHandler.php
CoreAutoloader() added in initialize.php
new Constants 'WB_REL' and 'DOCUMENT_ROOT' in initialize.php
class Database is able now to create multiple connections at same time
class ModLanguage added for easy handle of languages from modules

View differences:

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

  
14

  
14
03 May-2012 Build 1680 Werner v.d.Decken(DarkViper)
15
! renamed file class.database.php to Database.php
16
! renamed class database into Database
17
+ classes SecurityException and SecDirectoryTraversalException added in globalExceptionHandler.php
18
+ CoreAutoloader() added in initialize.php
19
+ new Constants 'WB_REL' and 'DOCUMENT_ROOT' in initialize.php
20
! class Database is able now to create multiple connections at same time
21
+ class ModLanguage added for easy handle of languages from modules
15 22
28 Apr-2012 Build 1679 Dietmar Woellbrink (Luisehahne)
16 23
+ add tool_icon.png to admintools
17 24
27 Apr-2012 Build 1678 Dietmar Woellbrink (Luisehahne)
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', '1679');
54
if(!defined('REVISION')) define('REVISION', '1680');
55 55
if(!defined('SP')) define('SP', '');
branches/2.8.x/wb/framework/class.database.php
1
<?php
2
/**
3
 *
4
 * @category        framework
5
 * @package         database
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$
14
 * @filesource      $HeadURL$
15
 * @lastmodified    $Date$
16
 *
17
 */
18
/*
19
Database class
20
This class will be used to interface between the database
21
and the Website Baker code
22
*/
23
/* -------------------------------------------------------- */
24
// Must include code to stop this file being accessed directly
25
if(!defined('WB_PATH')) {
26
	require_once(dirname(__FILE__).'/globalExceptionHandler.php');
27
	throw new IllegalFileException();
28
}
29
/* -------------------------------------------------------- */
30
if(!defined('DB_URL')) {
31
	//define('DB_URL', DB_TYPE.'://'.DB_USERNAME.':'.DB_PASSWORD.'@'.DB_HOST.'/'.DB_NAME);
32
}
33

  
34
define('DATABASE_CLASS_LOADED', true);
35

  
36
class database {
37

  
38
	private $db_handle  = null; // readonly from outside
39
	private $db_name    = '';
40
	private $connected  = false;
41

  
42
	private $error      = '';
43
	private $error_type = '';
44
	private $message    = array();
45
	private $iQueryCount= 0;
46

  
47

  
48
	// Set DB_URL
49
	function database($url = '') {
50
		// Connect to database
51
		$this->connect();
52
		// Check for database connection error
53
		if($this->is_error()) {
54
			die($this->get_error());
55
		}
56
	}
57
	
58
	// Connect to the database
59
	function connect() {
60
		$status = $this->db_handle = mysql_connect(DB_HOST, DB_USERNAME, DB_PASSWORD);
61
		if(mysql_error()) {
62
			$this->connected = false;
63
			$this->error = mysql_error();
64
		} else {
65
			if(!mysql_select_db(DB_NAME)) {
66
				$this->connected = false;
67
				$this->error = mysql_error();
68
			} else {
69
				$this->db_name = DB_NAME;
70
				$this->connected = true;
71
			}
72
		}
73
		return $this->connected;
74
	}
75
	
76
	// Disconnect from the database
77
	function disconnect() {
78
		if($this->connected==true) {
79
			mysql_close();
80
			return true;
81
		} else {
82
			return false;
83
		}
84
	}
85
	
86
	// Run a query
87
	function query($statement) {
88
		$this->iQueryCount++;
89
		$mysql = new mysql();
90
		$mysql->query($statement);
91
		$this->set_error($mysql->error());
92
		if($mysql->error()) {
93
			return null;
94
		} else {
95
			return $mysql;
96
		}
97
	}
98

  
99
	// Gets the first column of the first row
100
	function get_one( $statement )
101
	{
102
		$this->iQueryCount++;
103
		$fetch_row = mysql_fetch_array(mysql_query($statement) );
104
		$result = $fetch_row[0];
105
		$this->set_error(mysql_error());
106
		if(mysql_error()) {
107
			return null;
108
		} else {
109
			return $result;
110
		}
111
	}
112
	
113
	// Set the DB error
114
	function set_error($message = null) {
115
		global $TABLE_DOES_NOT_EXIST, $TABLE_UNKNOWN;
116
		$this->error = $message;
117
		if(strpos($message, 'no such table')) {
118
			$this->error_type = $TABLE_DOES_NOT_EXIST;
119
		} else {
120
			$this->error_type = $TABLE_UNKNOWN;
121
		}
122
	}
123
	
124
	// Return true if there was an error
125
	function is_error() {
126
		return (!empty($this->error)) ? true : false;
127
	}
128
	
129
	// Return the error
130
	function get_error() {
131
		return $this->error;
132
	}
133

  
134
/**
135
 * default Getter for some properties
136
 * @param string $sPropertyName
137
 * @return mixed NULL on error or missing property
138
 */
139
	public function __get($sPropertyName)
140
	{
141
		switch ($sPropertyName):
142
			case 'db_handle':
143
			case 'DbHandle':
144
			case 'getDbHandle':
145
				$retval = $this->db_handle;
146
				break;
147
			case 'db_name':
148
			case 'DbName':
149
			case 'getDbName':
150
				$retval = $this->db_name;
151
				break;
152
			case 'getQueryCount':
153
				$retval = $this->iQueryCount;
154
				break;
155
			default:
156
				$retval = null;
157
				break;
158
		endswitch;
159
		return $retval;
160
	} // __get()
161

  
162
/*
163
 * @param string $table_name: full name of the table (incl. TABLE_PREFIX)
164
 * @param string $field_name: name of the field to seek for
165
 * @return bool: true if field exists
166
 */
167
	public function field_exists($table_name, $field_name)
168
	{
169
		$sql = 'DESCRIBE `'.$table_name.'` `'.$field_name.'` ';
170
		$query = $this->query($sql);
171
		return ($query->numRows() != 0);
172
	}
173

  
174
/*
175
 * @param string $table_name: full name of the table (incl. TABLE_PREFIX)
176
 * @param string $index_name: name of the index to seek for
177
 * @return bool: true if field exists
178
 */
179
	public function index_exists($table_name, $index_name, $number_fields = 0)
180
	{
181
		$number_fields = intval($number_fields);
182
		$keys = 0;
183
		$sql = 'SHOW INDEX FROM `'.$table_name.'`';
184
		if( ($res_keys = $this->query($sql)) )
185
		{
186
			while(($rec_key = $res_keys->fetchRow()))
187
			{
188
				if( $rec_key['Key_name'] == $index_name )
189
				{
190
					$keys++;
191
				}
192
			}
193

  
194
		}
195
		if( $number_fields == 0 )
196
		{
197
			return ($keys != $number_fields);
198
		}else
199
		{
200
			return ($keys == $number_fields);
201
		}
202
	}
203
/*
204
 * @param string $table_name: full name of the table (incl. TABLE_PREFIX)
205
 * @param string $field_name: name of the field to add
206
 * @param string $description: describes the new field like ( INT NOT NULL DEFAULT '0')
207
 * @return bool: true if successful, otherwise false and error will be set
208
 */
209
	public function field_add($table_name, $field_name, $description)
210
	{
211
		if( !$this->field_exists($table_name, $field_name) )
212
		{ // add new field into a table
213
			$sql = 'ALTER TABLE `'.$table_name.'` ADD '.$field_name.' '.$description.' ';
214
			$query = $this->query($sql);
215
			$this->set_error(mysql_error());
216
			if( !$this->is_error() )
217
			{
218
				return ( $this->field_exists($table_name, $field_name) ) ? true : false;
219
			}
220
		}else
221
		{
222
			$this->set_error('field \''.$field_name.'\' already exists');
223
		}
224
		return false;
225
	}
226

  
227
/*
228
 * @param string $table_name: full name of the table (incl. TABLE_PREFIX)
229
 * @param string $field_name: name of the field to add
230
 * @param string $description: describes the new field like ( INT NOT NULL DEFAULT '0')
231
 * @return bool: true if successful, otherwise false and error will be set
232
 */
233
	public function field_modify($table_name, $field_name, $description)
234
	{
235
		$retval = false;
236
		if( $this->field_exists($table_name, $field_name) )
237
		{ // modify a existing field in a table
238
			$sql  = 'ALTER TABLE `'.$table_name.'` MODIFY `'.$field_name.'` '.$description;
239
			$retval = ( $this->query($sql) ? true : false);
240
			$this->set_error(mysql_error());
241
		}
242
		return $retval;
243
	}
244

  
245
/*
246
 * @param string $table_name: full name of the table (incl. TABLE_PREFIX)
247
 * @param string $field_name: name of the field to remove
248
 * @return bool: true if successful, otherwise false and error will be set
249
 */
250
	public function field_remove($table_name, $field_name)
251
	{
252
		$retval = false;
253
		if( $this->field_exists($table_name, $field_name) )
254
		{ // modify a existing field in a table
255
			$sql  = 'ALTER TABLE `'.$table_name.'` DROP `'.$field_name.'`';
256
			$retval = ( $this->query($sql) ? true : false );
257
		}
258
		return $retval;
259
	}
260

  
261
/*
262
 * @param string $table_name: full name of the table (incl. TABLE_PREFIX)
263
 * @param string $index_name: name of the new index
264
 * @param string $field_list: comma seperated list of fields for this index
265
 * @param string $index_type: kind of index (UNIQUE, PRIMARY, '')
266
 * @return bool: true if successful, otherwise false and error will be set
267
 */
268
	public function index_add($table_name, $index_name, $field_list, $index_type = '')
269
	{
270
		$retval = false;
271
		$field_list = str_replace(' ', '', $field_list);
272
		$field_list = explode(',', $field_list);
273
		$number_fields = sizeof($field_list);
274
		$field_list = '`'.implode('`,`', $field_list).'`';
275
		if( $this->index_exists($table_name, $index_name, $number_fields) ||
276
		    $this->index_exists($table_name, $index_name))
277
		{
278
			$sql  = 'ALTER TABLE `'.$table_name.'` ';
279
			$sql .= 'DROP INDEX `'.$index_name.'`';
280
			if( $this->query($sql))
281
			{
282
				$sql  = 'ALTER TABLE `'.$table_name.'` ';
283
				$sql .= 'ADD '.$index_type.' `'.$index_name.'` ( '.$field_list.' ); ';
284
				if( $this->query($sql)) { $retval = true; }
285
			}
286
		}
287
		return $retval;
288
	}
289

  
290
/*
291
 * @param string $table_name: full name of the table (incl. TABLE_PREFIX)
292
 * @param string $field_name: name of the field to remove
293
 * @return bool: true if successful, otherwise false and error will be set
294
 */
295
	public function index_remove($table_name, $index_name)
296
	{
297
		$retval = false;
298
		if( $this->index_exists($table_name, $index_name) )
299
		{ // modify a existing field in a table
300
			$sql  = 'ALTER TABLE `'.$table_name.'` DROP INDEX `'.$index_name.'`';
301
			$retval = ( $this->query($sql) ? true : false );
302
		}
303
		return $retval;
304
	}
305
/**
306
 * Import a standard *.sql dump file
307
 * @param string $sSqlDump link to the sql-dumpfile
308
 * @param string $sTablePrefix
309
 * @param bool $bPreserve set to true will ignore all DROP TABLE statements
310
 * @param string $sTblEngine
311
 * @param string $sTblCollation
312
 * @return boolean true if import successful
313
 */
314
	public function SqlImport($sSqlDump,
315
	                          $sTablePrefix = '',
316
	                          $bPreserve = true,
317
	                          $sTblEngine = 'ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci',
318
	                          $sTblCollation = ' collate utf8_unicode_ci')
319
	{
320
		$retval = true;
321
		$this->error = '';
322
		$aSearch  = array('{TABLE_PREFIX}','{TABLE_ENGINE}', '{TABLE_COLLATION}');
323
		$aReplace = array($sTablePrefix, $sTblEngine, $sTblCollation);
324
		$sql = '';
325
		$aSql = file($sSqlDump);
326
		while ( sizeof($aSql) > 0 ) {
327
			$sSqlLine = trim(array_shift($aSql));
328
			if (!preg_match('/^[-\/]+.*/', $sSqlLine)) {
329
				$sql = $sql.' '.$sSqlLine;
330
				if ((substr($sql,-1,1) == ';')) {
331
					$sql = trim(str_replace( $aSearch, $aReplace, $sql));
332
					if (!($bPreserve && preg_match('/^\s*DROP TABLE IF EXISTS/siU', $sql))) {
333
						if(!mysql_query($sql, $this->db_handle)) {
334
							$retval = false;
335
							$this->error = mysql_error($this->db_handle);
336
							unset($aSql);
337
							break;
338
						}
339
					}
340
					$sql = '';
341
				}
342
			}
343
		}
344
		return $retval;
345
	}
346

  
347
/**
348
 * retuns the type of the engine used for requested table
349
 * @param string $table name of the table, including prefix
350
 * @return boolean/string false on error, or name of the engine (myIsam/InnoDb)
351
 */
352
	public function getTableEngine($table)
353
	{
354
		$retVal = false;
355
		$mysqlVersion = mysql_get_server_info($this->db_handle);
356
		$engineValue = (version_compare($mysqlVersion, '5.0') < 0) ? 'Type' : 'Engine';
357
		$sql = "SHOW TABLE STATUS FROM " . $this->db_name . " LIKE '" . $table . "'";
358
		if(($result = $this->query($sql))) {
359
			if(($row = $result->fetchRow(MYSQL_ASSOC))) {
360
				$retVal = $row[$engineValue];
361
			}
362
		}
363
		return $retVal;
364
	}
365

  
366

  
367
} /// end of class database
368

  
369
define('MYSQL_SEEK_FIRST', 0);
370
define('MYSQL_SEEK_LAST', -1);
371

  
372
class mysql {
373

  
374
	// Run a query
375
	function query($statement) {
376
		$this->result = mysql_query($statement);
377
		$this->error = mysql_error();
378
		return $this->result;
379
	}
380
	
381
	// Fetch num rows
382
	function numRows() {
383
		return mysql_num_rows($this->result);
384
	}
385

  
386
	// Fetch row  $typ = MYSQL_ASSOC, MYSQL_NUM, MYSQL_BOTH
387
	function fetchRow($typ = MYSQL_BOTH) {
388
		return mysql_fetch_array($this->result, $typ);
389
	}
390

  
391
	function rewind()
392
	{
393
		return $this->seekRow();
394
	}
395

  
396
	function seekRow( $position = MYSQL_SEEK_FIRST )
397
	{
398
		$pmax = $this->numRows() - 1;
399
		$p = (($position < 0 || $position > $pmax) ? $pmax : $position);
400
		return mysql_data_seek($this->result, $p);
401
	}
402

  
403
	// Get error
404
	function error() {
405
		if(isset($this->error)) {
406
			return $this->error;
407
		} else {
408
			return null;
409
		}
410
	}
411

  
412
}
413
/* this function is placed inside this file temporarely until a better place is found */
414
/*  function to update a var/value-pair(s) in table ****************************
415
 *  nonexisting keys are inserted
416
 *  @param string $table: name of table to use (without prefix)
417
 *  @param mixed $key:    a array of key->value pairs to update
418
 *                        or a string with name of the key to update
419
 *  @param string $value: a sting with needed value, if $key is a string too
420
 *  @return bool:  true if any keys are updated, otherwise false
421
 */
422
	function db_update_key_value($table, $key, $value = '')
423
	{
424
		global $database;
425
		if( !is_array($key))
426
		{
427
			if( trim($key) != '' )
428
			{
429
				$key = array( trim($key) => trim($value) );
430
			} else {
431
				$key = array();
432
			}
433
		}
434
		$retval = true;
435
		foreach( $key as $index=>$val)
436
		{
437
			$index = strtolower($index);
438
			$sql = 'SELECT COUNT(`setting_id`) FROM `'.TABLE_PREFIX.$table.'` WHERE `name` = \''.$index.'\' ';
439
			if($database->get_one($sql))
440
			{
441
				$sql = 'UPDATE ';
442
				$sql_where = 'WHERE `name` = \''.$index.'\'';
443
			}else {
444
				$sql = 'INSERT INTO ';
445
				$sql_where = '';
446
			}
447
			$sql .= '`'.TABLE_PREFIX.$table.'` ';
448
			$sql .= 'SET `name` = \''.$index.'\', ';
449
			$sql .= '`value` = \''.$val.'\' '.$sql_where;
450
			if( !$database->query($sql) )
451
			{
452
				$retval = false;
453
			}
454
		}
455
		return $retval;
456
	}
457 0

  
branches/2.8.x/wb/framework/initialize.php
49 49
		}
50 50
		$_SERVER['HTTP_REFERER'] = $sTmpReferer;
51 51
	}
52

  
53
$starttime = array_sum(explode(" ",microtime()));
54
if(!defined('DEBUG')){ define('DEBUG', false); }// Include config file
55
if( !defined('ADMIN_DIRECTORY')) { define('ADMIN_DIRECTORY', 'admin'); }
56
if(!preg_match('/xx[a-z0-9_][a-z0-9_\-\.]+/i', 'xx'.ADMIN_DIRECTORY)) {
57
	throw new RuntimeException('Invalid admin-directory: ' . ADMIN_DIRECTORY);
58
}
59

  
60
if( !defined('ADMIN_URL')) { define('ADMIN_URL', WB_URL.'/'.ADMIN_DIRECTORY); }
61
if( !defined('WB_PATH')) { define('WB_PATH', dirname(dirname(__FILE__))); }
62
if( !defined('ADMIN_PATH')) { define('ADMIN_PATH', WB_PATH.'/'.ADMIN_DIRECTORY); }
63

  
64
if (file_exists(WB_PATH.'/framework/class.database.php')) {
65
	// sanitize $_SERVER['HTTP_REFERER']
66
	SanitizeHttpReferer(WB_URL);
52
/* -------------------------------------------------------- */
53
/**
54
 * Autoloader to load classes according to the new WB-2.9 standard
55
 * @param string $sClassName name of the requested class
56
 */
57
	function CoreAutoloader($sClassName) {
58
		$iCount = 0;
59
		$aSearch = array('/^m_/i', '/^a_/i');
60
		$aReplace = array('modules_', ADMIN_DIRECTORY.'_' );
61
		$sClassName = preg_replace($aSearch, $aReplace, $sClassName, 1, $iCount);
62
		if(!$iCount) { $sClassName = 'framework_'.$sClassName; }
63
		$sFileName = WB_PATH.'/'.str_replace('_', '/', $sClassName).'.php';
64
		if(file_exists($sFileName)) {
65
			include($sFileName);
66
		}
67
	}
68
/* -------------------------------------------------------- */
69
	function SetInstallPathConstants() {
70
		if(!defined('DEBUG')){ define('DEBUG', false); }// Include config file
71
		if(!defined('ADMIN_DIRECTORY')){ define('ADMIN_DIRECTORY', 'admin'); }
72
		if(!preg_match('/xx[a-z0-9_][a-z0-9_\-\.]+/i', 'xx'.ADMIN_DIRECTORY)) {
73
			throw new RuntimeException('Invalid admin-directory: ' . ADMIN_DIRECTORY);
74
		}
75
		if(!defined('WB_PATH')){ define('WB_PATH', dirname(dirname(__FILE__))); }
76
		if(!defined('ADMIN_URL')){ define('ADMIN_URL', WB_URL.'/'.ADMIN_DIRECTORY); }
77
		if(!defined('ADMIN_PATH')){ define('ADMIN_PATH', WB_PATH.'/'.ADMIN_DIRECTORY); }
78
		if(!defined('WB_REL')){
79
			$x1 = parse_url(WB_URL);
80
			define('WB_REL', (isset($x1['path']) ? $x1['path'] : ''));
81
		}
82
		if(!defined('DOCUMENT_ROOT')) {
83
			define('DOCUMENT_ROOT', preg_replace('/'.preg_quote(WB_REL, '/').'$/', '', WB_PATH));
84
		}
85
	}
86
/* -------------------------------------------------------- */
87
	$starttime = array_sum(explode(" ",microtime()));
88
	SetInstallPathConstants();
89
	SanitizeHttpReferer(WB_URL); // sanitize $_SERVER['HTTP_REFERER']
90
	spl_autoload_register('CoreAutoloader'); // activate core autoloader
67 91
	date_default_timezone_set('UTC');
68
	require_once(WB_PATH.'/framework/class.database.php');
69

  
70 92
	// Create database class
71
	$database = new database();
72

  
73
    if(version_compare(PHP_VERSION, '5.3.0', '<'))
74
    {
75
        set_magic_quotes_runtime(0); // Disable magic_quotes_runtime
76
    }
93
	$database = new Database();
94
	// disable all kind of magic_quotes
95
	if(get_magic_quotes_gpc() || get_magic_quotes_runtime()) {
96
		@ini_set('magic_quotes_sybase', 0);
97
		@ini_set('magic_quotes_gpc', 0);
98
		@ini_set('magic_quotes_runtime', 0);
99
	}
77 100
	// Get website settings (title, keywords, description, header, and footer)
78 101
	$query_settings = "SELECT name,value FROM ".TABLE_PREFIX."settings";
79 102
	$get_settings = $database->query($query_settings);
......
133 156

  
134 157
	// Get users language
135 158
	if(isset($_GET['lang']) AND $_GET['lang'] != '' AND !is_numeric($_GET['lang']) AND strlen($_GET['lang']) == 2) {
136
	  	define('LANGUAGE', strtoupper($_GET['lang']));
159
		define('LANGUAGE', strtoupper($_GET['lang']));
137 160
		$_SESSION['LANGUAGE']=LANGUAGE;
138 161
	} else {
139 162
		if(isset($_SESSION['LANGUAGE']) AND $_SESSION['LANGUAGE'] != '') {
......
142 165
			define('LANGUAGE', DEFAULT_LANGUAGE);
143 166
		}
144 167
	}
145
	
168

  
146 169
	// Load Language file
147 170
	if(!defined('LANGUAGE_LOADED')) {
148 171
		if(!file_exists(WB_PATH.'/languages/'.LANGUAGE.'.php')) {
......
151 174
			require_once(WB_PATH.'/languages/'.LANGUAGE.'.php');
152 175
		}
153 176
	}
154
	
177

  
155 178
	// Get users timezone
156 179
	if(isset($_SESSION['TIMEZONE'])) {
157 180
		define('TIMEZONE', $_SESSION['TIMEZONE']);
......
175 198
	define('THEME_URL', WB_URL.'/templates/'.DEFAULT_THEME);
176 199
	define('THEME_PATH', WB_PATH.'/templates/'.DEFAULT_THEME);
177 200

  
178
    // extended wb_settings
201
	// extended wb_settings
179 202
	define('EDIT_ONE_SECTION', false);
180 203

  
181 204
	define('EDITOR_WIDTH', 0);
182

  
183
}
branches/2.8.x/wb/framework/Database.php
1
<?php
2
/**
3
 *
4
 * @category        framework
5
 * @package         database
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$
14
 * @filesource      $HeadURL$
15
 * @lastmodified    $Date$
16
 *
17
 */
18
/*
19
Database class
20
This class will be used to interface between the database
21
and the Website Baker code
22
*/
23
/* -------------------------------------------------------- */
24
// Must include code to stop this file being accessed directly
25
if(!defined('WB_PATH')) {
26
	require_once(dirname(__FILE__).'/globalExceptionHandler.php');
27
	throw new IllegalFileException();
28
}
29
/* -------------------------------------------------------- */
30
define('DATABASE_CLASS_LOADED', true);
31

  
32
class Database {
33

  
34
//	$sdb = 'mysql://user:password@demo.de:3604/datenbank';
35

  
36
	private $_db_handle = null; // readonly from outside
37
	private $_scheme    = 'mysql';
38
	private $_hostname  = 'localhost';
39
	private $_username  = '';
40
	private $_password  = '';
41
	private $_hostport  = '3406';
42
	private $_db_name   = '';
43

  
44
	private $connected  = false;
45

  
46
	private $error      = '';
47
	private $error_type = '';
48
	private $message    = array();
49
	private $iQueryCount= 0;
50

  
51

  
52
	// Set DB_URL
53
	function __construct($url = '') {
54
		if($url != '') {
55
			$aIni = parse_url($url);
56
			$this->_scheme   = isset($aIni['scheme']) ? $aIni['scheme'] : 'mysql';
57
			$this->_hostname = isset($aIni['host']) ? $aIni['host'] : '';
58
			$this->_username = isset($aIni['user']) ? $aIni['user'] : '';
59
			$this->_password = isset($aIni['pass']) ? $aIni['pass'] : '';
60
			$this->_hostport = isset($aIni['port']) ? $aIni['port'] : '3306';
61
			$this->_hostport = $this->_hostport == '3306' ? '' : ':'.$this->_hostport;
62
			$this->_db_name  = ltrim(isset($aIni['path']) ? $aIni['path'] : '', '/\\');
63
		}else {
64
			$this->_hostname = DB_HOST;
65
			$this->_username = DB_USERNAME;
66
			$this->_password = DB_PASSWORD;
67
			$this->_hostport = '';
68
			$this->_db_name  = DB_NAME;
69
		}
70
		// Connect to database
71
		$this->connect();
72
	}
73
	
74
	// Connect to the database
75
	function connect() {
76
		$this->_db_handle = mysql_connect($this->_hostname.$this->_hostport,
77
		                                  $this->_username,
78
		                                  $this->_password);
79
		if(!$this->_db_handle) {
80
			throw new RuntimeException('unable to connect \''.$this->_scheme.'://'.
81
			                           $this->_hostname.$this->_hostport.'\'');
82
		} else {
83
			if(!mysql_select_db($this->_db_name)) {
84
				throw new RuntimeException('unable to select database \''.$this->_db_name.
85
				                           '\' on \''.$this->_scheme.'://'.
86
				                           $this->_hostname.$this->_hostport.'\'');
87
			} else {
88
				$this->connected = true;
89
			}
90
		}
91
		return $this->connected;
92
	}
93
	
94
	// Disconnect from the database
95
	function disconnect() {
96
		if($this->connected==true) {
97
			mysql_close($this->_db_handle);
98
			return true;
99
		} else {
100
			return false;
101
		}
102
	}
103
	
104
	// Run a query
105
	function query($statement) {
106
		$this->iQueryCount++;
107
		$mysql = new mysql();
108
		$mysql->query($statement, $this->_db_handle);
109
		$this->set_error($mysql->error($this->_db_handle));
110
		if($mysql->error($this->_db_handle)) {
111
			return null;
112
		} else {
113
			return $mysql;
114
		}
115
	}
116

  
117
	// Gets the first column of the first row
118
	function get_one( $statement )
119
	{
120
		$this->iQueryCount++;
121
		$fetch_row = mysql_fetch_array(mysql_query($statement, $this->_db_handle));
122
		$result = $fetch_row[0];
123
		$this->set_error(mysql_error($this->_db_handle));
124
		if(mysql_error($this->_db_handle)) {
125
			return null;
126
		} else {
127
			return $result;
128
		}
129
	}
130
	
131
	// Set the DB error
132
	function set_error($message = null) {
133
		global $TABLE_DOES_NOT_EXIST, $TABLE_UNKNOWN;
134
		$this->error = $message;
135
		if(strpos($message, 'no such table')) {
136
			$this->error_type = $TABLE_DOES_NOT_EXIST;
137
		} else {
138
			$this->error_type = $TABLE_UNKNOWN;
139
		}
140
	}
141
	
142
	// Return true if there was an error
143
	function is_error() {
144
		return (!empty($this->error)) ? true : false;
145
	}
146
	
147
	// Return the error
148
	function get_error() {
149
		return $this->error;
150
	}
151

  
152
/**
153
 * default Getter for some properties
154
 * @param string $sPropertyName
155
 * @return mixed NULL on error or missing property
156
 */
157
	public function __get($sPropertyName)
158
	{
159
		switch ($sPropertyName):
160
			case 'db_handle':
161
			case 'DbHandle':
162
			case 'getDbHandle':
163
				$retval = $this->_db_handle;
164
				break;
165
			case 'db_name':
166
			case 'DbName':
167
			case 'getDbName':
168
				$retval = $this->_db_name;
169
				break;
170
			case 'getQueryCount':
171
				$retval = $this->iQueryCount;
172
				break;
173
			default:
174
				$retval = null;
175
				break;
176
		endswitch;
177
		return $retval;
178
	} // __get()
179

  
180
/*
181
 * @param string $table_name: full name of the table (incl. TABLE_PREFIX)
182
 * @param string $field_name: name of the field to seek for
183
 * @return bool: true if field exists
184
 */
185
	public function field_exists($table_name, $field_name)
186
	{
187
		$sql = 'DESCRIBE `'.$table_name.'` `'.$field_name.'` ';
188
		$query = $this->query($sql, $this->_db_handle);
189
		return ($query->numRows() != 0);
190
	}
191

  
192
/*
193
 * @param string $table_name: full name of the table (incl. TABLE_PREFIX)
194
 * @param string $index_name: name of the index to seek for
195
 * @return bool: true if field exists
196
 */
197
	public function index_exists($table_name, $index_name, $number_fields = 0)
198
	{
199
		$number_fields = intval($number_fields);
200
		$keys = 0;
201
		$sql = 'SHOW INDEX FROM `'.$table_name.'`';
202
		if( ($res_keys = $this->query($sql, $this->_db_handle)) )
203
		{
204
			while(($rec_key = $res_keys->fetchRow()))
205
			{
206
				if( $rec_key['Key_name'] == $index_name )
207
				{
208
					$keys++;
209
				}
210
			}
211

  
212
		}
213
		if( $number_fields == 0 )
214
		{
215
			return ($keys != $number_fields);
216
		}else
217
		{
218
			return ($keys == $number_fields);
219
		}
220
	}
221
/*
222
 * @param string $table_name: full name of the table (incl. TABLE_PREFIX)
223
 * @param string $field_name: name of the field to add
224
 * @param string $description: describes the new field like ( INT NOT NULL DEFAULT '0')
225
 * @return bool: true if successful, otherwise false and error will be set
226
 */
227
	public function field_add($table_name, $field_name, $description)
228
	{
229
		if( !$this->field_exists($table_name, $field_name) )
230
		{ // add new field into a table
231
			$sql = 'ALTER TABLE `'.$table_name.'` ADD '.$field_name.' '.$description.' ';
232
			$query = $this->query($sql, $this->_db_handle);
233
			$this->set_error(mysql_error($this->_db_handle));
234
			if( !$this->is_error() )
235
			{
236
				return ( $this->field_exists($table_name, $field_name) ) ? true : false;
237
			}
238
		}else
239
		{
240
			$this->set_error('field \''.$field_name.'\' already exists');
241
		}
242
		return false;
243
	}
244

  
245
/*
246
 * @param string $table_name: full name of the table (incl. TABLE_PREFIX)
247
 * @param string $field_name: name of the field to add
248
 * @param string $description: describes the new field like ( INT NOT NULL DEFAULT '0')
249
 * @return bool: true if successful, otherwise false and error will be set
250
 */
251
	public function field_modify($table_name, $field_name, $description)
252
	{
253
		$retval = false;
254
		if( $this->field_exists($table_name, $field_name) )
255
		{ // modify a existing field in a table
256
			$sql  = 'ALTER TABLE `'.$table_name.'` MODIFY `'.$field_name.'` '.$description;
257
			$retval = ( $this->query($sql, $this->_db_handle) ? true : false);
258
			$this->set_error(mysql_error());
259
		}
260
		return $retval;
261
	}
262

  
263
/*
264
 * @param string $table_name: full name of the table (incl. TABLE_PREFIX)
265
 * @param string $field_name: name of the field to remove
266
 * @return bool: true if successful, otherwise false and error will be set
267
 */
268
	public function field_remove($table_name, $field_name)
269
	{
270
		$retval = false;
271
		if( $this->field_exists($table_name, $field_name) )
272
		{ // modify a existing field in a table
273
			$sql  = 'ALTER TABLE `'.$table_name.'` DROP `'.$field_name.'`';
274
			$retval = ( $this->query($sql, $this->_db_handle) ? true : false );
275
		}
276
		return $retval;
277
	}
278

  
279
/*
280
 * @param string $table_name: full name of the table (incl. TABLE_PREFIX)
281
 * @param string $index_name: name of the new index
282
 * @param string $field_list: comma seperated list of fields for this index
283
 * @param string $index_type: kind of index (UNIQUE, PRIMARY, '')
284
 * @return bool: true if successful, otherwise false and error will be set
285
 */
286
	public function index_add($table_name, $index_name, $field_list, $index_type = '')
287
	{
288
		$retval = false;
289
		$field_list = str_replace(' ', '', $field_list);
290
		$field_list = explode(',', $field_list);
291
		$number_fields = sizeof($field_list);
292
		$field_list = '`'.implode('`,`', $field_list).'`';
293
		if( $this->index_exists($table_name, $index_name, $number_fields) ||
294
		    $this->index_exists($table_name, $index_name))
295
		{
296
			$sql  = 'ALTER TABLE `'.$table_name.'` ';
297
			$sql .= 'DROP INDEX `'.$index_name.'`';
298
			if( $this->query($sql, $this->_db_handle))
299
			{
300
				$sql  = 'ALTER TABLE `'.$table_name.'` ';
301
				$sql .= 'ADD '.$index_type.' `'.$index_name.'` ( '.$field_list.' ); ';
302
				if( $this->query($sql, $this->_db_handle)) { $retval = true; }
303
			}
304
		}
305
		return $retval;
306
	}
307

  
308
/*
309
 * @param string $table_name: full name of the table (incl. TABLE_PREFIX)
310
 * @param string $field_name: name of the field to remove
311
 * @return bool: true if successful, otherwise false and error will be set
312
 */
313
	public function index_remove($table_name, $index_name)
314
	{
315
		$retval = false;
316
		if( $this->index_exists($table_name, $index_name) )
317
		{ // modify a existing field in a table
318
			$sql  = 'ALTER TABLE `'.$table_name.'` DROP INDEX `'.$index_name.'`';
319
			$retval = ( $this->query($sql, $this->_db_handle) ? true : false );
320
		}
321
		return $retval;
322
	}
323
/**
324
 * Import a standard *.sql dump file
325
 * @param string $sSqlDump link to the sql-dumpfile
326
 * @param string $sTablePrefix
327
 * @param bool $bPreserve set to true will ignore all DROP TABLE statements
328
 * @param string $sTblEngine
329
 * @param string $sTblCollation
330
 * @return boolean true if import successful
331
 */
332
	public function SqlImport($sSqlDump,
333
	                          $sTablePrefix = '',
334
	                          $bPreserve = true,
335
	                          $sTblEngine = 'ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci',
336
	                          $sTblCollation = ' collate utf8_unicode_ci')
337
	{
338
		$retval = true;
339
		$this->error = '';
340
		$aSearch  = array('{TABLE_PREFIX}','{TABLE_ENGINE}', '{TABLE_COLLATION}');
341
		$aReplace = array($sTablePrefix, $sTblEngine, $sTblCollation);
342
		$sql = '';
343
		$aSql = file($sSqlDump);
344
		while ( sizeof($aSql) > 0 ) {
345
			$sSqlLine = trim(array_shift($aSql));
346
			if (!preg_match('/^[-\/]+.*/', $sSqlLine)) {
347
				$sql = $sql.' '.$sSqlLine;
348
				if ((substr($sql,-1,1) == ';')) {
349
					$sql = trim(str_replace( $aSearch, $aReplace, $sql));
350
					if (!($bPreserve && preg_match('/^\s*DROP TABLE IF EXISTS/siU', $sql))) {
351
						if(!mysql_query($sql, $this->_db_handle)) {
352
							$retval = false;
353
							$this->error = mysql_error($this->_db_handle);
354
							unset($aSql);
355
							break;
356
						}
357
					}
358
					$sql = '';
359
				}
360
			}
361
		}
362
		return $retval;
363
	}
364

  
365
/**
366
 * retuns the type of the engine used for requested table
367
 * @param string $table name of the table, including prefix
368
 * @return boolean/string false on error, or name of the engine (myIsam/InnoDb)
369
 */
370
	public function getTableEngine($table)
371
	{
372
		$retVal = false;
373
		$mysqlVersion = mysql_get_server_info($this->_db_handle);
374
		$engineValue = (version_compare($mysqlVersion, '5.0') < 0) ? 'Type' : 'Engine';
375
		$sql = "SHOW TABLE STATUS FROM " . $this->_db_name . " LIKE '" . $table . "'";
376
		if(($result = $this->query($sql, $this->_db_handle))) {
377
			if(($row = $result->fetchRow(MYSQL_ASSOC))) {
378
				$retVal = $row[$engineValue];
379
			}
380
		}
381
		return $retVal;
382
	}
383

  
384

  
385
} /// end of class database
386

  
387
define('MYSQL_SEEK_FIRST', 0);
388
define('MYSQL_SEEK_LAST', -1);
389

  
390
class mysql {
391

  
392
	private $result = null;
393
	private $_db_handle = null;
394
	// Run a query
395
	function query($statement, $dbHandle) {
396
		$this->_db_handle = $dbHandle;
397
		$this->result = mysql_query($statement, $this->_db_handle);
398
		$this->error = mysql_error($this->_db_handle);
399
		return $this->result;
400
	}
401
	
402
	// Fetch num rows
403
	function numRows() {
404
		return mysql_num_rows($this->result);
405
	}
406

  
407
	// Fetch row  $typ = MYSQL_ASSOC, MYSQL_NUM, MYSQL_BOTH
408
	function fetchRow($typ = MYSQL_BOTH) {
409
		return mysql_fetch_array($this->result, $typ);
410
	}
411

  
412
	function rewind()
413
	{
414
		return $this->seekRow();
415
	}
416

  
417
	function seekRow( $position = MYSQL_SEEK_FIRST )
418
	{
419
		$pmax = $this->numRows() - 1;
420
		$p = (($position < 0 || $position > $pmax) ? $pmax : $position);
421
		return mysql_data_seek($this->result, $p);
422
	}
423

  
424
	// Get error
425
	function error() {
426
		if(isset($this->error)) {
427
			return $this->error;
428
		} else {
429
			return null;
430
		}
431
	}
432

  
433
}
434
/* this function is placed inside this file temporarely until a better place is found */
435
/*  function to update a var/value-pair(s) in table ****************************
436
 *  nonexisting keys are inserted
437
 *  @param string $table: name of table to use (without prefix)
438
 *  @param mixed $key:    a array of key->value pairs to update
439
 *                        or a string with name of the key to update
440
 *  @param string $value: a sting with needed value, if $key is a string too
441
 *  @return bool:  true if any keys are updated, otherwise false
442
 */
443
	function db_update_key_value($table, $key, $value = '')
444
	{
445
		global $database;
446
		if( !is_array($key))
447
		{
448
			if( trim($key) != '' )
449
			{
450
				$key = array( trim($key) => trim($value) );
451
			} else {
452
				$key = array();
453
			}
454
		}
455
		$retval = true;
456
		foreach( $key as $index=>$val)
457
		{
458
			$index = strtolower($index);
459
			$sql = 'SELECT COUNT(`setting_id`) '
460
			     . 'FROM `'.TABLE_PREFIX.$table.'` '
461
			     . 'WHERE `name` = \''.$index.'\' ';
462
			if($database->get_one($sql))
463
			{
464
				$sql = 'UPDATE ';
465
				$sql_where = 'WHERE `name` = \''.$index.'\'';
466
			}else {
467
				$sql = 'INSERT INTO ';
468
				$sql_where = '';
469
			}
470
			$sql .= '`'.TABLE_PREFIX.$table.'` ';
471
			$sql .= 'SET `name` = \''.$index.'\', ';
472
			$sql .= '`value` = \''.$val.'\' '.$sql_where;
473
			if( !$database->query($sql) )
474
			{
475
				$retval = false;
476
			}
477
		}
478
		return $retval;
479
	}
0 480

  
branches/2.8.x/wb/framework/class.wb.php
23 23
/* -------------------------------------------------------- */
24 24
// Include PHPLIB template class
25 25
require_once(WB_PATH."/include/phplib/template.inc");
26

  
27
require_once(WB_PATH.'/framework/class.database.php');
28

  
29 26
// Include new wbmailer class (subclass of PHPmailer)
30 27
require_once(WB_PATH."/framework/class.wbmailer.php");
31

  
32 28
//require_once(WB_PATH."/framework/SecureForm.php");
33 29

  
34 30
class wb extends SecureForm
branches/2.8.x/wb/framework/globalExceptionHandler.php
51 51
		}
52 52
	} // end of class
53 53

  
54
/* -- several security exceptions ----------------------------------------------------- */
55
	class SecurityException extends RuntimeException { 	}
56

  
57
	class SecDirectoryTraversalException extends SecurityException {
58
		public function __toString() {
59
			return 'possible directory traversal attack';
60
		}
61
	}
62
/* ------------------------------------------------------------------------------------ */
54 63
/**
55 64
 *
56 65
 * @param Exception $e
......
59 68
		// hide server internals from filename where the exception was thrown
60 69
		$file = str_replace(dirname(dirname(__FILE__)), '', $e->getFile());
61 70
		// select some exceptions for special handling
62
		if ($e instanceof IllegalFileException) {
71
		if ($e instanceof SecurityException) {
72
			$out = 'Exception: "'.(string)$e.'" @ ';
73
		    $trace = $e->getTrace();
74
			if($trace[0]['class'] != '') {
75
				$out .= $trace[0]['class'].'->';
76
			}
77
			$out .= $trace[0]['function'].'();<br />';
78
			$out .= 'in "'.$file.'"'."\n";
79
			echo $out;
80
		}elseif ($e instanceof IllegalFileException) {
63 81
			$sResponse  = $_SERVER['SERVER_PROTOCOL'].' 403 Forbidden';
64 82
			header($sResponse);
65 83
			echo $e;
66 84
		}elseif($e instanceof RuntimeException) {
67
			$out  ='There was a serious runtime error:'."\n";
85
			$out  = 'There was a serious runtime error:'."\n";
68 86
			$out .= $e->getMessage()."\n";
69 87
			$out .= 'in line ('.$e->getLine().') of ('.$file.')'."\n";
70 88
			echo $out;
branches/2.8.x/wb/framework/ModLanguage.php
1
<?php
2
/**
3
 * @category     Core
4
 * @package      Core_security
5
 * @author       Werner v.d.Decken
6
 * @copyright    ISTeasy-project(http://isteasy.de/)
7
 * @license      Creative Commons BY-SA 3.0 http://creativecommons.org/licenses/by-sa/3.0/
8
 * @version      $Id$
9
 * @filesource   $HeadURL$
10
 * @since        Datei vorhanden seit Release 2.8.2
11
 * @lastmodified $Date$
12
 */
13
class ModLanguage {
14

  
15
	private $_sCurrentLanguage   = '';
16
	private $_sDefaultLanguage   = '';
17
	private $_sLanguageDirectory = '';
18
	private $_sLanguageFile      = '';
19
	private $_LanguageTable      = array();
20
	private $_bLoaded            = false;
21

  
22
	private static $_oInstance   = null;
23
/* prevent from public instancing */
24
	protected function  __construct() { }
25
/* prevent from cloning */
26
	private function __clone() {}
27
/**
28
 * get a valid instance of this class
29
 * @return object
30
 */
31
	public function getInstance() {
32
		if( is_null(self::$_oInstance) ) {
33
            $c = __CLASS__;
34
            self::$_oInstance = new $c;
35
		}
36
		return self::$_oInstance;
37
	}
38
/**
39
 * set language and load needed language file
40
 * @param string $sDirectory full path to the language files
41
 * @param string $sLanguage 2-letters language code
42
 * @param string $sDefault 2-letters default-language code
43
 */
44
	public function setLanguage($sDirectory, $sLanguage, $sDefault = 'EN')
45
	{
46
		$sBasePath = realpath(dirname(dirname(__FILE__)));
47
		$sLangDir = realpath($sDirectory);
48
		if(!preg_match('/^'.preg_quote($sBasePath, '/').'/', $sLangDir)) {
49
			throw new SecDirectoryTraversalException();
50
		}
51
		$sLangDir = str_replace('\\', '/', $sLangDir);
52
		$sLangDir = rtrim($sLangDir, '/').'/';
53
		$sLanguage = strtoupper($sLanguage);
54
		$sLanguage = strtoupper($sDefault);
55
		if($this->_sLanguageDirectory != $sLangDir ||
56
		   $this->_sCurrentLanguage != $sLanguage ||
57
		   $this->_sDefaultLanguage != $sDefault)
58
		{
59
			$this->_sLanguageDirectory = rtrim($sLangDir, '/').'/';
60
			$this->_sCurrentLanguage = $sLanguage;
61
			$this->_sDefaultLanguage = $sDefault;
62

  
63
			if(!$this->_findLanguageFile()) {
64
				$msg  = 'unable to find valid language definition file in<br />';
65
				$msg .= '"'.str_replace($sBasePath, '', $this->_sLanguageDirectory).'"';
66
				throw new TranslationException($msg);
67
			}
68
			$this->_importArrays();
69
		}
70
		$this->_bLoaded = (sizeof($this->_LanguageTable) > 0);
71
	}
72
/**
73
 * return requested translation for a key
74
 * @param string $sLanguageKey 2-uppercase letters language code
75
 * @return string found translation or empty string 
76
 */
77
	public function __get($sLanguageKey)
78
	{
79
		$sRetval = (isset($this->_LanguageTable[$sLanguageKey])
80
		            ? $this->_LanguageTable[$sLanguageKey] : '{missing: '.$sLanguageKey.'}');
81
		return $sRetval;
82
	}
83
/**
84
 * returns the whoole language array for use in templateengine
85
 * @return array
86
 */
87
	public function getLangArray()
88
	{
89
		return $this->_LanguageTable;
90
	}
91
/**
92
 * search language file in order: LANGUAGE - DEFAULT_LANGUAGE - FIRST_FOUND
93
 * @return boolean
94
 */
95
	private function _findLanguageFile()
96
	{
97
		$bMatch = false;
98
		$dir = $this->_sLanguageDirectory;
99
		if(is_readable($dir.$this->_sCurrentLanguage.'.php')) {
100
		// check actual language
101
			$this->_sLanguageFile = $dir.$this->_sCurrentLanguage.'.php';
102
			$bMatch = true;
103
		}else {
104
			if(is_readable($dir.$this->_sDefaultLanguage.'.php')) {
105
			// check default language
106
				$this->_sLanguageFile = $dir.$this->_sDefaultLanguage.'.php';
107
				$bMatch = true;
108
			}else {
109
			// search for first available and readable language file
110
				if(is_readable($dir)) {
111
					$iterator = new DirectoryIterator($dir);
112
					foreach ($iterator as $fileinfo) {
113
						if(!preg_match('/^[A-Z]{2}\.php$/', $fileinfo->getBasename())) { continue; }
114
						$sLanguageFile = str_replace('\\', '/', $fileinfo->getPathname());
115
						if(is_readable($sLanguageFile)) {
116
							$this->_sLanguageFile = $sLanguageFile;
117
							$bMatch = true;
118
							break;
119
						}
120
					}
121
				}
122
			}
123
		}
124
		return $bMatch;
125
	}
126
/**
127
 * import key-values from language file
128
 */
129
	private function _importArrays()
130
	{
131
		include($this->_sLanguageFile);
132
		$aLangSections = array('HEADING', 'TEXT', 'MESSAGE', 'MENU', 'OVERVIEW', 'GENERIC');
133
		foreach($aLangSections as $sSection) {
134
			if(isset(${$sSection}) && is_array(${$sSection})) {
135
				foreach(${$sSection} as $key => $value) {
136
					$this->_LanguageTable[$sSection.'_'.$key] = $value;
137
				}
138
			}
139
		}
140
	}
141
} // end class Translate
142
/**
143
 *  Exception class for Translation
144
 */
145
class TranslationException extends AppException {}
146

  
0 147

  

Also available in: Unified diff