Render debug information

@param  string  $source  The template source
@return string The rendered template source
358132
public function renderDebug($source)
    {
        $template = end($this->__stack);

        if($this->getObject('filter.path')->validate($template)) {
            $path = $this->locateSource($template);
        } else {
            $path = '';
        }

        //Render debug comments
        if($this->isDebug())
        {
            $type  = $this->getIdentifier()->getName();
            $path = str_replace(rtrim(\Kodekit::getInstance()->getRootPath(), '/').'/', '', $path);

            $format  = PHP_EOL.'<!--BEGIN '.$type.':render '.$path.' -->'.PHP_EOL;
            $format .= '%s';
            $format .= PHP_EOL.'<!--END '.$type.':render '.$path.' -->'.PHP_EOL;

            $source = sprintf($format, trim($source));
        }

        return $source;
    }
1257890
private function parseHTML($source)
    {
        $DOMDocument = new \DOMDocument();

        // Has inline script element
        if (preg_match_all('/<script((?:(?!src=).)*?)>(.*?)<\/script>/smix', $source, $matches)) {
            if (isset($matches[ 2 ])) {
                foreach ($matches[ 2 ] as $match) {
                    $script = trim($match);
                    $this->bodyScriptContent[ md5($script) ] = $script . PHP_EOL;
                }
            }
        }

        // Remove all inline script first
        $source = preg_replace('/<script((?:(?!src=).)*?)>(.*?)<\/script>/smix', '', $source);

        $DOMDocument->loadHTML($source);

        $DOMXPath = new \DOMXPath($DOMDocument);
        $metas = $DOMXPath->query('//meta');
        foreach ($metas as $meta) {
            $attributes = [];
            foreach ($meta->attributes as $name => $attribute) {
                $attributes[ $name ] = $attribute->nodeValue;
            }

            $this->metaNodes->createElement($attributes);
        }

        $source = preg_replace('#<meta(.*?)>#is', '', $source); // clean up all inline meta tags

        $links = $DOMXPath->query('//link'); // find all inline link tags
        foreach ($links as $link) {
            $attributes = [];
            foreach ($link->attributes as $name => $attribute) {
                $attributes[ $name ] = $attribute->nodeValue;
            }

            $this->linkNodes->createElement($attributes);
        }

        $source = preg_replace('#<link(.*?)>#is', '', $source); // clean up all inline meta tags

        $scripts = $DOMXPath->query('//head/script'); // find all inline script tags
        foreach ($scripts as $script) {
            $attributes = [];
            foreach ($script->attributes as $name => $attribute) {
                $attributes[ $name ] = $attribute->nodeValue;
            }
        }

        $scripts = $DOMXPath->query('//body/script'); // find all inline script tags
        foreach ($scripts as $script) {
            $attributes = [];
            foreach ($script->attributes as $name => $attribute) {
                $attributes[ $name ] = $attribute->nodeValue;
            }

            if ($script->textContent == '') {
                $this->bodyScriptNodes->createElement($attributes);
            }
        }

        $source = preg_replace('#<script(.*?)>(.*?)</script>#is', '', $source);

        // Has inline style Element
        if (preg_match_all('/((<[\\s\\/]*style\\b[^>]*>)([^>]*)(<\\/style>))/i', $source, $matches)) {
            if (isset($matches[ 3 ])) {
                foreach ($matches[ 3 ] as $match) {
                    $style = trim($match);
                    $this->styleContent[ md5($style) ] = $style . PHP_EOL;
                }
            }

            $source = preg_replace('#<style(.*?)>(.*?)</style>#is', '', $source);
        }

        $codes = $DOMXPath->query('//code');
        foreach ($codes as $code) {
            if ($code->textContent == '') {
                $code = str_replace(['{{php', '/php}}'], ['<?php', '?>'], $code->textContent);
                $code = preg_replace("/(^[\r\n]*|[\r\n]+)[\s\t]*[\r\n]+/", "\r\n", $code);
                $source = str_replace($code, htmlentities($code), $source);
            }
        }

        $source = preg_replace("/(^[\r\n]*|[\r\n]+)[\s\t]*[\r\n]+/", "\r\n", $source);

        return $source;
    }
