public function getPanel()
    {
        $duplicitesQueries = $this->getDuplicateQueries();
        if (empty($duplicitesQueries)) {
            return '';
        }
        $panel = '
		<div class="tracy-inner nette-DbDuplicatesQueries">
			<table>
				<tr><th>Count</th><th>SQL Query</th><th>Locations</th></tr>';
        foreach ($duplicitesQueries as $query => $dupliciteQuery) {
            $panel .= '<tr>';
            $count = count($dupliciteQuery);
            $panel .= '<td>' . $count . 'x</td>';
            $panel .= '<td>' . $query . '</td>';
            $panel .= '<td>';
            foreach ($dupliciteQuery as $queryInformation) {
                $source = $queryInformation[1];
                if (!$source) {
                    continue;
                }
                $panel .= substr_replace(Tracy\Helpers::editorLink($source[0], $source[1]), ' class="nette-DbConnectionPanel-source"', 2, 0) . '<br />';
            }
            $panel .= '</td>';
            $panel .= '</tr>';
        }
        $panel .= '
			</table>
		</div>';
        return $panel;
    }
 /**
  * render.
  *
  * @method render
  *
  * @param \Exception $exception
  * @param array $error
  *
  * @return \Exception
  */
 protected function fixStack($exception, $error)
 {
     if (in_array($error['type'], [E_ERROR, E_CORE_ERROR, E_COMPILE_ERROR, E_PARSE, E_RECOVERABLE_ERROR, E_USER_ERROR], true) === true) {
         return Helpers::fixStack(new ErrorException($error['message'], 0, $error['type'], $error['file'], $error['line']));
     }
     return $exception;
 }
Exemple #3
0
 public static function initialize()
 {
     $blueScreen = Tracy\Debugger::getBlueScreen();
     if (preg_match('#(.+)/Bridges/Framework$#', strtr(__DIR__, '\\', '/'), $m)) {
         if (preg_match('#(.+)/nette/bootstrap/src$#', $m[1], $m2)) {
             $blueScreen->collapsePaths[] = "{$m2['1']}/nette";
             $blueScreen->collapsePaths[] = "{$m2['1']}/latte";
         } else {
             $blueScreen->collapsePaths[] = $m[1];
         }
     }
     if (class_exists('Nette\\Framework')) {
         $bar = Tracy\Debugger::getBar();
         $bar->info[] = $blueScreen->info[] = 'Nette Framework ' . Nette\Framework::VERSION . ' (' . Nette\Framework::REVISION . ')';
     }
     $blueScreen->addPanel(function ($e) {
         if ($e instanceof Latte\CompileException) {
             return array('tab' => 'Template', 'panel' => '<p>' . (is_file($e->sourceName) ? '<b>File:</b> ' . Helpers::editorLink($e->sourceName, $e->sourceLine) : htmlspecialchars($e->sourceName)) . '</p>' . ($e->sourceCode ? '<pre>' . BlueScreen::highlightLine(htmlspecialchars($e->sourceCode), $e->sourceLine) . '</pre>' : ''));
         } elseif ($e instanceof Nette\Neon\Exception && preg_match('#line (\\d+)#', $e->getMessage(), $m)) {
             if ($item = Helpers::findTrace($e->getTrace(), 'Nette\\DI\\Config\\Adapters\\NeonAdapter::load')) {
                 return array('tab' => 'NEON', 'panel' => '<p><b>File:</b> ' . Helpers::editorLink($item['args'][0], $m[1]) . '</p>' . BlueScreen::highlightFile($item['args'][0], $m[1]));
             } elseif ($item = Helpers::findTrace($e->getTrace(), 'Nette\\Neon\\Decoder::decode')) {
                 return array('tab' => 'NEON', 'panel' => BlueScreen::highlightPhp($item['args'][0], $m[1]));
             }
         }
     });
 }
Exemple #4
0
 public function log($message, $priority = self::INFO)
 {
     $parent = parent::log($message, $priority);
     $checked = array(self::CRITICAL, self::ERROR);
     if (defined('self::EXCEPTION')) {
         $checked[] = self::EXCEPTION;
     }
     if (in_array($priority, $checked, TRUE)) {
         $index = NULL;
         $trace = debug_backtrace(FALSE);
         if (!Tracy\Helpers::findTrace($trace, 'Tracy\\Debugger::log', $index)) {
             if (!Tracy\Helpers::findTrace($trace, 'Nette\\Diagnostics\\Debugger::log', $index)) {
                 Tracy\Helpers::findTrace($trace, 'log', $index);
             }
         }
         $errorTrace = $trace[$index + 1];
         //get trace for _errorHandler call
         $exceptionTrace = $trace[$index];
         //get trace for _exception or ::log call
         //if()
         $exception = NULL;
         if (isset($errorTrace['args']) && count($errorTrace['args']) == 5) {
             $exception = new \ErrorException($errorTrace['args'][1], 0, $errorTrace['args'][0], $errorTrace['args'][2], $errorTrace['args'][3]);
         } elseif (!empty($exceptionTrace['args']) && !empty($exceptionTrace['args'][0]) && $exceptionTrace['args'][0] instanceof \Exception) {
             $exception = $exceptionTrace['args'][0];
         }
         if ($exception) {
             $error = Consumerr::addError($exception);
             if ($error && is_array($message)) {
                 $error->addData('file', Tracy\Debugger::$logDirectory . '/' . substr($message[3], 5));
             }
         }
     }
     return $parent;
 }
 private function renderHtml()
 {
     $res = '<style>code, pre {white-space:nowrap} a {text-decoration:none} pre {color:gray;display:inline} big {color:red}</style><code>';
     foreach ($this->list as $item) {
         $res .= Helpers::editorLink($item[0], $item[1]) . ' ' . str_replace(self::BOM, '<big>BOM</big>', Dumper::toHtml($item[2])) . "<br>\n";
     }
     return $res . '</code>';
 }
Exemple #6
0
 /**
  * @param \Kdyby\Autowired\Exception $e
  * @return string
  */
 protected static function highlightException(Kdyby\Autowired\Exception $e)
 {
     $refl = $e->getReflector();
     /** @var \Reflector|\Nette\Reflection\Property|\Nette\Reflection\Method $refl */
     $file = $refl->getDeclaringClass()->getFileName();
     $line = $refl instanceof Nette\Reflection\Property ? self::getPropertyLine($refl) : $refl->getStartLine();
     return '<p><b>File:</b> ' . Helpers::editorLink($file, $line) . '</p>' . BlueScreen::highlightFile($file, $line);
 }
 public function log($message, $priority = self::INFO)
 {
     $context = ['at' => Helpers::getSource()];
     if ($message instanceof Throwable) {
         $context['exception'] = $message;
         $message = '';
     }
     $this->monolog->addRecord(self::PRIORITY_MAP[$priority] ?? Monolog\Logger::ERROR, $message, $context);
 }
 /**
  * @author David Grudl
  * @see    https://github.com/nette/tracy
  */
 protected static function formatMessage(Throwable $message) : string
 {
     $tmp = [];
     while ($message) {
         $tmp[] = ($message instanceof \ErrorException ? Helpers::errorTypeToString($message->getSeverity()) . ': ' . $message->getMessage() : Helpers::getClass($message) . ': ' . $message->getMessage()) . ' in ' . $message->getFile() . ':' . $message->getLine();
         $message = $message->getPrevious();
     }
     $message = implode($tmp, "\ncaused by ");
     return trim($message);
 }
Exemple #9
0
	/**
	 * Returns syntax highlighted source code.
	 * @param  string
	 * @param  int
	 * @param  int
	 * @return string
	 */
	public static function highlightFile($file, $line, $lines = 15, array $vars = NULL)
	{
		$source = @file_get_contents($file); // intentionally @
		if ($source) {
			$source = static::highlightPhp($source, $line, $lines, $vars);
			if ($editor = Helpers::editorUri($file, $line)) {
				$source = substr_replace($source, ' data-tracy-href="' . htmlspecialchars($editor, ENT_QUOTES, 'UTF-8') . '"', 4, 0);
			}
			return $source;
		}
	}
Exemple #10
0
 public static function renderException($e)
 {
     if (!$e instanceof \PDOException) {
         return;
     }
     if (isset($e->queryString)) {
         $sql = $e->queryString;
     } elseif ($item = Tracy\Helpers::findTrace($e->getTrace(), 'PDO::prepare')) {
         $sql = $item['args'][0];
     }
     return isset($sql) ? ['tab' => 'SQL', 'panel' => Helpers::dumpSql($sql)] : NULL;
 }
 private function renderHtml()
 {
     $res = '<style>code, pre {white-space:nowrap} a {text-decoration:none} pre {color:gray;display:inline} big {color:red}</style><code>';
     foreach ($this->list as $item) {
         $stack = array();
         foreach (array_slice($item[3], 1) as $t) {
             $t += array('class' => '', 'type' => '', 'function' => '');
             $stack[] = "{$t['class']}{$t['type']}{$t['function']}()" . (isset($t['file'], $t['line']) ? ' in ' . basename($t['file']) . ":{$t['line']}" : '');
         }
         $res .= Helpers::editorLink($item[0], $item[1]) . ' ' . '<span title="' . htmlspecialchars(implode("\n", $stack), ENT_IGNORE | ENT_QUOTES, 'UTF-8') . '">' . str_replace(self::BOM, '<big>BOM</big>', Dumper::toHtml($item[2])) . "</span><br>\n";
     }
     return $res . '</code>';
 }
