-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdebug.inc.php
More file actions
266 lines (231 loc) · 9.26 KB
/
debug.inc.php
File metadata and controls
266 lines (231 loc) · 9.26 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
<?php
/*
debug - simple debugging aids
Copyright (c) 2004, 2014 Thomas Rutter
This file is part of Bluestone.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of contributors may be used
to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
// implements the singleton pattern (using debug::getinstance())
// the value $this->debugmode determines whether we bother with things like
// the timer
class debug
{
private
$notices = array(),
$starttime,
$depth = 0,
$noticeid = 0,
$debugmode,
$useerrorhandler = false;
function __construct($debugmode = false, $useerrorhandler = true)
// constructor
// to use this as a singleton, use getinstance() instead
{
$this->debugmode = $debugmode;
if ($debugmode) $this->starttime = microtime(true);
$this->useerrorhandler($useerrorhandler);
}
public function notice($module, $notice, $data = null)
// module is name of module - should be the classname where the error occurred
// or 'global' if in global scope
// notice is name of notice
// data is further information about this notice such as the arguments
// errlog should be set to true to always show this in an error report
{
$this->notices[++$this->noticeid] = array(
'module' => $module,
'notice' => $notice,
'data' => strlen($data) > 8192 ? substr($data, 0, 8192 - 16) . ' ... (truncated)' : $data,
'elapsed' => !$this->debugmode ? null : microtime(true) - $this->starttime,
'depth' => $this->depth
);
// control size of debug log (don't allow it to grow indefinitely, as this is a memory leak
if ($this->noticeid > 250) {
if ($this->noticeid > 251) unset($this->notices[$this->noticeid - 250]);
else // if this->noticeid == 251
$this->notices[1] = array('module' => 'debug', 'notice' => 'debug log truncated', 'data' => null, 'elapsed' => null, 'depth' => 0);
}
return $this->notices[$this->noticeid];
}
public function starttask($module, $taskname, $data = NULL) {
// returns a unique task id
$this->notice($module, $taskname, $data);
$this->depth++;
return $this->noticeid;
}
public function endtask($noticeid)
{
if (!isset($this->notices[$noticeid])) throw new Exception('endtask() called with invalid noticeid');
if ($this->debugmode) {
$this->notices[$noticeid]['taskelapsed'] =
microtime(true) - $this->starttime - $this->notices[$noticeid]['elapsed'];
}
if ($this->depth) $this->depth--;
return $this->notices[$noticeid];
}
public function useerrorhandler($useerrorhandler = true)
// allows you to enable/disable whether this module's error handler should
// be used. note that the error handler is now used by default, hence
// calling this should be unnecessary if you want it turned _on_
{
if ($useerrorhandler == $this->useerrorhandler) return;
else $this->useerrorhandler = $useerrorhandler;
if ($useerrorhandler)
{
// in debug mode we handle all errors
if ($this->debugmode) {
error_reporting(E_ALL);
ini_set('display_errors', '1');
}
set_error_handler(array(&$this, 'debug_errorhandler'));
set_exception_handler(array(&$this, 'debug_errorhandler'));
}
else
{
restore_error_handler();
restore_exception_handler();
}
}
public static function &getinstance($debugmode = false, $useerrorhandler = true)
{
static $instance;
if (!isset($instance)) $instance = new debug($debugmode, $useerrorhandler);
return $instance;
}
public function seterrorcallback($callback)
// sets a function to be executed when a fatal error occurs. it could
// output an error message to the screen. in debug mode, this is not
// use
{
$this->error_callback = $callback;
}
public function halt($message = '', $errorlevel = 1, $htmlformat = null)
// errorlevel 0 = success, >0 = error
// htmlformat true = use html, false = use text, null = autodetect
{
if ($htmlformat === null)
$htmlformat = !empty($_SERVER['REQUEST_URI']);
if (!headers_sent() && empty($this->error_callback)) header('HTTP/1.1 500 Internal Server Error');
while (ob_get_length() !== false) ob_end_clean();
if (!$this->debugmode)
{
if (!empty($this->error_callback))
call_user_func($this->error_callback, 'Application Error');
else
require(BLUESTONE_DIR . '/system/fatalerror.inc.php');
exit;
}
if ($htmlformat) echo '<div style="background:$fff;color:#000">';
if ($message != '')
{
$c = $errorlevel ? '#c00' : '#080';
echo $htmlformat
? "<p style=\"background:$c;color:#fff;font:bold large sans-serif;padding:12px\">"
: str_repeat("======",13) . "\n";
echo $htmlformat
? htmlspecialchars($message)
: wordwrap($message, 78, "\n", true) . "\n";
echo $htmlformat
? "</p>"
: str_repeat("======",13) . "\n";
}
echo $htmlformat ? $this->getnoticeshtml(true) : $this->getnoticestext(true);
if ($htmlformat)
echo '<p style="font:small sans-serif"><em>Notice: These notices are shown because your site is in DEBUG mode.</em></p>';
exit((int)$errorlevel);
}
public function getnoticeshtml() {
return '<pre>' . htmlspecialchars($this->getnoticestext(160)) . '</pre>';
}
public function getnoticestext($linelength = 160) {
$output = '';
foreach ($this->notices as $notice) {
$taskelapsed = !empty($notice['taskelapsed']) ?
str_pad(number_format($notice['taskelapsed'] * 1000, 2), 7, ' ', STR_PAD_LEFT) : ' ';
$indent = str_repeat(' ', $notice['depth']);
$output .= str_pad(number_format($notice['elapsed'] * 1000, 2), 7, ' ', STR_PAD_LEFT) . " $taskelapsed $indent";
$msg = '[' . $notice['module'] . '] ' . $notice['notice'];
if ($notice['data'] != '') {
$linesep = "\n " . $indent;
$len = 16 + ($notice['depth']);
$output .=
wordwrap(str_replace("\n", $linesep, $msg . ': ' . $notice['data']), max(31, $linelength - $len), $linesep) . "\n";
}
else $output .= $msg . "\n";
}
return $output;
}
public function debug_errorhandler($err, $errstr='', $errfile='', $errline='')
// designed as a custom error handler - it logs it into the debug notices as
// a notice, unless it's a fatal error.
{
static $errortypes = array(
E_ERROR => 'Error', E_WARNING => 'Warning', E_PARSE => 'Parse Error',
E_NOTICE => 'Notice', E_CORE_ERROR => 'Core Error', E_CORE_WARNING => 'Core Warning',
E_COMPILE_ERROR => 'Compile Error', E_COMPILE_WARNING => 'Compile Warning',
E_USER_ERROR => 'User Error', E_USER_WARNING => 'User Warning',
E_USER_NOTICE => 'User Notice', E_STRICT => 'Strict Error',
E_RECOVERABLE_ERROR => 'Recoverable Error', E_DEPRECATED => 'Deprecated Error',
E_USER_DEPRECATED => 'User Deprecated Error',
);
if (is_object($err)) {
$errortype = get_class($err);
$errcode = $err->getCode();
if ($errcode) $errortype .= " (code $errcode)";
$errstr = $err->getMessage();
$errfile = $err->getFile();
$errline = $err->getLine();
$backtrace = $err->getTrace();
}
else {
// the following also allows suppressing errors with @ sign
if (!($err & error_reporting())) return;
$errortype = (isset($errortypes[$err])) ? $errortypes[$err] : 'Unknown Error';
$backtrace = debug_backtrace();
foreach ($backtrace as $id => $row)
if (isset($row['class']) && $row['class'] == 'debug')
unset($backtrace[$id]);
}
$this->notice('debug', 'Error', "$errortype in $errfile line $errline: $errstr", true);
$this->logtrace($backtrace);
$this->halt("$errortype in $errfile line $errline: $errstr");
}
private function logtrace($trace)
{
foreach ($trace as $row)
{
$func = isset($row['function']) ? $row['function'] : null;
if (!empty($row['class'])) $func = $row['class'] . '::' . $func;
$args = array();
if (isset($row['args']) && is_array($row['args']))
foreach ($row['args'] as $arg)
$args[] = is_object($arg) ? get_class($arg) : gettype($arg);
$args = implode(', ', $args);
$file = isset($row['file']) ? $row['file'] : '(unknown file)';
$line = isset($row['line']) ? $row['line'] : '(unknown line)';
$this->notice('debug', 'Backtrace',
"$func($args) in $file line $line", true
);
}
}
}
?>