/**
  * The main method of the Plugin
  *
  * @param	string		$content: The PlugIn content
  * @param	array		$conf: The PlugIn configuration
  * @return	The content that is displayed on the website
  */
 function main($content, $config)
 {
     if (!t3lib_extMgm::isLoaded('geshilib')) {
         return "Geshi library not loaded";
     }
     // get content
     $this->pi_initPIflexForm();
     $config['content.']['lang'] = $this->pi_getFFvalue($this->cObj->data['pi_flexform'], 'cLang', 'sVIEW');
     $config['content.']['code'] = $this->pi_getFFvalue($this->cObj->data['pi_flexform'], 'cCode', 'sVIEW');
     $config['content.']['highlight'] = $this->pi_getFFvalue($this->cObj->data['pi_flexform'], 'cHighlight', 'sOPTIONS');
     $config['content.']['startnumber'] = $this->pi_getFFvalue($this->cObj->data['pi_flexform'], 'cStartnumber', 'sOPTIONS');
     // init geshi library
     $this->geshi = new GeSHi($config['content.']['code'], $config['content.']['lang']);
     // defaults
     $this->geshi->enable_line_numbers(GESHI_NORMAL_LINE_NUMBERS);
     // set highlighted lines
     if ($config['content.']['highlight'] !== '') {
         $this->geshi->highlight_lines_extra(split(',', $config['content.']['highlight']));
     }
     // set startnumber
     if (isset($config['content.']['startnumber'])) {
         $this->geshi->start_line_numbers_at($config['content.']['startnumber']);
     }
     // style
     if (isset($config['default.'])) {
         $this->_styleSubjects($config['default.']);
     }
     if (isset($config[$config['content.']['lang'] . '.'])) {
         $this->_styleSubjects($config[$config['content.']['lang'] . '.']);
     }
     // external stylesheets
     if (isset($config['global.']['external']) && $config['global.']['external'] == 0) {
         // do not use external style sheets
     } else {
         // mtness.net modification: I love stylesheets!
         $this->geshi->enable_classes();
         // Echo out the stylesheet for this code block And continue echoing the page
         $this->geshiCSS = '<style type="text/css"><!--' . $this->geshi->get_stylesheet() . '--></style>';
         // additional headerdata to include the styles
         $GLOBALS['TSFE']->additionalHeaderData['sema_sourcecode:' . $config['content.']['lang']] = $this->geshiCSS;
     }
     // xhtml compliance
     if (isset($config['global.']['xhtmlcompliant']) && $config['global.']['xhtmlcompliant'] == 1) {
         $this->geshi->force_xhtml_compliance = true;
     }
     // check for errors
     if ($this->geshi->error() !== false) {
         // log an error, this happens if the language file is missing or non-readable. Other input
         // specific errors can also occour, eg. if a non-existing container type is set for the engine.
         $GLOBALS['BE_USER']->simplelog($this->geshi->error(), $extKey = 'sema_sourcecode', 1);
     }
     // render
     return $this->pi_wrapInBaseClass($this->geshi->parse_code());
 }
Exemple #2
0
 /**
  * Нумерация строк
  *
  * @return Code
  */
 protected function setNum()
 {
     if (isset($this->attributes['num'])) {
         $this->geshi->enable_line_numbers(GESHI_FANCY_LINE_NUMBERS);
         if ('' !== $this->attributes['num']) {
             $num = (int) $this->attributes['num'];
             $this->geshi->start_line_numbers_at($num);
         }
     }
     return $this;
 }
 function onParseContentBlock($page, $name, $text, $shortcut)
 {
     $output = NULL;
     if (!empty($name) && !$shortcut) {
         list($language, $lineNumber, $class, $id) = $this->getHighlightInfo($name);
         if (!empty($language)) {
             $geshi = new GeSHi(trim($text), $language);
             $geshi->set_language_path($this->yellow->config->get("pluginDir") . "/highlight/");
             $geshi->set_header_type(GESHI_HEADER_PRE_TABLE);
             $geshi->set_overall_class($class);
             $geshi->set_overall_id($id);
             $geshi->enable_line_numbers($lineNumber ? GESHI_NORMAL_LINE_NUMBERS : GESHI_NO_LINE_NUMBERS);
             $geshi->start_line_numbers_at($lineNumber);
             $geshi->enable_classes(true);
             $geshi->enable_keyword_links(false);
             $output = $geshi->parse_code();
             $output = preg_replace("#<pre(.*?)>(.+?)</pre>#s", "<pre\$1><code>\$2</code></pre>", $output);
         }
     }
     return $output;
 }
Exemple #4
0
function pretty_file($file, $language, $startline = 0, $endline = 0, $number = false)
{
    if (!$file) {
        return false;
    }
    $s = read_file($file, $startline, $endline);
    if (!$s) {
        return false;
    }
    if (!$language) {
        return $s;
    }
    $output = false;
    switch ($language) {
        case 'plain':
            $s = preg_replace("/\\]\\=\\>\n(\\s+)/m", "] => ", $s);
            $s = htmlentities($s, ENT_COMPAT, 'UTF-8');
            $output = '<pre class="plain">' . PHP_EOL . $s . '</pre>' . PHP_EOL;
            break;
        default:
            $geshi = new GeSHi($s, $language);
            $geshi->enable_classes(true);
            $geshi->set_header_type(GESHI_HEADER_DIV);
            if ($number) {
                $geshi->enable_line_numbers(GESHI_NORMAL_LINE_NUMBERS);
                $geshi->start_line_numbers_at($startline > 0 ? $startline : 1);
            }
            $geshi->enable_keyword_links(false);
            $geshi->set_tab_width(4);
            //			echo '<pre>' . PHP_EOL .$geshi->get_stylesheet( ). '</pre>' . PHP_EOL;
            $output = $geshi->parse_code();
            if ($geshi->error()) {
                return false;
            }
    }
    return $output;
}
Exemple #5
0
function data_code($pData, $pParams)
{
    // Pre-Clyde Changes
    global $gBitSystem;
    extract($pParams, EXTR_SKIP);
    if (!empty($colors) and $colors == 'php') {
        $source = 'php';
    }
    if (!empty($in)) {
        $source = $in;
    }
    $source = isset($source) ? strtolower($source) : $gBitSystem->getConfig('liberty_plugin_code_default_source', 'php');
    if (!empty($num) && !is_numeric($num)) {
        switch (strtoupper($num)) {
            case 'TRUE':
            case 'ON':
            case 'YES':
                $num = 1;
                break;
            default:
                $num = 0;
                break;
        }
    }
    $num = isset($num) ? $num : FALSE;
    // trim any trailing spaces
    $code = '';
    $lines = explode("\n", $pData);
    foreach ($lines as $line) {
        $code .= rtrim($line) . "\n";
    }
    $code = unHtmlEntities($code);
    // Trim any leading blank lines
    $code = preg_replace('/^[\\n\\r]+/', "", $code);
    // Trim any trailing blank lines
    if (file_exists(UTIL_PKG_PATH . 'geshi/geshi.php')) {
        $code = preg_replace('/[\\n\\r]+$/', "", $code);
    } else {
        $code = preg_replace('/[\\n\\r]+$/', "\n", $code);
    }
    if (file_exists(UTIL_PKG_PATH . 'geshi/geshi.php')) {
        // Include the GeSHi library
        include_once UTIL_PKG_PATH . 'geshi/geshi.php';
        $geshi = new GeSHi($code, $source, UTIL_PKG_PATH . 'geshi/geshi');
        if ($num) {
            // Line Numbering has been requested
            $geshi->enable_line_numbers(GESHI_FANCY_LINE_NUMBERS);
            if (is_numeric($num)) {
                $geshi->start_line_numbers_at($num);
            }
        }
        $code = deCodeHTML(htmlentities($geshi->parse_code()));
    } else {
        // Line Numbering has been requested
        if ($num) {
            $lines = explode("\n", $code);
            $code = '';
            //Line Number
            $i = is_numeric($num) ? $num : 1;
            foreach ($lines as $line) {
                if (strlen($line) > 1) {
                    $code .= sprintf("%3d", $i) . ": " . $line . "\n";
                    $i++;
                }
            }
        }
        switch (strtoupper($source)) {
            case 'HTML':
                $code = highlight_string(deCodeHTML($code), TRUE);
                // Remove the first <code>" tags
                if (substr($code, 0, 6) == '<code>') {
                    $code = substr($code, 6, strlen($code) - 13);
                }
                break;
            case 'PHP':
                // Check it if code starts with PHP tags, if not: add 'em.
                if (!preg_match('/^[ 0-9:]*<\\?/i', $code)) {
                    // The require these tags to function
                    $code = "<?php\n" . $code . "?>";
                }
                $code = highlight_string($code, TRUE);
                // Replacement-map to replace Colors
                $convmap = array('#000000">' => '#004A4A">', '#006600">' => '#2020FF">', '#0000CC">' => '#209020">', '#FF9900">' => '#BB4040">', '#CC0000">' => '#903030">');
                // <-- # Assigned by HighLight_String / --> # Color to be Displayed
                // NOTE: The colors assigned by HighLight_String have changed with different versions of PHP - these are for PHP 4.3.4
                // Change the Colors
                $code = strtr($code, $convmap);
                break;
            default:
                $code = highlight_string($code, TRUE);
                break;
        }
        $code = "<pre>{$code}</pre>";
    }
    return (!empty($title) ? '<p class="codetitle">' . $title . '</p>' : "") . "<div class='codelisting'>" . $code . "</div>";
}
 protected function _geshify($matches)
 {
     if (!(is_array($matches) && count($matches) > 1)) {
         return '';
     }
     $codeblock = $matches[2];
     if (strlen(trim($codeblock))) {
         $params = $matches[1];
         $language = preg_match('/(?<=lang=")(.+?)(?=")/', $params, $matches);
         if ($language !== 0) {
             $language = $matches[0];
         } else {
             $language = \thebuggenie\core\framework\Settings::get('highlight_default_lang');
         }
         $numbering_startfrom = preg_match('/(?<=line start=")(.+?)(?=")/', $params, $matches);
         if ($numbering_startfrom !== 0) {
             $numbering_startfrom = (int) $matches[0];
         } else {
             $numbering_startfrom = 1;
         }
         $geshi = new \GeSHi($codeblock, $language);
         $highlighting = preg_match('/(?<=line=")(.+?)(?=")/', $params, $matches);
         if ($highlighting !== 0) {
             $highlighting = $matches[0];
         } else {
             $highlighting = false;
         }
         $interval = preg_match('/(?<=highlight=")(.+?)(?=")/', $params, $matches);
         if ($interval !== 0) {
             $interval = $matches[0];
         } else {
             $interval = \thebuggenie\core\framework\Settings::get('highlight_default_interval');
         }
         if ($highlighting === false) {
             switch (\thebuggenie\core\framework\Settings::get('highlight_default_numbering')) {
                 case 1:
                     // Line numbering with a highloght every n rows
                     $geshi->enable_line_numbers(GESHI_FANCY_LINE_NUMBERS, $interval);
                     $geshi->start_line_numbers_at($numbering_startfrom);
                     break;
                 case 2:
                     // Normal line numbering
                     $geshi->enable_line_numbers(GESHI_NORMAL_LINE_NUMBERS, 10);
                     $geshi->start_line_numbers_at($numbering_startfrom);
                     break;
                 case 3:
                     break;
                     // No numbering
             }
         } else {
             switch ($highlighting) {
                 case 'highlighted':
                 case 'GESHI_FANCY_LINE_NUMBERS':
                     // Line numbering with a highloght every n rows
                     $geshi->enable_line_numbers(GESHI_FANCY_LINE_NUMBERS, $interval);
                     $geshi->start_line_numbers_at($numbering_startfrom);
                     break;
                 case 'normal':
                 case 'GESHI_NORMAL_LINE_NUMBERS':
                     // Normal line numbering
                     $geshi->enable_line_numbers(GESHI_NORMAL_LINE_NUMBERS, 10);
                     $geshi->start_line_numbers_at($numbering_startfrom);
                     break;
                 case 3:
                     break;
                     // No numbering
             }
         }
         $codeblock = $geshi->parse_code();
         unset($geshi);
     }
     return '<code>' . $codeblock . '</code>';
 }