Exemple #12
0
 public static function initialize()
 {
     $blueScreen = Tracy\Debugger::getBlueScreen();
     if (class_exists('Nette\\Framework')) {
         $version = Framework::VERSION . (Framework::REVISION ? ' (' . Framework::REVISION . ')' : '');
         Tracy\Debugger::getBar()->getPanel('Tracy:info')->data['Nette Framework'] = $version;
         $blueScreen->info[] = "Nette Framework {$version}";
     }
     $blueScreen->addPanel(function ($e) {
         if ($e instanceof Latte\CompileException) {
             return ['tab' => 'Template', 'panel' => (@is_file($e->sourceName) ? '<p><b>File:</b> ' . Helpers::editorLink($e->sourceName, $e->sourceLine) . '</p>' : '') . '<pre>' . BlueScreen::highlightLine(htmlspecialchars($e->sourceCode, ENT_IGNORE, 'UTF-8'), $e->sourceLine) . '</pre>'];
         }
     });
     $blueScreen->addPanel(function ($e) {
         if ($e instanceof Nette\Neon\Exception && preg_match('#line (\\d+)#', $e->getMessage(), $m) && ($trace = Helpers::findTrace($e->getTrace(), 'Nette\\Neon\\Decoder::decode'))) {
             return ['tab' => 'NEON', 'panel' => ($trace2 = Helpers::findTrace($e->getTrace(), 'Nette\\DI\\Config\\Adapters\\NeonAdapter::load')) ? '<p><b>File:</b> ' . Helpers::editorLink($trace2['args'][0], $m[1]) . '</p>' . BlueScreen::highlightFile($trace2['args'][0], $m[1]) : BlueScreen::highlightPhp($trace['args'][0], $m[1])];
         }
     });
 }
Exemple #13
0
 public static function initialize()
 {
     $bar = Tracy\Debugger::getBar();
     $bar->info[] = 'Nette Framework ' . Nette\Framework::VERSION . ' (' . substr(Nette\Framework::REVISION, 8) . ')';
     $blueScreen = Tracy\Debugger::getBlueScreen();
     $blueScreen->collapsePaths[] = dirname(dirname(__DIR__));
     $blueScreen->info[] = 'Nette Framework ' . Nette\Framework::VERSION . ' (revision ' . Nette\Framework::REVISION . ')';
     $blueScreen->addPanel(function ($e) {
         if ($e instanceof Latte\CompileException) {
             return array('tab' => 'Template', 'panel' => '<p>' . (is_file($e->sourceName) ? '<b>File:</b> ' . Helpers::editorLink($e->sourceName, $e->sourceLine) : htmlspecialchars($e->sourceName)) . '</p>' . ($e->sourceCode ? '<pre>' . BlueScreen::highlightLine(htmlspecialchars($e->sourceCode), $e->sourceLine) . '</pre>' : ''));
         } elseif ($e instanceof Nette\Utils\NeonException && preg_match('#line (\\d+)#', $e->getMessage(), $m)) {
             if ($item = Helpers::findTrace($e->getTrace(), 'Nette\\DI\\Config\\Adapters\\NeonAdapter::load')) {
                 return array('tab' => 'NEON', 'panel' => '<p><b>File:</b> ' . Helpers::editorLink($item['args'][0], $m[1]) . '</p>' . BlueScreen::highlightFile($item['args'][0], $m[1]));
             } elseif ($item = Helpers::findTrace($e->getTrace(), 'Nette\\Utils\\Neon::decode')) {
                 return array('tab' => 'NEON', 'panel' => BlueScreen::highlightPhp($item['args'][0], $m[1]));
             }
         }
     });
 }
    public function getPanel()
    {
        $this->disabled = TRUE;
        $s = '';
        foreach ($this->queries as $query) {
            list($connection, $sql, $params, $source, $time, $rows, $error) = $query;
            $explain = NULL;
            // EXPLAIN is called here to work SELECT FOUND_ROWS()
            if (!$error && $this->explain && preg_match('#\\s*\\(?\\s*SELECT\\s#iA', $sql)) {
                try {
                    $cmd = is_string($this->explain) ? $this->explain : 'EXPLAIN';
                    $explain = $connection->queryArgs("{$cmd} {$sql}", $params)->fetchAll();
                } catch (\PDOException $e) {
                }
            }
            $s .= '<tr><td>';
            if ($error) {
                $s .= '<span title="' . htmlSpecialChars($error, ENT_IGNORE | ENT_QUOTES) . '">ERROR</span>';
            } elseif ($time !== NULL) {
                $s .= sprintf('%0.3f', $time * 1000);
            }
            if ($explain) {
                static $counter;
                $counter++;
                $s .= "<br /><a class='tracy-toggle tracy-collapsed' href='#nette-DbConnectionPanel-row-{$counter}'>explain</a>";
            }
            $s .= '</td><td class="nette-DbConnectionPanel-sql">' . Helpers::dumpSql($sql, $params, $connection);
            if ($explain) {
                $s .= "<table id='nette-DbConnectionPanel-row-{$counter}' class='tracy-collapsed'><tr>";
                foreach ($explain[0] as $col => $foo) {
                    $s .= '<th>' . htmlSpecialChars($col) . '</th>';
                }
                $s .= '</tr>';
                foreach ($explain as $row) {
                    $s .= '<tr>';
                    foreach ($row as $col) {
                        $s .= '<td>' . htmlSpecialChars($col) . '</td>';
                    }
                    $s .= '</tr>';
                }
                $s .= '</table>';
            }
            if ($source) {
                $s .= substr_replace(Tracy\Helpers::editorLink($source[0], $source[1]), ' class="nette-DbConnectionPanel-source"', 2, 0);
            }
            $s .= '</td><td>' . $rows . '</td></tr>';
        }
        return $this->count ? '<style class="tracy-debug"> #tracy-debug td.nette-DbConnectionPanel-sql { background: white !important }
			#tracy-debug .nette-DbConnectionPanel-source { color: #BBB !important } </style>
			<h1 title="' . htmlSpecialChars($connection->getDsn()) . '">Queries: ' . $this->count . ($this->totalTime ? sprintf(', time: %0.3f ms', $this->totalTime * 1000) : '') . ', ' . htmlSpecialChars($this->name) . '</h1>
			<div class="tracy-inner nette-DbConnectionPanel">
			<table>
				<tr><th>Time&nbsp;ms</th><th>SQL Query</th><th>Rows</th></tr>' . $s . '
			</table>' . (count($this->queries) < $this->count ? '<p>...and more</p>' : '') . '</div>' : '';
    }
