Test Failed
Push — master ( d17d93...45248a )
by Joe
03:41
created
src/Mysqli/Db.php 1 patch
Indentation   +485 added lines, -485 removed lines patch added patch discarded remove patch
@@ -19,494 +19,494 @@
 block discarded – undo
19 19
  */
20 20
 class Db extends Generic implements Db_Interface
21 21
 {
22
-    /**
23
-     * @var string
24
-     */
25
-    public $type = 'mysqli';
26
-
27
-    /**
28
-     * alias function of select_db, changes the database we are working with.
29
-     *
30
-     * @param string $database the name of the database to use
31
-     * @return void
32
-     */
33
-    public function useDb($database)
34
-    {
35
-        $this->selectDb($database);
36
-    }
37
-
38
-    /**
39
-     * changes the database we are working with.
40
-     *
41
-     * @param string $database the name of the database to use
42
-     * @return void
43
-     */
44
-    public function selectDb($database)
45
-    {
46
-        $this->connect();
47
-        mysqli_select_db($this->linkId, $database);
48
-    }
49
-
50
-    /* public: connection management */
51
-
52
-    /**
53
-     * Db::connect()
54
-     * @param string $database
55
-     * @param string $host
56
-     * @param string $user
57
-     * @param string $password
58
-     * @return int|\mysqli
59
-     */
60
-    public function connect($database = '', $host = '', $user = '', $password = '', $port = '')
61
-    {
62
-        /* Handle defaults */
63
-        if ($database == '') {
64
-            $database = $this->database;
65
-        }
66
-        if ($host == '') {
67
-            $host = $this->host;
68
-        }
69
-        if ($user == '') {
70
-            $user = $this->user;
71
-        }
72
-        if ($password == '') {
73
-            $password = $this->password;
74
-        }
75
-        if ($port == '') {
76
-            $port = $this->port;
77
-        }
78
-        /* establish connection, select database */
79
-        if (!is_object($this->linkId)) {
80
-            $this->connectionAttempt++;
81
-            if ($this->connectionAttempt >= $this->maxConnectErrors - 1) {
82
-                error_log("MySQLi Connection Attempt #{$this->connectionAttempt}/{$this->maxConnectErrors}");
83
-            }
84
-            if ($this->connectionAttempt >= $this->maxConnectErrors) {
85
-                $this->halt("connect($host, $user, \$password) failed. ".$this->linkId->connect_error);
86
-                return 0;
87
-            }
88
-            $this->linkId = mysqli_init();
89
-            $this->linkId->options(MYSQLI_INIT_COMMAND, "SET NAMES {$this->characterSet} COLLATE {$this->collation}, COLLATION_CONNECTION = {$this->collation}, COLLATION_DATABASE = {$this->collation}");
90
-            if (!$this->linkId->real_connect($host, $user, $password, $database, $port != '' ? $port : NULL)) {
91
-                $this->halt("connect($host, $user, \$password) failed. ".$this->linkId->connect_error);
92
-                return 0;
93
-            }
94
-            $this->linkId->set_charset($this->characterSet);
95
-            if ($this->linkId->connect_errno) {
96
-                $this->halt("connect($host, $user, \$password) failed. ".$this->linkId->connect_error);
97
-                return 0;
98
-            }
99
-        }
100
-        return $this->linkId;
101
-    }
102
-
103
-    /**
104
-     * Db::disconnect()
105
-     * @return bool
106
-     */
107
-    public function disconnect()
108
-    {
109
-        $return = !is_int($this->linkId) && method_exists($this->linkId, 'close') ? $this->linkId->close() : false;
110
-        $this->linkId = 0;
111
-        return $return;
112
-    }
113
-
114
-    /**
115
-     * @param $string
116
-     * @return string
117
-     */
118
-    public function real_escape($string = '')
119
-    {
120
-        if ((!is_resource($this->linkId) || $this->linkId == 0) && !$this->connect()) {
121
-            return $this->escape($string);
122
-        }
123
-        return mysqli_real_escape_string($this->linkId, $string);
124
-    }
125
-
126
-    /**
127
-     * discard the query result
128
-     * @return void
129
-     */
130
-    public function free()
131
-    {
132
-        if (is_resource($this->queryId)) {
133
-            @mysqli_free_result($this->queryId);
134
-        }
135
-        $this->queryId = 0;
136
-    }
137
-
138
-    /**
139
-     * Db::queryReturn()
140
-     *
141
-     * Sends an SQL query to the server like the normal query() command but iterates through
142
-     * any rows and returns the row or rows immediately or FALSE on error
143
-     *
144
-     * @param mixed $query SQL Query to be used
145
-     * @param string $line optionally pass __LINE__ calling the query for logging
146
-     * @param string $file optionally pass __FILE__ calling the query for logging
147
-     * @return mixed FALSE if no rows, if a single row it returns that, if multiple it returns an array of rows, associative responses only
148
-     */
149
-    public function queryReturn($query, $line = '', $file = '')
150
-    {
151
-        $this->query($query, $line, $file);
152
-        if ($this->num_rows() == 0) {
153
-            return false;
154
-        } elseif ($this->num_rows() == 1) {
155
-            $this->next_record(MYSQLI_ASSOC);
156
-            return $this->Record;
157
-        } else {
158
-            $out = [];
159
-            while ($this->next_record(MYSQLI_ASSOC)) {
160
-                $out[] = $this->Record;
161
-            }
162
-            return $out;
163
-        }
164
-    }
165
-
166
-    /**
167
-     * db:qr()
168
-     *
169
-     *  alias of queryReturn()
170
-     *
171
-     * @param mixed $query SQL Query to be used
172
-     * @param string $line optionally pass __LINE__ calling the query for logging
173
-     * @param string $file optionally pass __FILE__ calling the query for logging
174
-     * @return mixed FALSE if no rows, if a single row it returns that, if multiple it returns an array of rows, associative responses only
175
-     */
176
-    public function qr($query, $line = '', $file = '')
177
-    {
178
-        return $this->queryReturn($query, $line, $file);
179
-    }
180
-
181
-    /**
182
-     * creates a prepaired statement from query
183
-     *
184
-     * @param string $query sql query like INSERT INTO table (col) VALUES (?)  or  SELECT * from table WHERE col1 = ? and col2 = ?  or  UPDATE table SET col1 = ?, col2 = ? WHERE col3 = ?
185
-     * @return int|\MyDb\Mysqli\mysqli_stmt
186
-     * @param string $line
187
-     * @param string $file
188
-     */
189
-    public function prepare($query, $line = '', $file = '')
190
-    {
191
-        if (!$this->connect()) {
192
-            return 0;
193
-        }
194
-        $haltPrev = $this->haltOnError;
195
-        $this->haltOnError = 'no';
196
-        $start = microtime(true);
197
-        $prepare = mysqli_prepare($this->linkId, $query);
198
-        if (!isset($GLOBALS['disable_db_queries'])) {
199
-            $this->addLog($query, microtime(true) - $start, $line, $file);
200
-        }
201
-        return $prepare;
202
-    }
203
-
204
-    /**
205
-     * Db::query()
206
-     *
207
-     *  Sends an SQL query to the database
208
-     *
209
-     * @param mixed $queryString
210
-     * @param string $line
211
-     * @param string $file
212
-     * @return mixed 0 if no query or query id handler, safe to ignore this return
213
-     */
214
-    public function query($queryString, $line = '', $file = '')
215
-    {
216
-        /* No empty queries, please, since PHP4 chokes on them. */
217
-        /* The empty query string is passed on from the constructor,
22
+	/**
23
+	 * @var string
24
+	 */
25
+	public $type = 'mysqli';
26
+
27
+	/**
28
+	 * alias function of select_db, changes the database we are working with.
29
+	 *
30
+	 * @param string $database the name of the database to use
31
+	 * @return void
32
+	 */
33
+	public function useDb($database)
34
+	{
35
+		$this->selectDb($database);
36
+	}
37
+
38
+	/**
39
+	 * changes the database we are working with.
40
+	 *
41
+	 * @param string $database the name of the database to use
42
+	 * @return void
43
+	 */
44
+	public function selectDb($database)
45
+	{
46
+		$this->connect();
47
+		mysqli_select_db($this->linkId, $database);
48
+	}
49
+
50
+	/* public: connection management */
51
+
52
+	/**
53
+	 * Db::connect()
54
+	 * @param string $database
55
+	 * @param string $host
56
+	 * @param string $user
57
+	 * @param string $password
58
+	 * @return int|\mysqli
59
+	 */
60
+	public function connect($database = '', $host = '', $user = '', $password = '', $port = '')
61
+	{
62
+		/* Handle defaults */
63
+		if ($database == '') {
64
+			$database = $this->database;
65
+		}
66
+		if ($host == '') {
67
+			$host = $this->host;
68
+		}
69
+		if ($user == '') {
70
+			$user = $this->user;
71
+		}
72
+		if ($password == '') {
73
+			$password = $this->password;
74
+		}
75
+		if ($port == '') {
76
+			$port = $this->port;
77
+		}
78
+		/* establish connection, select database */
79
+		if (!is_object($this->linkId)) {
80
+			$this->connectionAttempt++;
81
+			if ($this->connectionAttempt >= $this->maxConnectErrors - 1) {
82
+				error_log("MySQLi Connection Attempt #{$this->connectionAttempt}/{$this->maxConnectErrors}");
83
+			}
84
+			if ($this->connectionAttempt >= $this->maxConnectErrors) {
85
+				$this->halt("connect($host, $user, \$password) failed. ".$this->linkId->connect_error);
86
+				return 0;
87
+			}
88
+			$this->linkId = mysqli_init();
89
+			$this->linkId->options(MYSQLI_INIT_COMMAND, "SET NAMES {$this->characterSet} COLLATE {$this->collation}, COLLATION_CONNECTION = {$this->collation}, COLLATION_DATABASE = {$this->collation}");
90
+			if (!$this->linkId->real_connect($host, $user, $password, $database, $port != '' ? $port : NULL)) {
91
+				$this->halt("connect($host, $user, \$password) failed. ".$this->linkId->connect_error);
92
+				return 0;
93
+			}
94
+			$this->linkId->set_charset($this->characterSet);
95
+			if ($this->linkId->connect_errno) {
96
+				$this->halt("connect($host, $user, \$password) failed. ".$this->linkId->connect_error);
97
+				return 0;
98
+			}
99
+		}
100
+		return $this->linkId;
101
+	}
102
+
103
+	/**
104
+	 * Db::disconnect()
105
+	 * @return bool
106
+	 */
107
+	public function disconnect()
108
+	{
109
+		$return = !is_int($this->linkId) && method_exists($this->linkId, 'close') ? $this->linkId->close() : false;
110
+		$this->linkId = 0;
111
+		return $return;
112
+	}
113
+
114
+	/**
115
+	 * @param $string
116
+	 * @return string
117
+	 */
118
+	public function real_escape($string = '')
119
+	{
120
+		if ((!is_resource($this->linkId) || $this->linkId == 0) && !$this->connect()) {
121
+			return $this->escape($string);
122
+		}
123
+		return mysqli_real_escape_string($this->linkId, $string);
124
+	}
125
+
126
+	/**
127
+	 * discard the query result
128
+	 * @return void
129
+	 */
130
+	public function free()
131
+	{
132
+		if (is_resource($this->queryId)) {
133
+			@mysqli_free_result($this->queryId);
134
+		}
135
+		$this->queryId = 0;
136
+	}
137
+
138
+	/**
139
+	 * Db::queryReturn()
140
+	 *
141
+	 * Sends an SQL query to the server like the normal query() command but iterates through
142
+	 * any rows and returns the row or rows immediately or FALSE on error
143
+	 *
144
+	 * @param mixed $query SQL Query to be used
145
+	 * @param string $line optionally pass __LINE__ calling the query for logging
146
+	 * @param string $file optionally pass __FILE__ calling the query for logging
147
+	 * @return mixed FALSE if no rows, if a single row it returns that, if multiple it returns an array of rows, associative responses only
148
+	 */
149
+	public function queryReturn($query, $line = '', $file = '')
150
+	{
151
+		$this->query($query, $line, $file);
152
+		if ($this->num_rows() == 0) {
153
+			return false;
154
+		} elseif ($this->num_rows() == 1) {
155
+			$this->next_record(MYSQLI_ASSOC);
156
+			return $this->Record;
157
+		} else {
158
+			$out = [];
159
+			while ($this->next_record(MYSQLI_ASSOC)) {
160
+				$out[] = $this->Record;
161
+			}
162
+			return $out;
163
+		}
164
+	}
165
+
166
+	/**
167
+	 * db:qr()
168
+	 *
169
+	 *  alias of queryReturn()
170
+	 *
171
+	 * @param mixed $query SQL Query to be used
172
+	 * @param string $line optionally pass __LINE__ calling the query for logging
173
+	 * @param string $file optionally pass __FILE__ calling the query for logging
174
+	 * @return mixed FALSE if no rows, if a single row it returns that, if multiple it returns an array of rows, associative responses only
175
+	 */
176
+	public function qr($query, $line = '', $file = '')
177
+	{
178
+		return $this->queryReturn($query, $line, $file);
179
+	}
180
+
181
+	/**
182
+	 * creates a prepaired statement from query
183
+	 *
184
+	 * @param string $query sql query like INSERT INTO table (col) VALUES (?)  or  SELECT * from table WHERE col1 = ? and col2 = ?  or  UPDATE table SET col1 = ?, col2 = ? WHERE col3 = ?
185
+	 * @return int|\MyDb\Mysqli\mysqli_stmt
186
+	 * @param string $line
187
+	 * @param string $file
188
+	 */
189
+	public function prepare($query, $line = '', $file = '')
190
+	{
191
+		if (!$this->connect()) {
192
+			return 0;
193
+		}
194
+		$haltPrev = $this->haltOnError;
195
+		$this->haltOnError = 'no';
196
+		$start = microtime(true);
197
+		$prepare = mysqli_prepare($this->linkId, $query);
198
+		if (!isset($GLOBALS['disable_db_queries'])) {
199
+			$this->addLog($query, microtime(true) - $start, $line, $file);
200
+		}
201
+		return $prepare;
202
+	}
203
+
204
+	/**
205
+	 * Db::query()
206
+	 *
207
+	 *  Sends an SQL query to the database
208
+	 *
209
+	 * @param mixed $queryString
210
+	 * @param string $line
211
+	 * @param string $file
212
+	 * @return mixed 0 if no query or query id handler, safe to ignore this return
213
+	 */
214
+	public function query($queryString, $line = '', $file = '')
215
+	{
216
+		/* No empty queries, please, since PHP4 chokes on them. */
217
+		/* The empty query string is passed on from the constructor,
218 218
         * when calling the class without a query, e.g. in situations
219 219
         * like these: '$db = new db_Subclass;'
220 220
         */
221
-        if ($queryString == '') {
222
-            return 0;
223
-        }
224
-        if (!$this->connect()) {
225
-            return 0;
226
-            /* we already complained in connect() about that. */
227
-        }
228
-        $haltPrev = $this->haltOnError;
229
-        $this->haltOnError = 'no';
230
-        // New query, discard previous result.
231
-        if (is_resource($this->queryId)) {
232
-            $this->free();
233
-        }
234
-        if ($this->Debug) {
235
-            printf("Debug: query = %s<br>\n", $queryString);
236
-        }
237
-        if (isset($GLOBALS['log_queries']) && $GLOBALS['log_queries'] !== false) {
238
-            $this->log($queryString, $line, $file);
239
-        }
240
-        $tries = 2;
241
-        $try = 0;
242
-        $this->queryId = false;
243
-        while ((null === $this->queryId || $this->queryId === false) && $try <= $tries) {
244
-            $try++;
245
-            if ($try > 1) {
246
-                @mysqli_close($this->linkId);
247
-                $this->linkId = 0;
248
-                $this->connect();
249
-            }
250
-            $start = microtime(true);
251
-            $onlyRollback = true;
252
-            $fails = -1;
253
-            while ($fails < 10 && (null === $this->queryId || $this->queryId === false)) {
254
-                $fails++;
255
-                try {
256
-                    $this->queryId = @mysqli_query($this->linkId, $queryString, MYSQLI_STORE_RESULT);
257
-                    if (in_array((int)@mysqli_errno($this->linkId), [1213, 2006, 3101, 1180])) {
258
-                        //error_log("got ".@mysqli_errno($this->linkId)." sql error fails {$fails} on query {$queryString} from {$line}:{$file}");
259
-                        usleep(500000); // 0.5 second
260
-                    } else {
261
-                        $onlyRollback = false;
262
-                    }
263
-                } catch (\mysqli_sql_exception $e) {
264
-                    if (in_array((int)$e->getCode(), [1213, 2006, 3101, 1180])) {
265
-                        //error_log("got ".$e->getCode()." sql error fails {$fails}");
266
-                        usleep(100000); // 0.1 second
267
-                    } else {
268
-                        error_log('Got mysqli_sql_exception code '.$e->getCode().' error '.$e->getMessage().' on query '.$queryString.' from '.$line.':'.$file);
269
-                        $onlyRollback = false;
270
-                    }
271
-                }
272
-            }
273
-            if (!isset($GLOBALS['disable_db_queries'])) {
274
-                $this->addLog($queryString, microtime(true) - $start, $line, $file);
275
-            }
276
-            $this->Row = 0;
277
-            $this->Errno = @mysqli_errno($this->linkId);
278
-            $this->Error = @mysqli_error($this->linkId);
279
-            if ($try == 1 && (null === $this->queryId || $this->queryId === false)) {
280
-                //$this->emailError($queryString, 'Error #'.$this->Errno.': '.$this->Error, $line, $file);
281
-            }
282
-        }
283
-        $this->haltOnError = $haltPrev;
284
-        if ($onlyRollback === true && false === $this->queryId) {
285
-            error_log('Got MySQLi 3101 Rollback Error '.$fails.' Times, Giving Up on '.$queryString.' from '.$line.':'.$file.' on '.__LINE__.':'.__FILE__);
286
-        }
287
-        if (null === $this->queryId || $this->queryId === false) {
288
-            $this->emailError($queryString, 'Error #'.$this->Errno.': '.$this->Error, $line, $file);
289
-            $this->halt('', $line, $file);
290
-        }
291
-
292
-        // Will return nada if it fails. That's fine.
293
-        return $this->queryId;
294
-    }
295
-
296
-    /**
297
-     * @return array|null|object
298
-     */
299
-    public function fetchObject()
300
-    {
301
-        $this->Record = @mysqli_fetch_object($this->queryId);
302
-        return $this->Record;
303
-    }
304
-
305
-    /* public: walk result set */
306
-
307
-    /**
308
-     * Db::next_record()
309
-     *
310
-     * @param mixed $resultType
311
-     * @return bool
312
-     */
313
-    public function next_record($resultType = MYSQLI_BOTH)
314
-    {
315
-        if ($this->queryId === false) {
316
-            $this->haltmsg('next_record called with no query pending.');
317
-            return 0;
318
-        }
319
-
320
-        $this->Record = @mysqli_fetch_array($this->queryId, $resultType);
321
-        ++$this->Row;
322
-        $this->Errno = mysqli_errno($this->linkId);
323
-        $this->Error = mysqli_error($this->linkId);
324
-
325
-        $stat = is_array($this->Record);
326
-        if (!$stat && $this->autoFree && is_resource($this->queryId)) {
327
-            $this->free();
328
-        }
329
-        return $stat;
330
-    }
331
-
332
-    /**
333
-     * switch to position in result set
334
-     *
335
-     * @param integer $pos the row numbe starting at 0 to switch to
336
-     * @return bool whetherit was successfu or not.
337
-     */
338
-    public function seek($pos = 0)
339
-    {
340
-        $status = @mysqli_data_seek($this->queryId, $pos);
341
-        if ($status) {
342
-            $this->Row = $pos;
343
-        } else {
344
-            $this->haltmsg("seek({$pos}) failed: result has ".$this->num_rows().' rows', __LINE__, __FILE__);
345
-            /* half assed attempt to save the day, but do not consider this documented or even desirable behaviour. */
346
-            $rows = $this->num_rows();
347
-            @mysqli_data_seek($this->queryId, $rows);
348
-            $this->Row = $rows;
349
-            return false;
350
-        }
351
-        return true;
352
-    }
353
-
354
-    /**
355
-     * Initiates a transaction
356
-     *
357
-     * @return bool
358
-     */
359
-    public function transactionBegin()
360
-    {
361
-        if (version_compare(PHP_VERSION, '5.5.0') < 0) {
362
-            return true;
363
-        }
364
-        if (!$this->connect()) {
365
-            return 0;
366
-        }
367
-        return mysqli_begin_transaction($this->linkId);
368
-    }
369
-
370
-    /**
371
-     * Commits a transaction
372
-     *
373
-     * @return bool
374
-     */
375
-    public function transactionCommit()
376
-    {
377
-        if (version_compare(PHP_VERSION, '5.5.0') < 0 || $this->linkId === 0) {
378
-            return true;
379
-        }
380
-        return mysqli_commit($this->linkId);
381
-    }
382
-
383
-    /**
384
-     * Rolls back a transaction
385
-     *
386
-     * @return bool
387
-     */
388
-    public function transactionAbort()
389
-    {
390
-        if (version_compare(PHP_VERSION, '5.5.0') < 0 || $this->linkId === 0) {
391
-            return true;
392
-        }
393
-        return mysqli_rollback($this->linkId);
394
-    }
395
-
396
-    /**
397
-     * This will get the last insert ID created on the current connection.  Should only be called after an insert query is
398
-     * run on a table that has an auto incrementing field.  $table and $field are required, but unused here since it's
399
-     * unnecessary for mysql.  For compatibility with pgsql, the params must be supplied.
400
-     *
401
-     * @param string $table
402
-     * @param string $field
403
-     * @return int|string
404
-     */
405
-    public function getLastInsertId($table, $field)
406
-    {
407
-        if (!isset($table) || $table == '' || !isset($field) || $field == '') {
408
-            return -1;
409
-        }
410
-
411
-        return @mysqli_insert_id($this->linkId);
412
-    }
413
-
414
-    /* public: table locking */
415
-
416
-    /**
417
-     * Db::lock()
418
-     * @param mixed  $table
419
-     * @param string $mode
420
-     * @return bool|int|\mysqli_result
421
-     */
422
-    public function lock($table, $mode = 'write')
423
-    {
424
-        $this->connect();
425
-        $query = 'lock tables ';
426
-        if (is_array($table)) {
427
-            foreach ($table as $key => $value) {
428
-                if ($key == 'read' && $key != 0) {
429
-                    $query .= "$value read, ";
430
-                } else {
431
-                    $query .= "$value $mode, ";
432
-                }
433
-            }
434
-            $query = mb_substr($query, 0, -2);
435
-        } else {
436
-            $query .= "$table $mode";
437
-        }
438
-        $res = @mysqli_query($this->linkId, $query);
439
-        if (!$res) {
440
-            $this->halt("lock($table, $mode) failed.");
441
-            return 0;
442
-        }
443
-        return $res;
444
-    }
445
-
446
-    /**
447
-     * Db::unlock()
448
-     * @param bool $haltOnError optional, defaults to TRUE, whether or not to halt on error
449
-     * @return bool|int|\mysqli_result
450
-     */
451
-    public function unlock($haltOnError = true)
452
-    {
453
-        $this->connect();
454
-
455
-        $res = @mysqli_query($this->linkId, 'unlock tables');
456
-        if ($haltOnError === true && !$res) {
457
-            $this->halt('unlock() failed.');
458
-            return 0;
459
-        }
460
-        return $res;
461
-    }
462
-
463
-    /* public: evaluate the result (size, width) */
464
-
465
-    /**
466
-     * Db::affectedRows()
467
-     * @return int
468
-     */
469
-    public function affectedRows()
470
-    {
471
-        return @mysqli_affected_rows($this->linkId);
472
-    }
473
-
474
-    /**
475
-     * Db::num_rows()
476
-     * @return int
477
-     */
478
-    public function num_rows()
479
-    {
480
-        return @mysqli_num_rows($this->queryId);
481
-    }
482
-
483
-    /**
484
-     * Db::num_fields()
485
-     * @return int
486
-     */
487
-    public function num_fields()
488
-    {
489
-        return @mysqli_num_fields($this->queryId);
490
-    }
491
-
492
-    /**
493
-     * gets an array of the table names in teh current datase
494
-     *
495
-     * @return array
496
-     */
497
-    public function tableNames()
498
-    {
499
-        $return = [];
500
-        $this->query('SHOW TABLES');
501
-        $i = 0;
502
-        while ($info = $this->queryId->fetch_row()) {
503
-            $return[$i]['table_name'] = $info[0];
504
-            $return[$i]['tablespace_name'] = $this->database;
505
-            $return[$i]['database'] = $this->database;
506
-            ++$i;
507
-        }
508
-        return $return;
509
-    }
221
+		if ($queryString == '') {
222
+			return 0;
223
+		}
224
+		if (!$this->connect()) {
225
+			return 0;
226
+			/* we already complained in connect() about that. */
227
+		}
228
+		$haltPrev = $this->haltOnError;
229
+		$this->haltOnError = 'no';
230
+		// New query, discard previous result.
231
+		if (is_resource($this->queryId)) {
232
+			$this->free();
233
+		}
234
+		if ($this->Debug) {
235
+			printf("Debug: query = %s<br>\n", $queryString);
236
+		}
237
+		if (isset($GLOBALS['log_queries']) && $GLOBALS['log_queries'] !== false) {
238
+			$this->log($queryString, $line, $file);
239
+		}
240
+		$tries = 2;
241
+		$try = 0;
242
+		$this->queryId = false;
243
+		while ((null === $this->queryId || $this->queryId === false) && $try <= $tries) {
244
+			$try++;
245
+			if ($try > 1) {
246
+				@mysqli_close($this->linkId);
247
+				$this->linkId = 0;
248
+				$this->connect();
249
+			}
250
+			$start = microtime(true);
251
+			$onlyRollback = true;
252
+			$fails = -1;
253
+			while ($fails < 10 && (null === $this->queryId || $this->queryId === false)) {
254
+				$fails++;
255
+				try {
256
+					$this->queryId = @mysqli_query($this->linkId, $queryString, MYSQLI_STORE_RESULT);
257
+					if (in_array((int)@mysqli_errno($this->linkId), [1213, 2006, 3101, 1180])) {
258
+						//error_log("got ".@mysqli_errno($this->linkId)." sql error fails {$fails} on query {$queryString} from {$line}:{$file}");
259
+						usleep(500000); // 0.5 second
260
+					} else {
261
+						$onlyRollback = false;
262
+					}
263
+				} catch (\mysqli_sql_exception $e) {
264
+					if (in_array((int)$e->getCode(), [1213, 2006, 3101, 1180])) {
265
+						//error_log("got ".$e->getCode()." sql error fails {$fails}");
266
+						usleep(100000); // 0.1 second
267
+					} else {
268
+						error_log('Got mysqli_sql_exception code '.$e->getCode().' error '.$e->getMessage().' on query '.$queryString.' from '.$line.':'.$file);
269
+						$onlyRollback = false;
270
+					}
271
+				}
272
+			}
273
+			if (!isset($GLOBALS['disable_db_queries'])) {
274
+				$this->addLog($queryString, microtime(true) - $start, $line, $file);
275
+			}
276
+			$this->Row = 0;
277
+			$this->Errno = @mysqli_errno($this->linkId);
278
+			$this->Error = @mysqli_error($this->linkId);
279
+			if ($try == 1 && (null === $this->queryId || $this->queryId === false)) {
280
+				//$this->emailError($queryString, 'Error #'.$this->Errno.': '.$this->Error, $line, $file);
281
+			}
282
+		}
283
+		$this->haltOnError = $haltPrev;
284
+		if ($onlyRollback === true && false === $this->queryId) {
285
+			error_log('Got MySQLi 3101 Rollback Error '.$fails.' Times, Giving Up on '.$queryString.' from '.$line.':'.$file.' on '.__LINE__.':'.__FILE__);
286
+		}
287
+		if (null === $this->queryId || $this->queryId === false) {
288
+			$this->emailError($queryString, 'Error #'.$this->Errno.': '.$this->Error, $line, $file);
289
+			$this->halt('', $line, $file);
290
+		}
291
+
292
+		// Will return nada if it fails. That's fine.
293
+		return $this->queryId;
294
+	}
295
+
296
+	/**
297
+	 * @return array|null|object
298
+	 */
299
+	public function fetchObject()
300
+	{
301
+		$this->Record = @mysqli_fetch_object($this->queryId);
302
+		return $this->Record;
303
+	}
304
+
305
+	/* public: walk result set */
306
+
307
+	/**
308
+	 * Db::next_record()
309
+	 *
310
+	 * @param mixed $resultType
311
+	 * @return bool
312
+	 */
313
+	public function next_record($resultType = MYSQLI_BOTH)
314
+	{
315
+		if ($this->queryId === false) {
316
+			$this->haltmsg('next_record called with no query pending.');
317
+			return 0;
318
+		}
319
+
320
+		$this->Record = @mysqli_fetch_array($this->queryId, $resultType);
321
+		++$this->Row;
322
+		$this->Errno = mysqli_errno($this->linkId);
323
+		$this->Error = mysqli_error($this->linkId);
324
+
325
+		$stat = is_array($this->Record);
326
+		if (!$stat && $this->autoFree && is_resource($this->queryId)) {
327
+			$this->free();
328
+		}
329
+		return $stat;
330
+	}
331
+
332
+	/**
333
+	 * switch to position in result set
334
+	 *
335
+	 * @param integer $pos the row numbe starting at 0 to switch to
336
+	 * @return bool whetherit was successfu or not.
337
+	 */
338
+	public function seek($pos = 0)
339
+	{
340
+		$status = @mysqli_data_seek($this->queryId, $pos);
341
+		if ($status) {
342
+			$this->Row = $pos;
343
+		} else {
344
+			$this->haltmsg("seek({$pos}) failed: result has ".$this->num_rows().' rows', __LINE__, __FILE__);
345
+			/* half assed attempt to save the day, but do not consider this documented or even desirable behaviour. */
346
+			$rows = $this->num_rows();
347
+			@mysqli_data_seek($this->queryId, $rows);
348
+			$this->Row = $rows;
349
+			return false;
350
+		}
351
+		return true;
352
+	}
353
+
354
+	/**
355
+	 * Initiates a transaction
356
+	 *
357
+	 * @return bool
358
+	 */
359
+	public function transactionBegin()
360
+	{
361
+		if (version_compare(PHP_VERSION, '5.5.0') < 0) {
362
+			return true;
363
+		}
364
+		if (!$this->connect()) {
365
+			return 0;
366
+		}
367
+		return mysqli_begin_transaction($this->linkId);
368
+	}
369
+
370
+	/**
371
+	 * Commits a transaction
372
+	 *
373
+	 * @return bool
374
+	 */
375
+	public function transactionCommit()
376
+	{
377
+		if (version_compare(PHP_VERSION, '5.5.0') < 0 || $this->linkId === 0) {
378
+			return true;
379
+		}
380
+		return mysqli_commit($this->linkId);
381
+	}
382
+
383
+	/**
384
+	 * Rolls back a transaction
385
+	 *
386
+	 * @return bool
387
+	 */
388
+	public function transactionAbort()
389
+	{
390
+		if (version_compare(PHP_VERSION, '5.5.0') < 0 || $this->linkId === 0) {
391
+			return true;
392
+		}
393
+		return mysqli_rollback($this->linkId);
394
+	}
395
+
396
+	/**
397
+	 * This will get the last insert ID created on the current connection.  Should only be called after an insert query is
398
+	 * run on a table that has an auto incrementing field.  $table and $field are required, but unused here since it's
399
+	 * unnecessary for mysql.  For compatibility with pgsql, the params must be supplied.
400
+	 *
401
+	 * @param string $table
402
+	 * @param string $field
403
+	 * @return int|string
404
+	 */
405
+	public function getLastInsertId($table, $field)
406
+	{
407
+		if (!isset($table) || $table == '' || !isset($field) || $field == '') {
408
+			return -1;
409
+		}
410
+
411
+		return @mysqli_insert_id($this->linkId);
412
+	}
413
+
414
+	/* public: table locking */
415
+
416
+	/**
417
+	 * Db::lock()
418
+	 * @param mixed  $table
419
+	 * @param string $mode
420
+	 * @return bool|int|\mysqli_result
421
+	 */
422
+	public function lock($table, $mode = 'write')
423
+	{
424
+		$this->connect();
425
+		$query = 'lock tables ';
426
+		if (is_array($table)) {
427
+			foreach ($table as $key => $value) {
428
+				if ($key == 'read' && $key != 0) {
429
+					$query .= "$value read, ";
430
+				} else {
431
+					$query .= "$value $mode, ";
432
+				}
433
+			}
434
+			$query = mb_substr($query, 0, -2);
435
+		} else {
436
+			$query .= "$table $mode";
437
+		}
438
+		$res = @mysqli_query($this->linkId, $query);
439
+		if (!$res) {
440
+			$this->halt("lock($table, $mode) failed.");
441
+			return 0;
442
+		}
443
+		return $res;
444
+	}
445
+
446
+	/**
447
+	 * Db::unlock()
448
+	 * @param bool $haltOnError optional, defaults to TRUE, whether or not to halt on error
449
+	 * @return bool|int|\mysqli_result
450
+	 */
451
+	public function unlock($haltOnError = true)
452
+	{
453
+		$this->connect();
454
+
455
+		$res = @mysqli_query($this->linkId, 'unlock tables');
456
+		if ($haltOnError === true && !$res) {
457
+			$this->halt('unlock() failed.');
458
+			return 0;
459
+		}
460
+		return $res;
461
+	}
462
+
463
+	/* public: evaluate the result (size, width) */
464
+
465
+	/**
466
+	 * Db::affectedRows()
467
+	 * @return int
468
+	 */
469
+	public function affectedRows()
470
+	{
471
+		return @mysqli_affected_rows($this->linkId);
472
+	}
473
+
474
+	/**
475
+	 * Db::num_rows()
476
+	 * @return int
477
+	 */
478
+	public function num_rows()
479
+	{
480
+		return @mysqli_num_rows($this->queryId);
481
+	}
482
+
483
+	/**
484
+	 * Db::num_fields()
485
+	 * @return int
486
+	 */
487
+	public function num_fields()
488
+	{
489
+		return @mysqli_num_fields($this->queryId);
490
+	}
491
+
492
+	/**
493
+	 * gets an array of the table names in teh current datase
494
+	 *
495
+	 * @return array
496
+	 */
497
+	public function tableNames()
498
+	{
499
+		$return = [];
500
+		$this->query('SHOW TABLES');
501
+		$i = 0;
502
+		while ($info = $this->queryId->fetch_row()) {
503
+			$return[$i]['table_name'] = $info[0];
504
+			$return[$i]['tablespace_name'] = $this->database;
505
+			$return[$i]['database'] = $this->database;
506
+			++$i;
507
+		}
508
+		return $return;
509
+	}
510 510
 }
511 511
 
512 512
 /**
Please login to merge, or discard this patch.