Project

General

Profile

1
<?php
2
/**
3
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
4
 *
5
 * 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
 *
10
 * 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
 */
18
/**
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: 1866 $
29
 * @lastmodified $Date: 2013-02-19 21:47:39 +0100 (Tue, 19 Feb 2013) $
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
/* -------------------------------------------------------- */
35
define('DATABASE_CLASS_LOADED', true);
36

    
37
class WbDatabase {
38

    
39
	private static $_oInstances = array();
40

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

    
48
/* prevent from public instancing */
49
	protected function  __construct() {}
50
/* prevent from cloning */
51
	private function __clone() {}
52
/**
53
 * 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
 * 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
		if($url != '') {
85
			$aIni = parse_url($url);
86
			
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
		}else {
96
			throw new RuntimeException('Missing parameter: unable to connect database');
97
		}
98
		$this->_db_handle = mysql_connect($hostname.$hostport,
99
		                                  $username,
100
		                                  $password);
101
		if(!$this->_db_handle) {
102
			throw new RuntimeException('unable to connect \''.$scheme.'://'.
103
			                           $hostname.$hostport.'\'');
104
		} else {
105
			if(!mysql_select_db($db_name)) {
106
				throw new RuntimeException('unable to select database \''.$db_name.
107
				                           '\' on \''.$scheme.'://'.
108
				                           $hostname.$hostport.'\'');
109
			} else {
110
				$this->connected = true;
111
			}
112
		}
113
		return $this->connected;
114
	}
115

    
116
	// Disconnect from the database
117
	public function disconnect() {
118
		if($this->connected==true) {
119
			mysql_close($this->_db_handle);
120
			return true;
121
		} else {
122
			return false;
123
		}
124
	}
125

    
126
	// Run a query
127
	public function query($statement) {
128
		$this->iQueryCount++;
129
		$mysql = new mysql();
130
		$mysql->query($statement, $this->_db_handle);
131
		$this->set_error($mysql->error($this->_db_handle));
132
		if($mysql->error($this->_db_handle)) {
133
			return null;
134
		} else {
135
			return $mysql;
136
		}
137
	}
138

    
139
	// Gets the first column of the first row
140
	public function get_one( $statement )
141
	{
142
		$this->iQueryCount++;
143
		$fetch_row = mysql_fetch_array(mysql_query($statement, $this->_db_handle));
144
		$result = $fetch_row[0];
145
		$this->set_error(mysql_error($this->_db_handle));
146
		if(mysql_error($this->_db_handle)) {
147
			return null;
148
		} else {
149
			return $result;
150
		}
151
	}
152

    
153
	// Set the DB error
154
	public function set_error($message = null) {
155
		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

    
164
	// Return true if there was an error
165
	public function is_error() {
166
		return (!empty($this->error)) ? true : false;
167
	}
168

    
169
	// Return the error
170
	public function get_error() {
171
		return $this->error;
172
	}
173

    
174
	// Return escape_string
175
/**
176
 * 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
 * default Getter for some properties
186
 * @param string name of the Property
187
 * @return mixed NULL on error or missing property
188
 */
189
	public function __get($sPropertyName)
190
	{
191
		switch ($sPropertyName):
192
			case 'db_handle':
193
			case 'DbHandle':
194
			case 'getDbHandle':
195
				$retval = $this->_db_handle;
196
				break;
197
			case 'LastInsertId':
198
				$retval = mysql_insert_id($this->_db_handle);
199
				break;
200
			case 'db_name':
201
			case 'DbName':
202
			case 'getDbName':
203
				$retval = $this->_db_name;
204
				break;
205
			case 'getQueryCount':
206
				$retval = $this->iQueryCount;
207
				break;
208
			default:
209
				$retval = null;
210
				break;
211
		endswitch;
212
		return $retval;
213
	} // __get()
214

    
215
/*
216
 * @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
 */
220
	public function field_exists($table_name, $field_name)
221
	{
222
		$sql = 'DESCRIBE `'.$table_name.'` `'.$field_name.'` ';
223
		$query = $this->query($sql, $this->_db_handle);
224
		return ($query->numRows() != 0);
225
	}
226

    
227
/*
228
 * @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
 */
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
		if( ($res_keys = $this->query($sql, $this->_db_handle)) )
238
		{
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

    
257
/*
258
 * @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
 */
263
	public function field_add($table_name, $field_name, $description)
264
	{
265
		if( !$this->field_exists($table_name, $field_name) )
266
		{ // add new field into a table
267
			$sql = 'ALTER TABLE `'.$table_name.'` ADD '.$field_name.' '.$description.' ';
268
			$query = $this->query($sql, $this->_db_handle);
269
			$this->set_error(mysql_error($this->_db_handle));
270
			if( !$this->is_error() )
271
			{
272
				return ( $this->field_exists($table_name, $field_name) ) ? true : false;
273
			}
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
		if( $this->field_exists($table_name, $field_name) )
291
		{ // modify a existing field in a table
292
			$sql  = 'ALTER TABLE `'.$table_name.'` MODIFY `'.$field_name.'` '.$description;
293
			$retval = ( $this->query($sql, $this->_db_handle) ? true : false);
294
			$this->set_error(mysql_error());
295
		}
296
		return $retval;
297
	}
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
		if( $this->field_exists($table_name, $field_name) )
308
		{ // modify a existing field in a table
309
			$sql  = 'ALTER TABLE `'.$table_name.'` DROP `'.$field_name.'`';
310
			$retval = ( $this->query($sql, $this->_db_handle) ? true : false );
311
		}
312
		return $retval;
313
	}
314

    
315
/*
316
 * @param string $table_name: full name of the table (incl. TABLE_PREFIX)
317
 * @param string $index_name: name of the new index (empty string for PRIMARY)
318
 * @param string $field_list: comma seperated list of fields for this index
319
 * @param string $index_type: kind of index (PRIMARY, UNIQUE, KEY, FULLTEXT)
320
 * @return bool: true if successful, otherwise false and error will be set
321
 */
322
     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

    
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
			$retval = ( $this->query($sql, $this->_db_handle) ? true : false );
357
		}
358
		return $retval;
359
	}