Exemple #15
0
 public static function getEditorLink($source)
 {
     $link = null;
     if ($source !== null) {
         $file = $source[0];
         $line = $source[1];
         $link = Helpers::editorLink($file, $line);
         // $link = self::updateEditorUri($link);
     }
     return $link;
 }
Exemple #16
0
 /**
  * Renders SQL query string to Nette debug bluescreen when available.
  * @param NeevoException $e
  * @return array
  */
 public function renderException($e)
 {
     if (!($e instanceof NeevoException && $e->getSql())) {
         return;
     }
     list($file, $line) = $this->failedQuerySource;
     return array('tab' => 'SQL', 'panel' => Manager::highlightSql($e->getSql()) . '<p><b>File:</b> ' . Helpers::editorLink($file, $line) . " &nbsp; <b>Line:</b> {$line}</p>" . ($line ? BlueScreen::highlightFile($file, $line) : '') . 'Neevo v' . Manager::VERSION);
 }
Exemple #17
0
 /**
  * Handler to catch warnings and notices.
  * @return bool   FALSE to call normal error handler, NULL otherwise
  * @throws ErrorException
  * @internal
  */
 public static function errorHandler($severity, $message, $file, $line, $context)
 {
     if (self::$scream) {
         error_reporting(E_ALL);
     }
     if ($severity === E_RECOVERABLE_ERROR || $severity === E_USER_ERROR) {
         if (Helpers::findTrace(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS), '*::__toString')) {
             $previous = isset($context['e']) && $context['e'] instanceof \Exception ? $context['e'] : NULL;
             $e = new ErrorException($message, 0, $severity, $file, $line, $previous);
             $e->context = $context;
             self::exceptionHandler($e);
         }
         $e = new ErrorException($message, 0, $severity, $file, $line);
         $e->context = $context;
         throw $e;
     } elseif (($severity & error_reporting()) !== $severity) {
         return FALSE;
         // calls normal error handler to fill-in error_get_last()
     } elseif (self::$productionMode && ($severity & self::$logSeverity) === $severity) {
         $e = new ErrorException($message, 0, $severity, $file, $line);
         $e->context = $context;
         try {
             self::log($e, self::ERROR);
         } catch (\Exception $foo) {
         }
         return NULL;
     } elseif (!self::$productionMode && !isset($_GET['_tracy_skip_error']) && (is_bool(self::$strictMode) ? self::$strictMode : (self::$strictMode & $severity) === $severity)) {
         $e = new ErrorException($message, 0, $severity, $file, $line);
         $e->context = $context;
         $e->skippable = TRUE;
         self::exceptionHandler($e);
     }
     $message = 'PHP ' . Helpers::errorTypeToString($severity) . ": {$message}";
     $count =& self::getBar()->getPanel('Tracy:errors')->data["{$file}|{$line}|{$message}"];
     if ($count++) {
         // repeated error
         return NULL;
     } elseif (self::$productionMode) {
         try {
             self::log("{$message} in {$file}:{$line}", self::ERROR);
         } catch (\Exception $foo) {
         }
         return NULL;
     } else {
         self::fireLog(new ErrorException($message, 0, $severity, $file, $line));
         return self::isHtmlMode() ? NULL : FALSE;
         // FALSE calls normal error handler
     }
 }
