summaryrefslogtreecommitdiff
path: root/it_dbi.class
blob: 09557de7ed781384cb780d2cb69deb5fe9d65a2c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
<?php
/*
**	$Id$
**
**	Copyright (C) 1995-2007 by the ITools Authors.
**	This file is part of ITools - the Internet Tools Library
**
**	ITools is free software; you can redistribute it and/or modify
**	it under the terms of the GNU General Public License as published by
**	the Free Software Foundation; either version 3 of the License, or
**	(at your option) any later version.
**
**	ITools is distributed in the hope that it will be useful,
**	but WITHOUT ANY WARRANTY; without even the implied warranty of
**	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
**	GNU General Public License for more details.
**
**	You should have received a copy of the GNU General Public License
**	along with this program.  If not, see <http://www.gnu.org/licenses/>.
**
**	dbi.class - UltraFlexible Database Interface 3000
*/

class it_dbi
{
	# Default configuration of dbi class
	var $_defaultconfig = array
	(
		'db' => null,
		'server' => "localhost",
		'server_update' => null,
		'user' => "itools",
		'pw' => "",
		'safety' => 1,		# 0= never die, 1=die if query invalid, 2=die also if no results
		#'keyfield' => 'ID',	# Don't set to null here, filled later by _get_field_info()
		'classprefix' => "",
		'persistent' => false,
		'sqllog' => false,
	);

