Project

General

Profile

1 4 ryan
<?php
2 1362 Luisehahne
/**
3 1866 Luisehahne
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
4 1362 Luisehahne
 *
5 1866 Luisehahne
 * This program is free software: you can redistribute it and/or modify
6
 * it under the terms of the GNU General Public License as published by
7
 * the Free Software Foundation, either version 3 of the License, or
8
 * (at your option) any later version.
9 1362 Luisehahne
 *
10 1866 Luisehahne
 * This program is distributed in the hope that it will be useful,
11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
 * GNU General Public License for more details.
14
 *
15
 * You should have received a copy of the GNU General Public License
16
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
17 1362 Luisehahne
 */
18 1866 Luisehahne
/**
19
 * WbDatabase.php
20
 *
21
 * @category     Core
22
 * @package      Core_database
23
 * @author       Werner v.d.Decken <wkl@isteam.de>
24
 * @author       Dietmar W. <dietmar.woellbrink@websitebaker.org>
25
 * @copyright    Werner v.d.Decken <wkl@isteam.de>
26
 * @license      http://www.gnu.org/licenses/gpl.html   GPL License
27
 * @version      0.0.9
28
 * @revision     $Revision$
29
 * @lastmodified $Date$
30
 * @deprecated   from WB version number 2.9
31
 * @description  Mysql database wrapper for use with websitebaker up to version 2.8.4
32
 */
