Test Failed
Push — master ( e35e3f...92cb25 )
by Joe
13:20
created
src/Generic.php 2 patches
Indentation   +381 added lines, -381 removed lines patch added patch discarded remove patch
@@ -14,385 +14,385 @@
 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
-    /**
34
-     * @var int
35
-     */
36
-    public $autoFree = 0; // Set to 1 for automatic mysql_free_result()
37
-
38
-    /* public: result array and current row number */
39
-    public $Record = [];
40
-    public $Row;
41
-
42
-    /* public: current error number and error text */
43
-    public $Errno = 0;
44
-    public $Error = '';
45
-
46
-    /* public: this is an api revision, not a CVS revision. */
47
-    public $type = 'generic';
48
-
49
-    /**
50
-     * @var int|object
51
-     */
52
-    public $linkId = 0;
53
-    public $queryId = 0;
54
-
55
-    public $characterSet = 'utf8mb4';
56
-    public $collation = 'utf8mb4_unicode_ci';
57
-
58
-    /**
59
-     * Logged queries.
60
-     * @var array
61
-     */
62
-    protected $log = [];
63
-
64
-    /**
65
-     * Constructs the db handler, can optionally specify connection parameters
66
-     *
67
-     * @param string $database Optional The database name
68
-     * @param string $user Optional The username to connect with
69
-     * @param string $password Optional The password to use
70
-     * @param string $host Optional The hostname where the server is, or default to localhost
71
-     * @param string $query Optional query to perform immediately
72
-     * @param string $port optional port for the connection
73
-     */
74
-    public function __construct($database = '', $user = '', $password = '', $host = 'localhost', $query = '', $port = '')
75
-    {
76
-        $this->database = $database;
77
-        $this->user = $user;
78
-        $this->password = $password;
79
-        $this->host = $host;
80
-        $this->port = $port;
81
-        if ($query != '') {
82
-            $this->query($query);
83
-        }
84
-        $this->connection_atttempt = 0;
85
-    }
86
-
87
-    /**
88
-     * @param string $message
89
-     * @param string $line
90
-     * @param string $file
91
-     * @return void
92
-     */
93
-    public function log($message, $line = '', $file = '', $level = 'info')
94
-    {
95
-        error_log($message);
96
-    }
97
-
98
-    /**
99
-     * @return int|object
100
-     */
101
-    public function linkId()
102
-    {
103
-        return $this->linkId;
104
-    }
105
-
106
-    /**
107
-     * @return int|object
108
-     */
109
-    public function queryId()
110
-    {
111
-        return $this->queryId;
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
-     * @param $string
128
-     * @return string
129
-     */
130
-    public function escape($string = '')
131
-    {
132
-        //if (function_exists('mysql_escape_string'))
133
-        //return mysql_escape_string($string);
134
-        return str_replace(['\\', "\0", "\n", "\r", "'", '"', "\x1a"], ['\\\\', '\\0', '\\n', '\\r', "\\'", '\\"', '\\Z'], $string);
135
-    }
136
-
137
-    /**
138
-     * @param mixed $str
139
-     * @return string
140
-     */
141
-    public function dbAddslashes($str = '')
142
-    {
143
-        if (!isset($str) || $str == '') {
144
-            return '';
145
-        }
146
-        return addslashes($str);
147
-    }
148
-
149
-    /**
150
-     * Db::toTimestamp()
151
-     * @param mixed $epoch
152
-     * @return bool|string
153
-     */
154
-    public function toTimestamp($epoch)
155
-    {
156
-        return date('Y-m-d H:i:s', is_float($epoch) ? intval($epoch) : $epoch);
157
-    }
158
-
159
-    /**
160
-     * Db::fromTimestamp()
161
-     * @param mixed $timestamp
162
-     * @return bool|int|mixed
163
-     */
164
-    public function fromTimestamp($timestamp)
165
-    {
166
-        if (preg_match('/([0-9]{4})-([0-9]{2})-([0-9]{2}) ([0-9]{2}):([0-9]{2}):([0-9]{2})/', $timestamp, $parts)) {
167
-            $time = mktime($parts[4], $parts[5], $parts[6], $parts[2], $parts[3], $parts[1]);
168
-        } elseif (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})/', $timestamp, $parts)) {
171
-            $time = mktime(1, 1, 1, $parts[2], $parts[3], $parts[1]);
172
-        } elseif (is_numeric($timestamp) && $timestamp >= 943938000) {
173
-            $time = $timestamp;
174
-        } else {
175
-            $this->log('Cannot Match Timestamp from '.$timestamp, __LINE__, __FILE__);
176
-            $time = false;
177
-        }
178
-        return $time;
179
-    }
180
-
181
-    /**
182
-     * perform a query with limited result set
183
-     *
184
-     * @param string $queryString
185
-     * @param string|int $numRows
186
-     * @param int $offset
187
-     * @param string|int $line
188
-     * @param string $file
189
-     * @return mixed
190
-     */
191
-    public function limitQuery($queryString, $numRows = '', $offset = 0, $line = '', $file = '')
192
-    {
193
-        if (!$numRows) {
194
-            $numRows = $this->maxMatches;
195
-        }
196
-        if ($offset == 0) {
197
-            $queryString .= ' LIMIT '.(int) $numRows;
198
-        } else {
199
-            $queryString .= ' LIMIT '.(int) $offset.','.(int) $numRows;
200
-        }
201
-
202
-        if ($this->Debug) {
203
-            printf("Debug: limitQuery = %s<br>offset=%d, num_rows=%d<br>\n", $queryString, $offset, $numRows);
204
-        }
205
-
206
-        return $this->query($queryString, $line, $file);
207
-    }
208
-
209
-    /**
210
-     * db:qr()
211
-     *
212
-     *  alias of queryReturn()
213
-     *
214
-     * @param mixed $query SQL Query to be used
215
-     * @param string $line optionally pass __LINE__ calling the query for logging
216
-     * @param string $file optionally pass __FILE__ calling the query for logging
217
-     * @return mixed FALSE if no rows, if a single row it returns that, if multiple it returns an array of rows, associative responses only
218
-     */
219
-    public function qr($query, $line = '', $file = '')
220
-    {
221
-        return $this->queryReturn($query, $line, $file);
222
-    }
223
-
224
-    /**
225
-     * gets a field
226
-     *
227
-     * @param mixed  $name
228
-     * @param string $stripSlashes
229
-     * @return string
230
-     */
231
-    public function f($name, $stripSlashes = '')
232
-    {
233
-        if (is_null($this->Record)) {
234
-            return null;
235
-        } elseif ($stripSlashes || ($this->autoStripslashes && !$stripSlashes)) {
236
-            return stripslashes($this->Record[$name]);
237
-        } else {
238
-            return $this->Record[$name];
239
-        }
240
-    }
241
-
242
-    /**
243
-     * error handling
244
-     *
245
-     * @param mixed $msg
246
-     * @param string $line
247
-     * @param string $file
248
-     * @return void
249
-     */
250
-    public function halt($msg, $line = '', $file = '')
251
-    {
252
-        $this->unlock(false);
253
-        /* Just in case there is a table currently locked */
254
-
255
-        //$this->Error = @$this->linkId->error;
256
-        //$this->Errno = @$this->linkId->errno;
257
-        if ($this->haltOnError == 'no') {
258
-            return true;
259
-        }
260
-        if ($msg != '') {
261
-            $this->haltmsg($msg, $line, $file);
262
-        }
263
-        if ($this->haltOnError != 'report') {
264
-            echo '<p><b>Session halted.</b>';
265
-            //if (isset($GLOBALS['tf']))
266
-            //$GLOBALS['tf']->terminate();
267
-            die();
268
-        }
269
-        return true;
270
-    }
271
-
272
-    /**
273
-     * @param mixed $msg
274
-     * @param string $line
275
-     * @param string $file
276
-     * @return mixed|void
277
-     */
278
-    public function logBackTrace($msg, $line = '', $file = '')
279
-    {
280
-        $backtrace = (function_exists('debug_backtrace') ? debug_backtrace() : []);
281
-        $this->log(
282
-            ('' !== getenv('REQUEST_URI') ? ' '.getenv('REQUEST_URI') : '').
283
-            ((isset($_POST) && count($_POST)) ? ' POST='.json_encode($_POST) : '').
284
-            ((isset($_GET) && count($_GET)) ? ' GET='.json_encode($_GET) : '').
285
-            ((isset($_FILES) && count($_FILES)) ? ' FILES='.json_encode($_FILES) : '').
286
-            ('' !== getenv('HTTP_USER_AGENT') ? ' AGENT="'.getenv('HTTP_USER_AGENT').'"' : '').
287
-            (isset($_SERVER['REQUEST_METHOD']) ? ' METHOD="'.$_SERVER['REQUEST_METHOD'].'"'.
288
-                ($_SERVER['REQUEST_METHOD'] === 'POST' ? ' POST="'.json_encode($_POST).'"' : '') : ''),
289
-            $line,
290
-            $file,
291
-            'error'
292
-        );
293
-        for ($level = 1, $levelMax = count($backtrace); $level < $levelMax; $level++) {
294
-            $message = (isset($backtrace[$level]['file']) ? 'File: '.$backtrace[$level]['file'] : '').
295
-                (isset($backtrace[$level]['line']) ? ' Line: '.$backtrace[$level]['line'] : '').
296
-                ' Function: '.(isset($backtrace[$level] ['class']) ? '(class '.$backtrace[$level] ['class'].') ' : '').
297
-                (isset($backtrace[$level] ['type']) ? $backtrace[$level] ['type'].' ' : '').
298
-                $backtrace[$level] ['function'].'(';
299
-            if (isset($backtrace[$level] ['args'])) {
300
-                for ($argument = 0, $argumentMax = count($backtrace[$level]['args']); $argument < $argumentMax; $argument++) {
301
-                    $message .= ($argument > 0 ? ', ' : '').
302
-                        (is_object($backtrace[$level]['args'][$argument]) ? 'class '.get_class($backtrace[$level]['args'][$argument]) : json_encode($backtrace[$level]['args'][$argument]));
303
-                }
304
-            }
305
-            $message .= ')';
306
-            $this->log($message, $line, $file, 'error');
307
-        }
308
-    }
309
-
310
-    public function emailError($queryString, $error, $line, $file)
311
-    {
312
-        $subject = php_uname('n').' MySQLi Error '.$queryString;
313
-        if (class_exists('\\TFSmarty')) {
314
-            $smarty = new \TFSmarty();
315
-            $smarty->assign([
316
-                'type' => $this->type,
317
-                'queryString' => $queryString,
318
-                'error' => $error,
319
-                'line' => $line,
320
-                'file' => $file,
321
-                'request' => $_REQUEST,
322
-                'server' => $_SERVER,
323
-            ]);
324
-            if (isset($GLOBALS['tf'])) {
325
-                $smarty->assign('account_id', $GLOBALS['tf']->session->account_id);
326
-            }
327
-            $email = $smarty->fetch('email/admin/sql_error.tpl');
328
-            (new \MyAdmin\Mail())->adminMail($subject, $email, '[email protected]', '');
329
-            (new \MyAdmin\Mail())->adminMail($subject, $email, '[email protected]', '');
330
-        }
331
-        $this->haltmsg('Invalid SQL: '.$queryString, $line, $file);
332
-    }
333
-
334
-    /**
335
-     * @param mixed $msg
336
-     * @param string $line
337
-     * @param string $file
338
-     * @return mixed|void
339
-     */
340
-    public function haltmsg($msg, $line = '', $file = '')
341
-    {
342
-        $email = "DB Error {$msg} {$file}:{$line}";
343
-        if (class_exists('\\MyAdmin\Mail')) {
344
-            \MyAdmin\Mail::failsafeMail($email, $email, ['[email protected]', '[email protected]']);
345
-            return;
346
-        }
347
-        $this->log("Database error: $msg", $line, $file, 'error');
348
-        if ($this->Errno != '0' || !in_array($this->Error, ['', '()'])) {
349
-            $sqlstate = mysqli_sqlstate($this->linkId);
350
-            $this->log("MySQLi SQLState: {$sqlstate}. Error: ".$this->Errno.' ('.$this->Error.')', $line, $file, 'error');
351
-        }
352
-        $this->logBackTrace($msg, $line, $file);
353
-    }
354
-
355
-    /**
356
-     * @return array
357
-     */
358
-    public function indexNames()
359
-    {
360
-        return [];
361
-    }
362
-
363
-
364
-    /**
365
-     * Add query to logged queries.
366
-     * @param string $statement
367
-     * @param float $time Elapsed seconds with microseconds
368
-     * @param string|int $line Line Number
369
-     * @param string $file File Name
370
-     */
371
-    public function addLog($statement, $time, $line = '', $file = '')
372
-    {
373
-        $query = [
374
-            'statement' => $statement,
375
-            'time' => $time * 1000
376
-        ];
377
-        if ($line != '') {
378
-            $query['line'] = $line;
379
-        }
380
-        if ($file != '') {
381
-            $query['file'] = $file;
382
-        }
383
-        if (!isset($GLOBALS['db_queries'])) {
384
-            $GLOBALS['db_queries'] = [];
385
-        }
386
-        $GLOBALS['db_queries'][] = $query;
387
-        array_push($this->log, $query);
388
-    }
389
-
390
-    /**
391
-     * Return logged queries.
392
-     * @return array Logged queries
393
-     */
394
-    public function getLog()
395
-    {
396
-        return $this->log;
397
-    }
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
+	/**
34
+	 * @var int
35
+	 */
36
+	public $autoFree = 0; // Set to 1 for automatic mysql_free_result()
37
+
38
+	/* public: result array and current row number */
39
+	public $Record = [];
40
+	public $Row;
41
+
42
+	/* public: current error number and error text */
43
+	public $Errno = 0;
44
+	public $Error = '';
45
+
46
+	/* public: this is an api revision, not a CVS revision. */
47
+	public $type = 'generic';
48
+
49
+	/**
50
+	 * @var int|object
51
+	 */
52
+	public $linkId = 0;
53
+	public $queryId = 0;
54
+
55
+	public $characterSet = 'utf8mb4';
56
+	public $collation = 'utf8mb4_unicode_ci';
57
+
58
+	/**
59
+	 * Logged queries.
60
+	 * @var array
61
+	 */
62
+	protected $log = [];
63
+
64
+	/**
65
+	 * Constructs the db handler, can optionally specify connection parameters
66
+	 *
67
+	 * @param string $database Optional The database name
68
+	 * @param string $user Optional The username to connect with
69
+	 * @param string $password Optional The password to use
70
+	 * @param string $host Optional The hostname where the server is, or default to localhost
71
+	 * @param string $query Optional query to perform immediately
72
+	 * @param string $port optional port for the connection
73
+	 */
74
+	public function __construct($database = '', $user = '', $password = '', $host = 'localhost', $query = '', $port = '')
75
+	{
76
+		$this->database = $database;
77
+		$this->user = $user;
78
+		$this->password = $password;
79
+		$this->host = $host;
80
+		$this->port = $port;
81
+		if ($query != '') {
82
+			$this->query($query);
83
+		}
84
+		$this->connection_atttempt = 0;
85
+	}
86
+
87
+	/**
88
+	 * @param string $message
89
+	 * @param string $line
90
+	 * @param string $file
91
+	 * @return void
92
+	 */
93
+	public function log($message, $line = '', $file = '', $level = 'info')
94
+	{
95
+		error_log($message);
96
+	}
97
+
98
+	/**
99
+	 * @return int|object
100
+	 */
101
+	public function linkId()
102
+	{
103
+		return $this->linkId;
104
+	}
105
+
106
+	/**
107
+	 * @return int|object
108
+	 */
109
+	public function queryId()
110
+	{
111
+		return $this->queryId;
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
+	 * @param $string
128
+	 * @return string
129
+	 */
130
+	public function escape($string = '')
131
+	{
132
+		//if (function_exists('mysql_escape_string'))
133
+		//return mysql_escape_string($string);
134
+		return str_replace(['\\', "\0", "\n", "\r", "'", '"', "\x1a"], ['\\\\', '\\0', '\\n', '\\r', "\\'", '\\"', '\\Z'], $string);
135
+	}
136
+
137
+	/**
138
+	 * @param mixed $str
139
+	 * @return string
140
+	 */
141
+	public function dbAddslashes($str = '')
142
+	{
143
+		if (!isset($str) || $str == '') {
144
+			return '';
145
+		}
146
+		return addslashes($str);
147
+	}
148
+
149
+	/**
150
+	 * Db::toTimestamp()
151
+	 * @param mixed $epoch
152
+	 * @return bool|string
153
+	 */
154
+	public function toTimestamp($epoch)
155
+	{
156
+		return date('Y-m-d H:i:s', is_float($epoch) ? intval($epoch) : $epoch);
157
+	}
158
+
159
+	/**
160
+	 * Db::fromTimestamp()
161
+	 * @param mixed $timestamp
162
+	 * @return bool|int|mixed
163
+	 */
164
+	public function fromTimestamp($timestamp)
165
+	{
166
+		if (preg_match('/([0-9]{4})-([0-9]{2})-([0-9]{2}) ([0-9]{2}):([0-9]{2}):([0-9]{2})/', $timestamp, $parts)) {
167
+			$time = mktime($parts[4], $parts[5], $parts[6], $parts[2], $parts[3], $parts[1]);
168
+		} elseif (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})/', $timestamp, $parts)) {
171
+			$time = mktime(1, 1, 1, $parts[2], $parts[3], $parts[1]);
172
+		} elseif (is_numeric($timestamp) && $timestamp >= 943938000) {
173
+			$time = $timestamp;
174
+		} else {
175
+			$this->log('Cannot Match Timestamp from '.$timestamp, __LINE__, __FILE__);
176
+			$time = false;
177
+		}
178
+		return $time;
179
+	}
180
+
181
+	/**
182
+	 * perform a query with limited result set
183
+	 *
184
+	 * @param string $queryString
185
+	 * @param string|int $numRows
186
+	 * @param int $offset
187
+	 * @param string|int $line
188
+	 * @param string $file
189
+	 * @return mixed
190
+	 */
191
+	public function limitQuery($queryString, $numRows = '', $offset = 0, $line = '', $file = '')
192
+	{
193
+		if (!$numRows) {
194
+			$numRows = $this->maxMatches;
195
+		}
196
+		if ($offset == 0) {
197
+			$queryString .= ' LIMIT '.(int) $numRows;
198
+		} else {
199
+			$queryString .= ' LIMIT '.(int) $offset.','.(int) $numRows;
200
+		}
201
+
202
+		if ($this->Debug) {
203
+			printf("Debug: limitQuery = %s<br>offset=%d, num_rows=%d<br>\n", $queryString, $offset, $numRows);
204
+		}
205
+
206
+		return $this->query($queryString, $line, $file);
207
+	}
208
+
209
+	/**
210
+	 * db:qr()
211
+	 *
212
+	 *  alias of queryReturn()
213
+	 *
214
+	 * @param mixed $query SQL Query to be used
215
+	 * @param string $line optionally pass __LINE__ calling the query for logging
216
+	 * @param string $file optionally pass __FILE__ calling the query for logging
217
+	 * @return mixed FALSE if no rows, if a single row it returns that, if multiple it returns an array of rows, associative responses only
218
+	 */
219
+	public function qr($query, $line = '', $file = '')
220
+	{
221
+		return $this->queryReturn($query, $line, $file);
222
+	}
223
+
224
+	/**
225
+	 * gets a field
226
+	 *
227
+	 * @param mixed  $name
228
+	 * @param string $stripSlashes
229
+	 * @return string
230
+	 */
231
+	public function f($name, $stripSlashes = '')
232
+	{
233
+		if (is_null($this->Record)) {
234
+			return null;
235
+		} elseif ($stripSlashes || ($this->autoStripslashes && !$stripSlashes)) {
236
+			return stripslashes($this->Record[$name]);
237
+		} else {
238
+			return $this->Record[$name];
239
+		}
240
+	}
241
+
242
+	/**
243
+	 * error handling
244
+	 *
245
+	 * @param mixed $msg
246
+	 * @param string $line
247
+	 * @param string $file
248
+	 * @return void
249
+	 */
250
+	public function halt($msg, $line = '', $file = '')
251
+	{
252
+		$this->unlock(false);
253
+		/* Just in case there is a table currently locked */
254
+
255
+		//$this->Error = @$this->linkId->error;
256
+		//$this->Errno = @$this->linkId->errno;
257
+		if ($this->haltOnError == 'no') {
258
+			return true;
259
+		}
260
+		if ($msg != '') {
261
+			$this->haltmsg($msg, $line, $file);
262
+		}
263
+		if ($this->haltOnError != 'report') {
264
+			echo '<p><b>Session halted.</b>';
265
+			//if (isset($GLOBALS['tf']))
266
+			//$GLOBALS['tf']->terminate();
267
+			die();
268
+		}
269
+		return true;
270
+	}
271
+
272
+	/**
273
+	 * @param mixed $msg
274
+	 * @param string $line
275
+	 * @param string $file
276
+	 * @return mixed|void
277
+	 */
278
+	public function logBackTrace($msg, $line = '', $file = '')
279
+	{
280
+		$backtrace = (function_exists('debug_backtrace') ? debug_backtrace() : []);
281
+		$this->log(
282
+			('' !== getenv('REQUEST_URI') ? ' '.getenv('REQUEST_URI') : '').
283
+			((isset($_POST) && count($_POST)) ? ' POST='.json_encode($_POST) : '').
284
+			((isset($_GET) && count($_GET)) ? ' GET='.json_encode($_GET) : '').
285
+			((isset($_FILES) && count($_FILES)) ? ' FILES='.json_encode($_FILES) : '').
286
+			('' !== getenv('HTTP_USER_AGENT') ? ' AGENT="'.getenv('HTTP_USER_AGENT').'"' : '').
287
+			(isset($_SERVER['REQUEST_METHOD']) ? ' METHOD="'.$_SERVER['REQUEST_METHOD'].'"'.
288
+				($_SERVER['REQUEST_METHOD'] === 'POST' ? ' POST="'.json_encode($_POST).'"' : '') : ''),
289
+			$line,
290
+			$file,
291
+			'error'
292
+		);
293
+		for ($level = 1, $levelMax = count($backtrace); $level < $levelMax; $level++) {
294
+			$message = (isset($backtrace[$level]['file']) ? 'File: '.$backtrace[$level]['file'] : '').
295
+				(isset($backtrace[$level]['line']) ? ' Line: '.$backtrace[$level]['line'] : '').
296
+				' Function: '.(isset($backtrace[$level] ['class']) ? '(class '.$backtrace[$level] ['class'].') ' : '').
297
+				(isset($backtrace[$level] ['type']) ? $backtrace[$level] ['type'].' ' : '').
298
+				$backtrace[$level] ['function'].'(';
299
+			if (isset($backtrace[$level] ['args'])) {
300
+				for ($argument = 0, $argumentMax = count($backtrace[$level]['args']); $argument < $argumentMax; $argument++) {
301
+					$message .= ($argument > 0 ? ', ' : '').
302
+						(is_object($backtrace[$level]['args'][$argument]) ? 'class '.get_class($backtrace[$level]['args'][$argument]) : json_encode($backtrace[$level]['args'][$argument]));
303
+				}
304
+			}
305
+			$message .= ')';
306
+			$this->log($message, $line, $file, 'error');
307
+		}
308
+	}
309
+
310
+	public function emailError($queryString, $error, $line, $file)
311
+	{
312
+		$subject = php_uname('n').' MySQLi Error '.$queryString;
313
+		if (class_exists('\\TFSmarty')) {
314
+			$smarty = new \TFSmarty();
315
+			$smarty->assign([
316
+				'type' => $this->type,
317
+				'queryString' => $queryString,
318
+				'error' => $error,
319
+				'line' => $line,
320
+				'file' => $file,
321
+				'request' => $_REQUEST,
322
+				'server' => $_SERVER,
323
+			]);
324
+			if (isset($GLOBALS['tf'])) {
325
+				$smarty->assign('account_id', $GLOBALS['tf']->session->account_id);
326
+			}
327
+			$email = $smarty->fetch('email/admin/sql_error.tpl');
328
+			(new \MyAdmin\Mail())->adminMail($subject, $email, '[email protected]', '');
329
+			(new \MyAdmin\Mail())->adminMail($subject, $email, '[email protected]', '');
330
+		}
331
+		$this->haltmsg('Invalid SQL: '.$queryString, $line, $file);
332
+	}
333
+
334
+	/**
335
+	 * @param mixed $msg
336
+	 * @param string $line
337
+	 * @param string $file
338
+	 * @return mixed|void
339
+	 */
340
+	public function haltmsg($msg, $line = '', $file = '')
341
+	{
342
+		$email = "DB Error {$msg} {$file}:{$line}";
343
+		if (class_exists('\\MyAdmin\Mail')) {
344
+			\MyAdmin\Mail::failsafeMail($email, $email, ['[email protected]', '[email protected]']);
345
+			return;
346
+		}
347
+		$this->log("Database error: $msg", $line, $file, 'error');
348
+		if ($this->Errno != '0' || !in_array($this->Error, ['', '()'])) {
349
+			$sqlstate = mysqli_sqlstate($this->linkId);
350
+			$this->log("MySQLi SQLState: {$sqlstate}. Error: ".$this->Errno.' ('.$this->Error.')', $line, $file, 'error');
351
+		}
352
+		$this->logBackTrace($msg, $line, $file);
353
+	}
354
+
355
+	/**
356
+	 * @return array
357
+	 */
358
+	public function indexNames()
359
+	{
360
+		return [];
361
+	}
362
+
363
+
364
+	/**
365
+	 * Add query to logged queries.
366
+	 * @param string $statement
367
+	 * @param float $time Elapsed seconds with microseconds
368
+	 * @param string|int $line Line Number
369
+	 * @param string $file File Name
370
+	 */
371
+	public function addLog($statement, $time, $line = '', $file = '')
372
+	{
373
+		$query = [
374
+			'statement' => $statement,
375
+			'time' => $time * 1000
376
+		];
377
+		if ($line != '') {
378
+			$query['line'] = $line;
379
+		}
380
+		if ($file != '') {
381
+			$query['file'] = $file;
382
+		}
383
+		if (!isset($GLOBALS['db_queries'])) {
384
+			$GLOBALS['db_queries'] = [];
385
+		}
386
+		$GLOBALS['db_queries'][] = $query;
387
+		array_push($this->log, $query);
388
+	}
389
+
390
+	/**
391
+	 * Return logged queries.
392
+	 * @return array Logged queries
393
+	 */
394
+	public function getLog()
395
+	{
396
+		return $this->log;
397
+	}
398 398
 }
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 = '';
@@ -71,8 +70,7 @@  discard block
 block discarded – undo