Exemple #18
0
 /**
  * Dump implementation for JSON.
  * @param  mixed  variable to dump
  * @param  int    current recursion level
  * @return string
  */
 private function jsonDump(&$var, $level = 0)
 {
     if (is_bool($var) || is_null($var) || is_int($var) || is_float($var)) {
         return $var;
     } elseif (is_string($var)) {
         return Dumper::encodeString($var, $this->maxLength);
     } elseif (is_array($var)) {
         static $marker;
         if ($marker === NULL) {
             $marker = uniqid("", TRUE);
         }
         if (isset($var[$marker])) {
             return "…RECURSION…";
         } elseif ($level < $this->maxDepth || !$this->maxDepth) {
             $var[$marker] = TRUE;
             $res = [];
             foreach ($var as $k => &$v) {
                 if ($k !== $marker) {
                     $res[$this->jsonDump($k)] = $this->jsonDump($v, $level + 1);
                 }
             }
             unset($var[$marker]);
             return $res;
         } else {
             return " … ";
         }
     } elseif (is_object($var)) {
         $arr = (array) $var;
         static $list = [];
         if (in_array($var, $list, TRUE)) {
             return "…RECURSION…";
         } elseif ($level < $this->maxDepth || !$this->maxDepth) {
             $list[] = $var;
             $res = ["" => '(object) ' . Helpers::getClass($var)];
             foreach ($arr as $k => &$v) {
                 if (isset($k[0]) && $k[0] === "") {
                     $k = substr($k, strrpos($k, "") + 1);
                 }
                 $res[$this->jsonDump($k)] = $this->jsonDump($v, $level + 1);
             }
             array_pop($list);
             return $res;
         } else {
             return " … ";
         }
     } elseif (is_resource($var)) {
         return 'resource ' . get_resource_type($var);
     } else {
         return 'unknown type';
     }
 }
Exemple #19
0
 /**
  * Returns link to editor.
  * @author David Grudl
  * @return Nette\Utils\Html|string
  */
 private static function editorLink($file, $line, $text = NULL)
 {
     if (Debugger::$editor && is_file($file) && $text !== NULL) {
         return Nette\Utils\Html::el('a')->href(strtr(Debugger::$editor, array('%file' => rawurlencode($file), '%line' => $line)))->title("{$file}:{$line}")->setHtml($text);
     } else {
         return Helpers::editorLink($file, $line);
     }
 }
Exemple #20
0
 /**
  * Simple trace info
  *
  * @param array $stack
  * @return string
  */
 public static function showTraceSimple($stack)
 {
     $maxDepth = Debugger::$maxDepth;
     Debugger::$maxDepth = 1;
     $counter = 0;
     ob_start();
     foreach ($stack as $row) {
         try {
             $r = isset($row['class']) ? new \ReflectionMethod($row['class'], $row['function']) : new \ReflectionFunction($row['function']);
             $params = $r->getParameters();
         } catch (\Exception $e) {
             $params = array();
         }
         $args = array();
         if (array_key_exists('args', $row)) {
             $argList = new \ArrayIterator($row['args']);
             while ($argList->valid()) {
                 $key = $argList->key();
                 $args[] = !isset($params[$key]) ?: '$' . $params[$key]->name;
                 $argList->next();
             }
         }
         echo ++$counter . '. <b>' . (isset($row['class']) ? htmlspecialchars($row['class'] . $row['type']) : '') . htmlspecialchars($row['function']) . '(' . implode(', ', $args) . ');</b> ' . '<br>' . (isset($row['file']) && is_file($row['file']) ? Helpers::editorLink($row['file'], $row['line']) : '<i>inner-code</i>' . isset($row['line']) ?: $row['line']) . '<br>';
         if ($counter == self::$traceMode) {
             break;
         }
     }
     Debugger::$maxDepth = $maxDepth;
     return ob_get_clean();
 }
 private function renderListeners($ids)
 {
     static $addIcon;
     if (empty($addIcon)) {
         $addIcon = '<img width="18" height="18" src="data:image/png;base64,' . base64_encode(file_get_contents(__DIR__ . '/add.png')) . '" title="Listener" />';
     }
     $registeredClasses = $this->getClassMap();
     $h = 'htmlspecialchars';
     $shortFilename = function (Nette\Reflection\GlobalFunction $refl) {
         $title = '.../' . basename($refl->getFileName()) . ':' . $refl->getStartLine();
         if ($editor = Tracy\Helpers::editorUri($refl->getFileName(), $refl->getStartLine())) {
             return sprintf(' defined at <a href="%s">%s</a>', htmlspecialchars($editor), $title);
         }
         return ' defined at ' . $title;
     };
     $s = '';
     foreach ($ids as $id) {
         if (is_callable($id)) {
             $s .= '<tr><td width=18>' . $addIcon . '</td><td><pre class="nette-dump"><span class="nette-dump-object">' . Callback::toString($id) . ($id instanceof \Closure ? $shortFilename(Callback::toReflection($id)) : '') . '</span></span></th></tr>';
             continue;
         }
         if (!$this->sl->isCreated($id) && ($class = array_search($id, $registeredClasses, TRUE))) {
             $s .= '<tr><td width=18>' . $addIcon . '</td><td><pre class="nette-dump"><span class="nette-dump-object">' . $h(Nette\Reflection\ClassType::from($class)->getName()) . '</span></span></th></tr>';
         } else {
             try {
                 $s .= '<tr><td width=18>' . $addIcon . '</td><td>' . self::dumpToHtml($this->sl->getService($id)) . '</th></tr>';
             } catch (\Exception $e) {
                 $s .= "<tr><td colspan=2>Service {$id} cannot be loaded because of exception<br><br>\n" . (string) $e . '</td></th>';
             }
         }
     }
     return $s;
 }
Exemple #22
0
 /**
  * @return string
  */
 protected function formatLogLine($message, $exceptionFile = NULL)
 {
     return implode(' ', array(@date('[Y-m-d H-i-s]'), preg_replace('#\\s*\\r?\\n\\s*#', ' ', $this->formatMessage($message)), ' @  ' . Helpers::getSource(), $exceptionFile ? ' @@  ' . basename($exceptionFile) : NULL));
 }
Exemple #23
0
	/**
	 * Dump implementation for JSON.
	 * @param  mixed  variable to dump
	 * @param  int    current recursion level
	 * @return string
	 */
	private static function jsonDump(& $var, $level = 0)
	{
		if (is_bool($var) || is_null($var) || is_int($var) || is_float($var)) {
			return $var;

		} elseif (is_string($var)) {
			if (Debugger::$maxLen && strlen($var) > Debugger::$maxLen) {
				$var = substr($var, 0, Debugger::$maxLen) . " \xE2\x80\xA6 ";
			}
			return Helpers::fixEncoding($var);

		} elseif (is_array($var)) {
			static $marker;
			if ($marker === NULL) {
				$marker = uniqid("\x00", TRUE);
			}
			if (isset($var[$marker])) {
				return "\xE2\x80\xA6RECURSION\xE2\x80\xA6";

			} elseif ($level < Debugger::$maxDepth || !Debugger::$maxDepth) {
				$var[$marker] = TRUE;
				$res = array();
				foreach ($var as $k => & $v) {
					if ($k !== $marker) {
						$res[self::jsonDump($k)] = self::jsonDump($v, $level + 1);
					}
				}
				unset($var[$marker]);
				return $res;

			} else {
				return " \xE2\x80\xA6 ";
			}

		} elseif (is_object($var)) {
			$arr = (array) $var;
			static $list = array();
			if (in_array($var, $list, TRUE)) {
				return "\xE2\x80\xA6RECURSION\xE2\x80\xA6";

			} elseif ($level < Debugger::$maxDepth || !Debugger::$maxDepth) {
				$list[] = $var;
				$res = array("\x00" => '(object) ' . Helpers::getClass($var));
				foreach ($arr as $k => & $v) {
					if ($k[0] === "\x00") {
						$k = substr($k, strrpos($k, "\x00") + 1);
					}
					$res[self::jsonDump($k)] = self::jsonDump($v, $level + 1);
				}
				array_pop($list);
				return $res;

			} else {
				return " \xE2\x80\xA6 ";
			}

		} elseif (is_resource($var)) {
			return 'resource ' . get_resource_type($var);

		} else {
			return 'unknown type';
		}
	}
Exemple #24
0
 /**
  * Default mailer.
  * @param  string
  * @param  string
  * @return void
  * @internal
  */
 public function defaultMailer($message, $email)
 {
     $host = preg_replace('#[^\\w.-]+#', '', isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : php_uname('n'));
     $parts = str_replace(array("\r\n", "\n"), array("\n", PHP_EOL), array('headers' => implode("\n", array("From: noreply@{$host}", 'X-Mailer: Tracy', 'Content-Type: text/plain; charset=UTF-8', 'Content-Transfer-Encoding: 8bit')) . "\n", 'subject' => "PHP: An error occurred on the server {$host}", 'body' => $this->formatMessage($message) . "\n\nsource: " . Helpers::getSource()));
     mail($email, $parts['subject'], $parts['body'], $parts['headers']);
 }
