Test Failed
Push — master ( 81e3a2...ed0ed2 )
by Joe
13:45
created
src/Mysqli/Db.php 2 patches
Indentation   +495 added lines, -495 removed lines patch added patch discarded remove patch
@@ -19,504 +19,504 @@
 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
-            //error_log("real_connect($host, $user, $password, $database, $port)");
89
-            $this->linkId = mysqli_init();
90
-            $this->linkId->options(MYSQLI_INIT_COMMAND, "SET NAMES {$this->characterSet} COLLATE {$this->collation}, COLLATION_CONNECTION = {$this->collation}, COLLATION_DATABASE = {$this->collation}");
91
-            if (!$this->linkId->real_connect($host, $user, $password, $database, $port != '' ? $port : NULL)) {
92
-                $this->halt("connect($host, $user, \$password) failed. ".$this->linkId->connect_error);
93
-                return 0;
94
-            }
95
-            $this->linkId->set_charset($this->characterSet);
96
-            if ($this->linkId->connect_errno) {
97
-                $this->halt("connect($host, $user, \$password) failed. ".$this->linkId->connect_error);
98
-                return 0;
99
-            }
100
-        }
101
-        return $this->linkId;
102
-    }
103
-
104
-    /**
105
-     * Db::disconnect()
106
-     * @return bool
107
-     */
108
-    public function disconnect()
109
-    {
110
-        $return = !is_int($this->linkId) && method_exists($this->linkId, 'close') ? $this->linkId->close() : false;
111
-        $this->linkId = 0;
112
-        return $return;
113
-    }
114
-
115
-    /**
116
-     * @param $string
117
-     * @return string
118
-     */
119
-    public function real_escape($string = '')
120
-    {
121
-        if ((!is_resource($this->linkId) || $this->linkId == 0) && !$this->connect()) {
122
-            return $this->escape($string);
123
-        }
124
-        return mysqli_real_escape_string($this->linkId, $string);
125
-    }
126
-
127
-    /**
128
-     * discard the query result
129
-     * @return void
130
-     */
131
-    public function free()
132
-    {
133
-        if (is_resource($this->queryId)) {
134
-            @mysqli_free_result($this->queryId);
135
-        }
136
-        $this->queryId = 0;
137
-    }
138
-
139
-    /**
140
-     * Db::queryReturn()
141
-     *
142
-     * Sends an SQL query to the server like the normal query() command but iterates through
143
-     * any rows and returns the row or rows immediately or FALSE on error
144
-     *
145
-     * @param mixed $query SQL Query to be used
146
-     * @param string $line optionally pass __LINE__ calling the query for logging
147
-     * @param string $file optionally pass __FILE__ calling the query for logging
148
-     * @return mixed FALSE if no rows, if a single row it returns that, if multiple it returns an array of rows, associative responses only
149
-     */
150
-    public function queryReturn($query, $line = '', $file = '')
151
-    {
152
-        $this->query($query, $line, $file);
153
-        if ($this->num_rows() == 0) {
154
-            return false;
155
-        } elseif ($this->num_rows() == 1) {
156
-            $this->next_record(MYSQLI_ASSOC);
157
-            return $this->Record;
158
-        } else {
159
-            $out = [];
160
-            while ($this->next_record(MYSQLI_ASSOC)) {
161
-                $out[] = $this->Record;
162
-            }
163
-            return $out;
164
-        }
165
-    }
166
-
167
-    /**
168
-     * db:qr()
169
-     *
170
-     *  alias of queryReturn()
171
-     *
172
-     * @param mixed $query SQL Query to be used
173
-     * @param string $line optionally pass __LINE__ calling the query for logging
174
-     * @param string $file optionally pass __FILE__ calling the query for logging
175
-     * @return mixed FALSE if no rows, if a single row it returns that, if multiple it returns an array of rows, associative responses only
176
-     */
177
-    public function qr($query, $line = '', $file = '')
178
-    {
179
-        return $this->queryReturn($query, $line, $file);
180
-    }
181
-
182
-    /**
183
-     * creates a prepaired statement from query
184
-     *
185
-     * @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 = ?
186
-     * @return int|\MyDb\Mysqli\mysqli_stmt
187
-     * @param string $line
188
-     * @param string $file
189
-     */
190
-    public function prepare($query, $line = '', $file = '')
191
-    {
192
-        if (!$this->connect()) {
193
-            return 0;
194
-        }
195
-        $haltPrev = $this->haltOnError;
196
-        $this->haltOnError = 'no';
197
-        $start = microtime(true);
198
-        $prepare = mysqli_prepare($this->linkId, $query);
199
-        if (!isset($GLOBALS['disable_db_queries'])) {
200
-            $this->addLog($query, microtime(true) - $start, $line, $file);
201
-        }
202
-        return $prepare;
203
-    }
204
-
205
-    /**
206
-     * Db::query()
207
-     *
208
-     *  Sends an SQL query to the database
209
-     *
210
-     * @param mixed $queryString
211
-     * @param int $line
212
-     * @param string $file
213
-     * @param bool $log
214
-     * @return mixed 0 if no query or query id handler, safe to ignore this return
215
-     */
216
-    public function query($queryString, $line = '', $file = '', $log = false)
217
-    {
218
-        /* No empty queries, please, since PHP4 chokes on them. */
219
-        /* 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
+			//error_log("real_connect($host, $user, $password, $database, $port)");
89
+			$this->linkId = mysqli_init();
90
+			$this->linkId->options(MYSQLI_INIT_COMMAND, "SET NAMES {$this->characterSet} COLLATE {$this->collation}, COLLATION_CONNECTION = {$this->collation}, COLLATION_DATABASE = {$this->collation}");
91
+			if (!$this->linkId->real_connect($host, $user, $password, $database, $port != '' ? $port : NULL)) {
92
+				$this->halt("connect($host, $user, \$password) failed. ".$this->linkId->connect_error);
93
+				return 0;
94
+			}
95
+			$this->linkId->set_charset($this->characterSet);
96
+			if ($this->linkId->connect_errno) {
97
+				$this->halt("connect($host, $user, \$password) failed. ".$this->linkId->connect_error);
98
+				return 0;
99
+			}
100
+		}
101
+		return $this->linkId;
102
+	}
103
+
104
+	/**
105
+	 * Db::disconnect()
106
+	 * @return bool
107
+	 */
108
+	public function disconnect()
109
+	{
110
+		$return = !is_int($this->linkId) && method_exists($this->linkId, 'close') ? $this->linkId->close() : false;
111
+		$this->linkId = 0;
112
+		return $return;
113
+	}
114
+
115
+	/**
116
+	 * @param $string
117
+	 * @return string
118
+	 */
119
+	public function real_escape($string = '')
120
+	{
121
+		if ((!is_resource($this->linkId) || $this->linkId == 0) && !$this->connect()) {
122
+			return $this->escape($string);
123
+		}
124
+		return mysqli_real_escape_string($this->linkId, $string);
125
+	}
126
+
127
+	/**
128
+	 * discard the query result
129
+	 * @return void
130
+	 */
131
+	public function free()
132
+	{
133
+		if (is_resource($this->queryId)) {
134
+			@mysqli_free_result($this->queryId);
135
+		}
136
+		$this->queryId = 0;
137
+	}
138
+
139
+	/**
140
+	 * Db::queryReturn()
141
+	 *
142
+	 * Sends an SQL query to the server like the normal query() command but iterates through
143
+	 * any rows and returns the row or rows immediately or FALSE on error
144
+	 *
145
+	 * @param mixed $query SQL Query to be used
146
+	 * @param string $line optionally pass __LINE__ calling the query for logging
147
+	 * @param string $file optionally pass __FILE__ calling the query for logging
148
+	 * @return mixed FALSE if no rows, if a single row it returns that, if multiple it returns an array of rows, associative responses only
149
+	 */
150
+	public function queryReturn($query, $line = '', $file = '')
151
+	{
152
+		$this->query($query, $line, $file);
153
+		if ($this->num_rows() == 0) {
154
+			return false;
155
+		} elseif ($this->num_rows() == 1) {
156
+			$this->next_record(MYSQLI_ASSOC);
157
+			return $this->Record;
158
+		} else {
159
+			$out = [];
160
+			while ($this->next_record(MYSQLI_ASSOC)) {
161
+				$out[] = $this->Record;
162
+			}
163
+			return $out;
164
+		}
165
+	}
166
+
167
+	/**
168
+	 * db:qr()
169
+	 *
170
+	 *  alias of queryReturn()
171
+	 *
172
+	 * @param mixed $query SQL Query to be used
173
+	 * @param string $line optionally pass __LINE__ calling the query for logging
174
+	 * @param string $file optionally pass __FILE__ calling the query for logging
175
+	 * @return mixed FALSE if no rows, if a single row it returns that, if multiple it returns an array of rows, associative responses only
176
+	 */
177
+	public function qr($query, $line = '', $file = '')
178
+	{
179
+		return $this->queryReturn($query, $line, $file);
180
+	}
181
+
182
+	/**
183
+	 * creates a prepaired statement from query
184
+	 *
185
+	 * @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 = ?
186
+	 * @return int|\MyDb\Mysqli\mysqli_stmt
187
+	 * @param string $line
188
+	 * @param string $file
189
+	 */
190
+	public function prepare($query, $line = '', $file = '')
191
+	{
192
+		if (!$this->connect()) {
193
+			return 0;
194
+		}
195
+		$haltPrev = $this->haltOnError;
196
+		$this->haltOnError = 'no';
197
+		$start = microtime(true);
198
+		$prepare = mysqli_prepare($this->linkId, $query);
199
+		if (!isset($GLOBALS['disable_db_queries'])) {
200
+			$this->addLog($query, microtime(true) - $start, $line, $file);
201
+		}
202
+		return $prepare;
203
+	}
204
+
205
+	/**
206
+	 * Db::query()
207
+	 *
208
+	 *  Sends an SQL query to the database
209
+	 *
210
+	 * @param mixed $queryString
211
+	 * @param int $line
212
+	 * @param string $file
213
+	 * @param bool $log
214
+	 * @return mixed 0 if no query or query id handler, safe to ignore this return
215
+	 */
216
+	public function query($queryString, $line = '', $file = '', $log = false)
217
+	{
218
+		/* No empty queries, please, since PHP4 chokes on them. */
219
+		/* The empty query string is passed on from the constructor,
220 220
         * when calling the class without a query, e.g. in situations
221 221
         * like these: '$db = new db_Subclass;'
222 222
         */
223
-        if ($queryString == '') {
224
-            return 0;
225
-        }
226
-        if (!$this->connect()) {
227
-            return 0;
228
-            /* we already complained in connect() about that. */
229
-        }
230
-        $haltPrev = $this->haltOnError;
231
-        $this->haltOnError = 'no';
232
-        // New query, discard previous result.
233
-        if (is_resource($this->queryId)) {
234
-            $this->free();
235
-        }
236
-        if ($this->Debug) {
237
-            printf("Debug: query = %s<br>\n", $queryString);
238
-        }
239
-        if ($log === true || (isset($GLOBALS['log_queries']) && $GLOBALS['log_queries'] !== false)) {
240
-            $this->log($queryString, $line, $file);
241
-        }
242
-        $tries = 2;
243
-        $try = 0;
244
-        $this->queryId = false;
245
-        while ((null === $this->queryId || $this->queryId === false) && $try <= $tries) {
246
-            $try++;
247
-            if ($try > 1) {
248
-                @mysqli_close($this->linkId);
249
-                $this->linkId = 0;
250
-            }
251
-            $start = microtime(true);
252
-            $onlyRollback = true;
253
-            $fails = -1;
254
-            while ($fails < 30 && (null === $this->queryId || $this->queryId === false)) {
255
-                $this->connect();
256
-                $fails++;
257
-                try {
258
-                    $this->queryId = @mysqli_query($this->linkId, $queryString, MYSQLI_STORE_RESULT);
259
-                    if (in_array((int)@mysqli_errno($this->linkId), [1213, 2006, 3101, 1180])) {
260
-                        //error_log("got ".@mysqli_errno($this->linkId)." sql error fails {$fails} on query {$queryString} from {$line}:{$file}");
261
-                        usleep(250000); // 0.25 second
262
-                    } else {
263
-                        $onlyRollback = false;
264
-                        if (in_array((int)@mysqli_errno($this->linkId), [1064])) {
265
-                            $tries = 0;
266
-                        }
267
-                        break;
268
-                    }
269
-                } catch (\mysqli_sql_exception $e) {
270
-                    if (in_array((int)$e->getCode(), [1213, 2006, 3101, 1180])) {
271
-                        //error_log("got ".$e->getCode()." sql error fails {$fails}");
272
-                        usleep(250000); // 0.25 second
273
-                    } else {
274
-                        error_log('Got mysqli_sql_exception code '.$e->getCode().' error '.$e->getMessage().' on query '.$queryString.' from '.$line.':'.$file);
275
-                        $onlyRollback = false;
276
-                        if (in_array((int)@mysqli_errno($this->linkId), [1064])) {
277
-                            $tries = 0;
278
-                        }
279
-                        break;
280
-                    }
281
-                }
282
-            }
283
-            if (!isset($GLOBALS['disable_db_queries'])) {
284
-                $this->addLog($queryString, microtime(true) - $start, $line, $file);
285
-            }
286
-            $this->Row = 0;
287
-            $this->Errno = @mysqli_errno($this->linkId);
288
-            $this->Error = @mysqli_error($this->linkId);
289
-            if ($try == 1 && (null === $this->queryId || $this->queryId === false)) {
290
-                //$this->emailError($queryString, 'Error #'.$this->Errno.': '.$this->Error, $line, $file);
291
-            }
292
-        }
293
-        $this->haltOnError = $haltPrev;
294
-        if ($onlyRollback === true && false === $this->queryId) {
295
-            error_log('Got MySQLi 3101 Rollback Error '.$fails.' Times, Giving Up on '.$queryString.' from '.$line.':'.$file.' on '.__LINE__.':'.__FILE__);
296
-        }
297
-        if (null === $this->queryId || $this->queryId === false) {
298
-            $this->emailError($queryString, 'Error #'.$this->Errno.': '.$this->Error, $line, $file);
299
-            $this->halt('', $line, $file);
300
-        }
301
-
302
-        // Will return nada if it fails. That's fine.
303
-        return $this->queryId;
304
-    }
305
-
306
-    /**
307
-     * @return array|null|object
308
-     */
309
-    public function fetchObject()
310
-    {
311
-        $this->Record = @mysqli_fetch_object($this->queryId);
312
-        return $this->Record;
313
-    }
314
-
315
-    /* public: walk result set */
316
-
317
-    /**
318
-     * Db::next_record()
319
-     *
320
-     * @param mixed $resultType
321
-     * @return bool
322
-     */
323
-    public function next_record($resultType = MYSQLI_BOTH)
324
-    {
325
-        if ($this->queryId === false) {
326
-            $this->haltmsg('next_record called with no query pending.');
327
-            return 0;
328
-        }
329
-
330
-        $this->Record = @mysqli_fetch_array($this->queryId, $resultType);
331
-        ++$this->Row;
332
-        $this->Errno = mysqli_errno($this->linkId);
333
-        $this->Error = mysqli_error($this->linkId);
334
-
335
-        $stat = is_array($this->Record);
336
-        if (!$stat && $this->autoFree && is_resource($this->queryId)) {
337
-            $this->free();
338
-        }
339
-        return $stat;
340
-    }
341
-
342
-    /**
343
-     * switch to position in result set
344
-     *
345
-     * @param integer $pos the row numbe starting at 0 to switch to
346
-     * @return bool whetherit was successfu or not.
347
-     */
348
-    public function seek($pos = 0)
349
-    {
350
-        $status = @mysqli_data_seek($this->queryId, $pos);
351
-        if ($status) {
352
-            $this->Row = $pos;
353
-        } else {
354
-            $this->haltmsg("seek({$pos}) failed: result has ".$this->num_rows().' rows', __LINE__, __FILE__);
355
-            /* half assed attempt to save the day, but do not consider this documented or even desirable behaviour. */
356
-            $rows = $this->num_rows();
357
-            @mysqli_data_seek($this->queryId, $rows);
358
-            $this->Row = $rows;
359
-            return false;
360
-        }
361
-        return true;
362
-    }
363
-
364
-    /**
365
-     * Initiates a transaction
366
-     *
367
-     * @return bool
368
-     */
369
-    public function transactionBegin()
370
-    {
371
-        if (version_compare(PHP_VERSION, '5.5.0') < 0) {
372
-            return true;
373
-        }
374
-        if (!$this->connect()) {
375
-            return 0;
376
-        }
377
-        return mysqli_begin_transaction($this->linkId);
378
-    }
379
-
380
-    /**
381
-     * Commits a transaction
382
-     *
383
-     * @return bool
384
-     */
385
-    public function transactionCommit()
386
-    {
387
-        if (version_compare(PHP_VERSION, '5.5.0') < 0 || $this->linkId === 0) {
388
-            return true;
389
-        }
390
-        return mysqli_commit($this->linkId);
391
-    }
392
-
393
-    /**
394
-     * Rolls back a transaction
395
-     *
396
-     * @return bool
397
-     */
398
-    public function transactionAbort()
399
-    {
400
-        if (version_compare(PHP_VERSION, '5.5.0') < 0 || $this->linkId === 0) {
401
-            return true;
402
-        }
403
-        return mysqli_rollback($this->linkId);
404
-    }
405
-
406
-    /**
407
-     * This will get the last insert ID created on the current connection.  Should only be called after an insert query is
408
-     * run on a table that has an auto incrementing field.  $table and $field are required, but unused here since it's
409
-     * unnecessary for mysql.  For compatibility with pgsql, the params must be supplied.
410
-     *
411
-     * @param string $table
412
-     * @param string $field
413
-     * @return int|string
414
-     */
415
-    public function getLastInsertId($table, $field)
416
-    {
417
-        if (!isset($table) || $table == '' || !isset($field) || $field == '') {
418
-            return -1;
419
-        }
420
-
421
-        return @mysqli_insert_id($this->linkId);
422
-    }
423
-
424
-    /* public: table locking */
425
-
426
-    /**
427
-     * Db::lock()
428
-     * @param mixed  $table
429
-     * @param string $mode
430
-     * @return bool|int|\mysqli_result
431
-     */
432
-    public function lock($table, $mode = 'write')
433
-    {
434
-        $this->connect();
435
-        $query = 'lock tables ';
436
-        if (is_array($table)) {
437
-            foreach ($table as $key => $value) {
438
-                if ($key == 'read' && $key != 0) {
439
-                    $query .= "$value read, ";
440
-                } else {
441
-                    $query .= "$value $mode, ";
442
-                }
443
-            }
444
-            $query = mb_substr($query, 0, -2);
445
-        } else {
446
-            $query .= "$table $mode";
447
-        }
448
-        $res = @mysqli_query($this->linkId, $query);
449
-        if (!$res) {
450
-            $this->halt("lock($table, $mode) failed.");
451
-            return 0;
452
-        }
453
-        return $res;
454
-    }
455
-
456
-    /**
457
-     * Db::unlock()
458
-     * @param bool $haltOnError optional, defaults to TRUE, whether or not to halt on error
459
-     * @return bool|int|\mysqli_result
460
-     */
461
-    public function unlock($haltOnError = true)
462
-    {
463
-        $this->connect();
464
-
465
-        $res = @mysqli_query($this->linkId, 'unlock tables');
466
-        if ($haltOnError === true && !$res) {
467
-            $this->halt('unlock() failed.');
468
-            return 0;
469
-        }
470
-        return $res;
471
-    }
472
-
473
-    /* public: evaluate the result (size, width) */
474
-
475
-    /**
476
-     * Db::affectedRows()
477
-     * @return int
478
-     */
479
-    public function affectedRows()
480
-    {
481
-        return @mysqli_affected_rows($this->linkId);
482
-    }
483
-
484
-    /**
485
-     * Db::num_rows()
486
-     * @return int
487
-     */
488
-    public function num_rows()
489
-    {
490
-        return @mysqli_num_rows($this->queryId);
491
-    }
492
-
493
-    /**
494
-     * Db::num_fields()
495
-     * @return int
496
-     */
497
-    public function num_fields()
498
-    {
499
-        return @mysqli_num_fields($this->queryId);
500
-    }
501
-
502
-    /**
503
-     * gets an array of the table names in teh current datase
504
-     *
505
-     * @return array
506
-     */
507
-    public function tableNames()
508
-    {
509
-        $return = [];
510
-        $this->query('SHOW TABLES');
511
-        $i = 0;
512
-        while ($info = $this->queryId->fetch_row()) {
513
-            $return[$i]['table_name'] = $info[0];
514
-            $return[$i]['tablespace_name'] = $this->database;
515
-            $return[$i]['database'] = $this->database;
516
-            ++$i;
517
-        }
518
-        return $return;
519
-    }
223
+		if ($queryString == '') {
224
+			return 0;
225
+		}
226
+		if (!$this->connect()) {
227
+			return 0;
228
+			/* we already complained in connect() about that. */
229
+		}
230
+		$haltPrev = $this->haltOnError;
231
+		$this->haltOnError = 'no';
232
+		// New query, discard previous result.
233
+		if (is_resource($this->queryId)) {
234
+			$this->free();
235
+		}
236
+		if ($this->Debug) {
237
+			printf("Debug: query = %s<br>\n", $queryString);
238
+		}
239
+		if ($log === true || (isset($GLOBALS['log_queries']) && $GLOBALS['log_queries'] !== false)) {
240
+			$this->log($queryString, $line, $file);
241
+		}
242
+		$tries = 2;
243
+		$try = 0;
244
+		$this->queryId = false;
245
+		while ((null === $this->queryId || $this->queryId === false) && $try <= $tries) {
246
+			$try++;
247
+			if ($try > 1) {
248
+				@mysqli_close($this->linkId);
249
+				$this->linkId = 0;
250
+			}
251
+			$start = microtime(true);
252
+			$onlyRollback = true;
253
+			$fails = -1;
254
+			while ($fails < 30 && (null === $this->queryId || $this->queryId === false)) {
255
+				$this->connect();
256
+				$fails++;
257
+				try {
258
+					$this->queryId = @mysqli_query($this->linkId, $queryString, MYSQLI_STORE_RESULT);
259
+					if (in_array((int)@mysqli_errno($this->linkId), [1213, 2006, 3101, 1180])) {
260
+						//error_log("got ".@mysqli_errno($this->linkId)." sql error fails {$fails} on query {$queryString} from {$line}:{$file}");
261
+						usleep(250000); // 0.25 second
262
+					} else {
263
+						$onlyRollback = false;
264
+						if (in_array((int)@mysqli_errno($this->linkId), [1064])) {
265
+							$tries = 0;
266
+						}
267
+						break;
268
+					}
269
+				} catch (\mysqli_sql_exception $e) {
270
+					if (in_array((int)$e->getCode(), [1213, 2006, 3101, 1180])) {
271
+						//error_log("got ".$e->getCode()." sql error fails {$fails}");
272
+						usleep(250000); // 0.25 second
273
+					} else {
274
+						error_log('Got mysqli_sql_exception code '.$e->getCode().' error '.$e->getMessage().' on query '.$queryString.' from '.$line.':'.$file);
275
+						$onlyRollback = false;
276
+						if (in_array((int)@mysqli_errno($this->linkId), [1064])) {
277
+							$tries = 0;
278
+						}
279
+						break;
280
+					}
281
+				}
282
+			}
283
+			if (!isset($GLOBALS['disable_db_queries'])) {
284
+				$this->addLog($queryString, microtime(true) - $start, $line, $file);
285
+			}
286
+			$this->Row = 0;
287
+			$this->Errno = @mysqli_errno($this->linkId);
288
+			$this->Error = @mysqli_error($this->linkId);
289
+			if ($try == 1 && (null === $this->queryId || $this->queryId === false)) {
290
+				//$this->emailError($queryString, 'Error #'.$this->Errno.': '.$this->Error, $line, $file);
291
+			}
292
+		}
293
+		$this->haltOnError = $haltPrev;
294
+		if ($onlyRollback === true && false === $this->queryId) {
295
+			error_log('Got MySQLi 3101 Rollback Error '.$fails.' Times, Giving Up on '.$queryString.' from '.$line.':'.$file.' on '.__LINE__.':'.__FILE__);
296
+		}
297
+		if (null === $this->queryId || $this->queryId === false) {
298
+			$this->emailError($queryString, 'Error #'.$this->Errno.': '.$this->Error, $line, $file);
299
+			$this->halt('', $line, $file);
300
+		}
301
+
302
+		// Will return nada if it fails. That's fine.
303
+		return $this->queryId;
304
+	}
305
+
306
+	/**
307
+	 * @return array|null|object
308
+	 */
309
+	public function fetchObject()
310
+	{
311
+		$this->Record = @mysqli_fetch_object($this->queryId);
312
+		return $this->Record;
313
+	}
314
+
315
+	/* public: walk result set */
316
+
317
+	/**
318
+	 * Db::next_record()
319
+	 *
320
+	 * @param mixed $resultType
321
+	 * @return bool
322
+	 */
323
+	public function next_record($resultType = MYSQLI_BOTH)
324
+	{
325
+		if ($this->queryId === false) {
326
+			$this->haltmsg('next_record called with no query pending.');
327
+			return 0;
328
+		}
329
+
330
+		$this->Record = @mysqli_fetch_array($this->queryId, $resultType);
331
+		++$this->Row;
332
+		$this->Errno = mysqli_errno($this->linkId);
333
+		$this->Error = mysqli_error($this->linkId);
334
+
335
+		$stat = is_array($this->Record);
336
+		if (!$stat && $this->autoFree && is_resource($this->queryId)) {
337
+			$this->free();
338
+		}
339
+		return $stat;
340
+	}
341
+
342
+	/**
343
+	 * switch to position in result set
344
+	 *
345
+	 * @param integer $pos the row numbe starting at 0 to switch to
346
+	 * @return bool whetherit was successfu or not.
347
+	 */
348
+	public function seek($pos = 0)
349
+	{
350
+		$status = @mysqli_data_seek($this->queryId, $pos);
351
+		if ($status) {
352
+			$this->Row = $pos;
353
+		} else {
354
+			$this->haltmsg("seek({$pos}) failed: result has ".$this->num_rows().' rows', __LINE__, __FILE__);
355
+			/* half assed attempt to save the day, but do not consider this documented or even desirable behaviour. */
356
+			$rows = $this->num_rows();
357
+			@mysqli_data_seek($this->queryId, $rows);
358
+			$this->Row = $rows;
359
+			return false;
360
+		}
361
+		return true;
362
+	}
363
+
364
+	/**
365
+	 * Initiates a transaction
366
+	 *
367
+	 * @return bool
368
+	 */
369
+	public function transactionBegin()
370
+	{
371
+		if (version_compare(PHP_VERSION, '5.5.0') < 0) {
372
+			return true;
373
+		}
374
+		if (!$this->connect()) {
375
+			return 0;
376
+		}
377
+		return mysqli_begin_transaction($this->linkId);
378
+	}
379
+
380
+	/**
381
+	 * Commits a transaction
382
+	 *
383
+	 * @return bool
384
+	 */
385
+	public function transactionCommit()
386
+	{
387
+		if (version_compare(PHP_VERSION, '5.5.0') < 0 || $this->linkId === 0) {
388
+			return true;
389
+		}
390
+		return mysqli_commit($this->linkId);
391
+	}
392
+
393
+	/**
394
+	 * Rolls back a transaction
395
+	 *
396
+	 * @return bool
397
+	 */
398
+	public function transactionAbort()
399
+	{
400
+		if (version_compare(PHP_VERSION, '5.5.0') < 0 || $this->linkId === 0) {
401
+			return true;
402
+		}
403
+		return mysqli_rollback($this->linkId);
404
+	}
405
+
406
+	/**
407
+	 * This will get the last insert ID created on the current connection.  Should only be called after an insert query is
408
+	 * run on a table that has an auto incrementing field.  $table and $field are required, but unused here since it's
409
+	 * unnecessary for mysql.  For compatibility with pgsql, the params must be supplied.
410
+	 *
411
+	 * @param string $table
412
+	 * @param string $field
413
+	 * @return int|string
414
+	 */
415
+	public function getLastInsertId($table, $field)
416
+	{
417
+		if (!isset($table) || $table == '' || !isset($field) || $field == '') {
418
+			return -1;
419
+		}
420
+
421
+		return @mysqli_insert_id($this->linkId);
422
+	}
423
+
424
+	/* public: table locking */
425
+
426
+	/**
427
+	 * Db::lock()
428
+	 * @param mixed  $table
429
+	 * @param string $mode
430
+	 * @return bool|int|\mysqli_result
431
+	 */
432
+	public function lock($table, $mode = 'write')
433
+	{
434
+		$this->connect();
435
+		$query = 'lock tables ';
436
+		if (is_array($table)) {
437
+			foreach ($table as $key => $value) {
438
+				if ($key == 'read' && $key != 0) {
439
+					$query .= "$value read, ";
440
+				} else {
441
+					$query .= "$value $mode, ";
442
+				}
443
+			}
444
+			$query = mb_substr($query, 0, -2);
445
+		} else {
446
+			$query .= "$table $mode";
447
+		}
448
+		$res = @mysqli_query($this->linkId, $query);
449
+		if (!$res) {
450
+			$this->halt("lock($table, $mode) failed.");
451
+			return 0;
452
+		}
453
+		return $res;
454
+	}
455
+
456
+	/**
457
+	 * Db::unlock()
458
+	 * @param bool $haltOnError optional, defaults to TRUE, whether or not to halt on error
459
+	 * @return bool|int|\mysqli_result
460
+	 */
461
+	public function unlock($haltOnError = true)
462
+	{
463
+		$this->connect();
464
+
465
+		$res = @mysqli_query($this->linkId, 'unlock tables');
466
+		if ($haltOnError === true && !$res) {
467
+			$this->halt('unlock() failed.');
468
+			return 0;
469
+		}
470
+		return $res;
471
+	}
472
+
473
+	/* public: evaluate the result (size, width) */
474
+
475
+	/**
476
+	 * Db::affectedRows()
477
+	 * @return int
478
+	 */
479
+	public function affectedRows()
480
+	{
481
+		return @mysqli_affected_rows($this->linkId);
482
+	}
483
+
484
+	/**
485
+	 * Db::num_rows()
486
+	 * @return int
487
+	 */
488
+	public function num_rows()
489
+	{
490
+		return @mysqli_num_rows($this->queryId);
491
+	}
492
+
493
+	/**
494
+	 * Db::num_fields()
495
+	 * @return int
496
+	 */
497
+	public function num_fields()
498
+	{
499
+		return @mysqli_num_fields($this->queryId);
500
+	}
501
+
502
+	/**
503
+	 * gets an array of the table names in teh current datase
504
+	 *
505
+	 * @return array
506
+	 */
507
+	public function tableNames()
508
+	{
509
+		$return = [];
510
+		$this->query('SHOW TABLES');
511
+		$i = 0;
512
+		while ($info = $this->queryId->fetch_row()) {
513
+			$return[$i]['table_name'] = $info[0];
514
+			$return[$i]['tablespace_name'] = $this->database;
515
+			$return[$i]['database'] = $this->database;
516
+			++$i;
517
+		}
518
+		return $return;
519
+	}
520 520
 }
