Project

General

Profile

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: WbDatabase.php 1686 2012-05-07 12:31:03Z darkviper $
14
 * @filesource      $HeadURL: svn://isteam.dynxs.de/wb-archiv/branches/2.8.x/wb/framework/WbDatabase.php $
15
 * @lastmodified    $Date: 2012-05-07 14:31:03 +0200 (Mon, 07 May 2012) $
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

    
33
class WbDatabase {
34
	
35
	private static $_oInstances = array();
36

    
37
	private $_db_handle = null; // readonly from outside
38
	private $_scheme    = 'mysql';
39
	private $_hostname  = 'localhost';
40
	private $_username  = '';
41
	private $_password  = '';
42
	private $_hostport  = '3306';
43
	private $_db_name   = '';
44
	private $connected  = false;
45
	private $error      = '';
46
	private $error_type = '';
47
	private $iQueryCount= 0;
48

    
49
/* prevent from public instancing */
50
	protected function  __construct() {}
51
/* prevent from cloning */
52
	private function __clone() {}
53
/**
54
 * get a valid instance of this class
55
 * @param string $sIdentifier selector for several different instances
56
 * @return object
57
 */
58
	public static function getInstance($sIdentifier = 'core') {
59
		if( !isset(self::$_oInstances[$sIdentifier])) {
60
            $c = __CLASS__;
61
            self::$_oInstances[$sIdentifier] = new $c;
62
		}
63
		return self::$_oInstances[$sIdentifier];
64
	}
65
/**
66
 * disconnect and kills an existing instance
67
 * @param string $sIdentifier
68
 */
69
	public static function killInstance($sIdentifier) {
70
		if($sIdentifier != 'core') {
71
			if( isset(self::$_oInstances[$sIdentifier])) {
72
				self::$_oInstances[$sIdentifier]->disconnect();
73
				unset(self::$_oInstances[$sIdentifier]);
74
			}
75
		}
76
	}
77
/**
78
 * Connect to the database
79
 * @param string $url
80
 * @return bool
81
 *
82
 * Example for SQL-Url:  'mysql://user:password@demo.de[:3306]/datenbank'
83
 */
84
	public function doConnect($url = '') {
85
		if($url != '') {
86
			$aIni = parse_url($url);
87
			$this->_scheme   = isset($aIni['scheme']) ? $aIni['scheme'] : 'mysql';
88
			$this->_hostname = isset($aIni['host']) ? $aIni['host'] : '';
89
			$this->_username = isset($aIni['user']) ? $aIni['user'] : '';
90
			$this->_password = isset($aIni['pass']) ? $aIni['pass'] : '';
91
			$this->_hostport = isset($aIni['port']) ? $aIni['port'] : '3306';
92
			$this->_hostport = $this->_hostport == '3306' ? '' : ':'.$this->_hostport;
93
			$this->_db_name  = ltrim(isset($aIni['path']) ? $aIni['path'] : '', '/\\');
94
		}else {
95
			throw new RuntimeException('Missing parameter: unable to connect database');
96
		}
97
		$this->_db_handle = mysql_connect($this->_hostname.$this->_hostport,
98
		                                  $this->_username,
99
		                                  $this->_password);
100
		if(!$this->_db_handle) {
101
			throw new RuntimeException('unable to connect \''.$this->_scheme.'://'.
102
			                           $this->_hostname.$this->_hostport.'\'');
103
		} else {
104
			if(!mysql_select_db($this->_db_name)) {
105
				throw new RuntimeException('unable to select database \''.$this->_db_name.
106
				                           '\' on \''.$this->_scheme.'://'.
107
				                           $this->_hostname.$this->_hostport.'\'');
108
			} else {
109
				$this->connected = true;
110
			}
111
		}
112
		return $this->connected;
113
	}
114
	
115
	// Disconnect from the database
116
	public function disconnect() {
117
		if($this->connected==true) {
118
			mysql_close($this->_db_handle);
119
			return true;
120
		} else {
121
			return false;
122
		}
123
	}
124
	
125
	// Run a query
126
	public function query($statement) {
127
		$this->iQueryCount++;
128
		$mysql = new mysql();
129
		$mysql->query($statement, $this->_db_handle);
130
		$this->set_error($mysql->error($this->_db_handle));
131
		if($mysql->error($this->_db_handle)) {
132
			return null;
133
		} else {
134
			return $mysql;
135
		}
136
	}
137

    
138
	// Gets the first column of the first row
139
	public function get_one( $statement )
140
	{
141
		$this->iQueryCount++;
142
		$fetch_row = mysql_fetch_array(mysql_query($statement, $this->_db_handle));
143
		$result = $fetch_row[0];
144
		$this->set_error(mysql_error($this->_db_handle));
145
		if(mysql_error($this->_db_handle)) {
146
			return null;
147
		} else {
148
			return $result;
149
		}
150
	}
151
	
152
	// Set the DB error
153
	public function set_error($message = null) {
154
		global $TABLE_DOES_NOT_EXIST, $TABLE_UNKNOWN;
155
		$this->error = $message;
156
		if(strpos($message, 'no such table')) {
157
			$this->error_type = $TABLE_DOES_NOT_EXIST;
158
		} else {
159
			$this->error_type = $TABLE_UNKNOWN;
160
		}
161
	}
162
	
163
	// Return true if there was an error
164
	public function is_error() {
165
		return (!empty($this->error)) ? true : false;
166
	}
167
	
168
	// Return the error
169
	public function get_error() {
170
		return $this->error;
171
	}
172

    
173
/**
174
 * default Getter for some properties
175
 * @param string $sPropertyName
176
 * @return mixed NULL on error or missing property
177
 */
178
	public function __get($sPropertyName)
179
	{
180
		switch ($sPropertyName):
181
			case 'db_handle':
182
			case 'DbHandle':
183
			case 'getDbHandle':
184
				$retval = $this->_db_handle;
185
				break;
186
			case 'db_name':
187
			case 'DbName':
188
			case 'getDbName':
189
				$retval = $this->_db_name;
190
				break;
191
			case 'getQueryCount':
192
				$retval = $this->iQueryCount;
193
				break;
194
			default:
195
				$retval = null;
196
				break;
197
		endswitch;
198
		return $retval;
199
	} // __get()
200

    
201
/*
202
 * @param string $table_name: full name of the table (incl. TABLE_PREFIX)
203
 * @param string $field_name: name of the field to seek for
204
 * @return bool: true if field exists
205
 */
206
	public function field_exists($table_name, $field_name)
207
	{
208
		$sql = 'DESCRIBE `'.$table_name.'` `'.$field_name.'` ';
209
		$query = $this->query($sql, $this->_db_handle);
210
		return ($query->numRows() != 0);
211
	}
212

    
213
/*
214
 * @param string $table_name: full name of the table (incl. TABLE_PREFIX)
215
 * @param string $index_name: name of the index to seek for
216
 * @return bool: true if field exists
217
 */
218
	public function index_exists($table_name, $index_name, $number_fields = 0)
219
	{
220
		$number_fields = intval($number_fields);
221
		$keys = 0;
222
		$sql = 'SHOW INDEX FROM `'.$table_name.'`';
223
		if( ($res_keys = $this->query($sql, $this->_db_handle)) )
224
		{
225
			while(($rec_key = $res_keys->fetchRow()))
226
			{
227
				if( $rec_key['Key_name'] == $index_name )
228
				{
229
					$keys++;
230
				}
231
			}
232

    
233
		}
234
		if( $number_fields == 0 )
235
		{
236
			return ($keys != $number_fields);
237
		}else
238
		{
239
			return ($keys == $number_fields);
240
		}
241
	}
242
/*
243
 * @param string $table_name: full name of the table (incl. TABLE_PREFIX)
244
 * @param string $field_name: name of the field to add
245
 * @param string $description: describes the new field like ( INT NOT NULL DEFAULT '0')
246
 * @return bool: true if successful, otherwise false and error will be set
247
 */
248
	public function field_add($table_name, $field_name, $description)
249
	{
250
		if( !$this->field_exists($table_name, $field_name) )
251
		{ // add new field into a table
252
			$sql = 'ALTER TABLE `'.$table_name.'` ADD '.$field_name.' '.$description.' ';
253
			$query = $this->query($sql, $this->_db_handle);
254
			$this->set_error(mysql_error($this->_db_handle));
255
			if( !$this->is_error() )
256
			{
257
				return ( $this->field_exists($table_name, $field_name) ) ? true : false;
258
			}
259
		}else
260
		{
261
			$this->set_error('field \''.$field_name.'\' already exists');
262
		}
263
		return false;
264
	}
265

    
266
/*
267
 * @param string $table_name: full name of the table (incl. TABLE_PREFIX)
268
 * @param string $field_name: name of the field to add
269
 * @param string $description: describes the new field like ( INT NOT NULL DEFAULT '0')
270
 * @return bool: true if successful, otherwise false and error will be set
271
 */
272
	public function field_modify($table_name, $field_name, $description)
273
	{
274
		$retval = false;
275
		if( $this->field_exists($table_name, $field_name) )
276
		{ // modify a existing field in a table
277
			$sql  = 'ALTER TABLE `'.$table_name.'` MODIFY `'.$field_name.'` '.$description;
278
			$retval = ( $this->query($sql, $this->_db_handle) ? true : false);
279
			$this->set_error(mysql_error());
280
		}
281
		return $retval;
282
	}
283

    
284
/*
285
 * @param string $table_name: full name of the table (incl. TABLE_PREFIX)
286
 * @param string $field_name: name of the field to remove
287
 * @return bool: true if successful, otherwise false and error will be set
288
 */
289
	public function field_remove($table_name, $field_name)
290
	{
291
		$retval = false;
292
		if( $this->field_exists($table_name, $field_name) )
293
		{ // modify a existing field in a table
294
			$sql  = 'ALTER TABLE `'.$table_name.'` DROP `'.$field_name.'`';
295
			$retval = ( $this->query($sql, $this->_db_handle) ? true : false );
296
		}
297
		return $retval;
298
	}
299

    
300
/*
301
 * @param string $table_name: full name of the table (incl. TABLE_PREFIX)
302
 * @param string $index_name: name of the new index
303
 * @param string $field_list: comma seperated list of fields for this index
304
 * @param string $index_type: kind of index (UNIQUE, PRIMARY, '')
305
 * @return bool: true if successful, otherwise false and error will be set
306
 */
307
	public function index_add($table_name, $index_name, $field_list, $index_type = '')
308
	{
309
		$retval = false;
310
		$field_list = str_replace(' ', '', $field_list);
311
		$field_list = explode(',', $field_list);
312
		$number_fields = sizeof($field_list);
313
		$field_list = '`'.implode('`,`', $field_list).'`';
314
		if( $this->index_exists($table_name, $index_name, $number_fields) ||
315
		    $this->index_exists($table_name, $index_name))
316
		{
317
			$sql  = 'ALTER TABLE `'.$table_name.'` ';
318
			$sql .= 'DROP INDEX `'.$index_name.'`';
319
			if( $this->query($sql, $this->_db_handle))
320
			{
321
				$sql  = 'ALTER TABLE `'.$table_name.'` ';
322
				$sql .= 'ADD '.$index_type.' `'.$index_name.'` ( '.$field_list.' ); ';
323
				if( $this->query($sql, $this->_db_handle)) { $retval = true; }
324
			}
325
		}
326
		return $retval;
327
	}
328

    
329
/*
330
 * @param string $table_name: full name of the table (incl. TABLE_PREFIX)
331
 * @param string $field_name: name of the field to remove
332
 * @return bool: true if successful, otherwise false and error will be set
333
 */
334
	public function index_remove($table_name, $index_name)
335
	{
336
		$retval = false;
337
		if( $this->index_exists($table_name, $index_name) )
338
		{ // modify a existing field in a table
339
			$sql  = 'ALTER TABLE `'.$table_name.'` DROP INDEX `'.$index_name.'`';
340
			$retval = ( $this->query($sql, $this->_db_handle) ? true : false );
341
		}
342
		return $retval;
343
	}
344
/**
345
 * Import a standard *.sql dump file
346
 * @param string $sSqlDump link to the sql-dumpfile
347
 * @param string $sTablePrefix
348
 * @param bool $bPreserve set to true will ignore all DROP TABLE statements
349
 * @param string $sTblEngine
350
 * @param string $sTblCollation
351
 * @return boolean true if import successful
352
 */
353
	public function SqlImport($sSqlDump,
354
	                          $sTablePrefix = '',
355
	                          $bPreserve = true,
356
	                          $sTblEngine = 'ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci',
357
	                          $sTblCollation = ' collate utf8_unicode_ci')
358
	{
359
		$retval = true;
360
		$this->error = '';
361
		$aSearch  = array('{TABLE_PREFIX}','{TABLE_ENGINE}', '{TABLE_COLLATION}');
362
		$aReplace = array($sTablePrefix, $sTblEngine, $sTblCollation);
363
		$sql = '';
364
		$aSql = file($sSqlDump);
365
		while ( sizeof($aSql) > 0 ) {
366
			$sSqlLine = trim(array_shift($aSql));
367
			if (!preg_match('/^[-\/]+.*/', $sSqlLine)) {
368
				$sql = $sql.' '.$sSqlLine;
369
				if ((substr($sql,-1,1) == ';')) {
370
					$sql = trim(str_replace( $aSearch, $aReplace, $sql));
371
					if (!($bPreserve && preg_match('/^\s*DROP TABLE IF EXISTS/siU', $sql))) {
372
						if(!mysql_query($sql, $this->_db_handle)) {
373
							$retval = false;
374
							$this->error = mysql_error($this->_db_handle);
375
							unset($aSql);
376
							break;
377
						}
378
					}
379
					$sql = '';
380
				}
381
			}
382
		}
383
		return $retval;
384
	}
385

    
386
/**
387
 * retuns the type of the engine used for requested table
388
 * @param string $table name of the table, including prefix
389
 * @return boolean/string false on error, or name of the engine (myIsam/InnoDb)
390
 */
391
	public function getTableEngine($table)
392
	{
393
		$retVal = false;
394
		$mysqlVersion = mysql_get_server_info($this->_db_handle);
395
		$engineValue = (version_compare($mysqlVersion, '5.0') < 0) ? 'Type' : 'Engine';
396
		$sql = "SHOW TABLE STATUS FROM " . $this->_db_name . " LIKE '" . $table . "'";
397
		if(($result = $this->query($sql, $this->_db_handle))) {
398
			if(($row = $result->fetchRow(MYSQL_ASSOC))) {
399
				$retVal = $row[$engineValue];
400
			}
401
		}
402
		return $retVal;
403
	}
404

    
405

    
406
} /// end of class database
407

    
408
define('MYSQL_SEEK_FIRST', 0);
409
define('MYSQL_SEEK_LAST', -1);
410

    
411
class mysql {
412

    
413
	private $result = null;
414
	private $_db_handle = null;
415
	// Run a query
416
	function query($statement, $dbHandle) {
417
		$this->_db_handle = $dbHandle;
418
		$this->result = mysql_query($statement, $this->_db_handle);
419
		$this->error = mysql_error($this->_db_handle);
420
		return $this->result;
421
	}
422
	
423
	// Fetch num rows
424
	function numRows() {
425
		return mysql_num_rows($this->result);
426
	}
427

    
428
	// Fetch row  $typ = MYSQL_ASSOC, MYSQL_NUM, MYSQL_BOTH
429
	function fetchRow($typ = MYSQL_BOTH) {
430
		return mysql_fetch_array($this->result, $typ);
431
	}
432

    
433
	function rewind()
434
	{
435
		return $this->seekRow();
436
	}
437

    
438
	function seekRow( $position = MYSQL_SEEK_FIRST )
439
	{
440
		$pmax = $this->numRows() - 1;
441
		$p = (($position < 0 || $position > $pmax) ? $pmax : $position);
442
		return mysql_data_seek($this->result, $p);
443
	}
444

    
445
	// Get error
446
	function error() {
447
		if(isset($this->error)) {
448
			return $this->error;
449
		} else {
450
			return null;
451
		}
452
	}
453

    
454
}
455
/* this function is placed inside this file temporarely until a better place is found */
456
/*  function to update a var/value-pair(s) in table ****************************
457
 *  nonexisting keys are inserted
458
 *  @param string $table: name of table to use (without prefix)
459
 *  @param mixed $key:    a array of key->value pairs to update
460
 *                        or a string with name of the key to update
461
 *  @param string $value: a sting with needed value, if $key is a string too
462
 *  @return bool:  true if any keys are updated, otherwise false
463
 */
