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: 1974 $
29
 * @lastmodified $Date: 2013-10-04 01:35:37 +0200 (Fri, 04 Oct 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 $_sInstanceIdentifier = '';
44
	protected $sTablePrefix = '';
45
	protected $sCharset     = '';
46
	protected $connected    = false;
47
	protected $error        = '';
48
	protected $error_type   = '';
49
	protected $iQueryCount  = 0;
50

    
51
/* prevent from public instancing */
52
	protected function  __construct() {}
53
/* prevent from cloning */
54
	private function __clone() {}
55
/**
56
 * get a valid instance of this class
57
 * @param string $sIdentifier selector for several different instances
58
 * @return object
59
 */
60
	public static function getInstance($sIdentifier = 'core') {
61
		if( !isset(self::$_oInstances[$sIdentifier])) {
62
            $c = __CLASS__;
63
			$oInstance = new $c;
64
			$oInstance->_sInstanceIdentifier = $sIdentifier;
65
            self::$_oInstances[$sIdentifier] = $oInstance;
66
		}
67
		return self::$_oInstances[$sIdentifier];
68
	}
69
/**
70
 * disconnect and kills an existing instance
71
 * @param string $sIdentifier
72
 */
73
	public static function killInstance($sIdentifier) {
74
		if($sIdentifier != 'core') {
75
			if( isset(self::$_oInstances[$sIdentifier])) {
76
				self::$_oInstances[$sIdentifier]->disconnect();
77
				unset(self::$_oInstances[$sIdentifier]);
78
			}
79
		}
80
	}
81
/**
82
 * Connect to the database
83
 * @param string $url
84
 * @return bool
85
 *
86
 * Example for SQL-Url:  'mysql://user:password@demo.de[:3306]/datenbank'
87
 */
88
	public function doConnect($url = '') {
89
		if($this->connected) { return $this->connected; } // prevent from reconnecting
90
		$this->connected = false;
91
		if($url != '') {
92
			$aIni = parse_url($url);
93
			
94
			$scheme   = isset($aIni['scheme']) ? $aIni['scheme'] : 'mysql';
95
			$hostname = isset($aIni['host']) ? $aIni['host'] : '';
96
			$username = isset($aIni['user']) ? $aIni['user'] : '';
97
			$password = isset($aIni['pass']) ? $aIni['pass'] : '';
98
			$hostport = isset($aIni['port']) ? $aIni['port'] : '3306';
99
			$hostport = $hostport == '3306' ? '' : ':'.$hostport;
100
			$db_name  = ltrim(isset($aIni['path']) ? $aIni['path'] : '', '/\\');
101
			$sTmp = isset($aIni['query']) ? $aIni['query'] : '';
102
			$aQuery = explode('&', $sTmp);
103
			foreach($aQuery as $sArgument) {
104
				$aArg = explode('=', $sArgument);
105
				switch(strtolower($aArg[0])) {
106
					case 'charset':
107
						$this->sCharset = strtolower(preg_replace('/[^a-z0-9]/i', '', $aArg[1]));
108
						break;
109
					case 'tableprefix':
110
						$this->sTablePrefix = $aArg[1];
111
						break;
112
					default:
113
						break;
114
				}
115
			}
116
			$this->_db_name = $db_name;
117
		}else {
118
			throw new WbDatabaseException('Missing parameter: unable to connect database');
119
		}
120
		$this->_db_handle = @mysql_connect($hostname.$hostport,
121
		                                   $username,
122
		                                   $password,
123
		                                   true);
124
		if(!$this->_db_handle) {
125
			throw new WbDatabaseException('unable to connect \''.$scheme.'://'.
126
			                           $hostname.$hostport.'\'');
127
		} else {
128
			if(!@mysql_select_db($db_name, $this->_db_handle)) {
129
				throw new WbDatabaseException('unable to select database \''.$db_name.
130
				                           '\' on \''.$scheme.'://'.
131
				                           $hostname.$hostport.'\'');
132
			} else {
133
				if($this->sCharset) {
134
					@mysql_query('SET NAMES \''.$this->sCharset.'\'', $this->_db_handle);
135
				}
136
				$this->connected = true;
137
			}
138
		}
139
		return $this->connected;
140
	}
141

    
142
	// Disconnect from the database
143
	public function disconnect() {
144
		if($this->connected == true && $oInstance->_sInstanceIdentifier != 'core' ) {
145
			mysql_close($this->_db_handle);
146
			$this->connected = false;
147
			return true;
148
		}
149
		return false;
150
	}
151

    
152
	// Run a query
153
	public function query($statement) {
154
		$this->iQueryCount++;
155
		$mysql = new mysql();
156
		$mysql->query($statement, $this->_db_handle);
157
		$this->set_error($mysql->error($this->_db_handle));
158
		if($mysql->error($this->_db_handle)) {
159
			return null;
160
		} else {
161
			return $mysql;
162
		}
163
	}
164

    
165
	// Gets the first column of the first row
166
	public function get_one( $statement )
167
	{
168
		$this->iQueryCount++;
169
		$fetch_row = mysql_fetch_array(mysql_query($statement, $this->_db_handle));
170
		$result = $fetch_row[0];
171
		$this->set_error(mysql_error($this->_db_handle));
172
		if(mysql_error($this->_db_handle)) {
173
			return null;
174
		} else {
175
			return $result;
176
		}
177
	}
178

    
179
	// Set the DB error
180
	public function set_error($message = null) {
181
		global $TABLE_DOES_NOT_EXIST, $TABLE_UNKNOWN;
182
		$this->error = $message;
183
		if(strpos($message, 'no such table')) {
184
			$this->error_type = $TABLE_DOES_NOT_EXIST;
185
		} else {
186
			$this->error_type = $TABLE_UNKNOWN;
187
		}
188
	}
189

    
190
	// Return true if there was an error
191
	public function is_error() {
192
		return (!empty($this->error)) ? true : false;
193
	}
194

    
195
	// Return the error
196
	public function get_error() {
197
		return $this->error;
198
	}
199
/**
200
 * Protect class from property injections
201
 * @param string name of property
202
 * @param mixed value
203
 * @throws WbDatabaseException
204
 */	
205
	public function __set($name, $value) {
206
		throw new WbDatabaseException('tried to set a readonly or nonexisting property ['.$name.']!! ');
207
	}
208
/**
209
 * default Getter for some properties
210
 * @param string name of the Property
211
 * @return mixed NULL on error or missing property
212
 */
213
	public function __get($sPropertyName)
214
	{
215
		switch ($sPropertyName):
216
			case 'db_handle':
217
			case 'DbHandle':
218
			case 'getDbHandle':
219
				$retval = $this->_db_handle;
220
				break;
221
			case 'LastInsertId':
222
			case 'getLastInsertId':
223
				$retval = mysql_insert_id($this->_db_handle);
224
				break;
225
			case 'db_name':
226
			case 'DbName':
227
			case 'getDbName':
228
				$retval = $this->_db_name;
229
				break;
230
			case 'TablePrefix':
231
			case 'getTablePrefix':
232
				$retval = $this->sTablePrefix;			
233
				break;
234
			case 'QueryCount':
235
			case 'getQueryCount':
236
				$retval = $this->iQueryCount;
237
				break;
238
			default:
239
				$retval = null;
240
				break;
241
		endswitch;
242
		return $retval;
243
	} // __get()
244
/**
245
 * Escapes special characters in a string for use in an SQL statement
246
 * @param string $unescaped_string
247
 * @return string
248
 */
249
	public function escapeString($unescaped_string)
250
	{
251
		return mysql_real_escape_string($unescaped_string, $this->_db_handle);
252
	}
253
/**
254
 * Last inserted Id
255
 * @return bool|int false on error, 0 if no record inserted
256
 */	
257
	public function getLastInsertId()
258
	{
259
		return mysql_insert_id($this->_db_handle);
260
	}
261
/*
262
 * @param string full name of the table (incl. TABLE_PREFIX)
263
 * @param string name of the field to seek for
264
 * @return bool true if field exists
265
 */
266
	public function field_exists($table_name, $field_name)
267
	{
268
		$sql = 'DESCRIBE `'.$table_name.'` `'.$field_name.'` ';
269
		$query = $this->query($sql, $this->_db_handle);
270
		return ($query->numRows() != 0);
271
	}
272
/*
273
 * @param string full name of the table (incl. TABLE_PREFIX)
274
 * @param string name of the index to seek for
275
 * @return bool true if field exists
276
 */
277
	public function index_exists($table_name, $index_name, $number_fields = 0)
278
	{
279
		$number_fields = intval($number_fields);
280
		$keys = 0;
281
		$sql = 'SHOW INDEX FROM `'.$table_name.'`';
282
		if( ($res_keys = $this->query($sql, $this->_db_handle)) )
283
		{
284
			while(($rec_key = $res_keys->fetchRow()))
285
			{
286
				if( $rec_key['Key_name'] == $index_name )
287
				{
288
					$keys++;
289
				}
290
			}
291

    
292
		}
293
		if( $number_fields == 0 )
294
		{
295
			return ($keys != $number_fields);
296
		}else
297
		{
298
			return ($keys == $number_fields);
299
		}
300
	}
301

    
302
/*
303
 * @param string full name of the table (incl. TABLE_PREFIX)
304
 * @param string name of the field to add
305
 * @param string describes the new field like ( INT NOT NULL DEFAULT '0')
306
 * @return bool true if successful, otherwise false and error will be set
307
 */
308
	public function field_add($table_name, $field_name, $description)
309
	{
310
		if( !$this->field_exists($table_name, $field_name) )
311
		{ // add new field into a table
312
			$sql = 'ALTER TABLE `'.$table_name.'` ADD '.$field_name.' '.$description.' ';
313
			$query = $this->query($sql, $this->_db_handle);
314
			$this->set_error(mysql_error($this->_db_handle));
315
			if( !$this->is_error() )
316
			{
317
				return ( $this->field_exists($table_name, $field_name) ) ? true : false;
318
			}
319
		}else
320
		{
321
			$this->set_error('field \''.$field_name.'\' already exists');
322
		}
323
		return false;
324
	}
325

    
326
/*
327
 * @param string $table_name: full name of the table (incl. TABLE_PREFIX)
328
 * @param string $field_name: name of the field to add
329
 * @param string $description: describes the new field like ( INT NOT NULL DEFAULT '0')
330
 * @return bool: true if successful, otherwise false and error will be set
331
 */
332
	public function field_modify($table_name, $field_name, $description)
333
	{
334
		$retval = false;
335
		if( $this->field_exists($table_name, $field_name) )
336
		{ // modify a existing field in a table
337
			$sql  = 'ALTER TABLE `'.$table_name.'` MODIFY `'.$field_name.'` '.$description;
338
			$retval = ( $this->query($sql, $this->_db_handle) ? true : false);
339
			$this->set_error(mysql_error());
340
		}
341
		return $retval;
342
	}
343

    
344
/*
345
 * @param string $table_name: full name of the table (incl. TABLE_PREFIX)
346
 * @param string $field_name: name of the field to remove
347
 * @return bool: true if successful, otherwise false and error will be set
348
 */
349
	public function field_remove($table_name, $field_name)
350
	{
351
		$retval = false;
352
		if( $this->field_exists($table_name, $field_name) )
353
		{ // modify a existing field in a table
354
			$sql  = 'ALTER TABLE `'.$table_name.'` DROP `'.$field_name.'`';
355
			$retval = ( $this->query($sql, $this->_db_handle) ? true : false );
356
		}
357
		return $retval;
358
	}
359

    
360
/*
361
 * @param string $table_name: full name of the table (incl. TABLE_PREFIX)
362
 * @param string $index_name: name of the new index (empty string for PRIMARY)
363
 * @param string $field_list: comma seperated list of fields for this index
364
 * @param string $index_type: kind of index (PRIMARY, UNIQUE, KEY, FULLTEXT)
365
 * @return bool: true if successful, otherwise false and error will be set
366
 */
367
     public function index_add($table_name, $index_name, $field_list, $index_type = 'KEY')
368
     {
369
        $retval = false;
370
        $field_list = explode(',', (str_replace(' ', '', $field_list)));
371
        $number_fields = sizeof($field_list);
372
        $field_list = '`'.implode('`,`', $field_list).'`';
373
        $index_name = $index_type == 'PRIMARY' ? $index_type : $index_name;
374
        if( $this->index_exists($table_name, $index_name, $number_fields) ||
375
            $this->index_exists($table_name, $index_name))
376
        {
377
            $sql  = 'ALTER TABLE `'.$table_name.'` ';
378
            $sql .= 'DROP INDEX `'.$index_name.'`';
379
            if( !$this->query($sql, $this->_db_handle)) { return false; }
380
        }
381
        $sql  = 'ALTER TABLE `'.$table_name.'` ';
382
        $sql .= 'ADD '.$index_type.' ';
383
        $sql .= $index_type == 'PRIMARY' ? 'KEY ' : '`'.$index_name.'` ';
384
        $sql .= '( '.$field_list.' ); ';
385
        if( $this->query($sql, $this->_db_handle)) { $retval = true; }
386
        return $retval;
387
    }
388

    
389
/*
390
 * @param string $table_name: full name of the table (incl. TABLE_PREFIX)
391
 * @param string $field_name: name of the field to remove
392
 * @return bool: true if successful, otherwise false and error will be set
393
 */
394
	public function index_remove($table_name, $index_name)
395
	{
396
		$retval = false;
397
		if( $this->index_exists($table_name, $index_name) )
398
		{ // modify a existing field in a table
399
			$sql  = 'ALTER TABLE `'.$table_name.'` DROP INDEX `'.$index_name.'`';
400
			$retval = ( $this->query($sql, $this->_db_handle) ? true : false );
401
		}
402
		return $retval;
403
	}
404

    
405
/**
406
 * Import a standard *.sql dump file
407
 * @param string $sSqlDump link to the sql-dumpfile
408
 * @param string $sTablePrefix
409
 * @param bool     $bPreserve   set to true will ignore all DROP TABLE statements
410
 * @param string   $sEngine     can be 'MyISAM' or 'InnoDB'
411
 * @param string   $sCollation  one of the list of available collations
412
 * @return boolean true if import successful
413
 */
414
	public function SqlImport($sSqlDump,
415
	                          $sTablePrefix = '',
416
	                          $bPreserve    = true,
417
	                          $sEngine      = 'MyISAM',
418
	                          $sCollation   = 'utf8_unicode_ci')
419
	{
420
		$sCollation = ($sCollation != '' ? $sCollation : 'utf8_unicode_ci');
421
		$aCharset = preg_split('/_/', $sCollation, null, PREG_SPLIT_NO_EMPTY);
422
		$sEngine = 'ENGINE='.$sEngine.' DEFAULT CHARSET='.$aCharset[0].' COLLATE='.$sCollation;
423
		$sCollation = ' collate '.$sCollation;
424
		$retval = true;
425
		$this->error = '';
426
		$aSearch  = array('{TABLE_PREFIX}','{TABLE_ENGINE}', '{TABLE_COLLATION}');
427
		$aReplace = array($this->sTablePrefix, $sEngine, $sCollation);
428
		$sql = '';
429
		$aSql = file($sSqlDump);
430
//		$aSql[0] = preg_replace('/^\xEF\xBB\xBF/', '', $aSql[0]);
431
		$aSql[0] = preg_replace('/^[\xAA-\xFF]{3}/', '', $aSql[0]);
432
		while ( sizeof($aSql) > 0 ) {
433
			$sSqlLine = trim(array_shift($aSql));
434
			if (!preg_match('/^[-\/]+.*/', $sSqlLine)) {
435
				$sql = $sql.' '.$sSqlLine;
436
				if ((substr($sql,-1,1) == ';')) {
437
					$sql = trim(str_replace( $aSearch, $aReplace, $sql));
438
					if (!($bPreserve && preg_match('/^\s*DROP TABLE IF EXISTS/siU', $sql))) {
439
						if(!mysql_query($sql, $this->_db_handle)) {
440
							$retval = false;
441
							$this->error = mysql_error($this->_db_handle);
442
							unset($aSql);
443
							break;
444
						}
445
					}
446
					$sql = '';
447
				}
448
			}
449
		}
450
		return $retval;
451
	}
452

    
453
/**
454
 * retuns the type of the engine used for requested table
455
 * @param string $table name of the table, including prefix
456
 * @return boolean/string false on error, or name of the engine (myIsam/InnoDb)
457
 */
458
	public function getTableEngine($table)
459
	{
460
		$retVal = false;
461
		$mysqlVersion = mysql_get_server_info($this->_db_handle);
462
		$engineValue = (version_compare($mysqlVersion, '5.0') < 0) ? 'Type' : 'Engine';
463
		$sql = 'SHOW TABLE STATUS FROM `' . $this->_db_name . '` LIKE \'' . $table . '\'';
464
		if(($result = $this->query($sql, $this->_db_handle))) {
465
			if(($row = $result->fetchRow(MYSQL_ASSOC))) {
466
				$retVal = $row[$engineValue];
467
			}
468
		}
469
		return $retVal;
470
	}
471

    
472

    
473
} /// end of class database
474
// //////////////////////////////////////////////////////////////////////////////////// //
475
/**
476
 * WbDatabaseException
477
 *
478
 * @category     Core
479
 * @package      Core_database
480
 * @author       Werner v.d.Decken <wkl@isteam.de>
481
 * @copyright    Werner v.d.Decken <wkl@isteam.de>
482
 * @license      http://www.gnu.org/licenses/gpl.html   GPL License
483
 * @version      2.9.0
484
 * @revision     $Revision: 1974 $
485
 * @lastmodified $Date: 2013-10-04 01:35:37 +0200 (Fri, 04 Oct 2013) $
486
 * @description  Exceptionhandler for the WbDatabase and depending classes
487
 */