Exemple #25
0
 /**
  * Handler to catch warnings and notices.
  * @param  int    level of the error raised
  * @param  string error message
  * @param  string file that the error was raised in
  * @param  int    line number the error was raised at
  * @param  array  an array of variables that existed in the scope the error was triggered in
  * @return bool   FALSE to call normal error handler, NULL otherwise
  * @throws ErrorException
  * @internal
  */
 public static function _errorHandler($severity, $message, $file, $line, $context)
 {
     if (self::$scream) {
         error_reporting(E_ALL | E_STRICT);
     }
     if ($severity === E_RECOVERABLE_ERROR || $severity === E_USER_ERROR) {
         if (Helpers::findTrace(debug_backtrace(PHP_VERSION_ID >= 50306 ? DEBUG_BACKTRACE_IGNORE_ARGS : FALSE), '*::__toString')) {
             $previous = isset($context['e']) && $context['e'] instanceof \Exception ? $context['e'] : NULL;
             $e = new ErrorException($message, 0, $severity, $file, $line, $previous);
             $e->context = $context;
             self::_exceptionHandler($e);
         }
         $e = new ErrorException($message, 0, $severity, $file, $line);
         $e->context = $context;
         throw $e;
     } elseif (($severity & error_reporting()) !== $severity) {
         return FALSE;
         // calls normal error handler to fill-in error_get_last()
     } elseif (self::$productionMode && ($severity & self::$logSeverity) === $severity) {
         $e = new ErrorException($message, 0, $severity, $file, $line);
         $e->context = $context;
         self::log($e, self::ERROR);
         return NULL;
     } elseif (!self::$productionMode && (is_bool(self::$strictMode) ? self::$strictMode : (self::$strictMode & $severity) === $severity)) {
         $e = new ErrorException($message, 0, $severity, $file, $line);
         $e->context = $context;
         self::_exceptionHandler($e);
     }
     $message = 'PHP ' . (isset(self::$errorTypes[$severity]) ? self::$errorTypes[$severity] : 'Unknown error') . ": {$message}";
     $count =& self::getBar()->getPanel(__CLASS__ . ':errors')->data["{$file}|{$line}|{$message}"];
     if ($count++) {
         // repeated error
         return NULL;
     } elseif (self::$productionMode) {
         self::log("{$message} in {$file}:{$line}", self::ERROR);
         return NULL;
     } else {
         self::fireLog(new ErrorException($message, 0, $severity, $file, $line));
         return self::isHtmlMode() ? NULL : FALSE;
         // FALSE calls normal error handler
     }
 }
Exemple #26
0
 protected function getTitle($message, $priority)
 {
     if ($message instanceof \Exception) {
         return Tracy\Helpers::getClass($message);
     } else {
         return $priority;
     }
 }
Exemple #27
0
 /**
  * @return mixed
  */
 private static function toJson(&$var, $options, $level = 0)
 {
     if (is_bool($var) || is_null($var) || is_int($var)) {
         return $var;
     } elseif (is_float($var)) {
         return is_finite($var) ? strpos($tmp = json_encode($var), '.') ? $var : array('number' => "{$tmp}.0") : array('type' => (string) $var);
     } elseif (is_string($var)) {
         return self::encodeString($var, $options[self::TRUNCATE]);
     } elseif (is_array($var)) {
         static $marker;
         if ($marker === NULL) {
             $marker = uniqid("", TRUE);
         }
         if (isset($var[$marker]) || $level >= $options[self::DEPTH]) {
             return array(NULL);
         }
         $res = array();
         $var[$marker] = TRUE;
         foreach ($var as $k => &$v) {
             if ($k !== $marker) {
                 $k = preg_match('#^\\w{1,50}\\z#', $k) ? $k : '"' . self::encodeString($k, $options[self::TRUNCATE]) . '"';
                 $res[] = array($k, self::toJson($v, $options, $level + 1));
             }
         }
         unset($var[$marker]);
         return $res;
     } elseif (is_object($var)) {
         $obj =& self::$liveStorage[spl_object_hash($var)];
         if ($obj && $obj['level'] <= $level) {
             return array('object' => $obj['id']);
         }
         if ($options[self::LOCATION] & self::LOCATION_CLASS) {
             $rc = $var instanceof \Closure ? new \ReflectionFunction($var) : new \ReflectionClass($var);
             $editor = Helpers::editorUri($rc->getFileName(), $rc->getStartLine());
         }
         static $counter = 1;
         $obj = $obj ?: array('id' => self::$livePrefix . '0' . $counter++, 'name' => Helpers::getClass($var), 'editor' => empty($editor) ? NULL : array('file' => $rc->getFileName(), 'line' => $rc->getStartLine(), 'url' => $editor), 'level' => $level, 'object' => $var);
         if ($level < $options[self::DEPTH] || !$options[self::DEPTH]) {
             $obj['level'] = $level;
             $obj['items'] = array();
             foreach (self::exportObject($var, $options[self::OBJECT_EXPORTERS]) as $k => $v) {
                 $vis = 0;
                 if (isset($k[0]) && $k[0] === "") {
                     $vis = $k[1] === '*' ? 1 : 2;
                     $k = substr($k, strrpos($k, "") + 1);
                 }
                 $k = preg_match('#^\\w{1,50}\\z#', $k) ? $k : '"' . self::encodeString($k, $options[self::TRUNCATE]) . '"';
                 $obj['items'][] = array($k, self::toJson($v, $options, $level + 1), $vis);
             }
         }
         return array('object' => $obj['id']);
     } elseif (is_resource($var)) {
         $obj =& self::$liveStorage[(string) $var];
         if (!$obj) {
             $type = get_resource_type($var);
             $obj = array('id' => self::$livePrefix . (int) $var, 'name' => $type . ' resource');
             if (isset(self::$resources[$type])) {
                 foreach (call_user_func(self::$resources[$type], $var) as $k => $v) {
                     $obj['items'][] = array($k, self::toJson($v, $options, $level + 1));
                 }
             }
         }
         return array('resource' => $obj['id']);
     } else {
         return array('type' => 'unknown type');
     }
 }