464
	function db_update_key_value($table, $key, $value = '')
465
	{
466
		global $database;
467
		if( !is_array($key))
468
		{
469
			if( trim($key) != '' )
470
			{
471
				$key = array( trim($key) => trim($value) );
472
			} else {
473
				$key = array();
474
			}
475
		}
476
		$retval = true;
477
		foreach( $key as $index=>$val)
478
		{
479
			$index = strtolower($index);
480
			$sql = 'SELECT COUNT(`setting_id`) '
481
			     . 'FROM `'.TABLE_PREFIX.$table.'` '
482
			     . 'WHERE `name` = \''.$index.'\' ';
483
			if($database->get_one($sql))
484
			{
485
				$sql = 'UPDATE ';
486
				$sql_where = 'WHERE `name` = \''.$index.'\'';
487
			}else {
488
				$sql = 'INSERT INTO ';
489
				$sql_where = '';
490
			}
491
			$sql .= '`'.TABLE_PREFIX.$table.'` ';
492
			$sql .= 'SET `name` = \''.$index.'\', ';
493
			$sql .= '`value` = \''.$val.'\' '.$sql_where;
494
			if( !$database->query($sql) )
495
			{
496
				$retval = false;
497
			}
498
		}
499
		return $retval;
500
	}
(7-7/25)