· 6 years ago · Aug 03, 2019, 02:44 AM
1<?php
2
3/**
4* A database layer class that relies on the MySQLi PHP extension.
5*
6* @copyright (C) 2008-2012 PunBB, partially based on code (C) 2008-2009 FluxBB.org
7* @license http://www.gnu.org/licenses/gpl.html GPL version 2 or higher
8* @package PunBB
9*/
10
11
12// Make sure we have built in support for MySQL
13if (!function_exists('mysqli_connect'))
14 exit('This PHP environment doesn\'t have Improved MySQL (mysqli) support built in. Improved MySQL support is required if you want to use a MySQL 4.1 (or later) database to run this forum. Consult the PHP documentation for further assistance.');
15
16
17class DBLayer
18{
19 var $prefix;
20 var $link_id;
21 var $query_result;
22 var $public;
23 var $saved_queries = array();
24 var $num_queries = 0;
25
26 var $datatype_transformations = array(
27 '/^SERIAL$/' => 'INT(10) UNSIGNED AUTO_INCREMENT'
28 );
29
30
31 public function __construct($db_host, $db_username, $db_password, $db_name, $db_prefix, $foo)
32 {
33 $this->prefix = $db_prefix;
34
35 // Was a custom port supplied with $db_host?
36 if (strpos($db_host, ':') !== false)
37 list($db_host, $db_port) = explode(':', $db_host);
38
39 if (isset($db_port))
40 $this->link_id = @mysqli_connect($db_host, $db_username, $db_password, $db_name, $db_port);
41 else
42 $this->link_id = @mysqli_connect($db_host, $db_username, $db_password, $db_name);
43
44 if (!$this->link_id)
45 error('Unable to connect to MySQL and select database.<br />MySQL reported: '.mysqli_connect_error(), __FILE__, __LINE__);
46
47 // Setup the client-server character set (UTF-8)
48 if (!defined('FORUM_NO_SET_NAMES'))
49 $this->set_names('utf8');
50
51 return $this->link_id;
52 }
53
54
55 function start_transaction()
56 {
57 return;
58 }
59
60
61 function end_transaction()
62 {
63 return;
64 }
65
66
67 function query($sql, $unbuffered = false)
68 {
69 if (strlen($sql) > FORUM_DATABASE_QUERY_MAXIMUM_LENGTH)
70 exit('Insane query. Aborting.');
71
72 if (defined('FORUM_SHOW_QUERIES') || defined('FORUM_DEBUG'))
73 $q_start = forum_microtime();
74
75 $this->query_result = @mysqli_query($this->link_id, $sql);
76
77 if ($this->query_result)
78 {
79 if (defined('FORUM_SHOW_QUERIES') || defined('FORUM_DEBUG'))
80 $this->saved_queries[] = array($sql, sprintf('%.5f', forum_microtime() - $q_start));
81
82 ++$this->num_queries;
83
84 return $this->query_result;
85 }
86 else
87 {
88 if (defined('FORUM_SHOW_QUERIES') || defined('FORUM_DEBUG'))
89 $this->saved_queries[] = array($sql, 0);
90
91 return false;
92 }
93 }
94
95
96 function query_build($query, $return_query_string = false, $unbuffered = false)
97 {
98 $sql = '';
99
100 if (isset($query['SELECT']))
101 {
102 $sql = 'SELECT '.$query['SELECT'].' FROM '.(isset($query['PARAMS']['NO_PREFIX']) ? '' : $this->prefix).$query['FROM'];
103
104 if (isset($query['JOINS']))
105 {
106 foreach ($query['JOINS'] as $cur_join)
107 $sql .= ' '.key($cur_join).' '.(isset($query['PARAMS']['NO_PREFIX']) ? '' : $this->prefix).current($cur_join).' ON '.$cur_join['ON'];
108 }
109
110 if (!empty($query['WHERE']))
111 $sql .= ' WHERE '.$query['WHERE'];
112 if (!empty($query['GROUP BY']))
113 $sql .= ' GROUP BY '.$query['GROUP BY'];
114 if (!empty($query['HAVING']))
115 $sql .= ' HAVING '.$query['HAVING'];
116 if (!empty($query['ORDER BY']))
117 $sql .= ' ORDER BY '.$query['ORDER BY'];
118 if (!empty($query['LIMIT']))
119 $sql .= ' LIMIT '.$query['LIMIT'];
120 }
121 else if (isset($query['INSERT']))
122 {
123 $sql = 'INSERT INTO '.(isset($query['PARAMS']['NO_PREFIX']) ? '' : $this->prefix).$query['INTO'];
124
125 if (!empty($query['INSERT']))
126 $sql .= ' ('.$query['INSERT'].')';
127
128 if (is_array($query['VALUES']))
129 $sql .= ' VALUES('.implode('),(', $query['VALUES']).')';
130 else
131 $sql .= ' VALUES('.$query['VALUES'].')';
132 }
133 else if (isset($query['UPDATE']))
134 {
135 $query['UPDATE'] = (isset($query['PARAMS']['NO_PREFIX']) ? '' : $this->prefix).$query['UPDATE'];
136
137 $sql = 'UPDATE '.$query['UPDATE'].' SET '.$query['SET'];
138
139 if (!empty($query['WHERE']))
140 $sql .= ' WHERE '.$query['WHERE'];
141 }
142 else if (isset($query['DELETE']))
143 {
144 $sql = 'DELETE FROM '.(isset($query['PARAMS']['NO_PREFIX']) ? '' : $this->prefix).$query['DELETE'];
145
146 if (!empty($query['WHERE']))
147 $sql .= ' WHERE '.$query['WHERE'];
148 }
149 else if (isset($query['REPLACE']))
150 {
151 $sql = 'REPLACE INTO '.(isset($query['PARAMS']['NO_PREFIX']) ? '' : $this->prefix).$query['INTO'];
152
153 if (!empty($query['REPLACE']))
154 $sql .= ' ('.$query['REPLACE'].')';
155
156 $sql .= ' VALUES('.$query['VALUES'].')';
157 }
158
159 return ($return_query_string) ? $sql : $this->query($sql, $unbuffered);
160 }
161
162
163 function result($query_id = 0, $row = 0, $col = 0)
164 {
165 if ($query_id)
166 {
167 if ($row)
168 @mysqli_data_seek($query_id, $row);
169
170 $cur_row = @mysqli_fetch_row($query_id);
171 return $cur_row[$col];
172 }
173 else
174 return false;
175 }
176
177
178 function fetch_assoc($query_id = 0)
179 {
180 return ($query_id) ? @mysqli_fetch_assoc($query_id) : false;
181 }
182
183
184 function fetch_row($query_id = 0)
185 {
186 return ($query_id) ? @mysqli_fetch_row($query_id) : false;
187 }
188
189
190 function num_rows($query_id = 0)
191 {
192 return ($query_id) ? @mysqli_num_rows($query_id) : false;
193 }
194
195
196 function affected_rows()
197 {
198 return ($this->link_id) ? @mysqli_affected_rows($this->link_id) : false;
199 }
200
201
202 function insert_id()
203 {
204 return ($this->link_id) ? @mysqli_insert_id($this->link_id) : false;
205 }
206
207
208 function get_num_queries()
209 {
210 return $this->num_queries;
211 }
212
213
214 function get_saved_queries()
215 {
216 return $this->saved_queries;
217 }
218
219
220 function free_result($query_id = false)
221 {
222 return ($query_id) ? @mysqli_free_result($query_id) : false;
223 }
224
225
226 function escape($str)
227 {
228 return is_array($str) ? '' : mysqli_real_escape_string($this->link_id, $str);
229 }
230
231
232 function error()
233 {
234 $result['error_sql'] = @current(@end($this->saved_queries));
235 $result['error_no'] = @mysqli_errno($this->link_id);
236 $result['error_msg'] = @mysqli_error($this->link_id);
237
238 return $result;
239 }
240
241
242 function close()
243 {
244 if ($this->link_id)
245 {
246 if ($this->query_result)
247 @mysqli_free_result($this->query_result);
248
249 return @mysqli_close($this->link_id);
250 }
251 else
252 return false;
253 }
254
255
256 function set_names($names)
257 {
258 return $this->query('SET NAMES \''.$this->escape($names).'\'');
259 }
260
261
262 function get_version()
263 {
264 $result = $this->query('SELECT VERSION()');
265
266 return array(
267 'name' => 'MySQL Improved',
268 'version' => preg_replace('/^([^-]+).*$/', '\\1', $this->result($result))
269 );
270 }
271
272
273 function table_exists($table_name, $no_prefix = false)
274 {
275 $result = $this->query('SHOW TABLES LIKE \''.($no_prefix ? '' : $this->prefix).$this->escape($table_name).'\'');
276 return $this->num_rows($result) > 0;
277 }
278
279
280 function field_exists($table_name, $field_name, $no_prefix = false)
281 {
282 $result = $this->query('SHOW COLUMNS FROM '.($no_prefix ? '' : $this->prefix).$table_name.' LIKE \''.$this->escape($field_name).'\'');
283 return $this->num_rows($result) > 0;
284 }
285
286
287 function index_exists($table_name, $index_name, $no_prefix = false)
288 {
289 $exists = false;
290
291 $result = $this->query('SHOW INDEX FROM '.($no_prefix ? '' : $this->prefix).$table_name);
292 while ($cur_index = $this->fetch_assoc($result))
293 {
294 if ($cur_index['Key_name'] == ($no_prefix ? '' : $this->prefix).$table_name.'_'.$index_name)
295 {
296 $exists = true;
297 break;
298 }
299 }
300
301 return $exists;
302 }
303
304
305 function create_table($table_name, $schema, $no_prefix = false)
306 {
307 if ($this->table_exists($table_name, $no_prefix))
308 return;
309
310 $query = 'CREATE TABLE '.($no_prefix ? '' : $this->prefix).$table_name." (\n";
311
312 // Go through every schema element and add it to the query
313 foreach ($schema['FIELDS'] as $field_name => $field_data)
314 {
315 $field_data['datatype'] = preg_replace(array_keys($this->datatype_transformations), array_values($this->datatype_transformations), $field_data['datatype']);
316
317 $query .= $field_name.' '.$field_data['datatype'];
318
319 if (isset($field_data['collation']))
320 $query .= 'CHARACTER SET utf8 COLLATE utf8_'.$field_data['collation'];
321
322 if (!$field_data['allow_null'])
323 $query .= ' NOT NULL';
324
325 if (isset($field_data['default']))
326 $query .= ' DEFAULT '.$field_data['default'];
327
328 $query .= ",\n";
329 }
330
331 // If we have a primary key, add it
332 if (isset($schema['PRIMARY KEY']))
333 $query .= 'PRIMARY KEY ('.implode(',', $schema['PRIMARY KEY']).'),'."\n";
334
335 // Add unique keys
336 if (isset($schema['UNIQUE KEYS']))
337 {
338 foreach ($schema['UNIQUE KEYS'] as $key_name => $key_fields)
339 $query .= 'UNIQUE KEY '.($no_prefix ? '' : $this->prefix).$table_name.'_'.$key_name.'('.implode(',', $key_fields).'),'."\n";
340 }
341
342 // Add indexes
343 if (isset($schema['INDEXES']))
344 {
345 foreach ($schema['INDEXES'] as $index_name => $index_fields)
346 $query .= 'KEY '.($no_prefix ? '' : $this->prefix).$table_name.'_'.$index_name.'('.implode(',', $index_fields).'),'."\n";
347 }
348
349 // We remove the last two characters (a newline and a comma) and add on the ending
350 $query = substr($query, 0, strlen($query) - 2)."\n".') ENGINE = '.(isset($schema['ENGINE']) ? $schema['ENGINE'] : 'MyISAM').' CHARACTER SET utf8';
351
352 $this->query($query) or error(__FILE__, __LINE__);
353 }
354
355
356 function drop_table($table_name, $no_prefix = false)
357 {
358 if (!$this->table_exists($table_name, $no_prefix))
359 return;
360
361 $this->query('DROP TABLE '.($no_prefix ? '' : $this->prefix).$table_name) or error(__FILE__, __LINE__);
362 }
363
364
365 function add_field($table_name, $field_name, $field_type, $allow_null, $default_value = null, $after_field = null, $no_prefix = false)
366 {
367 if ($this->field_exists($table_name, $field_name, $no_prefix))
368 return;
369
370 $field_type = preg_replace(array_keys($this->datatype_transformations), array_values($this->datatype_transformations), $field_type);
371
372 if ($default_value !== null && !is_int($default_value) && !is_float($default_value))
373 $default_value = '\''.$this->escape($default_value).'\'';
374
375 $this->query('ALTER TABLE '.($no_prefix ? '' : $this->prefix).$table_name.' ADD '.$field_name.' '.$field_type.($allow_null ? ' ' : ' NOT NULL').($default_value !== null ? ' DEFAULT '.$default_value : ' ').($after_field != null ? ' AFTER '.$after_field : '')) or error(__FILE__, __LINE__);
376 }
377
378
379 function alter_field($table_name, $field_name, $field_type, $allow_null, $default_value = null, $after_field = null, $no_prefix = false)
380 {
381 if (!$this->field_exists($table_name, $field_name, $no_prefix))
382 return;
383
384 $field_type = preg_replace(array_keys($this->datatype_transformations), array_values($this->datatype_transformations), $field_type);
385
386 if ($default_value !== null && !is_int($default_value) && !is_float($default_value))
387 $default_value = '\''.$this->escape($default_value).'\'';
388
389 $this->query('ALTER TABLE '.($no_prefix ? '' : $this->prefix).$table_name.' MODIFY '.$field_name.' '.$field_type.($allow_null ? ' ' : ' NOT NULL').($default_value !== null ? ' DEFAULT '.$default_value : ' ').($after_field != null ? ' AFTER '.$after_field : '')) or error(__FILE__, __LINE__);
390 }
391
392
393 function drop_field($table_name, $field_name, $no_prefix = false)
394 {
395 if (!$this->field_exists($table_name, $field_name, $no_prefix))
396 return;
397
398 $this->query('ALTER TABLE '.($no_prefix ? '' : $this->prefix).$table_name.' DROP '.$field_name) or error(__FILE__, __LINE__);
399 }
400
401
402 function add_index($table_name, $index_name, $index_fields, $unique = false, $no_prefix = false)
403 {
404 if ($this->index_exists($table_name, $index_name, $no_prefix))
405 return;
406
407 $this->query('ALTER TABLE '.($no_prefix ? '' : $this->prefix).$table_name.' ADD '.($unique ? 'UNIQUE ' : '').'INDEX '.($no_prefix ? '' : $this->prefix).$table_name.'_'.$index_name.' ('.implode(',', $index_fields).')') or error(__FILE__, __LINE__);
408 }
409
410
411 function drop_index($table_name, $index_name, $no_prefix = false)
412 {
413 if (!$this->index_exists($table_name, $index_name, $no_prefix))
414 return;
415
416 $this->query('ALTER TABLE '.($no_prefix ? '' : $this->prefix).$table_name.' DROP INDEX '.($no_prefix ? '' : $this->prefix).$table_name.'_'.$index_name) or error(__FILE__, __LINE__);
417 }