This class implements all functions necessary for highlighting, but it does not contain highlighting rules. Actual highlighting is done using a descendent of this class. One is not supposed to manually create descendent classes. Instead, describe highlighting rules in XML format and use {@link Text_Highlighter_Generator} to create descendent class. Alternatively, an instance of a descendent class can be created directly. Use {@link Text_Highlighter::factory()} to create an object for particular language highlighter Usage example require_once 'Text/Highlighter.php'; $hlSQL = Text_Highlighter::factory('SQL',array('numbers'=>true)); echo $hlSQL->highlight('SELECT * FROM table a WHERE id = 12');
Author: Andrey Demenev (demenev@gmail.com)
Exemple #1
0
 /**
  * Функция перенесена из функции addElementsForm() из-за возникающей ошибки:
  *     Cannot redeclare highlighter() (previously declared in 
  *     application\models\Form\Test\Testing.php:41) in 
  *     application\models\Form\Test\Testing.php on line 41
  * @param unknown_type $text
  * @param unknown_type $classExistsTH
  */
 private function _highlighter($text, $classExistsTH = false)
 {
     $text = str_replace('[js]', '[javascript]', $text);
     $text = str_replace('[/js]', '[/javascript]', $text);
     $text = str_replace(array('[code lang="js"]', '[code lang=\'js\']'), '[code lang="javascript"]', $text);
     $tags = '(?:php)|(?:sql)|(?:css)|(?:javascript)|(?:html)|(?:sh)';
     if ($classExistsTH) {
         $text .= '[code lang=""][/code]';
         // заменяет все теги на [code lang="langName"] и [/code]
         $text = preg_replace('/\\[(' . $tags . ')\\](.*?)\\[\\/(?:' . $tags . ')\\]/is', "[code lang='\$1']\$2[/code]", $text);
         //розбтвает строку и записывает в массив
         preg_match_all("/(.*?)\\[code lang=['\"](.*?)['\"]\\](.*?)\\[\\/code\\]/is", $text, $matches);
         $text = '';
         $count = count($matches[0]);
         for ($i = 0; $i < $count; $i++) {
             $text .= nl2br(htmlspecialchars($matches[1][$i]));
             if ($matches[2][$i]) {
                 $hl =& Text_Highlighter::factory($matches[2][$i]);
                 $text .= $hl->highlight($matches[3][$i]);
             }
         }
     } else {
         $text = htmlspecialchars($text);
         $text = preg_replace('/(\\[code lang=.*?\\])/is', '<pre>', $text);
         $text = str_replace(array('[php]', '[sql]', '[css]', '[js]', '[html]', '[bash]'), '<pre>', $text);
         $text = str_replace(array('[/php]', '[/sql]', '[/css]', '[/js]', '[/html]', '[/bash]', '[/code]'), '</pre>', $text);
         //$text = nl2br($text);
         $text = str_replace("\r\n", '<br/>', $text);
     }
     return $text;
 }
Exemple #2
0
 function conf__cuadro(toba_ei_cuadro $cuadro)
 {
     $info = toba::memoria()->get_dato_instancia('previsualizacion_consultas');
     if (!isset($info)) {
         throw new toba_error('No se encontró información de consultas ejecutadas');
     }
     $datos = $info['datos'];
     require_once '3ros/Text_Highlighter/Highlighter.php';
     $hlSQL = Text_Highlighter::factory('SQL');
     $i = 1;
     foreach (array_keys($datos) as $id) {
         $datos[$id]['numero'] = $i;
         $datos[$id]['id'] = $id;
         if (isset($datos[$id]['fin'])) {
             $datos[$id]['tiempo'] = $datos[$id]['fin'] - $datos[$id]['inicio'];
         } else {
             $datos[$id]['tiempo'] = 0;
         }
         $datos[$id]['sql'] = $hlSQL->highlight($datos[$id]['sql']);
         $i++;
     }
     if ($this->s__formateado) {
         $cuadro->set_formateo_columna('sql', 'pre');
     }
     $cuadro->set_formateo_columna('tiempo', 'tiempo_ms');
     $cuadro->set_datos($datos);
 }