	var $_key;	# Key of currently loaded record or null (public readonly)
	var $_fields;	# Array of name => array(Field,Type,Null,Key,Default,Extra,Length) of fields (public readonly)
	var $_link;	# DB link identifier (private)


/**
 * Constructor: Initialize the DBI interface
 * @param $p optional array(key => value) of configuration data
 * @param $query Optional initial query to run
 */
function it_dbi($p = array(), $query = null)
{
	# Shortcut: String config means use this table with default values
	if (!is_array($p))
		$p = array('table' => $p);

	if ($p['home'])
		$p['db'] = strtr(it::match('/www/([^/]*)', $p['home']), '.-', '__');

	# If the global singleton defaults are for this db/server/server_update then use them.
	$dp = (array)$GLOBALS['it_dbi']->_p;
	if ((!isset($p['db']) || ($p['db'] == $dp['db'])) && (!isset($p['server']) || ($p['server'] == $dp['server'])) && (!isset($p['server_update']) || ($p['server_update'] == $dp['server_update'])))
		$p += $dp;

	# Combine our settings with user's defaults and class defaults
	$p += (array)$GLOBALS['it_dbi_defaultconfig'] + array('sqllog' => EDC('sqllog'), 'db' => $GLOBALS['ULTRADB']) + $this->_defaultconfig;
	unset($this->_defaultconfig);	# to shorten ED() output

	$p['dbid'] = "{$p['user']}@{$p['server']}:{$p['db']}";
	$this->_p = $p;

	if ($p['table'])		# Standard use: create a table object
	{
		$this->_p += $this->_get_field_info();	# Get $this->_fields and p[keyfield, autoincrement, randomid]

		if (is_array($query))
			$this->select($query);
		elseif (isset($query))
			$this->read($query);
	}
	elseif (!$GLOBALS['it_dbi'])	# Special use w/o table: create singleton to store settings
		$GLOBALS['it_dbi'] =& $this;
}


/**
 * Factory: Create classes of all database tables. Call statically.
 * @param $p array(key => value) of configuration data
 */
function createclasses($p = array())
{
	# Make sure singleton exists
	$dbi = $GLOBALS['it_dbi'] ? $GLOBALS['it_dbi'] : new it_dbi($p);

	$p += $dbi->_p;
	$p['dbid'] = "{$p['user']}@{$p['server']}:{$p['db']}";
	$dbi->_connect($p);

	if (!($tables = mysql_list_tables($p['db'], $dbi->_link)))
		$dbi->_fatal("it_dbi::createclasses(): can't list on tables \"{$p['db']}\"");

	for ($i = 0; $i < mysql_num_rows($tables); $i++)
		it_dbi::createclass(array('table' => mysql_tablename($tables, $i)) + $p);
}


/**
 * Convert table given by name into a class
 */
function createclass($p)
{
	# Shortcut: String config means use this table with default values
	if (!is_array($p))
		$p = array('table' => $p);

	$classname = $p['classprefix'] . $p['table'];

	if (substr($classname, 0, 4) != 'PMA_')	# It is designed behaviour that an error is generated if this class already exists!
	{
		$code = "class $classname extends it_dbi
		{
			function $classname(\$query = null, \$p = array())
			{
				\$p += " . var_export($p, true) . ";
				\$this->it_dbi(\$p, \$query);
			}
		}";

		debug("it_dbi::createclass('{$p['table']}'): creating class $classname", 5);
		eval($code);
	}
}


/**
 * INTERNAL: Connect to mysql server and maintain a global link cache
 */
function _connect($p = array())
{
	$p += $this->_p;
	if (!($this->_link = $GLOBALS['it_dbi']->_state[$p['dbid']]['link']))
	{
		# Use persistent connections but prevent reuse if only DB differs
		if (!$p['persistent'] || $GLOBALS['it_dbi']->_connected["{$p['server']}/{$p['user']}"]++)
			$this->_link = @mysql_connect($p['server'], $p['user'], $p['pw'], true);
		else
			$this->_link = @mysql_connect($p['server'], $p['user'], $p['pw']);

		if (!$this->_link)
		{
			# One retry after a short delay (always non-persistent)
			it::log('sqllog', "it_dbi(): retrying DB link (mysql_connect {$p['server']}, {$p['db']}): " . mysql_error());
			sleep(1);
			$this->_link = @mysql_connect($p['server'], $p['user'], $p['pw'], true);
		}

		if (!$this->_link)
			$this->_fatal("it_dbi(): can't create DB link (mysql_connect {$p['user']}@{$p['server']}, {$p['db']})");

		if (!(@mysql_select_db($p['db'], $this->_link)))
			$this->_fatal("it_dbi(): can't select database \"{$p['db']}\"");

		$GLOBALS['it_dbi']->_state[$p['dbid']]['link'] = $this->_link;
	}
}


/**
 * INTERNAL: construct SQL SET clause of changed values from member vars and tags array.
 * Merge current values into $tags. Modifies caller's array (callers rely on it)!
 */
function _set(&$tags)
{
	# DEPRECATED BEHAVIOUR: Add member vars to tags, considering unquoted fields
	foreach (get_object_vars($this) as $field => $value)
		# Don't use isset($tags[$field]) (would not handle null values correctly)
		if (isset($this->_fields[$field]) && !array_key_exists('-'.$field, $tags) && !array_key_exists($field, $tags))
		{
				$tags[$field] = $value;
				if ($this->_data && ($value != $this->_data[$field]))
					it::error("it_dbi::_set() would take value '$value' from this->$field:" . D($this, $tags));
		}

	# Create SQL
	$r = array();
	foreach((array)$tags as $key => $value)
	{
		if (substr($key, 0, 1) == '-')		# Unquoted value (always added)
			$r[] = substr($key, 1)."=$value";
		elseif (!isset($this->_data) || ($value !== $this->_data[$key]))	# Add to SQL if value has changed
			$r[] = "$key=".(isset($value) ? "'".mysql_real_escape_string($value, $this->_link)."'" : 'NULL');
	}

	return $r ? 'SET '.implode(', ', $r) : '';
}


/**
 * Create an SQL query (the stuff after 'WHERE') according to an array of selection criteria.
 *
 * Example:
 * $sql = $table->_where(array('Type' => 'bar',
 *    'Date >=' => '1999-01-01', '-Date <' => 'NOW()',
 *    'User NI' => 'chris'), 'ORDER BY Date');
 *
 * @param $params optional array of fieldname => value tupels. These are ANDed to form a WHERE clause.
 *   fieldname can contain an operator (separated by space), the default operator is '='.
 *   The special operator 'NI' specifies that the argument must be contained in a comma-separated list.
 * @param $link DB link used to escape values
 * @param $omit_where Do not add 'WHERE ' to result
 * @return The generated SQL clause
 * @see select(), iterate()
 */
function _where($params = "", $link = null, $omit_where = false)
{
	if (is_array($params) && (count($params) > 0))
	{
		$query = '';
		$sep = '';

		foreach($params as $field => $value)
		{
			if (is_int($field)) /* no key specified; just append */
			{
				if ($field === $value)	/* ignore array(1 => 1) et al */
					continue;

				$query .= " $value";
			}
			else
			{
				$needs_where = true;

				if (!isset($value))
				{
					$op = 'IS';
					$qval = 'NULL';
				}
				else
				{
					if (preg_match('/^(\S+)\s+(\S.*)$/', $field, $regs))
					{
						$field = $regs[1];
						$op = strtoupper($regs[2]);
					}
					else
						$op = '=';

					# If field name starts with '-', the raw value is taken, no escaping is done and no quotes are put around it.
					if (substr($field, 0, 1) == '-')
					{
						$field = substr($field, 1);	# Strip that '-' sign
						$qval = $value;
					}
					else if (!is_array($value))
						$qval = "'" . ($link ? mysql_real_escape_string((string)$value, $link) : mysql_real_escape_string((string)$value)) . "'";
				}

				switch ($op)
				{
					case 'NI':
						$query .= $sep."CONCAT(',',$field,',') LIKE '%,$value,%'";
						break;

					case 'IN':
					case 'NOT IN':
						if (is_array($value))
						{
							if ($value)
							{
								$qvals = array();

								foreach ($value as $val)
									$qvals[] = $link ? mysql_real_escape_string($val, $link) : mysql_real_escape_string($val);

								$query .= "$sep$field $op ('" . join("','", $qvals) . "')";	 # null is mapped to ''
							}
							else
								$query .= $sep . "0";

							break;
						}
						/* FALLTHROUGH */

					default:
						if (isset($qval))
							$query .= "$sep$field $op $qval";
						else
							it::fatal('Undefined $qval when constructing query due to invalid $value (array)');
						break;
				}
				$sep = ' AND ';
			}
		}

		if ($needs_where && !$omit_where)
			$query = "WHERE $query";
	}

	return $query;
}


/**
 * Internal: Output class name::error message and terminate execution.
 */
function _fatal($text)
{
	if ($this->_link && ($t = mysql_error($this->_link)))
		$mysql_error = ", mysql_error=$t";

	it::fatal(get_class($this).'::'.$text . $mysql_error);
	/* NOT REACHED */
}


/**
 * Post-process data after reading a record.
 * This is a stub-function that can be overloaded.
 */
function _read_post_process()
{
}


/**
 * Pre-process data before writing a record.
 * This is a stub-function that can be overloaded.
 * @param $tags Reference to update/create tags, can be modified as needed
 */
function _write_pre_process(&$tags)
{
}


/**
 * Clear record
 */
function clear($pp = true)
{
	foreach ((array)$this->_fields as $key => $dummy)
		unset($this->$key);
	unset($this->_data);
	unset($this->_key);
	$pp && $this->_read_post_process();
}


/**
 * Semi-internal: send a raw SQL query and return mysql result value
 * @param $query complete SQL query string
 * @return raw MySQL result. May die if query fails and safety is big enough
 */
function query($query)
{
	$start = gettimeofday();

	if ($this->_p['server_update'] && !preg_match('/^(EXPLAIN|SELECT|SHOW) /i', $query))
	{
		debug("switching to update server \"{$this->_p['server_update']}\"", 5);
		$this->_p['server'] = $this->_p['server_update'];
		unset($this->_p['server_update'], $this->_link);
	}

	$this->_connect();	# must be called after update server switching code

	debug($this->_p['dbid'] . '.' . get_class($this) . "::query(\"$query\")", 4);

	if (!($result = mysql_query($query, $this->_link)) && $this->_p['safety'])
	{
		if (($this->_p['safety'] < 2) && (mysql_errno($this->_link) == 1062)) # Duplicate entry
			return false;

		$error = mysql_errno($this->_link).' ('.mysql_error($this->_link).')';
		$res = mysql_fetch_row(mysql_query('select database()', $this->_link));
		$this->_fatal("query(\"$query\") on {$res[0]} failed: $error");
	}


	if ($this->_p['sqllog'])
	{
		$end = gettimeofday();
		$msec = round(($end['sec'] - $start['sec']) * 1000 + ($end['usec'] - $start['usec']) / 1000);
		it::log('sqllog', "$msec\t$query");
	}

	return $result;
}


/**
 * Read a single record by primary key, not destroying old query result $this->_result
 * @param $id primary key. If null, record is cleared
 * @return True if record could be read, false if not.
 */
function read($id=null)
{
	$mres = $this->_result;
	$result = $this->select(array($this->_p['keyfield'] => $id));
	$this->_result = $mres;
	return $result;
}


/**
 * Select a set of records from table and fetch the first one
 * @param $query Optional array of (field => value) or (int => sqlstring) pairs. Defaults to null (select all records)
 *	         Can contain magic field 'SELECT' for things like 'COUNT(*)' or 'DISTINCT foo', defaults to '*'
 *	         Can contain magic field 'JOIN' for things like 'tableA LEFT JOIN tableB ON a=b', defaults to table name
 *	         If magic field 'CALC_FOUND_ROWS' is true, sets member var _found_rows to number of matching rows without LIMIT
 *	         If magic field 'NOFETCH' is true, then the first row is not prefetched (e.g. when directly using _result)
 * @return Number of matching rows, use iterate() to fetch the next record
 * @see it_dbi::iterate(), it_dbi::_where()
 */
function select($query = null)
{
	$this->_connect();

	$result = 0;
	$calc_found_rows = false;

	$what = '*';
	if (isset($query['SELECT']))
	{
		$what = $query['SELECT'];
		unset($query['SELECT']);
	}

	$join = $this->_p['table'];
	if (isset($query['JOIN'])) # WARNING: this field gets abused for "tablename USE INDEX (fast2)
	{
		$join = $query['JOIN'];
		unset($query['JOIN']);
	}

	unset($this->_found_rows);
	if (isset($query['CALC_FOUND_ROWS']) && $query['CALC_FOUND_ROWS'])
	{
		$calc_found_rows = true;
		$what = 'SQL_CALC_FOUND_ROWS '.$what;
		unset($query['CALC_FOUND_ROWS']);
	}

	$nofetch = $this->_nofetch = $query['NOFETCH'];
	unset($query['NOFETCH']);

	if ($this->_result = $this->query($sql = "SELECT $what FROM $join " . $this->_where($query, $this->_link)))
		$result = mysql_num_rows($this->_result);

	if ($calc_found_rows)
	{
		list($count) = mysql_fetch_row($this->query('SELECT FOUND_ROWS()'));
		$this->_found_rows = intval($count);
	}

	if (!$this->iterate() && ($this->_p['safety'] >= 2))
		$this->_fatal("select(): query produced no results: \"$sql\"");

	$this->_nofetch = !$nofetch;

	return $result;
}


/**
 * Iterate through select()ed records
 * @return true if another record was fetched, false if no more records
 * @see it_dbi::select()
 */
function iterate()
{
	if (!$this->_nofetch)
	{
		$this->clear(false);
		if ($this->_data = mysql_fetch_assoc($this->_result))
		{
			if (!empty($this->_p['keyfield']))
				$this->_key = $this->_data[$this->_p['keyfield']];

			foreach ($this->_data as $key => $value)
				$this->$key = $value;
		}

		$this->_read_post_process();
	}
	else
		$this->_nofetch = false;

	return (bool)$this->_data;
}


/**
 * Insert a record into table. Values are taken from member vars and $tags.
 * After inserting, all values are valid (record is read back).
 * Does not destroy internal state of last select() call
 * @param $tags Additional key => value pairs (these have priority over member vars)
 */
function insert($tags = array(), $command = "INSERT")
{
	$this->_connect();

	/* Pre-processing, $tags is passed by reference and may be modified here */
	$this->_write_pre_process($tags);

	unset($this->_data);		# All new value set
	$set = $this->_set($tags);	# Update $tags (!) and generate SQL

	if ($this->_p['randomid'] && !isset($tags[$this->_p['keyfield']]))
	{
		$tags[$this->_p['keyfield']] = md5(uniqid(mt_rand()));
		$set = $this->_set($tags);	# Generate new SQL containing ID
	}

	if ($result = $this->query("$command INTO {$this->_p['table']} " . $set))
	{
		$id = ($this->_p['autoincrement'] && !isset($tags[$this->_p['keyfield']])) ? mysql_insert_id($this->_link) : $tags[$this->_p['keyfield']];
		if (!$this->read($id) && $this->_p['safety'])
			$this->_fatal("insert(): can't read record back (key truncated?), id=\"$id\"");
	}

	return $result;
}


/**
 * Replace a record in a table
 * @param $tags Additional key => value pairs (these have priority over member vars)
 * Does not destroy internal state of last select() call
 * @see it_dbi::insert()
 */
function replace($tags = array())
{
	return $this->insert($tags, "REPLACE");
}


/**
 * Update a record in a table
 * @param $tags Additional key => value pairs (these have priority over member vars)
 * Does not destroy internal state of last select() call
 */
function update($tags = array(), $query = null)
{
	$this->_connect();
	$result = true;

	/* Pre-processing, $tags is passed by reference and may be modified here */
	$this->_write_pre_process($tags);

	if (!$query && !empty($this->_p['keyfield']))
		$query = array($this->_p['keyfield'] => $this->_data[$this->_p['keyfield']]);

	if ($set = $this->_set($tags))
		if ($result = $this->query("UPDATE {$this->_p['table']} $set " . $this->_where($query, $this->_link)))
		{
			if (array_key_exists($this->_p['keyfield'], $tags))	# Did we just update the key?
				$this->_key = $tags[$this->_p['keyfield']];

			if ($this->read($this->_key))
				$this->_nofetch = false; # So we can do while(iterate()) update();
		}

	return $result;
}


/**
 * Delete a record
 * Does not destroy query result $this->_result
 * @param $query optional query for WHERE, default: delete currently loaded record
 * @return number of deleted records
 */
function delete($query = null)
{
	$this->_connect();
	$result = 0;

	if (!$query && $this->_p['keyfield'])
	{
		$query = array($this->_p['keyfield'] => $this->_key);
		$this->clear();
	}

	if ($query && $this->query("DELETE FROM {$this->_p['table']} " . $this->_where($query, $this->_link)))
		$result = mysql_affected_rows($this->_link);

	return $result;
}


/**
 * INTERNAL: Store information about a table's fields in $this->_fields, possibly from cache.
 * @return array(keyfield, autoincrement, randomid)
 */
function _get_field_info()
{
	$result = array();

	if (!($this->_fields = $GLOBALS['it_dbi']->_state[$this->_p['dbid']]['fields'][$this->_p['table']]))
	{
		debug("it_dbi(): no fields for {$this->_p['dbid']}.{$this->_p['table']}, calculating.", 5);
		for ($res = $this->query('SHOW COLUMNS FROM ' . $this->_p['table']); $field = mysql_fetch_assoc($res);)
			$this->_fields[$field['Field']] = $field + array('Length' => intval(it::match('\d+', $field['Type'])));

		$GLOBALS['it_dbi']->_state[$this->_p['dbid']]['fields'][$this->_p['table']] = $this->_fields;
	}

	foreach($this->_fields as $field)
	{
		if ($field['Key'] == 'PRI')
		{
			$result = array('keyfield' => $field['Field'], 'autoincrement' => (strpos($field['Extra'], "auto_increment") !== false),
					'randomid' => (strpos($field['Type'], "char") !== false));
			break;
		}
	}

	unset($GLOBALS['it_dbi']->_p['table'], $GLOBALS['it_dbi']->_p['keyfield']);	# Remove cruft
	return $result;
}

} /* End class it_dbi */

?>