PageRenderTime 75ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 1ms

/plugins/content/geshi/geshi/geshi.php

https://bitbucket.org/asosso/joomla25
PHP | 4758 lines | 2706 code | 404 blank | 1648 comment | 704 complexity | a42450e098d3a226bab73b7d462896ce MD5 | raw file
Possible License(s): LGPL-2.1
  1. <?php
  2. // no direct access
  3. defined('_JEXEC') or die;
  4. /**
  5. * GeSHi - Generic Syntax Highlighter
  6. *
  7. * The GeSHi class for Generic Syntax Highlighting. Please refer to the
  8. * documentation at http://qbnz.com/highlighter/documentation.php for more
  9. * information about how to use this class.
  10. *
  11. * For changes, release notes, TODOs etc, see the relevant files in the docs/
  12. * directory.
  13. *
  14. * This file is part of GeSHi.
  15. *
  16. * GeSHi is free software; you can redistribute it and/or modify
  17. * it under the terms of the GNU General Public License as published by
  18. * the Free Software Foundation; either version 2 of the License, or
  19. * (at your option) any later version.
  20. *
  21. * GeSHi is distributed in the hope that it will be useful,
  22. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  23. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  24. * GNU General Public License for more details.
  25. *
  26. * You should have received a copy of the GNU General Public License
  27. * along with GeSHi; if not, write to the Free Software
  28. * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  29. *
  30. * @package geshi
  31. * @subpackage core
  32. * @author Nigel McNie <nigel@geshi.org>, Benny Baumann <BenBE@omorphia.de>
  33. * @copyright (C) 2004 - 2007 Nigel McNie, (C) 2007 - 2008 Benny Baumann
  34. * @license http://gnu.org/copyleft/gpl.html GNU GPL
  35. *
  36. */
  37. //
  38. // GeSHi Constants
  39. // You should use these constant names in your programs instead of
  40. // their values - you never know when a value may change in a future
  41. // version
  42. //
  43. /** The version of this GeSHi file */
  44. define('GESHI_VERSION', '1.0.8.10');
  45. // Define the root directory for the GeSHi code tree
  46. if (!defined('GESHI_ROOT')) {
  47. /** The root directory for GeSHi */
  48. define('GESHI_ROOT', dirname(__FILE__) . DIRECTORY_SEPARATOR);
  49. }
  50. /** The language file directory for GeSHi
  51. @access private */
  52. define('GESHI_LANG_ROOT', GESHI_ROOT . 'geshi' . DIRECTORY_SEPARATOR);
  53. // Define if GeSHi should be paranoid about security
  54. if (!defined('GESHI_SECURITY_PARANOID')) {
  55. /** Tells GeSHi to be paranoid about security settings */
  56. define('GESHI_SECURITY_PARANOID', false);
  57. }
  58. // Line numbers - use with enable_line_numbers()
  59. /** Use no line numbers when building the result */
  60. define('GESHI_NO_LINE_NUMBERS', 0);
  61. /** Use normal line numbers when building the result */
  62. define('GESHI_NORMAL_LINE_NUMBERS', 1);
  63. /** Use fancy line numbers when building the result */
  64. define('GESHI_FANCY_LINE_NUMBERS', 2);
  65. // Container HTML type
  66. /** Use nothing to surround the source */
  67. define('GESHI_HEADER_NONE', 0);
  68. /** Use a "div" to surround the source */
  69. define('GESHI_HEADER_DIV', 1);
  70. /** Use a "pre" to surround the source */
  71. define('GESHI_HEADER_PRE', 2);
  72. /** Use a pre to wrap lines when line numbers are enabled or to wrap the whole code. */
  73. define('GESHI_HEADER_PRE_VALID', 3);
  74. /**
  75. * Use a "table" to surround the source:
  76. *
  77. * <table>
  78. * <thead><tr><td colspan="2">$header</td></tr></thead>
  79. * <tbody><tr><td><pre>$linenumbers</pre></td><td><pre>$code></pre></td></tr></tbody>
  80. * <tfooter><tr><td colspan="2">$footer</td></tr></tfoot>
  81. * </table>
  82. *
  83. * this is essentially only a workaround for Firefox, see sf#1651996 or take a look at
  84. * https://bugzilla.mozilla.org/show_bug.cgi?id=365805
  85. * @note when linenumbers are disabled this is essentially the same as GESHI_HEADER_PRE
  86. */
  87. define('GESHI_HEADER_PRE_TABLE', 4);
  88. // Capatalisation constants
  89. /** Lowercase keywords found */
  90. define('GESHI_CAPS_NO_CHANGE', 0);
  91. /** Uppercase keywords found */
  92. define('GESHI_CAPS_UPPER', 1);
  93. /** Leave keywords found as the case that they are */
  94. define('GESHI_CAPS_LOWER', 2);
  95. // Link style constants
  96. /** Links in the source in the :link state */
  97. define('GESHI_LINK', 0);
  98. /** Links in the source in the :hover state */
  99. define('GESHI_HOVER', 1);
  100. /** Links in the source in the :active state */
  101. define('GESHI_ACTIVE', 2);
  102. /** Links in the source in the :visited state */
  103. define('GESHI_VISITED', 3);
  104. // Important string starter/finisher
  105. // Note that if you change these, they should be as-is: i.e., don't
  106. // write them as if they had been run through htmlentities()
  107. /** The starter for important parts of the source */
  108. define('GESHI_START_IMPORTANT', '<BEGIN GeSHi>');
  109. /** The ender for important parts of the source */
  110. define('GESHI_END_IMPORTANT', '<END GeSHi>');
  111. /**#@+
  112. * @access private
  113. */
  114. // When strict mode applies for a language
  115. /** Strict mode never applies (this is the most common) */
  116. define('GESHI_NEVER', 0);
  117. /** Strict mode *might* apply, and can be enabled or
  118. disabled by {@link GeSHi->enable_strict_mode()} */
  119. define('GESHI_MAYBE', 1);
  120. /** Strict mode always applies */
  121. define('GESHI_ALWAYS', 2);
  122. // Advanced regexp handling constants, used in language files
  123. /** The key of the regex array defining what to search for */
  124. define('GESHI_SEARCH', 0);
  125. /** The key of the regex array defining what bracket group in a
  126. matched search to use as a replacement */
  127. define('GESHI_REPLACE', 1);
  128. /** The key of the regex array defining any modifiers to the regular expression */
  129. define('GESHI_MODIFIERS', 2);
  130. /** The key of the regex array defining what bracket group in a
  131. matched search to put before the replacement */
  132. define('GESHI_BEFORE', 3);
  133. /** The key of the regex array defining what bracket group in a
  134. matched search to put after the replacement */
  135. define('GESHI_AFTER', 4);
  136. /** The key of the regex array defining a custom keyword to use
  137. for this regexp's html tag class */
  138. define('GESHI_CLASS', 5);
  139. /** Used in language files to mark comments */
  140. define('GESHI_COMMENTS', 0);
  141. /** Used to work around missing PHP features **/
  142. define('GESHI_PHP_PRE_433', !(version_compare(PHP_VERSION, '4.3.3') === 1));
  143. /** make sure we can call stripos **/
  144. if (!function_exists('stripos')) {
  145. // the offset param of preg_match is not supported below PHP 4.3.3
  146. if (GESHI_PHP_PRE_433) {
  147. /**
  148. * @ignore
  149. */
  150. function stripos($haystack, $needle, $offset = null) {
  151. if (!is_null($offset)) {
  152. $haystack = substr($haystack, $offset);
  153. }
  154. if (preg_match('/'. preg_quote($needle, '/') . '/', $haystack, $match, PREG_OFFSET_CAPTURE)) {
  155. return $match[0][1];
  156. }
  157. return false;
  158. }
  159. }
  160. else {
  161. /**
  162. * @ignore
  163. */
  164. function stripos($haystack, $needle, $offset = null) {
  165. if (preg_match('/'. preg_quote($needle, '/') . '/', $haystack, $match, PREG_OFFSET_CAPTURE, $offset)) {
  166. return $match[0][1];
  167. }
  168. return false;
  169. }
  170. }
  171. }
  172. /** some old PHP / PCRE subpatterns only support up to xxx subpatterns in
  173. regular expressions. Set this to false if your PCRE lib is up to date
  174. @see GeSHi->optimize_regexp_list()
  175. **/
  176. define('GESHI_MAX_PCRE_SUBPATTERNS', 500);
  177. /** it's also important not to generate too long regular expressions
  178. be generous here... but keep in mind, that when reaching this limit we
  179. still have to close open patterns. 12k should do just fine on a 16k limit.
  180. @see GeSHi->optimize_regexp_list()
  181. **/
  182. define('GESHI_MAX_PCRE_LENGTH', 12288);
  183. //Number format specification
  184. /** Basic number format for integers */
  185. define('GESHI_NUMBER_INT_BASIC', 1); //Default integers \d+
  186. /** Enhanced number format for integers like seen in C */
  187. define('GESHI_NUMBER_INT_CSTYLE', 2); //Default C-Style \d+[lL]?
  188. /** Number format to highlight binary numbers with a suffix "b" */
  189. define('GESHI_NUMBER_BIN_SUFFIX', 16); //[01]+[bB]
  190. /** Number format to highlight binary numbers with a prefix % */
  191. define('GESHI_NUMBER_BIN_PREFIX_PERCENT', 32); //%[01]+
  192. /** Number format to highlight binary numbers with a prefix 0b (C) */
  193. define('GESHI_NUMBER_BIN_PREFIX_0B', 64); //0b[01]+
  194. /** Number format to highlight octal numbers with a leading zero */
  195. define('GESHI_NUMBER_OCT_PREFIX', 256); //0[0-7]+
  196. /** Number format to highlight octal numbers with a prefix 0o (logtalk) */
  197. define('GESHI_NUMBER_OCT_PREFIX_0O', 512); //0[0-7]+
  198. /** Number format to highlight octal numbers with a leading @ (Used in HiSofts Devpac series). */
  199. define('GESHI_NUMBER_OCT_PREFIX_AT', 1024); //@[0-7]+
  200. /** Number format to highlight octal numbers with a suffix of o */
  201. define('GESHI_NUMBER_OCT_SUFFIX', 2048); //[0-7]+[oO]
  202. /** Number format to highlight hex numbers with a prefix 0x */
  203. define('GESHI_NUMBER_HEX_PREFIX', 4096); //0x[0-9a-fA-F]+
  204. /** Number format to highlight hex numbers with a prefix $ */
  205. define('GESHI_NUMBER_HEX_PREFIX_DOLLAR', 8192); //$[0-9a-fA-F]+
  206. /** Number format to highlight hex numbers with a suffix of h */
  207. define('GESHI_NUMBER_HEX_SUFFIX', 16384); //[0-9][0-9a-fA-F]*h
  208. /** Number format to highlight floating-point numbers without support for scientific notation */
  209. define('GESHI_NUMBER_FLT_NONSCI', 65536); //\d+\.\d+
  210. /** Number format to highlight floating-point numbers without support for scientific notation */
  211. define('GESHI_NUMBER_FLT_NONSCI_F', 131072); //\d+(\.\d+)?f
  212. /** Number format to highlight floating-point numbers with support for scientific notation (E) and optional leading zero */
  213. define('GESHI_NUMBER_FLT_SCI_SHORT', 262144); //\.\d+e\d+
  214. /** Number format to highlight floating-point numbers with support for scientific notation (E) and required leading digit */
  215. define('GESHI_NUMBER_FLT_SCI_ZERO', 524288); //\d+(\.\d+)?e\d+
  216. //Custom formats are passed by RX array
  217. // Error detection - use these to analyse faults
  218. /** No sourcecode to highlight was specified
  219. * @deprecated
  220. */
  221. define('GESHI_ERROR_NO_INPUT', 1);
  222. /** The language specified does not exist */
  223. define('GESHI_ERROR_NO_SUCH_LANG', 2);
  224. /** GeSHi could not open a file for reading (generally a language file) */
  225. define('GESHI_ERROR_FILE_NOT_READABLE', 3);
  226. /** The header type passed to {@link GeSHi->set_header_type()} was invalid */
  227. define('GESHI_ERROR_INVALID_HEADER_TYPE', 4);
  228. /** The line number type passed to {@link GeSHi->enable_line_numbers()} was invalid */
  229. define('GESHI_ERROR_INVALID_LINE_NUMBER_TYPE', 5);
  230. /**#@-*/
  231. /**
  232. * The GeSHi Class.
  233. *
  234. * Please refer to the documentation for GeSHi 1.0.X that is available
  235. * at http://qbnz.com/highlighter/documentation.php for more information
  236. * about how to use this class.
  237. *
  238. * @package geshi
  239. * @author Nigel McNie <nigel@geshi.org>, Benny Baumann <BenBE@omorphia.de>
  240. * @copyright (C) 2004 - 2007 Nigel McNie, (C) 2007 - 2008 Benny Baumann
  241. */
  242. class GeSHi {
  243. /**#@+
  244. * @access private
  245. */
  246. /**
  247. * The source code to highlight
  248. * @var string
  249. */
  250. var $source = '';
  251. /**
  252. * The language to use when highlighting
  253. * @var string
  254. */
  255. var $language = '';
  256. /**
  257. * The data for the language used
  258. * @var array
  259. */
  260. var $language_data = array();
  261. /**
  262. * The path to the language files
  263. * @var string
  264. */
  265. var $language_path = GESHI_LANG_ROOT;
  266. /**
  267. * The error message associated with an error
  268. * @var string
  269. * @todo check err reporting works
  270. */
  271. var $error = false;
  272. /**
  273. * Possible error messages
  274. * @var array
  275. */
  276. var $error_messages = array(
  277. GESHI_ERROR_NO_SUCH_LANG => 'GeSHi could not find the language {LANGUAGE} (using path {PATH})',
  278. GESHI_ERROR_FILE_NOT_READABLE => 'The file specified for load_from_file was not readable',
  279. GESHI_ERROR_INVALID_HEADER_TYPE => 'The header type specified is invalid',
  280. GESHI_ERROR_INVALID_LINE_NUMBER_TYPE => 'The line number type specified is invalid'
  281. );
  282. /**
  283. * Whether highlighting is strict or not
  284. * @var boolean
  285. */
  286. var $strict_mode = false;
  287. /**
  288. * Whether to use CSS classes in output
  289. * @var boolean
  290. */
  291. var $use_classes = false;
  292. /**
  293. * The type of header to use. Can be one of the following
  294. * values:
  295. *
  296. * - GESHI_HEADER_PRE: Source is outputted in a "pre" HTML element.
  297. * - GESHI_HEADER_DIV: Source is outputted in a "div" HTML element.
  298. * - GESHI_HEADER_NONE: No header is outputted.
  299. *
  300. * @var int
  301. */
  302. var $header_type = GESHI_HEADER_PRE;
  303. /**
  304. * Array of permissions for which lexics should be highlighted
  305. * @var array
  306. */
  307. var $lexic_permissions = array(
  308. 'KEYWORDS' => array(),
  309. 'COMMENTS' => array('MULTI' => true),
  310. 'REGEXPS' => array(),
  311. 'ESCAPE_CHAR' => true,
  312. 'BRACKETS' => true,
  313. 'SYMBOLS' => false,
  314. 'STRINGS' => true,
  315. 'NUMBERS' => true,
  316. 'METHODS' => true,
  317. 'SCRIPT' => true
  318. );
  319. /**
  320. * The time it took to parse the code
  321. * @var double
  322. */
  323. var $time = 0;
  324. /**
  325. * The content of the header block
  326. * @var string
  327. */
  328. var $header_content = '';
  329. /**
  330. * The content of the footer block
  331. * @var string
  332. */
  333. var $footer_content = '';
  334. /**
  335. * The style of the header block
  336. * @var string
  337. */
  338. var $header_content_style = '';
  339. /**
  340. * The style of the footer block
  341. * @var string
  342. */
  343. var $footer_content_style = '';
  344. /**
  345. * Tells if a block around the highlighted source should be forced
  346. * if not using line numbering
  347. * @var boolean
  348. */
  349. var $force_code_block = false;
  350. /**
  351. * The styles for hyperlinks in the code
  352. * @var array
  353. */
  354. var $link_styles = array();
  355. /**
  356. * Whether important blocks should be recognised or not
  357. * @var boolean
  358. * @deprecated
  359. * @todo REMOVE THIS FUNCTIONALITY!
  360. */
  361. var $enable_important_blocks = false;
  362. /**
  363. * Styles for important parts of the code
  364. * @var string
  365. * @deprecated
  366. * @todo As above - rethink the whole idea of important blocks as it is buggy and
  367. * will be hard to implement in 1.2
  368. */
  369. var $important_styles = 'font-weight: bold; color: red;'; // Styles for important parts of the code
  370. /**
  371. * Whether CSS IDs should be added to the code
  372. * @var boolean
  373. */
  374. var $add_ids = false;
  375. /**
  376. * Lines that should be highlighted extra
  377. * @var array
  378. */
  379. var $highlight_extra_lines = array();
  380. /**
  381. * Styles of lines that should be highlighted extra
  382. * @var array
  383. */
  384. var $highlight_extra_lines_styles = array();
  385. /**
  386. * Styles of extra-highlighted lines
  387. * @var string
  388. */
  389. var $highlight_extra_lines_style = 'background-color: #ffc;';
  390. /**
  391. * The line ending
  392. * If null, nl2br() will be used on the result string.
  393. * Otherwise, all instances of \n will be replaced with $line_ending
  394. * @var string
  395. */
  396. var $line_ending = null;
  397. /**
  398. * Number at which line numbers should start at
  399. * @var int
  400. */
  401. var $line_numbers_start = 1;
  402. /**
  403. * The overall style for this code block
  404. * @var string
  405. */
  406. var $overall_style = 'font-family:monospace;';
  407. /**
  408. * The style for the actual code
  409. * @var string
  410. */
  411. var $code_style = 'font: normal normal 1em/1.2em monospace; margin:0; padding:0; background:none; vertical-align:top;';
  412. /**
  413. * The overall class for this code block
  414. * @var string
  415. */
  416. var $overall_class = '';
  417. /**
  418. * The overall ID for this code block
  419. * @var string
  420. */
  421. var $overall_id = '';
  422. /**
  423. * Line number styles
  424. * @var string
  425. */
  426. var $line_style1 = 'font-weight: normal; vertical-align:top;';
  427. /**
  428. * Line number styles for fancy lines
  429. * @var string
  430. */
  431. var $line_style2 = 'font-weight: bold; vertical-align:top;';
  432. /**
  433. * Style for line numbers when GESHI_HEADER_PRE_TABLE is chosen
  434. * @var string
  435. */
  436. var $table_linenumber_style = 'width:1px;text-align:right;margin:0;padding:0 2px;vertical-align:top;';
  437. /**
  438. * Flag for how line numbers are displayed
  439. * @var boolean
  440. */
  441. var $line_numbers = GESHI_NO_LINE_NUMBERS;
  442. /**
  443. * Flag to decide if multi line spans are allowed. Set it to false to make sure
  444. * each tag is closed before and reopened after each linefeed.
  445. * @var boolean
  446. */
  447. var $allow_multiline_span = true;
  448. /**
  449. * The "nth" value for fancy line highlighting
  450. * @var int
  451. */
  452. var $line_nth_row = 0;
  453. /**
  454. * The size of tab stops
  455. * @var int
  456. */
  457. var $tab_width = 8;
  458. /**
  459. * Should we use language-defined tab stop widths?
  460. * @var int
  461. */
  462. var $use_language_tab_width = false;
  463. /**
  464. * Default target for keyword links
  465. * @var string
  466. */
  467. var $link_target = '';
  468. /**
  469. * The encoding to use for entity encoding
  470. * NOTE: Used with Escape Char Sequences to fix UTF-8 handling (cf. SF#2037598)
  471. * @var string
  472. */
  473. var $encoding = 'utf-8';
  474. /**
  475. * Should keywords be linked?
  476. * @var boolean
  477. */
  478. var $keyword_links = true;
  479. /**
  480. * Currently loaded language file
  481. * @var string
  482. * @since 1.0.7.22
  483. */
  484. var $loaded_language = '';
  485. /**
  486. * Wether the caches needed for parsing are built or not
  487. *
  488. * @var bool
  489. * @since 1.0.8
  490. */
  491. var $parse_cache_built = false;
  492. /**
  493. * Work around for Suhosin Patch with disabled /e modifier
  494. *
  495. * Note from suhosins author in config file:
  496. * <blockquote>
  497. * The /e modifier inside <code>preg_replace()</code> allows code execution.
  498. * Often it is the cause for remote code execution exploits. It is wise to
  499. * deactivate this feature and test where in the application it is used.
  500. * The developer using the /e modifier should be made aware that he should
  501. * use <code>preg_replace_callback()</code> instead
  502. * </blockquote>
  503. *
  504. * @var array
  505. * @since 1.0.8
  506. */
  507. var $_kw_replace_group = 0;
  508. var $_rx_key = 0;
  509. /**
  510. * some "callback parameters" for handle_multiline_regexps
  511. *
  512. * @since 1.0.8
  513. * @access private
  514. * @var string
  515. */
  516. var $_hmr_before = '';
  517. var $_hmr_replace = '';
  518. var $_hmr_after = '';
  519. var $_hmr_key = 0;
  520. /**#@-*/
  521. /**
  522. * Creates a new GeSHi object, with source and language
  523. *
  524. * @param string The source code to highlight
  525. * @param string The language to highlight the source with
  526. * @param string The path to the language file directory. <b>This
  527. * is deprecated!</b> I've backported the auto path
  528. * detection from the 1.1.X dev branch, so now it
  529. * should be automatically set correctly. If you have
  530. * renamed the language directory however, you will
  531. * still need to set the path using this parameter or
  532. * {@link GeSHi->set_language_path()}
  533. * @since 1.0.0
  534. */
  535. function GeSHi($source = '', $language = '', $path = '') {
  536. if (!empty($source)) {
  537. $this->set_source($source);
  538. }
  539. if (!empty($language)) {
  540. $this->set_language($language);
  541. }
  542. $this->set_language_path($path);
  543. }
  544. /**
  545. * Returns an error message associated with the last GeSHi operation,
  546. * or false if no error has occured
  547. *
  548. * @return string|false An error message if there has been an error, else false
  549. * @since 1.0.0
  550. */
  551. function error() {
  552. if ($this->error) {
  553. //Put some template variables for debugging here ...
  554. $debug_tpl_vars = array(
  555. '{LANGUAGE}' => $this->language,
  556. '{PATH}' => $this->language_path
  557. );
  558. $msg = str_replace(
  559. array_keys($debug_tpl_vars),
  560. array_values($debug_tpl_vars),
  561. $this->error_messages[$this->error]);
  562. return "<br /><strong>GeSHi Error:</strong> $msg (code {$this->error})<br />";
  563. }
  564. return false;
  565. }
  566. /**
  567. * Gets a human-readable language name (thanks to Simon Patterson
  568. * for the idea :))
  569. *
  570. * @return string The name for the current language
  571. * @since 1.0.2
  572. */
  573. function get_language_name() {
  574. if (GESHI_ERROR_NO_SUCH_LANG == $this->error) {
  575. return $this->language_data['LANG_NAME'] . ' (Unknown Language)';
  576. }
  577. return $this->language_data['LANG_NAME'];
  578. }
  579. /**
  580. * Sets the source code for this object
  581. *
  582. * @param string The source code to highlight
  583. * @since 1.0.0
  584. */
  585. function set_source($source) {
  586. $this->source = $source;
  587. $this->highlight_extra_lines = array();
  588. }
  589. /**
  590. * Sets the language for this object
  591. *
  592. * @note since 1.0.8 this function won't reset language-settings by default anymore!
  593. * if you need this set $force_reset = true
  594. *
  595. * @param string The name of the language to use
  596. * @since 1.0.0
  597. */
  598. function set_language($language, $force_reset = false) {
  599. if ($force_reset) {
  600. $this->loaded_language = false;
  601. }
  602. //Clean up the language name to prevent malicious code injection
  603. $language = preg_replace('#[^a-zA-Z0-9\-_]#', '', $language);
  604. $language = strtolower($language);
  605. //Retreive the full filename
  606. $file_name = $this->language_path . $language . '.php';
  607. if ($file_name == $this->loaded_language) {
  608. // this language is already loaded!
  609. return;
  610. }
  611. $this->language = $language;
  612. $this->error = false;
  613. $this->strict_mode = GESHI_NEVER;
  614. //Check if we can read the desired file
  615. if (!is_readable($file_name)) {
  616. $this->error = GESHI_ERROR_NO_SUCH_LANG;
  617. return;
  618. }
  619. // Load the language for parsing
  620. $this->load_language($file_name);
  621. }
  622. /**
  623. * Sets the path to the directory containing the language files. Note
  624. * that this path is relative to the directory of the script that included
  625. * geshi.php, NOT geshi.php itself.
  626. *
  627. * @param string The path to the language directory
  628. * @since 1.0.0
  629. * @deprecated The path to the language files should now be automatically
  630. * detected, so this method should no longer be needed. The
  631. * 1.1.X branch handles manual setting of the path differently
  632. * so this method will disappear in 1.2.0.
  633. */
  634. function set_language_path($path) {
  635. if(strpos($path, ':')) {
  636. //Security Fix to prevent external directories using fopen wrappers.
  637. if(DIRECTORY_SEPARATOR == "\\") {
  638. if(!preg_match('#^[a-zA-Z]:#', $path) || false !== strpos($path, ':', 2)) {
  639. return;
  640. }
  641. } else {
  642. return;
  643. }
  644. }
  645. if(preg_match('#[^/a-zA-Z0-9_\.\-\\\s:]#', $path)) {
  646. //Security Fix to prevent external directories using fopen wrappers.
  647. return;
  648. }
  649. if(GESHI_SECURITY_PARANOID && false !== strpos($path, '/.')) {
  650. //Security Fix to prevent external directories using fopen wrappers.
  651. return;
  652. }
  653. if(GESHI_SECURITY_PARANOID && false !== strpos($path, '..')) {
  654. //Security Fix to prevent external directories using fopen wrappers.
  655. return;
  656. }
  657. if ($path) {
  658. $this->language_path = ('/' == $path[strlen($path) - 1]) ? $path : $path . '/';
  659. $this->set_language($this->language); // otherwise set_language_path has no effect
  660. }
  661. }
  662. /**
  663. * Get supported langs or an associative array lang=>full_name.
  664. * @param boolean $longnames
  665. * @return array
  666. */
  667. function get_supported_languages($full_names=false)
  668. {
  669. // return array
  670. $back = array();
  671. // we walk the lang root
  672. $dir = dir($this->language_path);
  673. // foreach entry
  674. while (false !== ($entry = $dir->read()))
  675. {
  676. $full_path = $this->language_path.$entry;
  677. // Skip all dirs
  678. if (is_dir($full_path)) {
  679. continue;
  680. }
  681. // we only want lang.php files
  682. if (!preg_match('/^([^.]+)\.php$/', $entry, $matches)) {
  683. continue;
  684. }
  685. // Raw lang name is here
  686. $langname = $matches[1];
  687. // We want the fullname too?
  688. if ($full_names === true)
  689. {
  690. if (false !== ($fullname = $this->get_language_fullname($langname)))
  691. {
  692. $back[$langname] = $fullname; // we go associative
  693. }
  694. }
  695. else
  696. {
  697. // just store raw langname
  698. $back[] = $langname;
  699. }
  700. }
  701. $dir->close();
  702. return $back;
  703. }
  704. /**
  705. * Get full_name for a lang or false.
  706. * @param string $language short langname (html4strict for example)
  707. * @return mixed
  708. */
  709. function get_language_fullname($language)
  710. {
  711. //Clean up the language name to prevent malicious code injection
  712. $language = preg_replace('#[^a-zA-Z0-9\-_]#', '', $language);
  713. $language = strtolower($language);
  714. // get fullpath-filename for a langname
  715. $fullpath = $this->language_path.$language.'.php';
  716. // we need to get contents :S
  717. if (false === ($data = file_get_contents($fullpath))) {
  718. $this->error = sprintf('Geshi::get_lang_fullname() Unknown Language: %s', $language);
  719. return false;
  720. }
  721. // match the langname
  722. if (!preg_match('/\'LANG_NAME\'\s*=>\s*\'((?:[^\']|\\\')+)\'/', $data, $matches)) {
  723. $this->error = sprintf('Geshi::get_lang_fullname(%s): Regex can not detect language', $language);
  724. return false;
  725. }
  726. // return fullname for langname
  727. return stripcslashes($matches[1]);
  728. }
  729. /**
  730. * Sets the type of header to be used.
  731. *
  732. * If GESHI_HEADER_DIV is used, the code is surrounded in a "div".This
  733. * means more source code but more control over tab width and line-wrapping.
  734. * GESHI_HEADER_PRE means that a "pre" is used - less source, but less
  735. * control. Default is GESHI_HEADER_PRE.
  736. *
  737. * From 1.0.7.2, you can use GESHI_HEADER_NONE to specify that no header code
  738. * should be outputted.
  739. *
  740. * @param int The type of header to be used
  741. * @since 1.0.0
  742. */
  743. function set_header_type($type) {
  744. //Check if we got a valid header type
  745. if (!in_array($type, array(GESHI_HEADER_NONE, GESHI_HEADER_DIV,
  746. GESHI_HEADER_PRE, GESHI_HEADER_PRE_VALID, GESHI_HEADER_PRE_TABLE))) {
  747. $this->error = GESHI_ERROR_INVALID_HEADER_TYPE;
  748. return;
  749. }
  750. //Set that new header type
  751. $this->header_type = $type;
  752. }
  753. /**
  754. * Sets the styles for the code that will be outputted
  755. * when this object is parsed. The style should be a
  756. * string of valid stylesheet declarations
  757. *
  758. * @param string The overall style for the outputted code block
  759. * @param boolean Whether to merge the styles with the current styles or not
  760. * @since 1.0.0
  761. */
  762. function set_overall_style($style, $preserve_defaults = false) {
  763. if (!$preserve_defaults) {
  764. $this->overall_style = $style;
  765. } else {
  766. $this->overall_style .= $style;
  767. }
  768. }
  769. /**
  770. * Sets the overall classname for this block of code. This
  771. * class can then be used in a stylesheet to style this object's
  772. * output
  773. *
  774. * @param string The class name to use for this block of code
  775. * @since 1.0.0
  776. */
  777. function set_overall_class($class) {
  778. $this->overall_class = $class;
  779. }
  780. /**
  781. * Sets the overall id for this block of code. This id can then
  782. * be used in a stylesheet to style this object's output
  783. *
  784. * @param string The ID to use for this block of code
  785. * @since 1.0.0
  786. */
  787. function set_overall_id($id) {
  788. $this->overall_id = $id;
  789. }
  790. /**
  791. * Sets whether CSS classes should be used to highlight the source. Default
  792. * is off, calling this method with no arguments will turn it on
  793. *
  794. * @param boolean Whether to turn classes on or not
  795. * @since 1.0.0
  796. */
  797. function enable_classes($flag = true) {
  798. $this->use_classes = ($flag) ? true : false;
  799. }
  800. /**
  801. * Sets the style for the actual code. This should be a string
  802. * containing valid stylesheet declarations. If $preserve_defaults is
  803. * true, then styles are merged with the default styles, with the
  804. * user defined styles having priority
  805. *
  806. * Note: Use this method to override any style changes you made to
  807. * the line numbers if you are using line numbers, else the line of
  808. * code will have the same style as the line number! Consult the
  809. * GeSHi documentation for more information about this.
  810. *
  811. * @param string The style to use for actual code
  812. * @param boolean Whether to merge the current styles with the new styles
  813. * @since 1.0.2
  814. */
  815. function set_code_style($style, $preserve_defaults = false) {
  816. if (!$preserve_defaults) {
  817. $this->code_style = $style;
  818. } else {
  819. $this->code_style .= $style;
  820. }
  821. }
  822. /**
  823. * Sets the styles for the line numbers.
  824. *
  825. * @param string The style for the line numbers that are "normal"
  826. * @param string|boolean If a string, this is the style of the line
  827. * numbers that are "fancy", otherwise if boolean then this
  828. * defines whether the normal styles should be merged with the
  829. * new normal styles or not
  830. * @param boolean If set, is the flag for whether to merge the "fancy"
  831. * styles with the current styles or not
  832. * @since 1.0.2
  833. */
  834. function set_line_style($style1, $style2 = '', $preserve_defaults = false) {
  835. //Check if we got 2 or three parameters
  836. if (is_bool($style2)) {
  837. $preserve_defaults = $style2;
  838. $style2 = '';
  839. }
  840. //Actually set the new styles
  841. if (!$preserve_defaults) {
  842. $this->line_style1 = $style1;
  843. $this->line_style2 = $style2;
  844. } else {
  845. $this->line_style1 .= $style1;
  846. $this->line_style2 .= $style2;
  847. }
  848. }
  849. /**
  850. * Sets whether line numbers should be displayed.
  851. *
  852. * Valid values for the first parameter are:
  853. *
  854. * - GESHI_NO_LINE_NUMBERS: Line numbers will not be displayed
  855. * - GESHI_NORMAL_LINE_NUMBERS: Line numbers will be displayed
  856. * - GESHI_FANCY_LINE_NUMBERS: Fancy line numbers will be displayed
  857. *
  858. * For fancy line numbers, the second parameter is used to signal which lines
  859. * are to be fancy. For example, if the value of this parameter is 5 then every
  860. * 5th line will be fancy.
  861. *
  862. * @param int How line numbers should be displayed
  863. * @param int Defines which lines are fancy
  864. * @since 1.0.0
  865. */
  866. function enable_line_numbers($flag, $nth_row = 5) {
  867. if (GESHI_NO_LINE_NUMBERS != $flag && GESHI_NORMAL_LINE_NUMBERS != $flag
  868. && GESHI_FANCY_LINE_NUMBERS != $flag) {
  869. $this->error = GESHI_ERROR_INVALID_LINE_NUMBER_TYPE;
  870. }
  871. $this->line_numbers = $flag;
  872. $this->line_nth_row = $nth_row;
  873. }
  874. /**
  875. * Sets wether spans and other HTML markup generated by GeSHi can
  876. * span over multiple lines or not. Defaults to true to reduce overhead.
  877. * Set it to false if you want to manipulate the output or manually display
  878. * the code in an ordered list.
  879. *
  880. * @param boolean Wether multiline spans are allowed or not
  881. * @since 1.0.7.22
  882. */
  883. function enable_multiline_span($flag) {
  884. $this->allow_multiline_span = (bool) $flag;
  885. }
  886. /**
  887. * Get current setting for multiline spans, see GeSHi->enable_multiline_span().
  888. *
  889. * @see enable_multiline_span
  890. * @return bool
  891. */
  892. function get_multiline_span() {
  893. return $this->allow_multiline_span;
  894. }
  895. /**
  896. * Sets the style for a keyword group. If $preserve_defaults is
  897. * true, then styles are merged with the default styles, with the
  898. * user defined styles having priority
  899. *
  900. * @param int The key of the keyword group to change the styles of
  901. * @param string The style to make the keywords
  902. * @param boolean Whether to merge the new styles with the old or just
  903. * to overwrite them
  904. * @since 1.0.0
  905. */
  906. function set_keyword_group_style($key, $style, $preserve_defaults = false) {
  907. //Set the style for this keyword group
  908. if (!$preserve_defaults) {
  909. $this->language_data['STYLES']['KEYWORDS'][$key] = $style;
  910. } else {
  911. $this->language_data['STYLES']['KEYWORDS'][$key] .= $style;
  912. }
  913. //Update the lexic permissions
  914. if (!isset($this->lexic_permissions['KEYWORDS'][$key])) {
  915. $this->lexic_permissions['KEYWORDS'][$key] = true;
  916. }
  917. }
  918. /**
  919. * Turns highlighting on/off for a keyword group
  920. *
  921. * @param int The key of the keyword group to turn on or off
  922. * @param boolean Whether to turn highlighting for that group on or off
  923. * @since 1.0.0
  924. */
  925. function set_keyword_group_highlighting($key, $flag = true) {
  926. $this->lexic_permissions['KEYWORDS'][$key] = ($flag) ? true : false;
  927. }
  928. /**
  929. * Sets the styles for comment groups. If $preserve_defaults is
  930. * true, then styles are merged with the default styles, with the
  931. * user defined styles having priority
  932. *
  933. * @param int The key of the comment group to change the styles of
  934. * @param string The style to make the comments
  935. * @param boolean Whether to merge the new styles with the old or just
  936. * to overwrite them
  937. * @since 1.0.0
  938. */
  939. function set_comments_style($key, $style, $preserve_defaults = false) {
  940. if (!$preserve_defaults) {
  941. $this->language_data['STYLES']['COMMENTS'][$key] = $style;
  942. } else {
  943. $this->language_data['STYLES']['COMMENTS'][$key] .= $style;
  944. }
  945. }
  946. /**
  947. * Turns highlighting on/off for comment groups
  948. *
  949. * @param int The key of the comment group to turn on or off
  950. * @param boolean Whether to turn highlighting for that group on or off
  951. * @since 1.0.0
  952. */
  953. function set_comments_highlighting($key, $flag = true) {
  954. $this->lexic_permissions['COMMENTS'][$key] = ($flag) ? true : false;
  955. }
  956. /**
  957. * Sets the styles for escaped characters. If $preserve_defaults is
  958. * true, then styles are merged with the default styles, with the
  959. * user defined styles having priority
  960. *
  961. * @param string The style to make the escape characters
  962. * @param boolean Whether to merge the new styles with the old or just
  963. * to overwrite them
  964. * @since 1.0.0
  965. */
  966. function set_escape_characters_style($style, $preserve_defaults = false, $group = 0) {
  967. if (!$preserve_defaults) {
  968. $this->language_data['STYLES']['ESCAPE_CHAR'][$group] = $style;
  969. } else {
  970. $this->language_data['STYLES']['ESCAPE_CHAR'][$group] .= $style;
  971. }
  972. }
  973. /**
  974. * Turns highlighting on/off for escaped characters
  975. *
  976. * @param boolean Whether to turn highlighting for escape characters on or off
  977. * @since 1.0.0
  978. */
  979. function set_escape_characters_highlighting($flag = true) {
  980. $this->lexic_permissions['ESCAPE_CHAR'] = ($flag) ? true : false;
  981. }
  982. /**
  983. * Sets the styles for brackets. If $preserve_defaults is
  984. * true, then styles are merged with the default styles, with the
  985. * user defined styles having priority
  986. *
  987. * This method is DEPRECATED: use set_symbols_style instead.
  988. * This method will be removed in 1.2.X
  989. *
  990. * @param string The style to make the brackets
  991. * @param boolean Whether to merge the new styles with the old or just
  992. * to overwrite them
  993. * @since 1.0.0
  994. * @deprecated In favour of set_symbols_style
  995. */
  996. function set_brackets_style($style, $preserve_defaults = false) {
  997. if (!$preserve_defaults) {
  998. $this->language_data['STYLES']['BRACKETS'][0] = $style;
  999. } else {
  1000. $this->language_data['STYLES']['BRACKETS'][0] .= $style;
  1001. }
  1002. }
  1003. /**
  1004. * Turns highlighting on/off for brackets
  1005. *
  1006. * This method is DEPRECATED: use set_symbols_highlighting instead.
  1007. * This method will be remove in 1.2.X
  1008. *
  1009. * @param boolean Whether to turn highlighting for brackets on or off
  1010. * @since 1.0.0
  1011. * @deprecated In favour of set_symbols_highlighting
  1012. */
  1013. function set_brackets_highlighting($flag) {
  1014. $this->lexic_permissions['BRACKETS'] = ($flag) ? true : false;
  1015. }
  1016. /**
  1017. * Sets the styles for symbols. If $preserve_defaults is
  1018. * true, then styles are merged with the default styles, with the
  1019. * user defined styles having priority
  1020. *
  1021. * @param string The style to make the symbols
  1022. * @param boolean Whether to merge the new styles with the old or just
  1023. * to overwrite them
  1024. * @param int Tells the group of symbols for which style should be set.
  1025. * @since 1.0.1
  1026. */
  1027. function set_symbols_style($style, $preserve_defaults = false, $group = 0) {
  1028. // Update the style of symbols
  1029. if (!$preserve_defaults) {
  1030. $this->language_data['STYLES']['SYMBOLS'][$group] = $style;
  1031. } else {
  1032. $this->language_data['STYLES']['SYMBOLS'][$group] .= $style;
  1033. }
  1034. // For backward compatibility
  1035. if (0 == $group) {
  1036. $this->set_brackets_style ($style, $preserve_defaults);
  1037. }
  1038. }
  1039. /**
  1040. * Turns highlighting on/off for symbols
  1041. *
  1042. * @param boolean Whether to turn highlighting for symbols on or off
  1043. * @since 1.0.0
  1044. */
  1045. function set_symbols_highlighting($flag) {
  1046. // Update lexic permissions for this symbol group
  1047. $this->lexic_permissions['SYMBOLS'] = ($flag) ? true : false;
  1048. // For backward compatibility
  1049. $this->set_brackets_highlighting ($flag);
  1050. }
  1051. /**
  1052. * Sets the styles for strings. If $preserve_defaults is
  1053. * true, then styles are merged with the default styles, with the
  1054. * user defined styles having priority
  1055. *
  1056. * @param string The style to make the escape characters
  1057. * @param boolean Whether to merge the new styles with the old or just
  1058. * to overwrite them
  1059. * @param int Tells the group of strings for which style should be set.
  1060. * @since 1.0.0
  1061. */
  1062. function set_strings_style($style, $preserve_defaults = false, $group = 0) {
  1063. if (!$preserve_defaults) {
  1064. $this->language_data['STYLES']['STRINGS'][$group] = $style;
  1065. } else {
  1066. $this->language_data['STYLES']['STRINGS'][$group] .= $style;
  1067. }
  1068. }
  1069. /**
  1070. * Turns highlighting on/off for strings
  1071. *
  1072. * @param boolean Whether to turn highlighting for strings on or off
  1073. * @since 1.0.0
  1074. */
  1075. function set_strings_highlighting($flag) {
  1076. $this->lexic_permissions['STRINGS'] = ($flag) ? true : false;
  1077. }
  1078. /**
  1079. * Sets the styles for strict code blocks. If $preserve_defaults is
  1080. * true, then styles are merged with the default styles, with the
  1081. * user defined styles having priority
  1082. *
  1083. * @param string The style to make the script blocks
  1084. * @param boolean Whether to merge the new styles with the old or just
  1085. * to overwrite them
  1086. * @param int Tells the group of script blocks for which style should be set.
  1087. * @since 1.0.8.4
  1088. */
  1089. function set_script_style($style, $preserve_defaults = false, $group = 0) {
  1090. // Update the style of symbols
  1091. if (!$preserve_defaults) {
  1092. $this->language_data['STYLES']['SCRIPT'][$group] = $style;
  1093. } else {
  1094. $this->language_data['STYLES']['SCRIPT'][$group] .= $style;
  1095. }
  1096. }
  1097. /**
  1098. * Sets the styles for numbers. If $preserve_defaults is
  1099. * true, then styles are merged with the default styles, with the
  1100. * user defined styles having priority
  1101. *
  1102. * @param string The style to make the numbers
  1103. * @param boolean Whether to merge the new styles with the old or just
  1104. * to overwrite them
  1105. * @param int Tells the group of numbers for which style should be set.
  1106. * @since 1.0.0
  1107. */
  1108. function set_numbers_style($style, $preserve_defaults = false, $group = 0) {
  1109. if (!$preserve_defaults) {
  1110. $this->language_data['STYLES']['NUMBERS'][$group] = $style;
  1111. } else {
  1112. $this->language_data['STYLES']['NUMBERS'][$group] .= $style;
  1113. }
  1114. }
  1115. /**
  1116. * Turns highlighting on/off for numbers
  1117. *
  1118. * @param boolean Whether to turn highlighting for numbers on or off
  1119. * @since 1.0.0
  1120. */
  1121. function set_numbers_highlighting($flag) {
  1122. $this->lexic_permissions['NUMBERS'] = ($flag) ? true : false;
  1123. }
  1124. /**
  1125. * Sets the styles for methods. $key is a number that references the
  1126. * appropriate "object splitter" - see the language file for the language
  1127. * you are highlighting to get this number. If $preserve_defaults is
  1128. * true, then styles are merged with the default styles, with the
  1129. * user defined styles having priority
  1130. *
  1131. * @param int The key of the object splitter to change the styles of
  1132. * @param string The style to make the methods
  1133. * @param boolean Whether to merge the new styles with the old or just
  1134. * to overwrite them
  1135. * @since 1.0.0
  1136. */
  1137. function set_methods_style($key, $style, $preserve_defaults = false) {
  1138. if (!$preserve_defaults) {
  1139. $this->language_data['STYLES']['METHODS'][$key] = $style;
  1140. } else {
  1141. $this->language_data['STYLES']['METHODS'][$key] .= $style;
  1142. }
  1143. }
  1144. /**
  1145. * Turns highlighting on/off for methods
  1146. *
  1147. * @param boolean Whether to turn highlighting for methods on or off
  1148. * @since 1.0.0
  1149. */
  1150. function set_methods_highlighting($flag) {
  1151. $this->lexic_permissions['METHODS'] = ($flag) ? true : false;
  1152. }
  1153. /**
  1154. * Sets the styles for regexps. If $preserve_defaults is
  1155. * true, then styles are merged with the default styles, with the
  1156. * user defined styles having priority
  1157. *
  1158. * @param string The style to make the regular expression matches
  1159. * @param boolean Whether to merge the new styles with the old or just
  1160. * to overwrite them
  1161. * @since 1.0.0
  1162. */
  1163. function set_regexps_style($key, $style, $preserve_defaults = false) {
  1164. if (!$preserve_defaults) {
  1165. $this->language_data['STYLES']['REGEXPS'][$key] = $style;
  1166. } else {
  1167. $this->language_data['STYLES']['REGEXPS'][$key] .= $style;
  1168. }
  1169. }
  1170. /**
  1171. * Turns highlighting on/off for regexps
  1172. *
  1173. * @param int The key of the regular expression group to turn on or off
  1174. * @param boolean Whether to turn highlighting for the regular expression group on or off
  1175. * @since 1.0.0
  1176. */
  1177. function set_regexps_highlighting($key, $flag) {
  1178. $this->lexic_permissions['REGEXPS'][$key] = ($flag) ? true : false;
  1179. }
  1180. /**
  1181. * Sets whether a set of keywords are checked for in a case sensitive manner
  1182. *
  1183. * @param int The key of the keyword group to change the case sensitivity of
  1184. * @param boolean Whether to check in a case sensitive manner or not
  1185. * @since 1.0.0
  1186. */
  1187. function set_case_sensitivity($key, $case) {
  1188. $this->language_data['CASE_SENSITIVE'][$key] = ($case) ? true : false;
  1189. }
  1190. /**
  1191. * Sets the case that keywords should use when found. Use the constants:
  1192. *
  1193. * - GESHI_CAPS_NO_CHANGE: leave keywords as-is
  1194. * - GESHI_CAPS_UPPER: convert all keywords to uppercase where found
  1195. * - GESHI_CAPS_LOWER: convert all keywords to lowercase where found
  1196. *
  1197. * @param int A constant specifying what to do with matched keywords
  1198. * @since 1.0.1
  1199. */
  1200. function set_case_keywords($case) {
  1201. if (in_array($case, array(
  1202. GESHI_CAPS_NO_CHANGE, GESHI_CAPS_UPPER, GESHI_CAPS_LOWER))) {
  1203. $this->language_data['CASE_KEYWORDS'] = $case;
  1204. }
  1205. }
  1206. /**
  1207. * Sets how many spaces a tab is substituted for
  1208. *
  1209. * Widths below zero are ignored
  1210. *
  1211. * @param int The tab width
  1212. * @since 1.0.0
  1213. */
  1214. function set_tab_width($width) {
  1215. $this->tab_width = intval($width);
  1216. //Check if it fit's the constraints:
  1217. if ($this->tab_width < 1) {
  1218. //Return it to the default
  1219. $this->tab_width = 8;
  1220. }
  1221. }
  1222. /**
  1223. * Sets whether or not to use tab-stop width specifed by language
  1224. *
  1225. * @param boolean Whether to use language-specific tab-stop widths
  1226. * @since 1.0.7.20
  1227. */
  1228. function set_use_language_tab_width($use) {
  1229. $this->use_language_tab_width = (bool) $use;
  1230. }
  1231. /**
  1232. * Returns the tab width to use, based on the current language and user
  1233. * preference
  1234. *
  1235. * @return int Tab width
  1236. * @since 1.0.7.20
  1237. */
  1238. function get_real_tab_width() {
  1239. if (!$this->use_language_tab_width ||
  1240. !isset($this->language_data['TAB_WIDTH'])) {
  1241. return $this->tab_width;
  1242. } else {
  1243. return $this->language_data['TAB_WIDTH'];
  1244. }
  1245. }
  1246. /**
  1247. * Enables/disables strict highlighting. Default is off, calling this
  1248. * method without parameters will turn it on. See documentation
  1249. * for more details on strict mode and where to use it.
  1250. *
  1251. * @param boolean Whether to enable strict mode or not
  1252. * @since 1.0.0
  1253. */
  1254. function enable_strict_mode($mode = true) {
  1255. if (GESHI_MAYBE == $this->language_data['STRICT_MODE_APPLIES']) {
  1256. $this->strict_mode = ($mode) ? GESHI_ALWAYS : GESHI_NEVER;
  1257. }
  1258. }
  1259. /**
  1260. * Disables all highlighting
  1261. *
  1262. * @since 1.0.0
  1263. * @todo Rewrite with array traversal
  1264. * @deprecated In favour of enable_highlighting
  1265. */
  1266. function disable_highlighting() {
  1267. $this->enable_highlighting(false);
  1268. }
  1269. /**
  1270. * Enables all highlighting
  1271. *
  1272. * The optional flag parameter was added in version 1.0.7.21 and can be used
  1273. * to enable (true) or disable (false) all highlighting.
  1274. *
  1275. * @since 1.0.0
  1276. * @param boolean A flag specifying whether to enable or disable all highlighting
  1277. * @todo Rewrite with array traversal
  1278. */
  1279. function enable_highlighting($flag = true) {
  1280. $flag = $flag ? true : false;
  1281. foreach ($this->lexic_permissions as $key => $value) {
  1282. if (is_array($value)) {
  1283. foreach ($value as $k => $v) {
  1284. $this->lexic_permissions[$key][$k] = $flag;
  1285. }
  1286. } else {
  1287. $this->lexic_permissions[$key] = $flag;
  1288. }
  1289. }
  1290. // Context blocks
  1291. $this->enable_important_blocks = $flag;
  1292. }
  1293. /**
  1294. * Given a file extension, this method returns either a valid geshi language
  1295. * name, or the empty string if it couldn't be found
  1296. *
  1297. * @param string The extension to get a language name for
  1298. * @param array A lookup array to use instead of the default one
  1299. * @since 1.0.5
  1300. * @todo Re-think about how this method works (maybe make it private and/or make it
  1301. * a extension->lang lookup?)
  1302. * @todo static?
  1303. */
  1304. function get_language_name_from_extension( $extension, $lookup = array() ) {
  1305. if ( !is_array($lookup) || empty($lookup)) {
  1306. $lookup = array(
  1307. '6502acme' => array( 'a', 's', 'asm', 'inc' ),
  1308. '6502tasm' => array( 'a', 's', 'asm', 'inc' ),
  1309. '6502kickass' => array( 'a', 's', 'asm', 'inc' ),
  1310. '68000devpac' => array( 'a', 's', 'asm', 'inc' ),
  1311. 'abap' => array('abap'),
  1312. 'actionscript' => array('as'),
  1313. 'ada' => array('a', 'ada', 'adb', 'ads'),
  1314. 'apache' => array('conf'),
  1315. 'asm' => array('ash', 'asm', 'inc'),
  1316. 'asp' => array('asp'),
  1317. 'bash' => array('sh'),
  1318. 'bf' => array('bf'),
  1319. 'c' => array('c', 'h'),
  1320. 'c_mac' => array('c', 'h'),
  1321. 'caddcl' => array(),
  1322. 'cadlisp' => array(),
  1323. 'cdfg' => array('cdfg'),
  1324. 'cobol' => array('cbl'),
  1325. 'cpp' => array('cpp', 'hpp', 'C', 'H', 'CPP', 'HPP'),
  1326. 'csharp' => array('cs'),
  1327. 'css' => array('css'),
  1328. 'd' => array('d'),
  1329. 'delphi' => array('dpk', 'dpr', 'pp', 'pas'),
  1330. 'diff' => array('diff', 'patch'),
  1331. 'dos' => array('bat', 'cmd'),
  1332. 'gdb' => array('kcrash', 'crash', 'bt'),
  1333. 'gettext' => array('po', 'pot'),
  1334. 'gml' => array('gml'),
  1335. 'gnuplot' => array('plt'),
  1336. 'groovy' => array('groovy'),
  1337. 'haskell' => array('hs'),
  1338. 'html4strict' => array('html', 'htm'),
  1339. 'ini' => array('ini', 'desktop'),
  1340. 'java' => array('java'),
  1341. 'javascript' => array('js'),
  1342. 'klonec' => array('kl1'),
  1343. 'klonecpp' => array('klx'),
  1344. 'latex' => array('tex'),
  1345. 'lisp' => array('lisp'),
  1346. 'lua' => array('lua'),
  1347. 'matlab' => array('m'),
  1348. 'mpasm' => array(),
  1349. 'mysql' => array('sql'),
  1350. 'nsis' => array(),
  1351. 'objc' => array(),
  1352. 'oobas' => array(),
  1353. 'oracle8' => array(),
  1354. 'oracle10' => array(),
  1355. 'pascal' => array('pas'),
  1356. 'perl' => array('pl', 'pm'),
  1357. 'php' => array('php', 'php5', 'phtml', 'phps'),
  1358. 'povray' => array('pov'),
  1359. 'providex' => array('pvc', 'pvx'),
  1360. 'prolog' => array('pl'),
  1361. 'python' => array('py'),
  1362. 'qbasic' => array('bi'),
  1363. 'reg' => array('reg'),
  1364. 'ruby' => array('rb'),
  1365. 'sas' => array('sas'),
  1366. 'scala' => array('scala'),
  1367. 'scheme' => array('scm'),
  1368. 'scilab' => array('sci'),
  1369. 'smalltalk' => array('st'),
  1370. 'smarty' => array(),
  1371. 'tcl' => array('tcl'),
  1372. 'vb' => array('bas'),
  1373. 'vbnet' => array(),
  1374. 'visualfoxpro' => array(),
  1375. 'whitespace' => array('ws'),
  1376. 'xml' => array('xml', 'svg', 'xrc'),
  1377. 'z80' => array('z80', 'asm', 'inc')
  1378. );
  1379. }
  1380. foreach ($lookup as $lang => $extensions) {
  1381. if (in_array($extension, $extensions)) {
  1382. return $lang;
  1383. }
  1384. }
  1385. return '';
  1386. }
  1387. /**
  1388. * Given a file name, this method loads its contents in, and attempts
  1389. * to set the language automatically. An optional lookup table can be
  1390. * passed for looking up the language name. If not specified a default
  1391. * table is used
  1392. *
  1393. * The language table is in the form
  1394. * <pre>array(
  1395. * 'lang_name' => array('extension', 'extension', ...),
  1396. * 'lang_name' ...
  1397. * );</pre>
  1398. *
  1399. * @param string The filename to load the source from
  1400. * @param array A lookup array to use instead of the default one
  1401. * @todo Complete rethink of this and above method
  1402. * @since 1.0.5
  1403. */
  1404. function load_from_file($file_name, $lookup = array()) {
  1405. if (is_readable($file_name)) {
  1406. $this->set_source(file_get_contents($file_name));
  1407. $this->set_language($this->get_language_name_from_extension(substr(strrchr($file_name, '.'), 1), $lookup));
  1408. } else {
  1409. $this->error = GESHI_ERROR_FILE_NOT_READABLE;
  1410. }
  1411. }
  1412. /**
  1413. * Adds a keyword to a keyword group for highlighting
  1414. *
  1415. * @param int The key of the keyword group to add the keyword to
  1416. * @param string The word to add to the keyword group
  1417. * @since 1.0.0
  1418. */
  1419. function add_keyword($key, $word) {
  1420. if (!in_array($word, $this->language_data['KEYWORDS'][$key])) {
  1421. $this->language_data['KEYWORDS'][$key][] = $word;
  1422. //NEW in 1.0.8 don't recompile the whole optimized regexp, simply append it
  1423. if ($this->parse_cache_built) {
  1424. $subkey = count($this->language_data['CACHED_KEYWORD_LISTS'][$key]) - 1;
  1425. $this->language_data['CACHED_KEYWORD_LISTS'][$key][$subkey] .= '|' . preg_quote($word, '/');
  1426. }
  1427. }
  1428. }
  1429. /**
  1430. * Removes a keyword from a keyword group
  1431. *
  1432. * @param int The key of the keyword group to remove the keyword from
  1433. * @param string The word to remove from the keyword group
  1434. * @param bool Wether to automatically recompile the optimized regexp list or not.
  1435. * Note: if you set this to false and @see GeSHi->parse_code() was already called once,
  1436. * for the current language, you have to manually call @see GeSHi->optimize_keyword_group()
  1437. * or the removed keyword will stay in cache and still be highlighted! On the other hand
  1438. * it might be too expensive to recompile the regexp list for every removal if you want to
  1439. * remove a lot of keywords.
  1440. * @since 1.0.0
  1441. */
  1442. function remove_keyword($key, $word, $recompile = true) {
  1443. $key_to_remove = array_search($word, $this->language_data['KEYWORDS'][$key]);
  1444. if ($key_to_remove !== false) {
  1445. unset($this->language_data['KEYWORDS'][$key][$key_to_remove]);
  1446. //NEW in 1.0.8, optionally recompile keyword group
  1447. if ($recompile && $this->parse_cache_built) {
  1448. $this->optimize_keyword_group($key);
  1449. }
  1450. }
  1451. }
  1452. /**
  1453. * Creates a new keyword group
  1454. *
  1455. * @param int The key of the keyword group to create
  1456. * @param string The styles for the keyword group
  1457. * @param boolean Whether the keyword group is case sensitive ornot
  1458. * @param array The words to use for the keyword group
  1459. * @since 1.0.0
  1460. */
  1461. function add_keyword_group($key, $styles, $case_sensitive = true, $words = array()) {
  1462. $words = (array) $words;
  1463. if (empty($words)) {
  1464. // empty word lists mess up highlighting
  1465. return false;
  1466. }
  1467. //Add the new keyword group internally
  1468. $this->language_data['KEYWORDS'][$key] = $words;
  1469. $this->lexic_permissions['KEYWORDS'][$key] = true;
  1470. $this->language_data['CASE_SENSITIVE'][$key] = $case_sensitive;
  1471. $this->language_data['STYLES']['KEYWORDS'][$key] = $styles;
  1472. //NEW in 1.0.8, cache keyword regexp
  1473. if ($this->parse_cache_built) {
  1474. $this->optimize_keyword_group($key);
  1475. }
  1476. }
  1477. /**
  1478. * Removes a keyword group
  1479. *
  1480. * @param int The key of the keyword group to remove
  1481. * @since 1.0.0
  1482. */
  1483. function remove_keyword_group ($key) {
  1484. //Remove the keyword group internally
  1485. unset($this->language_data['KEYWORDS'][$key]);
  1486. unset($this->lexic_permissions['KEYWORDS'][$key]);
  1487. unset($this->language_data['CASE_SENSITIVE'][$key]);
  1488. unset($this->language_data['STYLES']['KEYWORDS'][$key]);
  1489. //NEW in 1.0.8
  1490. unset($this->language_data['CACHED_KEYWORD_LISTS'][$key]);
  1491. }
  1492. /**
  1493. * compile optimized regexp list for keyword group
  1494. *
  1495. * @param int The key of the keyword group to compile & optimize
  1496. * @since 1.0.8
  1497. */
  1498. function optimize_keyword_group($key) {
  1499. $this->language_data['CACHED_KEYWORD_LISTS'][$key] =
  1500. $this->optimize_regexp_list($this->language_data['KEYWORDS'][$key]);
  1501. $space_as_whitespace = false;
  1502. if(isset($this->language_data['PARSER_CONTROL'])) {
  1503. if(isset($this->language_data['PARSER_CONTROL']['KEYWORDS'])) {
  1504. if(isset($this->language_data['PARSER_CONTROL']['KEYWORDS']['SPACE_AS_WHITESPACE'])) {
  1505. $space_as_whitespace = $this->language_data['PARSER_CONTROL']['KEYWORDS']['SPACE_AS_WHITESPACE'];
  1506. }
  1507. if(isset($this->language_data['PARSER_CONTROL']['KEYWORDS'][$key]['SPACE_AS_WHITESPACE'])) {
  1508. if(isset($this->language_data['PARSER_CONTROL']['KEYWORDS'][$key]['SPACE_AS_WHITESPACE'])) {
  1509. $space_as_whitespace = $this->language_data['PARSER_CONTROL']['KEYWORDS'][$key]['SPACE_AS_WHITESPACE'];
  1510. }
  1511. }
  1512. }
  1513. }
  1514. if($space_as_whitespace) {
  1515. foreach($this->language_data['CACHED_KEYWORD_LISTS'][$key] as $rxk => $rxv) {
  1516. $this->language_data['CACHED_KEYWORD_LISTS'][$key][$rxk] =
  1517. str_replace(" ", "\\s+", $rxv);
  1518. }
  1519. }
  1520. }
  1521. /**
  1522. * Sets the content of the header block
  1523. *
  1524. * @param string The content of the header block
  1525. * @since 1.0.2
  1526. */
  1527. function set_header_content($content) {
  1528. $this->header_content = $content;
  1529. }
  1530. /**
  1531. * Sets the content of the footer block
  1532. *
  1533. * @param string The content of the footer block
  1534. * @since 1.0.2
  1535. */
  1536. function set_footer_content($content) {
  1537. $this->footer_content = $content;
  1538. }
  1539. /**
  1540. * Sets the style for the header content
  1541. *
  1542. * @param string The style for the header content
  1543. * @since 1.0.2
  1544. */
  1545. function set_header_content_style($style) {
  1546. $this->header_content_style = $style;
  1547. }
  1548. /**
  1549. * Sets the style for the footer content
  1550. *
  1551. * @param string The style for the footer content
  1552. * @since 1.0.2
  1553. */
  1554. function set_footer_content_style($style) {
  1555. $this->footer_content_style = $style;
  1556. }
  1557. /**
  1558. * Sets whether to force a surrounding block around
  1559. * the highlighted code or not
  1560. *
  1561. * @param boolean Tells whether to enable or disable this feature
  1562. * @since 1.0.7.20
  1563. */
  1564. function enable_inner_code_block($flag) {
  1565. $this->force_code_block = (bool)$flag;
  1566. }
  1567. /**
  1568. * Sets the base URL to be used for keywords
  1569. *
  1570. * @param int The key of the keyword group to set the URL for
  1571. * @param string The URL to set for the group. If {FNAME} is in
  1572. * the url somewhere, it is replaced by the keyword
  1573. * that the URL is being made for
  1574. * @since 1.0.2
  1575. */
  1576. function set_url_for_keyword_group($group, $url) {
  1577. $this->language_data['URLS'][$group] = $url;
  1578. }
  1579. /**
  1580. * Sets styles for links in code
  1581. *
  1582. * @param int A constant that specifies what state the style is being
  1583. * set for - e.g. :hover or :visited
  1584. * @param string The styles to use for that state
  1585. * @since 1.0.2
  1586. */
  1587. function set_link_styles($type, $styles) {
  1588. $this->link_styles[$type] = $styles;
  1589. }
  1590. /**
  1591. * Sets the target for links in code
  1592. *
  1593. * @param string The target for links in the code, e.g. _blank
  1594. * @since 1.0.3
  1595. */
  1596. function set_link_target($target) {
  1597. if (!$target) {
  1598. $this->link_target = '';
  1599. } else {
  1600. $this->link_target = ' target="' . $target . '"';
  1601. }
  1602. }
  1603. /**
  1604. * Sets styles for important parts of the code
  1605. *
  1606. * @param string The styles to use on important parts of the code
  1607. * @since 1.0.2
  1608. */
  1609. function set_important_styles($styles) {
  1610. $this->important_styles = $styles;
  1611. }
  1612. /**
  1613. * Sets whether context-important blocks are highlighted
  1614. *
  1615. * @param boolean Tells whether to enable or disable highlighting of important blocks
  1616. * @todo REMOVE THIS SHIZ FROM GESHI!
  1617. * @deprecated
  1618. * @since 1.0.2
  1619. */
  1620. function enable_important_blocks($flag) {
  1621. $this->enable_important_blocks = ( $flag ) ? true : false;
  1622. }
  1623. /**
  1624. * Whether CSS IDs should be added to each line
  1625. *
  1626. * @param boolean If true, IDs will be added to each line.
  1627. * @since 1.0.2
  1628. */
  1629. function enable_ids($flag = true) {
  1630. $this->add_ids = ($flag) ? true : false;
  1631. }
  1632. /**
  1633. * Specifies which lines to highlight extra
  1634. *
  1635. * The extra style parameter was added in 1.0.7.21.
  1636. *
  1637. * @param mixed An array of line numbers to highlight, or just a line
  1638. * number on its own.
  1639. * @param string A string specifying the style to use for this line.
  1640. * If null is specified, the default style is used.
  1641. * If false is specified, the line will be removed from
  1642. * special highlighting
  1643. * @since 1.0.2
  1644. * @todo Some data replication here that could be cut down on
  1645. */
  1646. function highlight_lines_extra($lines, $style = null) {
  1647. if (is_array($lines)) {
  1648. //Split up the job using single lines at a time
  1649. foreach ($lines as $line) {
  1650. $this->highlight_lines_extra($line, $style);
  1651. }
  1652. } else {
  1653. //Mark the line as being highlighted specially
  1654. $lines = intval($lines);
  1655. $this->highlight_extra_lines[$lines] = $lines;
  1656. //Decide on which style to use
  1657. if ($style === null) { //Check if we should use default style
  1658. unset($this->highlight_extra_lines_styles[$lines]);
  1659. } elseif ($style === false) { //Check if to remove this line
  1660. unset($this->highlight_extra_lines[$lines]);
  1661. unset($this->highlight_extra_lines_styles[$lines]);
  1662. } else {
  1663. $this->highlight_extra_lines_styles[$lines] = $style;
  1664. }
  1665. }
  1666. }
  1667. /**
  1668. * Sets the style for extra-highlighted lines
  1669. *
  1670. * @param string The style for extra-highlighted lines
  1671. * @since 1.0.2
  1672. */
  1673. function set_highlight_lines_extra_style($styles) {
  1674. $this->highlight_extra_lines_style = $styles;
  1675. }
  1676. /**
  1677. * Sets the line-ending
  1678. *
  1679. * @param string The new line-ending
  1680. * @since 1.0.2
  1681. */
  1682. function set_line_ending($line_ending) {
  1683. $this->line_ending = (string)$line_ending;
  1684. }
  1685. /**
  1686. * Sets what number line numbers should start at. Should
  1687. * be a positive integer, and will be converted to one.
  1688. *
  1689. * <b>Warning:</b> Using this method will add the "start"
  1690. * attribute to the &lt;ol&gt; that is used for line numbering.
  1691. * This is <b>not</b> valid XHTML strict, so if that's what you
  1692. * care about then don't use this method. Firefox is getting
  1693. * support for the CSS method of doing this in 1.1 and Opera
  1694. * has support for the CSS method, but (of course) IE doesn't
  1695. * so it's not worth doing it the CSS way yet.
  1696. *
  1697. * @param int The number to start line numbers at
  1698. * @since 1.0.2
  1699. */
  1700. function start_line_numbers_at($number) {
  1701. $this->line_numbers_start = abs(intval($number));
  1702. }
  1703. /**
  1704. * Sets the encoding used for htmlspecialchars(), for international
  1705. * support.
  1706. *
  1707. * NOTE: This is not needed for now because htmlspecialchars() is not
  1708. * being used (it has a security hole in PHP4 that has not been patched).
  1709. * Maybe in a future version it may make a return for speed reasons, but
  1710. * I doubt it.
  1711. *
  1712. * @param string The encoding to use for the source
  1713. * @since 1.0.3
  1714. */
  1715. function set_encoding($encoding) {
  1716. if ($encoding) {
  1717. $this->encoding = strtolower($encoding);
  1718. }
  1719. }
  1720. /**
  1721. * Turns linking of keywords on or off.
  1722. *
  1723. * @param boolean If true, links will be added to keywords
  1724. * @since 1.0.2
  1725. */
  1726. function enable_keyword_links($enable = true) {
  1727. $this->keyword_links = (bool) $enable;
  1728. }
  1729. /**
  1730. * Setup caches needed for styling. This is automatically called in
  1731. * parse_code() and get_stylesheet() when appropriate. This function helps
  1732. * stylesheet generators as they rely on some style information being
  1733. * preprocessed
  1734. *
  1735. * @since 1.0.8
  1736. * @access private
  1737. */
  1738. function build_style_cache() {
  1739. //Build the style cache needed to highlight numbers appropriate
  1740. if($this->lexic_permissions['NUMBERS']) {
  1741. //First check what way highlighting information for numbers are given
  1742. if(!isset($this->language_data['NUMBERS'])) {
  1743. $this->language_data['NUMBERS'] = 0;
  1744. }
  1745. if(is_array($this->language_data['NUMBERS'])) {
  1746. $this->language_data['NUMBERS_CACHE'] = $this->language_data['NUMBERS'];
  1747. } else {
  1748. $this->language_data['NUMBERS_CACHE'] = array();
  1749. if(!$this->language_data['NUMBERS']) {
  1750. $this->language_data['NUMBERS'] =
  1751. GESHI_NUMBER_INT_BASIC |
  1752. GESHI_NUMBER_FLT_NONSCI;
  1753. }
  1754. for($i = 0, $j = $this->language_data['NUMBERS']; $j > 0; ++$i, $j>>=1) {
  1755. //Rearrange style indices if required ...
  1756. if(isset($this->language_data['STYLES']['NUMBERS'][1<<$i])) {
  1757. $this->language_data['STYLES']['NUMBERS'][$i] =
  1758. $this->language_data['STYLES']['NUMBERS'][1<<$i];
  1759. unset($this->language_data['STYLES']['NUMBERS'][1<<$i]);
  1760. }
  1761. //Check if this bit is set for highlighting
  1762. if($j&1) {
  1763. //So this bit is set ...
  1764. //Check if it belongs to group 0 or the actual stylegroup
  1765. if(isset($this->language_data['STYLES']['NUMBERS'][$i])) {
  1766. $this->language_data['NUMBERS_CACHE'][$i] = 1 << $i;
  1767. } else {
  1768. if(!isset($this->language_data['NUMBERS_CACHE'][0])) {
  1769. $this->language_data['NUMBERS_CACHE'][0] = 0;
  1770. }
  1771. $this->language_data['NUMBERS_CACHE'][0] |= 1 << $i;
  1772. }
  1773. }
  1774. }
  1775. }
  1776. }
  1777. }
  1778. /**
  1779. * Setup caches needed for parsing. This is automatically called in parse_code() when appropriate.
  1780. * This function makes stylesheet generators much faster as they do not need these caches.
  1781. *
  1782. * @since 1.0.8
  1783. * @access private
  1784. */
  1785. function build_parse_cache() {
  1786. // cache symbol regexp
  1787. //As this is a costy operation, we avoid doing it for multiple groups ...
  1788. //Instead we perform it for all symbols at once.
  1789. //
  1790. //For this to work, we need to reorganize the data arrays.
  1791. if ($this->lexic_permissions['SYMBOLS'] && !empty($this->language_data['SYMBOLS'])) {
  1792. $this->language_data['MULTIPLE_SYMBOL_GROUPS'] = count($this->language_data['STYLES']['SYMBOLS']) > 1;
  1793. $this->language_data['SYMBOL_DATA'] = array();
  1794. $symbol_preg_multi = array(); // multi char symbols
  1795. $symbol_preg_single = array(); // single char symbols
  1796. foreach ($this->language_data['SYMBOLS'] as $key => $symbols) {
  1797. if (is_array($symbols)) {
  1798. foreach ($symbols as $sym) {
  1799. $sym = $this->hsc($sym);
  1800. if (!isset($this->language_data['SYMBOL_DATA'][$sym])) {
  1801. $this->language_data['SYMBOL_DATA'][$sym] = $key;
  1802. if (isset($sym[1])) { // multiple chars
  1803. $symbol_preg_multi[] = preg_quote($sym, '/');
  1804. } else { // single char
  1805. if ($sym == '-') {
  1806. // don't trigger range out of order error
  1807. $symbol_preg_single[] = '\-';
  1808. } else {
  1809. $symbol_preg_single[] = preg_quote($sym, '/');
  1810. }
  1811. }
  1812. }
  1813. }
  1814. } else {
  1815. $symbols = $this->hsc($symbols);
  1816. if (!isset($this->language_data['SYMBOL_DATA'][$symbols])) {
  1817. $this->language_data['SYMBOL_DATA'][$symbols] = 0;
  1818. if (isset($symbols[1])) { // multiple chars
  1819. $symbol_preg_multi[] = preg_quote($symbols, '/');
  1820. } elseif ($symbols == '-') {
  1821. // don't trigger range out of order error
  1822. $symbol_preg_single[] = '\-';
  1823. } else { // single char
  1824. $symbol_preg_single[] = preg_quote($symbols, '/');
  1825. }
  1826. }
  1827. }
  1828. }
  1829. //Now we have an array with each possible symbol as the key and the style as the actual data.
  1830. //This way we can set the correct style just the moment we highlight ...
  1831. //
  1832. //Now we need to rewrite our array to get a search string that
  1833. $symbol_preg = array();
  1834. if (!empty($symbol_preg_multi)) {
  1835. rsort($symbol_preg_multi);
  1836. $symbol_preg[] = implode('|', $symbol_preg_multi);
  1837. }
  1838. if (!empty($symbol_preg_single)) {
  1839. rsort($symbol_preg_single);
  1840. $symbol_preg[] = '[' . implode('', $symbol_preg_single) . ']';
  1841. }
  1842. $this->language_data['SYMBOL_SEARCH'] = implode("|", $symbol_preg);
  1843. }
  1844. // cache optimized regexp for keyword matching
  1845. // remove old cache
  1846. $this->language_data['CACHED_KEYWORD_LISTS'] = array();
  1847. foreach (array_keys($this->language_data['KEYWORDS']) as $key) {
  1848. if (!isset($this->lexic_permissions['KEYWORDS'][$key]) ||
  1849. $this->lexic_permissions['KEYWORDS'][$key]) {
  1850. $this->optimize_keyword_group($key);
  1851. }
  1852. }
  1853. // brackets
  1854. if ($this->lexic_permissions['BRACKETS']) {
  1855. $this->language_data['CACHE_BRACKET_MATCH'] = array('[', ']', '(', ')', '{', '}');
  1856. if (!$this->use_classes && isset($this->language_data['STYLES']['BRACKETS'][0])) {
  1857. $this->language_data['CACHE_BRACKET_REPLACE'] = array(
  1858. '<| style="' . $this->language_data['STYLES']['BRACKETS'][0] . '">&#91;|>',
  1859. '<| style="' . $this->language_data['STYLES']['BRACKETS'][0] . '">&#93;|>',
  1860. '<| style="' . $this->language_data['STYLES']['BRACKETS'][0] . '">&#40;|>',
  1861. '<| style="' . $this->language_data['STYLES']['BRACKETS'][0] . '">&#41;|>',
  1862. '<| style="' . $this->language_data['STYLES']['BRACKETS'][0] . '">&#123;|>',
  1863. '<| style="' . $this->language_data['STYLES']['BRACKETS'][0] . '">&#125;|>',
  1864. );
  1865. }
  1866. else {
  1867. $this->language_data['CACHE_BRACKET_REPLACE'] = array(
  1868. '<| class="br0">&#91;|>',
  1869. '<| class="br0">&#93;|>',
  1870. '<| class="br0">&#40;|>',
  1871. '<| class="br0">&#41;|>',
  1872. '<| class="br0">&#123;|>',
  1873. '<| class="br0">&#125;|>',
  1874. );
  1875. }
  1876. }
  1877. //Build the parse cache needed to highlight numbers appropriate
  1878. if($this->lexic_permissions['NUMBERS']) {
  1879. //Check if the style rearrangements have been processed ...
  1880. //This also does some preprocessing to check which style groups are useable ...
  1881. if(!isset($this->language_data['NUMBERS_CACHE'])) {
  1882. $this->build_style_cache();
  1883. }
  1884. //Number format specification
  1885. //All this formats are matched case-insensitively!
  1886. static $numbers_format = array(
  1887. GESHI_NUMBER_INT_BASIC =>
  1888. '(?:(?<![0-9a-z_\.%$@])|(?<=\.\.))(?<![\d\.]e[+\-])([1-9]\d*?|0)(?![0-9a-z]|\.(?:[eE][+\-]?)?\d)',
  1889. GESHI_NUMBER_INT_CSTYLE =>
  1890. '(?<![0-9a-z_\.%])(?<![\d\.]e[+\-])([1-9]\d*?|0)l(?![0-9a-z]|\.(?:[eE][+\-]?)?\d)',
  1891. GESHI_NUMBER_BIN_SUFFIX =>
  1892. '(?<![0-9a-z_\.])(?<![\d\.]e[+\-])[01]+?[bB](?![0-9a-z]|\.(?:[eE][+\-]?)?\d)',
  1893. GESHI_NUMBER_BIN_PREFIX_PERCENT =>
  1894. '(?<![0-9a-z_\.%])(?<![\d\.]e[+\-])%[01]+?(?![0-9a-z]|\.(?:[eE][+\-]?)?\d)',
  1895. GESHI_NUMBER_BIN_PREFIX_0B =>
  1896. '(?<![0-9a-z_\.%])(?<![\d\.]e[+\-])0b[01]+?(?![0-9a-z]|\.(?:[eE][+\-]?)?\d)',
  1897. GESHI_NUMBER_OCT_PREFIX =>
  1898. '(?<![0-9a-z_\.])(?<![\d\.]e[+\-])0[0-7]+?(?![0-9a-z]|\.(?:[eE][+\-]?)?\d)',
  1899. GESHI_NUMBER_OCT_PREFIX_0O =>
  1900. '(?<![0-9a-z_\.%])(?<![\d\.]e[+\-])0o[0-7]+?(?![0-9a-z]|\.(?:[eE][+\-]?)?\d)',
  1901. GESHI_NUMBER_OCT_PREFIX_AT =>
  1902. '(?<![0-9a-z_\.%])(?<![\d\.]e[+\-])\@[0-7]+?(?![0-9a-z]|\.(?:[eE][+\-]?)?\d)',
  1903. GESHI_NUMBER_OCT_SUFFIX =>
  1904. '(?<![0-9a-z_\.])(?<![\d\.]e[+\-])[0-7]+?o(?![0-9a-z]|\.(?:[eE][+\-]?)?\d)',
  1905. GESHI_NUMBER_HEX_PREFIX =>
  1906. '(?<![0-9a-z_\.])(?<![\d\.]e[+\-])0x[0-9a-fA-F]+?(?![0-9a-z]|\.(?:[eE][+\-]?)?\d)',
  1907. GESHI_NUMBER_HEX_PREFIX_DOLLAR =>
  1908. '(?<![0-9a-z_\.])(?<![\d\.]e[+\-])\$[0-9a-fA-F]+?(?![0-9a-z]|\.(?:[eE][+\-]?)?\d)',
  1909. GESHI_NUMBER_HEX_SUFFIX =>
  1910. '(?<![0-9a-z_\.])(?<![\d\.]e[+\-])\d[0-9a-fA-F]*?[hH](?![0-9a-z]|\.(?:[eE][+\-]?)?\d)',
  1911. GESHI_NUMBER_FLT_NONSCI =>
  1912. '(?<![0-9a-z_\.])(?<![\d\.]e[+\-])\d+?\.\d+?(?![0-9a-z]|\.(?:[eE][+\-]?)?\d)',
  1913. GESHI_NUMBER_FLT_NONSCI_F =>
  1914. '(?<![0-9a-z_\.])(?<![\d\.]e[+\-])(?:\d+?(?:\.\d*?)?|\.\d+?)f(?![0-9a-z]|\.(?:[eE][+\-]?)?\d)',
  1915. GESHI_NUMBER_FLT_SCI_SHORT =>
  1916. '(?<![0-9a-z_\.])(?<![\d\.]e[+\-])\.\d+?(?:e[+\-]?\d+?)?(?![0-9a-z]|\.(?:[eE][+\-]?)?\d)',
  1917. GESHI_NUMBER_FLT_SCI_ZERO =>
  1918. '(?<![0-9a-z_\.])(?<![\d\.]e[+\-])(?:\d+?(?:\.\d*?)?|\.\d+?)(?:e[+\-]?\d+?)?(?![0-9a-z]|\.(?:[eE][+\-]?)?\d)'
  1919. );
  1920. //At this step we have an associative array with flag groups for a
  1921. //specific style or an string denoting a regexp given its index.
  1922. $this->language_data['NUMBERS_RXCACHE'] = array();
  1923. foreach($this->language_data['NUMBERS_CACHE'] as $key => $rxdata) {
  1924. if(is_string($rxdata)) {
  1925. $regexp = $rxdata;
  1926. } else {
  1927. //This is a bitfield of number flags to highlight:
  1928. //Build an array, implode them together and make this the actual RX
  1929. $rxuse = array();
  1930. for($i = 1; $i <= $rxdata; $i<<=1) {
  1931. if($rxdata & $i) {
  1932. $rxuse[] = $numbers_format[$i];
  1933. }
  1934. }
  1935. $regexp = implode("|", $rxuse);
  1936. }
  1937. $this->language_data['NUMBERS_RXCACHE'][$key] =
  1938. "/(?<!<\|\/)(?<!<\|!REG3XP)(?<!<\|\/NUM!)(?<!\d\/>)($regexp)(?!(?:<DOT>|(?>[^\<]))+>)(?![^<]*>)(?!\|>)(?!\/>)/i"; //
  1939. }
  1940. if(!isset($this->language_data['PARSER_CONTROL']['NUMBERS']['PRECHECK_RX'])) {
  1941. $this->language_data['PARSER_CONTROL']['NUMBERS']['PRECHECK_RX'] = '#\d#';
  1942. }
  1943. }
  1944. $this->parse_cache_built = true;
  1945. }
  1946. /**
  1947. * Returns the code in $this->source, highlighted and surrounded by the
  1948. * nessecary HTML.
  1949. *
  1950. * This should only be called ONCE, cos it's SLOW! If you want to highlight
  1951. * the same source multiple times, you're better off doing a whole lot of
  1952. * str_replaces to replace the &lt;span&gt;s
  1953. *
  1954. * @since 1.0.0
  1955. */
  1956. function parse_code () {
  1957. // Start the timer
  1958. $start_time = microtime();
  1959. // Replace all newlines to a common form.
  1960. $code = str_replace("\r\n", "\n", $this->source);
  1961. $code = str_replace("\r", "\n", $code);
  1962. // Firstly, if there is an error, we won't highlight
  1963. if ($this->error) {
  1964. //Escape the source for output
  1965. $result = $this->hsc($this->source);
  1966. //This fix is related to SF#1923020, but has to be applied regardless of
  1967. //actually highlighting symbols.
  1968. $result = str_replace(array('<SEMI>', '<PIPE>'), array(';', '|'), $result);
  1969. // Timing is irrelevant
  1970. $this->set_time($start_time, $start_time);
  1971. $this->finalise($result);
  1972. return $result;
  1973. }
  1974. // make sure the parse cache is up2date
  1975. if (!$this->parse_cache_built) {
  1976. $this->build_parse_cache();
  1977. }
  1978. // Initialise various stuff
  1979. $length = strlen($code);
  1980. $COMMENT_MATCHED = false;
  1981. $stuff_to_parse = '';
  1982. $endresult = '';
  1983. // "Important" selections are handled like multiline comments
  1984. // @todo GET RID OF THIS SHIZ
  1985. if ($this->enable_important_blocks) {
  1986. $this->language_data['COMMENT_MULTI'][GESHI_START_IMPORTANT] = GESHI_END_IMPORTANT;
  1987. }
  1988. if ($this->strict_mode) {
  1989. // Break the source into bits. Each bit will be a portion of the code
  1990. // within script delimiters - for example, HTML between < and >
  1991. $k = 0;
  1992. $parts = array();
  1993. $matches = array();
  1994. $next_match_pointer = null;
  1995. // we use a copy to unset delimiters on demand (when they are not found)
  1996. $delim_copy = $this->language_data['SCRIPT_DELIMITERS'];
  1997. $i = 0;
  1998. while ($i < $length) {
  1999. $next_match_pos = $length + 1; // never true
  2000. foreach ($delim_copy as $dk => $delimiters) {
  2001. if(is_array($delimiters)) {
  2002. foreach ($delimiters as $open => $close) {
  2003. // make sure the cache is setup properly
  2004. if (!isset($matches[$dk][$open])) {
  2005. $matches[$dk][$open] = array(
  2006. 'next_match' => -1,
  2007. 'dk' => $dk,
  2008. 'open' => $open, // needed for grouping of adjacent code blocks (see below)
  2009. 'open_strlen' => strlen($open),
  2010. 'close' => $close,
  2011. 'close_strlen' => strlen($close),
  2012. );
  2013. }
  2014. // Get the next little bit for this opening string
  2015. if ($matches[$dk][$open]['next_match'] < $i) {
  2016. // only find the next pos if it was not already cached
  2017. $open_pos = strpos($code, $open, $i);
  2018. if ($open_pos === false) {
  2019. // no match for this delimiter ever
  2020. unset($delim_copy[$dk][$open]);
  2021. continue;
  2022. }
  2023. $matches[$dk][$open]['next_match'] = $open_pos;
  2024. }
  2025. if ($matches[$dk][$open]['next_match'] < $next_match_pos) {
  2026. //So we got a new match, update the close_pos
  2027. $matches[$dk][$open]['close_pos'] =
  2028. strpos($code, $close, $matches[$dk][$open]['next_match']+1);
  2029. $next_match_pointer =& $matches[$dk][$open];
  2030. $next_match_pos = $matches[$dk][$open]['next_match'];
  2031. }
  2032. }
  2033. } else {
  2034. //So we should match an RegExp as Strict Block ...
  2035. /**
  2036. * The value in $delimiters is expected to be an RegExp
  2037. * containing exactly 2 matching groups:
  2038. * - Group 1 is the opener
  2039. * - Group 2 is the closer
  2040. */
  2041. if(!GESHI_PHP_PRE_433 && //Needs proper rewrite to work with PHP >=4.3.0; 4.3.3 is guaranteed to work.
  2042. preg_match($delimiters, $code, $matches_rx, PREG_OFFSET_CAPTURE, $i)) {
  2043. //We got a match ...
  2044. if(isset($matches_rx['start']) && isset($matches_rx['end']))
  2045. {
  2046. $matches[$dk] = array(
  2047. 'next_match' => $matches_rx['start'][1],
  2048. 'dk' => $dk,
  2049. 'close_strlen' => strlen($matches_rx['end'][0]),
  2050. 'close_pos' => $matches_rx['end'][1],
  2051. );
  2052. } else {
  2053. $matches[$dk] = array(
  2054. 'next_match' => $matches_rx[1][1],
  2055. 'dk' => $dk,
  2056. 'close_strlen' => strlen($matches_rx[2][0]),
  2057. 'close_pos' => $matches_rx[2][1],
  2058. );
  2059. }
  2060. } else {
  2061. // no match for this delimiter ever
  2062. unset($delim_copy[$dk]);
  2063. continue;
  2064. }
  2065. if ($matches[$dk]['next_match'] <= $next_match_pos) {
  2066. $next_match_pointer =& $matches[$dk];
  2067. $next_match_pos = $matches[$dk]['next_match'];
  2068. }
  2069. }
  2070. }
  2071. // non-highlightable text
  2072. $parts[$k] = array(
  2073. 1 => substr($code, $i, $next_match_pos - $i)
  2074. );
  2075. ++$k;
  2076. if ($next_match_pos > $length) {
  2077. // out of bounds means no next match was found
  2078. break;
  2079. }
  2080. // highlightable code
  2081. $parts[$k][0] = $next_match_pointer['dk'];
  2082. //Only combine for non-rx script blocks
  2083. if(is_array($delim_copy[$next_match_pointer['dk']])) {
  2084. // group adjacent script blocks, e.g. <foobar><asdf> should be one block, not three!
  2085. $i = $next_match_pos + $next_match_pointer['open_strlen'];
  2086. while (true) {
  2087. $close_pos = strpos($code, $next_match_pointer['close'], $i);
  2088. if ($close_pos == false) {
  2089. break;
  2090. }
  2091. $i = $close_pos + $next_match_pointer['close_strlen'];
  2092. if ($i == $length) {
  2093. break;
  2094. }
  2095. if ($code[$i] == $next_match_pointer['open'][0] && ($next_match_pointer['open_strlen'] == 1 ||
  2096. substr($code, $i, $next_match_pointer['open_strlen']) == $next_match_pointer['open'])) {
  2097. // merge adjacent but make sure we don't merge things like <tag><!-- comment -->
  2098. foreach ($matches as $submatches) {
  2099. foreach ($submatches as $match) {
  2100. if ($match['next_match'] == $i) {
  2101. // a different block already matches here!
  2102. break 3;
  2103. }
  2104. }
  2105. }
  2106. } else {
  2107. break;
  2108. }
  2109. }
  2110. } else {
  2111. $close_pos = $next_match_pointer['close_pos'] + $next_match_pointer['close_strlen'];
  2112. $i = $close_pos;
  2113. }
  2114. if ($close_pos === false) {
  2115. // no closing delimiter found!
  2116. $parts[$k][1] = substr($code, $next_match_pos);
  2117. ++$k;
  2118. break;
  2119. } else {
  2120. $parts[$k][1] = substr($code, $next_match_pos, $i - $next_match_pos);
  2121. ++$k;
  2122. }
  2123. }
  2124. unset($delim_copy, $next_match_pointer, $next_match_pos, $matches);
  2125. $num_parts = $k;
  2126. if ($num_parts == 1 && $this->strict_mode == GESHI_MAYBE) {
  2127. // when we have only one part, we don't have anything to highlight at all.
  2128. // if we have a "maybe" strict language, this should be handled as highlightable code
  2129. $parts = array(
  2130. 0 => array(
  2131. 0 => '',
  2132. 1 => ''
  2133. ),
  2134. 1 => array(
  2135. 0 => null,
  2136. 1 => $parts[0][1]
  2137. )
  2138. );
  2139. $num_parts = 2;
  2140. }
  2141. } else {
  2142. // Not strict mode - simply dump the source into
  2143. // the array at index 1 (the first highlightable block)
  2144. $parts = array(
  2145. 0 => array(
  2146. 0 => '',
  2147. 1 => ''
  2148. ),
  2149. 1 => array(
  2150. 0 => null,
  2151. 1 => $code
  2152. )
  2153. );
  2154. $num_parts = 2;
  2155. }
  2156. //Unset variables we won't need any longer
  2157. unset($code);
  2158. //Preload some repeatedly used values regarding hardquotes ...
  2159. $hq = isset($this->language_data['HARDQUOTE']) ? $this->language_data['HARDQUOTE'][0] : false;
  2160. $hq_strlen = strlen($hq);
  2161. //Preload if line numbers are to be generated afterwards
  2162. //Added a check if line breaks should be forced even without line numbers, fixes SF#1727398
  2163. $check_linenumbers = $this->line_numbers != GESHI_NO_LINE_NUMBERS ||
  2164. !empty($this->highlight_extra_lines) || !$this->allow_multiline_span;
  2165. //preload the escape char for faster checking ...
  2166. $escaped_escape_char = $this->hsc($this->language_data['ESCAPE_CHAR']);
  2167. // this is used for single-line comments
  2168. $sc_disallowed_before = "";
  2169. $sc_disallowed_after = "";
  2170. if (isset($this->language_data['PARSER_CONTROL'])) {
  2171. if (isset($this->language_data['PARSER_CONTROL']['COMMENTS'])) {
  2172. if (isset($this->language_data['PARSER_CONTROL']['COMMENTS']['DISALLOWED_BEFORE'])) {
  2173. $sc_disallowed_before = $this->language_data['PARSER_CONTROL']['COMMENTS']['DISALLOWED_BEFORE'];
  2174. }
  2175. if (isset($this->language_data['PARSER_CONTROL']['COMMENTS']['DISALLOWED_AFTER'])) {
  2176. $sc_disallowed_after = $this->language_data['PARSER_CONTROL']['COMMENTS']['DISALLOWED_AFTER'];
  2177. }
  2178. }
  2179. }
  2180. //Fix for SF#1932083: Multichar Quotemarks unsupported
  2181. $is_string_starter = array();
  2182. if ($this->lexic_permissions['STRINGS']) {
  2183. foreach ($this->language_data['QUOTEMARKS'] as $quotemark) {
  2184. if (!isset($is_string_starter[$quotemark[0]])) {
  2185. $is_string_starter[$quotemark[0]] = (string)$quotemark;
  2186. } elseif (is_string($is_string_starter[$quotemark[0]])) {
  2187. $is_string_starter[$quotemark[0]] = array(
  2188. $is_string_starter[$quotemark[0]],
  2189. $quotemark);
  2190. } else {
  2191. $is_string_starter[$quotemark[0]][] = $quotemark;
  2192. }
  2193. }
  2194. }
  2195. // Now we go through each part. We know that even-indexed parts are
  2196. // code that shouldn't be highlighted, and odd-indexed parts should
  2197. // be highlighted
  2198. for ($key = 0; $key < $num_parts; ++$key) {
  2199. $STRICTATTRS = '';
  2200. // If this block should be highlighted...
  2201. if (!($key & 1)) {
  2202. // Else not a block to highlight
  2203. $endresult .= $this->hsc($parts[$key][1]);
  2204. unset($parts[$key]);
  2205. continue;
  2206. }
  2207. $result = '';
  2208. $part = $parts[$key][1];
  2209. $highlight_part = true;
  2210. if ($this->strict_mode && !is_null($parts[$key][0])) {
  2211. // get the class key for this block of code
  2212. $script_key = $parts[$key][0];
  2213. $highlight_part = $this->language_data['HIGHLIGHT_STRICT_BLOCK'][$script_key];
  2214. if ($this->language_data['STYLES']['SCRIPT'][$script_key] != '' &&
  2215. $this->lexic_permissions['SCRIPT']) {
  2216. // Add a span element around the source to
  2217. // highlight the overall source block
  2218. if (!$this->use_classes &&
  2219. $this->language_data['STYLES']['SCRIPT'][$script_key] != '') {
  2220. $attributes = ' style="' . $this->language_data['STYLES']['SCRIPT'][$script_key] . '"';
  2221. } else {
  2222. $attributes = ' class="sc' . $script_key . '"';
  2223. }
  2224. $result .= "<span$attributes>";
  2225. $STRICTATTRS = $attributes;
  2226. }
  2227. }
  2228. if ($highlight_part) {
  2229. // Now, highlight the code in this block. This code
  2230. // is really the engine of GeSHi (along with the method
  2231. // parse_non_string_part).
  2232. // cache comment regexps incrementally
  2233. $next_comment_regexp_key = '';
  2234. $next_comment_regexp_pos = -1;
  2235. $next_comment_multi_pos = -1;
  2236. $next_comment_single_pos = -1;
  2237. $comment_regexp_cache_per_key = array();
  2238. $comment_multi_cache_per_key = array();
  2239. $comment_single_cache_per_key = array();
  2240. $next_open_comment_multi = '';
  2241. $next_comment_single_key = '';
  2242. $escape_regexp_cache_per_key = array();
  2243. $next_escape_regexp_key = '';
  2244. $next_escape_regexp_pos = -1;
  2245. $length = strlen($part);
  2246. for ($i = 0; $i < $length; ++$i) {
  2247. // Get the next char
  2248. $char = $part[$i];
  2249. $char_len = 1;
  2250. // update regexp comment cache if needed
  2251. if (isset($this->language_data['COMMENT_REGEXP']) && $next_comment_regexp_pos < $i) {
  2252. $next_comment_regexp_pos = $length;
  2253. foreach ($this->language_data['COMMENT_REGEXP'] as $comment_key => $regexp) {
  2254. $match_i = false;
  2255. if (isset($comment_regexp_cache_per_key[$comment_key]) &&
  2256. ($comment_regexp_cache_per_key[$comment_key]['pos'] >= $i ||
  2257. $comment_regexp_cache_per_key[$comment_key]['pos'] === false)) {
  2258. // we have already matched something
  2259. if ($comment_regexp_cache_per_key[$comment_key]['pos'] === false) {
  2260. // this comment is never matched
  2261. continue;
  2262. }
  2263. $match_i = $comment_regexp_cache_per_key[$comment_key]['pos'];
  2264. } elseif (
  2265. //This is to allow use of the offset parameter in preg_match and stay as compatible with older PHP versions as possible
  2266. (GESHI_PHP_PRE_433 && preg_match($regexp, substr($part, $i), $match, PREG_OFFSET_CAPTURE)) ||
  2267. (!GESHI_PHP_PRE_433 && preg_match($regexp, $part, $match, PREG_OFFSET_CAPTURE, $i))
  2268. ) {
  2269. $match_i = $match[0][1];
  2270. if (GESHI_PHP_PRE_433) {
  2271. $match_i += $i;
  2272. }
  2273. $comment_regexp_cache_per_key[$comment_key] = array(
  2274. 'key' => $comment_key,
  2275. 'length' => strlen($match[0][0]),
  2276. 'pos' => $match_i
  2277. );
  2278. } else {
  2279. $comment_regexp_cache_per_key[$comment_key]['pos'] = false;
  2280. continue;
  2281. }
  2282. if ($match_i !== false && $match_i < $next_comment_regexp_pos) {
  2283. $next_comment_regexp_pos = $match_i;
  2284. $next_comment_regexp_key = $comment_key;
  2285. if ($match_i === $i) {
  2286. break;
  2287. }
  2288. }
  2289. }
  2290. }
  2291. $string_started = false;
  2292. if (isset($is_string_starter[$char])) {
  2293. // Possibly the start of a new string ...
  2294. //Check which starter it was ...
  2295. //Fix for SF#1932083: Multichar Quotemarks unsupported
  2296. if (is_array($is_string_starter[$char])) {
  2297. $char_new = '';
  2298. foreach ($is_string_starter[$char] as $testchar) {
  2299. if ($testchar === substr($part, $i, strlen($testchar)) &&
  2300. strlen($testchar) > strlen($char_new)) {
  2301. $char_new = $testchar;
  2302. $string_started = true;
  2303. }
  2304. }
  2305. if ($string_started) {
  2306. $char = $char_new;
  2307. }
  2308. } else {
  2309. $testchar = $is_string_starter[$char];
  2310. if ($testchar === substr($part, $i, strlen($testchar))) {
  2311. $char = $testchar;
  2312. $string_started = true;
  2313. }
  2314. }
  2315. $char_len = strlen($char);
  2316. }
  2317. if ($string_started && ($i != $next_comment_regexp_pos)) {
  2318. // Hand out the correct style information for this string
  2319. $string_key = array_search($char, $this->language_data['QUOTEMARKS']);
  2320. if (!isset($this->language_data['STYLES']['STRINGS'][$string_key]) ||
  2321. !isset($this->language_data['STYLES']['ESCAPE_CHAR'][$string_key])) {
  2322. $string_key = 0;
  2323. }
  2324. // parse the stuff before this
  2325. $result .= $this->parse_non_string_part($stuff_to_parse);
  2326. $stuff_to_parse = '';
  2327. if (!$this->use_classes) {
  2328. $string_attributes = ' style="' . $this->language_data['STYLES']['STRINGS'][$string_key] . '"';
  2329. } else {
  2330. $string_attributes = ' class="st'.$string_key.'"';
  2331. }
  2332. // now handle the string
  2333. $string = "<span$string_attributes>" . GeSHi::hsc($char);
  2334. $start = $i + $char_len;
  2335. $string_open = true;
  2336. if(empty($this->language_data['ESCAPE_REGEXP'])) {
  2337. $next_escape_regexp_pos = $length;
  2338. }
  2339. do {
  2340. //Get the regular ending pos ...
  2341. $close_pos = strpos($part, $char, $start);
  2342. if(false === $close_pos) {
  2343. $close_pos = $length;
  2344. }
  2345. if($this->lexic_permissions['ESCAPE_CHAR']) {
  2346. // update escape regexp cache if needed
  2347. if (isset($this->language_data['ESCAPE_REGEXP']) && $next_escape_regexp_pos < $start) {
  2348. $next_escape_regexp_pos = $length;
  2349. foreach ($this->language_data['ESCAPE_REGEXP'] as $escape_key => $regexp) {
  2350. $match_i = false;
  2351. if (isset($escape_regexp_cache_per_key[$escape_key]) &&
  2352. ($escape_regexp_cache_per_key[$escape_key]['pos'] >= $start ||
  2353. $escape_regexp_cache_per_key[$escape_key]['pos'] === false)) {
  2354. // we have already matched something
  2355. if ($escape_regexp_cache_per_key[$escape_key]['pos'] === false) {
  2356. // this comment is never matched
  2357. continue;
  2358. }
  2359. $match_i = $escape_regexp_cache_per_key[$escape_key]['pos'];
  2360. } elseif (
  2361. //This is to allow use of the offset parameter in preg_match and stay as compatible with older PHP versions as possible
  2362. (GESHI_PHP_PRE_433 && preg_match($regexp, substr($part, $start), $match, PREG_OFFSET_CAPTURE)) ||
  2363. (!GESHI_PHP_PRE_433 && preg_match($regexp, $part, $match, PREG_OFFSET_CAPTURE, $start))
  2364. ) {
  2365. $match_i = $match[0][1];
  2366. if (GESHI_PHP_PRE_433) {
  2367. $match_i += $start;
  2368. }
  2369. $escape_regexp_cache_per_key[$escape_key] = array(
  2370. 'key' => $escape_key,
  2371. 'length' => strlen($match[0][0]),
  2372. 'pos' => $match_i
  2373. );
  2374. } else {
  2375. $escape_regexp_cache_per_key[$escape_key]['pos'] = false;
  2376. continue;
  2377. }
  2378. if ($match_i !== false && $match_i < $next_escape_regexp_pos) {
  2379. $next_escape_regexp_pos = $match_i;
  2380. $next_escape_regexp_key = $escape_key;
  2381. if ($match_i === $start) {
  2382. break;
  2383. }
  2384. }
  2385. }
  2386. }
  2387. //Find the next simple escape position
  2388. if('' != $this->language_data['ESCAPE_CHAR']) {
  2389. $simple_escape = strpos($part, $this->language_data['ESCAPE_CHAR'], $start);
  2390. if(false === $simple_escape) {
  2391. $simple_escape = $length;
  2392. }
  2393. } else {
  2394. $simple_escape = $length;
  2395. }
  2396. } else {
  2397. $next_escape_regexp_pos = $length;
  2398. $simple_escape = $length;
  2399. }
  2400. if($simple_escape < $next_escape_regexp_pos &&
  2401. $simple_escape < $length &&
  2402. $simple_escape < $close_pos) {
  2403. //The nexxt escape sequence is a simple one ...
  2404. $es_pos = $simple_escape;
  2405. //Add the stuff not in the string yet ...
  2406. $string .= $this->hsc(substr($part, $start, $es_pos - $start));
  2407. //Get the style for this escaped char ...
  2408. if (!$this->use_classes) {
  2409. $escape_char_attributes = ' style="' . $this->language_data['STYLES']['ESCAPE_CHAR'][0] . '"';
  2410. } else {
  2411. $escape_char_attributes = ' class="es0"';
  2412. }
  2413. //Add the style for the escape char ...
  2414. $string .= "<span$escape_char_attributes>" .
  2415. GeSHi::hsc($this->language_data['ESCAPE_CHAR']);
  2416. //Get the byte AFTER the ESCAPE_CHAR we just found
  2417. $es_char = $part[$es_pos + 1];
  2418. if ($es_char == "\n") {
  2419. // don't put a newline around newlines
  2420. $string .= "</span>\n";
  2421. $start = $es_pos + 2;
  2422. } elseif (ord($es_char) >= 128) {
  2423. //This is an non-ASCII char (UTF8 or single byte)
  2424. //This code tries to work around SF#2037598 ...
  2425. if(function_exists('mb_substr')) {
  2426. $es_char_m = mb_substr(substr($part, $es_pos+1, 16), 0, 1, $this->encoding);
  2427. $string .= $es_char_m . '</span>';
  2428. } elseif (!GESHI_PHP_PRE_433 && 'utf-8' == $this->encoding) {
  2429. if(preg_match("/[\xC2-\xDF][\x80-\xBF]".
  2430. "|\xE0[\xA0-\xBF][\x80-\xBF]".
  2431. "|[\xE1-\xEC\xEE\xEF][\x80-\xBF]{2}".
  2432. "|\xED[\x80-\x9F][\x80-\xBF]".
  2433. "|\xF0[\x90-\xBF][\x80-\xBF]{2}".
  2434. "|[\xF1-\xF3][\x80-\xBF]{3}".
  2435. "|\xF4[\x80-\x8F][\x80-\xBF]{2}/s",
  2436. $part, $es_char_m, null, $es_pos + 1)) {
  2437. $es_char_m = $es_char_m[0];
  2438. } else {
  2439. $es_char_m = $es_char;
  2440. }
  2441. $string .= $this->hsc($es_char_m) . '</span>';
  2442. } else {
  2443. $es_char_m = $this->hsc($es_char);
  2444. }
  2445. $start = $es_pos + strlen($es_char_m) + 1;
  2446. } else {
  2447. $string .= $this->hsc($es_char) . '</span>';
  2448. $start = $es_pos + 2;
  2449. }
  2450. } elseif ($next_escape_regexp_pos < $length &&
  2451. $next_escape_regexp_pos < $close_pos) {
  2452. $es_pos = $next_escape_regexp_pos;
  2453. //Add the stuff not in the string yet ...
  2454. $string .= $this->hsc(substr($part, $start, $es_pos - $start));
  2455. //Get the key and length of this match ...
  2456. $escape = $escape_regexp_cache_per_key[$next_escape_regexp_key];
  2457. $escape_str = substr($part, $es_pos, $escape['length']);
  2458. $escape_key = $escape['key'];
  2459. //Get the style for this escaped char ...
  2460. if (!$this->use_classes) {
  2461. $escape_char_attributes = ' style="' . $this->language_data['STYLES']['ESCAPE_CHAR'][$escape_key] . '"';
  2462. } else {
  2463. $escape_char_attributes = ' class="es' . $escape_key . '"';
  2464. }
  2465. //Add the style for the escape char ...
  2466. $string .= "<span$escape_char_attributes>" .
  2467. $this->hsc($escape_str) . '</span>';
  2468. $start = $es_pos + $escape['length'];
  2469. } else {
  2470. //Copy the remainder of the string ...
  2471. $string .= $this->hsc(substr($part, $start, $close_pos - $start + $char_len)) . '</span>';
  2472. $start = $close_pos + $char_len;
  2473. $string_open = false;
  2474. }
  2475. } while($string_open);
  2476. if ($check_linenumbers) {
  2477. // Are line numbers used? If, we should end the string before
  2478. // the newline and begin it again (so when <li>s are put in the source
  2479. // remains XHTML compliant)
  2480. // note to self: This opens up possibility of config files specifying
  2481. // that languages can/cannot have multiline strings???
  2482. $string = str_replace("\n", "</span>\n<span$string_attributes>", $string);
  2483. }
  2484. $result .= $string;
  2485. $string = '';
  2486. $i = $start - 1;
  2487. continue;
  2488. } elseif ($this->lexic_permissions['STRINGS'] && $hq && $hq[0] == $char &&
  2489. substr($part, $i, $hq_strlen) == $hq && ($i != $next_comment_regexp_pos)) {
  2490. // The start of a hard quoted string
  2491. if (!$this->use_classes) {
  2492. $string_attributes = ' style="' . $this->language_data['STYLES']['STRINGS']['HARD'] . '"';
  2493. $escape_char_attributes = ' style="' . $this->language_data['STYLES']['ESCAPE_CHAR']['HARD'] . '"';
  2494. } else {
  2495. $string_attributes = ' class="st_h"';
  2496. $escape_char_attributes = ' class="es_h"';
  2497. }
  2498. // parse the stuff before this
  2499. $result .= $this->parse_non_string_part($stuff_to_parse);
  2500. $stuff_to_parse = '';
  2501. // now handle the string
  2502. $string = '';
  2503. // look for closing quote
  2504. $start = $i + $hq_strlen;
  2505. while ($close_pos = strpos($part, $this->language_data['HARDQUOTE'][1], $start)) {
  2506. $start = $close_pos + 1;
  2507. if ($this->lexic_permissions['ESCAPE_CHAR'] && $part[$close_pos - 1] == $this->language_data['HARDCHAR'] &&
  2508. (($i + $hq_strlen) != ($close_pos))) { //Support empty string for HQ escapes if Starter = Escape
  2509. // make sure this quote is not escaped
  2510. foreach ($this->language_data['HARDESCAPE'] as $hardescape) {
  2511. if (substr($part, $close_pos - 1, strlen($hardescape)) == $hardescape) {
  2512. // check wether this quote is escaped or if it is something like '\\'
  2513. $escape_char_pos = $close_pos - 1;
  2514. while ($escape_char_pos > 0
  2515. && $part[$escape_char_pos - 1] == $this->language_data['HARDCHAR']) {
  2516. --$escape_char_pos;
  2517. }
  2518. if (($close_pos - $escape_char_pos) & 1) {
  2519. // uneven number of escape chars => this quote is escaped
  2520. continue 2;
  2521. }
  2522. }
  2523. }
  2524. }
  2525. // found closing quote
  2526. break;
  2527. }
  2528. //Found the closing delimiter?
  2529. if (!$close_pos) {
  2530. // span till the end of this $part when no closing delimiter is found
  2531. $close_pos = $length;
  2532. }
  2533. //Get the actual string
  2534. $string = substr($part, $i, $close_pos - $i + 1);
  2535. $i = $close_pos;
  2536. // handle escape chars and encode html chars
  2537. // (special because when we have escape chars within our string they may not be escaped)
  2538. if ($this->lexic_permissions['ESCAPE_CHAR'] && $this->language_data['ESCAPE_CHAR']) {
  2539. $start = 0;
  2540. $new_string = '';
  2541. while ($es_pos = strpos($string, $this->language_data['ESCAPE_CHAR'], $start)) {
  2542. // hmtl escape stuff before
  2543. $new_string .= $this->hsc(substr($string, $start, $es_pos - $start));
  2544. // check if this is a hard escape
  2545. foreach ($this->language_data['HARDESCAPE'] as $hardescape) {
  2546. if (substr($string, $es_pos, strlen($hardescape)) == $hardescape) {
  2547. // indeed, this is a hardescape
  2548. $new_string .= "<span$escape_char_attributes>" .
  2549. $this->hsc($hardescape) . '</span>';
  2550. $start = $es_pos + strlen($hardescape);
  2551. continue 2;
  2552. }
  2553. }
  2554. // not a hard escape, but a normal escape
  2555. // they come in pairs of two
  2556. $c = 0;
  2557. while (isset($string[$es_pos + $c]) && isset($string[$es_pos + $c + 1])
  2558. && $string[$es_pos + $c] == $this->language_data['ESCAPE_CHAR']
  2559. && $string[$es_pos + $c + 1] == $this->language_data['ESCAPE_CHAR']) {
  2560. $c += 2;
  2561. }
  2562. if ($c) {
  2563. $new_string .= "<span$escape_char_attributes>" .
  2564. str_repeat($escaped_escape_char, $c) .
  2565. '</span>';
  2566. $start = $es_pos + $c;
  2567. } else {
  2568. // this is just a single lonely escape char...
  2569. $new_string .= $escaped_escape_char;
  2570. $start = $es_pos + 1;
  2571. }
  2572. }
  2573. $string = $new_string . $this->hsc(substr($string, $start));
  2574. } else {
  2575. $string = $this->hsc($string);
  2576. }
  2577. if ($check_linenumbers) {
  2578. // Are line numbers used? If, we should end the string before
  2579. // the newline and begin it again (so when <li>s are put in the source
  2580. // remains XHTML compliant)
  2581. // note to self: This opens up possibility of config files specifying
  2582. // that languages can/cannot have multiline strings???
  2583. $string = str_replace("\n", "</span>\n<span$string_attributes>", $string);
  2584. }
  2585. $result .= "<span$string_attributes>" . $string . '</span>';
  2586. $string = '';
  2587. continue;
  2588. } else {
  2589. //Have a look for regexp comments
  2590. if ($i == $next_comment_regexp_pos) {
  2591. $COMMENT_MATCHED = true;
  2592. $comment = $comment_regexp_cache_per_key[$next_comment_regexp_key];
  2593. $test_str = $this->hsc(substr($part, $i, $comment['length']));
  2594. //@todo If remove important do remove here
  2595. if ($this->lexic_permissions['COMMENTS']['MULTI']) {
  2596. if (!$this->use_classes) {
  2597. $attributes = ' style="' . $this->language_data['STYLES']['COMMENTS'][$comment['key']] . '"';
  2598. } else {
  2599. $attributes = ' class="co' . $comment['key'] . '"';
  2600. }
  2601. $test_str = "<span$attributes>" . $test_str . "</span>";
  2602. // Short-cut through all the multiline code
  2603. if ($check_linenumbers) {
  2604. // strreplace to put close span and open span around multiline newlines
  2605. $test_str = str_replace(
  2606. "\n", "</span>\n<span$attributes>",
  2607. str_replace("\n ", "\n&nbsp;", $test_str)
  2608. );
  2609. }
  2610. }
  2611. $i += $comment['length'] - 1;
  2612. // parse the rest
  2613. $result .= $this->parse_non_string_part($stuff_to_parse);
  2614. $stuff_to_parse = '';
  2615. }
  2616. // If we haven't matched a regexp comment, try multi-line comments
  2617. if (!$COMMENT_MATCHED) {
  2618. // Is this a multiline comment?
  2619. if (!empty($this->language_data['COMMENT_MULTI']) && $next_comment_multi_pos < $i) {
  2620. $next_comment_multi_pos = $length;
  2621. foreach ($this->language_data['COMMENT_MULTI'] as $open => $close) {
  2622. $match_i = false;
  2623. if (isset($comment_multi_cache_per_key[$open]) &&
  2624. ($comment_multi_cache_per_key[$open] >= $i ||
  2625. $comment_multi_cache_per_key[$open] === false)) {
  2626. // we have already matched something
  2627. if ($comment_multi_cache_per_key[$open] === false) {
  2628. // this comment is never matched
  2629. continue;
  2630. }
  2631. $match_i = $comment_multi_cache_per_key[$open];
  2632. } elseif (($match_i = stripos($part, $open, $i)) !== false) {
  2633. $comment_multi_cache_per_key[$open] = $match_i;
  2634. } else {
  2635. $comment_multi_cache_per_key[$open] = false;
  2636. continue;
  2637. }
  2638. if ($match_i !== false && $match_i < $next_comment_multi_pos) {
  2639. $next_comment_multi_pos = $match_i;
  2640. $next_open_comment_multi = $open;
  2641. if ($match_i === $i) {
  2642. break;
  2643. }
  2644. }
  2645. }
  2646. }
  2647. if ($i == $next_comment_multi_pos) {
  2648. $open = $next_open_comment_multi;
  2649. $close = $this->language_data['COMMENT_MULTI'][$open];
  2650. $open_strlen = strlen($open);
  2651. $close_strlen = strlen($close);
  2652. $COMMENT_MATCHED = true;
  2653. $test_str_match = $open;
  2654. //@todo If remove important do remove here
  2655. if ($this->lexic_permissions['COMMENTS']['MULTI'] ||
  2656. $open == GESHI_START_IMPORTANT) {
  2657. if ($open != GESHI_START_IMPORTANT) {
  2658. if (!$this->use_classes) {
  2659. $attributes = ' style="' . $this->language_data['STYLES']['COMMENTS']['MULTI'] . '"';
  2660. } else {
  2661. $attributes = ' class="coMULTI"';
  2662. }
  2663. $test_str = "<span$attributes>" . $this->hsc($open);
  2664. } else {
  2665. if (!$this->use_classes) {
  2666. $attributes = ' style="' . $this->important_styles . '"';
  2667. } else {
  2668. $attributes = ' class="imp"';
  2669. }
  2670. // We don't include the start of the comment if it's an
  2671. // "important" part
  2672. $test_str = "<span$attributes>";
  2673. }
  2674. } else {
  2675. $test_str = $this->hsc($open);
  2676. }
  2677. $close_pos = strpos( $part, $close, $i + $open_strlen );
  2678. if ($close_pos === false) {
  2679. $close_pos = $length;
  2680. }
  2681. // Short-cut through all the multiline code
  2682. $rest_of_comment = $this->hsc(substr($part, $i + $open_strlen, $close_pos - $i - $open_strlen + $close_strlen));
  2683. if (($this->lexic_permissions['COMMENTS']['MULTI'] ||
  2684. $test_str_match == GESHI_START_IMPORTANT) &&
  2685. $check_linenumbers) {
  2686. // strreplace to put close span and open span around multiline newlines
  2687. $test_str .= str_replace(
  2688. "\n", "</span>\n<span$attributes>",
  2689. str_replace("\n ", "\n&nbsp;", $rest_of_comment)
  2690. );
  2691. } else {
  2692. $test_str .= $rest_of_comment;
  2693. }
  2694. if ($this->lexic_permissions['COMMENTS']['MULTI'] ||
  2695. $test_str_match == GESHI_START_IMPORTANT) {
  2696. $test_str .= '</span>';
  2697. }
  2698. $i = $close_pos + $close_strlen - 1;
  2699. // parse the rest
  2700. $result .= $this->parse_non_string_part($stuff_to_parse);
  2701. $stuff_to_parse = '';
  2702. }
  2703. }
  2704. // If we haven't matched a multiline comment, try single-line comments
  2705. if (!$COMMENT_MATCHED) {
  2706. // cache potential single line comment occurances
  2707. if (!empty($this->language_data['COMMENT_SINGLE']) && $next_comment_single_pos < $i) {
  2708. $next_comment_single_pos = $length;
  2709. foreach ($this->language_data['COMMENT_SINGLE'] as $comment_key => $comment_mark) {
  2710. $match_i = false;
  2711. if (isset($comment_single_cache_per_key[$comment_key]) &&
  2712. ($comment_single_cache_per_key[$comment_key] >= $i ||
  2713. $comment_single_cache_per_key[$comment_key] === false)) {
  2714. // we have already matched something
  2715. if ($comment_single_cache_per_key[$comment_key] === false) {
  2716. // this comment is never matched
  2717. continue;
  2718. }
  2719. $match_i = $comment_single_cache_per_key[$comment_key];
  2720. } elseif (
  2721. // case sensitive comments
  2722. ($this->language_data['CASE_SENSITIVE'][GESHI_COMMENTS] &&
  2723. ($match_i = stripos($part, $comment_mark, $i)) !== false) ||
  2724. // non case sensitive
  2725. (!$this->language_data['CASE_SENSITIVE'][GESHI_COMMENTS] &&
  2726. (($match_i = strpos($part, $comment_mark, $i)) !== false))) {
  2727. $comment_single_cache_per_key[$comment_key] = $match_i;
  2728. } else {
  2729. $comment_single_cache_per_key[$comment_key] = false;
  2730. continue;
  2731. }
  2732. if ($match_i !== false && $match_i < $next_comment_single_pos) {
  2733. $next_comment_single_pos = $match_i;
  2734. $next_comment_single_key = $comment_key;
  2735. if ($match_i === $i) {
  2736. break;
  2737. }
  2738. }
  2739. }
  2740. }
  2741. if ($next_comment_single_pos == $i) {
  2742. $comment_key = $next_comment_single_key;
  2743. $comment_mark = $this->language_data['COMMENT_SINGLE'][$comment_key];
  2744. $com_len = strlen($comment_mark);
  2745. // This check will find special variables like $# in bash
  2746. // or compiler directives of Delphi beginning {$
  2747. if ((empty($sc_disallowed_before) || ($i == 0) ||
  2748. (false === strpos($sc_disallowed_before, $part[$i-1]))) &&
  2749. (empty($sc_disallowed_after) || ($length <= $i + $com_len) ||
  2750. (false === strpos($sc_disallowed_after, $part[$i + $com_len]))))
  2751. {
  2752. // this is a valid comment
  2753. $COMMENT_MATCHED = true;
  2754. if ($this->lexic_permissions['COMMENTS'][$comment_key]) {
  2755. if (!$this->use_classes) {
  2756. $attributes = ' style="' . $this->language_data['STYLES']['COMMENTS'][$comment_key] . '"';
  2757. } else {
  2758. $attributes = ' class="co' . $comment_key . '"';
  2759. }
  2760. $test_str = "<span$attributes>" . $this->hsc($this->change_case($comment_mark));
  2761. } else {
  2762. $test_str = $this->hsc($comment_mark);
  2763. }
  2764. //Check if this comment is the last in the source
  2765. $close_pos = strpos($part, "\n", $i);
  2766. $oops = false;
  2767. if ($close_pos === false) {
  2768. $close_pos = $length;
  2769. $oops = true;
  2770. }
  2771. $test_str .= $this->hsc(substr($part, $i + $com_len, $close_pos - $i - $com_len));
  2772. if ($this->lexic_permissions['COMMENTS'][$comment_key]) {
  2773. $test_str .= "</span>";
  2774. }
  2775. // Take into account that the comment might be the last in the source
  2776. if (!$oops) {
  2777. $test_str .= "\n";
  2778. }
  2779. $i = $close_pos;
  2780. // parse the rest
  2781. $result .= $this->parse_non_string_part($stuff_to_parse);
  2782. $stuff_to_parse = '';
  2783. }
  2784. }
  2785. }
  2786. }
  2787. // Where are we adding this char?
  2788. if (!$COMMENT_MATCHED) {
  2789. $stuff_to_parse .= $char;
  2790. } else {
  2791. $result .= $test_str;
  2792. unset($test_str);
  2793. $COMMENT_MATCHED = false;
  2794. }
  2795. }
  2796. // Parse the last bit
  2797. $result .= $this->parse_non_string_part($stuff_to_parse);
  2798. $stuff_to_parse = '';
  2799. } else {
  2800. $result .= $this->hsc($part);
  2801. }
  2802. // Close the <span> that surrounds the block
  2803. if ($STRICTATTRS != '') {
  2804. $result = str_replace("\n", "</span>\n<span$STRICTATTRS>", $result);
  2805. $result .= '</span>';
  2806. }
  2807. $endresult .= $result;
  2808. unset($part, $parts[$key], $result);
  2809. }
  2810. //This fix is related to SF#1923020, but has to be applied regardless of
  2811. //actually highlighting symbols.
  2812. /** NOTE: memorypeak #3 */
  2813. $endresult = str_replace(array('<SEMI>', '<PIPE>'), array(';', '|'), $endresult);
  2814. // // Parse the last stuff (redundant?)
  2815. // $result .= $this->parse_non_string_part($stuff_to_parse);
  2816. // Lop off the very first and last spaces
  2817. // $result = substr($result, 1, -1);
  2818. // We're finished: stop timing
  2819. $this->set_time($start_time, microtime());
  2820. $this->finalise($endresult);
  2821. return $endresult;
  2822. }
  2823. /**
  2824. * Swaps out spaces and tabs for HTML indentation. Not needed if
  2825. * the code is in a pre block...
  2826. *
  2827. * @param string The source to indent (reference!)
  2828. * @since 1.0.0
  2829. * @access private
  2830. */
  2831. function indent(&$result) {
  2832. /// Replace tabs with the correct number of spaces
  2833. if (false !== strpos($result, "\t")) {
  2834. $lines = explode("\n", $result);
  2835. $result = null;//Save memory while we process the lines individually
  2836. $tab_width = $this->get_real_tab_width();
  2837. $tab_string = '&nbsp;' . str_repeat(' ', $tab_width);
  2838. for ($key = 0, $n = count($lines); $key < $n; $key++) {
  2839. $line = $lines[$key];
  2840. if (false === strpos($line, "\t")) {
  2841. continue;
  2842. }
  2843. $pos = 0;
  2844. $length = strlen($line);
  2845. $lines[$key] = ''; // reduce memory
  2846. $IN_TAG = false;
  2847. for ($i = 0; $i < $length; ++$i) {
  2848. $char = $line[$i];
  2849. // Simple engine to work out whether we're in a tag.
  2850. // If we are we modify $pos. This is so we ignore HTML
  2851. // in the line and only workout the tab replacement
  2852. // via the actual content of the string
  2853. // This test could be improved to include strings in the
  2854. // html so that < or > would be allowed in user's styles
  2855. // (e.g. quotes: '<' '>'; or similar)
  2856. if ($IN_TAG) {
  2857. if ('>' == $char) {
  2858. $IN_TAG = false;
  2859. }
  2860. $lines[$key] .= $char;
  2861. } elseif ('<' == $char) {
  2862. $IN_TAG = true;
  2863. $lines[$key] .= '<';
  2864. } elseif ('&' == $char) {
  2865. $substr = substr($line, $i + 3, 5);
  2866. $posi = strpos($substr, ';');
  2867. if (false === $posi) {
  2868. ++$pos;
  2869. } else {
  2870. $pos -= $posi+2;
  2871. }
  2872. $lines[$key] .= $char;
  2873. } elseif ("\t" == $char) {
  2874. $str = '';
  2875. // OPTIMISE - move $strs out. Make an array:
  2876. // $tabs = array(
  2877. // 1 => '&nbsp;',
  2878. // 2 => '&nbsp; ',
  2879. // 3 => '&nbsp; &nbsp;' etc etc
  2880. // to use instead of building a string every time
  2881. $tab_end_width = $tab_width - ($pos % $tab_width); //Moved out of the look as it doesn't change within the loop
  2882. if (($pos & 1) || 1 == $tab_end_width) {
  2883. $str .= substr($tab_string, 6, $tab_end_width);
  2884. } else {
  2885. $str .= substr($tab_string, 0, $tab_end_width+5);
  2886. }
  2887. $lines[$key] .= $str;
  2888. $pos += $tab_end_width;
  2889. if (false === strpos($line, "\t", $i + 1)) {
  2890. $lines[$key] .= substr($line, $i + 1);
  2891. break;
  2892. }
  2893. } elseif (0 == $pos && ' ' == $char) {
  2894. $lines[$key] .= '&nbsp;';
  2895. ++$pos;
  2896. } else {
  2897. $lines[$key] .= $char;
  2898. ++$pos;
  2899. }
  2900. }
  2901. }
  2902. $result = implode("\n", $lines);
  2903. unset($lines);//We don't need the lines separated beyond this --- free them!
  2904. }
  2905. // Other whitespace
  2906. // BenBE: Fix to reduce the number of replacements to be done
  2907. $result = preg_replace('/^ /m', '&nbsp;', $result);
  2908. $result = str_replace(' ', ' &nbsp;', $result);
  2909. if ($this->line_numbers == GESHI_NO_LINE_NUMBERS && $this->header_type != GESHI_HEADER_PRE_TABLE) {
  2910. if ($this->line_ending === null) {
  2911. $result = nl2br($result);
  2912. } else {
  2913. $result = str_replace("\n", $this->line_ending, $result);
  2914. }
  2915. }
  2916. }
  2917. /**
  2918. * Changes the case of a keyword for those languages where a change is asked for
  2919. *
  2920. * @param string The keyword to change the case of
  2921. * @return string The keyword with its case changed
  2922. * @since 1.0.0
  2923. * @access private
  2924. */
  2925. function change_case($instr) {
  2926. switch ($this->language_data['CASE_KEYWORDS']) {
  2927. case GESHI_CAPS_UPPER:
  2928. return strtoupper($instr);
  2929. case GESHI_CAPS_LOWER:
  2930. return strtolower($instr);
  2931. default:
  2932. return $instr;
  2933. }
  2934. }
  2935. /**
  2936. * Handles replacements of keywords to include markup and links if requested
  2937. *
  2938. * @param string The keyword to add the Markup to
  2939. * @return The HTML for the match found
  2940. * @since 1.0.8
  2941. * @access private
  2942. *
  2943. * @todo Get rid of ender in keyword links
  2944. */
  2945. function handle_keyword_replace($match) {
  2946. $k = $this->_kw_replace_group;
  2947. $keyword = $match[0];
  2948. $before = '';
  2949. $after = '';
  2950. if ($this->keyword_links) {
  2951. // Keyword links have been ebabled
  2952. if (isset($this->language_data['URLS'][$k]) &&
  2953. $this->language_data['URLS'][$k] != '') {
  2954. // There is a base group for this keyword
  2955. // Old system: strtolower
  2956. //$keyword = ( $this->language_data['CASE_SENSITIVE'][$group] ) ? $keyword : strtolower($keyword);
  2957. // New system: get keyword from language file to get correct case
  2958. if (!$this->language_data['CASE_SENSITIVE'][$k] &&
  2959. strpos($this->language_data['URLS'][$k], '{FNAME}') !== false) {
  2960. foreach ($this->language_data['KEYWORDS'][$k] as $word) {
  2961. if (strcasecmp($word, $keyword) == 0) {
  2962. break;
  2963. }
  2964. }
  2965. } else {
  2966. $word = $keyword;
  2967. }
  2968. $before = '<|UR1|"' .
  2969. str_replace(
  2970. array(
  2971. '{FNAME}',
  2972. '{FNAMEL}',
  2973. '{FNAMEU}',
  2974. '.'),
  2975. array(
  2976. str_replace('+', '%20', urlencode($this->hsc($word))),
  2977. str_replace('+', '%20', urlencode($this->hsc(strtolower($word)))),
  2978. str_replace('+', '%20', urlencode($this->hsc(strtoupper($word)))),
  2979. '<DOT>'),
  2980. $this->language_data['URLS'][$k]
  2981. ) . '">';
  2982. $after = '</a>';
  2983. }
  2984. }
  2985. return $before . '<|/'. $k .'/>' . $this->change_case($keyword) . '|>' . $after;
  2986. }
  2987. /**
  2988. * handles regular expressions highlighting-definitions with callback functions
  2989. *
  2990. * @note this is a callback, don't use it directly
  2991. *
  2992. * @param array the matches array
  2993. * @return The highlighted string
  2994. * @since 1.0.8
  2995. * @access private
  2996. */
  2997. function handle_regexps_callback($matches) {
  2998. // before: "' style=\"' . call_user_func(\"$func\", '\\1') . '\"\\1|>'",
  2999. return ' style="' . call_user_func($this->language_data['STYLES']['REGEXPS'][$this->_rx_key], $matches[1]) . '"'. $matches[1] . '|>';
  3000. }
  3001. /**
  3002. * handles newlines in REGEXPS matches. Set the _hmr_* vars before calling this
  3003. *
  3004. * @note this is a callback, don't use it directly
  3005. *
  3006. * @param array the matches array
  3007. * @return string
  3008. * @since 1.0.8
  3009. * @access private
  3010. */
  3011. function handle_multiline_regexps($matches) {
  3012. $before = $this->_hmr_before;
  3013. $after = $this->_hmr_after;
  3014. if ($this->_hmr_replace) {
  3015. $replace = $this->_hmr_replace;
  3016. $search = array();
  3017. foreach (array_keys($matches) as $k) {
  3018. $search[] = '\\' . $k;
  3019. }
  3020. $before = str_replace($search, $matches, $before);
  3021. $after = str_replace($search, $matches, $after);
  3022. $replace = str_replace($search, $matches, $replace);
  3023. } else {
  3024. $replace = $matches[0];
  3025. }
  3026. return $before
  3027. . '<|!REG3XP' . $this->_hmr_key .'!>'
  3028. . str_replace("\n", "|>\n<|!REG3XP" . $this->_hmr_key . '!>', $replace)
  3029. . '|>'
  3030. . $after;
  3031. }
  3032. /**
  3033. * Takes a string that has no strings or comments in it, and highlights
  3034. * stuff like keywords, numbers and methods.
  3035. *
  3036. * @param string The string to parse for keyword, numbers etc.
  3037. * @since 1.0.0
  3038. * @access private
  3039. * @todo BUGGY! Why? Why not build string and return?
  3040. */
  3041. function parse_non_string_part($stuff_to_parse) {
  3042. $stuff_to_parse = ' ' . $this->hsc($stuff_to_parse);
  3043. // Highlight keywords
  3044. $disallowed_before = "(?<![a-zA-Z0-9\$_\|\#|^&";
  3045. $disallowed_after = "(?![a-zA-Z0-9_\|%\\-&;";
  3046. if ($this->lexic_permissions['STRINGS']) {
  3047. $quotemarks = preg_quote(implode($this->language_data['QUOTEMARKS']), '/');
  3048. $disallowed_before .= $quotemarks;
  3049. $disallowed_after .= $quotemarks;
  3050. }
  3051. $disallowed_before .= "])";
  3052. $disallowed_after .= "])";
  3053. $parser_control_pergroup = false;
  3054. if (isset($this->language_data['PARSER_CONTROL'])) {
  3055. if (isset($this->language_data['PARSER_CONTROL']['KEYWORDS'])) {
  3056. $x = 0; // check wether per-keyword-group parser_control is enabled
  3057. if (isset($this->language_data['PARSER_CONTROL']['KEYWORDS']['DISALLOWED_BEFORE'])) {
  3058. $disallowed_before = $this->language_data['PARSER_CONTROL']['KEYWORDS']['DISALLOWED_BEFORE'];
  3059. ++$x;
  3060. }
  3061. if (isset($this->language_data['PARSER_CONTROL']['KEYWORDS']['DISALLOWED_AFTER'])) {
  3062. $disallowed_after = $this->language_data['PARSER_CONTROL']['KEYWORDS']['DISALLOWED_AFTER'];
  3063. ++$x;
  3064. }
  3065. $parser_control_pergroup = (count($this->language_data['PARSER_CONTROL']['KEYWORDS']) - $x) > 0;
  3066. }
  3067. }
  3068. foreach (array_keys($this->language_data['KEYWORDS']) as $k) {
  3069. if (!isset($this->lexic_permissions['KEYWORDS'][$k]) ||
  3070. $this->lexic_permissions['KEYWORDS'][$k]) {
  3071. $case_sensitive = $this->language_data['CASE_SENSITIVE'][$k];
  3072. $modifiers = $case_sensitive ? '' : 'i';
  3073. // NEW in 1.0.8 - per-keyword-group parser control
  3074. $disallowed_before_local = $disallowed_before;
  3075. $disallowed_after_local = $disallowed_after;
  3076. if ($parser_control_pergroup && isset($this->language_data['PARSER_CONTROL']['KEYWORDS'][$k])) {
  3077. if (isset($this->language_data['PARSER_CONTROL']['KEYWORDS'][$k]['DISALLOWED_BEFORE'])) {
  3078. $disallowed_before_local =
  3079. $this->language_data['PARSER_CONTROL']['KEYWORDS'][$k]['DISALLOWED_BEFORE'];
  3080. }
  3081. if (isset($this->language_data['PARSER_CONTROL']['KEYWORDS'][$k]['DISALLOWED_AFTER'])) {
  3082. $disallowed_after_local =
  3083. $this->language_data['PARSER_CONTROL']['KEYWORDS'][$k]['DISALLOWED_AFTER'];
  3084. }
  3085. }
  3086. $this->_kw_replace_group = $k;
  3087. //NEW in 1.0.8, the cached regexp list
  3088. // since we don't want PHP / PCRE to crash due to too large patterns we split them into smaller chunks
  3089. for ($set = 0, $set_length = count($this->language_data['CACHED_KEYWORD_LISTS'][$k]); $set < $set_length; ++$set) {
  3090. $keywordset =& $this->language_data['CACHED_KEYWORD_LISTS'][$k][$set];
  3091. // Might make a more unique string for putting the number in soon
  3092. // Basically, we don't put the styles in yet because then the styles themselves will
  3093. // get highlighted if the language has a CSS keyword in it (like CSS, for example ;))
  3094. $stuff_to_parse = preg_replace_callback(
  3095. "/$disallowed_before_local({$keywordset})(?!\<DOT\>(?:htm|php|aspx?))$disallowed_after_local/$modifiers",
  3096. array($this, 'handle_keyword_replace'),
  3097. $stuff_to_parse
  3098. );
  3099. }
  3100. }
  3101. }
  3102. // Regular expressions
  3103. foreach ($this->language_data['REGEXPS'] as $key => $regexp) {
  3104. if ($this->lexic_permissions['REGEXPS'][$key]) {
  3105. if (is_array($regexp)) {
  3106. if ($this->line_numbers != GESHI_NO_LINE_NUMBERS) {
  3107. // produce valid HTML when we match multiple lines
  3108. $this->_hmr_replace = $regexp[GESHI_REPLACE];
  3109. $this->_hmr_before = $regexp[GESHI_BEFORE];
  3110. $this->_hmr_key = $key;
  3111. $this->_hmr_after = $regexp[GESHI_AFTER];
  3112. $stuff_to_parse = preg_replace_callback(
  3113. "/" . $regexp[GESHI_SEARCH] . "/{$regexp[GESHI_MODIFIERS]}",
  3114. array($this, 'handle_multiline_regexps'),
  3115. $stuff_to_parse);
  3116. $this->_hmr_replace = false;
  3117. $this->_hmr_before = '';
  3118. $this->_hmr_after = '';
  3119. } else {
  3120. $stuff_to_parse = preg_replace(
  3121. '/' . $regexp[GESHI_SEARCH] . '/' . $regexp[GESHI_MODIFIERS],
  3122. $regexp[GESHI_BEFORE] . '<|!REG3XP'. $key .'!>' . $regexp[GESHI_REPLACE] . '|>' . $regexp[GESHI_AFTER],
  3123. $stuff_to_parse);
  3124. }
  3125. } else {
  3126. if ($this->line_numbers != GESHI_NO_LINE_NUMBERS) {
  3127. // produce valid HTML when we match multiple lines
  3128. $this->_hmr_key = $key;
  3129. $stuff_to_parse = preg_replace_callback( "/(" . $regexp . ")/",
  3130. array($this, 'handle_multiline_regexps'), $stuff_to_parse);
  3131. $this->_hmr_key = '';
  3132. } else {
  3133. $stuff_to_parse = preg_replace( "/(" . $regexp . ")/", "<|!REG3XP$key!>\\1|>", $stuff_to_parse);
  3134. }
  3135. }
  3136. }
  3137. }
  3138. // Highlight numbers. As of 1.0.8 we support different types of numbers
  3139. $numbers_found = false;
  3140. if ($this->lexic_permissions['NUMBERS'] && preg_match($this->language_data['PARSER_CONTROL']['NUMBERS']['PRECHECK_RX'], $stuff_to_parse )) {
  3141. $numbers_found = true;
  3142. //For each of the formats ...
  3143. foreach($this->language_data['NUMBERS_RXCACHE'] as $id => $regexp) {
  3144. //Check if it should be highlighted ...
  3145. $stuff_to_parse = preg_replace($regexp, "<|/NUM!$id/>\\1|>", $stuff_to_parse);
  3146. }
  3147. }
  3148. //
  3149. // Now that's all done, replace /[number]/ with the correct styles
  3150. //
  3151. foreach (array_keys($this->language_data['KEYWORDS']) as $k) {
  3152. if (!$this->use_classes) {
  3153. $attributes = ' style="' .
  3154. (isset($this->language_data['STYLES']['KEYWORDS'][$k]) ?
  3155. $this->language_data['STYLES']['KEYWORDS'][$k] : "") . '"';
  3156. } else {
  3157. $attributes = ' class="kw' . $k . '"';
  3158. }
  3159. $stuff_to_parse = str_replace("<|/$k/>", "<|$attributes>", $stuff_to_parse);
  3160. }
  3161. if ($numbers_found) {
  3162. // Put number styles in
  3163. foreach($this->language_data['NUMBERS_RXCACHE'] as $id => $regexp) {
  3164. //Commented out for now, as this needs some review ...
  3165. // if ($numbers_permissions & $id) {
  3166. //Get the appropriate style ...
  3167. //Checking for unset styles is done by the style cache builder ...
  3168. if (!$this->use_classes) {
  3169. $attributes = ' style="' . $this->language_data['STYLES']['NUMBERS'][$id] . '"';
  3170. } else {
  3171. $attributes = ' class="nu'.$id.'"';
  3172. }
  3173. //Set in the correct styles ...
  3174. $stuff_to_parse = str_replace("/NUM!$id/", $attributes, $stuff_to_parse);
  3175. // }
  3176. }
  3177. }
  3178. // Highlight methods and fields in objects
  3179. if ($this->lexic_permissions['METHODS'] && $this->language_data['OOLANG']) {
  3180. $oolang_spaces = "[\s]*";
  3181. $oolang_before = "";
  3182. $oolang_after = "[a-zA-Z][a-zA-Z0-9_]*";
  3183. if (isset($this->language_data['PARSER_CONTROL'])) {
  3184. if (isset($this->language_data['PARSER_CONTROL']['OOLANG'])) {
  3185. if (isset($this->language_data['PARSER_CONTROL']['OOLANG']['MATCH_BEFORE'])) {
  3186. $oolang_before = $this->language_data['PARSER_CONTROL']['OOLANG']['MATCH_BEFORE'];
  3187. }
  3188. if (isset($this->language_data['PARSER_CONTROL']['OOLANG']['MATCH_AFTER'])) {
  3189. $oolang_after = $this->language_data['PARSER_CONTROL']['OOLANG']['MATCH_AFTER'];
  3190. }
  3191. if (isset($this->language_data['PARSER_CONTROL']['OOLANG']['MATCH_SPACES'])) {
  3192. $oolang_spaces = $this->language_data['PARSER_CONTROL']['OOLANG']['MATCH_SPACES'];
  3193. }
  3194. }
  3195. }
  3196. foreach ($this->language_data['OBJECT_SPLITTERS'] as $key => $splitter) {
  3197. if (false !== strpos($stuff_to_parse, $splitter)) {
  3198. if (!$this->use_classes) {
  3199. $attributes = ' style="' . $this->language_data['STYLES']['METHODS'][$key] . '"';
  3200. } else {
  3201. $attributes = ' class="me' . $key . '"';
  3202. }
  3203. $stuff_to_parse = preg_replace("/($oolang_before)(" . preg_quote($this->language_data['OBJECT_SPLITTERS'][$key], '/') . ")($oolang_spaces)($oolang_after)/", "\\1\\2\\3<|$attributes>\\4|>", $stuff_to_parse);
  3204. }
  3205. }
  3206. }
  3207. //
  3208. // Highlight brackets. Yes, I've tried adding a semi-colon to this list.
  3209. // You try it, and see what happens ;)
  3210. // TODO: Fix lexic permissions not converting entities if shouldn't
  3211. // be highlighting regardless
  3212. //
  3213. if ($this->lexic_permissions['BRACKETS']) {
  3214. $stuff_to_parse = str_replace( $this->language_data['CACHE_BRACKET_MATCH'],
  3215. $this->language_data['CACHE_BRACKET_REPLACE'], $stuff_to_parse );
  3216. }
  3217. //FIX for symbol highlighting ...
  3218. if ($this->lexic_permissions['SYMBOLS'] && !empty($this->language_data['SYMBOLS'])) {
  3219. //Get all matches and throw away those witin a block that is already highlighted... (i.e. matched by a regexp)
  3220. $n_symbols = preg_match_all("/<\|(?:<DOT>|[^>])+>(?:(?!\|>).*?)\|>|<\/a>|(?:" . $this->language_data['SYMBOL_SEARCH'] . ")+(?![^<]+?>)/", $stuff_to_parse, $pot_symbols, PREG_OFFSET_CAPTURE | PREG_SET_ORDER);
  3221. $global_offset = 0;
  3222. for ($s_id = 0; $s_id < $n_symbols; ++$s_id) {
  3223. $symbol_match = $pot_symbols[$s_id][0][0];
  3224. if (strpos($symbol_match, '<') !== false || strpos($symbol_match, '>') !== false) {
  3225. // already highlighted blocks _must_ include either < or >
  3226. // so if this conditional applies, we have to skip this match
  3227. // BenBE: UNLESS the block contains <SEMI> or <PIPE>
  3228. if(strpos($symbol_match, '<SEMI>') === false &&
  3229. strpos($symbol_match, '<PIPE>') === false) {
  3230. continue;
  3231. }
  3232. }
  3233. // if we reach this point, we have a valid match which needs to be highlighted
  3234. $symbol_length = strlen($symbol_match);
  3235. $symbol_offset = $pot_symbols[$s_id][0][1];
  3236. unset($pot_symbols[$s_id]);
  3237. $symbol_end = $symbol_length + $symbol_offset;
  3238. $symbol_hl = "";
  3239. // if we have multiple styles, we have to handle them properly
  3240. if ($this->language_data['MULTIPLE_SYMBOL_GROUPS']) {
  3241. $old_sym = -1;
  3242. // Split the current stuff to replace into its atomic symbols ...
  3243. preg_match_all("/" . $this->language_data['SYMBOL_SEARCH'] . "/", $symbol_match, $sym_match_syms, PREG_PATTERN_ORDER);
  3244. foreach ($sym_match_syms[0] as $sym_ms) {
  3245. //Check if consequtive symbols belong to the same group to save output ...
  3246. if (isset($this->language_data['SYMBOL_DATA'][$sym_ms])
  3247. && ($this->language_data['SYMBOL_DATA'][$sym_ms] != $old_sym)) {
  3248. if (-1 != $old_sym) {
  3249. $symbol_hl .= "|>";
  3250. }
  3251. $old_sym = $this->language_data['SYMBOL_DATA'][$sym_ms];
  3252. if (!$this->use_classes) {
  3253. $symbol_hl .= '<| style="' . $this->language_data['STYLES']['SYMBOLS'][$old_sym] . '">';
  3254. } else {
  3255. $symbol_hl .= '<| class="sy' . $old_sym . '">';
  3256. }
  3257. }
  3258. $symbol_hl .= $sym_ms;
  3259. }
  3260. unset($sym_match_syms);
  3261. //Close remaining tags and insert the replacement at the right position ...
  3262. //Take caution if symbol_hl is empty to avoid doubled closing spans.
  3263. if (-1 != $old_sym) {
  3264. $symbol_hl .= "|>";
  3265. }
  3266. } else {
  3267. if (!$this->use_classes) {
  3268. $symbol_hl = '<| style="' . $this->language_data['STYLES']['SYMBOLS'][0] . '">';
  3269. } else {
  3270. $symbol_hl = '<| class="sy0">';
  3271. }
  3272. $symbol_hl .= $symbol_match . '|>';
  3273. }
  3274. $stuff_to_parse = substr_replace($stuff_to_parse, $symbol_hl, $symbol_offset + $global_offset, $symbol_length);
  3275. // since we replace old text with something of different size,
  3276. // we'll have to keep track of the differences
  3277. $global_offset += strlen($symbol_hl) - $symbol_length;
  3278. }
  3279. }
  3280. //FIX for symbol highlighting ...
  3281. // Add class/style for regexps
  3282. foreach (array_keys($this->language_data['REGEXPS']) as $key) {
  3283. if ($this->lexic_permissions['REGEXPS'][$key]) {
  3284. if (is_callable($this->language_data['STYLES']['REGEXPS'][$key])) {
  3285. $this->_rx_key = $key;
  3286. $stuff_to_parse = preg_replace_callback("/!REG3XP$key!(.*)\|>/U",
  3287. array($this, 'handle_regexps_callback'),
  3288. $stuff_to_parse);
  3289. } else {
  3290. if (!$this->use_classes) {
  3291. $attributes = ' style="' . $this->language_data['STYLES']['REGEXPS'][$key] . '"';
  3292. } else {
  3293. if (is_array($this->language_data['REGEXPS'][$key]) &&
  3294. array_key_exists(GESHI_CLASS, $this->language_data['REGEXPS'][$key])) {
  3295. $attributes = ' class="' .
  3296. $this->language_data['REGEXPS'][$key][GESHI_CLASS] . '"';
  3297. } else {
  3298. $attributes = ' class="re' . $key . '"';
  3299. }
  3300. }
  3301. $stuff_to_parse = str_replace("!REG3XP$key!", "$attributes", $stuff_to_parse);
  3302. }
  3303. }
  3304. }
  3305. // Replace <DOT> with . for urls
  3306. $stuff_to_parse = str_replace('<DOT>', '.', $stuff_to_parse);
  3307. // Replace <|UR1| with <a href= for urls also
  3308. if (isset($this->link_styles[GESHI_LINK])) {
  3309. if ($this->use_classes) {
  3310. $stuff_to_parse = str_replace('<|UR1|', '<a' . $this->link_target . ' href=', $stuff_to_parse);
  3311. } else {
  3312. $stuff_to_parse = str_replace('<|UR1|', '<a' . $this->link_target . ' style="' . $this->link_styles[GESHI_LINK] . '" href=', $stuff_to_parse);
  3313. }
  3314. } else {
  3315. $stuff_to_parse = str_replace('<|UR1|', '<a' . $this->link_target . ' href=', $stuff_to_parse);
  3316. }
  3317. //
  3318. // NOW we add the span thingy ;)
  3319. //
  3320. $stuff_to_parse = str_replace('<|', '<span', $stuff_to_parse);
  3321. $stuff_to_parse = str_replace ( '|>', '</span>', $stuff_to_parse );
  3322. return substr($stuff_to_parse, 1);
  3323. }
  3324. /**
  3325. * Sets the time taken to parse the code
  3326. *
  3327. * @param microtime The time when parsing started
  3328. * @param microtime The time when parsing ended
  3329. * @since 1.0.2
  3330. * @access private
  3331. */
  3332. function set_time($start_time, $end_time) {
  3333. $start = explode(' ', $start_time);
  3334. $end = explode(' ', $end_time);
  3335. $this->time = $end[0] + $end[1] - $start[0] - $start[1];
  3336. }
  3337. /**
  3338. * Gets the time taken to parse the code
  3339. *
  3340. * @return double The time taken to parse the code
  3341. * @since 1.0.2
  3342. */
  3343. function get_time() {
  3344. return $this->time;
  3345. }
  3346. /**
  3347. * Merges arrays recursively, overwriting values of the first array with values of later arrays
  3348. *
  3349. * @since 1.0.8
  3350. * @access private
  3351. */
  3352. function merge_arrays() {
  3353. $arrays = func_get_args();
  3354. $narrays = count($arrays);
  3355. // check arguments
  3356. // comment out if more performance is necessary (in this case the foreach loop will trigger a warning if the argument is not an array)
  3357. for ($i = 0; $i < $narrays; $i ++) {
  3358. if (!is_array($arrays[$i])) {
  3359. // also array_merge_recursive returns nothing in this case
  3360. trigger_error('Argument #' . ($i+1) . ' is not an array - trying to merge array with scalar! Returning false!', E_USER_WARNING);
  3361. return false;
  3362. }
  3363. }
  3364. // the first array is in the output set in every case
  3365. $ret = $arrays[0];
  3366. // merege $ret with the remaining arrays
  3367. for ($i = 1; $i < $narrays; $i ++) {
  3368. foreach ($arrays[$i] as $key => $value) {
  3369. if (is_array($value) && isset($ret[$key])) {
  3370. // if $ret[$key] is not an array you try to merge an scalar value with an array - the result is not defined (incompatible arrays)
  3371. // in this case the call will trigger an E_USER_WARNING and the $ret[$key] will be false.
  3372. $ret[$key] = $this->merge_arrays($ret[$key], $value);
  3373. } else {
  3374. $ret[$key] = $value;
  3375. }
  3376. }
  3377. }
  3378. return $ret;
  3379. }
  3380. /**
  3381. * Gets language information and stores it for later use
  3382. *
  3383. * @param string The filename of the language file you want to load
  3384. * @since 1.0.0
  3385. * @access private
  3386. * @todo Needs to load keys for lexic permissions for keywords, regexps etc
  3387. */
  3388. function load_language($file_name) {
  3389. if ($file_name == $this->loaded_language) {
  3390. // this file is already loaded!
  3391. return;
  3392. }
  3393. //Prepare some stuff before actually loading the language file
  3394. $this->loaded_language = $file_name;
  3395. $this->parse_cache_built = false;
  3396. $this->enable_highlighting();
  3397. $language_data = array();
  3398. //Load the language file
  3399. require $file_name;
  3400. // Perhaps some checking might be added here later to check that
  3401. // $language data is a valid thing but maybe not
  3402. $this->language_data = $language_data;
  3403. // Set strict mode if should be set
  3404. $this->strict_mode = $this->language_data['STRICT_MODE_APPLIES'];
  3405. // Set permissions for all lexics to true
  3406. // so they'll be highlighted by default
  3407. foreach (array_keys($this->language_data['KEYWORDS']) as $key) {
  3408. if (!empty($this->language_data['KEYWORDS'][$key])) {
  3409. $this->lexic_permissions['KEYWORDS'][$key] = true;
  3410. } else {
  3411. $this->lexic_permissions['KEYWORDS'][$key] = false;
  3412. }
  3413. }
  3414. foreach (array_keys($this->language_data['COMMENT_SINGLE']) as $key) {
  3415. $this->lexic_permissions['COMMENTS'][$key] = true;
  3416. }
  3417. foreach (array_keys($this->language_data['REGEXPS']) as $key) {
  3418. $this->lexic_permissions['REGEXPS'][$key] = true;
  3419. }
  3420. // for BenBE and future code reviews:
  3421. // we can use empty here since we only check for existance and emptiness of an array
  3422. // if it is not an array at all but rather false or null this will work as intended as well
  3423. // even if $this->language_data['PARSER_CONTROL'] is undefined this won't trigger a notice
  3424. if (!empty($this->language_data['PARSER_CONTROL']['ENABLE_FLAGS'])) {
  3425. foreach ($this->language_data['PARSER_CONTROL']['ENABLE_FLAGS'] as $flag => $value) {
  3426. // it's either true or false and maybe is true as well
  3427. $perm = $value !== GESHI_NEVER;
  3428. if ($flag == 'ALL') {
  3429. $this->enable_highlighting($perm);
  3430. continue;
  3431. }
  3432. if (!isset($this->lexic_permissions[$flag])) {
  3433. // unknown lexic permission
  3434. continue;
  3435. }
  3436. if (is_array($this->lexic_permissions[$flag])) {
  3437. foreach ($this->lexic_permissions[$flag] as $key => $val) {
  3438. $this->lexic_permissions[$flag][$key] = $perm;
  3439. }
  3440. } else {
  3441. $this->lexic_permissions[$flag] = $perm;
  3442. }
  3443. }
  3444. unset($this->language_data['PARSER_CONTROL']['ENABLE_FLAGS']);
  3445. }
  3446. //Fix: Problem where hardescapes weren't handled if no ESCAPE_CHAR was given
  3447. //You need to set one for HARDESCAPES only in this case.
  3448. if(!isset($this->language_data['HARDCHAR'])) {
  3449. $this->language_data['HARDCHAR'] = $this->language_data['ESCAPE_CHAR'];
  3450. }
  3451. //NEW in 1.0.8: Allow styles to be loaded from a separate file to override defaults
  3452. $style_filename = substr($file_name, 0, -4) . '.style.php';
  3453. if (is_readable($style_filename)) {
  3454. //Clear any style_data that could have been set before ...
  3455. if (isset($style_data)) {
  3456. unset($style_data);
  3457. }
  3458. //Read the Style Information from the style file
  3459. include $style_filename;
  3460. //Apply the new styles to our current language styles
  3461. if (isset($style_data) && is_array($style_data)) {
  3462. $this->language_data['STYLES'] =
  3463. $this->merge_arrays($this->language_data['STYLES'], $style_data);
  3464. }
  3465. }
  3466. }
  3467. /**
  3468. * Takes the parsed code and various options, and creates the HTML
  3469. * surrounding it to make it look nice.
  3470. *
  3471. * @param string The code already parsed (reference!)
  3472. * @since 1.0.0
  3473. * @access private
  3474. */
  3475. function finalise(&$parsed_code) {
  3476. // Remove end parts of important declarations
  3477. // This is BUGGY!! My fault for bad code: fix coming in 1.2
  3478. // @todo Remove this crap
  3479. if ($this->enable_important_blocks &&
  3480. (strpos($parsed_code, $this->hsc(GESHI_START_IMPORTANT)) === false)) {
  3481. $parsed_code = str_replace($this->hsc(GESHI_END_IMPORTANT), '', $parsed_code);
  3482. }
  3483. // Add HTML whitespace stuff if we're using the <div> header
  3484. if ($this->header_type != GESHI_HEADER_PRE && $this->header_type != GESHI_HEADER_PRE_VALID) {
  3485. $this->indent($parsed_code);
  3486. }
  3487. // purge some unnecessary stuff
  3488. /** NOTE: memorypeak #1 */
  3489. $parsed_code = preg_replace('#<span[^>]+>(\s*)</span>#', '\\1', $parsed_code);
  3490. // If we are using IDs for line numbers, there needs to be an overall
  3491. // ID set to prevent collisions.
  3492. if ($this->add_ids && !$this->overall_id) {
  3493. $this->overall_id = 'geshi-' . substr(md5(microtime()), 0, 4);
  3494. }
  3495. // Get code into lines
  3496. /** NOTE: memorypeak #2 */
  3497. $code = explode("\n", $parsed_code);
  3498. $parsed_code = $this->header();
  3499. // If we're using line numbers, we insert <li>s and appropriate
  3500. // markup to style them (otherwise we don't need to do anything)
  3501. if ($this->line_numbers != GESHI_NO_LINE_NUMBERS && $this->header_type != GESHI_HEADER_PRE_TABLE) {
  3502. // If we're using the <pre> header, we shouldn't add newlines because
  3503. // the <pre> will line-break them (and the <li>s already do this for us)
  3504. $ls = ($this->header_type != GESHI_HEADER_PRE && $this->header_type != GESHI_HEADER_PRE_VALID) ? "\n" : '';
  3505. // Set vars to defaults for following loop
  3506. $i = 0;
  3507. // Foreach line...
  3508. for ($i = 0, $n = count($code); $i < $n;) {
  3509. //Reset the attributes for a new line ...
  3510. $attrs = array();
  3511. // Make lines have at least one space in them if they're empty
  3512. // BenBE: Checking emptiness using trim instead of relying on blanks
  3513. if ('' == trim($code[$i])) {
  3514. $code[$i] = '&nbsp;';
  3515. }
  3516. // If this is a "special line"...
  3517. if ($this->line_numbers == GESHI_FANCY_LINE_NUMBERS &&
  3518. $i % $this->line_nth_row == ($this->line_nth_row - 1)) {
  3519. // Set the attributes to style the line
  3520. if ($this->use_classes) {
  3521. //$attr = ' class="li2"';
  3522. $attrs['class'][] = 'li2';
  3523. $def_attr = ' class="de2"';
  3524. } else {
  3525. //$attr = ' style="' . $this->line_style2 . '"';
  3526. $attrs['style'][] = $this->line_style2;
  3527. // This style "covers up" the special styles set for special lines
  3528. // so that styles applied to special lines don't apply to the actual
  3529. // code on that line
  3530. $def_attr = ' style="' . $this->code_style . '"';
  3531. }
  3532. } else {
  3533. if ($this->use_classes) {
  3534. //$attr = ' class="li1"';
  3535. $attrs['class'][] = 'li1';
  3536. $def_attr = ' class="de1"';
  3537. } else {
  3538. //$attr = ' style="' . $this->line_style1 . '"';
  3539. $attrs['style'][] = $this->line_style1;
  3540. $def_attr = ' style="' . $this->code_style . '"';
  3541. }
  3542. }
  3543. //Check which type of tag to insert for this line
  3544. if ($this->header_type == GESHI_HEADER_PRE_VALID) {
  3545. $start = "<pre$def_attr>";
  3546. $end = '</pre>';
  3547. } else {
  3548. // Span or div?
  3549. $start = "<div$def_attr>";
  3550. $end = '</div>';
  3551. }
  3552. ++$i;
  3553. // Are we supposed to use ids? If so, add them
  3554. if ($this->add_ids) {
  3555. $attrs['id'][] = "$this->overall_id-$i";
  3556. }
  3557. //Is this some line with extra styles???
  3558. if (in_array($i, $this->highlight_extra_lines)) {
  3559. if ($this->use_classes) {
  3560. if (isset($this->highlight_extra_lines_styles[$i])) {
  3561. $attrs['class'][] = "lx$i";
  3562. } else {
  3563. $attrs['class'][] = "ln-xtra";
  3564. }
  3565. } else {
  3566. array_push($attrs['style'], $this->get_line_style($i));
  3567. }
  3568. }
  3569. // Add in the line surrounded by appropriate list HTML
  3570. $attr_string = '';
  3571. foreach ($attrs as $key => $attr) {
  3572. $attr_string .= ' ' . $key . '="' . implode(' ', $attr) . '"';
  3573. }
  3574. $parsed_code .= "<li$attr_string>$start{$code[$i-1]}$end</li>$ls";
  3575. unset($code[$i - 1]);
  3576. }
  3577. } else {
  3578. $n = count($code);
  3579. if ($this->use_classes) {
  3580. $attributes = ' class="de1"';
  3581. } else {
  3582. $attributes = ' style="'. $this->code_style .'"';
  3583. }
  3584. if ($this->header_type == GESHI_HEADER_PRE_VALID) {
  3585. $parsed_code .= '<pre'. $attributes .'>';
  3586. } elseif ($this->header_type == GESHI_HEADER_PRE_TABLE) {
  3587. if ($this->line_numbers != GESHI_NO_LINE_NUMBERS) {
  3588. if ($this->use_classes) {
  3589. $attrs = ' class="ln"';
  3590. } else {
  3591. $attrs = ' style="'. $this->table_linenumber_style .'"';
  3592. }
  3593. $parsed_code .= '<td'.$attrs.'><pre'.$attributes.'>';
  3594. // get linenumbers
  3595. // we don't merge it with the for below, since it should be better for
  3596. // memory consumption this way
  3597. // @todo: but... actually it would still be somewhat nice to merge the two loops
  3598. // the mem peaks are at different positions
  3599. for ($i = 0; $i < $n; ++$i) {
  3600. $close = 0;
  3601. // fancy lines
  3602. if ($this->line_numbers == GESHI_FANCY_LINE_NUMBERS &&
  3603. $i % $this->line_nth_row == ($this->line_nth_row - 1)) {
  3604. // Set the attributes to style the line
  3605. if ($this->use_classes) {
  3606. $parsed_code .= '<span class="xtra li2"><span class="de2">';
  3607. } else {
  3608. // This style "covers up" the special styles set for special lines
  3609. // so that styles applied to special lines don't apply to the actual
  3610. // code on that line
  3611. $parsed_code .= '<span style="display:block;' . $this->line_style2 . '">'
  3612. .'<span style="' . $this->code_style .'">';
  3613. }
  3614. $close += 2;
  3615. }
  3616. //Is this some line with extra styles???
  3617. if (in_array($i + 1, $this->highlight_extra_lines)) {
  3618. if ($this->use_classes) {
  3619. if (isset($this->highlight_extra_lines_styles[$i])) {
  3620. $parsed_code .= "<span class=\"xtra lx$i\">";
  3621. } else {
  3622. $parsed_code .= "<span class=\"xtra ln-xtra\">";
  3623. }
  3624. } else {
  3625. $parsed_code .= "<span style=\"display:block;" . $this->get_line_style($i) . "\">";
  3626. }
  3627. ++$close;
  3628. }
  3629. $parsed_code .= $this->line_numbers_start + $i;
  3630. if ($close) {
  3631. $parsed_code .= str_repeat('</span>', $close);
  3632. } elseif ($i != $n) {
  3633. $parsed_code .= "\n";
  3634. }
  3635. }
  3636. $parsed_code .= '</pre></td><td'.$attributes.'>';
  3637. }
  3638. $parsed_code .= '<pre'. $attributes .'>';
  3639. }
  3640. // No line numbers, but still need to handle highlighting lines extra.
  3641. // Have to use divs so the full width of the code is highlighted
  3642. $close = 0;
  3643. for ($i = 0; $i < $n; ++$i) {
  3644. // Make lines have at least one space in them if they're empty
  3645. // BenBE: Checking emptiness using trim instead of relying on blanks
  3646. if ('' == trim($code[$i])) {
  3647. $code[$i] = '&nbsp;';
  3648. }
  3649. // fancy lines
  3650. if ($this->line_numbers == GESHI_FANCY_LINE_NUMBERS &&
  3651. $i % $this->line_nth_row == ($this->line_nth_row - 1)) {
  3652. // Set the attributes to style the line
  3653. if ($this->use_classes) {
  3654. $parsed_code .= '<span class="xtra li2"><span class="de2">';
  3655. } else {
  3656. // This style "covers up" the special styles set for special lines
  3657. // so that styles applied to special lines don't apply to the actual
  3658. // code on that line
  3659. $parsed_code .= '<span style="display:block;' . $this->line_style2 . '">'
  3660. .'<span style="' . $this->code_style .'">';
  3661. }
  3662. $close += 2;
  3663. }
  3664. //Is this some line with extra styles???
  3665. if (in_array($i + 1, $this->highlight_extra_lines)) {
  3666. if ($this->use_classes) {
  3667. if (isset($this->highlight_extra_lines_styles[$i])) {
  3668. $parsed_code .= "<span class=\"xtra lx$i\">";
  3669. } else {
  3670. $parsed_code .= "<span class=\"xtra ln-xtra\">";
  3671. }
  3672. } else {
  3673. $parsed_code .= "<span style=\"display:block;" . $this->get_line_style($i) . "\">";
  3674. }
  3675. ++$close;
  3676. }
  3677. $parsed_code .= $code[$i];
  3678. if ($close) {
  3679. $parsed_code .= str_repeat('</span>', $close);
  3680. $close = 0;
  3681. }
  3682. elseif ($i + 1 < $n) {
  3683. $parsed_code .= "\n";
  3684. }
  3685. unset($code[$i]);
  3686. }
  3687. if ($this->header_type == GESHI_HEADER_PRE_VALID || $this->header_type == GESHI_HEADER_PRE_TABLE) {
  3688. $parsed_code .= '</pre>';
  3689. }
  3690. if ($this->header_type == GESHI_HEADER_PRE_TABLE && $this->line_numbers != GESHI_NO_LINE_NUMBERS) {
  3691. $parsed_code .= '</td>';
  3692. }
  3693. }
  3694. $parsed_code .= $this->footer();
  3695. }
  3696. /**
  3697. * Creates the header for the code block (with correct attributes)
  3698. *
  3699. * @return string The header for the code block
  3700. * @since 1.0.0
  3701. * @access private
  3702. */
  3703. function header() {
  3704. // Get attributes needed
  3705. /**
  3706. * @todo Document behaviour change - class is outputted regardless of whether
  3707. * we're using classes or not. Same with style
  3708. */
  3709. $attributes = ' class="' . $this->_genCSSName($this->language);
  3710. if ($this->overall_class != '') {
  3711. $attributes .= " ".$this->_genCSSName($this->overall_class);
  3712. }
  3713. $attributes .= '"';
  3714. if ($this->overall_id != '') {
  3715. $attributes .= " id=\"{$this->overall_id}\"";
  3716. }
  3717. if ($this->overall_style != '' && !$this->use_classes) {
  3718. $attributes .= ' style="' . $this->overall_style . '"';
  3719. }
  3720. $ol_attributes = '';
  3721. if ($this->line_numbers_start != 1) {
  3722. $ol_attributes .= ' start="' . $this->line_numbers_start . '"';
  3723. }
  3724. // Get the header HTML
  3725. $header = $this->header_content;
  3726. if ($header) {
  3727. if ($this->header_type == GESHI_HEADER_PRE || $this->header_type == GESHI_HEADER_PRE_VALID) {
  3728. $header = str_replace("\n", '', $header);
  3729. }
  3730. $header = $this->replace_keywords($header);
  3731. if ($this->use_classes) {
  3732. $attr = ' class="head"';
  3733. } else {
  3734. $attr = " style=\"{$this->header_content_style}\"";
  3735. }
  3736. if ($this->header_type == GESHI_HEADER_PRE_TABLE && $this->line_numbers != GESHI_NO_LINE_NUMBERS) {
  3737. $header = "<thead><tr><td colspan=\"2\" $attr>$header</td></tr></thead>";
  3738. } else {
  3739. $header = "<div$attr>$header</div>";
  3740. }
  3741. }
  3742. if (GESHI_HEADER_NONE == $this->header_type) {
  3743. if ($this->line_numbers != GESHI_NO_LINE_NUMBERS) {
  3744. return "$header<ol$attributes$ol_attributes>";
  3745. }
  3746. return $header . ($this->force_code_block ? '<div>' : '');
  3747. }
  3748. // Work out what to return and do it
  3749. if ($this->line_numbers != GESHI_NO_LINE_NUMBERS) {
  3750. if ($this->header_type == GESHI_HEADER_PRE) {
  3751. return "<pre$attributes>$header<ol$ol_attributes>";
  3752. } elseif ($this->header_type == GESHI_HEADER_DIV ||
  3753. $this->header_type == GESHI_HEADER_PRE_VALID) {
  3754. return "<div$attributes>$header<ol$ol_attributes>";
  3755. } elseif ($this->header_type == GESHI_HEADER_PRE_TABLE) {
  3756. return "<table$attributes>$header<tbody><tr class=\"li1\">";
  3757. }
  3758. } else {
  3759. if ($this->header_type == GESHI_HEADER_PRE) {
  3760. return "<pre$attributes>$header" .
  3761. ($this->force_code_block ? '<div>' : '');
  3762. } else {
  3763. return "<div$attributes>$header" .
  3764. ($this->force_code_block ? '<div>' : '');
  3765. }
  3766. }
  3767. }
  3768. /**
  3769. * Returns the footer for the code block.
  3770. *
  3771. * @return string The footer for the code block
  3772. * @since 1.0.0
  3773. * @access private
  3774. */
  3775. function footer() {
  3776. $footer = $this->footer_content;
  3777. if ($footer) {
  3778. if ($this->header_type == GESHI_HEADER_PRE) {
  3779. $footer = str_replace("\n", '', $footer);
  3780. }
  3781. $footer = $this->replace_keywords($footer);
  3782. if ($this->use_classes) {
  3783. $attr = ' class="foot"';
  3784. } else {
  3785. $attr = " style=\"{$this->footer_content_style}\"";
  3786. }
  3787. if ($this->header_type == GESHI_HEADER_PRE_TABLE && $this->line_numbers != GESHI_NO_LINE_NUMBERS) {
  3788. $footer = "<tfoot><tr><td colspan=\"2\">$footer</td></tr></tfoot>";
  3789. } else {
  3790. $footer = "<div$attr>$footer</div>";
  3791. }
  3792. }
  3793. if (GESHI_HEADER_NONE == $this->header_type) {
  3794. return ($this->line_numbers != GESHI_NO_LINE_NUMBERS) ? '</ol>' . $footer : $footer;
  3795. }
  3796. if ($this->header_type == GESHI_HEADER_DIV || $this->header_type == GESHI_HEADER_PRE_VALID) {
  3797. if ($this->line_numbers != GESHI_NO_LINE_NUMBERS) {
  3798. return "</ol>$footer</div>";
  3799. }
  3800. return ($this->force_code_block ? '</div>' : '') .
  3801. "$footer</div>";
  3802. }
  3803. elseif ($this->header_type == GESHI_HEADER_PRE_TABLE) {
  3804. if ($this->line_numbers != GESHI_NO_LINE_NUMBERS) {
  3805. return "</tr></tbody>$footer</table>";
  3806. }
  3807. return ($this->force_code_block ? '</div>' : '') .
  3808. "$footer</div>";
  3809. }
  3810. else {
  3811. if ($this->line_numbers != GESHI_NO_LINE_NUMBERS) {
  3812. return "</ol>$footer</pre>";
  3813. }
  3814. return ($this->force_code_block ? '</div>' : '') .
  3815. "$footer</pre>";
  3816. }
  3817. }
  3818. /**
  3819. * Replaces certain keywords in the header and footer with
  3820. * certain configuration values
  3821. *
  3822. * @param string The header or footer content to do replacement on
  3823. * @return string The header or footer with replaced keywords
  3824. * @since 1.0.2
  3825. * @access private
  3826. */
  3827. function replace_keywords($instr) {
  3828. $keywords = $replacements = array();
  3829. $keywords[] = '<TIME>';
  3830. $keywords[] = '{TIME}';
  3831. $replacements[] = $replacements[] = number_format($time = $this->get_time(), 3);
  3832. $keywords[] = '<LANGUAGE>';
  3833. $keywords[] = '{LANGUAGE}';
  3834. $replacements[] = $replacements[] = $this->language_data['LANG_NAME'];
  3835. $keywords[] = '<VERSION>';
  3836. $keywords[] = '{VERSION}';
  3837. $replacements[] = $replacements[] = GESHI_VERSION;
  3838. $keywords[] = '<SPEED>';
  3839. $keywords[] = '{SPEED}';
  3840. if ($time <= 0) {
  3841. $speed = 'N/A';
  3842. } else {
  3843. $speed = strlen($this->source) / $time;
  3844. if ($speed >= 1024) {
  3845. $speed = sprintf("%.2f KB/s", $speed / 1024.0);
  3846. } else {
  3847. $speed = sprintf("%.0f B/s", $speed);
  3848. }
  3849. }
  3850. $replacements[] = $replacements[] = $speed;
  3851. return str_replace($keywords, $replacements, $instr);
  3852. }
  3853. /**
  3854. * Secure replacement for PHP built-in function htmlspecialchars().
  3855. *
  3856. * See ticket #427 (http://wush.net/trac/wikka/ticket/427) for the rationale
  3857. * for this replacement function.
  3858. *
  3859. * The INTERFACE for this function is almost the same as that for
  3860. * htmlspecialchars(), with the same default for quote style; however, there
  3861. * is no 'charset' parameter. The reason for this is as follows:
  3862. *
  3863. * The PHP docs say:
  3864. * "The third argument charset defines character set used in conversion."
  3865. *
  3866. * I suspect PHP's htmlspecialchars() is working at the byte-value level and
  3867. * thus _needs_ to know (or asssume) a character set because the special
  3868. * characters to be replaced could exist at different code points in
  3869. * different character sets. (If indeed htmlspecialchars() works at
  3870. * byte-value level that goes some way towards explaining why the
  3871. * vulnerability would exist in this function, too, and not only in
  3872. * htmlentities() which certainly is working at byte-value level.)
  3873. *
  3874. * This replacement function however works at character level and should
  3875. * therefore be "immune" to character set differences - so no charset
  3876. * parameter is needed or provided. If a third parameter is passed, it will
  3877. * be silently ignored.
  3878. *
  3879. * In the OUTPUT there is a minor difference in that we use '&#39;' instead
  3880. * of PHP's '&#039;' for a single quote: this provides compatibility with
  3881. * get_html_translation_table(HTML_SPECIALCHARS, ENT_QUOTES)
  3882. * (see comment by mikiwoz at yahoo dot co dot uk on
  3883. * http://php.net/htmlspecialchars); it also matches the entity definition
  3884. * for XML 1.0
  3885. * (http://www.w3.org/TR/xhtml1/dtds.html#a_dtd_Special_characters).
  3886. * Like PHP we use a numeric character reference instead of '&apos;' for the
  3887. * single quote. For the other special characters we use the named entity
  3888. * references, as PHP is doing.
  3889. *
  3890. * @author {@link http://wikkawiki.org/JavaWoman Marjolein Katsma}
  3891. *
  3892. * @license http://www.gnu.org/copyleft/lgpl.html
  3893. * GNU Lesser General Public License
  3894. * @copyright Copyright 2007, {@link http://wikkawiki.org/CreditsPage
  3895. * Wikka Development Team}
  3896. *
  3897. * @access private
  3898. * @param string $string string to be converted
  3899. * @param integer $quote_style
  3900. * - ENT_COMPAT: escapes &, <, > and double quote (default)
  3901. * - ENT_NOQUOTES: escapes only &, < and >
  3902. * - ENT_QUOTES: escapes &, <, >, double and single quotes
  3903. * @return string converted string
  3904. * @since 1.0.7.18
  3905. */
  3906. function hsc($string, $quote_style = ENT_COMPAT) {
  3907. // init
  3908. static $aTransSpecchar = array(
  3909. '&' => '&amp;',
  3910. '"' => '&quot;',
  3911. '<' => '&lt;',
  3912. '>' => '&gt;',
  3913. //This fix is related to SF#1923020, but has to be applied
  3914. //regardless of actually highlighting symbols.
  3915. //Circumvent a bug with symbol highlighting
  3916. //This is required as ; would produce undesirable side-effects if it
  3917. //was not to be processed as an entity.
  3918. ';' => '<SEMI>', // Force ; to be processed as entity
  3919. '|' => '<PIPE>' // Force | to be processed as entity
  3920. ); // ENT_COMPAT set
  3921. switch ($quote_style) {
  3922. case ENT_NOQUOTES: // don't convert double quotes
  3923. unset($aTransSpecchar['"']);
  3924. break;
  3925. case ENT_QUOTES: // convert single quotes as well
  3926. $aTransSpecchar["'"] = '&#39;'; // (apos) htmlspecialchars() uses '&#039;'
  3927. break;
  3928. }
  3929. // return translated string
  3930. return strtr($string, $aTransSpecchar);
  3931. }
  3932. function _genCSSName($name){
  3933. return (is_numeric($name[0]) ? '_' : '') . $name;
  3934. }
  3935. /**
  3936. * Returns a stylesheet for the highlighted code. If $economy mode
  3937. * is true, we only return the stylesheet declarations that matter for
  3938. * this code block instead of the whole thing
  3939. *
  3940. * @param boolean Whether to use economy mode or not
  3941. * @return string A stylesheet built on the data for the current language
  3942. * @since 1.0.0
  3943. */
  3944. function get_stylesheet($economy_mode = true) {
  3945. // If there's an error, chances are that the language file
  3946. // won't have populated the language data file, so we can't
  3947. // risk getting a stylesheet...
  3948. if ($this->error) {
  3949. return '';
  3950. }
  3951. //Check if the style rearrangements have been processed ...
  3952. //This also does some preprocessing to check which style groups are useable ...
  3953. if(!isset($this->language_data['NUMBERS_CACHE'])) {
  3954. $this->build_style_cache();
  3955. }
  3956. // First, work out what the selector should be. If there's an ID,
  3957. // that should be used, the same for a class. Otherwise, a selector
  3958. // of '' means that these styles will be applied anywhere
  3959. if ($this->overall_id) {
  3960. $selector = '#' . $this->_genCSSName($this->overall_id);
  3961. } else {
  3962. $selector = '.' . $this->_genCSSName($this->language);
  3963. if ($this->overall_class) {
  3964. $selector .= '.' . $this->_genCSSName($this->overall_class);
  3965. }
  3966. }
  3967. $selector .= ' ';
  3968. // Header of the stylesheet
  3969. if (!$economy_mode) {
  3970. $stylesheet = "/**\n".
  3971. " * GeSHi Dynamically Generated Stylesheet\n".
  3972. " * --------------------------------------\n".
  3973. " * Dynamically generated stylesheet for {$this->language}\n".
  3974. " * CSS class: {$this->overall_class}, CSS id: {$this->overall_id}\n".
  3975. " * GeSHi (C) 2004 - 2007 Nigel McNie, 2007 - 2008 Benny Baumann\n" .
  3976. " * (http://qbnz.com/highlighter/ and http://geshi.org/)\n".
  3977. " * --------------------------------------\n".
  3978. " */\n";
  3979. } else {
  3980. $stylesheet = "/**\n".
  3981. " * GeSHi (C) 2004 - 2007 Nigel McNie, 2007 - 2008 Benny Baumann\n" .
  3982. " * (http://qbnz.com/highlighter/ and http://geshi.org/)\n".
  3983. " */\n";
  3984. }
  3985. // Set the <ol> to have no effect at all if there are line numbers
  3986. // (<ol>s have margins that should be destroyed so all layout is
  3987. // controlled by the set_overall_style method, which works on the
  3988. // <pre> or <div> container). Additionally, set default styles for lines
  3989. if (!$economy_mode || $this->line_numbers != GESHI_NO_LINE_NUMBERS) {
  3990. //$stylesheet .= "$selector, {$selector}ol, {$selector}ol li {margin: 0;}\n";
  3991. $stylesheet .= "$selector.de1, $selector.de2 {{$this->code_style}}\n";
  3992. }
  3993. // Add overall styles
  3994. // note: neglect economy_mode, empty styles are meaningless
  3995. if ($this->overall_style != '') {
  3996. $stylesheet .= "$selector {{$this->overall_style}}\n";
  3997. }
  3998. // Add styles for links
  3999. // note: economy mode does not make _any_ sense here
  4000. // either the style is empty and thus no selector is needed
  4001. // or the appropriate key is given.
  4002. foreach ($this->link_styles as $key => $style) {
  4003. if ($style != '') {
  4004. switch ($key) {
  4005. case GESHI_LINK:
  4006. $stylesheet .= "{$selector}a:link {{$style}}\n";
  4007. break;
  4008. case GESHI_HOVER:
  4009. $stylesheet .= "{$selector}a:hover {{$style}}\n";
  4010. break;
  4011. case GESHI_ACTIVE:
  4012. $stylesheet .= "{$selector}a:active {{$style}}\n";
  4013. break;
  4014. case GESHI_VISITED:
  4015. $stylesheet .= "{$selector}a:visited {{$style}}\n";
  4016. break;
  4017. }
  4018. }
  4019. }
  4020. // Header and footer
  4021. // note: neglect economy_mode, empty styles are meaningless
  4022. if ($this->header_content_style != '') {
  4023. $stylesheet .= "$selector.head {{$this->header_content_style}}\n";
  4024. }
  4025. if ($this->footer_content_style != '') {
  4026. $stylesheet .= "$selector.foot {{$this->footer_content_style}}\n";
  4027. }
  4028. // Styles for important stuff
  4029. // note: neglect economy_mode, empty styles are meaningless
  4030. if ($this->important_styles != '') {
  4031. $stylesheet .= "$selector.imp {{$this->important_styles}}\n";
  4032. }
  4033. // Simple line number styles
  4034. if ((!$economy_mode || $this->line_numbers != GESHI_NO_LINE_NUMBERS) && $this->line_style1 != '') {
  4035. $stylesheet .= "{$selector}li, {$selector}.li1 {{$this->line_style1}}\n";
  4036. }
  4037. if ((!$economy_mode || $this->line_numbers != GESHI_NO_LINE_NUMBERS) && $this->table_linenumber_style != '') {
  4038. $stylesheet .= "{$selector}.ln {{$this->table_linenumber_style}}\n";
  4039. }
  4040. // If there is a style set for fancy line numbers, echo it out
  4041. if ((!$economy_mode || $this->line_numbers == GESHI_FANCY_LINE_NUMBERS) && $this->line_style2 != '') {
  4042. $stylesheet .= "{$selector}.li2 {{$this->line_style2}}\n";
  4043. }
  4044. // note: empty styles are meaningless
  4045. foreach ($this->language_data['STYLES']['KEYWORDS'] as $group => $styles) {
  4046. if ($styles != '' && (!$economy_mode ||
  4047. (isset($this->lexic_permissions['KEYWORDS'][$group]) &&
  4048. $this->lexic_permissions['KEYWORDS'][$group]))) {
  4049. $stylesheet .= "$selector.kw$group {{$styles}}\n";
  4050. }
  4051. }
  4052. foreach ($this->language_data['STYLES']['COMMENTS'] as $group => $styles) {
  4053. if ($styles != '' && (!$economy_mode ||
  4054. (isset($this->lexic_permissions['COMMENTS'][$group]) &&
  4055. $this->lexic_permissions['COMMENTS'][$group]) ||
  4056. (!empty($this->language_data['COMMENT_REGEXP']) &&
  4057. !empty($this->language_data['COMMENT_REGEXP'][$group])))) {
  4058. $stylesheet .= "$selector.co$group {{$styles}}\n";
  4059. }
  4060. }
  4061. foreach ($this->language_data['STYLES']['ESCAPE_CHAR'] as $group => $styles) {
  4062. if ($styles != '' && (!$economy_mode || $this->lexic_permissions['ESCAPE_CHAR'])) {
  4063. // NEW: since 1.0.8 we have to handle hardescapes
  4064. if ($group === 'HARD') {
  4065. $group = '_h';
  4066. }
  4067. $stylesheet .= "$selector.es$group {{$styles}}\n";
  4068. }
  4069. }
  4070. foreach ($this->language_data['STYLES']['BRACKETS'] as $group => $styles) {
  4071. if ($styles != '' && (!$economy_mode || $this->lexic_permissions['BRACKETS'])) {
  4072. $stylesheet .= "$selector.br$group {{$styles}}\n";
  4073. }
  4074. }
  4075. foreach ($this->language_data['STYLES']['SYMBOLS'] as $group => $styles) {
  4076. if ($styles != '' && (!$economy_mode || $this->lexic_permissions['SYMBOLS'])) {
  4077. $stylesheet .= "$selector.sy$group {{$styles}}\n";
  4078. }
  4079. }
  4080. foreach ($this->language_data['STYLES']['STRINGS'] as $group => $styles) {
  4081. if ($styles != '' && (!$economy_mode || $this->lexic_permissions['STRINGS'])) {
  4082. // NEW: since 1.0.8 we have to handle hardquotes
  4083. if ($group === 'HARD') {
  4084. $group = '_h';
  4085. }
  4086. $stylesheet .= "$selector.st$group {{$styles}}\n";
  4087. }
  4088. }
  4089. foreach ($this->language_data['STYLES']['NUMBERS'] as $group => $styles) {
  4090. if ($styles != '' && (!$economy_mode || $this->lexic_permissions['NUMBERS'])) {
  4091. $stylesheet .= "$selector.nu$group {{$styles}}\n";
  4092. }
  4093. }
  4094. foreach ($this->language_data['STYLES']['METHODS'] as $group => $styles) {
  4095. if ($styles != '' && (!$economy_mode || $this->lexic_permissions['METHODS'])) {
  4096. $stylesheet .= "$selector.me$group {{$styles}}\n";
  4097. }
  4098. }
  4099. // note: neglect economy_mode, empty styles are meaningless
  4100. foreach ($this->language_data['STYLES']['SCRIPT'] as $group => $styles) {
  4101. if ($styles != '') {
  4102. $stylesheet .= "$selector.sc$group {{$styles}}\n";
  4103. }
  4104. }
  4105. foreach ($this->language_data['STYLES']['REGEXPS'] as $group => $styles) {
  4106. if ($styles != '' && (!$economy_mode ||
  4107. (isset($this->lexic_permissions['REGEXPS'][$group]) &&
  4108. $this->lexic_permissions['REGEXPS'][$group]))) {
  4109. if (is_array($this->language_data['REGEXPS'][$group]) &&
  4110. array_key_exists(GESHI_CLASS, $this->language_data['REGEXPS'][$group])) {
  4111. $stylesheet .= "$selector.";
  4112. $stylesheet .= $this->language_data['REGEXPS'][$group][GESHI_CLASS];
  4113. $stylesheet .= " {{$styles}}\n";
  4114. } else {
  4115. $stylesheet .= "$selector.re$group {{$styles}}\n";
  4116. }
  4117. }
  4118. }
  4119. // Styles for lines being highlighted extra
  4120. if (!$economy_mode || (count($this->highlight_extra_lines)!=count($this->highlight_extra_lines_styles))) {
  4121. $stylesheet .= "{$selector}.ln-xtra, {$selector}li.ln-xtra, {$selector}div.ln-xtra {{$this->highlight_extra_lines_style}}\n";
  4122. }
  4123. $stylesheet .= "{$selector}span.xtra { display:block; }\n";
  4124. foreach ($this->highlight_extra_lines_styles as $lineid => $linestyle) {
  4125. $stylesheet .= "{$selector}.lx$lineid, {$selector}li.lx$lineid, {$selector}div.lx$lineid {{$linestyle}}\n";
  4126. }
  4127. return $stylesheet;
  4128. }
  4129. /**
  4130. * Get's the style that is used for the specified line
  4131. *
  4132. * @param int The line number information is requested for
  4133. * @access private
  4134. * @since 1.0.7.21
  4135. */
  4136. function get_line_style($line) {
  4137. //$style = null;
  4138. $style = null;
  4139. if (isset($this->highlight_extra_lines_styles[$line])) {
  4140. $style = $this->highlight_extra_lines_styles[$line];
  4141. } else { // if no "extra" style assigned
  4142. $style = $this->highlight_extra_lines_style;
  4143. }
  4144. return $style;
  4145. }
  4146. /**
  4147. * this functions creates an optimized regular expression list
  4148. * of an array of strings.
  4149. *
  4150. * Example:
  4151. * <code>$list = array('faa', 'foo', 'foobar');
  4152. * => string 'f(aa|oo(bar)?)'</code>
  4153. *
  4154. * @param $list array of (unquoted) strings
  4155. * @param $regexp_delimiter your regular expression delimiter, @see preg_quote()
  4156. * @return string for regular expression
  4157. * @author Milian Wolff <mail@milianw.de>
  4158. * @since 1.0.8
  4159. * @access private
  4160. */
  4161. function optimize_regexp_list($list, $regexp_delimiter = '/') {
  4162. $regex_chars = array('.', '\\', '+', '-', '*', '?', '[', '^', ']', '$',
  4163. '(', ')', '{', '}', '=', '!', '<', '>', '|', ':', $regexp_delimiter);
  4164. sort($list);
  4165. $regexp_list = array('');
  4166. $num_subpatterns = 0;
  4167. $list_key = 0;
  4168. // the tokens which we will use to generate the regexp list
  4169. $tokens = array();
  4170. $prev_keys = array();
  4171. // go through all entries of the list and generate the token list
  4172. $cur_len = 0;
  4173. for ($i = 0, $i_max = count($list); $i < $i_max; ++$i) {
  4174. if ($cur_len > GESHI_MAX_PCRE_LENGTH) {
  4175. // seems like the length of this pcre is growing exorbitantly
  4176. $regexp_list[++$list_key] = $this->_optimize_regexp_list_tokens_to_string($tokens);
  4177. $num_subpatterns = substr_count($regexp_list[$list_key], '(?:');
  4178. $tokens = array();
  4179. $cur_len = 0;
  4180. }
  4181. $level = 0;
  4182. $entry = preg_quote((string) $list[$i], $regexp_delimiter);
  4183. $pointer = &$tokens;
  4184. // properly assign the new entry to the correct position in the token array
  4185. // possibly generate smaller common denominator keys
  4186. while (true) {
  4187. // get the common denominator
  4188. if (isset($prev_keys[$level])) {
  4189. if ($prev_keys[$level] == $entry) {
  4190. // this is a duplicate entry, skip it
  4191. continue 2;
  4192. }
  4193. $char = 0;
  4194. while (isset($entry[$char]) && isset($prev_keys[$level][$char])
  4195. && $entry[$char] == $prev_keys[$level][$char]) {
  4196. ++$char;
  4197. }
  4198. if ($char > 0) {
  4199. // this entry has at least some chars in common with the current key
  4200. if ($char == strlen($prev_keys[$level])) {
  4201. // current key is totally matched, i.e. this entry has just some bits appended
  4202. $pointer = &$pointer[$prev_keys[$level]];
  4203. } else {
  4204. // only part of the keys match
  4205. $new_key_part1 = substr($prev_keys[$level], 0, $char);
  4206. $new_key_part2 = substr($prev_keys[$level], $char);
  4207. if (in_array($new_key_part1[0], $regex_chars)
  4208. || in_array($new_key_part2[0], $regex_chars)) {
  4209. // this is bad, a regex char as first character
  4210. $pointer[$entry] = array('' => true);
  4211. array_splice($prev_keys, $level, count($prev_keys), $entry);
  4212. $cur_len += strlen($entry);
  4213. continue;
  4214. } else {
  4215. // relocate previous tokens
  4216. $pointer[$new_key_part1] = array($new_key_part2 => $pointer[$prev_keys[$level]]);
  4217. unset($pointer[$prev_keys[$level]]);
  4218. $pointer = &$pointer[$new_key_part1];
  4219. // recreate key index
  4220. array_splice($prev_keys, $level, count($prev_keys), array($new_key_part1, $new_key_part2));
  4221. $cur_len += strlen($new_key_part2);
  4222. }
  4223. }
  4224. ++$level;
  4225. $entry = substr($entry, $char);
  4226. continue;
  4227. }
  4228. // else: fall trough, i.e. no common denominator was found
  4229. }
  4230. if ($level == 0 && !empty($tokens)) {
  4231. // we can dump current tokens into the string and throw them away afterwards
  4232. $new_entry = $this->_optimize_regexp_list_tokens_to_string($tokens);
  4233. $new_subpatterns = substr_count($new_entry, '(?:');
  4234. if (GESHI_MAX_PCRE_SUBPATTERNS && $num_subpatterns + $new_subpatterns > GESHI_MAX_PCRE_SUBPATTERNS) {
  4235. $regexp_list[++$list_key] = $new_entry;
  4236. $num_subpatterns = $new_subpatterns;
  4237. } else {
  4238. if (!empty($regexp_list[$list_key])) {
  4239. $new_entry = '|' . $new_entry;
  4240. }
  4241. $regexp_list[$list_key] .= $new_entry;
  4242. $num_subpatterns += $new_subpatterns;
  4243. }
  4244. $tokens = array();
  4245. $cur_len = 0;
  4246. }
  4247. // no further common denominator found
  4248. $pointer[$entry] = array('' => true);
  4249. array_splice($prev_keys, $level, count($prev_keys), $entry);
  4250. $cur_len += strlen($entry);
  4251. break;
  4252. }
  4253. unset($list[$i]);
  4254. }
  4255. // make sure the last tokens get converted as well
  4256. $new_entry = $this->_optimize_regexp_list_tokens_to_string($tokens);
  4257. if (GESHI_MAX_PCRE_SUBPATTERNS && $num_subpatterns + substr_count($new_entry, '(?:') > GESHI_MAX_PCRE_SUBPATTERNS) {
  4258. if ( !empty($regexp_list[$list_key]) ) {
  4259. ++$list_key;
  4260. }
  4261. $regexp_list[$list_key] = $new_entry;
  4262. } else {
  4263. if (!empty($regexp_list[$list_key])) {
  4264. $new_entry = '|' . $new_entry;
  4265. }
  4266. $regexp_list[$list_key] .= $new_entry;
  4267. }
  4268. return $regexp_list;
  4269. }
  4270. /**
  4271. * this function creates the appropriate regexp string of an token array
  4272. * you should not call this function directly, @see $this->optimize_regexp_list().
  4273. *
  4274. * @param &$tokens array of tokens
  4275. * @param $recursed bool to know wether we recursed or not
  4276. * @return string
  4277. * @author Milian Wolff <mail@milianw.de>
  4278. * @since 1.0.8
  4279. * @access private
  4280. */
  4281. function _optimize_regexp_list_tokens_to_string(&$tokens, $recursed = false) {
  4282. $list = '';
  4283. foreach ($tokens as $token => $sub_tokens) {
  4284. $list .= $token;
  4285. $close_entry = isset($sub_tokens['']);
  4286. unset($sub_tokens['']);
  4287. if (!empty($sub_tokens)) {
  4288. $list .= '(?:' . $this->_optimize_regexp_list_tokens_to_string($sub_tokens, true) . ')';
  4289. if ($close_entry) {
  4290. // make sub_tokens optional
  4291. $list .= '?';
  4292. }
  4293. }
  4294. $list .= '|';
  4295. }
  4296. if (!$recursed) {
  4297. // do some optimizations
  4298. // common trailing strings
  4299. // BUGGY!
  4300. //$list = preg_replace_callback('#(?<=^|\:|\|)\w+?(\w+)(?:\|.+\1)+(?=\|)#', create_function(
  4301. // '$matches', 'return "(?:" . preg_replace("#" . preg_quote($matches[1], "#") . "(?=\||$)#", "", $matches[0]) . ")" . $matches[1];'), $list);
  4302. // (?:p)? => p?
  4303. $list = preg_replace('#\(\?\:(.)\)\?#', '\1?', $list);
  4304. // (?:a|b|c|d|...)? => [abcd...]?
  4305. // TODO: a|bb|c => [ac]|bb
  4306. static $callback_2;
  4307. if (!isset($callback_2)) {
  4308. $callback_2 = create_function('$matches', 'return "[" . str_replace("|", "", $matches[1]) . "]";');
  4309. }
  4310. $list = preg_replace_callback('#\(\?\:((?:.\|)+.)\)#', $callback_2, $list);
  4311. }
  4312. // return $list without trailing pipe
  4313. return substr($list, 0, -1);
  4314. }
  4315. } // End Class GeSHi
  4316. if (!function_exists('geshi_highlight')) {
  4317. /**
  4318. * Easy way to highlight stuff. Behaves just like highlight_string
  4319. *
  4320. * @param string The code to highlight
  4321. * @param string The language to highlight the code in
  4322. * @param string The path to the language files. You can leave this blank if you need
  4323. * as from version 1.0.7 the path should be automatically detected
  4324. * @param boolean Whether to return the result or to echo
  4325. * @return string The code highlighted (if $return is true)
  4326. * @since 1.0.2
  4327. */
  4328. function geshi_highlight($string, $language, $path = null, $return = false) {
  4329. $geshi = new GeSHi($string, $language, $path);
  4330. $geshi->set_header_type(GESHI_HEADER_NONE);
  4331. if ($return) {
  4332. return '<code>' . $geshi->parse_code() . '</code>';
  4333. }
  4334. echo '<code>' . $geshi->parse_code() . '</code>';
  4335. if ($geshi->error()) {
  4336. return false;
  4337. }
  4338. return true;
  4339. }
  4340. }
  4341. ?>