360

    
361
/**
362
 * Import a standard *.sql dump file
363
 * @param string $sSqlDump link to the sql-dumpfile
364
 * @param string $sTablePrefix
365
 * @param bool $bPreserve set to true will ignore all DROP TABLE statements
366
 * @param string $sTblEngine
367
 * @param string $sTblCollation
368
 * @return boolean true if import successful
369
 */
370
	public function SqlImport($sSqlDump,
371
	                          $sTablePrefix = '',
372
	                          $bPreserve = true,
373
	                          $sTblEngine = 'ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci',
374
	                          $sTblCollation = ' collate utf8_unicode_ci')
375
	{
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
			if (!preg_match('/^[-\/]+.*/', $sSqlLine)) {
385
				$sql = $sql.' '.$sSqlLine;
386
				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
						if(!mysql_query($sql, $this->_db_handle)) {
390
							$retval = false;
391
							$this->error = mysql_error($this->_db_handle);
392
							unset($aSql);
393
							break;
394
						}
395
					}
396
					$sql = '';
397
				}
398
			}
399
		}
400
		return $retval;
401
	}
402

    
403
/**
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
	public function getTableEngine($table)
409
	{
410
		$retVal = false;
411
		$mysqlVersion = mysql_get_server_info($this->_db_handle);
412
		$engineValue = (version_compare($mysqlVersion, '5.0') < 0) ? 'Type' : 'Engine';
413
		$sql = 'SHOW TABLE STATUS FROM `' . $this->_db_name . '` LIKE \'' . $table . '\'';
414
		if(($result = $this->query($sql, $this->_db_handle))) {
415
			if(($row = $result->fetchRow(MYSQL_ASSOC))) {
416
				$retVal = $row[$engineValue];
417
			}
418
		}
419
		return $retVal;
420
	}
421

    
422

    
423
} /// end of class database
424

    
425
define('MYSQL_SEEK_FIRST', 0);
426
define('MYSQL_SEEK_LAST', -1);
427

    
428
class mysql {
429

    
430
	private $result = null;
431
	private $_db_handle = null;
432
	// Run a query
433
	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
		return $this->result;
438
	}
439

    
440
	// Fetch num rows
441
	function numRows() {
442
		return mysql_num_rows($this->result);
443
	}
444

    
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
	}
449

    
450
	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
	// Get error
463
	function error() {
464
		if(isset($this->error)) {
465
			return $this->error;
466
		} else {
467
			return null;
468
		}
469
	}
470

    
471
}
472

    
473
/* 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
			$sql = 'SELECT COUNT(`setting_id`) '
499
			     . 'FROM `'.TABLE_PREFIX.$table.'` '
500
			     . 'WHERE `name` = \''.$index.'\' ';
501
			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
	}
(13-13/30)