function plugin_geshi_highlight_code($source, $options)
{
    if (!class_exists('GeSHi')) {
        require PLUGIN_GESHI_LIB_DIR . 'geshi.php';
    }
    $geshi = new GeSHi($source, $options['language']);
    $geshi->set_encoding(CONTENT_CHARSET);
    if (PLUGIN_GESHI_USE_CSS) {
        $geshi->enable_classes();
    }
    if ($options['number']) {
        $geshi->enable_line_numbers(GESHI_NORMAL_LINE_NUMBERS);
        $geshi->start_line_numbers_at($options['start']);
        $geshi->set_overall_class('geshi number ' . $options['language']);
        plugin_geshi_read_setting($geshi, 'default');
        plugin_geshi_read_setting($geshi, $options['language']);
        $html = $geshi->parse_code();
        if ($geshi->header_type == GESHI_HEADER_PRE) {
            $before = array('<ol', '/ol>', '</div', '> ', '  ');
            $after = array('<code><object><ol style="margin-top: 0; margin-bottom: 0;"', '/ol></object></code>', "\n</div", '>&nbsp;', ' &nbsp;');
            $html = str_replace($before, $after, $html);
        }
    } else {
        $geshi->set_overall_class('geshi ' . $options['language']);
        plugin_geshi_read_setting($geshi, 'default');
        plugin_geshi_read_setting($geshi, $options['language']);
        $html = $geshi->parse_code();
        $html = str_replace("\n&nbsp;", "\n", $html);
    }
    return $html;
}
Exemple #8
0
function fox_code($atts, $thing)
{
    global $file_base_path, $thisfile, $fox_code_prefs;
    if (isset($fox_code_prefs)) {
        foreach (array('fileid', 'filename', 'language', 'lines', 'startline', 'overallclass', 'tabs', 'css', 'keywordslinks', 'encoding', 'fromline', 'toline') as $value) {
            ${$value} = $fox_code_prefs[$value];
        }
    } else {
        extract(lAtts(array('fileid' => '', 'filename' => '', 'language' => 'php', 'lines' => '1', 'startline' => '1', 'overallclass' => '', 'tabs' => '2', 'css' => '0', 'keywordslinks' => '0', 'encoding' => 'UTF-8', 'fromline' => '', 'toline' => ''), $atts));
    }
    if (!$thisfile) {
        if ($fileid) {
            $thisfile = fileDownloadFetchInfo('id = ' . intval($fileid));
        } else {
            if ($filename) {
                $thisfile = fileDownloadFetchInfo("filename = '" . $filename . "'");
            } else {
                $local_notfile = false;
            }
        }
    }
    if (!empty($thisfile)) {
        $filename = $thisfile['filename'];
        $fileid = $thisfile['id'];
        if (!empty($fromline) || !empty($toline)) {
            $handle = fopen($file_base_path . '/' . $filename, "r");
            $fromline = !empty($fromline) ? intval($fromline) : intval(1);
            $toline = !empty($toline) ? intval($toline) : intval(-1);
            $currentLine = 0;
            $code = "";
            while (!feof($handle)) {
                $currentLine++;
                if ($currentLine >= $fromline && ($toline < 0 || $currentLine <= $toline)) {
                    $code .= fgets($handle);
                } else {
                    fgets($handle);
                }
            }
            fclose($handle);
            $startline = $fromline;
        } else {
            $code = file_get_contents($file_base_path . '/' . $filename);
        }
    } else {
        if (strlen($fox_code_prefs['code']) > 0) {
            $code = $fox_code_prefs['code'];
        } else {
            $code = $thing;
        }
    }
    if (!$overallclass) {
        $overallclass = $language;
    }
    require_once 'geshi.php';
    $geshi = new GeSHi(trim($code, "\r\n"), $language);
    if ((bool) $css) {
        $geshi->enable_classes();
        $geshi->set_overall_class($overallclass);
    }
    $geshi->start_line_numbers_at($startline);
    $geshi->set_header_type(GESHI_HEADER_DIV);
    $geshi->set_encoding($encoding);
    $geshi->set_tab_width(intval($tabs));
    $geshi->enable_keyword_links((bool) $keywordslinks);
    $geshi->enable_line_numbers((bool) $lines);
    if (!isset($local_notfile)) {
        $thisfile = NULL;
    }
    return $geshi->parse_code();
}
Exemple #9
0
function plugin_geshi_highlight_code($source, $options)
{
    if (class_exists('GeSHi') === false) {
        require PLUGIN_GESHI_LIB_DIR . 'geshi.php';
    }
    $geshi = new GeSHi($source, $options['language']);
    $geshi->set_encoding(CONTENT_CHARSET);
    if (PLUGIN_GESHI_USE_CSS) {
        $geshi->enable_classes();
    }
    $class = 'geshi';
    if (version_compare(GESHI_VERSION, '1.0.8', '<')) {
        $class .= ' ' . $options['language'];
    }
    if ($options['number']) {
        $class .= ' number';
    }
    $geshi->set_overall_class($class);
    if ($options['number']) {
        $geshi->enable_line_numbers(GESHI_NORMAL_LINE_NUMBERS);
        $geshi->start_line_numbers_at($options['start']);
        plugin_geshi_read_setting($geshi, 'default');
        plugin_geshi_read_setting($geshi, $options['language']);
        switch ($geshi->header_type) {
            case GESHI_HEADER_PRE:
                $before = array('<ol', '/ol>', '</div', '> ', '  ');
                $after = array('<code><object><ol style="margin-top: 0; margin-bottom: 0;"', '/ol></object></code>', "\n</div", '>&nbsp;', ' &nbsp;');
                break;
            case GESHI_HEADER_PRE_TABLE:
                $before = array("&nbsp;\n");
                $after = array("\n");
                if (PLUGIN_GESHI_USE_CSS) {
                    $before[] = '"><td class="';
                    $after[] = '"><td class="de1 ';
                } else {
                    $before[] = '"><td';
                    $after[] = '"><td style="' . $geshi->code_style . '"';
                }
                break;
        }
    } else {
        plugin_geshi_read_setting($geshi, 'default');
        plugin_geshi_read_setting($geshi, $options['language']);
        $before = array("&nbsp;\n");
        $after = array("\n");
    }
    $html = $geshi->parse_code();
    if (isset($before) && isset($after)) {
        $html = str_replace($before, $after, $html);
    }
    return $html;
}
Exemple #10
0
 * @package    EasyCreator
 * @subpackage Views
 * @author     Nikolai Plath (elkuku)
 * @author     Created on 06-Oct-2008
 * @license    GNU/GPL, see JROOT/LICENSE.php
 */