Exemple #3
0
function highlightText($text)
{
    global $pathToIndex;
    set_include_path($pathToIndex . '/lib/php');
    require_once 'Text/Highlighter.php';
    require_once 'Text/Highlighter/Renderer/Html.php';
    $pattern = '/' . '(<pre class=")' . '(' . 'abap|cpp|css|diff|dtd|html|java|javascript|mysql|' . 'perl|php|python|ruby|sh|sql|vbscript|xml' . ')' . '(">)' . '([^<]+[^\\/]+)' . '(<\\/pre>)' . '/m';
    // Search matched pattern in $text
    preg_match_all($pattern, $text, $matches);
    for ($i = 0; $i < count($matches[0]); $i++) {
        // Check syntax style
        $syntaxStyle = strtoupper($matches[2][$i]);
        // Take "matches[4]", which is "([^<]+[^\/]+)" as a source code.
        // Decode HTML tags
        $sourceCode = htmlspecialchars_decode($matches[4][$i], ENT_QUOTES);
        // Remove "\n" in the first line.
        $sourceCode = preg_replace('(^\\n)', '', $sourceCode);
        $sourceCode = str_replace('&#92;', '\\', $sourceCode);
        // To keep compatible with Markdown
        // Create renderer
        $renderer = new Text_Highlighter_Renderer_Html(array("numbers" => HL_NUMBERS_TABLE, "tabsize" => 4));
        $hlHtml = Text_Highlighter::factory($syntaxStyle);
        $hlHtml->setRenderer($renderer);
        // Convert text to highligten code
        $replacement = $hlHtml->highlight($sourceCode);
        // Matched pattern
        $matchedText = $matches[1][$i] . $matches[2][$i] . $matches[3][$i] . $matches[4][$i] . $matches[5][$i];
        $text = str_replace($matchedText, $replacement, $text);
    }
    return $text;
}
Exemple #4
0
 /**
  * デバック用にリソースを表示
  *
  * <pre>
  * テンプレート付リソースの時、リソースの詳細情報が画面上に表示されます。
  * デバックモード時に_resourceクエリーを付加すれば有効になります。
  *
  * _resource=html リソーステンプレート適用されたHTML表示
  * _resource=body リソースのBodyをprinta形式で表示
  * </pre>
  *
  * @param BEAR_Ro $ro リソースオブジェクト
  *
  * @return string
  */
 public function getResourceToString(BEAR_Ro $ro)
 {
     self::$_hasResourceDebug = true;
     $config = $ro->getConfig();
     $chainLinks = $ro->getHeader('_linked');
     $resourceHtml = $ro->getHtml();
     if (!isset($_GET['_resource'])) {
         return $resourceHtml;
     }
     $body = $ro->getBody();
     if (isset($_GET['_resource'])) {
         if ($_GET['_resource'] === 'html') {
             $renderer = new Text_Highlighter_Renderer_Html(array('tabsize' => 4));
             $hlHtml = Text_Highlighter::factory("HTML");
             $hlHtml->setRenderer($renderer);
             if ($resourceHtml == '') {
                 $resourceHtml = '<span class="hl-all">(*Empty String)</span>';
             } else {
                 $resourceHtml = '<span class="hl-all">' . $hlHtml->highlight($resourceHtml) . '</span>';
             }
         } elseif ($_GET['_resource'] === 'body') {
             $resourceHtml = print_a($body, 'return:1');
             $logs = $ro->getHeader('_log');
             foreach ((array) $logs as $logKey => $logVal) {
                 $resourceHtml .= '<div class="bear-resource-info-label">' . $logKey . '</div>';
                 $resourceHtml .= is_scalar($logVal) ? $logVal : print_a($logVal, 'return:1');
             }
         }
     }
     //class editor
     if (class_exists($config['class'], false)) {
         $classEditorLink = $this->_getClassEditorLink($config['class'], $config['uri']);
     } else {
         $classEditorLink = $config['uri'];
     }
     $labelUri = "{$config['uri']}";
     $labelUri = $classEditorLink;
     $labelVaules = $config['values'] ? '?' . http_build_query($config['values']) : '';
     if ($chainLinks) {
         $linkLabels = array();
         foreach ($chainLinks as $links) {
             $linkLabels[] .= count($links) > 1 ? implode(':', $links) : $links[0];
         }
         $linkLabel .= '_link=' . implode(',', $linkLabels);
     }
     $result = '<div class="bear-resource-template">';
     $result .= '<div class="bear-resource-label">' . $labelUri;
     $result .= '<span class="bear-resource-values">' . $labelVaules . '</span>';
     $result .= '<span class="bear-resource-links">' . $linkLabel . '</span>';
     $result .= '' . " + (" . '';
     $result .= '<span><a border="0" title="' . $config['options']['template'] . '" href="/__panda/edit/?file=';
     $result .= _BEAR_APP_HOME . $this->_config['path'] . 'elements/' . $config['options']['template'] . '.tpl' . '">';
     $result .= $config['options']['template'] . '</a>)</span>';
     $result .= '</div>' . $resourceHtml . '</div>';
     return $result;
 }
Exemple #5
0
 public function do_block($page, $param1, $codeString)
 {
     require_once 'Text/Highlighter.php';
     $codeType = trim($param1) == '' ? 'php' : trim($param1);
     $textHighlighter =& Text_Highlighter::factory($codeType);
     if (PEAR::isError($textHighlighter)) {
         return '<pre>' . htmlspecialchars($codeString) . '</pre>';
     } else {
         return $textHighlighter->highlight($codeString);
     }
 }
Exemple #6
0
function codehere($atts)
{
    global $post, $codehereFooter;
    if (empty($atts)) {
        return;
    }
    if (isset($atts['file'])) {
        $fileName = $atts['file'];
    } else {
        $fileName = $atts[0];
    }
    $fileType = "html";
    if (isset($atts['lang'])) {
        $fileType = $atts['lang'];
    }
    $attachmentPath = '';
    // get the attachments
    $attachments = get_children(array('post_parent' => $post->ID, 'post_status' => 'inherit', 'post_type' => 'attachment', 'order' => 'ASC', 'orderby' => 'guid'));
    // pr($attachments);
    foreach ($attachments as $attachment) {
        $attBaseName = preg_replace('/_\\..+$/', '', basename($attachment->guid));
        if ($fileName == $attBaseName) {
            $downloadLink = $attachment->guid;
            $uploadDir = wp_upload_dir();
            list($prefix, $sufix) = explode('uploads', $attachment->guid);
            $attachmentPath = $uploadDir['basedir'] . $sufix;
            continue;
        }
    }
    if (!empty($attachmentPath) && file_exists($attachmentPath)) {
        // Only now, that we'll use it. Require the highlighter library.
        require_once "Highlighter.php";
        $codehereFooter = true;
        // get the attachment contents
        $file = file_get_contents($attachmentPath);
        $highlighter = Text_Highlighter::factory(strtoupper($fileType), array('numbers' => HL_NUMBERS_TABLE));
        $output = "<div class=\"codehere\">";
        $output .= "<p><a class=\"show-raw\" href=\"#\">view raw</a> | ";
        $output .= "<a href=\"{$downloadLink}\" target=\"_blank\">download {$fileName} &darr;</a></p>";
        $output .= "<div class=\"higlighted\">";
        $output .= $highlighter->highlight($file);
        $output .= "</div>";
        $output .= "<div class=\"raw\" style=\"display:none;\"><pre>";
        $output .= htmlspecialchars($file);
        $output .= "</pre></div>";
        $output .= "</div>";
        return $output;
    }
}
Exemple #7
0
 /**
  * call the function
  *
  * @access	public
  * @param	array	parameters of the function (= attributes of the tag)
  * @param	string	content of the tag
  * @return	string	content to insert into the template
  */
 function call($params, $content)
 {
     if (!(include_once 'Text/Highlighter.php')) {
         return false;
     }
     include_once 'Text/Highlighter/Renderer/Html.php';
     if (!isset($params['type'])) {
         return $content;
     }
     $type = $params['type'];
     unset($params['type']);
     if (isset($params['numbers']) && defined($params['numbers'])) {
         $params['numbers'] = constant($params['numbers']);
     }
     $renderer =& new Text_Highlighter_Renderer_HTML($params);
     $highlighter =& Text_Highlighter::factory($type);
     $highlighter->setRenderer($renderer);
     return $highlighter->highlight(trim($content));
 }
Exemple #8
0
 public static function output($text, $syntax = 'none')
 {
     if ($syntax == 'none') {
         return '<pre>' . $text . '</pre>';
     } else {
         // Since we may be coming from another syntax highlighter,
         // we'll try upcasing the syntax name and hope we get lucky.
         $syntax = strtoupper($syntax);
         $highlighter = Text_Highlighter::factory($syntax);
         if ($highlighter instanceof PEAR_Error) {
             throw new Horde_Exception_Wrapped($highlighter);
         }
         $renderer = new Text_Highlighter_Renderer_Html(array("numbers" => HL_NUMBERS_LI));
         if ($renderer instanceof PEAR_Error) {
             throw new Horde_Exception_Wrapped($renderer);
         }
         $highlighter->setRenderer($renderer);
         return $highlighter->highlight($text);
     }
 }
Exemple #9
0
 * http://pear.php.net/package/XML_Beautifier/
 * http://pear.php.net/package/Text_Highlighter/
 *
 * Alguna dependencia de pear se baja del mismo pear
 * http://pear.php.net/package/XML_Parser
 * */
require_once 'XML/Beautifier.php';
require_once 'Text/Highlighter.php';
$fmt = new XML_Beautifier();
$fmt->setOption("multilineTags", TRUE);
$paso = $fmt->formatString($texto);
if (substr($paso, 0, 10) != "XML_Parser") {
    $texto = $paso;
}
// XML correctamente formado
$hl =& Text_Highlighter::factory('XML', array('numbers' => HL_NUMBERS_TABLE));
echo "<div style='height:300px; overflow:auto';";
echo $hl->highlight($texto);
echo "</div>";
/////////////////////////////////////////////////////////////////////////////
libxml_use_internal_errors(true);
// Gracias a Salim Giacoman
$xml = new DOMDocument();
$ok = $xml->loadXML($texto);
if (!$ok) {
    display_xml_errors();
    die;
}
if (strpos($texto, "cfdi:Comprobante") !== FALSE) {
    $tipo = "cfdi";
} elseif (strpos($texto, "<Comprobante") !== FALSE) {
Exemple #10
0
 public function readLinesFromFile($path)
 {
     $lines = file_get_contents($path);
     $rendererOptions = $this->getRendererOptions();
     $renderer = new \Text_Highlighter_Renderer_Console($rendererOptions);
     $th = new \Text_Highlighter();
     $highlighter = $th->factory('php');
     $highlighter->setRenderer($renderer);
     $text = $highlighter->highlight($lines);
     return explode(PHP_EOL, $text);
 }
	/**
	 * Creates a highlighter instance.
	 * @param string $options the user-entered options
	 * @return Text_Highlighter the highlighter instance
	 */
	protected function createHighLighter($options)
	{
		if(!class_exists('Text_Highlighter', false))
		{
			require_once(Yii::getPathOfAlias('system.vendors.TextHighlighter.Text.Highlighter').'.php');
			require_once(Yii::getPathOfAlias('system.vendors.TextHighlighter.Text.Highlighter.Renderer.Html').'.php');
		}
		$lang = current(preg_split('/\s+/', substr(substr($options,1), 0,-1),2));
		$highlighter = Text_Highlighter::factory($lang);
		if($highlighter)
			$highlighter->setRenderer(new Text_Highlighter_Renderer_Html($this->getHighlightConfig($options)));
		return $highlighter;
	}
 /**
  * Highlights the content by the syntax of the specified language.
  * @param string $content the content to be highlighted.
  * @return string the highlighted content
  */
 public function highlight($content)
 {
     $this->registerClientScript();
     $options['use_language'] = true;
     $options['tabsize'] = $this->tabSize;
     if ($this->showLineNumbers) {
         $options['numbers'] = $this->lineNumberStyle === 'list' ? HL_NUMBERS_LI : HL_NUMBERS_TABLE;
     }
     $highlighter = empty($this->language) ? false : Text_Highlighter::factory($this->language);
     if ($highlighter === false) {
         $o = '<pre>' . CHtml::encode($content) . '</pre>';
     } else {
         $highlighter->setRenderer(new Text_Highlighter_Renderer_Html($options));
         $o = preg_replace('/<span\\s+[^>]*>(\\s*)<\\/span>/', '\\1', $highlighter->highlight($content));
     }
     return CHtml::tag('div', $this->containerOptions, $o);
 }
 public static function printLog()
 {
     global $modx;
     $base_tpl = 'dbtBase';
     $nav_tpl = 'dbtNavItem';
     $kv_tpl = 'dbtBasicItem';
     $timing_tpl = 'dbtTiming';
     $headers_tpl = 'dbtHeaders';
     $panel_tpl = 'dbtPanel';
     $queries_tpl = 'dbtSql';
     $sql_tpl = 'dbtSqlItem';
     $logitem_tpl = 'dbtLogItem';
     $log_tpl = 'dbtLog';
     $parser_tpl = 'dbtParser';
     $parseritem_tpl = 'dbtParserItem';
     $modx_totalTime = $modx->getMicroTime() - $modx->startTime;
     $modx_queryTime = $modx->queryTime;
     $modx_phpTime = $modx_totalTime - $modx_queryTime;
     $modx_totalTime = sprintf("%2.4f s", $modx_totalTime);
     $modx_queryTime = sprintf("%2.4f s", $modx_queryTime);
     $modx_phpTime = sprintf("%2.4f s", $modx_phpTime);
     $modx_source = $modx->resourceGenerated ? "database" : "cache";
     $timing_array = array();
     $timing = '';
     $timing_array['queries'] = $modx_queryTime;
     $timing_array['php'] = $modx_phpTime;
     $timing_array['total'] = $modx_totalTime;
     $timing_array['source'] = $modx_source;
     $timing_array['memory'] = memory_get_usage();
     $timing_array['memory_peak'] = memory_get_peak_usage();
     if (function_exists('getrusage')) {
         $cpu_data = getrusage();
         $timing_array['cpu_user'] = $cpu_data['ru_utime.tv_sec'] + $cpu_data['ru_utime.tv_usec'] / 1000000;
         $timing_array['cpu_system'] = $cpu_data['ru_stime.tv_sec'] + $cpu_data['ru_stime.tv_usec'] / 1000000;
     }
     $headers = '';
     $hi = 0;
     if (!function_exists('getallheaders')) {
         foreach ($_SERVER as $key => $value) {
             if (substr($key, 0, 5) == 'HTTP_') {
                 $headers .= $modx->getChunk($kv_tpl, array('idx' => $hi, 'key' => str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($key, 5))))), 'value' => $value));
                 $hi++;
             }
         }
     } else {
         foreach (getallheaders() as $key => $value) {
             $headers .= $modx->getChunk($kv_tpl, array('idx' => $hi, 'key' => $key, 'value' => $value));
             $hi++;
         }
     }
     $panels['headers'] = $modx->getChunk($headers_tpl, array('headers' => $headers));
     $queries = '';
     $qi = 0;
     $totalTime = 0;
     $highlighter = Text_Highlighter::factory('SQL');
     $highlighter->setRenderer(new Text_Highlighter_Renderer_Html(array('use_language' => true)));
     foreach (self::$log as $entry) {
         $totalTime += $entry['time'];
         $tProperties = array('idx' => $qi, 'sql' => preg_replace('/<span\\s+[^>]*>(\\s*)<\\/span>/', '\\1', $highlighter->highlight($entry['query'])), 'queryTime' => $entry['time'], 'queryCount' => self::$queryCount[md5($entry['query'])]);
         $queries .= $modx->getChunk($sql_tpl, $tProperties);
         $qi++;
     }
     $qProperties = array('queries' => $queries, 'totalQueries' => count(self::$log), 'totalTime' => $totalTime, 'uQueries' => count(self::$queryCount));
     $panels['queries'] = $modx->getChunk($queries_tpl, $qProperties);
     $timing_array['queries'] = $totalTime;
     $ti = 0;
     foreach ($timing_array as $key => $value) {
         $timing .= $modx->getChunk($kv_tpl, array('idx' => $ti, 'key' => $key, 'value' => $value));
         $ti++;
     }
     $panels['timing'] = $modx->getChunk($timing_tpl, array('timing' => $timing));
     $parser = '';
     $pi = 0;
     $totalCount = 0;
     foreach (self::$petCount as $id => $item) {
         $totalCount += $item['count'];
         $content = htmlentities($item['content']);
         $paProperties = array('id' => $id, 'idx' => $pi, 'content' => $highlighter->highlight($content), 'count' => $item['count']);
         $parser .= $modx->getChunk($parseritem_tpl, $paProperties);
         $pi++;
     }
     $petProperties = array('parseritems' => $parser, 'petCount' => $totalCount);
     $panels['parser'] = $modx->getChunk($parser_tpl, $petProperties);
     $logfile = MODX_CORE_PATH . 'cache/logs/debug.log';
     if (is_file($logfile)) {
         $logs = '';
         $li = 0;
         $lines = file($logfile);
         foreach ($lines as $line_num => $line) {
             $logs .= $modx->getChunk($logitem_tpl, array('idx' => $li, 'log' => $line));
             $li++;
         }
         file_put_contents(MODX_CORE_PATH . 'cache/logs/error.log', file_get_contents($logfile), FILE_APPEND);
         file_put_contents($logfile, '');
         $panels['logs'] = $modx->getChunk($log_tpl, array('logs' => $logs));
     }
     $nav = array();
     foreach ($panels as $title => $value) {
         $nav[] = array('title' => ucwords($title), 'subtitle' => '', 'url' => '', 'classname' => $title);
         $pProperties = array('title' => ucwords($title), 'content' => $value, 'id' => $title);
         $panels_output .= $modx->getChunk($panel_tpl, $pProperties);
     }
     foreach ($nav as $idx => $value) {
         $nav_output .= $modx->getChunk($nav_tpl, $value);
     }
     $output .= $modx->getChunk($base_tpl, array('panels' => $panels_output, 'nav' => $nav_output));
     return $output;
 }
Exemple #14
0
/**
 * print log file
 *
 * @param string $file
 */
function printFile($file, $type = "MYSQL")
{
    $hasClass = (include_once 'Text/Highlighter.php');
    if ($_GET['full']) {
        $content = file_get_contents($file);
    } else {
        $content = file_exists($file) ? file($file) : 'no file';
        if (is_array($content)) {
            $more = isset($_GET['more']) ? $_GET['more'] : 0;
            $content = array_slice($content, -100 * ($more + 1), 100);
            $content = (string) implode('', $content);
        }
    }
    if ($hasClass) {
        require_once "Text/Highlighter/Renderer/Html.php";
        if ($type) {
            $hlSQL =& Text_Highlighter::factory($type);
            $renderer = new Text_Highlighter_Renderer_Html(array("numbers" => HL_NUMBERS_LI, "tabsize" => 4));
            $hlSQL->setRenderer($renderer);
            $content = $hlSQL->highlight($content);
        } else {
            $content = "<pre>{$content}</pre>";
        }
        echo '<div style="font-size:small;">';
        echo $content;
        echo '</div>';
        print '<ul><li><a href=?file=' . $_GET['file'] . '&more=' . (int) ($more + 1) . '> 次の100件 (' . $more * 100 . '~' . ($more + 1) * 100 . ')</a></li><li><a href=?full=1&file=' . $_GET['file'] . '>全て表示</li></li><li><a href=?full>戻る</li></ul>';
    } else {
        print "<pre>{$content}</pre>";
        print '<ul><li><a href="?">戻る</li></ul>';
    }
}
Exemple #15
0
 /**
  * Highlighting source code of given file.
  *
  * Php code is using native php highlighter.
  * If PEAR Text_Highlighter is installed all defined files in $highlightMap
  * will be highlighted as well.
  *
  * @param String $file The filename / realpath to file
  *
  * @return String Html representation of parsed source code
  */
 protected function _highlightCode($file)
 {
     $highlightMap = array('.js' => 'JAVASCRIPT', '.html' => 'HTML', '.css' => 'CSS');
     $extension = strrchr($file, '.');
     $sourceCode = $this->_ioHelper->loadFile($file);
     if ('.php' === $extension) {
         return $this->_highlightPhpCode($sourceCode);
     } else {
         if (class_exists('Text_Highlighter', false) && isset($highlightMap[$extension])) {
             $renderer = new Text_Highlighter_Renderer_Html(array('numbers' => HL_NUMBERS_LI, 'tabsize' => 4, 'class_map' => array('comment' => 'comment', 'main' => 'code', 'table' => 'table', 'gutter' => 'gutter', 'brackets' => 'brackets', 'builtin' => 'keyword', 'code' => 'code', 'default' => 'default', 'identifier' => 'default', 'inlinedoc' => 'inlinedoc', 'inlinetags' => 'inlinetags', 'mlcomment' => 'mlcomment', 'number' => 'number', 'quotes' => 'string', 'reserved' => 'keyword', 'special' => 'special', 'string' => 'string', 'url' => 'url', 'var' => 'var')));
             $highlighter = Text_Highlighter::factory($highlightMap[$extension]);
             $highlighter->setRenderer($renderer);
             $doc = new DOMDocument();
             $doc->loadHTML($highlighter->highlight($sourceCode));
             return $doc;
         } else {
             $sourceCode = preg_replace('/.*/', '<li>$0</li>', htmlentities($sourceCode));
             $sourceCode = '<div class="code"><ol class="code">' . $sourceCode . '</ol></div>';
             $doc = new DOMDocument();
             $doc->loadHTML($sourceCode);
             return $doc;
         }
     }
 }
