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