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

/e107_handlers/e_parse_class.php

https://github.com/CasperGemini/e107
PHP | 3465 lines | 2420 code | 436 blank | 609 comment | 274 complexity | 962cccc252f9cb2ff3168f1ac8fa9800 MD5 | raw file
Possible License(s): GPL-2.0

Large files files are truncated, but you can click here to view the full file

  1. <?php
  2. /*
  3. * e107 website system
  4. *
  5. * Copyright (C) 2008-2011 e107 Inc (e107.org)
  6. * Released under the terms and conditions of the
  7. * GNU General Public License (http://www.gnu.org/licenses/gpl.txt)
  8. *
  9. * Text processing and parsing functions
  10. *
  11. * $URL$
  12. * $Id$
  13. *
  14. */
  15. /**
  16. * @package e107
  17. * @subpackage e107_handlers
  18. * @version $Id$
  19. *
  20. * Text processing and parsing functions.
  21. * Simple parse data model.
  22. */
  23. if (!defined('e107_INIT')) { exit(); }
  24. // Directory for the hard-coded utf-8 handling routines
  25. define('E_UTF8_PACK', e_HANDLER.'utf8/');
  26. define("E_NL", chr(2));
  27. class e_parse extends e_parser
  28. {
  29. /**
  30. * Determine how to handle utf-8.
  31. * 0 = 'do nothing'
  32. * 1 = 'use mb_string'
  33. * 2 = emulation
  34. *
  35. * @var integer
  36. */
  37. protected $utfAction;
  38. // Shortcode processor - see __get()
  39. //var $e_sc;
  40. // BBCode processor
  41. var $e_bb;
  42. // Profanity filter
  43. var $e_pf;
  44. // Emote filter
  45. var $e_emote;
  46. // 'Hooked' parsers (array)
  47. var $e_hook;
  48. var $search = array('&amp;#039;', '&#039;', '&#39;', '&quot;', 'onerror', '&gt;', '&amp;quot;', ' & ');
  49. var $replace = array("'", "'", "'", '"', 'one<i></i>rror', '>', '"', ' &amp; ');
  50. // Set to TRUE or FALSE once it has been calculated
  51. var $e_highlighting;
  52. // Highlight query
  53. var $e_query;
  54. public $thumbWidth = 100;
  55. public $thumbHeight = 0;
  56. public $thumbCrop = 0;
  57. // Set up the defaults
  58. var $e_optDefault = array(
  59. // default context: reflects legacy settings (many items enabled)
  60. 'context' => 'OLDDEFAULT',
  61. //
  62. 'fromadmin' => FALSE,
  63. // Enable emote display
  64. 'emotes' => TRUE,
  65. // Convert defines(constants) within text.
  66. 'defs' => FALSE,
  67. // replace all {e_XXX} constants with their e107 value - 'rel' or 'abs'
  68. 'constants' => FALSE,
  69. // Enable hooked parsers
  70. 'hook' => TRUE,
  71. // Allow scripts through (new for 0.8)
  72. 'scripts' => TRUE,
  73. // Make links clickable
  74. 'link_click' => TRUE,
  75. // Substitute on clickable links (only if link_click == TRUE)
  76. 'link_replace' => TRUE,
  77. // Parse shortcodes - TRUE enables parsing
  78. 'parse_sc' => FALSE,
  79. // remove HTML tags.
  80. 'no_tags' => FALSE,
  81. // Restore entity form of quotes and such to single characters - TRUE disables
  82. 'value' => FALSE,
  83. // Line break compression - TRUE removes newline characters
  84. 'nobreak' => FALSE,
  85. // Retain newlines - wraps to \n instead of <br /> if TRUE (for non-HTML email text etc)
  86. 'retain_nl' => FALSE
  87. );
  88. // Super modifiers override default option values
  89. var $e_SuperMods = array(
  90. //text is part of a title (e.g. news title)
  91. 'TITLE' =>
  92. array(
  93. 'nobreak'=>TRUE, 'retain_nl'=>TRUE, 'link_click' => FALSE, 'emotes'=>FALSE, 'defs'=>TRUE, 'parse_sc'=>TRUE
  94. ),
  95. 'TITLE_PLAIN' =>
  96. array(
  97. 'nobreak'=>TRUE, 'retain_nl'=>TRUE, 'link_click' => FALSE, 'emotes'=>FALSE, 'defs'=>TRUE, 'parse_sc'=>TRUE, 'no_tags' => TRUE
  98. ),
  99. //text is user-entered (i.e. untrusted) and part of a title (e.g. forum title)
  100. 'USER_TITLE' =>
  101. array(
  102. 'nobreak'=>TRUE, 'retain_nl'=>TRUE, 'link_click' => FALSE, 'scripts' => FALSE, 'emotes'=>FALSE, 'hook'=>FALSE
  103. ),
  104. // text is 'body' of email or similar - being sent 'off-site' so don't rely on server availability
  105. 'E_TITLE' =>
  106. array(
  107. 'nobreak'=>TRUE, 'retain_nl'=>TRUE, 'defs'=>TRUE, 'parse_sc'=>TRUE, 'emotes'=>FALSE, 'scripts' => FALSE, 'link_click' => FALSE
  108. ),
  109. // text is part of the summary of a longer item (e.g. content summary)
  110. 'SUMMARY' =>
  111. array(
  112. 'defs'=>TRUE, 'constants'=>'full', 'parse_sc'=>TRUE
  113. ),
  114. // text is the description of an item (e.g. download, link)
  115. 'DESCRIPTION' =>
  116. array(
  117. 'defs'=>TRUE, 'constants'=>'full', 'parse_sc'=>TRUE
  118. ),
  119. // text is 'body' or 'bulk' text (e.g. custom page body, content body)
  120. 'BODY' =>
  121. array(
  122. 'defs'=>TRUE, 'constants'=>'full', 'parse_sc'=>TRUE
  123. ),
  124. 'WYSIWYG' =>
  125. array(
  126. 'defs'=>FALSE, 'constants'=>'full', 'parse_sc'=>FALSE, 'wysiwyg'=>TRUE
  127. ),
  128. // text is user-entered (i.e. untrusted)'body' or 'bulk' text (e.g. custom page body, content body)
  129. 'USER_BODY' =>
  130. array(
  131. 'constants'=>'full', 'scripts' => FALSE, 'nostrip'=>FALSE
  132. ),
  133. // text is 'body' of email or similar - being sent 'off-site' so don't rely on server availability
  134. 'E_BODY' =>
  135. array(
  136. 'defs'=>TRUE, 'constants'=>'full', 'parse_sc'=>TRUE, 'emotes'=>FALSE, 'scripts' => FALSE, 'link_click' => FALSE
  137. ),
  138. // text is text-only 'body' of email or similar - being sent 'off-site' so don't rely on server availability
  139. 'E_BODY_PLAIN' =>
  140. array(
  141. 'defs'=>TRUE, 'constants'=>'full', 'parse_sc'=>TRUE, 'emotes'=>FALSE, 'scripts' => FALSE, 'link_click' => FALSE, 'retain_nl' => TRUE, 'no_tags' => TRUE
  142. ),
  143. // text is the 'content' of a link (A tag, etc)
  144. 'LINKTEXT' =>
  145. array(
  146. 'nobreak'=>TRUE, 'retain_nl'=>TRUE, 'link_click' => FALSE, 'emotes'=>FALSE, 'hook'=>FALSE, 'defs'=>TRUE, 'parse_sc'=>TRUE
  147. ),
  148. // text is used (for admin edit) without fancy conversions or html.
  149. 'RAWTEXT' =>
  150. array(
  151. 'nobreak'=>TRUE, 'retain_nl'=>TRUE, 'link_click' => FALSE, 'emotes'=>FALSE, 'hook'=>FALSE, 'no_tags'=>TRUE
  152. )
  153. );
  154. // Individual modifiers change the current context
  155. var $e_Modifiers = array(
  156. 'emotes_off' => array('emotes' => FALSE),
  157. 'emotes_on' => array('emotes' => TRUE),
  158. 'no_hook' => array('hook' => FALSE),
  159. 'do_hook' => array('hook' => TRUE),
  160. // New for 0.8
  161. 'scripts_off' => array('scripts' => FALSE),
  162. // New for 0.8
  163. 'scripts_on' => array('scripts' => TRUE),
  164. 'no_make_clickable' => array('link_click' => FALSE),
  165. 'make_clickable' => array('link_click' => TRUE),
  166. 'no_replace' => array('link_replace' => FALSE),
  167. // Replace text of clickable links (only if make_clickable option set)
  168. 'replace' => array('link_replace' => TRUE),
  169. // No path replacement
  170. 'consts_off' => array('constants' => FALSE),
  171. // Relative path replacement
  172. 'consts_rel' => array('constants' => 'rel'),
  173. // Absolute path replacement
  174. 'consts_abs' => array('constants' => 'abs'),
  175. // Full path replacement
  176. 'consts_full' => array('constants' => 'full'),
  177. // No shortcode parsing
  178. 'scparse_off' => array('parse_sc' => FALSE),
  179. 'scparse_on' => array('parse_sc' => TRUE),
  180. // Strip tags
  181. 'no_tags' => array('no_tags' => TRUE),
  182. // Leave tags
  183. 'do_tags' => array('no_tags' => FALSE),
  184. 'fromadmin' => array('fromadmin' => TRUE),
  185. 'notadmin' => array('fromadmin' => FALSE),
  186. // entity replacement
  187. 'er_off' => array('value' => FALSE),
  188. 'er_on' => array('value' => TRUE),
  189. // Decode constant if exists
  190. 'defs_off' => array('defs' => FALSE),
  191. 'defs_on' => array('defs' => TRUE),
  192. 'dobreak' => array('nobreak' => FALSE),
  193. 'nobreak' => array('nobreak' => TRUE),
  194. // Line break using \n
  195. 'lb_nl' => array('retain_nl' => TRUE),
  196. // Line break using <br />
  197. 'lb_br' => array('retain_nl' => FALSE),
  198. // Legacy option names below here - discontinue later
  199. 'retain_nl' => array('retain_nl' => TRUE),
  200. 'defs' => array('defs' => TRUE),
  201. 'parse_sc' => array('parse_sc' => TRUE),
  202. 'constants' => array('constants' => 'rel'),
  203. 'value' => array('value' => TRUE),
  204. 'wysiwyg' => array('wysiwyg'=>TRUE)
  205. );
  206. /**
  207. * Constructor - keep it public for backward compatibility
  208. still some new e_parse() in the core
  209. *
  210. * @return void
  211. */
  212. public function __construct()
  213. {
  214. // initialise the type of UTF-8 processing methods depending on PHP version and mb string extension
  215. $this->init();
  216. $this->initCharset();
  217. // Preprocess the supermods to be useful default arrays with all values
  218. foreach ($this->e_SuperMods as $key => $val)
  219. {
  220. // precalculate super defaults
  221. $this->e_SuperMods[$key] = array_merge($this->e_optDefault , $this->e_SuperMods[$key]);
  222. $this->e_SuperMods[$key]['context'] = $key;
  223. }
  224. }
  225. /**
  226. * Initialise the type of UTF-8 processing methods depending on PHP version and mb string extension.
  227. *
  228. * NOTE: can't be called until CHARSET is known
  229. but we all know that it is UTF-8 now
  230. *
  231. * @return void
  232. */
  233. private function initCharset()
  234. {
  235. // Start by working out what, if anything, we do about utf-8 handling.
  236. // 'Do nothing' is the simple option
  237. $this->utfAction = 0;
  238. // CHARSET is utf-8
  239. // if(strtolower(CHARSET) == 'utf-8')
  240. // {
  241. if(version_compare(PHP_VERSION, '6.0.0') < 1)
  242. {
  243. // Need to do something here
  244. if(extension_loaded('mbstring'))
  245. {
  246. // Check for function overloading
  247. $temp = ini_get('mbstring.func_overload');
  248. // Just check the string functions - will be non-zero if overloaded
  249. if(($temp & MB_OVERLOAD_STRING) == 0)
  250. {
  251. // Can use the mb_string routines
  252. $this->utfAction = 1;
  253. }
  254. // Set the default encoding, so we don't have to specify every time
  255. mb_internal_encoding('UTF-8');
  256. }
  257. else
  258. {
  259. // Must use emulation - will probably be slow!
  260. $this->utfAction = 2;
  261. require (E_UTF8_PACK.'utils/unicode.php');
  262. // Always load the core routines - bound to need some of them!
  263. require (E_UTF8_PACK.'native/core.php');
  264. }
  265. }
  266. // }
  267. }
  268. /**
  269. * Unicode (UTF-8) analogue of standard @link http://php.net/strlen strlen PHP function.
  270. * Returns the length of the given string.
  271. *
  272. * @param string $str The UTF-8 encoded string being measured for length.
  273. * @return integer The length (amount of UTF-8 characters) of the string on success, and 0 if the string is empty.
  274. */
  275. public function ustrlen($str)
  276. {
  277. switch($this->utfAction)
  278. {
  279. case 0:
  280. return strlen($str);
  281. case 1:
  282. return mb_strlen($str);
  283. }
  284. // Default case shouldn't happen often
  285. // Save a call - invoke the function directly
  286. return strlen(utf8_decode($str));
  287. }
  288. /**
  289. * Unicode (UTF-8) analogue of standard @link http://php.net/strtolower strtolower PHP function.
  290. * Make a string lowercase.
  291. *
  292. * @param string $str The UTF-8 encoded string to be lowercased.
  293. * @return string Specified string with all alphabetic characters converted to lowercase.
  294. */
  295. public function ustrtolower($str)
  296. {
  297. switch($this->utfAction)
  298. {
  299. case 0:
  300. return strtolower($str);
  301. case 1:
  302. return mb_strtolower($str);
  303. }
  304. // Default case shouldn't happen often
  305. return utf8_strtolower($str);
  306. }
  307. /**
  308. * Unicode (UTF-8) analogue of standard @link http://php.net/strtoupper strtoupper PHP function.
  309. * Make a string uppercase.
  310. *
  311. * @param string $str The UTF-8 encoded string to be uppercased.
  312. * @return string Specified string with all alphabetic characters converted to uppercase.
  313. */
  314. public function ustrtoupper($str)
  315. {
  316. switch($this->utfAction)
  317. {
  318. case 0:
  319. return strtoupper($str);
  320. case 1:
  321. return mb_strtoupper($str);
  322. }
  323. // Default case shouldn't happen often
  324. return utf8_strtoupper($str);
  325. }
  326. /**
  327. * Unicode (UTF-8) analogue of standard @link http://php.net/strpos strpos PHP function.
  328. * Find the position of the first occurrence of a case-sensitive UTF-8 encoded string.
  329. * Returns the numeric position (offset in amount of UTF-8 characters)
  330. * of the first occurrence of needle in the haystack string.
  331. *
  332. * @param string $haystack The UTF-8 encoded string being searched in.
  333. * @param integer $needle The UTF-8 encoded string being searched for.
  334. * @param integer $offset [optional] The optional offset parameter allows you to specify which character in haystack to start searching.
  335. * The position returned is still relative to the beginning of haystack.
  336. * @return integer|boolean Returns the position as an integer. If needle is not found, the function will return boolean FALSE.
  337. */
  338. public function ustrpos($haystack, $needle, $offset = 0)
  339. {
  340. switch($this->utfAction)
  341. {
  342. case 0:
  343. return strpos($haystack, $needle, $offset);
  344. case 1:
  345. return mb_strpos($haystack, $needle, $offset);
  346. }
  347. return utf8_strpos($haystack, $needle, $offset);
  348. }
  349. /**
  350. * Unicode (UTF-8) analogue of standard @link http://php.net/strrpos strrpos PHP function.
  351. * Find the position of the last occurrence of a case-sensitive UTF-8 encoded string.
  352. * Returns the numeric position (offset in amount of UTF-8 characters)
  353. * of the last occurrence of needle in the haystack string.
  354. *
  355. * @param string $haystack The UTF-8 encoded string being searched in.
  356. * @param integer $needle The UTF-8 encoded string being searched for.
  357. * @param integer $offset [optional] - The optional offset parameter allows you to specify which character in haystack to start searching.
  358. * The position returned is still relative to the beginning of haystack.
  359. * @return integer|boolean Returns the position as an integer. If needle is not found, the function will return boolean FALSE.
  360. */
  361. public function ustrrpos($haystack, $needle, $offset = 0)
  362. {
  363. switch($this->utfAction)
  364. {
  365. case 0:
  366. return strrpos($haystack, $needle, $offset);
  367. case 1:
  368. return mb_strrpos($haystack, $needle, $offset);
  369. }
  370. return utf8_strrpos($haystack, $needle, $offset);
  371. }
  372. /**
  373. * Unicode (UTF-8) analogue of standard @link http://php.net/stristr stristr PHP function.
  374. * Returns all of haystack starting from and including the first occurrence of needle to the end.
  375. *
  376. * @param string $haystack The UTF-8 encoded string to search in.
  377. * @param mixed $needle If needle is not a string, it is converted to an integer and applied as the ordinal value of a character.
  378. * @param integer $length [optional] (PHP 5.3+) If TRUE, returns the part of the haystack before the first occurrence of the needle (excluding needle).
  379. * @return string Returns the matched substring. If needle is not found, returns FALSE.
  380. */
  381. public function ustristr($haystack, $needle, $before_needle = false)
  382. {
  383. switch($this->utfAction)
  384. {
  385. case 0:
  386. return stristr($haystack, $needle, $before_needle);
  387. case 1:
  388. return mb_substr($haystack, $needle, $before_needle);
  389. }
  390. // No utf8 pack backup
  391. return stristr($str, $start, $length);
  392. }
  393. /**
  394. * Unicode (UTF-8) analogue of standard @link http://php.net/substr substr PHP function.
  395. * Returns the portion of string specified by the start and length parameters.
  396. *
  397. * NOTE: May be subtle differences in return values dependent on which routine is used.
  398. * Native substr() routine can return FALSE. mb_substr() and utf8_substr() just return an empty string.
  399. *
  400. * @param string $str The UTF-8 encoded string.
  401. * @param integer $start Start of portion to be returned. Position is counted in amount of UTF-8 characters from the beginning of str.
  402. * First character's position is 0. Second character position is 1, and so on.
  403. * @param integer $length [optional] If length is given, the string returned will contain at most length characters beginning from start
  404. * (depending on the length of string). If length is omitted, the rest of string from start will be returned.
  405. * @return string The extracted UTF-8 encoded part of input string.
  406. */
  407. public function usubstr($str, $start, $length = NULL)
  408. {
  409. switch($this->utfAction)
  410. {
  411. case 0:
  412. return substr($str, $start, $length);
  413. case 1:
  414. if(is_null($length))
  415. {
  416. return mb_substr($str, $start);
  417. }
  418. else
  419. {
  420. return mb_substr($str, $start, $length);
  421. }
  422. }
  423. return utf8_substr($str, $start, $length);
  424. }
  425. /**
  426. * Converts the supplied text (presumed to be from user input) to a format suitable for storing in a database table.
  427. *
  428. * @param string $data
  429. * @param boolean $nostrip [optional] Assumes all data is GPC ($_GET, $_POST, $_COOKIE) unless indicate otherwise by setting this var to TRUE.
  430. * If magic quotes is enabled on the server and you do not tell toDB() that the data is non GPC then slashes will be stripped when they should not be.
  431. * @param boolean $no_encode [optional] This parameter should nearly always be FALSE. It is used by the save_prefs() function to preserve HTML content within prefs even when
  432. * the save_prefs() function has been called by a non admin user / user without html posting permissions.
  433. * @param boolean $mod [optional] The 'no_html' and 'no_php' modifiers blanket prevent HTML and PHP posting regardless of posting permissions. (used in logging)
  434. * The 'pReFs' value is for internal use only, when saving prefs, to prevent sanitisation of HTML.
  435. * @param boolean $original_author [optional]
  436. * @return string
  437. * @todo complete the documentation of this essential method
  438. */
  439. public function toDB($data, $nostrip = FALSE, $no_encode = FALSE, $mod = FALSE, $original_author = FALSE)
  440. {
  441. $core_pref = e107::getConfig();
  442. if (is_array($data))
  443. {
  444. foreach ($data as $key => $var)
  445. {
  446. //Fix - sanitize keys as well
  447. $ret[$this->toDB($key, $nostrip, $no_encode, $mod, $original_author)] = $this->toDB($var, $nostrip, $no_encode, $mod, $original_author);
  448. }
  449. return $ret;
  450. }
  451. if (MAGIC_QUOTES_GPC == TRUE && $nostrip == FALSE)
  452. {
  453. $data = stripslashes($data);
  454. }
  455. if ($mod != 'pReFs') //XXX We're not saving prefs.
  456. {
  457. $data = $this->preFilter($data); // used by bb_xxx.php toDB() functions. bb_code.php toDB() allows us to properly bypass HTML cleaning below.
  458. if (strip_tags($data) != $data) // html tags present.
  459. {
  460. // return $data;
  461. $data = $this->cleanHtml($data); // sanitize all html.
  462. $data = urldecode($data); // symptom of cleaning the HTML - urlencodes src attributes containing { and } .eg. {e_BASE}
  463. }
  464. if (!check_class($core_pref->get('post_html', e_UC_MAINADMIN)))
  465. {
  466. $data = strip_tags($data); // remove tags from cleaned html.
  467. $data = str_replace(array('[html]','[/html]'),'',$data);
  468. // $data = $this->dataFilter($data);
  469. }
  470. $data = html_entity_decode($data, ENT_QUOTES, 'utf-8'); // Prevent double-entities. Fix for [code] - see bb_code.php toDB();
  471. }
  472. if (check_class($core_pref->get('post_html'))) /*$core_pref->is('post_html') && */
  473. {
  474. $no_encode = TRUE;
  475. }
  476. if (is_numeric($original_author) && !check_class($core_pref->get('post_html'), '', $original_author))
  477. {
  478. $no_encode = FALSE;
  479. }
  480. if ($no_encode === TRUE && strpos($mod, 'no_html') === FALSE)
  481. {
  482. $search = array('$', '"', "'", '\\', '<?');
  483. $replace = array('&#036;', '&quot;', '&#039;', '&#092;', '&lt;?');
  484. $ret = str_replace($search, $replace, $data);
  485. }
  486. else
  487. {
  488. $data = htmlspecialchars($data, ENT_QUOTES, 'UTF-8');
  489. $data = str_replace('\\', '&#092;', $data);
  490. $ret = preg_replace("/&amp;#(\d*?);/", "&#\\1;", $data);
  491. }
  492. // XXX - php_bbcode has been deprecated.
  493. if ((strpos($mod, 'no_php') !== FALSE) || !check_class($core_pref->get('php_bbcode')))
  494. {
  495. $ret = preg_replace("#\[(php)#i", "&#91;\\1", $ret);
  496. }
  497. return $ret;
  498. }
  499. /**
  500. * Check for umatched 'dangerous' HTML tags
  501. * (these can destroy page layout where users are able to post HTML)
  502. * @DEPRECATED
  503. * @param string $data
  504. * @param string $tagList - if empty, uses default list of input tags. Otherwise a CSV list of tags to check (any type)
  505. *
  506. * @return boolean TRUE if an unopened closing tag found
  507. * FALSE if nothing found
  508. */
  509. function htmlAbuseFilter($data, $tagList = '')
  510. {
  511. if ($tagList == '')
  512. {
  513. $checkTags = array('textarea', 'input', 'td', 'tr', 'table');
  514. }
  515. else
  516. {
  517. $checkTags = explode(',', $tagList);
  518. }
  519. $tagArray = array_flip($checkTags);
  520. foreach ($tagArray as &$v) { $v = 0; }; // Data fields become zero; keys are tag names.
  521. $data = strtolower(preg_replace('#\[code\].*?\[\/code\]#i', '', $data)); // Ignore code blocks. All lower case simplifies the rest
  522. $matches = array();
  523. if (!preg_match_all('#<(\/|)([^<>]*?[^\/])>#', $data, $matches, PREG_SET_ORDER))
  524. {
  525. //echo "No tags found<br />";
  526. return TRUE; // No tags found; so all OK
  527. }
  528. //print_a($matches);
  529. foreach ($matches as $m)
  530. {
  531. // $m[0] is the complete tag; $m[1] is '/' or empty; $m[2] is the tag and any attributes
  532. list ($tag) = explode(' ', $m[2], 2);
  533. if (!isset($tagArray[$tag])) continue; // Not a tag of interest
  534. if ($m[1] == '/')
  535. { // Closing tag
  536. if ($tagArray[$tag] == 0)
  537. {
  538. //echo "Close before open: {$tag}<br />";
  539. return TRUE; // Closing tag before we've had an opening tag
  540. }
  541. $tagArray[$tag]--; // Obviously had at least one opening tag
  542. }
  543. else
  544. { // Opening tag
  545. $tagArray[$tag]++;
  546. }
  547. }
  548. //print_a($tagArray);
  549. foreach ($tagArray as $t)
  550. {
  551. if ($t > 0) return TRUE; // More opening tags than closing tags
  552. }
  553. return FALSE; // OK now
  554. }
  555. /**
  556. * @DEPRECATED XXX TODO Remove this horrible thing which adds junk to a db.
  557. * Checks a string for potentially dangerous HTML tags, including malformed tags
  558. *
  559. */
  560. public function dataFilter($data, $mode='bbcode')
  561. {
  562. $ans = '';
  563. $vetWords = array('<applet', '<body', '<embed', '<frame', '<script','%3Cscript',
  564. '<frameset', '<html', '<iframe', '<style', '<layer', '<link',
  565. '<ilayer', '<meta', '<object', '<plaintext', 'javascript:',
  566. 'vbscript:','data:text/html');
  567. $ret = preg_split('#(\[code.*?\[/code.*?])#mis', $data, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE );
  568. foreach ($ret as $s)
  569. {
  570. if (substr($s, 0, 5) != '[code')
  571. {
  572. $vl = array();
  573. $t = html_entity_decode(rawurldecode($s), ENT_QUOTES, CHARSET);
  574. $t = str_replace(array("\r", "\n", "\t", "\v", "\f", "\0"), '', $t);
  575. $t1 = strtolower($t);
  576. foreach ($vetWords as $vw)
  577. {
  578. if (strpos($t1, $vw) !== FALSE)
  579. {
  580. $vl[] = $vw; // Add to list of words found
  581. }
  582. if (substr($vw, 0, 1) == '<')
  583. {
  584. $vw = '</'.substr($vw, 1);
  585. if (strpos($t1, $vw) !== FALSE)
  586. {
  587. $vl[] = $vw; // Add to list of words found
  588. }
  589. }
  590. }
  591. // More checks here
  592. if (count($vl))
  593. { // Do something
  594. $s = preg_replace_callback('#('.implode('|', $vl).')#mis', array($this, 'modtag'), $t);
  595. }
  596. }
  597. $s = preg_replace('#(?:onmouse.+?|onclick|onfocus)\s*?\=#', '[sanitised]$0[/sanitised]', $s);
  598. $s = preg_replace_callback('#base64([,\(])(.+?)([\)\'\"])#mis', array($this, 'proc64'), $s);
  599. $ans .= $s;
  600. }
  601. if($mode == 'link' && count($vl))
  602. {
  603. return "#sanitized";
  604. }
  605. return $ans;
  606. }
  607. /**
  608. * Check base-64 encoded code
  609. */
  610. private function proc64($match)
  611. {
  612. $decode = base64_decode($match[2]);
  613. return 'base64'.$match[1].base64_encode($this->dataFilter($decode)).$match[3];
  614. }
  615. // XXX REmove ME.
  616. private function modTag($match)
  617. {
  618. $ans = '';
  619. if (isset($match[1]))
  620. {
  621. $chop = intval(strlen($match[1]) / 2);
  622. $ans = substr($match[1], 0, $chop).'##xss##'.substr($match[1], $chop);
  623. }
  624. else
  625. {
  626. $ans = '?????';
  627. }
  628. return '[sanitised]'.$ans.'[/sanitised]';
  629. }
  630. /**
  631. * Processes data as needed before its written to the DB.
  632. * Currently gives bbcodes the opportunity to do something
  633. *
  634. * @param $data string - data about to be written to DB
  635. * @return string - modified data
  636. */
  637. public function preFilter($data)
  638. {
  639. if (!is_object($this->e_bb))
  640. {
  641. require_once(e_HANDLER.'bbcode_handler.php');
  642. $this->e_bb = new e_bbcode;
  643. }
  644. $ret = $this->e_bb->parseBBCodes($data, USERID, 'default', 'PRE'); // $postID = logged in user here
  645. return $ret;
  646. }
  647. function toForm($text)
  648. {
  649. if(empty($text)) // fix - handle proper 0, Space etc values.
  650. {
  651. return $text;
  652. }
  653. $search = array('&#036;', '&quot;', '<', '>');
  654. $replace = array('$', '"', '&lt;', '&gt;');
  655. $text = str_replace($search, $replace, $text);
  656. if (e_WYSIWYG !== TRUE)
  657. {
  658. // fix for utf-8 issue with html_entity_decode(); ???
  659. $text = str_replace("&nbsp;", " ", $text);
  660. }
  661. return $text;
  662. }
  663. function post_toForm($text)
  664. {
  665. if(is_array($text))
  666. {
  667. foreach ($text as $key=>$value)
  668. {
  669. $text[$this->post_toForm($key)] = $this->post_toForm($value);
  670. }
  671. return $text;
  672. }
  673. if(MAGIC_QUOTES_GPC == TRUE)
  674. {
  675. $text = stripslashes($text);
  676. }
  677. return str_replace(array("'", '"', "<", ">"), array("&#039;", "&quot;", "&lt;", "&gt;"), $text);
  678. }
  679. function post_toHTML($text, $original_author = FALSE, $extra = '', $mod = FALSE)
  680. {
  681. $text = $this->toDB($text, FALSE, FALSE, $mod, $original_author);
  682. return $this->toHTML($text, TRUE, $extra);
  683. }
  684. function parseTemplate($text, $parseSCFiles = TRUE, $extraCodes = null, $eVars = null)
  685. {
  686. return e107::getScParser()->parseCodes($text, $parseSCFiles, $extraCodes, $eVars);
  687. }
  688. /**
  689. * Simple parser
  690. *
  691. * @param string $template
  692. * @param e_vars $vars
  693. * @param string $replaceUnset string to be used if replace variable is not set, false - don't replace
  694. * @return string parsed content
  695. */
  696. function simpleParse($template, e_vars $vars, $replaceUnset='')
  697. {
  698. $this->replaceVars = $vars;
  699. $this->replaceUnset = $replaceUnset;
  700. return preg_replace_callback("#\{([a-zA-Z0-9_]+)\}#", array($this, 'simpleReplace'), $template);
  701. }
  702. protected function simpleReplace($tmp)
  703. {
  704. $unset = ($this->replaceUnset !== false ? $this->replaceUnset : $tmp[0]);
  705. $key = $tmp[1];
  706. if(is_array($this->replaceVars))
  707. {
  708. return ($this->replaceVars[$key] !== null ? $this->replaceVars[$key]: $unset);
  709. }
  710. //
  711. return ($this->replaceVars->$tmp[1] !== null ? $this->replaceVars->$tmp[1] : $unset); // Doesn't work.
  712. }
  713. function htmlwrap($str, $width, $break = "\n", $nobreak = "a", $nobr = "pre", $utf = FALSE)
  714. {
  715. /*
  716. Pretty well complete rewrite to try and handle utf-8 properly.
  717. Breaks each utf-8 'word' every $width characters max. If possible, breaks after 'safe' characters.
  718. $break is the character inserted to flag the break.
  719. $nobreak is a list of tags within which word wrap is to be inactive
  720. */
  721. //TODO handle htmlwrap somehow
  722. //return $str;
  723. // Don't wrap if non-numeric width
  724. $width = intval($width);
  725. // And trap stupid wrap counts
  726. if ($width < 6)
  727. return $str;
  728. // Transform protected element lists into arrays
  729. $nobreak = explode(" ", strtolower($nobreak));
  730. // Variable setup
  731. $intag = FALSE;
  732. $innbk = array();
  733. $drain = "";
  734. // List of characters it is "safe" to insert line-breaks at
  735. // It is not necessary to add < and > as they are automatically implied
  736. $lbrks = "/?!%)-}]\\\"':;&";
  737. // Is $str a UTF8 string?
  738. if ($utf || strtolower(CHARSET) == 'utf-8')
  739. {
  740. // 0x1680, 0x180e, 0x2000-0x200a, 0x2028, 0x205f, 0x3000 are 'non-ASCII' Unicode UCS-4 codepoints - see http://www.unicode.org/Public/UNIDATA/UnicodeData.txt
  741. // All convert to 3-byte utf-8 sequences:
  742. // 0x1680 0xe1 0x9a 0x80
  743. // 0x180e 0xe1 0xa0 0x8e
  744. // 0x2000 0xe2 0x80 0x80
  745. // -
  746. // 0x200a 0xe2 0x80 0x8a
  747. // 0x2028 0xe2 0x80 0xa8
  748. // 0x205f 0xe2 0x81 0x9f
  749. // 0x3000 0xe3 0x80 0x80
  750. $utf8 = 'u';
  751. $whiteSpace = '#([\x20|\x0c]|[\xe1][\x9a][\x80]|[\xe1][\xa0][\x8e]|[\xe2][\x80][\x80-\x8a,\xa8]|[\xe2][\x81][\x9f]|[\xe3][\x80][\x80]+)#';
  752. // Have to explicitly enumerate the whitespace chars, and use non-utf-8 mode, otherwise regex fails on badly formed utf-8
  753. }
  754. else
  755. {
  756. $utf8 = '';
  757. // For non-utf-8, can use a simple match string
  758. $whiteSpace = '#(\s+)#';
  759. }
  760. // Start of the serious stuff - split into HTML tags and text between
  761. $content = preg_split('#(<.*?'.'>)#mis', $str, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE );
  762. foreach($content as $value)
  763. {
  764. if ($value[0] == "<")
  765. {
  766. // We are within an HTML tag
  767. // Create a lowercase copy of this tag's contents
  768. $lvalue = strtolower(substr($value, 1, -1));
  769. if ($lvalue)
  770. {
  771. // Tag of non-zero length
  772. // If the first character is not a / then this is an opening tag
  773. if ($lvalue[0] != "/")
  774. {
  775. // Collect the tag name
  776. preg_match("/^(\w*?)(\s|$)/", $lvalue, $t);
  777. // If this is a protected element, activate the associated protection flag
  778. if(in_array($t[1], $nobreak))
  779. array_unshift($innbk, $t[1]);
  780. }
  781. else
  782. {
  783. // Otherwise this is a closing tag
  784. // If this is a closing tag for a protected element, unset the flag
  785. if (in_array(substr($lvalue, 1), $nobreak))
  786. {
  787. reset($innbk);
  788. while (list($key, $tag) = each($innbk))
  789. {
  790. if (substr($lvalue, 1) == $tag)
  791. {
  792. unset($innbk[$key]);
  793. break;
  794. }
  795. }
  796. $innbk = array_values($innbk);
  797. }
  798. }
  799. }
  800. else
  801. {
  802. // Eliminate any empty tags altogether
  803. $value = '';
  804. }
  805. // Else if we're outside any tags, and with non-zero length string...
  806. }
  807. elseif ($value)
  808. {
  809. // If unprotected...
  810. if (!count($innbk))
  811. {
  812. // Use the ACK (006) ASCII symbol to replace all HTML entities temporarily
  813. $value = str_replace("\x06", "", $value);
  814. preg_match_all("/&([a-z\d]{2,7}|#\d{2,5});/i", $value, $ents);
  815. $value = preg_replace("/&([a-z\d]{2,7}|#\d{2,5});/i", "\x06", $value);
  816. // echo "Found block length ".strlen($value).': '.substr($value,20).'<br />';
  817. // Split at spaces - note that this will fail if presented with invalid utf-8 when doing the regex whitespace search
  818. // $split = preg_split('#(\s)#'.$utf8, $value, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE );
  819. $split = preg_split($whiteSpace, $value, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE );
  820. $value = '';
  821. foreach ($split as $sp)
  822. {
  823. // echo "Split length ".strlen($sp).': '.substr($sp,20).'<br />';
  824. $loopCount = 0;
  825. while (strlen($sp) > $width)
  826. {
  827. // Enough characters that we may need to do something.
  828. $pulled = '';
  829. if ($utf8)
  830. {
  831. // Pull out a piece of the maximum permissible length
  832. if (preg_match('#^((?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+){0,'.$width.'})(.{0,1}).*#s',$sp,$matches) == 0)
  833. {
  834. // Make any problems obvious for now
  835. $value .= '[!<b>invalid utf-8: '.$sp.'<b>!]';
  836. $sp = '';
  837. }
  838. elseif (empty($matches[2]))
  839. {
  840. // utf-8 length is less than specified - treat as a special case
  841. $value .= $sp;
  842. $sp = '';
  843. }
  844. else
  845. {
  846. // Need to find somewhere to break the string
  847. for($i = strlen($matches[1]) - 1; $i >= 0; $i--)
  848. {
  849. if(strpos($lbrks, $matches[1][$i]) !== FALSE)
  850. break;
  851. }
  852. if($i < 0)
  853. {
  854. // No 'special' break character found - break at the word boundary
  855. $pulled = $matches[1];
  856. }
  857. else
  858. {
  859. $pulled = substr($sp, 0, $i + 1);
  860. }
  861. }
  862. $loopCount++;
  863. if ($loopCount > 20)
  864. {
  865. // Make any problems obvious for now
  866. $value .= '[!<b>loop count exceeded: '.$sp.'</b>!]';
  867. $sp = '';
  868. }
  869. }
  870. else
  871. {
  872. for ($i = min($width, strlen($sp)); $i > 0; $i--)
  873. {
  874. // No speed advantage to defining match character
  875. if (strpos($lbrks, $sp[$i-1]) !== FALSE)
  876. break;
  877. }
  878. if ($i == 0)
  879. {
  880. // No 'special' break boundary character found - break at the word boundary
  881. $pulled = substr($sp, 0, $width);
  882. }
  883. else
  884. {
  885. $pulled = substr($sp, 0, $i);
  886. }
  887. }
  888. if ($pulled)
  889. {
  890. $value .= $pulled.$break;
  891. // Shorten $sp by whatever we've processed (will work even for utf-8)
  892. $sp = substr($sp, strlen($pulled));
  893. }
  894. }
  895. // Add in any residue
  896. $value .= $sp;
  897. }
  898. // Put captured HTML entities back into the string
  899. foreach ($ents[0] as $ent)
  900. $value = preg_replace("/\x06/", $ent, $value, 1);
  901. }
  902. }
  903. // Send the modified segment down the drain
  904. $drain .= $value;
  905. }
  906. // Return contents of the drain
  907. return $drain;
  908. }
  909. /**
  910. * CakePHP(tm) : Rapid Development Framework (http://www.cakephp.org)
  911. * Copyright 2005-2008, Cake Software Foundation, Inc. (http://www.cakefoundation.org)
  912. *
  913. * Truncate a HTML string
  914. *
  915. * Cuts a string to the length of $length and adds the value of $ending if the text is longer than length.
  916. *
  917. * @param string $text String to truncate.
  918. * @param integer $length Length of returned string, including ellipsis.
  919. * @param string $ending It will be used as Ending and appended to the trimmed string.
  920. * @param boolean $exact If false, $text will not be cut mid-word
  921. * @return string Trimmed string.
  922. */
  923. function html_truncate($text, $length = 100, $ending = '...', $exact = true)
  924. {
  925. if($this->ustrlen(preg_replace('/<.*?>/', '', $text)) <= $length)
  926. {
  927. return $text;
  928. }
  929. $totalLength = 0;
  930. $openTags = array();
  931. $truncate = '';
  932. preg_match_all('/(<\/?([\w+]+)[^>]*>)?([^<>]*)/', $text, $tags, PREG_SET_ORDER);
  933. foreach($tags as $tag)
  934. {
  935. if(!$tag[2] || !preg_match('/img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param/si', $tag[2]))
  936. {
  937. if(preg_match('/<[\w]+[^>]*>/s', $tag[0]))
  938. {
  939. array_unshift($openTags, $tag[2]);
  940. }
  941. else if(preg_match('/<\/([\w]+)[^>]*>/s', $tag[0], $closeTag))
  942. {
  943. $pos = array_search($closeTag[1], $openTags);
  944. if($pos !== false)
  945. {
  946. array_splice($openTags, $pos, 1);
  947. }
  948. }
  949. }
  950. $truncate .= $tag[1];
  951. $contentLength = $this->ustrlen(preg_replace('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|&#x[0-9a-f]{1,6};/i', ' ', $tag[3]));
  952. if($contentLength + $totalLength > $length)
  953. {
  954. $left = $length - $totalLength;
  955. $entitiesLength = 0;
  956. if(preg_match_all('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|&#x[0-9a-f]{1,6};/i', $tag[3], $entities, PREG_OFFSET_CAPTURE))
  957. {
  958. foreach($entities[0] as $entity)
  959. {
  960. if($entity[1] + 1 - $entitiesLength <= $left)
  961. {
  962. $left--;
  963. $entitiesLength += $this->ustrlen($entity[0]);
  964. }
  965. else
  966. {
  967. break;
  968. }
  969. }
  970. }
  971. $truncate .= $this->usubstr($tag[3], 0, $left + $entitiesLength);
  972. break;
  973. }
  974. else
  975. {
  976. $truncate .= $tag[3];
  977. $totalLength += $contentLength;
  978. }
  979. if($totalLength >= $length)
  980. {
  981. break;
  982. }
  983. }
  984. if(!$exact)
  985. {
  986. $spacepos = $this->ustrrpos($truncate, ' ');
  987. if(isset($spacepos))
  988. {
  989. $bits = $this->usubstr($truncate, $spacepos);
  990. preg_match_all('/<\/([a-z]+)>/i', $bits, $droppedTags, PREG_SET_ORDER);
  991. if(!empty($droppedTags))
  992. {
  993. foreach($droppedTags as $closingTag)
  994. {
  995. if(!in_array($closingTag[1], $openTags))
  996. {
  997. array_unshift($openTags, $closingTag[1]);
  998. }
  999. }
  1000. }
  1001. $truncate = $this->usubstr($truncate, 0, $spacepos);
  1002. }
  1003. }
  1004. $truncate .= $ending;
  1005. foreach($openTags as $tag)
  1006. {
  1007. $truncate .= '</' . $tag . '>';
  1008. }
  1009. return $truncate;
  1010. }
  1011. /**
  1012. * Truncate a HTML string to a maximum length $len ­ append the string $more if it was truncated
  1013. *
  1014. * @param string $text String to process
  1015. * @param integer $len [optional] Length of characters to be truncated - default 200
  1016. * @param string $more [optional] String which will be added if truncation - default ' ... '
  1017. * @return string
  1018. */
  1019. public function html_truncate_old ($text, $len = 200, $more = ' ... ')
  1020. {
  1021. $pos = 0;
  1022. $curlen = 0;
  1023. $tmp_pos = 0;
  1024. $intag = FALSE;
  1025. while($curlen < $len && $curlen < strlen($text))
  1026. {
  1027. switch($text {$pos} )
  1028. {
  1029. case "<":
  1030. if($text {$pos + 1} == "/")
  1031. {
  1032. $closing_tag = TRUE;
  1033. }
  1034. $intag = TRUE;
  1035. $tmp_pos = $pos - 1;
  1036. $pos++;
  1037. break;
  1038. case ">":
  1039. if($text {$pos - 1} == "/")
  1040. {
  1041. $closing_tag = TRUE;
  1042. }
  1043. if($closing_tag == TRUE)
  1044. {
  1045. $tmp_pos = 0;
  1046. $closing_tag = FALSE;
  1047. }
  1048. $intag = FALSE;
  1049. $pos++;
  1050. break;
  1051. case "&":
  1052. if($text {$pos + 1} == "#")
  1053. {
  1054. $end = strpos(substr($text, $pos, 7), ";");
  1055. if($end !== FALSE)
  1056. {
  1057. $pos += ($end + 1);
  1058. if(!$intag)
  1059. {
  1060. $curlen++;
  1061. }
  1062. break;
  1063. }
  1064. }
  1065. else
  1066. {
  1067. $pos++;
  1068. if(!$intag)
  1069. {
  1070. $curlen++;
  1071. }
  1072. break;
  1073. }
  1074. default:
  1075. $pos++;
  1076. if(!$intag)
  1077. {
  1078. $curlen++;
  1079. }
  1080. break;
  1081. }
  1082. }
  1083. $ret = ($tmp_pos > 0 ? substr($text, 0, $tmp_pos+1) : substr($text, 0, $pos));
  1084. if($pos < strlen($text))
  1085. {
  1086. $ret = $ret.$more;
  1087. }
  1088. return $ret;
  1089. }
  1090. /**
  1091. * Truncate a string of text to a maximum length $len ­ append the string $more if it was truncated
  1092. * Uses current CHARSET ­ for utf-8, returns $len characters rather than $len bytes
  1093. *
  1094. * @param string $text ­ string to process
  1095. * @param integer $len ­ length of characters to be truncated
  1096. * @param string $more ­ string which will be added if truncation
  1097. * @return string
  1098. */
  1099. public function text_truncate($text, $len = 200, $more = ' ... ')
  1100. {
  1101. // Always valid
  1102. if($this->ustrlen($text) <= $len)
  1103. {
  1104. return $text;
  1105. }
  1106. $ret = $this->usubstr($text, 0, $len);
  1107. // search for possible broken html entities
  1108. // - if an & is in the last 8 chars, removing it and whatever follows shouldn't hurt
  1109. // it should work for any characters encoding
  1110. // FIXME - INVESTIGATE this one, switch to utf8 aware methods
  1111. $leftAmp = $this->ustrrpos($this->usubstr($ret, -8), '&');
  1112. if($leftAmp)
  1113. {
  1114. $ret = $this->usubstr($ret, 0, $this->ustrlen($ret) - 8 + $leftAmp);
  1115. }
  1116. return $ret.$more;
  1117. }
  1118. function textclean ($text, $wrap = 100)
  1119. {
  1120. $text = str_replace("\n\n\n", "\n\n", $text);
  1121. $text = $this->htmlwrap($text, $wrap);
  1122. $text = str_replace(array('<br /> ', ' <br />', ' <br /> '), '<br />', $text);
  1123. /* we can remove any linebreaks added by htmlwrap function as any \n's will be converted later anyway */
  1124. return $text;
  1125. }
  1126. // Test for text highlighting, and determine the text highlighting transformation
  1127. // Returns TRUE if highlighting is active for this page display
  1128. function checkHighlighting()
  1129. {
  1130. global $pref;
  1131. if (!defined('e_SELF'))
  1132. {
  1133. // Still in startup, so can't calculate highlighting
  1134. return FALSE;
  1135. }
  1136. if(!isset($this->e_highlighting))
  1137. {
  1138. $this->e_highlighting = FALSE;
  1139. $shr = (isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : "");
  1140. if($pref['search_highlight'] && (strpos(e_SELF, 'search.php') === FALSE) && ((strpos($shr, 'q=') !== FALSE) || (strpos($shr, 'p=') !== FALSE)))
  1141. {
  1142. $this->e_highlighting = TRUE;
  1143. if(!isset($this->e_query))
  1144. {
  1145. $query = preg_match('#(q|p)=(.*?)(&|$)#', $shr, $matches);
  1146. $this->e_query = str_replace(array('+', '*', '"', ' '), array('', '.*?', '', '\b|\b'), trim(urldecode($matches[2])));
  1147. }
  1148. }
  1149. }
  1150. return $this->e_highlighting;
  1151. }
  1152. /**
  1153. * Converts the text (presumably retrieved from the database) for HTML output.
  1154. *
  1155. * @param string $text
  1156. * @param boolean $parseBB [optional]
  1157. * @param string $modifiers [optional] TITLE|SUMMARY|DESCRIPTION|BODY|RAW|LINKTEXT etc.
  1158. * Comma-separated list, no spaces allowed
  1159. * first modifier must be a CONTEXT modifier, in UPPER CASE.
  1160. * subsequent modifiers are lower case - see $this->e_Modifiers for possible values
  1161. * @param mixed $postID [optional]
  1162. * @param boolean $wrap [optional]
  1163. * @return string
  1164. * @todo complete the documentation of this essential method
  1165. */
  1166. public function toHTML($text, $parseBB = FALSE, $modifiers = '', $postID = '', $wrap = FALSE)
  1167. {
  1168. if($text == '')
  1169. {
  1170. return $text;
  1171. }
  1172. $pref = e107::getPref();
  1173. global $fromadmin;
  1174. // Set default modifiers to start
  1175. $opts = $this->e_optDefault;
  1176. // Now process any modifiers that are specified
  1177. if ($modifiers)
  1178. {
  1179. $aMods = explode(',', $modifiers);
  1180. // If there's a supermodifier, it must be first, and in uppercase
  1181. $psm = trim($aMods[0]);
  1182. if (isset($this->e_SuperMods[$psm]))
  1183. {
  1184. // Supermodifier found - override default values where necessary
  1185. $opts = array_merge($opts,$this->e_SuperMods[$psm]);
  1186. $opts['context'] = $psm;
  1187. unset($aMods[0]);
  1188. }
  1189. // Now find any regular modifiers; use them to modify the context
  1190. // (there should only be one or two out of the list of possibles)
  1191. foreach ($aMods as $mod)
  1192. {
  1193. // Slight concession to varying coding styles - stripping spaces is a waste of CPU cycles!
  1194. $mod = trim($mod);
  1195. if (isset($this->e_Modifiers[$mod]))
  1196. {
  1197. // This is probably quicker than array_merge
  1198. // - especially as usually only one or two loops
  1199. foreach ($this->e_Modifiers[$mod] as $k => $v)
  1200. {
  1201. // Update our context-specific options
  1202. $opts[$k] = $v;
  1203. }
  1204. }
  1205. }
  1206. }
  1207. // Turn off a few things if not enabled in options
  1208. if(!varsettrue($pref['smiley_activate']))
  1209. {
  1210. $opts['emotes'] = FALSE;
  1211. }
  1212. if(!varsettrue($pref['make_clickable']))
  1213. {
  1214. $opts['link_click'] = FALSE;
  1215. }
  1216. if(!varsettrue($pref['link_replace']))
  1217. {
  1218. $opts['link_replace'] = FALSE;
  1219. }
  1220. $fromadmin = $opts['fromadmin'];
  1221. // Convert defines(constants) within text. eg. Lan_XXXX - must be the entire text string (i.e. not embedded)
  1222. // The check for '::' is a workaround for a bug in the Zend Optimiser 3.3.0 and PHP 5.2.4 combination
  1223. // - causes crashes if '::' in site name
  1224. if($opts['defs'] && (strlen($text) < 35) && ((strpos($text, '::') === FALSE) && defined(trim($text))))
  1225. {
  1226. return constant(trim($text));
  1227. }
  1228. if ($opts['no_tags'])
  1229. {
  1230. $text = strip_tags($text);
  1231. }
  1232. if (MAGIC_QUOTES_GPC == TRUE) // precaution for badly saved data.
  1233. {
  1234. $text = stripslashes($text);
  1235. }
  1236. // Make sure we have a valid count for word wrapping
  1237. if (!$wrap && $pref['main_wordwrap'])
  1238. {
  1239. $wrap = $pref['main_wordwrap'];
  1240. }
  1241. // $text = " ".$text;
  1242. // Now get on with the parsing
  1243. $ret_parser = '';
  1244. $last_bbcode = '';
  1245. // So we can change them on each loop
  1246. $saveOpts = $opts;
  1247. if ($parseBB == FALSE)
  1248. {
  1249. $content = array($text);
  1250. }
  1251. else
  1252. {
  1253. // Split each text block into bits which are either within one of the 'key' bbcodes, or outside them
  1254. // (Because we have to match end words, the 'extra' capturing subpattern gets added to output array. We strip it later)
  1255. $content = preg_split('#(\[(table|html|php|code|scode|hide).*?\[/(?:\\2)\])#mis', $text, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE );
  1256. }
  1257. // Use $full_text variable so its available to special bbcodes if required
  1258. foreach ($content as $full_text)
  1259. {
  1260. $proc_funcs = TRUE;
  1261. $convertNL = TRUE;
  1262. // We may have 'captured' a bbcode word - strip it if so
  1263. if ($last_bbcode == $full_text)
  1264. {
  1265. $last_bbcode = '';
  1266. $proc_funcs = FALSE;
  1267. $full_text = '';
  1268. }
  1269. else
  1270. {
  1271. // Set the options for this pass
  1272. $opts = $saveOpts;
  1273. // Have to have a good test in case a 'non-key' bbcode starts the block
  1274. // - so pull out the bbcode parameters while we're there
  1275. if (($parseBB !== FALSE) && preg_match('#(^\[(table|html|php|code|scode|hide)(.*?)\])(.*?)(\[/\\2\]$)#is', $full_text, $matches ))
  1276. {
  1277. // It's one of the 'key' bbcodes
  1278. // Usually don't want 'normal' processing if its a 'special' bbcode
  1279. $proc_funcs = FALSE;
  1280. // $matches[0] - complete block from opening bracket of opening tag to closing bracket of closing tag
  1281. // $matches[1] - complete opening tag (inclusive of brackets)
  1282. // $matches[2] - bbcode word
  1283. // $matches[3] - parameter, including '='
  1284. // $matches[4] - bit between the tags (i.e. text to process)
  1285. // $matches[5] - closing tag
  1286. // In case we decide to load a file
  1287. $bbPath = e_CORE.'bbcodes/';
  1288. $bbFile = strtolower(str_replace('_', '', $matches[2]));
  1289. $bbcode = '';
  1290. $className = '';
  1291. $full_text = '';
  1292. $code_text = $matches[4];
  1293. $parm = $matches[3] ? substr($matches[3],1) : '';
  1294. $last_bbcode = $matches[2];
  1295. switch ($matches[2])
  1296. {
  1297. case 'php' :
  1298. // Probably run the output through the normal processing functions - but put here so the PHP code can disable if desired
  1299. $proc_funcs = TRUE;
  1300. // This is just the contents of the php.bb file pulled in - its short, so will be quicker
  1301. // $search = array("&quot;", "&#039;", "&#036;", '<br />', E_NL, "-&gt;", "&lt;br /&gt;");
  1302. // $replace = array('"', "'", "$", "\n", "\n", "->", "<br />");
  1303. // Shouldn't have any parameter on this bbcode
  1304. // Not sure whether checks are necessary now we've reorganised
  1305. // if (!$matches[3]) $bbcode = str_replace($search, $replace, $matches[4]);
  1306. // Because we're bypassing most of the initial parser processing, we should be able to just reverse the effects of toDB() and execute the code
  1307. // [SecretR] - avoid php code injections, missing php.bb will completely disable user posted php blocks
  1308. $bbcode = file_get_contents($bbPath.$bbFile.'.bb');
  1309. if (!$matches[3])
  1310. {
  1311. $code_text = html_entity_decode($matches[4], ENT_QUOTES, 'UTF-8');
  1312. }
  1313. break;
  1314. case 'html' : // This overrides and deprecates html.bb
  1315. $proc_funcs = TRUE;
  1316. $noBreak = TRUE;
  1317. // $code_text = str_replace("\r\n", " ", $code_text);
  1318. $code_text = html_entity_decode($code_text, ENT_QUOTES, CHARSET);
  1319. $html_start = "<!-- bbcode-html-start -->"; // markers for html-to-bbcode replacement.
  1320. $html_end = "<!-- bbcode-html-end -->";
  1321. $full_text = str_replace(array("[html]","[/html]"), "",$code_text); // quick fix.. security issue?
  1322. $full_text =$this->replaceConstants($full_text,'abs');
  1323. $full_text = $html_start.$full_text.$html_end;
  1324. $full_text = $this->parseBBTags($full_text); // strip <bbcode> tags.
  1325. $opts['nobreak'] = true;
  1326. break;
  1327. case 'table' : // strip <br /> from inside of <table>
  1328. $convertNL = FALSE;
  1329. // break;
  1330. case 'hide' :
  1331. $proc_funcs = TRUE;
  1332. default : // Most bbcodes will just execute their normal file
  1333. // @todo should we cache these bbcodes? require_once should make class-related codes quite efficient
  1334. if (file_exists($bbPath.'bb_'.$bbFile.'.php'))
  1335. { // Its a bbcode class file
  1336. require_once($bbPath.'bb_'.$bbFile.'.php');
  1337. $className = 'bb_'.$last_bbcode;
  1338. $this->bbList[$last_bbcode] = new $className();
  1339. }
  1340. elseif(file_exists($bbPath.$bbFile.'.bb'))
  1341. {
  1342. $bbcode = file_get_contents($bbPath.$bbFile.'.bb');
  1343. }
  1344. } // end - switch ($matches[2])
  1345. if ($className)
  1346. {
  1347. $tempCode = new $className();
  1348. $full_text = $tempCode->bbPreDisplay($matches[4], $parm);
  1349. }
  1350. elseif ($bbcode)
  1351. { // Execute the file
  1352. $full_text = eval($bbcode); // Require output of bbcode to be returned
  1353. // added to remove possibility of nested bbcode exploits ...
  1354. // (same as in bbcode_handler - is it right that it just operates on $bbcode_return and not on $bbcode_output? - QUERY XXX-02
  1355. }
  1356. if(strpos($full_text, '[') !== FALSE)
  1357. {
  1358. $exp_search = array('eval', 'expression');
  1359. $exp_replace = array('ev<b></b>al', 'expres<b></b>sion');
  1360. $bbcode_return = str_replace($exp_search, $exp_replace, $full_text);
  1361. }
  1362. }
  1363. }
  1364. // Do the 'normal' processing - in principle, as previously - but think about the order.
  1365. if ($proc_funcs && !empty($full_text)) // some more speed
  1366. {
  1367. // Split out and ignore any scripts and style blocks. With just two choices we can match the closing tag in the regex
  1368. $subcon = preg_split('#((?:<s)(?:cript[^>]+>.*?</script>|tyle[^>]+>.*?</style>))#mis', $full_text, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE );
  1369. foreach ($subcon as $sub_blk)
  1370. {
  1371. if(substr($sub_blk, 0, 7) == '<script')
  1372. {
  1373. if($opts['scripts'])
  1374. {
  1375. // Strip scripts unless permitted
  1376. $ret_parser .= $sub_blk;
  1377. }
  1378. }
  1379. elseif(substr($sub_blk, 0, 6) == '<style')
  1380. {
  1381. // Its a style block - just pass it through unaltered - except, do we need the line break stuff? - QUERY XXX-01
  1382. if(DB_INF_SHOW)
  1383. {
  1384. echo "Processing stylesheet: {$sub_blk}<br />";
  1385. }
  1386. $ret_parser .= $sub_blk;
  1387. }
  1388. else
  1389. {
  1390. // Do 'normal' processing on a chunk
  1391. // Could put tag stripping in here
  1392. /*
  1393. // Line break compression - filter white space after HTML tags - among other things, ensures HTML tables display properly
  1394. // Hopefully now achieved by other means
  1395. if ($convertNL && !$opts['nobreak'])
  1396. {
  1397. $sub_blk = preg_replace("#>\s*[\r]*\n[\r]*#", ">", $sub_blk);
  1398. }
  1399. */
  1400. // Link substitution
  1401. // Convert URL's to clickable links, unless modifiers or prefs override
  1402. if ($opts['link_click'])
  1403. {
  1404. if ($opts['link_replace'])
  1405. {
  1406. $_ext = ($pref['links_new_window'] ? " rel=\"external\"" : "");
  1407. // $sub_blk = preg_replace("#(^|[\s])([\w]+?://(?:[\w-%]+?)(?:\.[\w-%]+?)+.*?)(?=$|[\s()[\]<]|\.\s|\.$|,\s|,$)#is", "\\1<a href=\"\\2\" {$_ext}>".$pref['link_text']."</a>", $sub_blk);
  1408. // $sub_blk = preg_replace("#(^|[\s])((?:www|ftp)(?:\.[\w-%]+?){2}.*?)(?=$|[\s()[\]<]|\.\s|\.$|,\s|,$)#is", "\\1<a href=\"http://\\2\" {$_ext}>".$pref['link_text']."</a>", $sub_blk);
  1409. $sub_blk = preg_replace("#(^|[\s])([\w]+?://(?:[\w-%]+?)(?:\.[\w-%]+?)+.*?)(?=$|[\s[\]<]|\.\s|\.$|,\s|,$)#is", "\\1<a href=\"\\2\" {$_ext}>".$pref['link_text']."</a>", $sub_blk);
  1410. $sub_blk = preg_replace("#(^|[\s])((?:www|ftp)(?:\.[\w-%]+?){2}.*?)(?=$|[\s[\]<]|\.\s|\.$|,\s|,$)#is", "\\1<a href=\"http://\\2\" {$_ext}>".$pref['link_text']."</a>", $sub_blk);
  1411. $email_text = ($pref['email_text']) ? $this->replaceConstants($pref['email_text']) : LAN_EMAIL_SUBS;
  1412. $sub_blk = preg_replace("#([\n ])([a-z0-9\-_.]+?)@([\w\-]+\.([\w\-\.]+\.)*[\w]+)#i", "\\1<a rel='external' href='javascript:window.location=\"mai\"+\"lto:\"+\"\\2\"+\"@\"+\"\\3\";self.close();' onmouseover='window.status=\"mai\"+\"lto:\"+\"\\2\"+\"@\"+\"\\3\"; return true;' onmouseout='window.status=\"\";return true;'>".$email_text."</a>", $sub_blk);
  1413. }
  1414. else
  1415. {
  1416. $email_text = '$1$2©$3';
  1417. // $sub_blk = preg_replace("#(^|[\s])([\w]+?://(?:[\w-%]+?)(?:\.[\w-%]+?)+.*?)(?=$|[\s()[\]<]|\.\s|\.$|,\s|,$)#is", "\\1<a href=\"\\2\" rel=\"external\">\\2</a…

Large files files are truncated, but you can click here to view the full file