33
34 1496 DarkViper
/* -------------------------------------------------------- */
35 4 ryan
define('DATABASE_CLASS_LOADED', true);
36
37 1686 darkviper
class WbDatabase {
38 1763 Luisehahne
39 1686 darkviper
	private static $_oInstances = array();
40 1680 darkviper
41
	private $_db_handle = null; // readonly from outside
42
	private $_db_name   = '';
43 1362 Luisehahne
	private $connected  = false;
44
	private $error      = '';
45
	private $error_type = '';
46 1662 darkviper
	private $iQueryCount= 0;
47 1362 Luisehahne
48 1683 darkviper
/* prevent from public instancing */
49 1686 darkviper
	protected function  __construct() {}
50 1683 darkviper
/* prevent from cloning */
51
	private function __clone() {}
52
/**
53 1686 darkviper
 * get a valid instance of this class
54
 * @param string $sIdentifier selector for several different instances
55
 * @return object
56
 */
57
	public static function getInstance($sIdentifier = 'core') {
58
		if( !isset(self::$_oInstances[$sIdentifier])) {
59
            $c = __CLASS__;
60
            self::$_oInstances[$sIdentifier] = new $c;
61
		}
62
		return self::$_oInstances[$sIdentifier];
63
	}
64
/**
65
 * disconnect and kills an existing instance
66
 * @param string $sIdentifier
67
 */
68
	public static function killInstance($sIdentifier) {
69
		if($sIdentifier != 'core') {
70
			if( isset(self::$_oInstances[$sIdentifier])) {
71
				self::$_oInstances[$sIdentifier]->disconnect();
72
				unset(self::$_oInstances[$sIdentifier]);
73
			}
74
		}
75
	}
76
/**
77 1683 darkviper
 * Connect to the database
78
 * @param string $url
79
 * @return bool
80
 *
81
 * Example for SQL-Url:  'mysql://user:password@demo.de[:3306]/datenbank'
82
 */
83
	public function doConnect($url = '') {
84 1680 darkviper
		if($url != '') {
85
			$aIni = parse_url($url);
86 1866 Luisehahne
87
			$scheme   = isset($aIni['scheme']) ? $aIni['scheme'] : 'mysql';
88
			$hostname = isset($aIni['host']) ? $aIni['host'] : '';
89
			$username = isset($aIni['user']) ? $aIni['user'] : '';
90
			$password = isset($aIni['pass']) ? $aIni['pass'] : '';
91
			$hostport = isset($aIni['port']) ? $aIni['port'] : '3306';
92
			$hostport = $hostport == '3306' ? '' : ':'.$hostport;
93
			$db_name  = ltrim(isset($aIni['path']) ? $aIni['path'] : '', '/\\');
94
			$this->_db_name = $db_name;
95 1680 darkviper
		}else {
96 1682 darkviper
			throw new RuntimeException('Missing parameter: unable to connect database');
97 1680 darkviper
		}
98 1866 Luisehahne
		$this->_db_handle = mysql_connect($hostname.$hostport,
99
		                                  $username,
100
		                                  $password);
101 1680 darkviper
		if(!$this->_db_handle) {
102 1866 Luisehahne
			throw new RuntimeException('unable to connect \''.$scheme.'://'.
103
			                           $hostname.$hostport.'\'');
104 4 ryan
		} else {
105 1866 Luisehahne
			if(!mysql_select_db($db_name)) {
106
				throw new RuntimeException('unable to select database \''.$db_name.
107
				                           '\' on \''.$scheme.'://'.
108
				                           $hostname.$hostport.'\'');
109 4 ryan
			} else {
110
				$this->connected = true;
111
			}
112
		}
113
		return $this->connected;
114
	}
115 1763 Luisehahne
116 4 ryan
	// Disconnect from the database
117 1686 darkviper
	public function disconnect() {
118 95 stefan
		if($this->connected==true) {
119 1680 darkviper
			mysql_close($this->_db_handle);
120 4 ryan
			return true;
121
		} else {
122
			return false;
123
		}
124
	}
125 1763 Luisehahne
126 4 ryan
	// Run a query
127 1686 darkviper
	public function query($statement) {
128 1662 darkviper
		$this->iQueryCount++;
129 4 ryan
		$mysql = new mysql();
130 1680 darkviper
		$mysql->query($statement, $this->_db_handle);
131
		$this->set_error($mysql->error($this->_db_handle));
132
		if($mysql->error($this->_db_handle)) {
133 4 ryan
			return null;
134
		} else {
135
			return $mysql;
136
		}
137
	}
138 1362 Luisehahne
139 4 ryan
	// Gets the first column of the first row
140 1686 darkviper
	public function get_one( $statement )
141 1362 Luisehahne
	{
142 1662 darkviper
		$this->iQueryCount++;
143 1680 darkviper
		$fetch_row = mysql_fetch_array(mysql_query($statement, $this->_db_handle));
144 4 ryan
		$result = $fetch_row[0];
145 1680 darkviper
		$this->set_error(mysql_error($this->_db_handle));
146
		if(mysql_error($this->_db_handle)) {
147 4 ryan
			return null;
148
		} else {
149
			return $result;
150
		}
151
	}
152 1763 Luisehahne
153 4 ryan
	// Set the DB error
154 1686 darkviper
	public function set_error($message = null) {
155 4 ryan
		global $TABLE_DOES_NOT_EXIST, $TABLE_UNKNOWN;
156
		$this->error = $message;
157
		if(strpos($message, 'no such table')) {
158
			$this->error_type = $TABLE_DOES_NOT_EXIST;
159
		} else {
160
			$this->error_type = $TABLE_UNKNOWN;
161
		}
162
	}
163 1763 Luisehahne
164 4 ryan
	// Return true if there was an error
165 1686 darkviper
	public function is_error() {
166 4 ryan
		return (!empty($this->error)) ? true : false;
167
	}
168 1763 Luisehahne
169 4 ryan
	// Return the error
170 1686 darkviper
	public function get_error() {
171 4 ryan
		return $this->error;
172
	}
173
174 1866 Luisehahne
	// Return escape_string
175 1613 darkviper
/**
176 1866 Luisehahne
 * escape a string for use in DB
177
 * @param string
178
 * @return string
179
 */
180
	public function escapeString($string) {
181
		return mysql_real_escape_string($string, $this->_db_handle);
182
	}
183
184
/**
185 1613 darkviper
 * default Getter for some properties
186 1866 Luisehahne
 * @param string name of the Property
187 1613 darkviper
 * @return mixed NULL on error or missing property
188 1362 Luisehahne
 */
189 1613 darkviper
	public function __get($sPropertyName)
190 1362 Luisehahne
	{
191 1613 darkviper
		switch ($sPropertyName):
192
			case 'db_handle':
193
			case 'DbHandle':
194 1662 darkviper
			case 'getDbHandle':
195 1680 darkviper
				$retval = $this->_db_handle;
196 1613 darkviper
				break;
197 1866 Luisehahne
			case 'LastInsertId':
198
				$retval = mysql_insert_id($this->_db_handle);
199
				break;
200 1613 darkviper
			case 'db_name':
201
			case 'DbName':
202 1662 darkviper
			case 'getDbName':
203 1680 darkviper
				$retval = $this->_db_name;
204 1613 darkviper
				break;
205 1662 darkviper
			case 'getQueryCount':
206
				$retval = $this->iQueryCount;
207
				break;
208 1613 darkviper
			default:
209
				$retval = null;
210
				break;
211
		endswitch;
212
		return $retval;
213
	} // __get()
214 1362 Luisehahne
215
/*
216 1866 Luisehahne
 * @param string full name of the table (incl. TABLE_PREFIX)
217
 * @param string name of the field to seek for
218
 * @return bool true if field exists
219 1362 Luisehahne
 */
220
	public function field_exists($table_name, $field_name)
221
	{
222
		$sql = 'DESCRIBE `'.$table_name.'` `'.$field_name.'` ';
223 1680 darkviper
		$query = $this->query($sql, $this->_db_handle);
224 1362 Luisehahne
		return ($query->numRows() != 0);
225
	}
226
227
/*
228 1866 Luisehahne
 * @param string full name of the table (incl. TABLE_PREFIX)
229
 * @param string name of the index to seek for
230
 * @return bool true if field exists
231 1362 Luisehahne
 */
232
	public function index_exists($table_name, $index_name, $number_fields = 0)
233
	{
234
		$number_fields = intval($number_fields);
235
		$keys = 0;
236
		$sql = 'SHOW INDEX FROM `'.$table_name.'`';
237 1680 darkviper
		if( ($res_keys = $this->query($sql, $this->_db_handle)) )
238 1362 Luisehahne
		{
239
			while(($rec_key = $res_keys->fetchRow()))
240
			{
241
				if( $rec_key['Key_name'] == $index_name )
242
				{
243
					$keys++;
244
				}
245
			}
246
247
		}
248
		if( $number_fields == 0 )
249
		{
250
			return ($keys != $number_fields);
251
		}else
252
		{
253
			return ($keys == $number_fields);
254
		}
255
	}
256 1763 Luisehahne
257 1362 Luisehahne
/*
258 1866 Luisehahne
 * @param string full name of the table (incl. TABLE_PREFIX)
259
 * @param string name of the field to add
260
 * @param string describes the new field like ( INT NOT NULL DEFAULT '0')
261
 * @return bool true if successful, otherwise false and error will be set
262 1362 Luisehahne
 */
263
	public function field_add($table_name, $field_name, $description)
264
	{
265 1442 Luisehahne
		if( !$this->field_exists($table_name, $field_name) )
266 1362 Luisehahne
		{ // add new field into a table
267
			$sql = 'ALTER TABLE `'.$table_name.'` ADD '.$field_name.' '.$description.' ';
268 1680 darkviper
			$query = $this->query($sql, $this->_db_handle);
269
			$this->set_error(mysql_error($this->_db_handle));
270 1362 Luisehahne
			if( !$this->is_error() )
271
			{
272 1442 Luisehahne
				return ( $this->field_exists($table_name, $field_name) ) ? true : false;
273 1362 Luisehahne
			}
274
		}else
275
		{
276
			$this->set_error('field \''.$field_name.'\' already exists');
277
		}
278
		return false;
279
	}
280
281
/*
282
 * @param string $table_name: full name of the table (incl. TABLE_PREFIX)
283
 * @param string $field_name: name of the field to add
284
 * @param string $description: describes the new field like ( INT NOT NULL DEFAULT '0')
285
 * @return bool: true if successful, otherwise false and error will be set
286
 */
287
	public function field_modify($table_name, $field_name, $description)
288
	{
289
		$retval = false;
290 1486 DarkViper
		if( $this->field_exists($table_name, $field_name) )
291 1362 Luisehahne
		{ // modify a existing field in a table
292 1486 DarkViper
			$sql  = 'ALTER TABLE `'.$table_name.'` MODIFY `'.$field_name.'` '.$description;
293 1680 darkviper
			$retval = ( $this->query($sql, $this->_db_handle) ? true : false);
294 1486 DarkViper
			$this->set_error(mysql_error());
295 1362 Luisehahne
		}
296 1486 DarkViper
		return $retval;
297 1362 Luisehahne
	}
298
299
/*
300
 * @param string $table_name: full name of the table (incl. TABLE_PREFIX)
301
 * @param string $field_name: name of the field to remove
302
 * @return bool: true if successful, otherwise false and error will be set
303
 */
304
	public function field_remove($table_name, $field_name)
305
	{
306
		$retval = false;
307 1507 Luisehahne
		if( $this->field_exists($table_name, $field_name) )
308 1362 Luisehahne
		{ // modify a existing field in a table
309
			$sql  = 'ALTER TABLE `'.$table_name.'` DROP `'.$field_name.'`';
310 1680 darkviper
			$retval = ( $this->query($sql, $this->_db_handle) ? true : false );
311 1362 Luisehahne
		}
312
		return $retval;
313
	}
314
315
/*
316
 * @param string $table_name: full name of the table (incl. TABLE_PREFIX)
317 1763 Luisehahne
 * @param string $index_name: name of the new index (empty string for PRIMARY)
318 1362 Luisehahne
 * @param string $field_list: comma seperated list of fields for this index
319 1763 Luisehahne
 * @param string $index_type: kind of index (PRIMARY, UNIQUE, KEY, FULLTEXT)
320 1362 Luisehahne
 * @return bool: true if successful, otherwise false and error will be set
321
 */
322 1763 Luisehahne
     public function index_add($table_name, $index_name, $field_list, $index_type = 'KEY')
323
     {
324
        $retval = false;
325
        $field_list = str_replace(' ', '', $field_list);
326
        $field_list = explode(',', $field_list);
327
        $number_fields = sizeof($field_list);
328
        $field_list = '`'.implode('`,`', $field_list).'`';
329
        $index_name = $index_type == 'PRIMARY' ? $index_type : $index_name;
330
        if( $this->index_exists($table_name, $index_name, $number_fields) ||
331
            $this->index_exists($table_name, $index_name))
332
        {
333
            $sql  = 'ALTER TABLE `'.$table_name.'` ';
334
            $sql .= 'DROP INDEX `'.$index_name.'`';
335
            if( !$this->query($sql, $this->_db_handle)) { return false; }
336
        }
337
        $sql  = 'ALTER TABLE `'.$table_name.'` ';
338
        $sql .= 'ADD '.$index_type.' ';
339
        $sql .= $index_type == 'PRIMARY' ? 'KEY ' : '`'.$index_name.'` ';
340
        $sql .= '( '.$field_list.' ); ';
341
        if( $this->query($sql, $this->_db_handle)) { $retval = true; }
342
        return $retval;
343
    }
344 1362 Luisehahne
345
/*
346
 * @param string $table_name: full name of the table (incl. TABLE_PREFIX)
347
 * @param string $field_name: name of the field to remove
348
 * @return bool: true if successful, otherwise false and error will be set
349
 */
350
	public function index_remove($table_name, $index_name)
351
	{
352
		$retval = false;
353
		if( $this->index_exists($table_name, $index_name) )
354
		{ // modify a existing field in a table
355
			$sql  = 'ALTER TABLE `'.$table_name.'` DROP INDEX `'.$index_name.'`';
356 1680 darkviper
			$retval = ( $this->query($sql, $this->_db_handle) ? true : false );
357 1362 Luisehahne
		}
358
		return $retval;
359
	}
360 1763 Luisehahne
361 1586 darkviper
/**
362
 * Import a standard *.sql dump file
363
 * @param string $sSqlDump link to the sql-dumpfile
364
 * @param string $sTablePrefix
365 1591 darkviper
 * @param bool $bPreserve set to true will ignore all DROP TABLE statements
366 1586 darkviper
 * @param string $sTblEngine
367
 * @param string $sTblCollation
368
 * @return boolean true if import successful
369
 */
370
	public function SqlImport($sSqlDump,
371
	                          $sTablePrefix = '',
372 1591 darkviper
	                          $bPreserve = true,
373 1586 darkviper
	                          $sTblEngine = 'ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci',
374 1591 darkviper
	                          $sTblCollation = ' collate utf8_unicode_ci')
375 1586 darkviper
	{
376
		$retval = true;
377
		$this->error = '';
378
		$aSearch  = array('{TABLE_PREFIX}','{TABLE_ENGINE}', '{TABLE_COLLATION}');
379
		$aReplace = array($sTablePrefix, $sTblEngine, $sTblCollation);
380
		$sql = '';
381
		$aSql = file($sSqlDump);
382
		while ( sizeof($aSql) > 0 ) {
383
			$sSqlLine = trim(array_shift($aSql));
384 1591 darkviper
			if (!preg_match('/^[-\/]+.*/', $sSqlLine)) {
385 1592 darkviper
				$sql = $sql.' '.$sSqlLine;
386 1586 darkviper
				if ((substr($sql,-1,1) == ';')) {
387
					$sql = trim(str_replace( $aSearch, $aReplace, $sql));
388
					if (!($bPreserve && preg_match('/^\s*DROP TABLE IF EXISTS/siU', $sql))) {
389 1680 darkviper
						if(!mysql_query($sql, $this->_db_handle)) {
390 1586 darkviper
							$retval = false;
391 1680 darkviper
							$this->error = mysql_error($this->_db_handle);
392 1586 darkviper
							unset($aSql);
393
							break;
394
						}
395
					}
396
					$sql = '';
397
				}
398
			}
399
		}
400
		return $retval;
401
	}
402 1362 Luisehahne
403 1586 darkviper
/**
404
 * retuns the type of the engine used for requested table
405
 * @param string $table name of the table, including prefix
406
 * @return boolean/string false on error, or name of the engine (myIsam/InnoDb)
407
 */
408 1535 Luisehahne
	public function getTableEngine($table)
409
	{
410
		$retVal = false;
411 1680 darkviper
		$mysqlVersion = mysql_get_server_info($this->_db_handle);
412 1535 Luisehahne
		$engineValue = (version_compare($mysqlVersion, '5.0') < 0) ? 'Type' : 'Engine';
413 1770 Luisehahne
		$sql = 'SHOW TABLE STATUS FROM `' . $this->_db_name . '` LIKE \'' . $table . '\'';
414 1680 darkviper
		if(($result = $this->query($sql, $this->_db_handle))) {
415 1535 Luisehahne
			if(($row = $result->fetchRow(MYSQL_ASSOC))) {
416
				$retVal = $row[$engineValue];
417
			}
418
		}
419
		return $retVal;
420
	}
421
422
423 1362 Luisehahne
} /// end of class database
424
425 1549 Luisehahne
define('MYSQL_SEEK_FIRST', 0);
426
define('MYSQL_SEEK_LAST', -1);
427
428 4 ryan
class mysql {
429
430 1680 darkviper
	private $result = null;
431
	private $_db_handle = null;
432 4 ryan
	// Run a query
433 1680 darkviper
	function query($statement, $dbHandle) {
434
		$this->_db_handle = $dbHandle;
435
		$this->result = mysql_query($statement, $this->_db_handle);
436
		$this->error = mysql_error($this->_db_handle);
437 4 ryan
		return $this->result;
438
	}
439 1763 Luisehahne
440 4 ryan
	// Fetch num rows
441
	function numRows() {
442
		return mysql_num_rows($this->result);
443
	}
444 1011 Ruebenwurz
445
	// Fetch row  $typ = MYSQL_ASSOC, MYSQL_NUM, MYSQL_BOTH
446
	function fetchRow($typ = MYSQL_BOTH) {
447
		return mysql_fetch_array($this->result, $typ);
448 4 ryan
	}
449 1011 Ruebenwurz
450 1549 Luisehahne
	function rewind()
451
	{
452
		return $this->seekRow();
453
	}
454
455
	function seekRow( $position = MYSQL_SEEK_FIRST )
456
	{
457
		$pmax = $this->numRows() - 1;
458
		$p = (($position < 0 || $position > $pmax) ? $pmax : $position);
459
		return mysql_data_seek($this->result, $p);
460
	}
461
462 4 ryan
	// Get error
463
	function error() {
464
		if(isset($this->error)) {
465
			return $this->error;
466
		} else {
467
			return null;
468
		}
469
	}
470
471
}
472 1763 Luisehahne
473 1364 Luisehahne
/* this function is placed inside this file temporarely until a better place is found */
474
/*  function to update a var/value-pair(s) in table ****************************
475
 *  nonexisting keys are inserted
476
 *  @param string $table: name of table to use (without prefix)
477
 *  @param mixed $key:    a array of key->value pairs to update
478
 *                        or a string with name of the key to update
479
 *  @param string $value: a sting with needed value, if $key is a string too
480
 *  @return bool:  true if any keys are updated, otherwise false
481
 */