25500
protected static function renderObjectDump($object, int $level, bool $renderProperties = true, bool $plaintext = false, bool $ansiColors = false): string
    {
        $dump = '';
        $scope = '';
        $additionalAttributes = '';

        if ($object instanceof \Doctrine\Common\Collections\Collection || $object instanceof \ArrayObject) {
            // The doctrine Debug utility usually returns a \stdClass object that we need to cast to array.
            return self::renderArrayDump((array)\Doctrine\Common\Util\Debug::export($object, 3), $level, $plaintext, $ansiColors);
        }

        // Objects returned from Doctrine's Debug::export function are stdClass with special properties:
        try {
            $objectIdentifier = ObjectAccess::getProperty($object, 'Persistence_Object_Identifier', true);
        } catch (\Neos\Utility\Exception\PropertyNotAccessibleException $exception) {
            $objectIdentifier = spl_object_hash($object);
        }
        $className = ($object instanceof \stdClass && isset($object->__CLASS__)) ? $object->__CLASS__ : get_class($object);
        if (isset(self::$renderedObjects[$objectIdentifier]) || preg_match(self::getIgnoredClassesRegex(), $className) !== 0) {
            $renderProperties = false;
        }
        self::$renderedObjects[$objectIdentifier] = true;

        if (self::$objectManager !== null) {
            $objectName = self::$objectManager->getObjectNameByClassName(get_class($object));
            if ($objectName !== false) {
                switch (self::$objectManager->getScope($objectName)) {
                    case Configuration::SCOPE_PROTOTYPE:
                        $scope = 'prototype';
                        break;
                    case Configuration::SCOPE_SINGLETON:
                        $scope = 'singleton';
                        break;
                    case Configuration::SCOPE_SESSION:
                        $scope = 'session';
                        break;
                }
            } else {
                $additionalAttributes .= ' debug-unregistered';
            }
        }

        if ($renderProperties === true && !$plaintext) {
            if ($scope === '') {
                $scope = 'prototype';
            }
            $scope .= '<a id="o' . $objectIdentifier . '"></a>';
        }

        if ($plaintext) {
            $dump .= $className;
            $dump .= ($scope !== '') ? ' ' . self::ansiEscapeWrap($scope, '44;37', $ansiColors) : '';
        } else {
            $dump .= '<span class="debug-object' . $additionalAttributes . '" title="' . $objectIdentifier . '">' . $className . '</span>';
            $dump .= ($scope !== '') ? '<span class="debug-scope">' . $scope . '</span>' : '';
        }

        if (property_exists($object, 'Persistence_Object_Identifier')) {
            $persistenceIdentifier = $objectIdentifier;
            $persistenceType = 'persistable';
        } elseif ($object instanceof \Closure) {
            $persistenceIdentifier = 'n/a';
            $persistenceType = 'closure';
        } else {
            $persistenceIdentifier = 'unknown';
            $persistenceType = 'object';
        }

        if ($plaintext) {
            $dump .= ' ' . self::ansiEscapeWrap($persistenceType, '42;37', $ansiColors);
        } else {
            $dump .= '<span class="debug-ptype" title="' . $persistenceIdentifier . '">' . $persistenceType . '</span>';
        }

        if ($object instanceof ProxyInterface || (property_exists($object, '__IS_PROXY__') && $object->__IS_PROXY__ === true)) {
            if ($plaintext) {
                $dump .= ' ' . self::ansiEscapeWrap('proxy', '41;37', $ansiColors);
            } else {
                $dump .= '<span class="debug-proxy" title="' . $className . '">proxy</span>';
            }
        }

        if ($renderProperties === true) {
            if ($object instanceof \SplObjectStorage) {
                $dump .= ' (' . (count($object) ?: 'empty') . ')';
                foreach ($object as $value) {
                    $dump .= chr(10);
                    $dump .= str_repeat(' ', $level);
                    $dump .= self::renderObjectDump($value, 0, false, $plaintext, $ansiColors);
                }
            } else {
                $objectReflection = new \ReflectionObject($object);
                $properties = $objectReflection->getProperties();
                foreach ($properties as $property) {
                    if (preg_match(self::$blacklistedPropertyNames, $property->getName())) {
                        continue;
                    }
                    $dump .= chr(10);
                    $dump .= str_repeat(' ', $level) . ($plaintext ? '' : '<span class="debug-property">') . self::ansiEscapeWrap($property->getName(), '36', $ansiColors) . ($plaintext ? '' : '</span>') . ' => ';
                    $property->setAccessible(true);
                    $value = $property->getValue($object);
                    if (is_array($value)) {
                        $dump .= self::renderDump($value, $level + 1, $plaintext, $ansiColors);
                    } elseif (is_object($value)) {
                        $dump .= self::renderObjectDump($value, $level + 1, true, $plaintext, $ansiColors);
                    } else {
                        $dump .= self::renderDump($value, $level, $plaintext, $ansiColors);
                    }
                }
            }
        } elseif (isset(self::$renderedObjects[$objectIdentifier])) {
            if (!$plaintext) {
                $dump = '<a href="#o' . $objectIdentifier . '" onclick="document.location.hash=\'#o' . $objectIdentifier . '\'; return false;" class="debug-seeabove" title="see above">' . $dump . '</a>';
            }
        }

        return $dump;
    }