71 70
      * @param string $query Optional query to perform immediately
72 71
      * @param string $port optional port for the connection
73 72
      */
74
-    public function __construct($database = '', $user = '', $password = '', $host = 'localhost', $query = '', $port = '')
75
-    {
73
+    public function __construct($database = '', $user = '', $password = '', $host = 'localhost', $query = '', $port = '') {
76 74
         $this->database = $database;
77 75
         $this->user = $user;
78 76
         $this->password = $password;
@@ -90,24 +88,21 @@  discard block
 block discarded – undo
90 88
      * @param string $file
91 89
      * @return void
92 90
      */
93
-    public function log($message, $line = '', $file = '', $level = 'info')
94
-    {
91
+    public function log($message, $line = '', $file = '', $level = 'info') {
95 92
         error_log($message);
96 93
     }
97 94
 
98 95
     /**
99 96
      * @return int|object
100 97
      */
101
-    public function linkId()
102
-    {
98
+    public function linkId() {
103 99
         return $this->linkId;
104 100
     }
105 101
 
106 102
     /**
107 103
      * @return int|object
108 104
      */
109
-    public function queryId()
110
-    {
105
+    public function queryId() {
111 106
         return $this->queryId;
112 107
     }
113 108
 
@@ -115,8 +110,7 @@  discard block
 block discarded – undo
115 110
      * @param $string
116 111
      * @return string
117 112
      */
118
-    public function real_escape($string = '')
119
-    {
113
+    public function real_escape($string = '') {
120 114
         if ((!is_resource($this->linkId) || $this->linkId == 0) && !$this->connect()) {
121 115
             return $this->escape($string);
122 116
         }
@@ -127,8 +121,7 @@  discard block
 block discarded – undo
127 121
      * @param $string
128 122
      * @return string
129 123
      */
130
-    public function escape($string = '')
131
-    {
124
+    public function escape($string = '') {
132 125
         //if (function_exists('mysql_escape_string'))
133 126
         //return mysql_escape_string($string);
134 127
         return str_replace(['\\', "\0", "\n", "\r", "'", '"', "\x1a"], ['\\\\', '\\0', '\\n', '\\r', "\\'", '\\"', '\\Z'], $string);
@@ -138,8 +131,7 @@  discard block
 block discarded – undo
138 131
      * @param mixed $str
139 132
      * @return string
140 133
      */
141
-    public function dbAddslashes($str = '')
142
-    {
134
+    public function dbAddslashes($str = '') {
143 135
         if (!isset($str) || $str == '') {
144 136
             return '';
145 137
         }
@@ -151,8 +143,7 @@  discard block
 block discarded – undo
151 143
      * @param mixed $epoch
152 144
      * @return bool|string
153 145
      */
154
-    public function toTimestamp($epoch)
155
-    {
146
+    public function toTimestamp($epoch) {
156 147
         return date('Y-m-d H:i:s', is_float($epoch) ? intval($epoch) : $epoch);
157 148
     }
158 149
 
@@ -161,8 +152,7 @@  discard block
 block discarded – undo
161 152
      * @param mixed $timestamp
162 153
      * @return bool|int|mixed
163 154
      */
164
-    public function fromTimestamp($timestamp)
165
-    {
155
+    public function fromTimestamp($timestamp) {
166 156
         if (preg_match('/([0-9]{4})-([0-9]{2})-([0-9]{2}) ([0-9]{2}):([0-9]{2}):([0-9]{2})/', $timestamp, $parts)) {
167 157
             $time = mktime($parts[4], $parts[5], $parts[6], $parts[2], $parts[3], $parts[1]);
168 158
         } elseif (preg_match('/([0-9]{4})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})/', $timestamp, $parts)) {
@@ -188,8 +178,7 @@  discard block
 block discarded – undo
188 178
      * @param string $file
189 179
      * @return mixed
190 180
      */
191
-    public function limitQuery($queryString, $numRows = '', $offset = 0, $line = '', $file = '')
192
-    {
181
+    public function limitQuery($queryString, $numRows = '', $offset = 0, $line = '', $file = '') {
193 182
         if (!$numRows) {
194 183
             $numRows = $this->maxMatches;
195 184
         }
@@ -216,8 +205,7 @@  discard block
 block discarded – undo
216 205
      * @param string $file optionally pass __FILE__ calling the query for logging
217 206
      * @return mixed FALSE if no rows, if a single row it returns that, if multiple it returns an array of rows, associative responses only
218 207
      */
219
-    public function qr($query, $line = '', $file = '')
220
-    {
208
+    public function qr($query, $line = '', $file = '') {
221 209
         return $this->queryReturn($query, $line, $file);
222 210
     }
223 211
 
@@ -228,8 +216,7 @@  discard block
 block discarded – undo
228 216
      * @param string $stripSlashes
229 217
      * @return string
230 218
      */
231
-    public function f($name, $stripSlashes = '')
232
-    {
219
+    public function f($name, $stripSlashes = '') {
233 220
         if (is_null($this->Record)) {
234 221
             return null;
235 222
         } elseif ($stripSlashes || ($this->autoStripslashes && !$stripSlashes)) {
@@ -247,8 +234,7 @@  discard block
 block discarded – undo
247 234
      * @param string $file
248 235
      * @return void
249 236
      */
250
-    public function halt($msg, $line = '', $file = '')
251
-    {
237
+    public function halt($msg, $line = '', $file = '') {
252 238
         $this->unlock(false);
253 239
         /* Just in case there is a table currently locked */
254 240
 
@@ -275,8 +261,7 @@  discard block
 block discarded – undo
275 261
      * @param string $file
276 262
      * @return mixed|void
277 263
      */
278
-    public function logBackTrace($msg, $line = '', $file = '')
279
-    {
264
+    public function logBackTrace($msg, $line = '', $file = '') {
280 265
         $backtrace = (function_exists('debug_backtrace') ? debug_backtrace() : []);
281 266
         $this->log(
282 267
             ('' !== getenv('REQUEST_URI') ? ' '.getenv('REQUEST_URI') : '').
@@ -307,8 +292,7 @@  discard block
 block discarded – undo
307 292
         }
308 293
     }
309 294
 
310
-    public function emailError($queryString, $error, $line, $file)
311
-    {
295
+    public function emailError($queryString, $error, $line, $file) {
312 296
         $subject = php_uname('n').' MySQLi Error '.$queryString;
313 297
         if (class_exists('\\TFSmarty')) {
314 298
             $smarty = new \TFSmarty();
@@ -337,8 +321,7 @@  discard block
 block discarded – undo
337 321
      * @param string $file
338 322
      * @return mixed|void
339 323
      */
340
-    public function haltmsg($msg, $line = '', $file = '')
341
-    {
324
+    public function haltmsg($msg, $line = '', $file = '') {
342 325
         $email = "DB Error {$msg} {$file}:{$line}";
343 326
         if (class_exists('\\MyAdmin\Mail')) {
344 327
             \MyAdmin\Mail::failsafeMail($email, $email, ['[email protected]', '[email protected]']);
@@ -355,8 +338,7 @@  discard block
 block discarded – undo
355 338
     /**
356 339
      * @return array
357 340
      */
358
-    public function indexNames()
359
-    {
341
+    public function indexNames() {
360 342
         return [];
361 343
     }
362 344
 
@@ -368,8 +350,7 @@  discard block
 block discarded – undo
368 350
      * @param string|int $line Line Number
369 351
      * @param string $file File Name
370 352
      */
371
-    public function addLog($statement, $time, $line = '', $file = '')
372
-    {
353
+    public function addLog($statement, $time, $line = '', $file = '') {
373 354
         $query = [
374 355
             'statement' => $statement,
375 356
             'time' => $time * 1000
@@ -391,8 +372,7 @@  discard block
 block discarded – undo
391 372
      * Return logged queries.
392 373
      * @return array Logged queries
393 374
      */
394
-    public function getLog()
395
-    {
375
+    public function getLog() {
396 376
         return $this->log;
397 377
     }
398 378
 }
Please login to merge, or discard this patch.