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 NDebugger
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 NStaticClassException;
146: }
147:
148:
149:
150: 151: 152: 153:
154: public static function _init()
155: {
156: self::$time = isset($_SERVER['REQUEST_TIME_FLOAT']) ? $_SERVER['REQUEST_TIME_FLOAT'] : 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 NLogger;
171: self::$logDirectory = & self::$logger->directory;
172: self::$email = & self::$logger->email;
173: self::$mailer = & self::$logger->mailer;
174: self::$emailSnooze = & NLogger::$emailSnooze;
175:
176: self::$fireLogger = new NFireLogger;
177:
178: self::$blueScreen = new NDebugBlueScreen;
179: self::$blueScreen->addPanel(create_function('$e', '
180: if ($e instanceof NTemplateException) {
181: return array(
182: \'tab\' => \'Template\',
183: \'panel\' => \'<p><b>File:</b> \' . NDebugHelpers::editorLink($e->sourceFile, $e->sourceLine)
184: . \' <b>Line:</b> \' . ($e->sourceLine ? $e->sourceLine : \'n/a\') . \'</p>\'
185: . ($e->sourceLine ? NDebugBlueScreen::highlightFile($e->sourceFile, $e->sourceLine) : \'\')
186: );
187: } elseif ($e instanceof NNeonException && preg_match(\'#line (\\d+)#\', $e->getMessage(), $m)) {
188: if ($item = NDebugHelpers::findTrace($e->getTrace(), \'NConfigNeonAdapter::load\')) {
189: return array(
190: \'tab\' => \'NEON\',
191: \'panel\' => \'<p><b>File:</b> \' . NDebugHelpers::editorLink($item[\'args\'][0], $m[1]) . \' <b>Line:</b> \' . $m[1] . \'</p>\'
192: . NDebugBlueScreen::highlightFile($item[\'args\'][0], $m[1])
193: );
194: } elseif ($item = NDebugHelpers::findTrace($e->getTrace(), \'NNeon::decode\')) {
195: return array(
196: \'tab\' => \'NEON\',
197: \'panel\' => NDebugBlueScreen::highlightPhp($item[\'args\'][0], $m[1])
198: );
199: }
200: }
201: '));
202:
203: self::$bar = new NDebugBar;
204: self::$bar->addPanel(new NDefaultBarPanel('time'));
205: self::$bar->addPanel(new NDefaultBarPanel('memory'));
206: self::$bar->addPanel(self::$errorPanel = new NDefaultBarPanel('errors'));
207: self::$bar->addPanel(self::$dumpPanel = new NDefaultBarPanel('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: $list = is_string($mode) ? preg_split('#[,\s]+#', $mode) : (array) $mode;
233: if (!isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
234: $list[] = '127.0.0.1';
235: $list[] = '::1';
236: }
237: self::$productionMode = !in_array(isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : php_uname('n'), $list, TRUE);
238: }
239:
240:
241: if (is_string($logDirectory)) {
242: self::$logDirectory = realpath($logDirectory);
243: if (self::$logDirectory === FALSE) {
244: die(__METHOD__ . "() error: Log directory is not found or is not directory.");
245: }
246: } elseif ($logDirectory === FALSE) {
247: self::$logDirectory = FALSE;
248:
249: } elseif (self::$logDirectory === NULL) {
250: self::$logDirectory = defined('APP_DIR') ? APP_DIR . '/../log' : getcwd() . '/log';
251: }
252: if (self::$logDirectory) {
253: ini_set('error_log', self::$logDirectory . '/php_error.log');
254: }
255:
256:
257: if (function_exists('ini_set')) {
258: ini_set('display_errors', !self::$productionMode);
259: ini_set('html_errors', FALSE);
260: ini_set('log_errors', FALSE);
261:
262: } elseif (ini_get('display_errors') != !self::$productionMode && ini_get('display_errors') !== (self::$productionMode ? 'stderr' : 'stdout')) {
263: die(__METHOD__ . "() error: Unable to set 'display_errors' because function ini_set() is disabled.");
264: }
265:
266: if ($email) {
267: if (!is_string($email)) {
268: die(__METHOD__ . '() error: Email address must be a string.');
269: }
270: self::$email = $email;
271: }
272:
273: if (!defined('E_DEPRECATED')) {
274: define('E_DEPRECATED', 8192);
275: }
276:
277: if (!defined('E_USER_WARNING')) {
278: define('E_USER_WARNING', 16384);
279: }
280:
281: if (!self::$enabled) {
282: register_shutdown_function(array(__CLASS__, '_shutdownHandler'));
283: set_exception_handler(array(__CLASS__, '_exceptionHandler'));
284: set_error_handler(array(__CLASS__, '_errorHandler'));
285: self::$enabled = TRUE;
286: }
287: }
288:
289:
290:
291: 292: 293: 294:
295: public static function isEnabled()
296: {
297: return self::$enabled;
298: }
299:
300:
301:
302: 303: 304: 305: 306: 307:
308: public static function log($message, $priority = self::INFO)
309: {
310: if (self::$logDirectory === FALSE) {
311: return;
312:
313: } elseif (!self::$logDirectory) {
314: throw new InvalidStateException('Logging directory is not specified in NDebugger::$logDirectory.');
315: }
316:
317: if ($message instanceof Exception) {
318: $exception = $message;
319: $message = ($message instanceof FatalErrorException
320: ? 'Fatal error: ' . $exception->getMessage()
321: : get_class($exception) . ": " . $exception->getMessage())
322: . " in " . $exception->getFile() . ":" . $exception->getLine();
323:
324: $hash = md5($exception . (method_exists($exception, 'getPrevious') ? $exception->getPrevious() : (isset($exception->previous) ? $exception->previous : '')));
325: $exceptionFilename = "exception-" . @date('Y-m-d-H-i-s') . "-$hash.html";
326: foreach (new DirectoryIterator(self::$logDirectory) as $entry) {
327: if (strpos($entry, $hash)) {
328: $exceptionFilename = $entry;
329: $saved = TRUE;
330: break;
331: }
332: }
333: }
334:
335: self::$logger->log(array(
336: @date('[Y-m-d H-i-s]'),
337: trim($message),
338: self::$source ? ' @ ' . self::$source : NULL,
339: !empty($exceptionFilename) ? ' @@ ' . $exceptionFilename : NULL
340: ), $priority);
341:
342: if (!empty($exceptionFilename)) {
343: $exceptionFilename = self::$logDirectory . '/' . $exceptionFilename;
344: if (empty($saved) && $logHandle = @fopen($exceptionFilename, 'w')) {
345: ob_start();
346: ob_start(create_function('$buffer', 'extract(NCFix::$vars['.NCFix::uses(array('logHandle'=>$logHandle)).'], EXTR_REFS); fwrite($logHandle, $buffer); '), 4096);
347: self::$blueScreen->render($exception);
348: ob_end_flush();
349: ob_end_clean();
350: fclose($logHandle);
351: }
352: return strtr($exceptionFilename, '\\/', DIRECTORY_SEPARATOR . DIRECTORY_SEPARATOR);
353: }
354: }
355:
356:
357:
358: 359: 360: 361: 362:
363: public static function _shutdownHandler()
364: {
365: if (!self::$enabled) {
366: return;
367: }
368:
369:
370: static $types = array(
371: E_ERROR => 1,
372: E_CORE_ERROR => 1,
373: E_COMPILE_ERROR => 1,
374: E_PARSE => 1,
375: );
376: $error = error_get_last();
377: if (isset($types[$error['type']])) {
378: self::_exceptionHandler(new FatalErrorException($error['message'], 0, $error['type'], $error['file'], $error['line'], NULL));
379: }
380:
381:
382: if (self::$bar && !self::$productionMode && self::isHtmlMode()) {
383: self::$bar->render();
384: }
385: }
386:
387:
388:
389: 390: 391: 392: 393: 394:
395: public static function _exceptionHandler(Exception $exception)
396: {
397: if (!headers_sent()) {
398: $protocol = isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.1';
399: header($protocol . ' 500', TRUE, 500);
400: }
401:
402: try {
403: if (self::$productionMode) {
404: try {
405: self::log($exception, self::ERROR);
406: } catch (Exception $e) {
407: echo 'FATAL ERROR: unable to log error';
408: }
409:
410: if (self::$consoleMode) {
411: echo "ERROR: the server encountered an internal error and was unable to complete your request.\n";
412:
413: } elseif (self::isHtmlMode()) {
414: require dirname(__FILE__) . '/templates/error.phtml';
415: }
416:
417: } else {
418: if (self::$consoleMode) {
419: echo "$exception\n";
420: if ($file = self::log($exception)) {
421: echo "(stored in $file)\n";
422: if (self::$browser) {
423: exec(self::$browser . ' ' . escapeshellarg($file));
424: }
425: }
426:
427: } elseif (self::isHtmlMode()) {
428: self::$blueScreen->render($exception);
429: if (self::$bar) {
430: self::$bar->render();
431: }
432:
433: } elseif (!self::fireLog($exception, self::ERROR)) {
434: $file = self::log($exception);
435: if (!headers_sent()) {
436: header("X-Nette-Error-Log: $file");
437: }
438: }
439: }
440:
441: foreach (self::$onFatalError as $handler) {
442: call_user_func($handler, $exception);
443: }
444:
445: } catch (Exception $e) {
446: if (self::$productionMode) {
447: echo self::isHtmlMode() ? '<meta name=robots content=noindex>FATAL ERROR' : 'FATAL ERROR';
448: } else {
449: echo "FATAL ERROR: thrown ", get_class($e), ': ', $e->getMessage(),
450: "\nwhile processing ", get_class($exception), ': ', $exception->getMessage(), "\n";
451: }
452: }
453:
454: self::$enabled = FALSE;
455: exit(255);
456: }
457:
458:
459:
460: 461: 462: 463: 464: 465: 466: 467: 468: 469: 470:
471: public static function _errorHandler($severity, $message, $file, $line, $context)
472: {
473: if (self::$scream) {
474: error_reporting(E_ALL | E_STRICT);
475: }
476:
477: if (self::$lastError !== FALSE && ($severity & error_reporting()) === $severity) {
478: self::$lastError = new ErrorException($message, 0, $severity, $file, $line);
479: return NULL;
480: }
481:
482: if ($severity === E_RECOVERABLE_ERROR || $severity === E_USER_ERROR) {
483: if (NDebugHelpers::findTrace(PHP_VERSION_ID < 50205 ? debug_backtrace() :debug_backtrace(FALSE), '*::__toString')) {
484: $previous = isset($context['e']) && $context['e'] instanceof Exception ? $context['e'] : NULL;
485: self::_exceptionHandler(new FatalErrorException($message, 0, $severity, $file, $line, $context, $previous));
486: }
487: throw new FatalErrorException($message, 0, $severity, $file, $line, $context);
488:
489: } elseif (($severity & error_reporting()) !== $severity) {
490: return FALSE;
491:
492: } elseif (!self::$productionMode && (is_bool(self::$strictMode) ? self::$strictMode : ((self::$strictMode & $severity) === $severity))) {
493: self::_exceptionHandler(new FatalErrorException($message, 0, $severity, $file, $line, $context));
494: }
495:
496: static $types = array(
497: E_WARNING => 'Warning',
498: E_COMPILE_WARNING => 'Warning',
499: E_USER_WARNING => 'Warning',
500: E_NOTICE => 'Notice',
501: E_USER_NOTICE => 'Notice',
502: E_STRICT => 'Strict standards',
503: E_DEPRECATED => 'Deprecated',
504: E_USER_WARNING => 'Deprecated',
505: );
506:
507: $message = 'PHP ' . (isset($types[$severity]) ? $types[$severity] : 'Unknown error') . ": $message";
508: $count = & self::$errorPanel->data["$message|$file|$line"];
509:
510: if ($count++) {
511: return NULL;
512:
513: } elseif (self::$productionMode) {
514: self::log("$message in $file:$line", self::ERROR);
515: return NULL;
516:
517: } else {
518: $ok = self::fireLog(new ErrorException($message, 0, $severity, $file, $line), self::WARNING);
519: return !self::isHtmlMode() || (!self::$bar && !$ok) ? FALSE : NULL;
520: }
521:
522: return FALSE;
523: }
524:
525:
526:
527: 528: 529: 530: 531:
532: public static function toStringException(Exception $exception)
533: {
534: if (self::$enabled) {
535: self::_exceptionHandler($exception);
536: } else {
537: trigger_error($exception->getMessage(), E_USER_ERROR);
538: }
539: }
540:
541:
542:
543: 544: 545: 546:
547: public static function tryError()
548: {
549: if (!self::$enabled && self::$lastError === FALSE) {
550: set_error_handler(array(__CLASS__, '_errorHandler'));
551: }
552: self::$lastError = NULL;
553: }
554:
555:
556:
557: 558: 559: 560: 561:
562: public static function catchError(& $error)
563: {
564: if (!self::$enabled && self::$lastError !== FALSE) {
565: restore_error_handler();
566: }
567: $error = self::$lastError;
568: self::$lastError = FALSE;
569: return (bool) $error;
570: }
571:
572:
573:
574:
575:
576:
577:
578: 579: 580: 581: 582: 583:
584: public static function dump($var, $return = FALSE)
585: {
586: if (!$return && self::$productionMode) {
587: return $var;
588: }
589:
590: $output = "<pre class=\"nette-dump\">" . NDebugHelpers::htmlDump($var) . "</pre>\n";
591:
592: if (!$return) {
593: $trace = PHP_VERSION_ID < 50205 ? debug_backtrace() :debug_backtrace(FALSE);
594: $item = ($tmp=NDebugHelpers::findTrace($trace, 'dump')) ? $tmp : NDebugHelpers::findTrace($trace, __CLASS__ . '::dump');
595: if (isset($item['file'], $item['line']) && is_file($item['file'])) {
596: $lines = file($item['file']);
597: preg_match('#dump\((.*)\)#', $lines[$item['line'] - 1], $m);
598: $output = substr_replace(
599: $output,
600: ' title="' . htmlspecialchars((isset($m[0]) ? "$m[0] \n" : '') . "in file {$item['file']} on line {$item['line']}") . '"',
601: 4, 0);
602:
603: if (self::$showLocation) {
604: $output = substr_replace(
605: $output,
606: ' <small>in ' . NDebugHelpers::editorLink($item['file'], $item['line']) . ":{$item['line']}</small>",
607: -8, 0);
608: }
609: }
610: }
611:
612: if (self::$consoleMode) {
613: if (self::$consoleColors && substr(getenv('TERM'), 0, 5) === 'xterm') {
614: $output = preg_replace_callback('#<span class="php-(\w+)">|</span>#', create_function('$m', '
615: return "\\033[" . (isset($m[1], NDebugger::$consoleColors[$m[1]]) ? NDebugger::$consoleColors[$m[1]] : \'0\') . "m";
616: '), $output);
617: }
618: $output = htmlspecialchars_decode(strip_tags($output), ENT_QUOTES);
619: }
620:
621: if ($return) {
622: return $output;
623:
624: } else {
625: echo $output;
626: return $var;
627: }
628: }
629:
630:
631:
632: 633: 634: 635: 636:
637: public static function timer($name = NULL)
638: {
639: static $time = array();
640: $now = microtime(TRUE);
641: $delta = isset($time[$name]) ? $now - $time[$name] : 0;
642: $time[$name] = $now;
643: return $delta;
644: }
645:
646:
647:
648: 649: 650: 651: 652: 653:
654: public static function barDump($var, $title = NULL)
655: {
656: if (!self::$productionMode) {
657: $dump = array();
658: foreach ((is_array($var) ? $var : array('' => $var)) as $key => $val) {
659: $dump[$key] = NDebugHelpers::clickableDump($val);
660: }
661: self::$dumpPanel->data[] = array('title' => $title, 'dump' => $dump);
662: }
663: return $var;
664: }
665:
666:
667:
668: 669: 670: 671: 672:
673: public static function fireLog($message)
674: {
675: if (!self::$productionMode) {
676: return self::$fireLogger->log($message);
677: }
678: }
679:
680:
681:
682: private static function isHtmlMode()
683: {
684: return !self::$ajaxDetected && !self::$consoleMode
685: && !preg_match('#^Content-Type: (?!text/html)#im', implode("\n", headers_list()));
686: }
687:
688:
689:
690:
691: public static function addPanel(IBarPanel $panel, $id = NULL)
692: {
693: return self::$bar->addPanel($panel, $id);
694: }
695:
696: }
697: