Project

General

Profile

1 4 ryan
<?php
2 1362 Luisehahne
/**
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 1374 Luisehahne
 * @requirements    PHP 5.2.2 and higher
13 1362 Luisehahne
 * @version         $Id$
14 1457 Luisehahne
 * @filesource      $HeadURL$
15
 * @lastmodified    $Date$
16 1362 Luisehahne
 *
17
 */
18 4 ryan
/*
19
Database class
20
This class will be used to interface between the database
21
and the Website Baker code
22
*/
23 1496 DarkViper
/* -------------------------------------------------------- */
24
// Must include code to stop this file being accessed directly
25 1499 DarkViper
if(!defined('WB_PATH')) {
26
	require_once(dirname(__FILE__).'/globalExceptionHandler.php');
27
	throw new IllegalFileException();
28
}
29 1496 DarkViper
/* -------------------------------------------------------- */
30 4 ryan
define('DATABASE_CLASS_LOADED', true);
31
32 1362 Luisehahne
33 1683 darkviper
class Database extends DatabaseX {
34
35
	private static $_oInstance = array();
36
/* prevent from public instancing */
37
	protected function  __construct() {}
38
/* prevent from cloning */
39
	private function __clone() {}
40
/**
41
 * get a valid instance of this class
42
 * @param string $sIdentifier selector for several different instances
43
 * @return object
44
 */
45
	public static function getInstance($sIdentifier = 'core') {
46
		if( !isset(self::$_oInstance[$sIdentifier])) {
47
            $c = __CLASS__;
48
            self::$_oInstance[$sIdentifier] = new $c;
49
		}
50
		return self::$_oInstance[$sIdentifier];
51
	}
52
}
53 1680 darkviper
54 1683 darkviper
55
class DatabaseX {
56
57 1680 darkviper
	private $_db_handle = null; // readonly from outside
58
	private $_scheme    = 'mysql';
59
	private $_hostname  = 'localhost';
60
	private $_username  = '';
61
	private $_password  = '';
62 1682 darkviper
	private $_hostport  = '3306';
63 1680 darkviper
	private $_db_name   = '';
64
65 1362 Luisehahne
	private $connected  = false;
66
67
	private $error      = '';
68
	private $error_type = '';
69
	private $message    = array();
70 1662 darkviper
	private $iQueryCount= 0;
71 1362 Luisehahne
72 1683 darkviper
/* prevent from public instancing */
73
	protected function __construct() {}
74
/* prevent from cloning */
75
	private function __clone() {}
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 1680 darkviper
		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 1682 darkviper
			throw new RuntimeException('Missing parameter: unable to connect database');
96 1680 darkviper
		}
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 4 ryan
		} else {
104 1680 darkviper
			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 4 ryan
			} else {
109
				$this->connected = true;
110
			}
111
		}
112
		return $this->connected;
113
	}
114
115
	// Disconnect from the database
116
	function disconnect() {
117 95 stefan
		if($this->connected==true) {
118 1680 darkviper
			mysql_close($this->_db_handle);
119 4 ryan
			return true;
120
		} else {
121
			return false;
122
		}
123
	}
124
125
	// Run a query
126
	function query($statement) {
127 1662 darkviper
		$this->iQueryCount++;
128 4 ryan
		$mysql = new mysql();
129 1680 darkviper
		$mysql->query($statement, $this->_db_handle);
130
		$this->set_error($mysql->error($this->_db_handle));
131
		if($mysql->error($this->_db_handle)) {
132 4 ryan
			return null;
133
		} else {
134
			return $mysql;
135
		}
136
	}
137 1362 Luisehahne
138 4 ryan
	// Gets the first column of the first row
139 1362 Luisehahne
	function get_one( $statement )
140
	{
141 1662 darkviper
		$this->iQueryCount++;
142 1680 darkviper
		$fetch_row = mysql_fetch_array(mysql_query($statement, $this->_db_handle));
143 4 ryan
		$result = $fetch_row[0];
144 1680 darkviper
		$this->set_error(mysql_error($this->_db_handle));
145
		if(mysql_error($this->_db_handle)) {
146 4 ryan
			return null;
147
		} else {
148
			return $result;
149
		}
150
	}
151
152
	// Set the DB error
153
	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
	function is_error() {
165
		return (!empty($this->error)) ? true : false;
166
	}
167
168
	// Return the error
169
	function get_error() {
170
		return $this->error;
171
	}
172
173 1613 darkviper
/**
174
 * default Getter for some properties
175
 * @param string $sPropertyName
176
 * @return mixed NULL on error or missing property
177 1362 Luisehahne
 */
178 1613 darkviper
	public function __get($sPropertyName)
179 1362 Luisehahne
	{
180 1613 darkviper
		switch ($sPropertyName):
181
			case 'db_handle':
182
			case 'DbHandle':
183 1662 darkviper
			case 'getDbHandle':
184 1680 darkviper
				$retval = $this->_db_handle;
185 1613 darkviper
				break;
186
			case 'db_name':
187
			case 'DbName':
188 1662 darkviper
			case 'getDbName':
189 1680 darkviper
				$retval = $this->_db_name;
190 1613 darkviper
				break;
191 1662 darkviper
			case 'getQueryCount':
192
				$retval = $this->iQueryCount;
193
				break;
194 1613 darkviper
			default:
195
				$retval = null;
196
				break;
197
		endswitch;
198
		return $retval;
199
	} // __get()
200 1362 Luisehahne
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 1680 darkviper
		$query = $this->query($sql, $this->_db_handle);
210 1362 Luisehahne
		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 1680 darkviper
		if( ($res_keys = $this->query($sql, $this->_db_handle)) )
224 1362 Luisehahne
		{
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 1442 Luisehahne
		if( !$this->field_exists($table_name, $field_name) )
251 1362 Luisehahne
		{ // add new field into a table
252
			$sql = 'ALTER TABLE `'.$table_name.'` ADD '.$field_name.' '.$description.' ';
253 1680 darkviper
			$query = $this->query($sql, $this->_db_handle);
254
			$this->set_error(mysql_error($this->_db_handle));
255 1362 Luisehahne
			if( !$this->is_error() )
256
			{
257 1442 Luisehahne
				return ( $this->field_exists($table_name, $field_name) ) ? true : false;
258 1362 Luisehahne
			}
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 1486 DarkViper
		if( $this->field_exists($table_name, $field_name) )
276 1362 Luisehahne
		{ // modify a existing field in a table
277 1486 DarkViper
			$sql  = 'ALTER TABLE `'.$table_name.'` MODIFY `'.$field_name.'` '.$description;
278 1680 darkviper
			$retval = ( $this->query($sql, $this->_db_handle) ? true : false);
279 1486 DarkViper
			$this->set_error(mysql_error());
280 1362 Luisehahne
		}
281 1486 DarkViper
		return $retval;
282 1362 Luisehahne
	}
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 1507 Luisehahne
		if( $this->field_exists($table_name, $field_name) )
293 1362 Luisehahne
		{ // modify a existing field in a table
294
			$sql  = 'ALTER TABLE `'.$table_name.'` DROP `'.$field_name.'`';
295 1680 darkviper
			$retval = ( $this->query($sql, $this->_db_handle) ? true : false );
296 1362 Luisehahne
		}
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 1680 darkviper
			if( $this->query($sql, $this->_db_handle))
320 1362 Luisehahne
			{
321
				$sql  = 'ALTER TABLE `'.$table_name.'` ';
322
				$sql .= 'ADD '.$index_type.' `'.$index_name.'` ( '.$field_list.' ); ';
323 1680 darkviper
				if( $this->query($sql, $this->_db_handle)) { $retval = true; }
324 1362 Luisehahne
			}
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 1680 darkviper
			$retval = ( $this->query($sql, $this->_db_handle) ? true : false );
341 1362 Luisehahne
		}
342
		return $retval;
343
	}
344 1586 darkviper
/**
345
 * Import a standard *.sql dump file
346
 * @param string $sSqlDump link to the sql-dumpfile
347
 * @param string $sTablePrefix
348 1591 darkviper
 * @param bool $bPreserve set to true will ignore all DROP TABLE statements
349 1586 darkviper
 * @param string $sTblEngine
350
 * @param string $sTblCollation
351
 * @return boolean true if import successful
352
 */
353
	public function SqlImport($sSqlDump,
354
	                          $sTablePrefix = '',
355 1591 darkviper
	                          $bPreserve = true,
356 1586 darkviper
	                          $sTblEngine = 'ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci',
357 1591 darkviper
	                          $sTblCollation = ' collate utf8_unicode_ci')
358 1586 darkviper
	{
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 1591 darkviper
			if (!preg_match('/^[-\/]+.*/', $sSqlLine)) {
368 1592 darkviper
				$sql = $sql.' '.$sSqlLine;
369 1586 darkviper
				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 1680 darkviper
						if(!mysql_query($sql, $this->_db_handle)) {
373 1586 darkviper
							$retval = false;
374 1680 darkviper
							$this->error = mysql_error($this->_db_handle);
375 1586 darkviper
							unset($aSql);
376
							break;
377
						}
378
					}
379
					$sql = '';
380
				}
381
			}
382
		}
383
		return $retval;
384
	}
385 1362 Luisehahne
386 1586 darkviper
/**
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 1535 Luisehahne
	public function getTableEngine($table)
392
	{
393
		$retVal = false;
394 1680 darkviper
		$mysqlVersion = mysql_get_server_info($this->_db_handle);
395 1535 Luisehahne
		$engineValue = (version_compare($mysqlVersion, '5.0') < 0) ? 'Type' : 'Engine';
396 1680 darkviper
		$sql = "SHOW TABLE STATUS FROM " . $this->_db_name . " LIKE '" . $table . "'";
397
		if(($result = $this->query($sql, $this->_db_handle))) {
398 1535 Luisehahne
			if(($row = $result->fetchRow(MYSQL_ASSOC))) {
399
				$retVal = $row[$engineValue];
400
			}
401
		}
402
		return $retVal;
403
	}
404
405
406 1362 Luisehahne
} /// end of class database
407
408 1549 Luisehahne
define('MYSQL_SEEK_FIRST', 0);
409
define('MYSQL_SEEK_LAST', -1);
410
411 4 ryan
class mysql {
412
413 1680 darkviper
	private $result = null;
414
	private $_db_handle = null;
415 4 ryan
	// Run a query
416 1680 darkviper
	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 4 ryan
		return $this->result;
421
	}
422
423
	// Fetch num rows
424
	function numRows() {
425
		return mysql_num_rows($this->result);
426
	}
427 1011 Ruebenwurz
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 4 ryan
	}
432 1011 Ruebenwurz
433 1549 Luisehahne
	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 4 ryan
	// Get error
446
	function error() {
447
		if(isset($this->error)) {
448
			return $this->error;
449
		} else {
450
			return null;
451
		}
452
	}
453
454
}
455 1364 Luisehahne
/* 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 1680 darkviper
			$sql = 'SELECT COUNT(`setting_id`) '
481
			     . 'FROM `'.TABLE_PREFIX.$table.'` '
482
			     . 'WHERE `name` = \''.$index.'\' ';
483 1364 Luisehahne
			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
	}