//-- No direct access
defined('_JEXEC') || die('=;)');
jimport('geshi.geshi');
$snip = array();
for ($i = $this->startAtLine - 1; $i < $this->endAtLine; $i++) {
    $snip[] = $this->fileContents[$i];
}
//for
$snip = implode("\n", $snip);
//-- Code language for GeSHi
$lang = 'php';
//-- Alternating line colors
$background1 = '#fcfcfc';
$background2 = '#f0f0f0';
//-- Replace tag markers
$snip = str_replace('&lt;', '<', $snip);
$snip = str_replace('&gt;', '>', $snip);
//-- Replace TAB's with spaces
$snip = str_replace("\t", '   ', $snip);
$geshi = new GeSHi($snip, $lang);
$geshi->enable_line_numbers(GESHI_FANCY_LINE_NUMBERS, 2);
$geshi->set_line_style('background: ' . $background1 . ';', 'background: ' . $background2 . ';', true);
$geshi->start_line_numbers_at($this->startAtLine);
echo '<h3>' . substr($this->path, strlen(JPATH_ROOT) + 1) . '</h3>';
echo $geshi->parse_code();
Exemple #11
0
 /**
  * Function called by the pre_typography extension hook before the text will be parsed by EE
  * @param	string	$str	text that will be parsed
  * @param	object	$typo	Typography object
  * @param	array	$prefs	Preferences sent to $TYPE->parse_type
  * @return	string			text where the code has been stripped and code positions marked with an MD5-ID
  * @access	public
  * @global	$EXT			Extension-Object to support multiple calls to the same extension hook
  * @global	$OUT			could be used to display errors - it isn't at the moment
  * @todo					Display error using $OUT
  */
 function pre_typography($str, $typo, $prefs)
 {
     // we don't need the DB, nor IN, nor DSP
     // should probably use OUT to display user_error messages
     global $EXT, $OUT;
     // here we're doing the actual work
     if ($EXT->last_call !== FALSE) {
         // A different extension has run before us
         $str = $EXT->last_call;
     }
     $cache_dir = dirname(__FILE__) . '/' . $this->settings['cache_dir'];
     $rllen = strlen($this->rlimit);
     $pos = array();
     preg_match_all($this->llimit, $str, $matches, PREG_OFFSET_CAPTURE);
     foreach ($matches[0] as $key => $match) {
         $pos[$match[1]] = array();
         $pos[$match[1]]['match'] = $match[0];
         // lang (called type internally for historical reasons)
         if (!empty($matches[1][$key][0])) {
             // strip slashes for filesystem security and quotes because the value might be quoted
             $pos[$match[1]]['type'] = str_replace(array('/', '"', "'"), '', substr($matches[1][$key][0], 5));
         } else {
             $pos[$match[1]]['type'] = NULL;
         }
         // strict
         if (!empty($matches[2][$key][0])) {
             switch (str_replace(array('"', "'"), '', strtolower(substr($matches[2][$key][0], 7)))) {
                 case 'true':
                 case '1':
                     $pos[$match[1]]['strict'] = TRUE;
                     break;
                 case 'false':
                 case '0':
                     $pos[$match[1]]['strict'] = FALSE;
                     break;
                 default:
                     $pos[$match[1]]['strict'] = NULL;
                     break;
             }
         } else {
             $pos[$match[1]]['strict'] = NULL;
         }
         // line
         $pos[$match[1]]['line'] = !empty($matches[3][$key][0]) ? str_replace(array('"', "'"), '', substr($matches[3][$key][0], 5)) : NULL;
         // start
         $pos[$match[1]]['start'] = !empty($matches[4][$key][0]) ? str_replace(array('"', "'"), '', substr($matches[4][$key][0], 6)) : NULL;
         // keyword_links
         if (!empty($matches[5][$key][0])) {
             switch (str_replace(array("'", '"'), '', strtolower(substr($matches[5][$key][0], 14)))) {
                 case 'true':
                 case '1':
                     $pos[$match[1]]['keyword_links'] = TRUE;
                     break;
                 case 'false':
                 case '0':
                     $pos[$match[1]]['keyword_links'] = FALSE;
                     break;
                 default:
                     $pos[$match[1]]['keyword_links'] = NULL;
                     break;
             }
         } else {
             $pos[$match[1]]['keyword_links'] = NULL;
         }
         // overall_class
         $pos[$match[1]]['overall_class'] = !empty($matches[6][$key][0]) ? str_replace(array("'", '"'), '', substr($matches[6][$key][0], 14)) : NULL;
         // overall_id
         $pos[$match[1]]['overall_id'] = !empty($matches[7][$key][0]) ? str_replace(array("'", '"'), '', substr($matches[7][$key][0], 11)) : NULL;
     }
     // clean variables used in the loop
     unset($matches, $key, $match);
     // krsort the array so we can use substr stuff and won't mess future replacements
     krsort($pos);
     // Check for the cache dir
     if (file_exists($cache_dir) && is_dir($cache_dir)) {
         $cache_dir = realpath($cache_dir) . '/';
         if (!is_writable($cache_dir)) {
             // try to chmod it
             @chmod($cache_dir, 0777);
             if (!is_writable($cache_dir)) {
                 // still not writable? display a warning
                 print '<b>Warning</b>: Your <i>' . $this->name . '</i> cache directory <b>' . $cache_dir . '</b> is not writable! This will cause severe performance problems, so I suggest you chmod that dir.';
             }
         }
     } else {
         if (!mkdir($cache_dir, 0777)) {
             print '<b>Warning</b>: Your <i>' . $this->name . '</i> cache directory <b>' . $cache_dir . '</b> could not be created! This will cause severe performance problems, so I suggest you create and chmod that dir.';
         } else {
             // create an index.html so the contents will not be listed.
             @touch($cache_dir . 'index.html');
         }
     }
     if (mt_rand(0, 10) == 10) {
         // on every 10th visit do the garbage collection
         $cur = time();
         $d = dir($cache_dir);
         while (($f = $d->read()) !== FALSE) {
             if ($f != 'index.html' && $f[0] != '.') {
                 if ($cur - filemtime($cache_dir . $f) > $this->settings['cache_cutoff']) {
                     // File is older than cutoff, delete it.
                     @unlink($cache_dir . $f);
                 }
             }
         }
     }
     // loop through the code snippets
     $i = 0;
     foreach ($pos as $code_pos => $match) {
         $error = FALSE;
         if (($code_end_pos = strpos($str, $this->rlimit, (int) $code_pos + strlen($match['match']))) !== FALSE) {
             // we have a matching end tag.
             // make sure cache is regenerated when changing options, too!
             $md5 = md5(($not_geshified = substr($str, $code_pos + strlen($match['match']), $code_end_pos - $code_pos - strlen($match['match']))) . print_r($match, TRUE) . print_r($this->settings, TRUE));
             // check whether we already have this in a cache file
             if (is_file($cache_dir . $md5) && is_readable($cache_dir . $md5)) {
                 if (is_callable('file_get_contents')) {
                     $geshified = file_get_contents($cache_dir . $md5);
                     // this is for the garbage collection
                     touch($cache_dir . $md5);
                 } else {
                     // screw PHP4!
                     $f = fopen($cache_dir . $md5, 'r');
                     $geshified = fread($f, filesize($cache_dir . $md5));
                     fclose($f);
                     touch($cache_dir . $md5);
                 }
             } else {
                 // no cache so do the GeSHi thing
                 if ($this->settings['geshi_version'] == '1.1') {
                     // use GeSHi 1.1
                     include_once dirname(__FILE__) . '/geshi-1.1/class.geshi.php';
                     // highlight code according to type setting, default to setting
                     $geshi = new GeSHi($not_geshified, $match['type'] !== NULL ? $match['type'] : $this->settings['default_type']);
                     $str_error = $geshi->error();
                     if (empty($str_error)) {
                         // neither line numbers, nor strict mode is supported in GeSHi 1.1 yet.
                         // in fact it does pretty much nothing
                         // there used to be a rather large block of code here, testing wether methods were callable and call them if
                         // that's the case.
                         // parse the code
                         $geshified = $geshi->parseCode();
                     } else {
                         $error = TRUE;
                     }
                 } else {
                     // use GeSHi 1.0
                     include_once dirname(__FILE__) . '/geshi-1.0/geshi.php';
                     // highlight code according to type setting, default to php
                     $geshi = new GeSHi($not_geshified, $match['type'] !== NULL ? $match['type'] : $this->settings['default_type']);
                     $str_error = $geshi->error();
                     if (empty($str_error)) {
                         // enable line numbers
                         $number_style = !empty($match['line']) ? $match['line'] : $this->settings['default_line'];
                         switch (strtolower(preg_replace('/\\d+/', '', $number_style))) {
                             case 'normal':
                                 $geshi->enable_line_numbers(GESHI_NORMAL_LINE_NUMBERS);
                                 break;
                             case 'fancy':
                                 $geshi->enable_line_numbers(GESHI_FANCY_LINE_NUMBERS, (int) preg_replace('/[^\\d]*/', '', $number_style));
                                 break;
                             case 'none':
                                 $geshi->enable_line_numbers(GESHI_NO_LINE_NUMBERS);
                                 break;
                         }
                         // set first line number
                         if ($match['start']) {
                             $geshi->start_line_numbers_at($match['start']);
                         }
                         // set strict mode
                         if ($match['strict']) {
                             $geshi->enable_strict_mode(TRUE);
                         }
                         // enable or disable keyword links
                         $geshi->enable_keyword_links((bool) ($match['keyword_links'] !== NULL) ? $match['keyword_links'] : $this->settings['keyword_links']);
                         // set overall class name
                         if ($match['overall_class'] != NULL) {
                             $geshi->set_overall_class($match['overall_class']);
                         }
                         // set overall id
                         if ($match['overall_id'] != NULL) {
                             $geshi->set_overall_id($match['overall_id']);
                         }
                         // set header type
                         switch ($this->settings['geshi_header_type']) {
                             case 'div':
                                 $geshi->set_header_type(GESHI_HEADER_DIV);
                                 break;
                             case 'pre':
                                 $geshi->set_header_type(GESHI_HEADER_PRE);
                                 break;
                             case 'pre-valid':
                                 $geshi->set_header_type(GESHI_HEADER_PRE_VALID);
                                 break;
                             case 'pre-table':
                                 $geshi->set_header_type(GESHI_HEADER_PRE_TABLE);
                                 break;
                             case 'none':
                                 $geshi->set_header_type(GESHI_HEADER_NONE);
                                 break;
                         }
                         // set encoding (for legacy reasons afaik)
                         $geshi->set_encoding($this->settings['geshi_encoding']);
                         // parse the source code
                         $geshified = $geshi->parse_code();
                     } else {
                         $error = TRUE;
                     }
                 }
                 if (!file_exists($cache_dir . $md5) && is_writable($cache_dir) || file_exists($cache_dir . $md5) && is_writable($cache_dir . $md5)) {
                     if (!$error) {
                         // we can write to the cache file
                         if (is_callable('file_put_contents')) {
                             file_put_contents($cache_dir . $md5, $geshified);
                             @chmod($cache_dir . $md5, 0777);
                         } else {
                             // when will you guys finally drop PHP4 support?
                             $f = fopen($cache_dir . $md5, 'w');
                             fwrite($f, $geshified);
                             fclose($f);
                             @chmod($cache_dir . $md5, 0777);
                         }
                     }
                 } else {
                     // We could ignore that, but for performance reasons better warn the user.
                     print '<b>Warning</b>: Your <i>' . $this->name . '</i> cache directory <b>' . $cache_dir . '</b> is not writable! This will cause severe performance problems, so I suggest you chmod that dir.';
                 }
             }
             // save replacement to cache and mark location with an identifier for later replacement
             if (!isset($_SESSION['cache']['ext.geshify'])) {
                 $_SESSION['cache']['ext.geshify'] = array();
             }
             if (!$error) {
                 $_SESSION['cache']['ext.geshify'][$md5] = $geshified;
                 $str = substr($str, 0, $code_pos) . $md5 . substr($str, $code_end_pos + $rllen);
             }
         }
         // unset used variables, so we don't get messed up
         unset($code_pos, $code_end_pos, $md5, $geshified, $not_geshified, $geshi, $match, $ident, $error);
     }
     return $str;
 }
