PageRenderTime 180ms CodeModel.GetById 20ms RepoModel.GetById 1ms app.codeStats 1ms

/inc/app/sitellite/lib/geshi/geshi.php

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