/**
 * render_include
 *
 * This is called automatically by the MediaWiki parser extension system.
 * This does the work of loading a file and returning the text content.
 * $argv is an associative array of arguments passed in the <include> tag as
 * attributes.
 *
 * @param mixed $input unused
 * @param mixed $argv associative array
 * @param mixed $parser unused
 * @access public
 * @return string
 */
function render_include($input, $argv, &$parser)
{
    global $inline_css, $highlighter_package;
    global $wg_include_allowed_parent_paths, $wg_include_disallowed_regex;
    $error_msg_prefix = "ERROR in " . basename(__FILE__);
    if (!isset($argv['src'])) {
        return $error_msg_prefix . ": <include> tag is missing 'src' attribute.";
    }
    // You can add this to restrict contents to a given path or DOCUMENT_ROOT:
    //    if (is_file(realpath($argv['src'])) && strlen(strstr(realpath($argv['src']), realpath($_SERVER['DOCUMENT_ROOT']))) <= 0)
    //        return $error_msg_prefix . ": src to local path is not under DOCUMENT_ROOT.";
    // Or you could use this to disallow local files altogether:
    //    if (is_file(realpath($argv['src'])))
    //        return $error_msg_prefix . ": Local files are not allowed.";
    // You can use similar tricks to restrict the src url.
    // iframe option...
    // Note that this does not check that the iframe src actually exists.
    // I also don't need to check against $wg_include_allowed_parent_paths or $wg_include_disallowed_regex
    // because the iframe content is loaded by the web browser and so security
    // is handled by whatever server is hosting the src file.
    if (isset($argv['iframe'])) {
        if (isset($argv['width'])) {
            $width = $argv['width'];
        } else {
            $width = '100%';
        }
        if (isset($argv['height'])) {
            $height = $argv['height'];
        } else {
            $height = '100%';
        }
        $output = '<iframe src="' . $argv['src'] . '" frameborder="1" scrolling="1" width="' . $width . '" height="' . $height . '">iframe</iframe>';
        return $output;
    }
    // cat file from SVN repository...
    if (isset($argv['svncat'])) {
        $cmd = "svn cat " . escapeshellarg($argv['src']);
        exec($cmd, $output, $return_var);
        // If plain 'svn cat' fails then try again using 'svn cat
        // --config-dir=/tmp'. Plain 'svn cat' worked fine for months
        // then just stopped.
        // Adding --config-dir=/tmp is a hack that fixed it, but
        // I only want to use it if necessary. I wish I knew what
        // the root cause was.
        if ($return_var != 0) {
            $cmd = "svn cat --config-dir=/tmp " . escapeshellarg($argv['src']);
            exec($cmd, $output, $return_var);
        }
        if ($return_var != 0) {
            return $error_msg_prefix . ": could not read the given src URL using 'svn cat'.\ncmd: {$cmd}\nreturn code: {$return_var}\noutput: " . join("\n", $output);
        }
        $output = join("\n", $output);
    } else {
        $src_path = realpath($argv['src']);
        if (!$src_path) {
            $src_path = $argv['src'];
        } else {
            if (!path_in_allowed_list($wg_include_allowed_parent_paths, $src_path)) {
                return $error_msg_prefix . ": src_path is not a child of any path in \$wg_include_allowed_parent_paths.";
            }
            if (path_in_regex_disallowed_list($wg_include_disallowed_regex, $src_path)) {
                return $error_msg_prefix . ": src_path matches a pattern in \$wg_include_disallowed_regex.";
            }
        }
        $output = file_get_contents($argv['src']);
        if ($output === False) {
            return $error_msg_prefix . ": could not read the given src URL.";
        }
    }
    // FIXME line numbers should be added after highlighting.
    if (isset($argv['linenums'])) {
        $output_a = split("\n", $output);
        for ($index = 0; $index < count($output_a); ++$index) {
            $output_a[$index] = sprintf("%04d", 1 + $index) . ":" . $output_a[$index];
        }
        $output = join("\n", $output_a);
    }
    if (isset($argv['highlight']) && $highlighter_package === True) {
        //        if ($highlighter_package === False)
        //        {
        //            return $error_msg_prefix . ": Text_Highlighter is not installed. You can't use 'highlight'.";
        //        }
        $hl =& Text_Highlighter::factory($argv['highlight']);
        $output = $hl->highlight($output);
        if (isset($argv['csshref'])) {
            $output = '<link rel="stylesheet" href="' . $argv['csshref'] . '" type="text/css" media="all" />' . "\n" . $output;
        } else {
            $output = $inline_css . $output;
        }
        return $output;
    }
    if (!isset($argv['noesc'])) {
        $output = htmlentities($output);
    }
    if (isset($argv['wikitext'])) {
        $parsedText = $parser->parse($output, $parser->mTitle, $parser->mOptions, false, false);
        $output = $parsedText->getText();
    } else {
        if (!isset($argv['nopre'])) {
            $output = "<pre>" . $output . "</pre>";
        }
    }
    return $output;
}
Exemple #17
0
function text_highlight($s, $lang)
{
    if ($lang === 'js') {
        $lang = 'javascript';
    }
    if ($lang === 'json') {
        $lang = 'javascript';
        if (!strpos(trim($s), "\n")) {
            $s = jindent($s);
        }
    }
    if (!strpos('Text_Highlighter', get_include_path())) {
        set_include_path(get_include_path() . PATH_SEPARATOR . 'library/Text_Highlighter');
    }
    require_once 'library/Text_Highlighter/Text/Highlighter.php';
    require_once 'library/Text_Highlighter/Text/Highlighter/Renderer/Html.php';
    $options = array('numbers' => HL_NUMBERS_LI, 'tabsize' => 4);
    $tag_added = false;
    $s = trim(html_entity_decode($s, ENT_COMPAT));
    $s = str_replace("    ", "\t", $s);
    // The highlighter library insists on an opening php tag for php code blocks. If
    // it isn't present, nothing is highlighted. So we're going to see if it's present.
    // If not, we'll add it, and then quietly remove it after we get the processed output back.
    if ($lang === 'php') {
        if (strpos('<?php', $s) !== 0) {
            $s = '<?php' . "\n" . $s;
            $tag_added = true;
        }
    }
    $renderer = new Text_Highlighter_Renderer_HTML($options);
    $hl = Text_Highlighter::factory($lang);
    $hl->setRenderer($renderer);
    $o = $hl->highlight($s);
    $o = str_replace(["    ", "\n"], ["&nbsp;&nbsp;&nbsp;&nbsp;", ''], $o);
    if ($tag_added) {
        $b = substr($o, 0, strpos($o, '<li>'));
        $e = substr($o, strpos($o, '</li>'));
        $o = $b . $e;
    }
    return '<code>' . $o . '</code>';
}
 /**
  * Processes a text string.
  * This method is required by the parent class.
  * @param string text string to be processed
  * @return string the processed text result
  */
 public function processText($text)
 {
     try {
         $highlighter = Text_Highlighter::factory($this->getLanguage());
     } catch (Exception $e) {
         $highlighter = false;
     }
     if ($highlighter === false) {
         return '<pre>' . htmlentities(trim($text)) . '</pre>';
     }
     $options["use_language"] = true;
     $options["tabsize"] = $this->getTabSize();
     if ($this->getShowLineNumbers()) {
         $options["numbers"] = self::$_lineNumberStyle[$this->getLineNumberStyle()];
     }
     $highlighter->setRenderer(new Text_Highlighter_Renderer_Html($options));
     return $highlighter->highlight(trim($text));
 }
}
// Add your ip restriction here
function isIpAllowed()
{
    return true;
}
// Transform path for regex
function regPath($path)
{
    return str_replace(array('/', '-'), array('\\/', '\\-'), $path);
}
// Build the array options for the HTML renderer to get the nice file numbering
$rendOptions = array('numbers' => $options['HTML_TABLE_view_source_numbers'], 'tabsize' => $options['HTML_TABLE_view_source_tabsize']);
// Finish parser object creation
$renderer = new Text_Highlighter_Renderer_Html($rendOptions);
$phpHighlighter = Text_Highlighter::factory('PHP');
$phpHighlighter->setRenderer($renderer);
// Now start output, header
$header = str_replace('<title>PEAR::PHP_Debug</title>', '<title>PEAR::PHP_Debug::View_Source::' . $_GET['file'] . '</title>', $options['HTML_TABLE_simple_header']);
echo $header;
echo '
    <link rel="stylesheet" type="text/css" media="screen" href="' . $view_source_options['CSS_ROOT'] . '/view_source.css" />
  </head>
  <body>