function wp_geshi_highlight_and_generate_css()
{
    global $wp_geshi_codesnipmatch_arrays;
    global $wp_geshi_css_code;
    global $wp_geshi_highlighted_matches;
    global $wp_geshi_requested_css_files;
    global $wp_geshi_used_languages;
    // It is time to initialize the highlighting machinery.
    // Check for `class_exists('GeSHi')` for preventing
    // `Cannot redeclare class GeSHi` errors. Another plugin may already have
    // included its own version of GeSHi.
    // TODO: in this case, include GeSHi of WP-GeSHi-Highlight anyway, via
    // namespacing or class renaming.
    if (!class_exists('GeSHi')) {
        include_once "geshi/geshi.php";
    }
    $wp_geshi_css_code = "";
    foreach ($wp_geshi_codesnipmatch_arrays as $match_index => $match) {
        // Process match details. The array structure is explained in
        // a comment to function `wp_geshi_filter_replace_code()`.
        $language = strtolower(trim($match[1]));
        $line = trim($match[2]);
        $escaped = trim($match[3]);
        $cssfile = trim($match[4]);
        $code = wp_geshi_code_trim($match[5]);
        if ($escaped == "true") {
            $code = htmlspecialchars_decode($code);
        }
        // (C) Ryan McGeary
        // Set up GeSHi.
        $geshi = new GeSHi($code, $language);
        // Output CSS code / do *not* create inline styles.
        $geshi->enable_classes();
        // Disable keyword links.
        $geshi->enable_keyword_links(false);
        if ($line) {
            $geshi->enable_line_numbers(GESHI_NORMAL_LINE_NUMBERS);
            $geshi->start_line_numbers_at($line);
        }
        // Set the output type. Reference:
        // http://qbnz.com/highlighter/geshi-doc.html#the-code-container
        $geshi->set_header_type(GESHI_HEADER_PRE_VALID);
        // By default, geshi sets font size to 1em and line height to 1.2em.
        // That does not fit many modern CSS architectures. Make this
        // relative and, most importantly, customizable.
        $geshi->set_code_style('');
        // If the current language has not been processed in a previous
        // iteration:
        // - create CSS code for this language
        // - append this to the `$wp_geshi_css_code string`.
        // $geshi->get_stylesheet(false) disables the economy mode, i.e.
        // this will return the full CSS code for the given language.
        // This allows for reusing the same CSS code for multiple code
        // blocks of the same language.
        if (!in_array($language, $wp_geshi_used_languages)) {
            $wp_geshi_used_languages[] = $language;
            $wp_geshi_css_code .= $geshi->get_stylesheet(false);
        }
        $output = "";
        // cssfile "none" means no wrapping divs at all.
        if ($cssfile != "none") {
            if (empty($cssfile)) {
                // For this code snippet the default css file is required.
                $cssfile = "wp-geshi-highlight";
            }
            // Append "the css file" to the array.
            $wp_geshi_requested_css_files[] = $cssfile;
            $output .= "\n\n" . '<div class="' . $cssfile . '-wrap5">' . '<div class="' . $cssfile . '-wrap4">' . '<div class="' . $cssfile . '-wrap3">' . '<div class="' . $cssfile . '-wrap2">' . '<div class="' . $cssfile . '-wrap">' . '<div class="' . $cssfile . '">';
        }
        // Create highlighted HTML code.
        $output .= $geshi->parse_code();
        if ($cssfile != "none") {
            $output .= '</div></div></div></div></div></div>' . "\n\n";
        }
        // Store highlighted HTML code for later usage.
        $wp_geshi_highlighted_matches[$match_index] = $output;
    }
    // At this point, all code snippets are parsed. Highlighted code is stored.
    // CSS code has been generated. Delete what is not required anymore.
    unset($wp_geshi_codesnipmatch_arrays);
}
Exemple #13
0
/**
 * Function handler for coloring shortcodes. It's used in comments and for [filesyntax tag]
 *
 * @param string $atts
 * @param string $content
 * @return string
 */