77278
public function debugCanRender($object, string $context = null): string
    {
        $this->debugStr = "Testing renderer for directory '".$this->directory."'\n";
        if ($this->noDirectory) {
            return sprintf("Directory '%s' does not exists. Renderer disabled.\n", $this->directory);
        }

        $this->debugMode = true;
        $this->canRender($object, $context);

        $this->debugMode = false;

        return $this->debugStr;
    }
304722
public function render(Exception $e, $debug)
    {
        $e = FlattenException::create($e);
        $handler = new SymfonyExceptionHandler($debug);
        $status = $e->getStatusCode();

        $response = SymfonyResponse::create($handler->getHtml($e), $status, $e->getHeaders());

        $rex = explode("\n", $response);

        if (strstr(strtolower($rex[0]), 'http')) {
            for ($i = 0; $i < 2; $i++) {
                array_shift($rex);
            }
        }

        if (View::exists("errors.{$status}")) {
            echo View::renderView("errors.{$status}", 'exception', implode("\n", $rex));
        } else {
            echo implode("\n", $rex);
        }
    }
444715
protected function injectDebugBar($output)
    {
        if (!($debugBarConfig = Lb::app()->getConfigByName('debugbar'))) {
            return $output;
        }
        if (empty($debugBarConfig['enabled'])) {
            return $output;
        }
        if (empty($debugBarConfig['baseUrl'])) {
            return $output;
        }
        if (empty($debugBarConfig['basePath'])) {
            return $output;
        }

        /**
         * @var StandardDebugBar $debugBar
         */
        $debugBar = DebugBar::getInstance();
        $debugBarRenderer = $debugBar->getJavascriptRenderer($debugBarConfig['baseUrl'], $debugBarConfig['basePath']);
        $debugBarComponent = $debugBarRenderer->renderHead() . $debugBarRenderer->render();
        $replace = <<<EOF
{$debugBarComponent}
</body>
EOF;
        return str_replace('</body>', $replace, $output);
    }
660791
public function renderTrace($trace)
    {
        $output = '<div class="info">';
        $output .= '<h3>Trace</h3>';
        $output .= Backtrace::get_rendered_backtrace($trace);
        $output .= '</div>';

        return $output;
    }
641882
public function render($name, $source = null, $variable = null, $newLine = true)
    {
        $formatter = $this->getFormatter();
        $source = $source ?: 'src';
        $variable = $variable ?: 'script';

        return $formatter->renderClosure($formatter->renderLines([
            $formatter->renderAssignment(
                'var '.$variable,
                $formatter->renderCall(
                    $formatter->renderProperty('document', 'createElement'),
                    [$formatter->renderEscape('script')]
                ),
                true
            ),
            $formatter->renderAssignment(
                $formatter->renderProperty($variable, 'type'),
                $formatter->renderEscape('text/javascript'),
                true
            ),
            $formatter->renderAssignment(
                $formatter->renderProperty($variable, 'async'),
                $formatter->renderEscape(true),
                true
            ),
            $formatter->renderAssignment(
                $formatter->renderProperty($variable, 'src'),
                $source,
                true
            ),
            $formatter->renderCall(
                $formatter->renderProperty(
                    $formatter->renderCall(
                        $formatter->renderProperty('document', 'getElementsByTagName'),
                        [$formatter->renderEscape('head')]
                    ).'[0]',
                    'appendChild'
                ),
                [$variable],
                true
            ),
        ], true, false), [$source], $name, true, $newLine);
    }
780066
protected function debugHeaders(&$headers)
    {
        if (!$this->debug->getCfg('collect')) {
            return;
        }
        $eol = "\r\n";
        $strDebug = '';
        foreach ($headers as $k => $v) {
            if (in_array($k, array('Attachments', 'Body'))) {
                continue;
            }
            if (empty($v)) {
                continue;
            }
            $strDebug .= '<u>'.$k.'</u>: '.htmlspecialchars($v).$eol;
        }
        $strDebug .= $eol.htmlspecialchars(
            preg_replace('/(Content-Transfer-Encoding:\s+base64'.$eol.$eol.').+'.$eol.$eol.'/s', '$1removed for debug output'.$eol.$eol, $headers['Body'])
        );
        $this->debug->log(
            'Email:<br />'
            .'<pre style="margin-left:2em; padding:.25em; border:#999 solid 1px; background-color:#DDD; color:#000;">'
            .$strDebug
            .'</pre>'
        );
    }
