1: <?php
2:
3: 4: 5: 6: 7: 8: 9: 10: 11:
12:
13:
14:
15: 16: 17: 18: 19: 20: 21: 22: 23: 24:
25: final class Debugger
26: {
27:
28: public static $productionMode;
29:
30:
31: public static $consoleMode;
32:
33:
34: public static $time;
35:
36:
37: private static $ajaxDetected;
38:
39:
40: public static $source;
41:
42:
43: public static $editor = 'editor://open/?file=%file&line=%line';
44:
45:
46: public static $browser;
47:
48:
49:
50:
51: public static $maxDepth = 3;
52:
53:
54: public static $maxLen = 150;
55:
56:
57: public static $showLocation = FALSE;
58:
59:
60: public static $consoleColors = array(
61: 'bool' => '1;33',
62: 'null' => '1;33',
63: 'int' => '1;36',
64: 'float' => '1;36',
65: 'string' => '1;32',
66: 'array' => '1;31',
67: 'key' => '1;37',
68: 'object' => '1;31',
69: 'visibility' => '1;30',
70: 'resource' => '1;37',
71: );
72:
73:
74:
75:
76: const DEVELOPMENT = FALSE,
77: PRODUCTION = TRUE,
78: DETECT = NULL;
79:
80:
81: public static $blueScreen;
82:
83:
84: public static $strictMode = FALSE;
85:
86:
87: public static $scream = FALSE;
88:
89:
90: public static $onFatalError = array();
91:
92:
93: private static $enabled = FALSE;
94:
95:
96: private static $lastError = FALSE;
97:
98:
99:
100:
101: public static $logger;
102:
103:
104: public static $fireLogger;
105:
106:
107: public static $logDirectory;
108:
109:
110: public static $email;
111:
112:
113: public static $mailer;
114:
115:
116: public static $emailSnooze;
117:
118:
119:
120:
121: public static $bar;
122:
123:
124: private static $errorPanel;
125:
126:
127: private static $dumpPanel;
128:
129:
130:
131:
132: const DEBUG = 'debug',
133: INFO = 'info',
134: WARNING = 'warning',
135: ERROR = 'error',
136: CRITICAL = 'critical';
137:
138:
139:
140: 141: 142:
143: final public function __construct()
144: {
145: throw new StaticClassException;
146: }
147:
148:
149:
150: 151: 152: 153:
154: public static function _init()
155: {
156: self::$time = microtime(TRUE);
157: self::$consoleMode = PHP_SAPI === 'cli';
158: self::$productionMode = self::DETECT;
159: if (self::$consoleMode) {
160: self::$source = empty($_SERVER['argv']) ? 'cli' : 'cli: ' . implode(' ', $_SERVER['argv']);
161: } else {
162: self::$ajaxDetected = isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] === 'XMLHttpRequest';
163: if (isset($_SERVER['REQUEST_URI'])) {
164: self::$source = (isset($_SERVER['HTTPS']) && strcasecmp($_SERVER['HTTPS'], 'off') ? 'https://' : 'http://')
165: . (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : (isset($_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME'] : ''))
166: . $_SERVER['REQUEST_URI'];
167: }
168: }
169:
170: self::$logger = new Logger;
171: self::$logDirectory = & self::$logger->directory;
172: self::$email = & self::$logger->email;
173: self::$mailer = & self::$logger->mailer;
174: self::$emailSnooze = & Logger::$emailSnooze;
175:
176: self::$fireLogger = new FireLogger;
177:
178: self::$blueScreen = new DebugBlueScreen;
179: self::$blueScreen->addPanel(create_function('$e', '
180: if ($e instanceof TemplateException) {
181: return array(
182: \'tab\' => \'Template\',
183: \'panel\' => \'<p><b>File:</b> \' . DebugHelpers::editorLink($e->sourceFile, $e->sourceLine)
184: . \' <b>Line:</b> \' . ($e->sourceLine ? $e->sourceLine : \'n/a\') . \'</p>\'
185: . ($e->sourceLine ? DebugBlueScreen::highlightFile($e->sourceFile, $e->sourceLine) : \'\')
186: );
187: } elseif ($e instanceof NeonException && preg_match(\'#line (\\d+)#\', $e->getMessage(), $m)) {
188: if ($item = DebugHelpers::findTrace($e->getTrace(), \'ConfigNeonAdapter::load\')) {
189: return array(
190: \'tab\' => \'NEON\',
191: \'panel\' => \'<p><b>File:</b> \' . DebugHelpers::editorLink($item[\'args\'][0], $m[1]) . \' <b>Line:</b> \' . $m[1] . \'</p>\'
192: . DebugBlueScreen::highlightFile($item[\'args\'][0], $m[1])
193: );
194: } elseif ($item = DebugHelpers::findTrace($e->getTrace(), \'Neon::decode\')) {
195: return array(
196: \'tab\' => \'NEON\',
197: \'panel\' => DebugBlueScreen::highlightPhp($item[\'args\'][0], $m[1])
198: );
199: }
200: }
201: '));
202:
203: self::$bar = new DebugBar;
204: self::$bar->addPanel(new DefaultBarPanel('time'));
205: self::$bar->addPanel(new DefaultBarPanel('memory'));
206: self::$bar->addPanel(self::$errorPanel = new DefaultBarPanel('errors'));
207: self::$bar->addPanel(self::$dumpPanel = new DefaultBarPanel('dumps'));
208: }
209:
210:
211:
212:
213:
214:
215:
216: 217: 218: 219: 220: 221: 222:
223: public static function enable($mode = NULL, $logDirectory = NULL, $email = NULL)
224: {
225: error_reporting(E_ALL | E_STRICT);
226:
227:
228: if (is_bool($mode)) {
229: self::$productionMode = $mode;
230:
231: } elseif ($mode !== self::DETECT || self::$productionMode === NULL) {
232: $mode = is_string($mode) ? preg_split('#[,\s]+#', $mode) : (array) $mode;
233: $mode[] = '127.0.0.1';
234: $mode[] = '::1';
235: self::$productionMode = !in_array(isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : php_uname('n'), $mode, TRUE);
236: }
237:
238:
239: if (is_string($logDirectory)) {
240: self::$logDirectory = realpath($logDirectory);
241: if (self::$logDirectory === FALSE) {
242: throw new DirectoryNotFoundException("Directory '$logDirectory' is not found.");
243: }
244: } elseif ($logDirectory === FALSE) {
245: self::$logDirectory = FALSE;
246:
247: } elseif (self::$logDirectory === NULL) {
248: self::$logDirectory = defined('APP_DIR') ? APP_DIR . '/../log' : getcwd() . '/log';
249: }
250: if (self::$logDirectory) {
251: ini_set('error_log', self::$logDirectory . '/php_error.log');
252: }
253:
254:
255: if (function_exists('ini_set')) {
256: ini_set('display_errors', !self::$productionMode);
257: ini_set('html_errors', FALSE);
258: ini_set('log_errors', FALSE);
259:
260: } elseif (ini_get('display_errors') != !self::$productionMode && ini_get('display_errors') !== (self::$productionMode ? 'stderr' : 'stdout')) {
261: throw new NotSupportedException('Function ini_set() must be enabled.');
262: }
263:
264: if ($email) {
265: if (!is_string($email)) {
266: throw new InvalidArgumentException('Email address must be a string.');
267: }
268: self::$email = $email;
269: }
270:
271: if (!defined('E_DEPRECATED')) {
272: define('E_DEPRECATED', 8192);
273: }
274:
275: if (!defined('E_USER_WARNING')) {
276: define('E_USER_WARNING', 16384);
277: }
278:
279: if (!self::$enabled) {
280: register_shutdown_function(array(__CLASS__, '_shutdownHandler'));
281: set_exception_handler(array(__CLASS__, '_exceptionHandler'));
282: set_error_handler(array(__CLASS__, '_errorHandler'));
283: self::$enabled = TRUE;
284: }
285: }
286:
287:
288:
289: 290: 291: 292:
293: public static function isEnabled()
294: {
295: return self::$enabled;
296: }
297:
298:
299:
300: 301: 302: 303: 304: 305:
306: public static function log($message, $priority = self::INFO)
307: {
308: if (self::$logDirectory === FALSE) {
309: return;
310:
311: } elseif (!self::$logDirectory) {
312: throw new InvalidStateException('Logging directory is not specified in Debugger::$logDirectory.');
313: }
314:
315: if ($message instanceof Exception) {
316: $exception = $message;
317: $message = ($message instanceof FatalErrorException
318: ? 'Fatal error: ' . $exception->getMessage()
319: : get_class($exception) . ": " . $exception->getMessage())
320: . " in " . $exception->getFile() . ":" . $exception->getLine();
321:
322: $hash = md5($exception . (method_exists($exception, 'getPrevious') ? $exception->getPrevious() : (isset($exception->previous) ? $exception->previous : '')));
323: $exceptionFilename = "exception-" . @date('Y-m-d-H-i-s') . "-$hash.html";
324: foreach (new DirectoryIterator(self::$logDirectory) as $entry) {
325: if (strpos($entry, $hash)) {
326: $exceptionFilename = $entry;
327: $saved = TRUE;
328: break;
329: }
330: }
331: }
332:
333: self::$logger->log(array(
334: @date('[Y-m-d H-i-s]'),
335: trim($message),
336: self::$source ? ' @ ' . self::$source : NULL,
337: !empty($exceptionFilename) ? ' @@ ' . $exceptionFilename : NULL
338: ), $priority);
339:
340: if (!empty($exceptionFilename)) {
341: $exceptionFilename = self::$logDirectory . '/' . $exceptionFilename;
342: if (empty($saved) && $logHandle = @fopen($exceptionFilename, 'w')) {
343: ob_start();
344: ob_start(create_function('$buffer', 'extract(NCFix::$vars['.NCFix::uses(array('logHandle'=>$logHandle)).'], EXTR_REFS); fwrite($logHandle, $buffer); '), 4096);
345: self::$blueScreen->render($exception);
346: ob_end_flush();
347: ob_end_clean();
348: fclose($logHandle);
349: }
350: return strtr($exceptionFilename, '\\/', DIRECTORY_SEPARATOR . DIRECTORY_SEPARATOR);
351: }
352: }
353:
354:
355:
356: 357: 358: 359: 360:
361: public static function _shutdownHandler()
362: {
363: if (!self::$enabled) {
364: return;
365: }
366:
367:
368: static $types = array(
369: E_ERROR => 1,
370: E_CORE_ERROR => 1,
371: E_COMPILE_ERROR => 1,
372: E_PARSE => 1,
373: );
374: $error = error_get_last();
375: if (isset($types[$error['type']])) {
376: self::_exceptionHandler(new FatalErrorException($error['message'], 0, $error['type'], $error['file'], $error['line'], NULL));
377: }
378:
379:
380: if (self::$bar && !self::$productionMode && self::isHtmlMode()) {
381: self::$bar->render();
382: }
383: }
384:
385:
386:
387: 388: 389: 390: 391: 392:
393: public static function _exceptionHandler(Exception $exception)
394: {
395: if (!headers_sent()) {
396: $protocol = isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.1';
397: header($protocol . ' 500', TRUE, 500);
398: }
399:
400: try {
401: if (self::$productionMode) {
402: try {
403: self::log($exception, self::ERROR);
404: } catch (Exception $e) {
405: echo 'FATAL ERROR: unable to log error';
406: }
407:
408: if (self::$consoleMode) {
409: echo "ERROR: the server encountered an internal error and was unable to complete your request.\n";
410:
411: } elseif (self::isHtmlMode()) {
412: require dirname(__FILE__) . '/templates/error.phtml';
413: }
414:
415: } else {
416: if (self::$consoleMode) {
417: echo "$exception\n";
418: if ($file = self::log($exception)) {
419: echo "(stored in $file)\n";
420: if (self::$browser) {
421: exec(self::$browser . ' ' . escapeshellarg($file));
422: }
423: }
424:
425: } elseif (self::isHtmlMode()) {
426: self::$blueScreen->render($exception);
427: if (self::$bar) {
428: self::$bar->render();
429: }
430:
431: } elseif (!self::fireLog($exception, self::ERROR)) {
432: $file = self::log($exception);
433: if (!headers_sent()) {
434: header("X-Nette-Error-Log: $file");
435: }
436: }
437: }
438:
439: foreach (self::$onFatalError as $handler) {
440: call_user_func($handler, $exception);
441: }
442:
443: } catch (Exception $e) {
444: if (self::$productionMode) {
445: echo self::isHtmlMode() ? '<meta name=robots content=noindex>FATAL ERROR' : 'FATAL ERROR';
446: } else {
447: echo "FATAL ERROR: thrown ", get_class($e), ': ', $e->getMessage(),
448: "\nwhile processing ", get_class($exception), ': ', $exception->getMessage(), "\n";
449: }
450: }
451:
452: self::$enabled = FALSE;
453: exit(255);
454: }
455:
456:
457:
458: 459: 460: 461: 462: 463: 464: 465: 466: 467: 468:
469: public static function _errorHandler($severity, $message, $file, $line, $context)
470: {
471: if (self::$scream) {
472: error_reporting(E_ALL | E_STRICT);
473: }
474:
475: if (self::$lastError !== FALSE && ($severity & error_reporting()) === $severity) {
476: self::$lastError = new ErrorException($message, 0, $severity, $file, $line);
477: return NULL;
478: }
479:
480: if ($severity === E_RECOVERABLE_ERROR || $severity === E_USER_ERROR) {
481: throw new FatalErrorException($message, 0, $severity, $file, $line, $context);
482:
483: } elseif (($severity & error_reporting()) !== $severity) {
484: return FALSE;
485:
486: } elseif (!self::$productionMode && (is_bool(self::$strictMode) ? self::$strictMode : ((self::$strictMode & $severity) === $severity))) {
487: self::_exceptionHandler(new FatalErrorException($message, 0, $severity, $file, $line, $context));
488: }
489:
490: static $types = array(
491: E_WARNING => 'Warning',
492: E_COMPILE_WARNING => 'Warning',
493: E_USER_WARNING => 'Warning',
494: E_NOTICE => 'Notice',
495: E_USER_NOTICE => 'Notice',
496: E_STRICT => 'Strict standards',
497: E_DEPRECATED => 'Deprecated',
498: E_USER_WARNING => 'Deprecated',
499: );
500:
501: $message = 'PHP ' . (isset($types[$severity]) ? $types[$severity] : 'Unknown error') . ": $message";
502: $count = & self::$errorPanel->data["$message|$file|$line"];
503:
504: if ($count++) {
505: return NULL;
506:
507: } elseif (self::$productionMode) {
508: self::log("$message in $file:$line", self::ERROR);
509: return NULL;
510:
511: } else {
512: $ok = self::fireLog(new ErrorException($message, 0, $severity, $file, $line), self::WARNING);
513: return !self::isHtmlMode() || (!self::$bar && !$ok) ? FALSE : NULL;
514: }
515:
516: return FALSE;
517: }
518:
519:
520:
521: 522: 523: 524: 525:
526: public static function toStringException(Exception $exception)
527: {
528: if (self::$enabled) {
529: self::_exceptionHandler($exception);
530: } else {
531: trigger_error($exception->getMessage(), E_USER_ERROR);
532: }
533: }
534:
535:
536:
537: 538: 539: 540:
541: public static function tryError()
542: {
543: if (!self::$enabled && self::$lastError === FALSE) {
544: set_error_handler(array(__CLASS__, '_errorHandler'));
545: }
546: self::$lastError = NULL;
547: }
548:
549:
550:
551: 552: 553: 554: 555:
556: public static function catchError(& $error)
557: {
558: if (!self::$enabled && self::$lastError !== FALSE) {
559: restore_error_handler();
560: }
561: $error = self::$lastError;
562: self::$lastError = FALSE;
563: return (bool) $error;
564: }
565:
566:
567:
568:
569:
570:
571:
572: 573: 574: 575: 576: 577:
578: public static function dump($var, $return = FALSE)
579: {
580: if (!$return && self::$productionMode) {
581: return $var;
582: }
583:
584: $output = "<pre class=\"nette-dump\">" . DebugHelpers::htmlDump($var) . "</pre>\n";
585:
586: if (!$return) {
587: $trace = PHP_VERSION_ID < 50205 ? debug_backtrace() :debug_backtrace(FALSE);
588: $i = DebugHelpers::findTrace($trace, 'dump') ? 1 : 0;
589: if (isset($trace[$i]['file'], $trace[$i]['line']) && is_file($trace[$i]['file'])) {
590: $lines = file($trace[$i]['file']);
591: preg_match('#dump\((.*)\)#', $lines[$trace[$i]['line'] - 1], $m);
592: $output = substr_replace(
593: $output,
594: ' title="' . htmlspecialchars((isset($m[0]) ? "$m[0] \n" : '') . "in file {$trace[$i]['file']} on line {$trace[$i]['line']}") . '"',
595: 4, 0);
596:
597: if (self::$showLocation) {
598: $output = substr_replace(
599: $output,
600: ' <small>in ' . DebugHelpers::editorLink($trace[$i]['file'], $trace[$i]['line']) . ":{$trace[$i]['line']}</small>",
601: -8, 0);
602: }
603: }
604: }
605:
606: if (self::$consoleMode) {
607: if (self::$consoleColors && substr(PHP_OS, 0, 3) !== 'WIN') {
608: $output = preg_replace_callback('#<span class="php-(\w+)">|</span>#', create_function('$m', '
609: return "\\033[" . (isset($m[1], Debugger::$consoleColors[$m[1]]) ? Debugger::$consoleColors[$m[1]] : \'0\') . "m";
610: '), $output);
611: }
612: $output = htmlspecialchars_decode(strip_tags($output), ENT_QUOTES);
613: }
614:
615: if ($return) {
616: return $output;
617:
618: } else {
619: echo $output;
620: return $var;
621: }
622: }
623:
624:
625:
626: 627: 628: 629: 630:
631: public static function timer($name = NULL)
632: {
633: static $time = array();
634: $now = microtime(TRUE);
635: $delta = isset($time[$name]) ? $now - $time[$name] : 0;
636: $time[$name] = $now;
637: return $delta;
638: }
639:
640:
641:
642: 643: 644: 645: 646: 647:
648: public static function barDump($var, $title = NULL)
649: {
650: if (!self::$productionMode) {
651: $dump = array();
652: foreach ((is_array($var) ? $var : array('' => $var)) as $key => $val) {
653: $dump[$key] = DebugHelpers::clickableDump($val);
654: }
655: self::$dumpPanel->data[] = array('title' => $title, 'dump' => $dump);
656: }
657: return $var;
658: }
659:
660:
661:
662: 663: 664: 665: 666:
667: public static function fireLog($message)
668: {
669: if (!self::$productionMode) {
670: return self::$fireLogger->log($message);
671: }
672: }
673:
674:
675:
676: private static function isHtmlMode()
677: {
678: return !self::$ajaxDetected && !self::$consoleMode
679: && !preg_match('#^Content-Type: (?!text/html)#im', implode("\n", headers_list()));
680: }
681:
682:
683:
684:
685: public static function addPanel(IBarPanel $panel, $id = NULL)
686: {
687: return self::$bar->addPanel($panel, $id);
688: }
689:
690: }
691: