PageRenderTime 36ms CodeModel.GetById 24ms RepoModel.GetById 1ms app.codeStats 0ms

/forum/Sources/Subs-Editor.php

https://github.com/leftnode/nooges.com
PHP | 2176 lines | 1597 code | 274 blank | 305 comment | 279 complexity | e59d709141038879e23c171783c874bf MD5 | raw file

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

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

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