488
class WbDatabaseException extends AppException {}
489

    
490
define('MYSQL_SEEK_FIRST', 0);
491
define('MYSQL_SEEK_LAST', -1);
492

    
493
class mysql {
494

    
495
	private $result = null;
496
	private $_db_handle = null;
497
	// Run a query
498
	function query($statement, $dbHandle) {
499
		$this->_db_handle = $dbHandle;
500
		$this->result = @mysql_query($statement, $this->_db_handle);
501
		if($this->result === false) {
502
			if(DEBUG) {
503
				throw new WbDatabaseException(mysql_error($this->_db_handle));
504
			}else{
505
				throw new WbDatabaseException('Error in SQL-Statement');
506
			}
507
		}
508
		$this->error = mysql_error($this->_db_handle);
509
		return $this->result;
510
	}
511

    
512
	// Fetch num rows
513
	function numRows() {
514
		return mysql_num_rows($this->result);
515
	}
516

    
517
	// Fetch row  $typ = MYSQL_ASSOC, MYSQL_NUM, MYSQL_BOTH
518
	function fetchRow($typ = MYSQL_BOTH) {
519
		return mysql_fetch_array($this->result, $typ);
520
	}
521

    
522
	function rewind()
523
	{
524
		return $this->seekRow();
525
	}
526

    
527
	function seekRow( $position = MYSQL_SEEK_FIRST )
528
	{
529
		$pmax = $this->numRows() - 1;
530
		$p = (($position < 0 || $position > $pmax) ? $pmax : $position);
531
		return mysql_data_seek($this->result, $p);
532
	}
533

    
534
	// Get error
535
	function error() {
536
		if(isset($this->error)) {
537
			return $this->error;
538
		} else {
539
			return null;
540
		}
541
	}
542

    
543
}
544
// //////////////////////////////////////////////////////////////////////////////////// //
545
/* this function is placed inside this file temporarely until a better place is found */
546
/*  function to update a var/value-pair(s) in table ****************************
547
 *  nonexisting keys are inserted
548
 *  @param string $table: name of table to use (without prefix)
549
 *  @param mixed $key:    a array of key->value pairs to update
550
 *                        or a string with name of the key to update
551
 *  @param string $value: a sting with needed value, if $key is a string too
552
 *  @return bool:  true if any keys are updated, otherwise false
553
 */