';
// Security check
if (isPathAllowed($_GET['file']) && isIpAllowed()) {
    if (file_exists($_GET['file'])) {
        echo '<div>
            <span class="hl-title">' . (get_magic_quotes_gpc() ? stripslashes($_GET['file']) : $_GET['file']) . '
            </span>
 function do_CoolCode($content, $post_id, $txt, $options)
 {
     $options = str_replace(array("\\\"", "\\\\'"), array("\"", "\\'"), $options);
     if (preg_match('/lang="(\\w*?)"/i', $options, $match)) {
         $lang = $match[1];
     } else {
         $lang = "";
     }
     if (preg_match('/linenum="(\\w*?)"/i', $options, $match)) {
         $linenum = $match[1];
     } else {
         $linenum = "on";
     }
     if (preg_match('/download="(.*?)"/i', $options, $match)) {
         $download = $match[1];
     } else {
         $download = "";
     }
     $txt = str_replace("\\\"", "\"", $txt);
     $txt = trim($txt);
     $txt = str_replace("\r\n", "\n", $txt);
     $txt = str_replace("\r", "\n", $txt);
     $blockID = $this->getBlockID($content);
     if ($download == "") {
         $this->blocks[$blockID] = '';
     } else {
         $this->blocks[$blockID] = '<div class="hl-title">&#19979;&#36733;: <a href="' . 'plugins/CoolCode/CoolCode.php?p=' . $post_id . '&amp;download=' . htmlspecialchars($download) . '">' . htmlspecialchars($download) . '</a></div>';
     }
     $hackphp = false;
     if (strtolower($lang) == 'php') {
         if (strpos($txt, '<' . '?') === false) {
             $txt = '<' . "?php\n" . $txt . "\n?" . '>';
             $hackphp = true;
         }
     }
     if (strtolower($linenum) == 'on' or strtolower($linenum) == 'open') {
         if (!in_array(strtolower($lang), $this->acceptable_lang)) {
             $this->blocks[$blockID] .= '<div class="hl-surround"><ol class="hl-main ln-show" ' . 'title="Double click to hide line number." ' . 'ondblclick = "linenumber(this)"><li class="hl-firstline">' . str_replace("\n", "</li>\n<li>", htmlspecialchars($txt)) . '</li></ol></div>';
             $this->blocks[$blockID] = str_replace("<li></li>", "<li>&nbsp;</li>", $this->blocks[$blockID]);
             $this->blocks[$blockID] = str_replace('<li> ', '<li>&nbsp;', $this->blocks[$blockID]);
         } else {
             $options = array('numbers' => HL_NUMBERS_LI);
             $hl =& Text_Highlighter::factory($lang, $options);
             $this->blocks[$blockID] .= '<div class="hl-surround">' . str_replace($this->hl_class, $this->hl_style, $hl->highlight($txt)) . '</div>';
             $this->blocks[$blockID] = preg_replace('/<span style=\\"[^\\"]*?\\"><\\/span>/', '', $this->blocks[$blockID]);
             $this->blocks[$blockID] = str_replace('<ol class="hl-main">', '<ol class="hl-main ln-show" title="Double click to hide line number." ondblclick = "linenumber(this)">', $this->blocks[$blockID]);
             $this->blocks[$blockID] = str_replace("\"> </span></li>", "\">&nbsp;</span></li>", $this->blocks[$blockID]);
             $this->blocks[$blockID] = preg_replace('/<li><span style=(.*?)> </si', '<li><span style=\\1>&nbsp;<', $this->blocks[$blockID]);
             if ($hackphp) {
                 $this->blocks[$blockID] = str_replace("<span style=\"color: Blue;\">&lt;?php</span></li>\n<li>", '', $this->blocks[$blockID]);
                 $this->blocks[$blockID] = str_replace('<li><span style="color: Blue;">?&gt;</span></li>', '', $this->blocks[$blockID]);
             }
         }
     } else {
         if (!in_array(strtolower($lang), $this->acceptable_lang)) {
             $this->blocks[$blockID] .= '<div class="hl-surround"><div class="hl-main">' . str_replace("\n", "<br />", htmlspecialchars($txt)) . '</div></div>';
         } else {
             $hl =& Text_Highlighter::factory($lang);
             $this->blocks[$blockID] .= '<div class="hl-surround">' . str_replace("\n", "<br />", str_replace("</pre>", "", str_replace("<pre>", "", str_replace($this->hl_class, $this->hl_style, $hl->highlight($txt))))) . '</div>';
             if ($hackphp) {
                 $this->blocks[$blockID] = str_replace('<span style="color: Blue;">&lt;?php</span><span style="color: Gray;"><br /></span>', '', $this->blocks[$blockID]);
                 $this->blocks[$blockID] = str_replace('<br /></span><span style="color: Blue;">?&gt;</span>', '</span>', $this->blocks[$blockID]);
             }
         }
         $this->blocks[$blockID] = str_replace('<br /> ', '<br />&nbsp;', $this->blocks[$blockID]);
     }
     // correct the indent
     $this->blocks[$blockID] = str_replace("  ", '&nbsp; ', $this->blocks[$blockID]);
     $this->blocks[$blockID] = str_replace("  ", ' &nbsp;', $this->blocks[$blockID]);
     return $blockID;
 }
Exemple #21
0
 /**
  *
  * Renders a token into text matching the requested format.
  *
  * @access public
  *
  * @param array $options The "options" portion of the token (second
  * element).
  *
  * @return string The text rendered from the token options.
  *
  */
 function token($options)
 {
     $text = $options['text'];
     $attr = $options['attr'];
     $type = strtolower($attr['type']);
     $css = $this->formatConf(' class="%s"', 'css');
     $css_code = $this->formatConf(' class="%s"', 'css_code');
     $css_php = $this->formatConf(' class="%s"', 'css_php');
     $css_html = $this->formatConf(' class="%s"', 'css_html');
     $css_filename = $this->formatConf(' class="%s"', 'css_filename');
     $text = trim($text);
     if ($type == 'php') {
         /*if (substr($text, 0, 5) != '<?php') {
                // PHP code example:
                // add the PHP tags
                $text = "<?php\n" . $text . "\n?>"; // <?php
          	}*/
         $highlighter = Text_Highlighter::factory('php');
         $text = $highlighter->highlight($text);
     } elseif ($type == 'cpp') {
         $highlighter = Text_Highlighter::factory('cpp');
         $text = $highlighter->highlight($text);
     } elseif ($type == 'css') {
         $highlighter = Text_Highlighter::factory('css');
         $text = $highlighter->highlight($text);
     } elseif ($type == 'html' || $type == 'xhtml') {
         $highlighter = Text_Highlighter::factory('html');
         $text = $highlighter->highlight($text);
     } elseif ($type == 'diff') {
         $highlighter = Text_Highlighter::factory('diff');
         $text = $highlighter->highlight($text);
     } elseif ($type == 'dtd') {
         $highlighter = Text_Highlighter::factory('dtd');
         $text = $highlighter->highlight($text);
     } elseif ($type == 'java') {
         $highlighter = Text_Highlighter::factory('java');
         $text = $highlighter->highlight($text);
     } elseif ($type == 'javascript') {
         $highlighter = Text_Highlighter::factory('javascript');
         $text = $highlighter->highlight($text);
     } elseif ($type == 'sql') {
         $highlighter = Text_Highlighter::factory('sql');
         $text = $highlighter->highlight($text);
     } elseif ($type == 'perl') {
         $highlighter = Text_Highlighter::factory('perl');
         $text = $highlighter->highlight($text);
     } elseif ($type == 'python') {
         $highlighter = Text_Highlighter::factory('python');
         $text = $highlighter->highlight($text);
     } elseif ($type == 'ruby') {
         $highlighter = Text_Highlighter::factory('ruby');
         $text = $highlighter->highlight($text);
     } elseif ($type == 'sql') {
         $highlighter = Text_Highlighter::factory('sql');
         $text = $highlighter->highlight($text);
     } elseif ($type == "xml") {
         $highlighter = Text_Highlighter::factory('xml');
         $text = $highlighter->highlight($text);
     } else {
         // generic code example:
         // convert tabs to four spaces,
         // convert entities.
         $text = str_replace("\t", "    ", $text);
         $text = htmlspecialchars($text);
         $text = "<pre{$css}><code{$css_code}>{$text}</code></pre>";
     }
     $text = "<div class=\"code\">" . $text . "</div>";
     if ($css_filename && isset($attr['filename'])) {
         $text = "<div{$css_filename}>" . $attr['filename'] . '</div>' . $text;
     }
     return "\n{$text}\n\n";
 }
Exemple #22
0
//Include Pear
require_once 'PEAR.php';
//Include Debug_Renderer_HTML_Table_Config to get the configuration
require_once 'Debug.php';
require_once 'Debug/Renderer/HTML_Table_Config.php';
//Include the class definition of highlighter
require_once 'Text/Highlighter.php';
require_once 'Text/Highlighter/Renderer/Html.php';
// Get View source configuration
$options = Debug_Renderer_HTML_Table_Config::singleton()->getConfig();
//Debug::dumpVar($options, '$options');
// Buil the array options for the HTML renderer to get the nice file numbering
$rendOptions = array('numbers' => $options['HTML_TABLE_view_source_numbers'], 'tabsize' => $options['HTML_TABLE_view_source_tabsize']);
// Finish parser object creation
$renderer = new Text_Highlighter_Renderer_Html($rendOptions);
$phpHighlighter = Text_Highlighter::factory("PHP");
$phpHighlighter->setRenderer($renderer);
// Now make output, header
$header = str_replace('<title>PEAR::PHP_Debug</title>', '<title>PEAR::PHP_Debug::View_Source::' . $_GET['file'] . '</title>', $options['HTML_TABLE_simple_header']);
print $header;
// Print style sheet
print $options['HTML_TABLE_view_source_stylesheet'];
// Output source
print '
  </head>
  <body>
    <div>
      <span class="hl-title">' . $_GET['file'] . '
      </span>
    </div>';
print $phpHighlighter->highlight(file_get_contents($_GET['file']));
Exemple #23
0
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" type="text/css" href="/__bear/code/page.css">

<?php 
require_once 'BEAR/vendors/debuglib.php';
require_once 'App.php';
spl_autoload_unregister(array('BEAR', 'onAutoload'));
require_once 'CodeSniff.php';
require_once "Text/Highlighter.php";
require_once "Text/Highlighter/Renderer/Html.php";
// init
if (isset($_GET['bear'])) {
    $file = _BEAR_BEAR_HOME . DIRECTORY_SEPARATOR . $_GET['bear'];
} else {
    $file = _BEAR_APP_HOME . DIRECTORY_SEPARATOR . $_GET['do'];
}
// Code Sniffer
BEAR_Dev_CodeSniff::process($file);
// Source listを表示
echo "<div class='info'>Source:{$file}<div>";
$renderer = new Text_Highlighter_Renderer_Html(array("numbers" => HL_NUMBERS_TABLE, "tabsize" => 4));
$hlHtml = Text_Highlighter::factory("PHP");
$hlHtml->setRenderer($renderer);
$fieStr = file_get_contents($file);
echo $hlHtml->highlight($fieStr);
?>


</body>
</html>
 /**
  * Creates a highlighter instance.
  * @param string $options the user-entered options
  * @return \Text_Highlighter the highlighter instance
  */
 protected function createHighLighter($options)
 {
     if (!class_exists('Text_Highlighter', false)) {
         require_once dirname(__DIR__) . '/data/yii-1.1/framework/vendors/TextHighlighter/Text/Highlighter.php';
         require_once dirname(__DIR__) . '/data/yii-1.1/framework/vendors/TextHighlighter/Text/Highlighter/Renderer/Html.php';
     }
     $lang = current(preg_split('/\\s+/', substr(substr($options, 1), 0, -1), 2));
     $highlighter = \Text_Highlighter::factory($lang);
     if ($highlighter) {
         $highlighter->setRenderer(new \Text_Highlighter_Renderer_Html($this->getHighlightConfig($options)));
     }
     return $highlighter;
 }