482
	function db_update_key_value($table, $key, $value = '')
483
	{
484
		global $database;
485
		if( !is_array($key))
486
		{
487
			if( trim($key) != '' )
488
			{
489
				$key = array( trim($key) => trim($value) );
490
			} else {
491
				$key = array();
492
			}
493
		}
494
		$retval = true;
495
		foreach( $key as $index=>$val)
496
		{
497
			$index = strtolower($index);
498 1680 darkviper
			$sql = 'SELECT COUNT(`setting_id`) '
499
			     . 'FROM `'.TABLE_PREFIX.$table.'` '
500
			     . 'WHERE `name` = \''.$index.'\' ';
501 1364 Luisehahne
			if($database->get_one($sql))
502
			{
503
				$sql = 'UPDATE ';
504
				$sql_where = 'WHERE `name` = \''.$index.'\'';
505
			}else {
506
				$sql = 'INSERT INTO ';
507
				$sql_where = '';
508
			}
509
			$sql .= '`'.TABLE_PREFIX.$table.'` ';
510
			$sql .= 'SET `name` = \''.$index.'\', ';
511
			$sql .= '`value` = \''.$val.'\' '.$sql_where;
512
			if( !$database->query($sql) )
513
			{
514
				$retval = false;
515
			}
516
		}
517
		return $retval;
518
	}