554
	function db_update_key_value($table, $key, $value = '')
555
	{
556
		global $database;
557
		if( !is_array($key))
558
		{
559
			if( trim($key) != '' )
560
			{
561
				$key = array( trim($key) => trim($value) );
562
			} else {
563
				$key = array();
564
			}
565
		}
566
		$retval = true;
567
		foreach( $key as $index=>$val)
568
		{
569
			$index = strtolower($index);
570
			$sql = 'SELECT COUNT(`setting_id`) '
571
			     . 'FROM `'.TABLE_PREFIX.$table.'` '
572
			     . 'WHERE `name` = \''.$index.'\' ';
573
			if($database->get_one($sql))
574
			{
575
				$sql = 'UPDATE ';
576
				$sql_where = 'WHERE `name` = \''.$index.'\'';
577
			}else {
578
				$sql = 'INSERT INTO ';
579
				$sql_where = '';
580
			}
581
			$sql .= '`'.TABLE_PREFIX.$table.'` ';
582
			$sql .= 'SET `name` = \''.$index.'\', ';
583
			$sql .= '`value` = \''.$val.'\' '.$sql_where;
584
			if( !$database->query($sql) )
585
			{
586
				$retval = false;
587
			}
588
		}
589
		return $retval;
590
	}
(18-18/36)