Exemple #28
0
 /**
  * @param \Exception|\Throwable $e
  * @return string|NULL
  */
 private static function resolveExceptionTable($e)
 {
     if (!$e instanceof Doctrine\DBAL\DBALException) {
         return NULL;
     }
     if ($caused = Tracy\Helpers::findTrace($e->getTrace(), 'Doctrine\\DBAL\\DBALException::driverExceptionDuringQuery')) {
         if (preg_match('~(?:INSERT|UPDATE|REPLACE)(?:[A-Z_\\s]*)`?([^\\s`]+)`?\\s*~', is_string($caused['args'][1]) ? $caused['args'][1] : $caused['args'][2], $m)) {
             return $m[1];
         }
     }
     return NULL;
 }
Exemple #29
0
    /**
     * Returns HTML code for custom panel. (Tracy\IBarPanel)
     * @return mixed
     */
    public function getPanel()
    {
        $totalTime = $s = NULL;
        $h = 'htmlSpecialChars';
        foreach ($this->events as $event) {
            $totalTime += $event->time;
            $explain = NULL;
            // EXPLAIN is called here to work SELECT FOUND_ROWS()
            if ($this->explain && $event->type === Event::SELECT) {
                try {
                    $backup = [$event->connection->onEvent, \dibi::$numOfQueries, \dibi::$totalTime];
                    $event->connection->onEvent = NULL;
                    $cmd = is_string($this->explain) ? $this->explain : ($event->connection->getConfig('driver') === 'oracle' ? 'EXPLAIN PLAN FOR' : 'EXPLAIN');
                    $explain = Helpers::dump(@$event->connection->nativeQuery("{$cmd} {$event->sql}"), TRUE);
                } catch (Dibi\Exception $e) {
                }
                list($event->connection->onEvent, \dibi::$numOfQueries, \dibi::$totalTime) = $backup;
            }
            $s .= '<tr><td>' . sprintf('%0.3f', $event->time * 1000);
            if ($explain) {
                static $counter;
                $counter++;
                $s .= "<br /><a href='#tracy-debug-DibiProfiler-row-{$counter}' class='tracy-toggle tracy-collapsed' rel='#tracy-debug-DibiProfiler-row-{$counter}'>explain</a>";
            }
            $s .= '</td><td class="tracy-DibiProfiler-sql">' . Helpers::dump(strlen($event->sql) > self::$maxLength ? substr($event->sql, 0, self::$maxLength) . '...' : $event->sql, TRUE);
            if ($explain) {
                $s .= "<div id='tracy-debug-DibiProfiler-row-{$counter}' class='tracy-collapsed'>{$explain}</div>";
            }
            if ($event->source) {
                $s .= Tracy\Helpers::editorLink($event->source[0], $event->source[1]);
                //->class('tracy-DibiProfiler-source');
            }
            $s .= "</td><td>{$event->count}</td><td>{$h($event->connection->getConfig('driver') . '/' . $event->connection->getConfig('name'))}</td></tr>";
        }
        return empty($this->events) ? '' : '<style> #tracy-debug td.tracy-DibiProfiler-sql { background: white !important }
			#tracy-debug .tracy-DibiProfiler-source { color: #999 !important }
			#tracy-debug tracy-DibiProfiler tr table { margin: 8px 0; max-height: 150px; overflow:auto } </style>
			<h1>Queries: ' . count($this->events) . ($totalTime === NULL ? '' : sprintf(', time: %0.3f ms', $totalTime * 1000)) . '</h1>
			<div class="tracy-inner tracy-DibiProfiler">
			<table>
				<tr><th>Time&nbsp;ms</th><th>SQL Statement</th><th>Rows</th><th>Connection</th></tr>' . $s . '
			</table>
			</div>';
    }
 /**
  * editor link.
  *
  * @param string|array $source
  *
  * @return string
  */
 public static function editorLink($source)
 {
     $link = null;
     if (is_string($source) === true) {
         $file = $source;
         $line = null;
     } else {
         $file = $source[0];
         $line = $source[1];
     }
     $link = Helpers::editorLink($file, $line);
     // $link = self::updateEditorUri($link);
     return $link;
 }