PageRenderTime 49ms CodeModel.GetById 10ms RepoModel.GetById 1ms app.codeStats 0ms

/php/Sources/Subs-Editor.php

https://github.com/dekoza/openshift-smf-2.0.7
PHP | 2171 lines | 1603 code | 273 blank | 295 comment | 278 complexity | 48dca7044982e40d1313b12c6bc631c1 MD5 | raw file
Possible License(s): BSD-3-Clause

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

  1. <?php
  2. /**
  3. * Simple Machines Forum (SMF)
  4. *
  5. * @package SMF
  6. * @author Simple Machines http://www.simplemachines.org
  7. * @copyright 2011 Simple Machines
  8. * @license http://www.simplemachines.org/about/smf/license.php BSD
  9. *
  10. * @version 2.0.7
  11. */
  12. if (!defined('SMF'))
  13. die('Hacking attempt...');
  14. /* This file contains those functions specific to the editing box and is
  15. generally used for WYSIWYG type functionality. Doing all this is the
  16. following:
  17. void EditorMain()
  18. // !!
  19. void bbc_to_html()
  20. // !!
  21. void html_to_bbc()
  22. // !!
  23. void theme_postbox(string message)
  24. - for compatibility - passes right through to the template_control_richedit function.
  25. void create_control_richedit(&array editorOptions)
  26. // !!
  27. void create_control_verification(&array suggestOptions)
  28. // !!
  29. void fetchTagAttributes()
  30. // !!
  31. array getMessageIcons(int board_id)
  32. - retrieves a list of message icons.
  33. - based on the settings, the array will either contain a list of default
  34. message icons or a list of custom message icons retrieved from the
  35. database.
  36. - the board_id is needed for the custom message icons (which can be set for
  37. each board individually).
  38. void AutoSuggestHandler(string checkRegistered = null)
  39. // !!!
  40. void AutoSuggest_Search_Member()
  41. // !!!
  42. */
  43. // At the moment this is only used for returning WYSIWYG data...
  44. function EditorMain()
  45. {
  46. global $context, $smcFunc;
  47. checkSession('get');
  48. if (!isset($_REQUEST['view']) || !isset($_REQUEST['message']))
  49. fatal_lang_error('no_access', false);
  50. $context['sub_template'] = 'sendbody';
  51. $context['view'] = (int) $_REQUEST['view'];
  52. // Return the right thing for the mode.
  53. if ($context['view'])
  54. {
  55. $_REQUEST['message'] = strtr($_REQUEST['message'], array('#smcol#' => ';', '#smlt#' => '&lt;', '#smgt#' => '&gt;', '#smamp#' => '&amp;'));
  56. $context['message'] = bbc_to_html($_REQUEST['message']);
  57. }
  58. else
  59. {
  60. $_REQUEST['message'] = un_htmlspecialchars($_REQUEST['message']);
  61. $_REQUEST['message'] = strtr($_REQUEST['message'], array('#smcol#' => ';', '#smlt#' => '&lt;', '#smgt#' => '&gt;', '#smamp#' => '&amp;'));
  62. $context['message'] = html_to_bbc($_REQUEST['message']);
  63. }
  64. $context['message'] = $smcFunc['htmlspecialchars']($context['message']);
  65. }
  66. // Convert only the BBC that can be edited in HTML mode for the editor.
  67. function bbc_to_html($text)
  68. {
  69. global $modSettings, $smcFunc;
  70. // Turn line breaks back into br's.
  71. $text = strtr($text, array("\r" => '', "\n" => '<br />'));
  72. // Prevent conversion of all bbcode inside these bbcodes.
  73. // !!! Tie in with bbc permissions ?
  74. foreach (array('code', 'php', 'nobbc') as $code)
  75. {
  76. if (strpos($text, '['. $code) !== false)
  77. {
  78. $parts = preg_split('~(\[/' . $code . '\]|\[' . $code . '(?:=[^\]]+)?\])~i', $text, -1, PREG_SPLIT_DELIM_CAPTURE);
  79. // Only mess with stuff inside tags.
  80. for ($i = 0, $n = count($parts); $i < $n; $i++)
  81. {
  82. // Value of 2 means we're inside the tag.
  83. if ($i % 4 == 2)
  84. $parts[$i] = strtr($parts[$i], array('[' => '&#91;', ']' => '&#93;', "'" => "'"));
  85. }
  86. // Put our humpty dumpty message back together again.
  87. $text = implode('', $parts);
  88. }
  89. }
  90. // What tags do we allow?
  91. $allowed_tags = array('b', 'u', 'i', 's', 'hr', 'list', 'li', 'font', 'size', 'color', 'img', 'left', 'center', 'right', 'url', 'email', 'ftp', 'sub', 'sup');
  92. $text = parse_bbc($text, true, '', $allowed_tags);
  93. // Fix for having a line break then a thingy.
  94. $text = strtr($text, array('<br /><div' => '<div', "\n" => '', "\r" => ''));
  95. // Note that IE doesn't understand spans really - make them something "legacy"
  96. $working_html = array(
  97. '~<del>(.+?)</del>~i' => '<strike>$1</strike>',
  98. '~<span\sclass="bbc_u">(.+?)</span>~i' => '<u>$1</u>',
  99. '~<span\sstyle="color:\s*([#\d\w]+);" class="bbc_color">(.+?)</span>~i' => '<font color="$1">$2</font>',
  100. '~<span\sstyle="font-family:\s*([#\d\w\s]+);" class="bbc_font">(.+?)</span>~i' => '<font face="$1">$2</font>',
  101. '~<div\sstyle="text-align:\s*(left|right);">(.+?)</div>~i' => '<p align="$1">$2</p>',
  102. );
  103. $text = preg_replace(array_keys($working_html), array_values($working_html), $text);
  104. // Parse unique ID's and disable javascript into the smileys - using the double space.
  105. $text = preg_replace_callback('~(?:\s|&nbsp;)?<(img\ssrc="' . preg_quote($modSettings['smileys_url'], '~') . '/[^<>]+?/([^<>]+?)"\s*)[^<>]*?class="smiley" />~', create_function('$m', 'static $i = 1; return \'<\' . ' . 'stripslashes($m[1]) . \'alt="" title="" onresizestart="return false;" id="smiley_\' . ' . "\$" . 'i++ . \'_\' . $m[2] . \'" style="padding: 0 3px 0 3px;" />\';'), $text);
  106. return $text;
  107. }
  108. // The harder one - wysiwyg to BBC!
  109. function html_to_bbc($text)
  110. {
  111. global $modSettings, $smcFunc, $sourcedir, $scripturl, $context;
  112. // Replace newlines with spaces, as that's how browsers usually interpret them.
  113. $text = preg_replace("~\s*[\r\n]+\s*~", ' ', $text);
  114. // Though some of us love paragraphs, the parser will do better with breaks.
  115. $text = preg_replace('~</p>\s*?<p~i', '</p><br /><p', $text);
  116. $text = preg_replace('~</p>\s*(?!<)~i', '</p><br />', $text);
  117. // Safari/webkit wraps lines in Wysiwyg in <div>'s.
  118. if ($context['browser']['is_webkit'])
  119. $text = preg_replace(array('~<div(?:\s(?:[^<>]*?))?' . '>~i', '</div>'), array('<br />', ''), $text);
  120. // If there's a trailing break get rid of it - Firefox tends to add one.
  121. $text = preg_replace('~<br\s?/?' . '>$~i', '', $text);
  122. // Remove any formatting within code tags.
  123. if (strpos($text, '[code') !== false)
  124. {
  125. $text = preg_replace('~<br\s?/?' . '>~i', '#smf_br_spec_grudge_cool!#', $text);
  126. $parts = preg_split('~(\[/code\]|\[code(?:=[^\]]+)?\])~i', $text, -1, PREG_SPLIT_DELIM_CAPTURE);
  127. // Only mess with stuff outside [code] tags.
  128. for ($i = 0, $n = count($parts); $i < $n; $i++)
  129. {
  130. // Value of 2 means we're inside the tag.
  131. if ($i % 4 == 2)
  132. $parts[$i] = strip_tags($parts[$i]);
  133. }
  134. $text = strtr(implode('', $parts), array('#smf_br_spec_grudge_cool!#' => '<br />'));
  135. }
  136. // Remove scripts, style and comment blocks.
  137. $text = preg_replace('~<script[^>]*[^/]?' . '>.*?</script>~i', '', $text);
  138. $text = preg_replace('~<style[^>]*[^/]?' . '>.*?</style>~i', '', $text);
  139. $text = preg_replace('~\\<\\!--.*?-->~i', '', $text);
  140. $text = preg_replace('~\\<\\!\\[CDATA\\[.*?\\]\\]\\>~i', '', $text);
  141. // Do the smileys ultra first!
  142. preg_match_all('~<img\s+[^<>]*?id="*smiley_\d+_([^<>]+?)[\s"/>]\s*[^<>]*?/*>(?:\s)?~i', $text, $matches);
  143. if (!empty($matches[0]))
  144. {
  145. // Easy if it's not custom.
  146. if (empty($modSettings['smiley_enable']))
  147. {
  148. $smileysfrom = array('>:D', ':D', '::)', '>:(', ':)', ';)', ';D', ':(', ':o', '8)', ':P', '???', ':-[', ':-X', ':-*', ':\'(', ':-\\', '^-^', 'O0', 'C:-)', '0:)');
  149. $smileysto = array('evil.gif', 'cheesy.gif', 'rolleyes.gif', 'angry.gif', 'smiley.gif', 'wink.gif', 'grin.gif', 'sad.gif', 'shocked.gif', 'cool.gif', 'tongue.gif', 'huh.gif', 'embarrassed.gif', 'lipsrsealed.gif', 'kiss.gif', 'cry.gif', 'undecided.gif', 'azn.gif', 'afro.gif', 'police.gif', 'angel.gif');
  150. foreach ($matches[1] as $k => $file)
  151. {
  152. $found = array_search($file, $smileysto);
  153. // Note the weirdness here is to stop double spaces between smileys.
  154. if ($found)
  155. $matches[1][$k] = '-[]-smf_smily_start#|#' . htmlspecialchars($smileysfrom[$found]) . '-[]-smf_smily_end#|#';
  156. else
  157. $matches[1][$k] = '';
  158. }
  159. }
  160. else
  161. {
  162. // Load all the smileys.
  163. $names = array();
  164. foreach ($matches[1] as $file)
  165. $names[] = $file;
  166. $names = array_unique($names);
  167. if (!empty($names))
  168. {
  169. $request = $smcFunc['db_query']('', '
  170. SELECT code, filename
  171. FROM {db_prefix}smileys
  172. WHERE filename IN ({array_string:smiley_filenames})',
  173. array(
  174. 'smiley_filenames' => $names,
  175. )
  176. );
  177. $mappings = array();
  178. while ($row = $smcFunc['db_fetch_assoc']($request))
  179. $mappings[$row['filename']] = htmlspecialchars($row['code']);
  180. $smcFunc['db_free_result']($request);
  181. foreach ($matches[1] as $k => $file)
  182. if (isset($mappings[$file]))
  183. $matches[1][$k] = '-[]-smf_smily_start#|#' . $mappings[$file] . '-[]-smf_smily_end#|#';
  184. }
  185. }
  186. // Replace the tags!
  187. $text = str_replace($matches[0], $matches[1], $text);
  188. // Now sort out spaces
  189. $text = str_replace(array('-[]-smf_smily_end#|#-[]-smf_smily_start#|#', '-[]-smf_smily_end#|#', '-[]-smf_smily_start#|#'), ' ', $text);
  190. }
  191. // Only try to buy more time if the client didn't quit.
  192. if (connection_aborted() && $context['server']['is_apache'])
  193. @apache_reset_timeout();
  194. $parts = preg_split('~(<[A-Za-z]+\s*[^<>]*?style="?[^<>"]+"?[^<>]*?(?:/?)>|</[A-Za-z]+>)~', $text, -1, PREG_SPLIT_DELIM_CAPTURE);
  195. $replacement = '';
  196. $stack = array();
  197. foreach ($parts as $part)
  198. {
  199. if (preg_match('~(<([A-Za-z]+)\s*[^<>]*?)style="?([^<>"]+)"?([^<>]*?(/?)>)~', $part, $matches) === 1)
  200. {
  201. // If it's being closed instantly, we can't deal with it...yet.
  202. if ($matches[5] === '/')
  203. continue;
  204. else
  205. {
  206. // Get an array of styles that apply to this element. (The strtr is there to combat HTML generated by Word.)
  207. $styles = explode(';', strtr($matches[3], array('&quot;' => '')));
  208. $curElement = $matches[2];
  209. $precedingStyle = $matches[1];
  210. $afterStyle = $matches[4];
  211. $curCloseTags = '';
  212. $extra_attr = '';
  213. foreach ($styles as $type_value_pair)
  214. {
  215. // Remove spaces and convert uppercase letters.
  216. $clean_type_value_pair = strtolower(strtr(trim($type_value_pair), '=', ':'));
  217. // Something like 'font-weight: bold' is expected here.
  218. if (strpos($clean_type_value_pair, ':') === false)
  219. continue;
  220. // Capture the elements of a single style item (e.g. 'font-weight' and 'bold').
  221. list ($style_type, $style_value) = explode(':', $type_value_pair);
  222. $style_value = trim($style_value);
  223. switch (trim($style_type))
  224. {
  225. case 'font-weight':
  226. if ($style_value === 'bold')
  227. {
  228. $curCloseTags .= '[/b]';
  229. $replacement .= '[b]';
  230. }
  231. break;
  232. case 'text-decoration':
  233. if ($style_value == 'underline')
  234. {
  235. $curCloseTags .= '[/u]';
  236. $replacement .= '[u]';
  237. }
  238. elseif ($style_value == 'line-through')
  239. {
  240. $curCloseTags .= '[/s]';
  241. $replacement .= '[s]';
  242. }
  243. break;
  244. case 'text-align':
  245. if ($style_value == 'left')
  246. {
  247. $curCloseTags .= '[/left]';
  248. $replacement .= '[left]';
  249. }
  250. elseif ($style_value == 'center')
  251. {
  252. $curCloseTags .= '[/center]';
  253. $replacement .= '[center]';
  254. }
  255. elseif ($style_value == 'right')
  256. {
  257. $curCloseTags .= '[/right]';
  258. $replacement .= '[right]';
  259. }
  260. break;
  261. case 'font-style':
  262. if ($style_value == 'italic')
  263. {
  264. $curCloseTags .= '[/i]';
  265. $replacement .= '[i]';
  266. }
  267. break;
  268. case 'color':
  269. $curCloseTags .= '[/color]';
  270. $replacement .= '[color=' . $style_value . ']';
  271. break;
  272. case 'font-size':
  273. // Sometimes people put decimals where decimals should not be.
  274. if (preg_match('~(\d)+\.\d+(p[xt])~i', $style_value, $dec_matches) === 1)
  275. $style_value = $dec_matches[1] . $dec_matches[2];
  276. $curCloseTags .= '[/size]';
  277. $replacement .= '[size=' . $style_value . ']';
  278. break;
  279. case 'font-family':
  280. // Only get the first freaking font if there's a list!
  281. if (strpos($style_value, ',') !== false)
  282. $style_value = substr($style_value, 0, strpos($style_value, ','));
  283. $curCloseTags .= '[/font]';
  284. $replacement .= '[font=' . strtr($style_value, array("'" => '')) . ']';
  285. break;
  286. // This is a hack for images with dimensions embedded.
  287. case 'width':
  288. case 'height':
  289. if (preg_match('~[1-9]\d*~i', $style_value, $dimension) === 1)
  290. $extra_attr .= ' ' . $style_type . '="' . $dimension[0] . '"';
  291. break;
  292. case 'list-style-type':
  293. if (preg_match('~none|disc|circle|square|decimal|decimal-leading-zero|lower-roman|upper-roman|lower-alpha|upper-alpha|lower-greek|lower-latin|upper-latin|hebrew|armenian|georgian|cjk-ideographic|hiragana|katakana|hiragana-iroha|katakana-iroha~i', $style_value, $listType) === 1)
  294. $extra_attr .= ' listtype="' . $listType[0] . '"';
  295. break;
  296. }
  297. }
  298. // Preserve some tags stripping the styling.
  299. if (in_array($matches[2], array('a', 'font')))
  300. {
  301. $replacement .= $precedingStyle . $afterStyle;
  302. $curCloseTags = '</' . $matches[2] . '>' . $curCloseTags;
  303. }
  304. // If there's something that still needs closing, push it to the stack.
  305. if (!empty($curCloseTags))
  306. array_push($stack, array(
  307. 'element' => strtolower($curElement),
  308. 'closeTags' => $curCloseTags
  309. )
  310. );
  311. elseif (!empty($extra_attr))
  312. $replacement .= $precedingStyle . $extra_attr . $afterStyle;
  313. }
  314. }
  315. elseif (preg_match('~</([A-Za-z]+)>~', $part, $matches) === 1)
  316. {
  317. // Is this the element that we've been waiting for to be closed?
  318. if (!empty($stack) && strtolower($matches[1]) === $stack[count($stack) - 1]['element'])
  319. {
  320. $byebyeTag = array_pop($stack);
  321. $replacement .= $byebyeTag['closeTags'];
  322. }
  323. // Must've been something else.
  324. else
  325. $replacement .= $part;
  326. }
  327. // In all other cases, just add the part to the replacement.
  328. else
  329. $replacement .= $part;
  330. }
  331. // Now put back the replacement in the text.
  332. $text = $replacement;
  333. // We are not finished yet, request more time.
  334. if (connection_aborted() && $context['server']['is_apache'])
  335. @apache_reset_timeout();
  336. // Let's pull out any legacy alignments.
  337. while (preg_match('~<([A-Za-z]+)\s+[^<>]*?(align="*(left|center|right)"*)[^<>]*?(/?)>~i', $text, $matches) === 1)
  338. {
  339. // Find the position in the text of this tag over again.
  340. $start_pos = strpos($text, $matches[0]);
  341. if ($start_pos === false)
  342. break;
  343. // End tag?
  344. if ($matches[4] != '/' && strpos($text, '</' . $matches[1] . '>', $start_pos) !== false)
  345. {
  346. $end_length = strlen('</' . $matches[1] . '>');
  347. $end_pos = strpos($text, '</' . $matches[1] . '>', $start_pos);
  348. // Remove the align from that tag so it's never checked again.
  349. $tag = substr($text, $start_pos, strlen($matches[0]));
  350. $content = substr($text, $start_pos + strlen($matches[0]), $end_pos - $start_pos - strlen($matches[0]));
  351. $tag = str_replace($matches[2], '', $tag);
  352. // Put the tags back into the body.
  353. $text = substr($text, 0, $start_pos) . $tag . '[' . $matches[3] . ']' . $content . '[/' . $matches[3] . ']' . substr($text, $end_pos);
  354. }
  355. else
  356. {
  357. // Just get rid of this evil tag.
  358. $text = substr($text, 0, $start_pos) . substr($text, $start_pos + strlen($matches[0]));
  359. }
  360. }
  361. // Let's do some special stuff for fonts - cause we all love fonts.
  362. while (preg_match('~<font\s+([^<>]*)>~i', $text, $matches) === 1)
  363. {
  364. // Find the position of this again.
  365. $start_pos = strpos($text, $matches[0]);
  366. $end_pos = false;
  367. if ($start_pos === false)
  368. break;
  369. // This must have an end tag - and we must find the right one.
  370. $lower_text = strtolower($text);
  371. $start_pos_test = $start_pos + 4;
  372. // How many starting tags must we find closing ones for first?
  373. $start_font_tag_stack = 0;
  374. while ($start_pos_test < strlen($text))
  375. {
  376. // Where is the next starting font?
  377. $next_start_pos = strpos($lower_text, '<font', $start_pos_test);
  378. $next_end_pos = strpos($lower_text, '</font>', $start_pos_test);
  379. // Did we past another starting tag before an end one?
  380. if ($next_start_pos !== false && $next_start_pos < $next_end_pos)
  381. {
  382. $start_font_tag_stack++;
  383. $start_pos_test = $next_start_pos + 4;
  384. }
  385. // Otherwise we have an end tag but not the right one?
  386. elseif ($start_font_tag_stack)
  387. {
  388. $start_font_tag_stack--;
  389. $start_pos_test = $next_end_pos + 4;
  390. }
  391. // Otherwise we're there!
  392. else
  393. {
  394. $end_pos = $next_end_pos;
  395. break;
  396. }
  397. }
  398. if ($end_pos === false)
  399. break;
  400. // Now work out what the attributes are.
  401. $attribs = fetchTagAttributes($matches[1]);
  402. $tags = array();
  403. foreach ($attribs as $s => $v)
  404. {
  405. if ($s == 'size')
  406. $tags[] = array('[size=' . (int) trim($v) . ']', '[/size]');
  407. elseif ($s == 'face')
  408. $tags[] = array('[font=' . trim(strtolower($v)) . ']', '[/font]');
  409. elseif ($s == 'color')
  410. $tags[] = array('[color=' . trim(strtolower($v)) . ']', '[/color]');
  411. }
  412. // As before add in our tags.
  413. $before = $after = '';
  414. foreach ($tags as $tag)
  415. {
  416. $before .= $tag[0];
  417. if (isset($tag[1]))
  418. $after = $tag[1] . $after;
  419. }
  420. // Remove the tag so it's never checked again.
  421. $content = substr($text, $start_pos + strlen($matches[0]), $end_pos - $start_pos - strlen($matches[0]));
  422. // Put the tags back into the body.
  423. $text = substr($text, 0, $start_pos) . $before . $content . $after . substr($text, $end_pos + 7);
  424. }
  425. // Almost there, just a little more time.
  426. if (connection_aborted() && $context['server']['is_apache'])
  427. @apache_reset_timeout();
  428. if (count($parts = preg_split('~<(/?)(li|ol|ul)([^>]*)>~i', $text, null, PREG_SPLIT_DELIM_CAPTURE)) > 1)
  429. {
  430. // A toggle that dermines whether we're directly under a <ol> or <ul>.
  431. $inList = false;
  432. // Keep track of the number of nested list levels.
  433. $listDepth = 0;
  434. // Map what we can expect from the HTML to what is supported by SMF.
  435. $listTypeMapping = array(
  436. '1' => 'decimal',
  437. 'A' => 'upper-alpha',
  438. 'a' => 'lower-alpha',
  439. 'I' => 'upper-roman',
  440. 'i' => 'lower-roman',
  441. 'disc' => 'disc',
  442. 'square' => 'square',
  443. 'circle' => 'circle',
  444. );
  445. // $i: text, $i + 1: '/', $i + 2: tag, $i + 3: tail.
  446. for ($i = 0, $numParts = count($parts) - 1; $i < $numParts; $i += 4)
  447. {
  448. $tag = strtolower($parts[$i + 2]);
  449. $isOpeningTag = $parts[$i + 1] === '';
  450. if ($isOpeningTag)
  451. {
  452. switch ($tag)
  453. {
  454. case 'ol':
  455. case 'ul':
  456. // We have a problem, we're already in a list.
  457. if ($inList)
  458. {
  459. // Inject a list opener, we'll deal with the ol/ul next loop.
  460. array_splice($parts, $i, 0, array(
  461. '',
  462. '',
  463. str_repeat("\t", $listDepth) . '[li]',
  464. '',
  465. ));
  466. $numParts = count($parts) - 1;
  467. // The inlist status changes a bit.
  468. $inList = false;
  469. }
  470. // Just starting a new list.
  471. else
  472. {
  473. $inList = true;
  474. if ($tag === 'ol')
  475. $listType = 'decimal';
  476. elseif (preg_match('~type="?(' . implode('|', array_keys($listTypeMapping)) . ')"?~', $parts[$i + 3], $match) === 1)
  477. $listType = $listTypeMapping[$match[1]];
  478. else
  479. $listType = null;
  480. $listDepth++;
  481. $parts[$i + 2] = '[list' . ($listType === null ? '' : ' type=' . $listType) . ']' . "\n";
  482. $parts[$i + 3] = '';
  483. }
  484. break;
  485. case 'li':
  486. // This is how it should be: a list item inside the list.
  487. if ($inList)
  488. {
  489. $parts[$i + 2] = str_repeat("\t", $listDepth) . '[li]';
  490. $parts[$i + 3] = '';
  491. // Within a list item, it's almost as if you're outside.
  492. $inList = false;
  493. }
  494. // The li is no direct child of a list.
  495. else
  496. {
  497. // We are apparently in a list item.
  498. if ($listDepth > 0)
  499. {
  500. $parts[$i + 2] = '[/li]' . "\n" . str_repeat("\t", $listDepth) . '[li]';
  501. $parts[$i + 3] = '';
  502. }
  503. // We're not even near a list.
  504. else
  505. {
  506. // Quickly create a list with an item.
  507. $listDepth++;
  508. $parts[$i + 2] = '[list]' . "\n\t" . '[li]';
  509. $parts[$i + 3] = '';
  510. }
  511. }
  512. break;
  513. }
  514. }
  515. // Handle all the closing tags.
  516. else
  517. {
  518. switch ($tag)
  519. {
  520. case 'ol':
  521. case 'ul':
  522. // As we expected it, closing the list while we're in it.
  523. if ($inList)
  524. {
  525. $inList = false;
  526. $listDepth--;
  527. $parts[$i + 1] = '';
  528. $parts[$i + 2] = str_repeat("\t", $listDepth) . '[/list]';
  529. $parts[$i + 3] = '';
  530. }
  531. else
  532. {
  533. // We're in a list item.
  534. if ($listDepth > 0)
  535. {
  536. // Inject closure for this list item first.
  537. // The content of $parts[$i] is left as is!
  538. array_splice($parts, $i + 1, 0, array(
  539. '', // $i + 1
  540. '[/li]' . "\n", // $i + 2
  541. '', // $i + 3
  542. '', // $i + 4
  543. ));
  544. $numParts = count($parts) - 1;
  545. // Now that we've closed the li, we're in list space.
  546. $inList = true;
  547. }
  548. // We're not even in a list, ignore
  549. else
  550. {
  551. $parts[$i + 1] = '';
  552. $parts[$i + 2] = '';
  553. $parts[$i + 3] = '';
  554. }
  555. }
  556. break;
  557. case 'li':
  558. if ($inList)
  559. {
  560. // There's no use for a </li> after <ol> or <ul>, ignore.
  561. $parts[$i + 1] = '';
  562. $parts[$i + 2] = '';
  563. $parts[$i + 3] = '';
  564. }
  565. else
  566. {
  567. // Remove the trailing breaks from the list item.
  568. $parts[$i] = preg_replace('~\s*<br\s*' . '/?' . '>\s*$~', '', $parts[$i]);
  569. $parts[$i + 1] = '';
  570. $parts[$i + 2] = '[/li]' . "\n";
  571. $parts[$i + 3] = '';
  572. // And we're back in the [list] space.
  573. $inList = true;
  574. }
  575. break;
  576. }
  577. }
  578. // If we're in the [list] space, no content is allowed.
  579. if ($inList && trim(preg_replace('~\s*<br\s*' . '/?' . '>\s*~', '', $parts[$i + 4])) !== '')
  580. {
  581. // Fix it by injecting an extra list item.
  582. array_splice($parts, $i + 4, 0, array(
  583. '', // No content.
  584. '', // Opening tag.
  585. 'li', // It's a <li>.
  586. '', // No tail.
  587. ));
  588. $numParts = count($parts) - 1;
  589. }
  590. }
  591. $text = implode('', $parts);
  592. if ($inList)
  593. {
  594. $listDepth--;
  595. $text .= str_repeat("\t", $listDepth) . '[/list]';
  596. }
  597. for ($i = $listDepth; $i > 0; $i--)
  598. $text .= '[/li]' . "\n" . str_repeat("\t", $i - 1) . '[/list]';
  599. }
  600. // I love my own image...
  601. while (preg_match('~<img\s+([^<>]*)/*>~i', $text, $matches) === 1)
  602. {
  603. // Find the position of the image.
  604. $start_pos = strpos($text, $matches[0]);
  605. if ($start_pos === false)
  606. break;
  607. $end_pos = $start_pos + strlen($matches[0]);
  608. $params = '';
  609. $had_params = array();
  610. $src = '';
  611. $attrs = fetchTagAttributes($matches[1]);
  612. foreach ($attrs as $attrib => $value)
  613. {
  614. if (in_array($attrib, array('width', 'height')))
  615. $params .= ' ' . $attrib . '=' . (int) $value;
  616. elseif ($attrib == 'alt' && trim($value) != '')
  617. $params .= ' alt=' . trim($value);
  618. elseif ($attrib == 'src')
  619. $src = trim($value);
  620. }
  621. $tag = '';
  622. if (!empty($src))
  623. {
  624. // Attempt to fix the path in case it's not present.
  625. if (preg_match('~^https?://~i', $src) === 0 && is_array($parsedURL = parse_url($scripturl)) && isset($parsedURL['host']))
  626. {
  627. $baseURL = (isset($parsedURL['scheme']) ? $parsedURL['scheme'] : 'http') . '://' . $parsedURL['host'] . (empty($parsedURL['port']) ? '' : ':' . $parsedURL['port']);
  628. if (substr($src, 0, 1) === '/')
  629. $src = $baseURL . $src;
  630. else
  631. $src = $baseURL . (empty($parsedURL['path']) ? '/' : preg_replace('~/(?:index\\.php)?$~', '', $parsedURL['path'])) . '/' . $src;
  632. }
  633. $tag = '[img' . $params . ']' . $src . '[/img]';
  634. }
  635. // Replace the tag
  636. $text = substr($text, 0, $start_pos) . $tag . substr($text, $end_pos);
  637. }
  638. // The final bits are the easy ones - tags which map to tags which map to tags - etc etc.
  639. $tags = array(
  640. '~<b(\s(.)*?)*?' . '>~i' => '[b]',
  641. '~</b>~i' => '[/b]',
  642. '~<i(\s(.)*?)*?' . '>~i' => '[i]',
  643. '~</i>~i' => '[/i]',
  644. '~<u(\s(.)*?)*?' . '>~i' => '[u]',
  645. '~</u>~i' => '[/u]',
  646. '~<strong(\s(.)*?)*?' . '>~i' => '[b]',
  647. '~</strong>~i' => '[/b]',
  648. '~<em(\s(.)*?)*?' . '>~i' => '[i]',
  649. '~</em>~i' => '[/i]',
  650. '~<s(\s(.)*?)*?' . '>~i' => "[s]",
  651. '~</s>~i' => "[/s]",
  652. '~<strike(\s(.)*?)*?' . '>~i' => '[s]',
  653. '~</strike>~i' => '[/s]',
  654. '~<del(\s(.)*?)*?' . '>~i' => '[s]',
  655. '~</del>~i' => '[/s]',
  656. '~<center(\s(.)*?)*?' . '>~i' => '[center]',
  657. '~</center>~i' => '[/center]',
  658. '~<pre(\s(.)*?)*?' . '>~i' => '[pre]',
  659. '~</pre>~i' => '[/pre]',
  660. '~<sub(\s(.)*?)*?' . '>~i' => '[sub]',
  661. '~</sub>~i' => '[/sub]',
  662. '~<sup(\s(.)*?)*?' . '>~i' => '[sup]',
  663. '~</sup>~i' => '[/sup]',
  664. '~<tt(\s(.)*?)*?' . '>~i' => '[tt]',
  665. '~</tt>~i' => '[/tt]',
  666. '~<table(\s(.)*?)*?' . '>~i' => '[table]',
  667. '~</table>~i' => '[/table]',
  668. '~<tr(\s(.)*?)*?' . '>~i' => '[tr]',
  669. '~</tr>~i' => '[/tr]',
  670. '~<(td|th)(\s(.)*?)*?' . '>~i' => '[td]',
  671. '~</(td|th)>~i' => '[/td]',
  672. '~<br(?:\s[^<>]*?)?' . '>~i' => "\n",
  673. '~<hr[^<>]*>(\n)?~i' => "[hr]\n$1",
  674. '~(\n)?\\[hr\\]~i' => "\n[hr]",
  675. '~^\n\\[hr\\]~i' => "[hr]",
  676. '~<blockquote(\s(.)*?)*?' . '>~i' => "&lt;blockquote&gt;",
  677. '~</blockquote>~i' => "&lt;/blockquote&gt;",
  678. '~<ins(\s(.)*?)*?' . '>~i' => "&lt;ins&gt;",
  679. '~</ins>~i' => "&lt;/ins&gt;",
  680. );
  681. $text = preg_replace_callback('~<(td|th)\s[^<>]*?colspan="?(\d{1,2})"?.*?' . '>~i', create_function('$m', 'return str_repeat(\'[td][/td]\', $m[2] - 1) . \'[td]\';'), $text);
  682. $text = preg_replace(array_keys($tags), array_values($tags), $text);
  683. // Please give us just a little more time.
  684. if (connection_aborted() && $context['server']['is_apache'])
  685. @apache_reset_timeout();
  686. // What about URL's - the pain in the ass of the tag world.
  687. while (preg_match('~<a\s+([^<>]*)>([^<>]*)</a>~i', $text, $matches) === 1)
  688. {
  689. // Find the position of the URL.
  690. $start_pos = strpos($text, $matches[0]);
  691. if ($start_pos === false)
  692. break;
  693. $end_pos = $start_pos + strlen($matches[0]);
  694. $tag_type = 'url';
  695. $href = '';
  696. $attrs = fetchTagAttributes($matches[1]);
  697. foreach ($attrs as $attrib => $value)
  698. {
  699. if ($attrib == 'href')
  700. {
  701. $href = trim($value);
  702. // Are we dealing with an FTP link?
  703. if (preg_match('~^ftps?://~', $href) === 1)
  704. $tag_type = 'ftp';
  705. // Or is this a link to an email address?
  706. elseif (substr($href, 0, 7) == 'mailto:')
  707. {
  708. $tag_type = 'email';
  709. $href = substr($href, 7);
  710. }
  711. // No http(s), so attempt to fix this potential relative URL.
  712. elseif (preg_match('~^https?://~i', $href) === 0 && is_array($parsedURL = parse_url($scripturl)) && isset($parsedURL['host']))
  713. {
  714. $baseURL = (isset($parsedURL['scheme']) ? $parsedURL['scheme'] : 'http') . '://' . $parsedURL['host'] . (empty($parsedURL['port']) ? '' : ':' . $parsedURL['port']);
  715. if (substr($href, 0, 1) === '/')
  716. $href = $baseURL . $href;
  717. else
  718. $href = $baseURL . (empty($parsedURL['path']) ? '/' : preg_replace('~/(?:index\\.php)?$~', '', $parsedURL['path'])) . '/' . $href;
  719. }
  720. }
  721. // External URL?
  722. if ($attrib == 'target' && $tag_type == 'url')
  723. {
  724. if (trim($value) == '_blank')
  725. $tag_type == 'iurl';
  726. }
  727. }
  728. $tag = '';
  729. if ($href != '')
  730. {
  731. if ($matches[2] == $href)
  732. $tag = '[' . $tag_type . ']' . $href . '[/' . $tag_type . ']';
  733. else
  734. $tag = '[' . $tag_type . '=' . $href . ']' . $matches[2] . '[/' . $tag_type . ']';
  735. }
  736. // Replace the tag
  737. $text = substr($text, 0, $start_pos) . $tag . substr($text, $end_pos);
  738. }
  739. $text = strip_tags($text);
  740. // Some tags often end up as just dummy tags - remove those.
  741. $text = preg_replace('~\[[bisu]\]\s*\[/[bisu]\]~', '', $text);
  742. // Fix up entities.
  743. $text = preg_replace('~&#38;~i', '&#38;#38;', $text);
  744. $text = legalise_bbc($text);
  745. return $text;
  746. }
  747. // Returns an array of attributes associated with a tag.
  748. function fetchTagAttributes($text)
  749. {
  750. $attribs = array();
  751. $key = $value = '';
  752. $strpos = 0;
  753. $tag_state = 0; // 0 = key, 1 = attribute with no string, 2 = attribute with string
  754. for ($i = 0; $i < strlen($text); $i++)
  755. {
  756. // We're either moving from the key to the attribute or we're in a string and this is fine.
  757. if ($text{$i} == '=')
  758. {
  759. if ($tag_state == 0)
  760. $tag_state = 1;
  761. elseif ($tag_state == 2)
  762. $value .= '=';
  763. }
  764. // A space is either moving from an attribute back to a potential key or in a string is fine.
  765. elseif ($text{$i} == ' ')
  766. {
  767. if ($tag_state == 2)
  768. $value .= ' ';
  769. elseif ($tag_state == 1)
  770. {
  771. $attribs[$key] = $value;
  772. $key = $value = '';
  773. $tag_state = 0;
  774. }
  775. }
  776. // A quote?
  777. elseif ($text{$i} == '"')
  778. {
  779. // Must be either going into or out of a string.
  780. if ($tag_state == 1)
  781. $tag_state = 2;
  782. else
  783. $tag_state = 1;
  784. }
  785. // Otherwise it's fine.
  786. else
  787. {
  788. if ($tag_state == 0)
  789. $key .= $text{$i};
  790. else
  791. $value .= $text{$i};
  792. }
  793. }
  794. // Anything left?
  795. if ($key != '' && $value != '')
  796. $attribs[$key] = $value;
  797. return $attribs;
  798. }
  799. function getMessageIcons($board_id)
  800. {
  801. global $modSettings, $context, $txt, $settings, $smcFunc;
  802. if (empty($modSettings['messageIcons_enable']))
  803. {
  804. loadLanguage('Post');
  805. $icons = array(
  806. array('value' => 'xx', 'name' => $txt['standard']),
  807. array('value' => 'thumbup', 'name' => $txt['thumbs_up']),
  808. array('value' => 'thumbdown', 'name' => $txt['thumbs_down']),
  809. array('value' => 'exclamation', 'name' => $txt['excamation_point']),
  810. array('value' => 'question', 'name' => $txt['question_mark']),
  811. array('value' => 'lamp', 'name' => $txt['lamp']),
  812. array('value' => 'smiley', 'name' => $txt['icon_smiley']),
  813. array('value' => 'angry', 'name' => $txt['icon_angry']),
  814. array('value' => 'cheesy', 'name' => $txt['icon_cheesy']),
  815. array('value' => 'grin', 'name' => $txt['icon_grin']),
  816. array('value' => 'sad', 'name' => $txt['icon_sad']),
  817. array('value' => 'wink', 'name' => $txt['icon_wink'])
  818. );
  819. foreach ($icons as $k => $dummy)
  820. {
  821. $icons[$k]['url'] = $settings['images_url'] . '/post/' . $dummy['value'] . '.gif';
  822. $icons[$k]['is_last'] = false;
  823. }
  824. }
  825. // Otherwise load the icons, and check we give the right image too...
  826. else
  827. {
  828. if (($temp = cache_get_data('posting_icons-' . $board_id, 480)) == null)
  829. {
  830. $request = $smcFunc['db_query']('select_message_icons', '
  831. SELECT title, filename
  832. FROM {db_prefix}message_icons
  833. WHERE id_board IN (0, {int:board_id})',
  834. array(
  835. 'board_id' => $board_id,
  836. )
  837. );
  838. $icon_data = array();
  839. while ($row = $smcFunc['db_fetch_assoc']($request))
  840. $icon_data[] = $row;
  841. $smcFunc['db_free_result']($request);
  842. cache_put_data('posting_icons-' . $board_id, $icon_data, 480);
  843. }
  844. else
  845. $icon_data = $temp;
  846. $icons = array();
  847. foreach ($icon_data as $icon)
  848. {
  849. $icons[$icon['filename']] = array(
  850. 'value' => $icon['filename'],
  851. 'name' => $icon['title'],
  852. 'url' => $settings[file_exists($settings['theme_dir'] . '/images/post/' . $icon['filename'] . '.gif') ? 'images_url' : 'default_images_url'] . '/post/' . $icon['filename'] . '.gif',
  853. 'is_last' => false,
  854. );
  855. }
  856. }
  857. return array_values($icons);
  858. }
  859. // This is an important yet frustrating function - it attempts to clean up illegal BBC caused by browsers like Opera which don't obey the rules!!!
  860. function legalise_bbc($text)
  861. {
  862. global $modSettings;
  863. // Don't care about the texts that are too short.
  864. if (strlen($text) < 3)
  865. return $text;
  866. // We are going to cycle through the BBC and keep track of tags as they arise - in order. If get to a block level tag we're going to make sure it's not in a non-block level tag!
  867. // This will keep the order of tags that are open.
  868. $current_tags = array();
  869. // This will quickly let us see if the tag is active.
  870. $active_tags = array();
  871. // A list of tags that's disabled by the admin.
  872. $disabled = empty($modSettings['disabledBBC']) ? array() : array_flip(explode(',', strtolower($modSettings['disabledBBC'])));
  873. // Add flash if it's disabled as embedded tag.
  874. if (empty($modSettings['enableEmbeddedFlash']))
  875. $disabled['flash'] = true;
  876. // Get a list of all the tags that are not disabled.
  877. $all_tags = parse_bbc(false);
  878. $valid_tags = array();
  879. $self_closing_tags = array();
  880. foreach ($all_tags as $tag)
  881. {
  882. if (!isset($disabled[$tag['tag']]))
  883. $valid_tags[$tag['tag']] = !empty($tag['block_level']);
  884. if (isset($tag['type']) && $tag['type'] == 'closed')
  885. $self_closing_tags[] = $tag['tag'];
  886. }
  887. // Don't worry if we're in a code/nobbc.
  888. $in_code_nobbc = false;
  889. // Right - we're going to start by going through the whole lot to make sure we don't have align stuff crossed as this happens load and is stupid!
  890. $align_tags = array('left', 'center', 'right', 'pre');
  891. // Remove those align tags that are not valid.
  892. $align_tags = array_intersect($align_tags, array_keys($valid_tags));
  893. // These keep track of where we are!
  894. if (!empty($align_tags) && count($matches = preg_split('~(\\[/?(?:' . implode('|', $align_tags) . ')\\])~', $text, -1, PREG_SPLIT_DELIM_CAPTURE)) > 1)
  895. {
  896. // The first one is never a tag.
  897. $isTag = false;
  898. // By default we're not inside a tag too.
  899. $insideTag = null;
  900. foreach ($matches as $i => $match)
  901. {
  902. // We're only interested in tags, not text.
  903. if ($isTag)
  904. {
  905. $isClosingTag = substr($match, 1, 1) === '/';
  906. $tagName = substr($match, $isClosingTag ? 2 : 1, -1);
  907. // We're closing the exact same tag that we opened.
  908. if ($isClosingTag && $insideTag === $tagName)
  909. $insideTag = null;
  910. // We're opening a tag and we're not yet inside one either
  911. elseif (!$isClosingTag && $insideTag === null)
  912. $insideTag = $tagName;
  913. // In all other cases, this tag must be invalid
  914. else
  915. unset($matches[$i]);
  916. }
  917. // The next one is gonna be the other one.
  918. $isTag = !$isTag;
  919. }
  920. // We're still inside a tag and had no chance for closure?
  921. if ($insideTag !== null)
  922. $matches[] = '[/' . $insideTag . ']';
  923. // And a complete text string again.
  924. $text = implode('', $matches);
  925. }
  926. // Quickly remove any tags which are back to back.
  927. $backToBackPattern = '~\\[(' . implode('|', array_diff(array_keys($valid_tags), array('td', 'anchor'))) . ')[^<>\\[\\]]*\\]\s*\\[/\\1\\]~';
  928. $lastlen = 0;
  929. while (strlen($text) !== $lastlen)
  930. $lastlen = strlen($text = preg_replace($backToBackPattern, '', $text));
  931. // Need to sort the tags my name length.
  932. uksort($valid_tags, 'sort_array_length');
  933. // These inline tags can compete with each other regarding style.
  934. $competing_tags = array(
  935. 'color',
  936. 'size',
  937. );
  938. // In case things changed above set these back to normal.
  939. $in_code_nobbc = false;
  940. $new_text_offset = 0;
  941. // These keep track of where we are!
  942. if (count($parts = preg_split(sprintf('~(\\[)(/?)(%1$s)((?:[\\s=][^\\]\\[]*)?\\])~', implode('|', array_keys($valid_tags))), $text, -1, PREG_SPLIT_DELIM_CAPTURE)) > 1)
  943. {
  944. // Start with just text.
  945. $isTag = false;
  946. // Start outside [nobbc] or [code] blocks.
  947. $inCode = false;
  948. $inNoBbc = false;
  949. // A buffer containing all opened inline elements.
  950. $inlineElements = array();
  951. // A buffer containing all opened block elements.
  952. $blockElements = array();
  953. // A buffer containing the opened inline elements that might compete.
  954. $competingElements = array();
  955. // $i: text, $i + 1: '[', $i + 2: '/', $i + 3: tag, $i + 4: tag tail.
  956. for ($i = 0, $n = count($parts) - 1; $i < $n; $i += 5)
  957. {
  958. $tag = $parts[$i + 3];
  959. $isOpeningTag = $parts[$i + 2] === '';
  960. $isClosingTag = $parts[$i + 2] === '/';
  961. $isBlockLevelTag = isset($valid_tags[$tag]) && $valid_tags[$tag] && !in_array($tag, $self_closing_tags);
  962. $isCompetingTag = in_array($tag, $competing_tags);
  963. // Check if this might be one of those cleaned out tags.
  964. if ($tag === '')
  965. continue;
  966. // Special case: inside [code] blocks any code is left untouched.
  967. elseif ($tag === 'code')
  968. {
  969. // We're inside a code block and closing it.
  970. if ($inCode && $isClosingTag)
  971. {
  972. $inCode = false;
  973. // Reopen tags that were closed before the code block.
  974. if (!empty($inlineElements))
  975. $parts[$i + 4] .= '[' . implode('][', array_keys($inlineElements)) . ']';
  976. }
  977. // We're outside a coding and nobbc block and opening it.
  978. elseif (!$inCode && !$inNoBbc && $isOpeningTag)
  979. {
  980. // If there are still inline elements left open, close them now.
  981. if (!empty($inlineElements))
  982. {
  983. $parts[$i] .= '[/' . implode('][/', array_reverse($inlineElements)) . ']';
  984. //$inlineElements = array();
  985. }
  986. $inCode = true;
  987. }
  988. // Nothing further to do.
  989. continue;
  990. }
  991. // Special case: inside [nobbc] blocks any BBC is left untouched.
  992. elseif ($tag === 'nobbc')
  993. {
  994. // We're inside a nobbc block and closing it.
  995. if ($inNoBbc && $isClosingTag)
  996. {
  997. $inNoBbc = false;
  998. // Some inline elements might've been closed that need reopening.
  999. if (!empty($inlineElements))
  1000. $parts[$i + 4] .= '[' . implode('][', array_keys($inlineElements)) . ']';
  1001. }
  1002. // We're outside a nobbc and coding block and opening it.
  1003. elseif (!$inNoBbc && !$inCode && $isOpeningTag)
  1004. {
  1005. // Can't have inline elements still opened.
  1006. if (!empty($inlineElements))
  1007. {
  1008. $parts[$i] .= '[/' . implode('][/', array_reverse($inlineElements)) . ']';
  1009. //$inlineElements = array();
  1010. }
  1011. $inNoBbc = true;
  1012. }
  1013. continue;
  1014. }
  1015. // So, we're inside one of the special blocks: ignore any tag.
  1016. elseif ($inCode || $inNoBbc)
  1017. continue;
  1018. // We're dealing with an opening tag.
  1019. if ($isOpeningTag)
  1020. {
  1021. // Everyting inside the square brackets of the opening tag.
  1022. $elementContent = $parts[$i + 3] . substr($parts[$i + 4], 0, -1);
  1023. // A block level opening tag.
  1024. if ($isBlockLevelTag)
  1025. {
  1026. // Are there inline elements still open?
  1027. if (!empty($inlineElements))
  1028. {
  1029. // Close all the inline tags, a block tag is coming...
  1030. $parts[$i] .= '[/' . implode('][/', array_reverse($inlineElements)) . ']';
  1031. // Now open them again, we're inside the block tag now.
  1032. $parts[$i + 5] = '[' . implode('][', array_keys($inlineElements)) . ']' . $parts[$i + 5];
  1033. }
  1034. $blockElements[] = $tag;
  1035. }
  1036. // Inline opening tag.
  1037. elseif (!in_array($tag, $self_closing_tags))
  1038. {
  1039. // Can't have two opening elements with the same contents!
  1040. if (isset($inlineElements[$elementContent]))
  1041. {
  1042. // Get rid of this tag.
  1043. $parts[$i + 1] = $parts[$i + 2] = $parts[$i + 3] = $parts[$i + 4] = '';
  1044. // Now try to find the corresponding closing tag.
  1045. $curLevel = 1;
  1046. for ($j = $i + 5, $m = count($parts) - 1; $j < $m; $j += 5)
  1047. {
  1048. // Find the tags with the same tagname
  1049. if ($parts[$j + 3] === $tag)
  1050. {
  1051. // If it's an opening tag, increase the level.
  1052. if ($parts[$j + 2] === '')
  1053. $curLevel++;
  1054. // A closing tag, decrease the level.
  1055. else
  1056. {
  1057. $curLevel--;
  1058. // Gotcha! Clean out this closing tag gone rogue.
  1059. if ($curLevel === 0)
  1060. {
  1061. $parts[$j + 1] = $parts[$j + 2] = $parts[$j + 3] = $parts[$j + 4] = '';
  1062. break;
  1063. }
  1064. }
  1065. }
  1066. }
  1067. }
  1068. // Otherwise, add this one to the list.
  1069. else
  1070. {
  1071. if ($isCompetingTag)
  1072. {
  1073. if (!isset($competingElements[$tag]))
  1074. $competingElements[$tag] = array();
  1075. $competingElements[$tag][] = $parts[$i + 4];
  1076. if (count($competingElements[$tag]) > 1)
  1077. $parts[$i] .= '[/' . $tag . ']';
  1078. }
  1079. $inlineElements[$elementContent] = $tag;
  1080. }
  1081. }
  1082. }
  1083. // Closing tag.
  1084. else
  1085. {
  1086. // Closing the block tag.
  1087. if ($isBlockLevelTag)
  1088. {
  1089. // Close the elements that should've been closed by closing this tag.
  1090. if (!empty($blockElements))
  1091. {
  1092. $addClosingTags = array();
  1093. while ($element = array_pop($blockElements))
  1094. {
  1095. if ($element === $tag)
  1096. break;
  1097. // Still a block tag was open not equal to this tag.
  1098. $addClosingTags[] = $element['type'];
  1099. }
  1100. if (!empty($addClosingTags))
  1101. $parts[$i + 1] = '[/' . implode('][/', array_reverse($addClosingTags)) . ']' . $parts[$i + 1];
  1102. // Apparently the closing tag was not found on the stack.
  1103. if (!is_string($element) || $element !== $tag)
  1104. {
  1105. // Get rid of this particular closing tag, it was never opened.
  1106. $parts[$i + 1] = substr($parts[$i + 1], 0, -1);
  1107. $parts[$i + 2] = $parts[$i + 3] = $parts[$i + 4] = '';
  1108. continue;
  1109. }
  1110. }
  1111. else
  1112. {
  1113. // Get rid of this closing tag!
  1114. $parts[$i + 1] = $parts[$i + 2] = $parts[$i + 3] = $parts[$i + 4] = '';
  1115. continue;
  1116. }
  1117. // Inline elements are still left opened?
  1118. if (!empty($inlineElements))
  1119. {
  1120. // Close them first..
  1121. $parts[$i] .= '[/' . implode('][/', array_reverse($inlineElements)) . ']';
  1122. // Then reopen them.
  1123. $parts[$i + 5] = '[' . implode('][', array_keys($inlineElements)) . ']' . $parts[$i + 5];
  1124. }
  1125. }
  1126. // Inline tag.
  1127. else
  1128. {
  1129. // Are we expecting this tag to end?
  1130. if (in_array($tag, $inlineElements))
  1131. {
  1132. foreach (array_reverse($inlineElements, true) as $tagContentToBeClosed => $tagToBeClosed)
  1133. {
  1134. // Closing it one way or the other.
  1135. unset($inlineElements[$tagContentToBeClosed]);
  1136. // Was this the tag we were looking for?
  1137. if ($tagToBeClosed === $tag)
  1138. break;
  1139. // Nope, close it and look further!
  1140. else
  1141. $parts[$i] .= '[/' . $tagToBeClosed . ']';
  1142. }
  1143. if ($isCompetingTag && !empty($competingElements[$tag]))
  1144. {
  1145. array_pop($competingElements[$tag]);
  1146. if (count($competingElements[$tag]) > 0)
  1147. $parts[$i + 5] = '[' . $tag . $competingElements[$tag][count($competingElements[$tag]) - 1] . $parts[$i + 5];
  1148. }
  1149. }
  1150. // Unexpected closing tag, ex-ter-mi-nate.
  1151. else
  1152. $parts[$i + 1] = $parts[$i + 2] = $parts[$i + 3] = $parts[$i + 4] = '';
  1153. }
  1154. }
  1155. }
  1156. // Close the code tags.
  1157. if ($inCode)
  1158. $parts[$i] .= '[/code]';
  1159. // The same for nobbc tags.
  1160. elseif ($inNoBbc)
  1161. $parts[$i] .= '[/nobbc]';
  1162. // Still inline tags left unclosed? Close them now, better late than never.
  1163. elseif (!empty($inlineElements))
  1164. $parts[$i] .= '[/' . implode('][/', array_reverse($inlineElements)) . ']';
  1165. // Now close the block elements.
  1166. if (!empty($blockElements))
  1167. $parts[$i] .= '[/' . implode('][/', array_reverse($blockElements)) . ']';
  1168. $text = implode('', $parts);
  1169. }
  1170. // Final clean up of back to back tags.
  1171. $lastlen = 0;
  1172. while (strlen($text) !== $lastlen)
  1173. $lastlen = strlen($text = preg_replace($backToBackPattern, '', $text));
  1174. return $text;
  1175. }
  1176. // A help function for legalise_bbc for sorting arrays based on length.
  1177. function sort_array_length($a, $b)
  1178. {
  1179. return strlen($a) < strlen($b) ? 1 : -1;
  1180. }
  1181. // Compatibility function - used in 1.1 for showing a post box.
  1182. function theme_postbox($msg)
  1183. {
  1184. global $context;
  1185. return template_control_richedit($context['post_box_name']);
  1186. }
  1187. // Creates a box that can be used for richedit stuff like BBC, Smileys etc.
  1188. function create_control_richedit($editorOptions)
  1189. {
  1190. global $txt, $modSettings, $options, $smcFunc;
  1191. global $context, $settings, $user_info, $sourcedir, $scripturl;
  1192. // Load the Post language file... for the moment at least.
  1193. loadLanguage('Post');
  1194. // Every control must have a ID!
  1195. assert(isset($editorOptions['id']));
  1196. assert(isset($editorOptions['value']));
  1197. // Is this the first richedit - if so we need to ensure some template stuff is initialised.
  1198. if (empty($context['controls']['richedit']))
  1199. {
  1200. // Some general stuff.
  1201. $settings['smileys_url'] = $modSettings['smileys_url'] . '/' . $user_info['smiley_set'];
  1202. // This really has some WYSIWYG stuff.
  1203. loadTemplate('GenericControls', $context['browser']['is_ie'] ? 'editor_ie' : 'editor');
  1204. $context['html_headers'] .= '
  1205. <script type="text/javascript"><!-- // --><![CDATA[
  1206. var smf_smileys_url = \'' . $settings['smileys_url'] . '\';
  1207. var oEditorStrings= {
  1208. wont_work: \'' . addcslashes($txt['rich_edit_wont_work'], "'") . '\',
  1209. func_disabled: \'' . addcslashes($txt['rich_edit_function_disabled'], "'") . '\',
  1210. prompt_text_email: \'' . addcslashes($txt['prompt_text_email'], "'") . '\',
  1211. prompt_text_ftp: \'' . addcslashes($txt['prompt_text_ftp'], "'") . '\',
  1212. prompt_text_url: \'' . addcslashes($txt['prompt_text_url'], "'") . '\',
  1213. prompt_text_img: \'' . addcslashes($txt['prompt_text_img'], "'") . '\'
  1214. }
  1215. // ]]></script>
  1216. <script type="text/javascript" src="' . $settings['default_theme_url'] . '/scripts/editor.js?fin20"></script>';
  1217. $context['show_spellchecking'] = !empty($modSettings['enableSpellChecking']) && function_exists('pspell_new');
  1218. if ($context['show_spellchecking'])
  1219. {
  1220. $context['html_headers'] .= '
  1221. <script type="text/javascript" src="' . $settings['default_theme_url'] . '/scripts/spellcheck.js"></script>';
  1222. // Some hidden information is needed in order to make the spell checking work.
  1223. if (!isset($_REQUEST['xml']))
  1224. $context['insert_after_template'] .= '
  1225. <form name="spell_form" id="spell_form" method="post" accept-charset="' . $context['character_set'] . '" target="spellWindow" action="' . $scripturl . '?action=spellcheck">
  1226. <input type="hidden" name="spellstring" value="" />
  1227. </form>';
  1228. // Also make sure that spell check works with rich edit.
  1229. $context['html_headers'] .= '
  1230. <script type="text/javascript"><!-- // --><![CDATA[
  1231. function spellCheckDone()
  1232. {
  1233. for (i = 0; i < smf_editorArray.length; i++)
  1234. setTimeout("smf_editorArray[" + i + "].spellCheckEnd()", 150);
  1235. }
  1236. // ]]></script>';
  1237. }
  1238. }
  1239. // Start off the editor...
  1240. $context['controls']['richedit'][$editorOptions['id']] = array(
  1241. 'id' => $editorOptions['id'],
  1242. 'value' => $editorOptions['value'],
  1243. 'rich_value' => bbc_to_html($editorOptions['value']),
  1244. 'rich_active' => empty($modSettings['disable_wysiwyg']) && (!empty($options['wysiwyg_default']) || !empty($editorOptions['force_rich']) || !empty($_REQUEST[$editorOptions['id'] . '_mode'])),
  1245. 'disable_smiley_box' => !empty($editorOptions['disable_smiley_box']),
  1246. 'columns' => isset($editorOptions['columns']) ? $editorOptions['columns'] : 60,
  1247. 'rows' => isset($editorOptions['rows']) ? $editorOptions['rows'] : 12,
  1248. 'width' => isset($editorOptions['width']) ? $editorOptions['width'] : '70%',
  1249. 'height' => isset($editorOptions['height']) ? $editorOptions['height'] : '150px',
  1250. 'form' => isset($editorOptions['form']) ? $editorOptions['form'] : 'postmodify',
  1251. 'bbc_level' => !empty($editorOptions['bbc_level']) ? $editorOptions['bbc_level'] : 'full',
  1252. 'preview_type' => isset($editorOptions['preview_type']) ? (int) $editorOptions['preview_type'] : 1,
  1253. 'labels' => !empty($editorOptions['labels']) ? $editorOptions['labels'] : array(),
  1254. );
  1255. // Switch between default images and back... mostly in case you don't have an PersonalMessage template, but do have a Post template.
  1256. if (isset($settings['use_default_images']) && $settings['use_default_images'] == 'defaults' && isset($settings['default_template']))
  1257. {
  1258. $temp1 = $settings['theme_url'];
  1259. $settings['theme_url'] = $settings['default_theme_url'];
  1260. $temp2 = $settings['images_url'];
  1261. $settings['images_url'] = $settings['default_images_url'];
  1262. $temp3 = $settings['theme_dir'];
  1263. $settings['theme_dir'] = $settings['default_theme_dir'];
  1264. }
  1265. if (empty($context['bbc_tags']))
  1266. {
  1267. // The below array makes it dead easy to add images to this control. Add it to the array and everything else is done for you!
  1268. $context['bbc_tags'] = array();
  1269. $context['bbc_tags'][] = array(
  1270. array(
  1271. 'image' => 'bold',
  1272. 'code' => 'b',
  1273. 'before' => '[b]',
  1274. 'after' => '[/b]',
  1275. 'description' => $txt['bold'],
  1276. ),
  1277. array(
  1278. 'image' => 'italicize',
  1279. 'code' => 'i',
  1280. 'before' => '[i]',
  1281. 'after' => '[/i]',
  1282. 'description' => $txt['italic'],
  1283. ),
  1284. array(
  1285. 'image' => 'underline',
  1286. 'code' => 'u',
  1287. 'before' => '[u]',
  1288. 'after' => '[/u]',
  1289. 'description' => $txt['underline']
  1290. ),
  1291. array(
  1292. 'image' => 'strike',
  1293. 'code' => 's',
  1294. 'before' => '[s]',
  1295. 'after' => '[/s]',
  1296. 'description' => $txt['strike']
  1297. ),
  1298. array(),
  1299. array(
  1300. 'image' => 'pre',
  1301. 'code' => 'pre',
  1302. 'before' => '[pre]',
  1303. 'after' => '[/pre]',
  1304. 'description' => $txt['preformatted']
  1305. ),
  1306. array(
  1307. 'image' => 'left',
  1308. 'code' => 'left',
  1309. 'before' => '[left]',
  1310. 'after' => '[/left]',
  1311. 'description' => $txt['left_align']
  1312. ),
  1313. array(
  1314. 'image' => 'center',
  1315. 'code' => 'center',
  1316. 'before' => '[center]',
  1317. 'after' => '[/center]',
  1318. 'description' => $txt['center']
  1319. ),
  1320. array(
  1321. 'image' => 'right',
  1322. 'code' => 'right',
  1323. 'before' => '[right]',
  1324. 'after' => '[/right]',
  1325. 'description' => $txt['right_align']
  1326. ),
  1327. );
  1328. $context['bbc_tags'][] = array(
  1329. array(
  1330. 'image' => 'flash',
  1331. 'code' => 'flash',
  1332. 'before' => '[flash=200,200]',
  1333. 'after' => '[/flash]',
  1334. 'description' => $txt['flash']
  1335. ),
  1336. array(
  1337. 'image' => 'img',
  1338. 'code' => 'img',
  1339. 'before' => '[img]',
  1340. 'after' => '[/img]',
  1341. 'description' => $txt['image']
  1342. ),
  1343. array(
  1344. 'image' => 'url',
  1345. 'code' => 'url',
  1346. 'before' => '[url]',
  1347. 'after' => '[/url]',
  1348. 'description' => $txt['hyperlink']
  1349. ),
  1350. array(
  1351. 'image' => 'email',
  1352. 'code' => 'email',
  1353. 'before' => '[email]',
  1354. 'after' => '[/email]',
  1355. 'description' => $txt['insert_email']
  1356. ),
  1357. array(
  1358. 'image' => 'ftp',
  1359. 'code' => 'ftp',
  1360. 'before' => '[ftp]',
  1361. 'after' => '[/ftp]',
  1362. 'description' => $txt['ftp']
  1363. ),
  1364. array(),
  1365. array(
  1366. 'image' => 'glow',
  1367. 'code' => 'glow',
  1368. 'before' => '[glow=red,2,300]',
  1369. 'after' => '[/glow]',
  1370. 'description' => $txt['glow']
  1371. ),
  1372. array(
  1373. 'image' => 'shadow',
  1374. 'code' => 'shadow',
  1375. 'before' => '[shadow=red,left]',
  1376. 'after' => '[/shadow]',
  1377. 'description' => $txt['shadow']
  1378. ),
  1379. array(
  1380. 'image' => 'move',
  1381. 'code' => 'move',
  1382. 'before' => '[move]',
  1383. 'after' => '[/move]',
  1384. 'description' => $txt['marquee']
  1385. ),
  1386. array(),
  1387. array(
  1388. 'image' => 'sup',
  1389. 'code' => 'sup',
  1390. 'before' => '[sup]',
  1391. 'after' => '[/sup]',
  1392. 'description' => $txt['superscript']
  1393. ),
  1394. array(
  1395. 'image' => 'sub',
  1396. 'code' => 'sub',
  1397. 'before' => '[sub]',
  1398. 'after' => '[/sub]',
  1399. 'description' => $txt['subscript']
  1400. ),
  1401. array(
  1402. 'image' => 'tele',
  1403. 'code' => 'tt',
  1404. 'be…

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