521 521
 
522 522
 /**
Please login to merge, or discard this patch.
Braces   +24 added lines, -48 removed lines patch added patch discarded remove patch
@@ -17,8 +17,7 @@  discard block
 block discarded – undo
17 17
  *
18 18
  * @access public
19 19
  */
20
-class Db extends Generic implements Db_Interface
21
-{
20
+class Db extends Generic implements Db_Interface {
22 21
     /**
23 22
      * @var string
24 23
      */
@@ -30,8 +29,7 @@  discard block
 block discarded – undo
30 29
      * @param string $database the name of the database to use
31 30
      * @return void
32 31
      */
33
-    public function useDb($database)
34
-    {
32
+    public function useDb($database) {
35 33
         $this->selectDb($database);
36 34
     }
37 35
 
@@ -41,8 +39,7 @@  discard block
 block discarded – undo
41 39
      * @param string $database the name of the database to use
42 40
      * @return void
43 41
      */
44
-    public function selectDb($database)
45
-    {
42
+    public function selectDb($database) {
46 43
         $this->connect();
47 44
         mysqli_select_db($this->linkId, $database);
48 45
     }
@@ -57,8 +54,7 @@  discard block
 block discarded – undo
57 54
      * @param string $password
58 55
      * @return int|\mysqli
59 56
      */
60
-    public function connect($database = '', $host = '', $user = '', $password = '', $port = '')
61
-    {
57
+    public function connect($database = '', $host = '', $user = '', $password = '', $port = '') {
62 58
         /* Handle defaults */
63 59
         if ($database == '') {
64 60
             $database = $this->database;
@@ -105,8 +101,7 @@  discard block
 block discarded – undo
105 101
      * Db::disconnect()
106 102
      * @return bool
107 103
      */
108
-    public function disconnect()
109
-    {
104
+    public function disconnect() {
110 105
         $return = !is_int($this->linkId) && method_exists($this->linkId, 'close') ? $this->linkId->close() : false;
111 106
         $this->linkId = 0;
112 107
         return $return;
@@ -116,8 +111,7 @@  discard block
 block discarded – undo
116 111
      * @param $string
117 112
      * @return string
118 113
      */
119
-    public function real_escape($string = '')
120
-    {
114
+    public function real_escape($string = '') {
121 115
         if ((!is_resource($this->linkId) || $this->linkId == 0) && !$this->connect()) {
122 116
             return $this->escape($string);
123 117
         }
@@ -128,8 +122,7 @@  discard block
 block discarded – undo
128 122
      * discard the query result
129 123
      * @return void
130 124
      */
131
-    public function free()
132
-    {
125
+    public function free() {
133 126
         if (is_resource($this->queryId)) {
134 127
             @mysqli_free_result($this->queryId);
135 128
         }
@@ -147,8 +140,7 @@  discard block
 block discarded – undo
147 140
      * @param string $file optionally pass __FILE__ calling the query for logging
148 141
      * @return mixed FALSE if no rows, if a single row it returns that, if multiple it returns an array of rows, associative responses only
149 142
      */
150
-    public function queryReturn($query, $line = '', $file = '')
151
-    {
143
+    public function queryReturn($query, $line = '', $file = '') {
152 144
         $this->query($query, $line, $file);
153 145
         if ($this->num_rows() == 0) {
154 146
             return false;
@@ -174,8 +166,7 @@  discard block
 block discarded – undo
174 166
      * @param string $file optionally pass __FILE__ calling the query for logging
175 167
      * @return mixed FALSE if no rows, if a single row it returns that, if multiple it returns an array of rows, associative responses only
176 168
      */
177
-    public function qr($query, $line = '', $file = '')
178
-    {
169
+    public function qr($query, $line = '', $file = '') {
179 170
         return $this->queryReturn($query, $line, $file);
180 171
     }
181 172
 
@@ -187,8 +178,7 @@  discard block
 block discarded – undo
187 178
      * @param string $line
188 179
      * @param string $file
189 180
      */
190
-    public function prepare($query, $line = '', $file = '')
191
-    {
181
+    public function prepare($query, $line = '', $file = '') {
192 182
         if (!$this->connect()) {
193 183
             return 0;
194 184
         }
@@ -213,8 +203,7 @@  discard block
 block discarded – undo
213 203
      * @param bool $log
214 204
      * @return mixed 0 if no query or query id handler, safe to ignore this return
215 205
      */
216
-    public function query($queryString, $line = '', $file = '', $log = false)
217
-    {
206
+    public function query($queryString, $line = '', $file = '', $log = false) {
218 207
         /* No empty queries, please, since PHP4 chokes on them. */
219 208
         /* The empty query string is passed on from the constructor,
220 209
         * when calling the class without a query, e.g. in situations
@@ -306,8 +295,7 @@  discard block
 block discarded – undo
306 295
     /**
307 296
      * @return array|null|object
308 297
      */
309
-    public function fetchObject()
310
-    {
298
+    public function fetchObject() {
311 299
         $this->Record = @mysqli_fetch_object($this->queryId);
312 300
         return $this->Record;
313 301
     }
@@ -320,8 +308,7 @@  discard block
 block discarded – undo
320 308
      * @param mixed $resultType
321 309
      * @return bool
322 310
      */
323
-    public function next_record($resultType = MYSQLI_BOTH)
324
-    {
311
+    public function next_record($resultType = MYSQLI_BOTH) {
325 312
         if ($this->queryId === false) {
326 313
             $this->haltmsg('next_record called with no query pending.');
327 314
             return 0;
@@ -345,8 +332,7 @@  discard block
 block discarded – undo
345 332
      * @param integer $pos the row numbe starting at 0 to switch to
346 333
      * @return bool whetherit was successfu or not.
347 334
      */
348
-    public function seek($pos = 0)
349
-    {
335
+    public function seek($pos = 0) {
350 336
         $status = @mysqli_data_seek($this->queryId, $pos);
351 337
         if ($status) {
352 338
             $this->Row = $pos;
@@ -366,8 +352,7 @@  discard block
 block discarded – undo
366 352
      *
367 353
      * @return bool
368 354
      */
369
-    public function transactionBegin()
370
-    {
355
+    public function transactionBegin() {
371 356
         if (version_compare(PHP_VERSION, '5.5.0') < 0) {
372 357
             return true;
373 358
         }
@@ -382,8 +367,7 @@  discard block
 block discarded – undo
382 367
      *
383 368
      * @return bool
384 369
      */
385
-    public function transactionCommit()
386
-    {
370
+    public function transactionCommit() {
387 371
         if (version_compare(PHP_VERSION, '5.5.0') < 0 || $this->linkId === 0) {
388 372
             return true;
389 373
         }
@@ -395,8 +379,7 @@  discard block
 block discarded – undo
395 379
      *
396 380
      * @return bool
397 381
      */
398
-    public function transactionAbort()
399
-    {
382
+    public function transactionAbort() {
400 383
         if (version_compare(PHP_VERSION, '5.5.0') < 0 || $this->linkId === 0) {
401 384
             return true;
402 385
         }
@@ -412,8 +395,7 @@  discard block
 block discarded – undo
412 395
      * @param string $field
413 396
      * @return int|string
414 397
      */
415
-    public function getLastInsertId($table, $field)
416
-    {
398
+    public function getLastInsertId($table, $field) {
417 399
         if (!isset($table) || $table == '' || !isset($field) || $field == '') {
418 400
             return -1;
419 401
         }
@@ -429,8 +411,7 @@  discard block
 block discarded – undo
429 411
      * @param string $mode
430 412
      * @return bool|int|\mysqli_result
431 413
      */
432
-    public function lock($table, $mode = 'write')
433
-    {
414
+    public function lock($table, $mode = 'write') {
434 415
         $this->connect();
435 416
         $query = 'lock tables ';
436 417
         if (is_array($table)) {
@@ -458,8 +439,7 @@  discard block
 block discarded – undo
458 439
      * @param bool $haltOnError optional, defaults to TRUE, whether or not to halt on error
459 440
      * @return bool|int|\mysqli_result
460 441
      */
461
-    public function unlock($haltOnError = true)
462
-    {
442
+    public function unlock($haltOnError = true) {
463 443
         $this->connect();
464 444
 
465 445
         $res = @mysqli_query($this->linkId, 'unlock tables');
@@ -476,8 +456,7 @@  discard block
 block discarded – undo
476 456
      * Db::affectedRows()
477 457
      * @return int
478 458
      */
479
-    public function affectedRows()
480
-    {
459
+    public function affectedRows() {
481 460
         return @mysqli_affected_rows($this->linkId);
482 461
     }
483 462
 
@@ -485,8 +464,7 @@  discard block
 block discarded – undo
485 464
      * Db::num_rows()
486 465
      * @return int
487 466
      */
488
-    public function num_rows()
489
-    {
467
+    public function num_rows() {
490 468
         return @mysqli_num_rows($this->queryId);
491 469
     }
492 470
 
@@ -494,8 +472,7 @@  discard block
 block discarded – undo
494 472
      * Db::num_fields()
495 473
      * @return int
496 474
      */
497
-    public function num_fields()
498
-    {
475
+    public function num_fields() {
499 476
         return @mysqli_num_fields($this->queryId);
500 477
     }
501 478
 
@@ -504,8 +481,7 @@  discard block
 block discarded – undo
504 481
      *
505 482
      * @return array
506 483
      */
507
-    public function tableNames()
508
-    {
484
+    public function tableNames() {
509 485
         $return = [];
510 486
         $this->query('SHOW TABLES');
511 487
         $i = 0;
Please login to merge, or discard this patch.
src/Generic.php 2 patches
Indentation   +383 added lines, -383 removed lines patch added patch discarded remove patch
@@ -14,387 +14,387 @@
 block discarded – undo
14 14
  */
15 15
 abstract class Generic
16 16
 {
17
-    /* public: connection parameters */
18
-    public $host = 'localhost';
19
-    public $database = '';
20
-    public $user = '';
21
-    public $password = '';
22
-    public $port = '';
23
-
24
-    /* public: configuration parameters */
25
-    public $autoStripslashes = false;
26
-    public $Debug = 0; // Set to 1 for debugging messages.
27
-    public $haltOnError = 'yes'; // "yes" (halt with message), "no" (ignore errors quietly), "report" (ignore error, but spit a warning)
28
-
29
-    public $maxConnectErrors = 5;
30
-    public $connectionAttempt = 0;
31
-    public $maxMatches = 10000000;
32
-
33
-    public $Type = 'mysql';
34
-
35
-    /**
36
-     * @var int
37
-     */
38
-    public $autoFree = 0; // Set to 1 for automatic mysql_free_result()
39
-
40
-    /* public: result array and current row number */
41
-    public $Record = [];
42
-    public $Row;
43
-
44
-    /* public: current error number and error text */
45
-    public $Errno = 0;
46
-    public $Error = '';
47
-
48
-    /* public: this is an api revision, not a CVS revision. */
49
-    public $type = 'generic';
50
-
51
-    /**
52
-     * @var int|object
53
-     */
54
-    public $linkId = 0;
55
-    public $queryId = 0;
56
-
57
-    public $characterSet = 'utf8mb4';
58
-    public $collation = 'utf8mb4_unicode_ci';
59
-
60
-    /**
61
-     * Logged queries.
62
-     * @var array
63
-     */
64
-    protected $log = [];
65
-
66
-    /**
67
-     * Constructs the db handler, can optionally specify connection parameters
68
-     *
69
-     * @param string $database Optional The database name
70
-     * @param string $user Optional The username to connect with
71
-     * @param string $password Optional The password to use
72
-     * @param string $host Optional The hostname where the server is, or default to localhost
73
-     * @param string $query Optional query to perform immediately
74
-     * @param string $port optional port for the connection
75
-     */
76
-    public function __construct($database = '', $user = '', $password = '', $host = 'localhost', $query = '', $port = '')
77
-    {
78
-        $this->database = $database;
79
-        $this->user = $user;
80
-        $this->password = $password;
81
-        $this->host = $host;
82
-        $this->port = $port;
83
-        if ($query != '') {
84
-            $this->query($query);
85
-        }
86
-        $this->connectionAttempt = 0;
87
-    }
88
-
89
-    /**
90
-     * @param string $message
91
-     * @param string $line
92
-     * @param string $file
93
-     * @return void
94
-     */
95
-    public function log($message, $line = '', $file = '', $level = 'info')
96
-    {
97
-        error_log('SQL Query '.$line.' '.$file.' '.$message);
98
-    }
99
-
100
-    /**
101
-     * @return int|object
102
-     */
103
-    public function linkId()
104
-    {
105
-        return $this->linkId;
106
-    }
107
-
108
-    /**
109
-     * @return int|object
110
-     */
111
-    public function queryId()
112
-    {
113
-        return $this->queryId;
114
-    }
115
-
116
-    /**
117
-     * @param $string
118
-     * @return string
119
-     */
120
-    public function real_escape($string = '')
121
-    {
122
-        if ((!is_resource($this->linkId) || $this->linkId == 0) && !$this->connect()) {
123
-            return $this->escape($string);
124
-        }
125
-        return mysqli_real_escape_string($this->linkId, $string);
126
-    }
127
-
128
-    /**
129
-     * @param $string
130
-     * @return string
131
-     */
132
-    public function escape($string = '')
133
-    {
134
-        //if (function_exists('mysql_escape_string'))
135
-        //return mysql_escape_string($string);
136
-        return str_replace(['\\', "\0", "\n", "\r", "'", '"', "\x1a"], ['\\\\', '\\0', '\\n', '\\r', "\\'", '\\"', '\\Z'], $string);
137
-    }
138
-
139
-    /**
140
-     * @param mixed $str
141
-     * @return string
142
-     */
143
-    public function dbAddslashes($str = '')
144
-    {
145
-        if (!isset($str) || $str == '') {
146
-            return '';
147
-        }
148
-        return addslashes($str);
149
-    }
150
-
151
-    /**
152
-     * Db::toTimestamp()
153
-     * @param mixed $epoch
154
-     * @return bool|string
155
-     */
156
-    public function toTimestamp($epoch)
157
-    {
158
-        return date('Y-m-d H:i:s', is_float($epoch) ? intval($epoch) : $epoch);
159
-    }
160
-
161
-    /**
162
-     * Db::fromTimestamp()
163
-     * @param mixed $timestamp
164
-     * @return bool|int|mixed
165
-     */
166
-    public function fromTimestamp($timestamp)
167
-    {
168
-        if (preg_match('/([0-9]{4})-([0-9]{2})-([0-9]{2}) ([0-9]{2}):([0-9]{2}):([0-9]{2})/', $timestamp, $parts)) {
169
-            $time = mktime($parts[4], $parts[5], $parts[6], $parts[2], $parts[3], $parts[1]);
170
-        } elseif (preg_match('/([0-9]{4})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})/', $timestamp, $parts)) {
171
-            $time = mktime($parts[4], $parts[5], $parts[6], $parts[2], $parts[3], $parts[1]);
172
-        } elseif (preg_match('/([0-9]{4})([0-9]{2})([0-9]{2})/', $timestamp, $parts)) {
173
-            $time = mktime(1, 1, 1, $parts[2], $parts[3], $parts[1]);
174
-        } elseif (is_numeric($timestamp) && $timestamp >= 943938000) {
175
-            $time = $timestamp;
176
-        } else {
177
-            $this->log('Cannot Match Timestamp from '.$timestamp, __LINE__, __FILE__);
178
-            $time = false;
179
-        }
180
-        return $time;
181
-    }
182
-
183
-    /**
184
-     * perform a query with limited result set
185
-     *
186
-     * @param string $queryString
187
-     * @param string|int $numRows
188
-     * @param int $offset
189
-     * @param string|int $line
190
-     * @param string $file
191
-     * @return mixed
192
-     */
193
-    public function limitQuery($queryString, $numRows = '', $offset = 0, $line = '', $file = '')
194
-    {
195
-        if (!$numRows) {
196
-            $numRows = $this->maxMatches;
197
-        }
198
-        if ($offset == 0) {
199
-            $queryString .= ' LIMIT '.(int) $numRows;
200
-        } else {
201
-            $queryString .= ' LIMIT '.(int) $offset.','.(int) $numRows;
202
-        }
203
-
204
-        if ($this->Debug) {
205
-            printf("Debug: limitQuery = %s<br>offset=%d, num_rows=%d<br>\n", $queryString, $offset, $numRows);
206
-        }
207
-
208
-        return $this->query($queryString, $line, $file);
209
-    }
210
-
211
-    /**
212
-     * db:qr()
213
-     *
214
-     *  alias of queryReturn()
215
-     *
216
-     * @param mixed $query SQL Query to be used
217
-     * @param string $line optionally pass __LINE__ calling the query for logging
218
-     * @param string $file optionally pass __FILE__ calling the query for logging
219
-     * @return mixed FALSE if no rows, if a single row it returns that, if multiple it returns an array of rows, associative responses only
220
-     */
221
-    public function qr($query, $line = '', $file = '')
222
-    {
223
-        return $this->queryReturn($query, $line, $file);
224
-    }
225
-
226
-    /**
227
-     * gets a field
228
-     *
229
-     * @param mixed  $name
230
-     * @param string $stripSlashes
231
-     * @return string
232
-     */
233
-    public function f($name, $stripSlashes = '')
234
-    {
235
-        if (is_null($this->Record)) {
236
-            return null;
237
-        } elseif ($stripSlashes || ($this->autoStripslashes && !$stripSlashes)) {
238
-            return stripslashes($this->Record[$name]);
239
-        } else {
240
-            return $this->Record[$name];
241
-        }
242
-    }
243
-
244
-    /**
245
-     * error handling
246
-     *
247
-     * @param mixed $msg
248
-     * @param string $line
249
-     * @param string $file
250
-     * @return void
251
-     */
252
-    public function halt($msg, $line = '', $file = '')
253
-    {
254
-        $this->unlock(false);
255
-        /* Just in case there is a table currently locked */
256
-
257
-        //$this->Error = @$this->linkId->error;
258
-        //$this->Errno = @$this->linkId->errno;
259
-        if ($this->haltOnError == 'no') {
260
-            return true;
261
-        }
262
-        if ($msg != '') {
263
-            $this->haltmsg($msg, $line, $file);
264
-        }
265
-        if ($this->haltOnError != 'report') {
266
-            echo '<p><b>Session halted.</b>';
267
-            //if (isset($GLOBALS['tf']))
268
-            //$GLOBALS['tf']->terminate();
269
-            die();
270
-        }
271
-        return true;
272
-    }
273
-
274
-    /**
275
-     * @param mixed $msg
276
-     * @param string $line
277
-     * @param string $file
278
-     * @return mixed|void
279
-     */
280
-    public function logBackTrace($msg, $line = '', $file = '')
281
-    {
282
-        $backtrace = (function_exists('debug_backtrace') ? debug_backtrace() : []);
283
-        $this->log(
284
-            ('' !== getenv('REQUEST_URI') ? ' '.getenv('REQUEST_URI') : '').
285
-            ((isset($_POST) && count($_POST)) ? ' POST='.json_encode($_POST) : '').
286
-            ((isset($_GET) && count($_GET)) ? ' GET='.json_encode($_GET) : '').
287
-            ((isset($_FILES) && count($_FILES)) ? ' FILES='.json_encode($_FILES) : '').
288
-            ('' !== getenv('HTTP_USER_AGENT') ? ' AGENT="'.getenv('HTTP_USER_AGENT').'"' : '').
289
-            (isset($_SERVER['REQUEST_METHOD']) ? ' METHOD="'.$_SERVER['REQUEST_METHOD'].'"'.
290
-                ($_SERVER['REQUEST_METHOD'] === 'POST' ? ' POST="'.json_encode($_POST).'"' : '') : ''),
291
-            $line,
292
-            $file,
293
-            'error'
294
-        );
295
-        for ($level = 1, $levelMax = count($backtrace); $level < $levelMax; $level++) {
296
-            $message = (isset($backtrace[$level]['file']) ? 'File: '.$backtrace[$level]['file'] : '').
297
-                (isset($backtrace[$level]['line']) ? ' Line: '.$backtrace[$level]['line'] : '').
298
-                ' Function: '.(isset($backtrace[$level] ['class']) ? '(class '.$backtrace[$level] ['class'].') ' : '').
299
-                (isset($backtrace[$level] ['type']) ? $backtrace[$level] ['type'].' ' : '').
300
-                $backtrace[$level] ['function'].'(';
301
-            if (isset($backtrace[$level] ['args'])) {
302
-                for ($argument = 0, $argumentMax = count($backtrace[$level]['args']); $argument < $argumentMax; $argument++) {
303
-                    $message .= ($argument > 0 ? ', ' : '').
304
-                        (is_object($backtrace[$level]['args'][$argument]) ? 'class '.get_class($backtrace[$level]['args'][$argument]) : json_encode($backtrace[$level]['args'][$argument]));
305
-                }
306
-            }
307
-            $message .= ')';
308
-            $this->log($message, $line, $file, 'error');
309
-        }
310
-    }
311
-
312
-    public function emailError($queryString, $error, $line, $file)
313
-    {
314
-        $subject = php_uname('n').' MySQLi Error '.$queryString;
315
-        if (class_exists('\\TFSmarty')) {
316
-            $smarty = new \TFSmarty();
317
-            $smarty->assign([
318
-                'type' => $this->type,
319
-                'queryString' => $queryString,
320
-                'error' => $error,
321
-                'line' => $line,
322
-                'file' => $file,
323
-                'request' => $_REQUEST,
324
-                'server' => $_SERVER,
325
-            ]);
326
-            if (isset($GLOBALS['tf'])) {
327
-                $smarty->assign('account_id', $GLOBALS['tf']->session->account_id);
328
-            }
329
-            $email = $smarty->fetch('email/admin/sql_error.tpl');
330
-            (new \MyAdmin\Mail())->adminMail($subject, $email, '[email protected]', '');
331
-            (new \MyAdmin\Mail())->adminMail($subject, $email, '[email protected]', '');
332
-        }
333
-        $this->haltmsg('Invalid SQL: '.$queryString, $line, $file);
334
-    }
335
-
336
-    /**
337
-     * @param mixed $msg
338
-     * @param string $line
339
-     * @param string $file
340
-     * @return mixed|void
341
-     */
342
-    public function haltmsg($msg, $line = '', $file = '')
343
-    {
344
-        $email = "DB Error {$msg} {$file}:{$line}";
345
-        if (class_exists('\\MyAdmin\Mail')) {
346
-            \MyAdmin\Mail::failsafeMail($email, $email, ['[email protected]', '[email protected]']);
347
-            return;
348
-        }
349
-        $this->log("Database error: $msg", $line, $file, 'error');
350
-        if ($this->Errno != '0' || !in_array($this->Error, ['', '()'])) {
351
-            $sqlstate = mysqli_sqlstate($this->linkId);
352
-            $this->log("MySQLi SQLState: {$sqlstate}. Error: ".$this->Errno.' ('.$this->Error.')', $line, $file, 'error');
353
-        }
354
-        $this->logBackTrace($msg, $line, $file);
355
-    }
356
-
357
-    /**
358
-     * @return array
359
-     */
360
-    public function indexNames()
361
-    {
362
-        return [];
363
-    }
364
-
365
-
366
-    /**
367
-     * Add query to logged queries.
368
-     * @param string $statement
369
-     * @param float $time Elapsed seconds with microseconds
370
-     * @param string|int $line Line Number
371
-     * @param string $file File Name
372
-     */
373
-    public function addLog($statement, $time, $line = '', $file = '')
374
-    {
375
-        $query = [
376
-            'statement' => $statement,
377
-            'time' => $time * 1000
378
-        ];
379
-        if ($line != '') {
380
-            $query['line'] = $line;
381
-        }
382
-        if ($file != '') {
383
-            $query['file'] = $file;
384
-        }
385
-        if (!isset($GLOBALS['db_queries'])) {
386
-            $GLOBALS['db_queries'] = [];
387
-        }
388
-        $GLOBALS['db_queries'][] = $query;
389
-        array_push($this->log, $query);
390
-    }
391
-
392
-    /**
393
-     * Return logged queries.
394
-     * @return array Logged queries
395
-     */
396
-    public function getLog()
397
-    {
398
-        return $this->log;
399
-    }
17
+	/* public: connection parameters */
18
+	public $host = 'localhost';
19
+	public $database = '';
20
+	public $user = '';
21
+	public $password = '';
22
+	public $port = '';
23
+
24
+	/* public: configuration parameters */
25
+	public $autoStripslashes = false;
26
+	public $Debug = 0; // Set to 1 for debugging messages.
27
+	public $haltOnError = 'yes'; // "yes" (halt with message), "no" (ignore errors quietly), "report" (ignore error, but spit a warning)
28
+
29
+	public $maxConnectErrors = 5;
30
+	public $connectionAttempt = 0;
31
+	public $maxMatches = 10000000;
32
+
33
+	public $Type = 'mysql';
34
+
35
+	/**
36
+	 * @var int
37
+	 */
38
+	public $autoFree = 0; // Set to 1 for automatic mysql_free_result()
39
+
40
+	/* public: result array and current row number */
41
+	public $Record = [];
42
+	public $Row;
43
+
44
+	/* public: current error number and error text */
45
+	public $Errno = 0;
46
+	public $Error = '';
47
+
48
+	/* public: this is an api revision, not a CVS revision. */
49
+	public $type = 'generic';
50
+
51
+	/**
52
+	 * @var int|object
53
+	 */
54
+	public $linkId = 0;
55
+	public $queryId = 0;
56
+
57
+	public $characterSet = 'utf8mb4';
58
+	public $collation = 'utf8mb4_unicode_ci';
59
+
60
+	/**
61
+	 * Logged queries.
62
+	 * @var array
63
+	 */
64
+	protected $log = [];
65
+
66
+	/**
67
+	 * Constructs the db handler, can optionally specify connection parameters
68
+	 *
69
+	 * @param string $database Optional The database name
70
+	 * @param string $user Optional The username to connect with
71
+	 * @param string $password Optional The password to use
72
+	 * @param string $host Optional The hostname where the server is, or default to localhost
73
+	 * @param string $query Optional query to perform immediately
74
+	 * @param string $port optional port for the connection
75
+	 */
76
+	public function __construct($database = '', $user = '', $password = '', $host = 'localhost', $query = '', $port = '')
77
+	{
78
+		$this->database = $database;
79
+		$this->user = $user;
80
+		$this->password = $password;
81
+		$this->host = $host;
82
+		$this->port = $port;
83
+		if ($query != '') {
84
+			$this->query($query);
85
+		}
86
+		$this->connectionAttempt = 0;
87
+	}
88
+
89
+	/**
90
+	 * @param string $message
91
+	 * @param string $line
92
+	 * @param string $file
93
+	 * @return void
94
+	 */
95
+	public function log($message, $line = '', $file = '', $level = 'info')
96
+	{
97
+		error_log('SQL Query '.$line.' '.$file.' '.$message);
98
+	}
99
+
100
+	/**
101
+	 * @return int|object
102
+	 */
103
+	public function linkId()
104
+	{
105
+		return $this->linkId;
106
+	}
107
+
108
+	/**
109
+	 * @return int|object
110
+	 */
111
+	public function queryId()
112
+	{
113
+		return $this->queryId;
114
+	}
115
+
116
+	/**
117
+	 * @param $string
118
+	 * @return string
119
+	 */
120
+	public function real_escape($string = '')
121
+	{
122
+		if ((!is_resource($this->linkId) || $this->linkId == 0) && !$this->connect()) {
123
+			return $this->escape($string);
124
+		}
125
+		return mysqli_real_escape_string($this->linkId, $string);
126
+	}
127
+
128
+	/**
129
+	 * @param $string
130
+	 * @return string
131
+	 */
132
+	public function escape($string = '')
133
+	{
134
+		//if (function_exists('mysql_escape_string'))
135
+		//return mysql_escape_string($string);
136
+		return str_replace(['\\', "\0", "\n", "\r", "'", '"', "\x1a"], ['\\\\', '\\0', '\\n', '\\r', "\\'", '\\"', '\\Z'], $string);
137
+	}
138
+
139
+	/**
140
+	 * @param mixed $str
141
+	 * @return string
142
+	 */
143
+	public function dbAddslashes($str = '')
144
+	{
145
+		if (!isset($str) || $str == '') {
146
+			return '';
147
+		}
148
+		return addslashes($str);
149
+	}
150
+
151
+	/**
152
+	 * Db::toTimestamp()
153
+	 * @param mixed $epoch
154
+	 * @return bool|string
155
+	 */
156
+	public function toTimestamp($epoch)
157
+	{
158
+		return date('Y-m-d H:i:s', is_float($epoch) ? intval($epoch) : $epoch);
159
+	}
160
+
161
+	/**
162
+	 * Db::fromTimestamp()
163
+	 * @param mixed $timestamp
164
+	 * @return bool|int|mixed
165
+	 */
166
+	public function fromTimestamp($timestamp)
167
+	{
168
+		if (preg_match('/([0-9]{4})-([0-9]{2})-([0-9]{2}) ([0-9]{2}):([0-9]{2}):([0-9]{2})/', $timestamp, $parts)) {
169
+			$time = mktime($parts[4], $parts[5], $parts[6], $parts[2], $parts[3], $parts[1]);
170
+		} elseif (preg_match('/([0-9]{4})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})/', $timestamp, $parts)) {
171
+			$time = mktime($parts[4], $parts[5], $parts[6], $parts[2], $parts[3], $parts[1]);
172
+		} elseif (preg_match('/([0-9]{4})([0-9]{2})([0-9]{2})/', $timestamp, $parts)) {
173
+			$time = mktime(1, 1, 1, $parts[2], $parts[3], $parts[1]);
174
+		} elseif (is_numeric($timestamp) && $timestamp >= 943938000) {
175
+			$time = $timestamp;
176
+		} else {
177
+			$this->log('Cannot Match Timestamp from '.$timestamp, __LINE__, __FILE__);
178
+			$time = false;
179
+		}
180
+		return $time;
181
+	}
182
+
183
+	/**
184
+	 * perform a query with limited result set
185
+	 *
186
+	 * @param string $queryString
187
+	 * @param string|int $numRows
188
+	 * @param int $offset
189
+	 * @param string|int $line
190
+	 * @param string $file
191
+	 * @return mixed
192
+	 */
193
+	public function limitQuery($queryString, $numRows = '', $offset = 0, $line = '', $file = '')
194
+	{
195
+		if (!$numRows) {
196
+			$numRows = $this->maxMatches;
197
+		}
198
+		if ($offset == 0) {
199
+			$queryString .= ' LIMIT '.(int) $numRows;
200
+		} else {
201
+			$queryString .= ' LIMIT '.(int) $offset.','.(int) $numRows;
202
+		}
203
+
204
+		if ($this->Debug) {
205
+			printf("Debug: limitQuery = %s<br>offset=%d, num_rows=%d<br>\n", $queryString, $offset, $numRows);
206
+		}
207
+
208
+		return $this->query($queryString, $line, $file);
209
+	}
210
+
211
+	/**
212
+	 * db:qr()
213
+	 *
214
+	 *  alias of queryReturn()
215
+	 *
216
+	 * @param mixed $query SQL Query to be used
217
+	 * @param string $line optionally pass __LINE__ calling the query for logging
218
+	 * @param string $file optionally pass __FILE__ calling the query for logging
219
+	 * @return mixed FALSE if no rows, if a single row it returns that, if multiple it returns an array of rows, associative responses only
220
+	 */
221
+	public function qr($query, $line = '', $file = '')
222
+	{
223
+		return $this->queryReturn($query, $line, $file);
224
+	}
225
+
226
+	/**
227
+	 * gets a field
228
+	 *
229
+	 * @param mixed  $name
230
+	 * @param string $stripSlashes
231
+	 * @return string
232
+	 */
233
+	public function f($name, $stripSlashes = '')
234
+	{
235
+		if (is_null($this->Record)) {
236
+			return null;
237
+		} elseif ($stripSlashes || ($this->autoStripslashes && !$stripSlashes)) {
238
+			return stripslashes($this->Record[$name]);
239
+		} else {
240
+			return $this->Record[$name];
241
+		}
242
+	}
243
+
244
+	/**
245
+	 * error handling
246
+	 *
247
+	 * @param mixed $msg
248
+	 * @param string $line
249
+	 * @param string $file
250
+	 * @return void
251
+	 */
252
+	public function halt($msg, $line = '', $file = '')
253
+	{
254
+		$this->unlock(false);
255
+		/* Just in case there is a table currently locked */
256
+
257
+		//$this->Error = @$this->linkId->error;
258
+		//$this->Errno = @$this->linkId->errno;
259
+		if ($this->haltOnError == 'no') {
260
+			return true;
261
+		}
262
+		if ($msg != '') {
263
+			$this->haltmsg($msg, $line, $file);
264
+		}
265
+		if ($this->haltOnError != 'report') {
266
+			echo '<p><b>Session halted.</b>';
267
+			//if (isset($GLOBALS['tf']))
268
+			//$GLOBALS['tf']->terminate();
269
+			die();
270
+		}
271
+		return true;
272
+	}
273
+
274
+	/**
275
+	 * @param mixed $msg
276
+	 * @param string $line
277
+	 * @param string $file
278
+	 * @return mixed|void
279
+	 */
280
+	public function logBackTrace($msg, $line = '', $file = '')
281
+	{
282
+		$backtrace = (function_exists('debug_backtrace') ? debug_backtrace() : []);
283
+		$this->log(
284
+			('' !== getenv('REQUEST_URI') ? ' '.getenv('REQUEST_URI') : '').
285
+			((isset($_POST) && count($_POST)) ? ' POST='.json_encode($_POST) : '').
286
+			((isset($_GET) && count($_GET)) ? ' GET='.json_encode($_GET) : '').
287
+			((isset($_FILES) && count($_FILES)) ? ' FILES='.json_encode($_FILES) : '').
288
+			('' !== getenv('HTTP_USER_AGENT') ? ' AGENT="'.getenv('HTTP_USER_AGENT').'"' : '').
289
+			(isset($_SERVER['REQUEST_METHOD']) ? ' METHOD="'.$_SERVER['REQUEST_METHOD'].'"'.
290
+				($_SERVER['REQUEST_METHOD'] === 'POST' ? ' POST="'.json_encode($_POST).'"' : '') : ''),
291
+			$line,
292
+			$file,
293
+			'error'
294
+		);
295
+		for ($level = 1, $levelMax = count($backtrace); $level < $levelMax; $level++) {
296
+			$message = (isset($backtrace[$level]['file']) ? 'File: '.$backtrace[$level]['file'] : '').
297
+				(isset($backtrace[$level]['line']) ? ' Line: '.$backtrace[$level]['line'] : '').
298
+				' Function: '.(isset($backtrace[$level] ['class']) ? '(class '.$backtrace[$level] ['class'].') ' : '').
299
+				(isset($backtrace[$level] ['type']) ? $backtrace[$level] ['type'].' ' : '').
300
+				$backtrace[$level] ['function'].'(';
301
+			if (isset($backtrace[$level] ['args'])) {
302
+				for ($argument = 0, $argumentMax = count($backtrace[$level]['args']); $argument < $argumentMax; $argument++) {
303
+					$message .= ($argument > 0 ? ', ' : '').
304
+						(is_object($backtrace[$level]['args'][$argument]) ? 'class '.get_class($backtrace[$level]['args'][$argument]) : json_encode($backtrace[$level]['args'][$argument]));
305
+				}
306
+			}
307
+			$message .= ')';
308
+			$this->log($message, $line, $file, 'error');
309
+		}
310
+	}
311
+
312
+	public function emailError($queryString, $error, $line, $file)
313
+	{
314
+		$subject = php_uname('n').' MySQLi Error '.$queryString;
315
+		if (class_exists('\\TFSmarty')) {
316
+			$smarty = new \TFSmarty();
317
+			$smarty->assign([
318
+				'type' => $this->type,
319
+				'queryString' => $queryString,
320
+				'error' => $error,
321
+				'line' => $line,
322
+				'file' => $file,
323
+				'request' => $_REQUEST,
324
+				'server' => $_SERVER,
325
+			]);
326
+			if (isset($GLOBALS['tf'])) {
327
+				$smarty->assign('account_id', $GLOBALS['tf']->session->account_id);
328
+			}
329
+			$email = $smarty->fetch('email/admin/sql_error.tpl');
330
+			(new \MyAdmin\Mail())->adminMail($subject, $email, '[email protected]', '');
331
+			(new \MyAdmin\Mail())->adminMail($subject, $email, '[email protected]', '');
332
+		}
333
+		$this->haltmsg('Invalid SQL: '.$queryString, $line, $file);
334
+	}
335
+
336
+	/**
337
+	 * @param mixed $msg
338
+	 * @param string $line
339
+	 * @param string $file
340
+	 * @return mixed|void
341
+	 */
342
+	public function haltmsg($msg, $line = '', $file = '')
343
+	{
344
+		$email = "DB Error {$msg} {$file}:{$line}";
345
+		if (class_exists('\\MyAdmin\Mail')) {
346
+			\MyAdmin\Mail::failsafeMail($email, $email, ['[email protected]', '[email protected]']);
347
+			return;
348
+		}
349
+		$this->log("Database error: $msg", $line, $file, 'error');
350
+		if ($this->Errno != '0' || !in_array($this->Error, ['', '()'])) {
351
+			$sqlstate = mysqli_sqlstate($this->linkId);
352
+			$this->log("MySQLi SQLState: {$sqlstate}. Error: ".$this->Errno.' ('.$this->Error.')', $line, $file, 'error');
353
+		}
354
+		$this->logBackTrace($msg, $line, $file);
355
+	}
356
+
357
+	/**
358
+	 * @return array
359
+	 */
360
+	public function indexNames()
361
+	{
362
+		return [];
363
+	}
364
+
365
+
366
+	/**
367
+	 * Add query to logged queries.
368
+	 * @param string $statement
369
+	 * @param float $time Elapsed seconds with microseconds
370
+	 * @param string|int $line Line Number
371
+	 * @param string $file File Name
372
+	 */
373
+	public function addLog($statement, $time, $line = '', $file = '')
374
+	{
375
+		$query = [
376
+			'statement' => $statement,
377
+			'time' => $time * 1000
378
+		];
379
+		if ($line != '') {
380
+			$query['line'] = $line;
381
+		}
382
+		if ($file != '') {
383
+			$query['file'] = $file;
384
+		}
385
+		if (!isset($GLOBALS['db_queries'])) {
386
+			$GLOBALS['db_queries'] = [];
387
+		}
388
+		$GLOBALS['db_queries'][] = $query;
389
+		array_push($this->log, $query);
390
+	}
391
+
392
+	/**
393
+	 * Return logged queries.
394
+	 * @return array Logged queries
395
+	 */
396
+	public function getLog()
397
+	{
398
+		return $this->log;
399
+	}
400 400
 }
Please login to merge, or discard this patch.
Braces   +20 added lines, -40 removed lines patch added patch discarded remove patch
@@ -12,8 +12,7 @@  discard block
 block discarded – undo
12 12
 /**
13 13
  * Class Generic
14 14
  */
15
-abstract class Generic
16
-{
15
+abstract class Generic {
17 16
     /* public: connection parameters */
18 17
     public $host = 'localhost';
19 18
     public $database = '';
@@ -73,8 +72,7 @@  discard block
 block discarded – undo
73 72
      * @param string $query Optional query to perform immediately
74 73
      * @param string $port optional port for the connection
75 74
      */
76
-    public function __construct($database = '', $user = '', $password = '', $host = 'localhost', $query = '', $port = '')
77
-    {
75
+    public function __construct($database = '', $user = '', $password = '', $host = 'localhost', $query = '', $port = '') {
78 76
         $this->database = $database;
79 77
         $this->user = $user;
80 78
         $this->password = $password;
@@ -92,24 +90,21 @@  discard block
 block discarded – undo
92 90
      * @param string $file
93 91
      * @return void
94 92
      */
95
-    public function log($message, $line = '', $file = '', $level = 'info')
96
-    {
93
+    public function log($message, $line = '', $file = '', $level = 'info') {
97 94
         error_log('SQL Query '.$line.' '.$file.' '.$message);
98 95
     }
99 96
 
100 97
     /**
101 98
      * @return int|object
102 99
      */
103
-    public function linkId()
104
-    {
100
+    public function linkId() {
105 101
         return $this->linkId;
106 102
     }
107 103
 
108 104
     /**
109 105
      * @return int|object
110 106
      */
111
-    public function queryId()
112
-    {
107
+    public function queryId() {
113 108
         return $this->queryId;
114 109
     }
115 110
 
@@ -117,8 +112,7 @@  discard block
 block discarded – undo
117 112
      * @param $string
118 113
      * @return string
119 114
      */
120
-    public function real_escape($string = '')
121
-    {
115
+    public function real_escape($string = '') {
122 116
         if ((!is_resource($this->linkId) || $this->linkId == 0) && !$this->connect()) {
123 117
             return $this->escape($string);
124 118
         }
@@ -129,8 +123,7 @@  discard block
 block discarded – undo
129 123
      * @param $string
130 124
      * @return string
131 125
      */
132
-    public function escape($string = '')
133
-    {
126
+    public function escape($string = '') {
134 127
         //if (function_exists('mysql_escape_string'))
135 128
         //return mysql_escape_string($string);
136 129
         return str_replace(['\\', "\0", "\n", "\r", "'", '"', "\x1a"], ['\\\\', '\\0', '\\n', '\\r', "\\'", '\\"', '\\Z'], $string);
@@ -140,8 +133,7 @@  discard block
 block discarded – undo
140 133
      * @param mixed $str
141 134
      * @return string
142 135
      */
143
-    public function dbAddslashes($str = '')
144
-    {
136
+    public function dbAddslashes($str = '') {
145 137
         if (!isset($str) || $str == '') {
146 138
             return '';
147 139
         }
@@ -153,8 +145,7 @@  discard block
 block discarded – undo
153 145
      * @param mixed $epoch
154 146
      * @return bool|string
155 147
      */
156
-    public function toTimestamp($epoch)
157
-    {
148
+    public function toTimestamp($epoch) {
158 149
         return date('Y-m-d H:i:s', is_float($epoch) ? intval($epoch) : $epoch);
159 150
     }
160 151
 
@@ -163,8 +154,7 @@  discard block
 block discarded – undo
163 154
      * @param mixed $timestamp
164 155
      * @return bool|int|mixed
165 156
      */
166
-    public function fromTimestamp($timestamp)
167
-    {
157
+    public function fromTimestamp($timestamp) {
168 158
         if (preg_match('/([0-9]{4})-([0-9]{2})-([0-9]{2}) ([0-9]{2}):([0-9]{2}):([0-9]{2})/', $timestamp, $parts)) {
169 159
             $time = mktime($parts[4], $parts[5], $parts[6], $parts[2], $parts[3], $parts[1]);
170 160
         } elseif (preg_match('/([0-9]{4})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})/', $timestamp, $parts)) {
@@ -190,8 +180,7 @@  discard block
 block discarded – undo
190 180
      * @param string $file
191 181
      * @return mixed
192 182
      */
193
-    public function limitQuery($queryString, $numRows = '', $offset = 0, $line = '', $file = '')
194
-    {
183
+    public function limitQuery($queryString, $numRows = '', $offset = 0, $line = '', $file = '') {
195 184
         if (!$numRows) {
196 185
             $numRows = $this->maxMatches;
197 186
         }
@@ -218,8 +207,7 @@  discard block
 block discarded – undo
218 207
      * @param string $file optionally pass __FILE__ calling the query for logging
219 208
      * @return mixed FALSE if no rows, if a single row it returns that, if multiple it returns an array of rows, associative responses only
220 209
      */
221
-    public function qr($query, $line = '', $file = '')
222
-    {
210
+    public function qr($query, $line = '', $file = '') {
223 211
         return $this->queryReturn($query, $line, $file);
224 212
     }
225 213
 
@@ -230,8 +218,7 @@  discard block
 block discarded – undo
230 218
      * @param string $stripSlashes
231 219
      * @return string
232 220
      */
233
-    public function f($name, $stripSlashes = '')
234
-    {
221
+    public function f($name, $stripSlashes = '') {
235 222
         if (is_null($this->Record)) {
236 223
             return null;
237 224
         } elseif ($stripSlashes || ($this->autoStripslashes && !$stripSlashes)) {
@@ -249,8 +236,7 @@  discard block
 block discarded – undo
249 236
      * @param string $file
250 237
      * @return void
251 238
      */
252
-    public function halt($msg, $line = '', $file = '')
253
-    {
239
+    public function halt($msg, $line = '', $file = '') {
254 240
         $this->unlock(false);
255 241
         /* Just in case there is a table currently locked */
256 242
 
@@ -277,8 +263,7 @@  discard block
 block discarded – undo
277 263
      * @param string $file
278 264
      * @return mixed|void
279 265
      */
280
-    public function logBackTrace($msg, $line = '', $file = '')
281
-    {
266
+    public function logBackTrace($msg, $line = '', $file = '') {
282 267
         $backtrace = (function_exists('debug_backtrace') ? debug_backtrace() : []);
283 268
         $this->log(
284 269
             ('' !== getenv('REQUEST_URI') ? ' '.getenv('REQUEST_URI') : '').
@@ -309,8 +294,7 @@  discard block
 block discarded – undo
309 294
         }
310 295
     }
311 296
 
312
-    public function emailError($queryString, $error, $line, $file)
313
-    {
297
+    public function emailError($queryString, $error, $line, $file) {
314 298
         $subject = php_uname('n').' MySQLi Error '.$queryString;
315 299
         if (class_exists('\\TFSmarty')) {
316 300
             $smarty = new \TFSmarty();
@@ -339,8 +323,7 @@  discard block
 block discarded – undo
339 323
      * @param string $file
340 324
      * @return mixed|void
341 325
      */
342
-    public function haltmsg($msg, $line = '', $file = '')
343
-    {
326
+    public function haltmsg($msg, $line = '', $file = '') {
344 327
         $email = "DB Error {$msg} {$file}:{$line}";
345 328
         if (class_exists('\\MyAdmin\Mail')) {
346 329
             \MyAdmin\Mail::failsafeMail($email, $email, ['[email protected]', '[email protected]']);
@@ -357,8 +340,7 @@  discard block
 block discarded – undo
357 340
     /**
358 341
      * @return array
359 342
      */
360
-    public function indexNames()
361
-    {
343
+    public function indexNames() {
362 344
         return [];
363 345
     }
364 346
 
@@ -370,8 +352,7 @@  discard block
 block discarded – undo
370 352
      * @param string|int $line Line Number
371 353
      * @param string $file File Name
372 354
      */
373
-    public function addLog($statement, $time, $line = '', $file = '')
374
-    {
355
+    public function addLog($statement, $time, $line = '', $file = '') {
375 356
         $query = [
376 357
             'statement' => $statement,
377 358
             'time' => $time * 1000
@@ -393,8 +374,7 @@  discard block
 block discarded – undo
393 374
      * Return logged queries.
394 375
      * @return array Logged queries
395 376
      */
396
-    public function getLog()
397
-    {
377
+    public function getLog() {
398 378
         return $this->log;
399 379
     }
400 380
 }
Please login to merge, or discard this patch.