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: 1887 $
29
 * @lastmodified $Date: 2013-03-12 21:42:14 +0100 (Tue, 12 Mar 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
	protected $sTablePrefix = '';
44
	protected $sCharset     = 'utf8';
45
	protected $connected    = false;
46
	protected $error        = '';
47
	protected $error_type   = '';
48
	protected $iQueryCount  = 0;
49

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

    
137
	// Disconnect from the database
138
	public function disconnect() {
139
		if($this->connected==true) {
140
			mysql_close($this->_db_handle);
141
			return true;
142
		} else {
143
			return false;
144
		}
145
	}
146

    
147
	// Run a query
148
	public function query($statement) {
149
		$this->iQueryCount++;
150
		$mysql = new mysql();
151
		$mysql->query($statement, $this->_db_handle);
152
		$this->set_error($mysql->error($this->_db_handle));
153
		if($mysql->error($this->_db_handle)) {
154
			return null;
155
		} else {
156
			return $mysql;
157
		}
158
	}
159

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

    
174
	// Set the DB error
175
	public function set_error($message = null) {
176
		global $TABLE_DOES_NOT_EXIST, $TABLE_UNKNOWN;
177
		$this->error = $message;
178
		if(strpos($message, 'no such table')) {
179
			$this->error_type = $TABLE_DOES_NOT_EXIST;
180
		} else {
181
			$this->error_type = $TABLE_UNKNOWN;
182
		}
183
	}
184

    
185
	// Return true if there was an error
186
	public function is_error() {
187
		return (!empty($this->error)) ? true : false;
188
	}
189

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

    
286
		}
287
		if( $number_fields == 0 )
288
		{
289
			return ($keys != $number_fields);
290
		}else
291
		{
292
			return ($keys == $number_fields);
293
		}
294
	}
295

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

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

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

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

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

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

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

    
464

    
465
} /// end of class database
466
// //////////////////////////////////////////////////////////////////////////////////// //
467
/**
468
 * WbDatabaseException
469
 *
470
 * @category     Core
471
 * @package      Core_database
472
 * @author       Werner v.d.Decken <wkl@isteam.de>
473
 * @copyright    Werner v.d.Decken <wkl@isteam.de>
474
 * @license      http://www.gnu.org/licenses/gpl.html   GPL License
475
 * @version      2.9.0
476
 * @revision     $Revision: 1887 $
477
 * @lastmodified $Date: 2013-03-12 21:42:14 +0100 (Tue, 12 Mar 2013) $
478
 * @description  Exceptionhandler for the WbDatabase and depending classes
479
 */
480
class WbDatabaseException extends AppException {}
481

    
482
define('MYSQL_SEEK_FIRST', 0);
483
define('MYSQL_SEEK_LAST', -1);
484

    
485
class mysql {
486

    
487
	private $result = null;
488
	private $_db_handle = null;
489
	// Run a query
490
	function query($statement, $dbHandle) {
491
		$this->_db_handle = $dbHandle;
492
		$this->result = mysql_query($statement, $this->_db_handle);
493
		$this->error = mysql_error($this->_db_handle);
494
		return $this->result;
495
	}
496

    
497
	// Fetch num rows
498
	function numRows() {
499
		return mysql_num_rows($this->result);
500
	}
501

    
502
	// Fetch row  $typ = MYSQL_ASSOC, MYSQL_NUM, MYSQL_BOTH
503
	function fetchRow($typ = MYSQL_BOTH) {
504
		return mysql_fetch_array($this->result, $typ);
505
	}
506

    
507
	function rewind()
508
	{
509
		return $this->seekRow();
510
	}
511

    
512
	function seekRow( $position = MYSQL_SEEK_FIRST )
513
	{
514
		$pmax = $this->numRows() - 1;
515
		$p = (($position < 0 || $position > $pmax) ? $pmax : $position);
516
		return mysql_data_seek($this->result, $p);
517
	}
518

    
519
	// Get error
520
	function error() {
521
		if(isset($this->error)) {
522
			return $this->error;
523
		} else {
524
			return null;
525
		}
526
	}
527

    
528
}
529
// //////////////////////////////////////////////////////////////////////////////////// //
530
/* this function is placed inside this file temporarely until a better place is found */
531
/*  function to update a var/value-pair(s) in table ****************************
532
 *  nonexisting keys are inserted
533
 *  @param string $table: name of table to use (without prefix)
534
 *  @param mixed $key:    a array of key->value pairs to update
535
 *                        or a string with name of the key to update
536
 *  @param string $value: a sting with needed value, if $key is a string too
537
 *  @return bool:  true if any keys are updated, otherwise false
538
 */
539
	function db_update_key_value($table, $key, $value = '')
540
	{
541
		global $database;
542
		if( !is_array($key))
543
		{
544
			if( trim($key) != '' )
545
			{
546
				$key = array( trim($key) => trim($value) );
547
			} else {
548
				$key = array();
549
			}
550
		}
551
		$retval = true;
552
		foreach( $key as $index=>$val)
553
		{
554
			$index = strtolower($index);
555
			$sql = 'SELECT COUNT(`setting_id`) '
556
			     . 'FROM `'.TABLE_PREFIX.$table.'` '
557
			     . 'WHERE `name` = \''.$index.'\' ';
558
			if($database->get_one($sql))
559
			{
560
				$sql = 'UPDATE ';
561
				$sql_where = 'WHERE `name` = \''.$index.'\'';
562
			}else {
563
				$sql = 'INSERT INTO ';
564
				$sql_where = '';
565
			}
566
			$sql .= '`'.TABLE_PREFIX.$table.'` ';
567
			$sql .= 'SET `name` = \''.$index.'\', ';
568
			$sql .= '`value` = \''.$val.'\' '.$sql_where;
569
			if( !$database->query($sql) )
570
			{
571
				$retval = false;
572
			}
573
		}
574
		return $retval;
575
	}
(13-13/30)