function fr_codesyntax_handler($atts, $content = null, $cleanHTML = true, $commentProcessing = false)
{
    global $wp_sh_styling_type;
    if (empty($content)) {
        return '<font color="red"><b>' . __('WP-SYNHIGHLIGHT PLUGIN: NOTHING TO HIGHLIGHT! PLEASE READ README.TXT IN PLUGIN FOLDER!', 'wp-synhighlighter') . '</b></font>';
    }
    //Parsing paramters
    $params = shortcode_atts(array('title' => get_option('wp_synhighlight_default_codeblock_title') ? get_option('wp_synhighlight_default_codeblock_title') : __("Code block", 'wp-synhighlighter'), 'bookmarkname' => '', 'lang' => 'pascal', 'lines' => get_option('wp_synhighlight_default_lines') ? get_option('wp_synhighlight_default_lines') : 'fancy', 'lines_start' => get_option('wp_synhighlight_default_lines_start_with') ? get_option('wp_synhighlight_default_lines_start_with') : '1', 'container' => get_option('wp_synhighlight_default_container') ? get_option('wp_synhighlight_default_container') : 'pre', 'capitalize' => get_option('wp_synhighlight_default_capitalize_keywords') ? get_option('wp_synhighlight_default_capitalize_keywords') : 'no', 'tab_width' => get_option('wp_synhighlight_default_tab_width') ? get_option('wp_synhighlight_default_tab_width') : 4, 'strict' => get_option('wp_synhighlight_default_strict_mode') ? get_option('wp_synhighlight_default_strict_mode') : 'always', 'blockstate' => get_option('wp_synhighlight_default_blockstate') ? get_option('wp_synhighlight_default_blockstate') : 'default', 'highlight_lines' => "", 'doclinks' => !get_option('wp_synhighlight_doclinks_off')), $atts);
    if ($cleanHTML) {
        //Clearing all other HTML code
        $content = strip_tags($content);
        //Converting HTML entities
        $content = html_entity_decode($content, ENT_QUOTES);
    }
    //Trimming first and last incorrect newlines
    $content = trim($content);
    //Windows Live Writer patch
    foreach ($params as &$param) {
        $param = trim(html_entity_decode($param, ENT_QUOTES), '"');
    }
    //Highlighting
    $geshi = new GeSHi($content, $params['lang']);
    if (!$commentProcessing and ($wp_sh_styling_type == 'theme' or $wp_sh_styling_type == 'embedbody')) {
        $geshi->enable_classes();
    }
    //Setting Geshi options
    //Lines
    switch ($params['lines']) {
        case 'normal':
            $geshi->enable_line_numbers(GESHI_NORMAL_LINE_NUMBERS);
            break;
        case 'fancy':
            $geshi->enable_line_numbers(GESHI_FANCY_LINE_NUMBERS);
            break;
        case 'no':
            $geshi->enable_line_numbers(GESHI_NO_LINE_NUMBERS);
            break;
    }
    $geshi->start_line_numbers_at($params['lines_start']);
    //Container
    switch ($params['container']) {
        case 'pre':
            $geshi->set_header_type(GESHI_HEADER_PRE);
            break;
        case 'div':
            $geshi->set_header_type(GESHI_HEADER_DIV);
            break;
        case 'pre_valid':
            $geshi->set_header_type(GESHI_HEADER_PRE_VALID);
            break;
        case 'pre_table':
            $geshi->set_header_type(GESHI_HEADER_PRE_TABLE);
            break;
        case 'none':
            $geshi->set_header_type(GESHI_HEADER_NONE);
            break;
    }
    //Keywords capitalization
    switch ($params['capitalize']) {
        case 'no':
            $geshi->set_case_keywords(GESHI_CAPS_NO_CHANGE);
            break;
        case 'upper':
            $geshi->set_case_keywords(GESHI_CAPS_UPPER);
            break;
        case 'lower':
            $geshi->set_case_keywords(GESHI_CAPS_LOWER);
            break;
    }
    //Tab width
    $geshi->set_tab_width($params['tab_width']);
    //Strict mode
    switch ($params['strict']) {
        case 'always':
            $geshi->enable_strict_mode(GESHI_ALWAYS);
            break;
        case 'maybe':
            $geshi->enable_strict_mode(GESHI_MAYBE);
            break;
        case 'never':
            $geshi->enable_strict_mode(GESHI_NEVER);
            break;
    }
    //Block state
    switch ($params['blockstate']) {
        case 'collapsed':
            $initiallyHidden = true;
            break;
        case 'default':
        case 'expanded':
        default:
            $initiallyHidden = false;
            break;
    }
    //Controlling doclinks
    $geshi->enable_keyword_links($params['doclinks']);
    static $instanceNumber = 0;
    $instanceNumber++;
    $bookmarkName = empty($params['bookmarkname']) ? "codesyntax_" . $instanceNumber : $params['bookmarkname'];
    //Highlighting lines
    if (!empty($params['highlight_lines'])) {
        $geshi->highlight_lines_extra(explode(',', $params['highlight_lines']));
    }
    //Checking for geshi errors
    if ($geshi->error()) {
        return '<font color="red"><b>' . $geshi->error() . '</b></font>';
    }
    //Styling codeblock
    $header = wp_synhighlight_get_tpl_header($instanceNumber, $params['title'], $bookmarkName, $initiallyHidden);
    //Embedding only one copy of each used language style
    static $embeddedStylesheets = array();
    if ($wp_sh_styling_type == 'embedbody' and !in_array($params['lang'], $embeddedStylesheets)) {
        $header = '<style type="text/css"><!--' . "\r\n" . $geshi->get_stylesheet() . "\r\n" . '-->' . "\r\n" . '</style>' . $header;
        $embeddedStylesheets[] = $params['lang'];
    }
    $footer = wp_synhighlight_get_tpl_footer();
    $result = $header . $geshi->parse_code() . $footer;
    return $result;
}
//$geshi->set_header_type(GESHI_HEADER_DIV);
//$geshi->set_header_type(GESHI_HEADER_PRE);
//$geshi->set_header_type(GESHI_HEADER_PRE_VALID);
$geshi->set_header_type(GESHI_HEADER_PRE_TABLE);
//$geshi->set_header_type(GESHI_HEADER_NONE);
//===
// Select the line number method
if ($lineNumbers == "true") {
    $geshi->enable_line_numbers(GESHI_NORMAL_LINE_NUMBERS);
    //$geshi->enable_line_numbers(GESHI_FANCY_LINE_NUMBERS, 5);
} else {
    $geshi->enable_line_numbers(GESHI_NO_LINE_NUMBERS);
}
//===
// Set where to start counting line numbers from
$geshi->start_line_numbers_at((int) $startLine);
//===
// Set the tab processing (only used for non-pre header types)
$geshi->set_use_language_tab_width(true);
$geshi->set_tab_width(4);
//===
// Set the base styles
initGeshiStyles($geshi);
//===
// Set the header and footer
// Note: As of this moment the footer doesn't seem to work right with the table
//       output format so we are leaving it empty.
$geshi->set_header_content($codeHeader);
$geshi->set_footer_content('');
//===
// Process the code
function wp_geshi_highlight_and_generate_css()
{
    global $wp_geshi_codesnipmatch_arrays;
    global $wp_geshi_css_code;
    global $wp_geshi_highlighted_matches;
    global $wp_geshi_requested_css_files;
    global $wp_geshi_used_languages;
    // When we're here, code was found.
    // Time to initialize the highlighting machine...
    // Check for `class_exists('GeSHi')` for preventing
    // `Cannot redeclare class GeSHi` errors. Another plugin may already have
    // included its own version of GeSHi.
    // TODO: in this case, include GeSHi of WP-GeSHi-Highlight anyway via using
    // namespaces or class renaming.
    if (!class_exists('GeSHi')) {
        include_once "geshi/geshi.php";
    }
    $wp_geshi_css_code = "";
    foreach ($wp_geshi_codesnipmatch_arrays as $match_index => $match) {
        // Process the match details. The correspondence is explained in
        // function `wp_geshi_filter_replace_code()`.
        $language = strtolower(trim($match[1]));
        $line = trim($match[2]);
        $escaped = trim($match[3]);
        $cssfile = trim($match[4]);
        $code = wp_geshi_code_trim($match[5]);
        if ($escaped == "true") {
            $code = htmlspecialchars_decode($code);
        }
        // (C) Ryan McGeary
        // Set up GeSHi.
        $geshi = new GeSHi($code, $language);
        // Prepare GeSHi to output CSS code and to prohibit inline styles.
        $geshi->enable_classes();
        // Disable keyword links.
        $geshi->enable_keyword_links(false);
        // Process the line number option given by user.
        if ($line) {
            $geshi->enable_line_numbers(GESHI_NORMAL_LINE_NUMBERS);
            $geshi->start_line_numbers_at($line);
        }
        // Set the output code type.
        $geshi->set_header_type(GESHI_HEADER_PRE_VALID);
        // By default, geshi sets font size to 1em and line height to 1.2em.
        // That does not fit to many modern layouts, make this relative, and
        // most important, make it customizable from outside.
        $geshi->set_code_style('');
        // Append the CSS code to the CSS code string if this is the first
        // occurrence of the language. $geshi->get_stylesheet(false)
        // disables the economy mode, i.e. this will return the full CSS
        // code for the given language. This makes it much easier to use the
        // same CSS code for several code blocks of the same language.
        if (!in_array($language, $wp_geshi_used_languages)) {
            $wp_geshi_used_languages[] = $language;
            $wp_geshi_css_code .= $geshi->get_stylesheet(false);
        }
        $output = "";
        // cssfile "none" means no wrapping divs at all.
        if ($cssfile != "none") {
            if (empty($cssfile)) {
                // For this code snippet the default css file is required.
                $cssfile = "wp-geshi-highlight";
            }
            // Append "the css file" to the array.
            $wp_geshi_requested_css_files[] = $cssfile;
            $output .= "\n\n" . '<div class="' . $cssfile . '-wrap5">' . '<div class="' . $cssfile . '-wrap4">' . '<div class="' . $cssfile . '-wrap3">' . '<div class="' . $cssfile . '-wrap2">' . '<div class="' . $cssfile . '-wrap">' . '<div class="' . $cssfile . '">';
        }
        $output .= $geshi->parse_code();
        if ($cssfile != "none") {
            $output .= '</div></div></div></div></div></div>' . "\n\n";
        }
        $wp_geshi_highlighted_matches[$match_index] = $output;
    }
    // At this point, all code snippets are parsed. Highlighted code is stored.
    // CSS code is generated. Delete variables that are not required anymore.
    unset($wp_geshi_codesnipmatch_arrays);
}