941603
protected function render(Template $template)
    {
        $presenter = $this->createPresenter($template->getPresenter());

        try {
            $arguments = $this->getArguments($presenter, $template);
            $this->logger->debug($arguments);
            $result = call_user_func_array($presenter, $arguments);
        } catch(Exception $e) {
            if ($this->throwRenderExceptions) {
                throw $e;
            }

            $this->logger->error($e->getMessage() .
                    "\n\nURL: " . URLUtils::fullUrl() .
                    "\n\nTemplate:\n" . print_r($template, true) .
                    (isset($arguments) ? "\n\n$presenter args:\n" . print_r($arguments, true) : '')
                );

            $result = '';
        }

        return $result;
    }
42068
private function GenerateOutput($source) {
        array_push($this->Attributes, HtmlAttribute::Instanciate(HtmlAttributeConstants::Src, $source));
        $this->HtmlOutput = '<script type="application/javascript" {0}></script>';
        HtmlControlBuildHelper::Init()->GenerateAttributes($this);
    }
635394
public static function render()
    {
        $trace = static::$chronology;

        ob_start();
        include __DIR__ . '/Views/Debugger.php';
        $output = ob_get_contents();
        ob_end_clean();

        static::$chronology = [];

        echo $output;
    }
521561
public static function debugPrintln($message)
    {
        global $globals;
        
        if (isset($globals['DEBUG']) && $globals['DEBUG'] == true)
        {
            self::println($message);
        }
    }
589957
public function render()
    {
        if ($this->_enabled) {
            if (php_sapi_name() === 'cli') {
                echo 'FireBug: ' . $this->getLoadTime() . ' milliseconds' . "\n";
            } else {
                ob_start();
                include $this->_template;
                $debugPanel = ob_get_contents();
                ob_end_clean();

                return $debugPanel;
            }
        }
    }
522383
public function render($exception)
    {
        for ($level = ob_get_level(); $level > 0; $level--) {
            ob_end_clean();
        }

        if ($this->configure->debug) {
            if ($this->renderer->exists('@views/Errors/debug')) {
                return $this->renderer->render('@views/Errors/debug', ['exception' => $exception]);
            } else {
                return $this->renderer->render('@manaphp/Mvc/ErrorHandler/Views/debug', ['exception' => $exception]);
            }
        }

        $statusCode = $exception instanceof \ManaPHP\Exception ? $exception->getStatusCode() : 500;

        foreach (["@views/Errors/$statusCode",
                     '@views/Errors/error'] as $template) {
            if ($this->renderer->exists($template)) {
                return $this->renderer->render($template, ['statusCode' => $statusCode, 'exception' => $exception]);
            }
        }
        $status = $this->response->getStatus();
        return "<html lang='en'><title>$status</title><body>$status</body></html>";
    }
364044
protected static function parseTemplate($source)
    {
        $source =
            '<msg xmlns="http://www.erebot.net/xmlns/erebot/styling">'.
            $source.
            '</msg>';
        $schema = dirname(__DIR__) .
                    DIRECTORY_SEPARATOR . 'data' .
                    DIRECTORY_SEPARATOR . 'styling.rng';
        $dom    =   new \Erebot\DOM();
        $dom->substituteEntities    = true;
        $dom->resolveExternals      = false;
        $dom->recover               = true;
        $ue     = libxml_use_internal_errors(true);
        $dom->loadXML($source);
        $valid  = $dom->relaxNGValidate($schema);
        $errors = $dom->getErrors();
        libxml_use_internal_errors($ue);

        if (!$valid || count($errors)) {
            // Some unpredicted error occurred,
            // show some (hopefully) useful information.
            if (class_exists('\\Plop\\Plop')) {
                $logger = \Plop\Plop::getInstance();
                $logger->error(print_r($errors, true));
            }
            throw new \InvalidArgumentException(
                'Error while validating the message'
            );
        }
        return $dom;
    }
1041316
public function render(Model $model, $source)
    {
        if (null === $this->resolveModelSource($model, $source)) {
            return '';
        }

        return parent::render($model, $source);
    }