Subs-Editor.php 67 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192
  1. <?php
  2. /**
  3. * This file contains those functions specific to the editing box and is
  4. * generally used for WYSIWYG type functionality.
  5. *
  6. * Simple Machines Forum (SMF)
  7. *
  8. * @package SMF
  9. * @author Simple Machines http://www.simplemachines.org
  10. * @copyright 2011 Simple Machines
  11. * @license http://www.simplemachines.org/about/smf/license.php BSD
  12. *
  13. * @version 2.0
  14. */
  15. if (!defined('SMF'))
  16. die('Hacking attempt...');
  17. /*
  18. void theme_postbox(string message)
  19. - for compatibility - passes right through to the template_control_richedit function.
  20. void create_control_richedit(&array editorOptions)
  21. // !!
  22. void create_control_verification(&array suggestOptions)
  23. // !!
  24. void fetchTagAttributes()
  25. // !!
  26. array getMessageIcons(int board_id)
  27. - retrieves a list of message icons.
  28. - based on the settings, the array will either contain a list of default
  29. message icons or a list of custom message icons retrieved from the
  30. database.
  31. - the board_id is needed for the custom message icons (which can be set for
  32. each board individually).
  33. void AutoSuggestHandler(string checkRegistered = null)
  34. // @todo
  35. void AutoSuggest_Search_Member()
  36. // @todo
  37. */
  38. /**
  39. * At the moment this is only used for returning WYSIWYG data.
  40. */
  41. function EditorMain()
  42. {
  43. global $context, $smcFunc;
  44. checkSession('get');
  45. if (!isset($_REQUEST['view']) || !isset($_REQUEST['message']))
  46. fatal_lang_error('no_access', false);
  47. $context['sub_template'] = 'sendbody';
  48. $context['view'] = (int) $_REQUEST['view'];
  49. // Return the right thing for the mode.
  50. if ($context['view'])
  51. {
  52. $_REQUEST['message'] = strtr($_REQUEST['message'], array('#smcol#' => ';', '#smlt#' => '&lt;', '#smgt#' => '&gt;', '#smamp#' => '&amp;'));
  53. $context['message'] = bbc_to_html($_REQUEST['message']);
  54. }
  55. else
  56. {
  57. $_REQUEST['message'] = un_htmlspecialchars($_REQUEST['message']);
  58. $_REQUEST['message'] = strtr($_REQUEST['message'], array('#smcol#' => ';', '#smlt#' => '&lt;', '#smgt#' => '&gt;', '#smamp#' => '&amp;'));
  59. $context['message'] = html_to_bbc($_REQUEST['message']);
  60. }
  61. $context['message'] = $smcFunc['htmlspecialchars']($context['message']);
  62. }
  63. /**
  64. * Convert only the BBC that can be edited in HTML mode for the editor.
  65. * @param string $text
  66. */
  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. // @todo 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. $i = 1;
  106. $text = preg_replace('~(?:\s|&nbsp;)?<(img\ssrc="' . preg_quote($modSettings['smileys_url'], '~') . '/[^<>]+?/([^<>]+?)"\s*)[^<>]*?class="smiley" />~e', '\'<\' . ' . 'stripslashes(\'$1\') . \'alt="" title="" onresizestart="return false;" id="smiley_\' . ' . "\$" . 'i++ . \'_$2" style="padding: 0 3px 0 3px;" />\'', $text);
  107. return $text;
  108. }
  109. /**
  110. * The harder one - wysiwyg to BBC!
  111. *
  112. * @param string $text
  113. * @return string
  114. */
  115. function html_to_bbc($text)
  116. {
  117. global $modSettings, $smcFunc, $sourcedir, $scripturl, $context;
  118. // Replace newlines with spaces, as that's how browsers usually interpret them.
  119. $text = preg_replace("~\s*[\r\n]+\s*~", ' ', $text);
  120. // Though some of us love paragraphs, the parser will do better with breaks.
  121. $text = preg_replace('~</p>\s*?<p~i', '</p><br /><p', $text);
  122. $text = preg_replace('~</p>\s*(?!<)~i', '</p><br />', $text);
  123. // Safari/webkit wraps lines in Wysiwyg in <div>'s.
  124. if ($context['browser']['is_webkit'])
  125. $text = preg_replace(array('~<div(?:\s(?:[^<>]*?))?' . '>~i', '</div>'), array('<br />', ''), $text);
  126. // If there's a trailing break get rid of it - Firefox tends to add one.
  127. $text = preg_replace('~<br\s?/?' . '>$~i', '', $text);
  128. // Remove any formatting within code tags.
  129. if (strpos($text, '[code') !== false)
  130. {
  131. $text = preg_replace('~<br\s?/?' . '>~i', '#smf_br_spec_grudge_cool!#', $text);
  132. $parts = preg_split('~(\[/code\]|\[code(?:=[^\]]+)?\])~i', $text, -1, PREG_SPLIT_DELIM_CAPTURE);
  133. // Only mess with stuff outside [code] tags.
  134. for ($i = 0, $n = count($parts); $i < $n; $i++)
  135. {
  136. // Value of 2 means we're inside the tag.
  137. if ($i % 4 == 2)
  138. $parts[$i] = strip_tags($parts[$i]);
  139. }
  140. $text = strtr(implode('', $parts), array('#smf_br_spec_grudge_cool!#' => '<br />'));
  141. }
  142. // Remove scripts, style and comment blocks.
  143. $text = preg_replace('~<script[^>]*[^/]?' . '>.*?</script>~i', '', $text);
  144. $text = preg_replace('~<style[^>]*[^/]?' . '>.*?</style>~i', '', $text);
  145. $text = preg_replace('~\\<\\!--.*?-->~i', '', $text);
  146. $text = preg_replace('~\\<\\!\\[CDATA\\[.*?\\]\\]\\>~i', '', $text);
  147. // Do the smileys ultra first!
  148. preg_match_all('~<img\s+[^<>]*?id="*smiley_\d+_([^<>]+?)[\s"/>]\s*[^<>]*?/*>(?:\s)?~i', $text, $matches);
  149. if (!empty($matches[0]))
  150. {
  151. // Easy if it's not custom.
  152. if (empty($modSettings['smiley_enable']))
  153. {
  154. $smileysfrom = array('>:D', ':D', '::)', '>:(', ':)', ';)', ';D', ':(', ':o', '8)', ':P', '???', ':-[', ':-X', ':-*', ':\'(', ':-\\', '^-^', 'O0', 'C:-)', '0:)');
  155. $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');
  156. foreach ($matches[1] as $k => $file)
  157. {
  158. $found = array_search($file, $smileysto);
  159. // Note the weirdness here is to stop double spaces between smileys.
  160. if ($found)
  161. $matches[1][$k] = '-[]-smf_smily_start#|#' . htmlspecialchars($smileysfrom[$found]) . '-[]-smf_smily_end#|#';
  162. else
  163. $matches[1][$k] = '';
  164. }
  165. }
  166. else
  167. {
  168. // Load all the smileys.
  169. $names = array();
  170. foreach ($matches[1] as $file)
  171. $names[] = $file;
  172. $names = array_unique($names);
  173. if (!empty($names))
  174. {
  175. $request = $smcFunc['db_query']('', '
  176. SELECT code, filename
  177. FROM {db_prefix}smileys
  178. WHERE filename IN ({array_string:smiley_filenames})',
  179. array(
  180. 'smiley_filenames' => $names,
  181. )
  182. );
  183. $mappings = array();
  184. while ($row = $smcFunc['db_fetch_assoc']($request))
  185. $mappings[$row['filename']] = htmlspecialchars($row['code']);
  186. $smcFunc['db_free_result']($request);
  187. foreach ($matches[1] as $k => $file)
  188. if (isset($mappings[$file]))
  189. $matches[1][$k] = '-[]-smf_smily_start#|#' . $mappings[$file] . '-[]-smf_smily_end#|#';
  190. }
  191. }
  192. // Replace the tags!
  193. $text = str_replace($matches[0], $matches[1], $text);
  194. // Now sort out spaces
  195. $text = str_replace(array('-[]-smf_smily_end#|#-[]-smf_smily_start#|#', '-[]-smf_smily_end#|#', '-[]-smf_smily_start#|#'), ' ', $text);
  196. }
  197. // Only try to buy more time if the client didn't quit.
  198. if (connection_aborted() && $context['server']['is_apache'])
  199. @apache_reset_timeout();
  200. $parts = preg_split('~(<[A-Za-z]+\s*[^<>]*?style="?[^<>"]+"?[^<>]*?(?:/?)>|</[A-Za-z]+>)~', $text, -1, PREG_SPLIT_DELIM_CAPTURE);
  201. $replacement = '';
  202. $stack = array();
  203. foreach ($parts as $part)
  204. {
  205. if (preg_match('~(<([A-Za-z]+)\s*[^<>]*?)style="?([^<>"]+)"?([^<>]*?(/?)>)~', $part, $matches) === 1)
  206. {
  207. // If it's being closed instantly, we can't deal with it...yet.
  208. if ($matches[5] === '/')
  209. continue;
  210. else
  211. {
  212. // Get an array of styles that apply to this element. (The strtr is there to combat HTML generated by Word.)
  213. $styles = explode(';', strtr($matches[3], array('&quot;' => '')));
  214. $curElement = $matches[2];
  215. $precedingStyle = $matches[1];
  216. $afterStyle = $matches[4];
  217. $curCloseTags = '';
  218. $extra_attr = '';
  219. foreach ($styles as $type_value_pair)
  220. {
  221. // Remove spaces and convert uppercase letters.
  222. $clean_type_value_pair = strtolower(strtr(trim($type_value_pair), '=', ':'));
  223. // Something like 'font-weight: bold' is expected here.
  224. if (strpos($clean_type_value_pair, ':') === false)
  225. continue;
  226. // Capture the elements of a single style item (e.g. 'font-weight' and 'bold').
  227. list ($style_type, $style_value) = explode(':', $type_value_pair);
  228. $style_value = trim($style_value);
  229. switch (trim($style_type))
  230. {
  231. case 'font-weight':
  232. if ($style_value === 'bold')
  233. {
  234. $curCloseTags .= '[/b]';
  235. $replacement .= '[b]';
  236. }
  237. break;
  238. case 'text-decoration':
  239. if ($style_value == 'underline')
  240. {
  241. $curCloseTags .= '[/u]';
  242. $replacement .= '[u]';
  243. }
  244. elseif ($style_value == 'line-through')
  245. {
  246. $curCloseTags .= '[/s]';
  247. $replacement .= '[s]';
  248. }
  249. break;
  250. case 'text-align':
  251. if ($style_value == 'left')
  252. {
  253. $curCloseTags .= '[/left]';
  254. $replacement .= '[left]';
  255. }
  256. elseif ($style_value == 'center')
  257. {
  258. $curCloseTags .= '[/center]';
  259. $replacement .= '[center]';
  260. }
  261. elseif ($style_value == 'right')
  262. {
  263. $curCloseTags .= '[/right]';
  264. $replacement .= '[right]';
  265. }
  266. break;
  267. case 'font-style':
  268. if ($style_value == 'italic')
  269. {
  270. $curCloseTags .= '[/i]';
  271. $replacement .= '[i]';
  272. }
  273. break;
  274. case 'color':
  275. $curCloseTags .= '[/color]';
  276. $replacement .= '[color=' . $style_value . ']';
  277. break;
  278. case 'font-size':
  279. // Sometimes people put decimals where decimals should not be.
  280. if (preg_match('~(\d)+\.\d+(p[xt])~i', $style_value, $dec_matches) === 1)
  281. $style_value = $dec_matches[1] . $dec_matches[2];
  282. $curCloseTags .= '[/size]';
  283. $replacement .= '[size=' . $style_value . ']';
  284. break;
  285. case 'font-family':
  286. // Only get the first freaking font if there's a list!
  287. if (strpos($style_value, ',') !== false)
  288. $style_value = substr($style_value, 0, strpos($style_value, ','));
  289. $curCloseTags .= '[/font]';
  290. $replacement .= '[font=' . strtr($style_value, array("'" => '')) . ']';
  291. break;
  292. // This is a hack for images with dimensions embedded.
  293. case 'width':
  294. case 'height':
  295. if (preg_match('~[1-9]\d*~i', $style_value, $dimension) === 1)
  296. $extra_attr .= ' ' . $style_type . '="' . $dimension[0] . '"';
  297. break;
  298. case 'list-style-type':
  299. 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)
  300. $extra_attr .= ' listtype="' . $listType[0] . '"';
  301. break;
  302. }
  303. }
  304. // Preserve some tags stripping the styling.
  305. if (in_array($matches[2], array('a', 'font')))
  306. {
  307. $replacement .= $precedingStyle . $afterStyle;
  308. $curCloseTags = '</' . $matches[2] . '>' . $curCloseTags;
  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. /**
  754. * Returns an array of attributes associated with a tag.
  755. *
  756. * @param string $text
  757. * @return string
  758. */
  759. function fetchTagAttributes($text)
  760. {
  761. $attribs = array();
  762. $key = $value = '';
  763. $strpos = 0;
  764. $tag_state = 0; // 0 = key, 1 = attribute with no string, 2 = attribute with string
  765. for ($i = 0; $i < strlen($text); $i++)
  766. {
  767. // We're either moving from the key to the attribute or we're in a string and this is fine.
  768. if ($text{$i} == '=')
  769. {
  770. if ($tag_state == 0)
  771. $tag_state = 1;
  772. elseif ($tag_state == 2)
  773. $value .= '=';
  774. }
  775. // A space is either moving from an attribute back to a potential key or in a string is fine.
  776. elseif ($text{$i} == ' ')
  777. {
  778. if ($tag_state == 2)
  779. $value .= ' ';
  780. elseif ($tag_state == 1)
  781. {
  782. $attribs[$key] = $value;
  783. $key = $value = '';
  784. $tag_state = 0;
  785. }
  786. }
  787. // A quote?
  788. elseif ($text{$i} == '"')
  789. {
  790. // Must be either going into or out of a string.
  791. if ($tag_state == 1)
  792. $tag_state = 2;
  793. else
  794. $tag_state = 1;
  795. }
  796. // Otherwise it's fine.
  797. else
  798. {
  799. if ($tag_state == 0)
  800. $key .= $text{$i};
  801. else
  802. $value .= $text{$i};
  803. }
  804. }
  805. // Anything left?
  806. if ($key != '' && $value != '')
  807. $attribs[$key] = $value;
  808. return $attribs;
  809. }
  810. /**
  811. * Retrieves a list of message icons.
  812. * Based on the settings, the array will either contain a list of default
  813. * message icons or a list of custom message icons retrieved from the database.
  814. * The board_id is needed for the custom message icons (which can be set for
  815. * each board individually).
  816. *
  817. * @param int $board_id
  818. * @return array
  819. */
  820. function getMessageIcons($board_id)
  821. {
  822. global $modSettings, $context, $txt, $settings, $smcFunc;
  823. if (empty($modSettings['messageIcons_enable']))
  824. {
  825. loadLanguage('Post');
  826. $icons = array(
  827. array('value' => 'xx', 'name' => $txt['standard']),
  828. array('value' => 'thumbup', 'name' => $txt['thumbs_up']),
  829. array('value' => 'thumbdown', 'name' => $txt['thumbs_down']),
  830. array('value' => 'exclamation', 'name' => $txt['excamation_point']),
  831. array('value' => 'question', 'name' => $txt['question_mark']),
  832. array('value' => 'lamp', 'name' => $txt['lamp']),
  833. array('value' => 'smiley', 'name' => $txt['icon_smiley']),
  834. array('value' => 'angry', 'name' => $txt['icon_angry']),
  835. array('value' => 'cheesy', 'name' => $txt['icon_cheesy']),
  836. array('value' => 'grin', 'name' => $txt['icon_grin']),
  837. array('value' => 'sad', 'name' => $txt['icon_sad']),
  838. array('value' => 'wink', 'name' => $txt['icon_wink'])
  839. );
  840. foreach ($icons as $k => $dummy)
  841. {
  842. $icons[$k]['url'] = $settings['images_url'] . '/post/' . $dummy['value'] . '.gif';
  843. $icons[$k]['is_last'] = false;
  844. }
  845. }
  846. // Otherwise load the icons, and check we give the right image too...
  847. else
  848. {
  849. if (($temp = cache_get_data('posting_icons-' . $board_id, 480)) == null)
  850. {
  851. $request = $smcFunc['db_query']('select_message_icons', '
  852. SELECT title, filename
  853. FROM {db_prefix}message_icons
  854. WHERE id_board IN (0, {int:board_id})',
  855. array(
  856. 'board_id' => $board_id,
  857. )
  858. );
  859. $icon_data = array();
  860. while ($row = $smcFunc['db_fetch_assoc']($request))
  861. $icon_data[] = $row;
  862. $smcFunc['db_free_result']($request);
  863. cache_put_data('posting_icons-' . $board_id, $icon_data, 480);
  864. }
  865. else
  866. $icon_data = $temp;
  867. $icons = array();
  868. foreach ($icon_data as $icon)
  869. {
  870. $icons[$icon['filename']] = array(
  871. 'value' => $icon['filename'],
  872. 'name' => $icon['title'],
  873. 'url' => $settings[file_exists($settings['theme_dir'] . '/images/post/' . $icon['filename'] . '.gif') ? 'images_url' : 'default_images_url'] . '/post/' . $icon['filename'] . '.gif',
  874. 'is_last' => false,
  875. );
  876. }
  877. }
  878. return array_values($icons);
  879. }
  880. // 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!!!
  881. function legalise_bbc($text)
  882. {
  883. global $modSettings;
  884. // Don't care about the texts that are too short.
  885. if (strlen($text) < 3)
  886. return $text;
  887. // 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!
  888. // This will keep the order of tags that are open.
  889. $current_tags = array();
  890. // This will quickly let us see if the tag is active.
  891. $active_tags = array();
  892. // A list of tags that's disabled by the admin.
  893. $disabled = empty($modSettings['disabledBBC']) ? array() : array_flip(explode(',', strtolower($modSettings['disabledBBC'])));
  894. // Add flash if it's disabled as embedded tag.
  895. if (empty($modSettings['enableEmbeddedFlash']))
  896. $disabled['flash'] = true;
  897. // Get a list of all the tags that are not disabled.
  898. $all_tags = parse_bbc(false);
  899. $valid_tags = array();
  900. $self_closing_tags = array();
  901. foreach ($all_tags as $tag)
  902. {
  903. if (!isset($disabled[$tag['tag']]))
  904. $valid_tags[$tag['tag']] = !empty($tag['block_level']);
  905. if (isset($tag['type']) && $tag['type'] == 'closed')
  906. $self_closing_tags[] = $tag['tag'];
  907. }
  908. // Don't worry if we're in a code/nobbc.
  909. $in_code_nobbc = false;
  910. // 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!
  911. $align_tags = array('left', 'center', 'right', 'pre');
  912. // Remove those align tags that are not valid.
  913. $align_tags = array_intersect($align_tags, array_keys($valid_tags));
  914. // These keep track of where we are!
  915. if (!empty($align_tags) && count($matches = preg_split('~(\\[/?(?:' . implode('|', $align_tags) . ')\\])~', $text, -1, PREG_SPLIT_DELIM_CAPTURE)) > 1)
  916. {
  917. // The first one is never a tag.
  918. $isTag = false;
  919. // By default we're not inside a tag too.
  920. $insideTag = null;
  921. foreach ($matches as $i => $match)
  922. {
  923. // We're only interested in tags, not text.
  924. if ($isTag)
  925. {
  926. $isClosingTag = substr($match, 1, 1) === '/';
  927. $tagName = substr($match, $isClosingTag ? 2 : 1, -1);
  928. // We're closing the exact same tag that we opened.
  929. if ($isClosingTag && $insideTag === $tagName)
  930. $insideTag = null;
  931. // We're opening a tag and we're not yet inside one either
  932. elseif (!$isClosingTag && $insideTag === null)
  933. $insideTag = $tagName;
  934. // In all other cases, this tag must be invalid
  935. else
  936. unset($matches[$i]);
  937. }
  938. // The next one is gonna be the other one.
  939. $isTag = !$isTag;
  940. }
  941. // We're still inside a tag and had no chance for closure?
  942. if ($insideTag !== null)
  943. $matches[] = '[/' . $insideTag . ']';
  944. // And a complete text string again.
  945. $text = implode('', $matches);
  946. }
  947. // Quickly remove any tags which are back to back.
  948. $backToBackPattern = '~\\[(' . implode('|', array_diff(array_keys($valid_tags), array('td', 'anchor'))) . ')[^<>\\[\\]]*\\]\s*\\[/\\1\\]~';
  949. $lastlen = 0;
  950. while (strlen($text) !== $lastlen)
  951. $lastlen = strlen($text = preg_replace($backToBackPattern, '', $text));
  952. // Need to sort the tags my name length.
  953. uksort($valid_tags, 'sort_array_length');
  954. // These inline tags can compete with each other regarding style.
  955. $competing_tags = array(
  956. 'color',
  957. 'size',
  958. );
  959. // In case things changed above set these back to normal.
  960. $in_code_nobbc = false;
  961. $new_text_offset = 0;
  962. // These keep track of where we are!
  963. if (count($parts = preg_split(sprintf('~(\\[)(/?)(%1$s)((?:[\\s=][^\\]\\[]*)?\\])~', implode('|', array_keys($valid_tags))), $text, -1, PREG_SPLIT_DELIM_CAPTURE)) > 1)
  964. {
  965. // Start with just text.
  966. $isTag = false;
  967. // Start outside [nobbc] or [code] blocks.
  968. $inCode = false;
  969. $inNoBbc = false;
  970. // A buffer containing all opened inline elements.
  971. $inlineElements = array();
  972. // A buffer containing all opened block elements.
  973. $blockElements = array();
  974. // A buffer containing the opened inline elements that might compete.
  975. $competingElements = array();
  976. // $i: text, $i + 1: '[', $i + 2: '/', $i + 3: tag, $i + 4: tag tail.
  977. for ($i = 0, $n = count($parts) - 1; $i < $n; $i += 5)
  978. {
  979. $tag = $parts[$i + 3];
  980. $isOpeningTag = $parts[$i + 2] === '';
  981. $isClosingTag = $parts[$i + 2] === '/';
  982. $isBlockLevelTag = isset($valid_tags[$tag]) && $valid_tags[$tag] && !in_array($tag, $self_closing_tags);
  983. $isCompetingTag = in_array($tag, $competing_tags);
  984. // Check if this might be one of those cleaned out tags.
  985. if ($tag === '')
  986. continue;
  987. // Special case: inside [code] blocks any code is left untouched.
  988. elseif ($tag === 'code')
  989. {
  990. // We're inside a code block and closing it.
  991. if ($inCode && $isClosingTag)
  992. {
  993. $inCode = false;
  994. // Reopen tags that were closed before the code block.
  995. if (!empty($inlineElements))
  996. $parts[$i + 4] .= '[' . implode('][', array_keys($inlineElements)) . ']';
  997. }
  998. // We're outside a coding and nobbc block and opening it.
  999. elseif (!$inCode && !$inNoBbc && $isOpeningTag)
  1000. {
  1001. // If there are still inline elements left open, close them now.
  1002. if (!empty($inlineElements))
  1003. {
  1004. $parts[$i] .= '[/' . implode('][/', array_reverse($inlineElements)) . ']';
  1005. //$inlineElements = array();
  1006. }
  1007. $inCode = true;
  1008. }
  1009. // Nothing further to do.
  1010. continue;
  1011. }
  1012. // Special case: inside [nobbc] blocks any BBC is left untouched.
  1013. elseif ($tag === 'nobbc')
  1014. {
  1015. // We're inside a nobbc block and closing it.
  1016. if ($inNoBbc && $isClosingTag)
  1017. {
  1018. $inNoBbc = false;
  1019. // Some inline elements might've been closed that need reopening.
  1020. if (!empty($inlineElements))
  1021. $parts[$i + 4] .= '[' . implode('][', array_keys($inlineElements)) . ']';
  1022. }
  1023. // We're outside a nobbc and coding block and opening it.
  1024. elseif (!$inNoBbc && !$inCode && $isOpeningTag)
  1025. {
  1026. // Can't have inline elements still opened.
  1027. if (!empty($inlineElements))
  1028. {
  1029. $parts[$i] .= '[/' . implode('][/', array_reverse($inlineElements)) . ']';
  1030. //$inlineElements = array();
  1031. }
  1032. $inNoBbc = true;
  1033. }
  1034. continue;
  1035. }
  1036. // So, we're inside one of the special blocks: ignore any tag.
  1037. elseif ($inCode || $inNoBbc)
  1038. continue;
  1039. // We're dealing with an opening tag.
  1040. if ($isOpeningTag)
  1041. {
  1042. // Everyting inside the square brackets of the opening tag.
  1043. $elementContent = $parts[$i + 3] . substr($parts[$i + 4], 0, -1);
  1044. // A block level opening tag.
  1045. if ($isBlockLevelTag)
  1046. {
  1047. // Are there inline elements still open?
  1048. if (!empty($inlineElements))
  1049. {
  1050. // Close all the inline tags, a block tag is coming...
  1051. $parts[$i] .= '[/' . implode('][/', array_reverse($inlineElements)) . ']';
  1052. // Now open them again, we're inside the block tag now.
  1053. $parts[$i + 5] = '[' . implode('][', array_keys($inlineElements)) . ']' . $parts[$i + 5];
  1054. }
  1055. $blockElements[] = $tag;
  1056. }
  1057. // Inline opening tag.
  1058. elseif (!in_array($tag, $self_closing_tags))
  1059. {
  1060. // Can't have two opening elements with the same contents!
  1061. if (isset($inlineElements[$elementContent]))
  1062. {
  1063. // Get rid of this tag.
  1064. $parts[$i + 1] = $parts[$i + 2] = $parts[$i + 3] = $parts[$i + 4] = '';
  1065. // Now try to find the corresponding closing tag.
  1066. $curLevel = 1;
  1067. for ($j = $i + 5, $m = count($parts) - 1; $j < $m; $j += 5)
  1068. {
  1069. // Find the tags with the same tagname
  1070. if ($parts[$j + 3] === $tag)
  1071. {
  1072. // If it's an opening tag, increase the level.
  1073. if ($parts[$j + 2] === '')
  1074. $curLevel++;
  1075. // A closing tag, decrease the level.
  1076. else
  1077. {
  1078. $curLevel--;
  1079. // Gotcha! Clean out this closing tag gone rogue.
  1080. if ($curLevel === 0)
  1081. {
  1082. $parts[$j + 1] = $parts[$j + 2] = $parts[$j + 3] = $parts[$j + 4] = '';
  1083. break;
  1084. }
  1085. }
  1086. }
  1087. }
  1088. }
  1089. // Otherwise, add this one to the list.
  1090. else
  1091. {
  1092. if ($isCompetingTag)
  1093. {
  1094. if (!isset($competingElements[$tag]))
  1095. $competingElements[$tag] = array();
  1096. $competingElements[$tag][] = $parts[$i + 4];
  1097. if (count($competingElements[$tag]) > 1)
  1098. $parts[$i] .= '[/' . $tag . ']';
  1099. }
  1100. $inlineElements[$elementContent] = $tag;
  1101. }
  1102. }
  1103. }
  1104. // Closing tag.
  1105. else
  1106. {
  1107. // Closing the block tag.
  1108. if ($isBlockLevelTag)
  1109. {
  1110. // Close the elements that should've been closed by closing this tag.
  1111. if (!empty($blockElements))
  1112. {
  1113. $addClosingTags = array();
  1114. while ($element = array_pop($blockElements))
  1115. {
  1116. if ($element === $tag)
  1117. break;
  1118. // Still a block tag was open not equal to this tag.
  1119. $addClosingTags[] = $element['type'];
  1120. }
  1121. if (!empty($addClosingTags))
  1122. $parts[$i + 1] = '[/' . implode('][/', array_reverse($addClosingTags)) . ']' . $parts[$i + 1];
  1123. // Apparently the closing tag was not found on the stack.
  1124. if (!is_string($element) || $element !== $tag)
  1125. {
  1126. // Get rid of this particular closing tag, it was never opened.
  1127. $parts[$i + 1] = substr($parts[$i + 1], 0, -1);
  1128. $parts[$i + 2] = $parts[$i + 3] = $parts[$i + 4] = '';
  1129. continue;
  1130. }
  1131. }
  1132. else
  1133. {
  1134. // Get rid of this closing tag!
  1135. $parts[$i + 1] = $parts[$i + 2] = $parts[$i + 3] = $parts[$i + 4] = '';
  1136. continue;
  1137. }
  1138. // Inline elements are still left opened?
  1139. if (!empty($inlineElements))
  1140. {
  1141. // Close them first..
  1142. $parts[$i] .= '[/' . implode('][/', array_reverse($inlineElements)) . ']';
  1143. // Then reopen them.
  1144. $parts[$i + 5] = '[' . implode('][', array_keys($inlineElements)) . ']' . $parts[$i + 5];
  1145. }
  1146. }
  1147. // Inline tag.
  1148. else
  1149. {
  1150. // Are we expecting this tag to end?
  1151. if (in_array($tag, $inlineElements))
  1152. {
  1153. foreach (array_reverse($inlineElements, true) as $tagContentToBeClosed => $tagToBeClosed)
  1154. {
  1155. // Closing it one way or the other.
  1156. unset($inlineElements[$tagContentToBeClosed]);
  1157. // Was this the tag we were looking for?
  1158. if ($tagToBeClosed === $tag)
  1159. break;
  1160. // Nope, close it and look further!
  1161. else
  1162. $parts[$i] .= '[/' . $tagToBeClosed . ']';
  1163. }
  1164. if ($isCompetingTag && !empty($competingElements[$tag]))
  1165. {
  1166. array_pop($competingElements[$tag]);
  1167. if (count($competingElements[$tag]) > 0)
  1168. $parts[$i + 5] = '[' . $tag . $competingElements[$tag][count($competingElements[$tag]) - 1] . $parts[$i + 5];
  1169. }
  1170. }
  1171. // Unexpected closing tag, ex-ter-mi-nate.
  1172. else
  1173. $parts[$i + 1] = $parts[$i + 2] = $parts[$i + 3] = $parts[$i + 4] = '';
  1174. }
  1175. }
  1176. }
  1177. // Close the code tags.
  1178. if ($inCode)
  1179. $parts[$i] .= '[/code]';
  1180. // The same for nobbc tags.
  1181. elseif ($inNoBbc)
  1182. $parts[$i] .= '[/nobbc]';
  1183. // Still inline tags left unclosed? Close them now, better late than never.
  1184. elseif (!empty($inlineElements))
  1185. $parts[$i] .= '[/' . implode('][/', array_reverse($inlineElements)) . ']';
  1186. // Now close the block elements.
  1187. if (!empty($blockElements))
  1188. $parts[$i] .= '[/' . implode('][/', array_reverse($blockElements)) . ']';
  1189. $text = implode('', $parts);
  1190. }
  1191. // Final clean up of back to back tags.
  1192. $lastlen = 0;
  1193. while (strlen($text) !== $lastlen)
  1194. $lastlen = strlen($text = preg_replace($backToBackPattern, '', $text));
  1195. return $text;
  1196. }
  1197. // A help function for legalise_bbc for sorting arrays based on length.
  1198. function sort_array_length($a, $b)
  1199. {
  1200. return strlen($a) < strlen($b) ? 1 : -1;
  1201. }
  1202. // Compatibility function - used in 1.1 for showing a post box.
  1203. function theme_postbox($msg)
  1204. {
  1205. global $context;
  1206. return template_control_richedit($context['post_box_name']);
  1207. }
  1208. // Creates a box that can be used for richedit stuff like BBC, Smileys etc.
  1209. function create_control_richedit($editorOptions)
  1210. {
  1211. global $txt, $modSettings, $options, $smcFunc;
  1212. global $context, $settings, $user_info, $sourcedir, $scripturl;
  1213. // Load the Post language file... for the moment at least.
  1214. loadLanguage('Post');
  1215. // Every control must have a ID!
  1216. assert(isset($editorOptions['id']));
  1217. assert(isset($editorOptions['value']));
  1218. // Is this the first richedit - if so we need to ensure some template stuff is initialised.
  1219. if (empty($context['controls']['richedit']))
  1220. {
  1221. // Some general stuff.
  1222. $settings['smileys_url'] = $modSettings['smileys_url'] . '/' . $user_info['smiley_set'];
  1223. // This really has some WYSIWYG stuff.
  1224. loadTemplate('GenericControls', $context['browser']['is_ie'] ? 'editor_ie' : 'editor');
  1225. $context['html_headers'] .= '
  1226. <script type="text/javascript"><!-- // --><![CDATA[
  1227. var smf_smileys_url = \'' . $settings['smileys_url'] . '\';
  1228. var oEditorStrings= {
  1229. wont_work: \'' . addcslashes($txt['rich_edit_wont_work'], "'") . '\',
  1230. func_disabled: \'' . addcslashes($txt['rich_edit_function_disabled'], "'") . '\',
  1231. prompt_text_email: \'' . addcslashes($txt['prompt_text_email'], "'") . '\',
  1232. prompt_text_ftp: \'' . addcslashes($txt['prompt_text_ftp'], "'") . '\',
  1233. prompt_text_url: \'' . addcslashes($txt['prompt_text_url'], "'") . '\',
  1234. prompt_text_img: \'' . addcslashes($txt['prompt_text_img'], "'") . '\'
  1235. }
  1236. // ]]></script>
  1237. <script type="text/javascript" src="' . $settings['default_theme_url'] . '/scripts/editor.js?fin20"></script>';
  1238. $context['show_spellchecking'] = !empty($modSettings['enableSpellChecking']) && function_exists('pspell_new');
  1239. if ($context['show_spellchecking'])
  1240. {
  1241. $context['html_headers'] .= '
  1242. <script type="text/javascript" src="' . $settings['default_theme_url'] . '/scripts/spellcheck.js"></script>';
  1243. // Some hidden information is needed in order to make the spell checking work.
  1244. if (!isset($_REQUEST['xml']))
  1245. $context['insert_after_template'] .= '
  1246. <form name="spell_form" id="spell_form" method="post" accept-charset="' . $context['character_set'] . '" target="spellWindow" action="' . $scripturl . '?action=spellcheck">
  1247. <input type="hidden" name="spellstring" value="" />
  1248. </form>';
  1249. // Also make sure that spell check works with rich edit.
  1250. $context['html_headers'] .= '
  1251. <script type="text/javascript"><!-- // --><![CDATA[
  1252. function spellCheckDone()
  1253. {
  1254. for (i = 0; i < smf_editorArray.length; i++)
  1255. setTimeout("smf_editorArray[" + i + "].spellCheckEnd()", 150);
  1256. }
  1257. // ]]></script>';
  1258. }
  1259. }
  1260. // Start off the editor...
  1261. $context['controls']['richedit'][$editorOptions['id']] = array(
  1262. 'id' => $editorOptions['id'],
  1263. 'value' => $editorOptions['value'],
  1264. 'rich_value' => bbc_to_html($editorOptions['value']),
  1265. 'rich_active' => empty($modSettings['disable_wysiwyg']) && (!empty($options['wysiwyg_default']) || !empty($editorOptions['force_rich']) || !empty($_REQUEST[$editorOptions['id'] . '_mode'])),
  1266. 'disable_smiley_box' => !empty($editorOptions['disable_smiley_box']),
  1267. 'columns' => isset($editorOptions['columns']) ? $editorOptions['columns'] : 60,
  1268. 'rows' => isset($editorOptions['rows']) ? $editorOptions['rows'] : 12,
  1269. 'width' => isset($editorOptions['width']) ? $editorOptions['width'] : '70%',
  1270. 'height' => isset($editorOptions['height']) ? $editorOptions['height'] : '150px',
  1271. 'form' => isset($editorOptions['form']) ? $editorOptions['form'] : 'postmodify',
  1272. 'bbc_level' => !empty($editorOptions['bbc_level']) ? $editorOptions['bbc_level'] : 'full',
  1273. 'preview_type' => isset($editorOptions['preview_type']) ? (int) $editorOptions['preview_type'] : 1,
  1274. 'labels' => !empty($editorOptions['labels']) ? $editorOptions['labels'] : array(),
  1275. );
  1276. // Switch between default images and back... mostly in case you don't have an PersonalMessage template, but do have a Post template.
  1277. if (isset($settings['use_default_images']) && $settings['use_default_images'] == 'defaults' && isset($settings['default_template']))
  1278. {
  1279. $temp1 = $settings['theme_url'];
  1280. $settings['theme_url'] = $settings['default_theme_url'];
  1281. $temp2 = $settings['images_url'];
  1282. $settings['images_url'] = $settings['default_images_url'];
  1283. $temp3 = $settings['theme_dir'];
  1284. $settings['theme_dir'] = $settings['default_theme_dir'];
  1285. }
  1286. if (empty($context['bbc_tags']))
  1287. {
  1288. // 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!
  1289. $context['bbc_tags'] = array();
  1290. $context['bbc_tags'][] = array(
  1291. array(
  1292. 'image' => 'bold',
  1293. 'code' => 'b',
  1294. 'before' => '[b]',
  1295. 'after' => '[/b]',
  1296. 'description' => $txt['bold'],
  1297. ),
  1298. array(
  1299. 'image' => 'italicize',
  1300. 'code' => 'i',
  1301. 'before' => '[i]',
  1302. 'after' => '[/i]',
  1303. 'description' => $txt['italic'],
  1304. ),
  1305. array(
  1306. 'image' => 'underline',
  1307. 'code' => 'u',
  1308. 'before' => '[u]',
  1309. 'after' => '[/u]',
  1310. 'description' => $txt['underline']
  1311. ),
  1312. array(
  1313. 'image' => 'strike',
  1314. 'code' => 's',
  1315. 'before' => '[s]',
  1316. 'after' => '[/s]',
  1317. 'description' => $txt['strike']
  1318. ),
  1319. array(),
  1320. array(
  1321. 'image' => 'pre',
  1322. 'code' => 'pre',
  1323. 'before' => '[pre]',
  1324. 'after' => '[/pre]',
  1325. 'description' => $txt['preformatted']
  1326. ),
  1327. array(
  1328. 'image' => 'left',
  1329. 'code' => 'left',
  1330. 'before' => '[left]',
  1331. 'after' => '[/left]',
  1332. 'description' => $txt['left_align']
  1333. ),
  1334. array(
  1335. 'image' => 'center',
  1336. 'code' => 'center',
  1337. 'before' => '[center]',
  1338. 'after' => '[/center]',
  1339. 'description' => $txt['center']
  1340. ),
  1341. array(
  1342. 'image' => 'right',
  1343. 'code' => 'right',
  1344. 'before' => '[right]',
  1345. 'after' => '[/right]',
  1346. 'description' => $txt['right_align']
  1347. ),
  1348. );
  1349. $context['bbc_tags'][] = array(
  1350. array(
  1351. 'image' => 'flash',
  1352. 'code' => 'flash',
  1353. 'before' => '[flash=200,200]',
  1354. 'after' => '[/flash]',
  1355. 'description' => $txt['flash']
  1356. ),
  1357. array(
  1358. 'image' => 'img',
  1359. 'code' => 'img',
  1360. 'before' => '[img]',
  1361. 'after' => '[/img]',
  1362. 'description' => $txt['image']
  1363. ),
  1364. array(
  1365. 'image' => 'url',
  1366. 'code' => 'url',
  1367. 'before' => '[url]',
  1368. 'after' => '[/url]',
  1369. 'description' => $txt['hyperlink']
  1370. ),
  1371. array(
  1372. 'image' => 'email',
  1373. 'code' => 'email',
  1374. 'before' => '[email]',
  1375. 'after' => '[/email]',
  1376. 'description' => $txt['insert_email']
  1377. ),
  1378. array(
  1379. 'image' => 'ftp',
  1380. 'code' => 'ftp',
  1381. 'before' => '[ftp]',
  1382. 'after' => '[/ftp]',
  1383. 'description' => $txt['ftp']
  1384. ),
  1385. array(),
  1386. array(
  1387. 'image' => 'glow',
  1388. 'code' => 'glow',
  1389. 'before' => '[glow=red,2,300]',
  1390. 'after' => '[/glow]',
  1391. 'description' => $txt['glow']
  1392. ),
  1393. array(
  1394. 'image' => 'shadow',
  1395. 'code' => 'shadow',
  1396. 'before' => '[shadow=red,left]',
  1397. 'after' => '[/shadow]',
  1398. 'description' => $txt['shadow']
  1399. ),
  1400. array(
  1401. 'image' => 'move',
  1402. 'code' => 'move',
  1403. 'before' => '[move]',
  1404. 'after' => '[/move]',
  1405. 'description' => $txt['marquee']
  1406. ),
  1407. array(),
  1408. array(
  1409. 'image' => 'sup',
  1410. 'code' => 'sup',
  1411. 'before' => '[sup]',
  1412. 'after' => '[/sup]',
  1413. 'description' => $txt['superscript']
  1414. ),
  1415. array(
  1416. 'image' => 'sub',
  1417. 'code' => 'sub',
  1418. 'before' => '[sub]',
  1419. 'after' => '[/sub]',
  1420. 'description' => $txt['subscript']
  1421. ),
  1422. array(
  1423. 'image' => 'tele',
  1424. 'code' => 'tt',
  1425. 'before' => '[tt]',
  1426. 'after' => '[/tt]',
  1427. 'description' => $txt['teletype']
  1428. ),
  1429. array(),
  1430. array(
  1431. 'image' => 'table',
  1432. 'code' => 'table',
  1433. 'before' => '[table]\n[tr]\n[td]',
  1434. 'after' => '[/td]\n[/tr]\n[/table]',
  1435. 'description' => $txt['table']
  1436. ),
  1437. array(
  1438. 'image' => 'code',
  1439. 'code' => 'code',
  1440. 'before' => '[code]',
  1441. 'after' => '[/code]',
  1442. 'description' => $txt['bbc_code']
  1443. ),
  1444. array(
  1445. 'image' => 'quote',
  1446. 'code' => 'quote',
  1447. 'before' => '[quote]',
  1448. 'after' => '[/quote]',
  1449. 'description' => $txt['bbc_quote']
  1450. ),
  1451. array(),
  1452. array(
  1453. 'image' => 'list',
  1454. 'code' => 'list',
  1455. 'before' => '[list]\n[li]',
  1456. 'after' => '[/li]\n[li][/li]\n[/list]',
  1457. 'description' => $txt['list_unordered']
  1458. ),
  1459. array(
  1460. 'image' => 'orderlist',
  1461. 'code' => 'orderlist',
  1462. 'before' => '[list type=decimal]\n[li]',
  1463. 'after' => '[/li]\n[li][/li]\n[/list]',
  1464. 'description' => $txt['list_ordered']
  1465. ),
  1466. array(
  1467. 'image' => 'hr',
  1468. 'code' => 'hr',
  1469. 'before' => '[hr]',
  1470. 'description' => $txt['horizontal_rule']
  1471. ),
  1472. );
  1473. // Allow mods to modify BBC buttons.
  1474. call_integration_hook('integrate_bbc_buttons', array(&$context['bbc_tags']));
  1475. // Show the toggle?
  1476. if (empty($modSettings['disable_wysiwyg']))
  1477. {
  1478. $context['bbc_tags'][count($context['bbc_tags']) - 1][] = array();
  1479. $context['bbc_tags'][count($context['bbc_tags']) - 1][] = array(
  1480. 'image' => 'unformat',
  1481. 'code' => 'unformat',
  1482. 'before' => '',
  1483. 'description' => $txt['unformat_text'],
  1484. );
  1485. $context['bbc_tags'][count($context['bbc_tags']) - 1][] = array(
  1486. 'image' => 'toggle',
  1487. 'code' => 'toggle',
  1488. 'before' => '',
  1489. 'description' => $txt['toggle_view'],
  1490. );
  1491. }
  1492. foreach ($context['bbc_tags'] as $row => $tagRow)
  1493. $context['bbc_tags'][$row][count($tagRow) - 1]['isLast'] = true;
  1494. }
  1495. // Initialize smiley array... if not loaded before.
  1496. if (empty($context['smileys']) && empty($editorOptions['disable_smiley_box']))
  1497. {
  1498. $context['smileys'] = array(
  1499. 'postform' => array(),
  1500. 'popup' => array(),
  1501. );
  1502. // Load smileys - don't bother to run a query if we're not using the database's ones anyhow.
  1503. if (empty($modSettings['smiley_enable']) && $user_info['smiley_set'] != 'none')
  1504. $context['smileys']['postform'][] = array(
  1505. 'smileys' => array(
  1506. array(
  1507. 'code' => ':)',
  1508. 'filename' => 'smiley.gif',
  1509. 'description' => $txt['icon_smiley'],
  1510. ),
  1511. array(
  1512. 'code' => ';)',
  1513. 'filename' => 'wink.gif',
  1514. 'description' => $txt['icon_wink'],
  1515. ),
  1516. array(
  1517. 'code' => ':D',
  1518. 'filename' => 'cheesy.gif',
  1519. 'description' => $txt['icon_cheesy'],
  1520. ),
  1521. array(
  1522. 'code' => ';D',
  1523. 'filename' => 'grin.gif',
  1524. 'description' => $txt['icon_grin']
  1525. ),
  1526. array(
  1527. 'code' => '>:(',
  1528. 'filename' => 'angry.gif',
  1529. 'description' => $txt['icon_angry'],
  1530. ),
  1531. array(
  1532. 'code' => ':(',
  1533. 'filename' => 'sad.gif',
  1534. 'description' => $txt['icon_sad'],
  1535. ),
  1536. array(
  1537. 'code' => ':o',
  1538. 'filename' => 'shocked.gif',
  1539. 'description' => $txt['icon_shocked'],
  1540. ),
  1541. array(
  1542. 'code' => '8)',
  1543. 'filename' => 'cool.gif',
  1544. 'description' => $txt['icon_cool'],
  1545. ),
  1546. array(
  1547. 'code' => '???',
  1548. 'filename' => 'huh.gif',
  1549. 'description' => $txt['icon_huh'],
  1550. ),
  1551. array(
  1552. 'code' => '::)',
  1553. 'filename' => 'rolleyes.gif',
  1554. 'description' => $txt['icon_rolleyes'],
  1555. ),
  1556. array(
  1557. 'code' => ':P',
  1558. 'filename' => 'tongue.gif',
  1559. 'description' => $txt['icon_tongue'],
  1560. ),
  1561. array(
  1562. 'code' => ':-[',
  1563. 'filename' => 'embarrassed.gif',
  1564. 'description' => $txt['icon_embarrassed'],
  1565. ),
  1566. array(
  1567. 'code' => ':-X',
  1568. 'filename' => 'lipsrsealed.gif',
  1569. 'description' => $txt['icon_lips'],
  1570. ),
  1571. array(
  1572. 'code' => ':-\\',
  1573. 'filename' => 'undecided.gif',
  1574. 'description' => $txt['icon_undecided'],
  1575. ),
  1576. array(
  1577. 'code' => ':-*',
  1578. 'filename' => 'kiss.gif',
  1579. 'description' => $txt['icon_kiss'],
  1580. ),
  1581. array(
  1582. 'code' => ':\'(',
  1583. 'filename' => 'cry.gif',
  1584. 'description' => $txt['icon_cry'],
  1585. 'isLast' => true,
  1586. ),
  1587. ),
  1588. 'isLast' => true,
  1589. );
  1590. elseif ($user_info['smiley_set'] != 'none')
  1591. {
  1592. if (($temp = cache_get_data('posting_smileys', 480)) == null)
  1593. {
  1594. $request = $smcFunc['db_query']('', '
  1595. SELECT code, filename, description, smiley_row, hidden
  1596. FROM {db_prefix}smileys
  1597. WHERE hidden IN (0, 2)
  1598. ORDER BY smiley_row, smiley_order',
  1599. array(
  1600. )
  1601. );
  1602. while ($row = $smcFunc['db_fetch_assoc']($request))
  1603. {
  1604. $row['filename'] = htmlspecialchars($row['filename']);
  1605. $row['description'] = htmlspecialchars($row['description']);
  1606. $context['smileys'][empty($row['hidden']) ? 'postform' : 'popup'][$row['smiley_row']]['smileys'][] = $row;
  1607. }
  1608. $smcFunc['db_free_result']($request);
  1609. foreach ($context['smileys'] as $section => $smileyRows)
  1610. {
  1611. foreach ($smileyRows as $rowIndex => $smileys)
  1612. $context['smileys'][$section][$rowIndex]['smileys'][count($smileys['smileys']) - 1]['isLast'] = true;
  1613. if (!empty($smileyRows))
  1614. $context['smileys'][$section][count($smileyRows) - 1]['isLast'] = true;
  1615. }
  1616. cache_put_data('posting_smileys', $context['smileys'], 480);
  1617. }
  1618. else
  1619. $context['smileys'] = $temp;
  1620. }
  1621. }
  1622. // Set a flag so the sub template knows what to do...
  1623. $context['show_bbc'] = !empty($modSettings['enableBBC']) && !empty($settings['show_bbc']);
  1624. // Generate a list of buttons that shouldn't be shown - this should be the fastest way to do this.
  1625. $disabled_tags = array();
  1626. if (!empty($modSettings['disabledBBC']))
  1627. $disabled_tags = explode(',', $modSettings['disabledBBC']);
  1628. if (empty($modSettings['enableEmbeddedFlash']))
  1629. $disabled_tags[] = 'flash';
  1630. foreach ($disabled_tags as $tag)
  1631. {
  1632. if ($tag == 'list')
  1633. $context['disabled_tags']['orderlist'] = true;
  1634. $context['disabled_tags'][trim($tag)] = true;
  1635. }
  1636. // Switch the URLs back... now we're back to whatever the main sub template is. (like folder in PersonalMessage.)
  1637. if (isset($settings['use_default_images']) && $settings['use_default_images'] == 'defaults' && isset($settings['default_template']))
  1638. {
  1639. $settings['theme_url'] = $temp1;
  1640. $settings['images_url'] = $temp2;
  1641. $settings['theme_dir'] = $temp3;
  1642. }
  1643. }
  1644. // Create a anti-bot verification control?
  1645. function create_control_verification(&$verificationOptions, $do_test = false)
  1646. {
  1647. global $txt, $modSettings, $options, $smcFunc;
  1648. global $context, $settings, $user_info, $sourcedir, $scripturl;
  1649. // First verification means we need to set up some bits...
  1650. if (empty($context['controls']['verification']))
  1651. {
  1652. // The template
  1653. loadTemplate('GenericControls');
  1654. // Some javascript ma'am?
  1655. if (!empty($verificationOptions['override_visual']) || (!empty($modSettings['visual_verification_type']) && !isset($verificationOptions['override_visual'])))
  1656. $context['html_headers'] .= '
  1657. <script type="text/javascript" src="' . $settings['default_theme_url'] . '/scripts/captcha.js"></script>';
  1658. $context['use_graphic_library'] = in_array('gd', get_loaded_extensions());
  1659. // Skip I, J, L, O, Q, S and Z.
  1660. $context['standard_captcha_range'] = array_merge(range('A', 'H'), array('K', 'M', 'N', 'P', 'R'), range('T', 'Y'));
  1661. }
  1662. // Always have an ID.
  1663. assert(isset($verificationOptions['id']));
  1664. $isNew = !isset($context['controls']['verification'][$verificationOptions['id']]);
  1665. // Log this into our collection.
  1666. if ($isNew)
  1667. $context['controls']['verification'][$verificationOptions['id']] = array(
  1668. 'id' => $verificationOptions['id'],
  1669. 'show_visual' => !empty($verificationOptions['override_visual']) || (!empty($modSettings['visual_verification_type']) && !isset($verificationOptions['override_visual'])),
  1670. 'number_questions' => isset($verificationOptions['override_qs']) ? $verificationOptions['override_qs'] : (!empty($modSettings['qa_verification_number']) ? $modSettings['qa_verification_number'] : 0),
  1671. 'max_errors' => isset($verificationOptions['max_errors']) ? $verificationOptions['max_errors'] : 3,
  1672. 'image_href' => $scripturl . '?action=verificationcode;vid=' . $verificationOptions['id'] . ';rand=' . md5(mt_rand()),
  1673. 'text_value' => '',
  1674. 'questions' => array(),
  1675. );
  1676. $thisVerification = &$context['controls']['verification'][$verificationOptions['id']];
  1677. // Add javascript for the object.
  1678. if ($context['controls']['verification'][$verificationOptions['id']]['show_visual'] && !WIRELESS)
  1679. $context['insert_after_template'] .= '
  1680. <script type="text/javascript"><!-- // --><![CDATA[
  1681. var verification' . $verificationOptions['id'] . 'Handle = new smfCaptcha("' . $thisVerification['image_href'] . '", "' . $verificationOptions['id'] . '", ' . ($context['use_graphic_library'] ? 1 : 0) . ');
  1682. // ]]></script>';
  1683. // Is there actually going to be anything?
  1684. if (empty($thisVerification['show_visual']) && empty($thisVerification['number_questions']))
  1685. return false;
  1686. elseif (!$isNew && !$do_test)
  1687. return true;
  1688. // If we want questions do we have a cache of all the IDs?
  1689. if (!empty($thisVerification['number_questions']) && empty($modSettings['question_id_cache']))
  1690. {
  1691. if (($modSettings['question_id_cache'] = cache_get_data('verificationQuestionIds', 300)) == null)
  1692. {
  1693. $request = $smcFunc['db_query']('', '
  1694. SELECT id_comment
  1695. FROM {db_prefix}log_comments
  1696. WHERE comment_type = {string:ver_test}',
  1697. array(
  1698. 'ver_test' => 'ver_test',
  1699. )
  1700. );
  1701. $modSettings['question_id_cache'] = array();
  1702. while ($row = $smcFunc['db_fetch_assoc']($request))
  1703. $modSettings['question_id_cache'][] = $row['id_comment'];
  1704. $smcFunc['db_free_result']($request);
  1705. if (!empty($modSettings['cache_enable']))
  1706. cache_put_data('verificationQuestionIds', $modSettings['question_id_cache'], 300);
  1707. }
  1708. }
  1709. if (!isset($_SESSION[$verificationOptions['id'] . '_vv']))
  1710. $_SESSION[$verificationOptions['id'] . '_vv'] = array();
  1711. // Do we need to refresh the verification?
  1712. if (!$do_test && (!empty($_SESSION[$verificationOptions['id'] . '_vv']['did_pass']) || empty($_SESSION[$verificationOptions['id'] . '_vv']['count']) || $_SESSION[$verificationOptions['id'] . '_vv']['count'] > 3) && empty($verificationOptions['dont_refresh']))
  1713. $force_refresh = true;
  1714. else
  1715. $force_refresh = false;
  1716. // This can also force a fresh, although unlikely.
  1717. if (($thisVerification['show_visual'] && empty($_SESSION[$verificationOptions['id'] . '_vv']['code'])) || ($thisVerification['number_questions'] && empty($_SESSION[$verificationOptions['id'] . '_vv']['q'])))
  1718. $force_refresh = true;
  1719. $verification_errors = array();
  1720. // Start with any testing.
  1721. if ($do_test)
  1722. {
  1723. // This cannot happen!
  1724. if (!isset($_SESSION[$verificationOptions['id'] . '_vv']['count']))
  1725. fatal_lang_error('no_access', false);
  1726. // ... nor this!
  1727. if ($thisVerification['number_questions'] && (!isset($_SESSION[$verificationOptions['id'] . '_vv']['q']) || !isset($_REQUEST[$verificationOptions['id'] . '_vv']['q'])))
  1728. fatal_lang_error('no_access', false);
  1729. if ($thisVerification['show_visual'] && (empty($_REQUEST[$verificationOptions['id'] . '_vv']['code']) || empty($_SESSION[$verificationOptions['id'] . '_vv']['code']) || strtoupper($_REQUEST[$verificationOptions['id'] . '_vv']['code']) !== $_SESSION[$verificationOptions['id'] . '_vv']['code']))
  1730. $verification_errors[] = 'wrong_verification_code';
  1731. if ($thisVerification['number_questions'])
  1732. {
  1733. // Get the answers and see if they are all right!
  1734. $request = $smcFunc['db_query']('', '
  1735. SELECT id_comment, recipient_name AS answer
  1736. FROM {db_prefix}log_comments
  1737. WHERE comment_type = {string:ver_test}
  1738. AND id_comment IN ({array_int:comment_ids})',
  1739. array(
  1740. 'ver_test' => 'ver_test',
  1741. 'comment_ids' => $_SESSION[$verificationOptions['id'] . '_vv']['q'],
  1742. )
  1743. );
  1744. $incorrectQuestions = array();
  1745. while ($row = $smcFunc['db_fetch_assoc']($request))
  1746. {
  1747. if (empty($_REQUEST[$verificationOptions['id'] . '_vv']['q'][$row['id_comment']]) || trim($smcFunc['htmlspecialchars'](strtolower($_REQUEST[$verificationOptions['id'] . '_vv']['q'][$row['id_comment']]))) != strtolower($row['answer']))
  1748. $incorrectQuestions[] = $row['id_comment'];
  1749. }
  1750. $smcFunc['db_free_result']($request);
  1751. if (!empty($incorrectQuestions))
  1752. $verification_errors[] = 'wrong_verification_answer';
  1753. }
  1754. }
  1755. // Any errors means we refresh potentially.
  1756. if (!empty($verification_errors))
  1757. {
  1758. if (empty($_SESSION[$verificationOptions['id'] . '_vv']['errors']))
  1759. $_SESSION[$verificationOptions['id'] . '_vv']['errors'] = 0;
  1760. // Too many errors?
  1761. elseif ($_SESSION[$verificationOptions['id'] . '_vv']['errors'] > $thisVerification['max_errors'])
  1762. $force_refresh = true;
  1763. // Keep a track of these.
  1764. $_SESSION[$verificationOptions['id'] . '_vv']['errors']++;
  1765. }
  1766. // Are we refreshing then?
  1767. if ($force_refresh)
  1768. {
  1769. // Assume nothing went before.
  1770. $_SESSION[$verificationOptions['id'] . '_vv']['count'] = 0;
  1771. $_SESSION[$verificationOptions['id'] . '_vv']['errors'] = 0;
  1772. $_SESSION[$verificationOptions['id'] . '_vv']['did_pass'] = false;
  1773. $_SESSION[$verificationOptions['id'] . '_vv']['q'] = array();
  1774. $_SESSION[$verificationOptions['id'] . '_vv']['code'] = '';
  1775. // Generating a new image.
  1776. if ($thisVerification['show_visual'])
  1777. {
  1778. // Are we overriding the range?
  1779. $character_range = !empty($verificationOptions['override_range']) ? $verificationOptions['override_range'] : $context['standard_captcha_range'];
  1780. for ($i = 0; $i < 6; $i++)
  1781. $_SESSION[$verificationOptions['id'] . '_vv']['code'] .= $character_range[array_rand($character_range)];
  1782. }
  1783. // Getting some new questions?
  1784. if ($thisVerification['number_questions'])
  1785. {
  1786. // Pick some random IDs
  1787. $questionIDs = array();
  1788. if ($thisVerification['number_questions'] == 1)
  1789. $questionIDs[] = $modSettings['question_id_cache'][array_rand($modSettings['question_id_cache'], $thisVerification['number_questions'])];
  1790. else
  1791. foreach (array_rand($modSettings['question_id_cache'], $thisVerification['number_questions']) as $index)
  1792. $questionIDs[] = $modSettings['question_id_cache'][$index];
  1793. }
  1794. }
  1795. else
  1796. {
  1797. // Same questions as before.
  1798. $questionIDs = !empty($_SESSION[$verificationOptions['id'] . '_vv']['q']) ? $_SESSION[$verificationOptions['id'] . '_vv']['q'] : array();
  1799. $thisVerification['text_value'] = !empty($_REQUEST[$verificationOptions['id'] . '_vv']['code']) ? $smcFunc['htmlspecialchars']($_REQUEST[$verificationOptions['id'] . '_vv']['code']) : '';
  1800. }
  1801. // Have we got some questions to load?
  1802. if (!empty($questionIDs))
  1803. {
  1804. $request = $smcFunc['db_query']('', '
  1805. SELECT id_comment, body AS question
  1806. FROM {db_prefix}log_comments
  1807. WHERE comment_type = {string:ver_test}
  1808. AND id_comment IN ({array_int:comment_ids})',
  1809. array(
  1810. 'ver_test' => 'ver_test',
  1811. 'comment_ids' => $questionIDs,
  1812. )
  1813. );
  1814. $_SESSION[$verificationOptions['id'] . '_vv']['q'] = array();
  1815. while ($row = $smcFunc['db_fetch_assoc']($request))
  1816. {
  1817. $thisVerification['questions'][] = array(
  1818. 'id' => $row['id_comment'],
  1819. 'q' => parse_bbc($row['question']),
  1820. 'is_error' => !empty($incorrectQuestions) && in_array($row['id_comment'], $incorrectQuestions),
  1821. // Remember a previous submission?
  1822. 'a' => isset($_REQUEST[$verificationOptions['id'] . '_vv'], $_REQUEST[$verificationOptions['id'] . '_vv']['q'], $_REQUEST[$verificationOptions['id'] . '_vv']['q'][$row['id_comment']]) ? $smcFunc['htmlspecialchars']($_REQUEST[$verificationOptions['id'] . '_vv']['q'][$row['id_comment']]) : '',
  1823. );
  1824. $_SESSION[$verificationOptions['id'] . '_vv']['q'][] = $row['id_comment'];
  1825. }
  1826. $smcFunc['db_free_result']($request);
  1827. }
  1828. $_SESSION[$verificationOptions['id'] . '_vv']['count'] = empty($_SESSION[$verificationOptions['id'] . '_vv']['count']) ? 1 : $_SESSION[$verificationOptions['id'] . '_vv']['count'] + 1;
  1829. // Return errors if we have them.
  1830. if (!empty($verification_errors))
  1831. return $verification_errors;
  1832. // If we had a test that one, make a note.
  1833. elseif ($do_test)
  1834. $_SESSION[$verificationOptions['id'] . '_vv']['did_pass'] = true;
  1835. // Say that everything went well chaps.
  1836. return true;
  1837. }
  1838. // This keeps track of all registered handling functions for auto suggest functionality and passes execution to them.
  1839. function AutoSuggestHandler($checkRegistered = null)
  1840. {
  1841. global $context;
  1842. // These are all registered types.
  1843. $searchTypes = array(
  1844. 'member' => 'Member',
  1845. );
  1846. // If we're just checking the callback function is registered return true or false.
  1847. if ($checkRegistered != null)
  1848. return isset($searchTypes[$checkRegistered]) && function_exists('AutoSuggest_Search_' . $checkRegistered);
  1849. checkSession('get');
  1850. loadTemplate('Xml');
  1851. // Any parameters?
  1852. $context['search_param'] = isset($_REQUEST['search_param']) ? unserialize(base64_decode($_REQUEST['search_param'])) : array();
  1853. if (isset($_REQUEST['suggest_type'], $_REQUEST['search']) && isset($searchTypes[$_REQUEST['suggest_type']]))
  1854. {
  1855. $function = 'AutoSuggest_Search_' . $searchTypes[$_REQUEST['suggest_type']];
  1856. $context['sub_template'] = 'generic_xml';
  1857. $context['xml_data'] = $function();
  1858. }
  1859. }
  1860. /**
  1861. * Search for a member - by real_name or member_name by default.
  1862. *
  1863. * @return string
  1864. */
  1865. function AutoSuggest_Search_Member()
  1866. {
  1867. global $user_info, $txt, $smcFunc, $context;
  1868. $_REQUEST['search'] = trim($smcFunc['strtolower']($_REQUEST['search'])) . '*';
  1869. $_REQUEST['search'] = strtr($_REQUEST['search'], array('%' => '\%', '_' => '\_', '*' => '%', '?' => '_', '&#038;' => '&amp;'));
  1870. // Find the member.
  1871. $request = $smcFunc['db_query']('', '
  1872. SELECT id_member, real_name
  1873. FROM {db_prefix}members
  1874. WHERE real_name LIKE {string:search}' . (!empty($context['search_param']['buddies']) ? '
  1875. AND id_member IN ({array_int:buddy_list})' : '') . '
  1876. AND is_activated IN (1, 11)
  1877. LIMIT ' . ($smcFunc['strlen']($_REQUEST['search']) <= 2 ? '100' : '800'),
  1878. array(
  1879. 'buddy_list' => $user_info['buddies'],
  1880. 'search' => $_REQUEST['search'],
  1881. )
  1882. );
  1883. $xml_data = array(
  1884. 'items' => array(
  1885. 'identifier' => 'item',
  1886. 'children' => array(),
  1887. ),
  1888. );
  1889. while ($row = $smcFunc['db_fetch_assoc']($request))
  1890. {
  1891. $row['real_name'] = strtr($row['real_name'], array('&amp;' => '&#038;', '&lt;' => '&#060;', '&gt;' => '&#062;', '&quot;' => '&#034;'));
  1892. $xml_data['items']['children'][] = array(
  1893. 'attributes' => array(
  1894. 'id' => $row['id_member'],
  1895. ),
  1896. 'value' => $row['real_name'],
  1897. );
  1898. }
  1899. $smcFunc['db_free_result']($request);
  1900. return $xml_data;
  1901. }
  1902. ?>