Subs-Editor.php 67 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189
  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.1 Alpha 1
  14. */
  15. if (!defined('SMF'))
  16. die('Hacking attempt...');
  17. /**
  18. * At the moment this is only used for returning WYSIWYG data.
  19. */
  20. function EditorMain()
  21. {
  22. global $context, $smcFunc;
  23. checkSession('get');
  24. if (!isset($_REQUEST['view']) || !isset($_REQUEST['message']))
  25. fatal_lang_error('no_access', false);
  26. $context['sub_template'] = 'sendbody';
  27. $context['view'] = (int) $_REQUEST['view'];
  28. // Return the right thing for the mode.
  29. if ($context['view'])
  30. {
  31. $_REQUEST['message'] = strtr($_REQUEST['message'], array('#smcol#' => ';', '#smlt#' => '&lt;', '#smgt#' => '&gt;', '#smamp#' => '&amp;'));
  32. $context['message'] = bbc_to_html($_REQUEST['message']);
  33. }
  34. else
  35. {
  36. $_REQUEST['message'] = un_htmlspecialchars($_REQUEST['message']);
  37. $_REQUEST['message'] = strtr($_REQUEST['message'], array('#smcol#' => ';', '#smlt#' => '&lt;', '#smgt#' => '&gt;', '#smamp#' => '&amp;'));
  38. $context['message'] = html_to_bbc($_REQUEST['message']);
  39. }
  40. $context['message'] = $smcFunc['htmlspecialchars']($context['message']);
  41. }
  42. /**
  43. * Convert only the BBC that can be edited in HTML mode for the editor.
  44. * @param string $text
  45. * @return string
  46. */
  47. function bbc_to_html($text)
  48. {
  49. global $modSettings, $smcFunc;
  50. // Turn line breaks back into br's.
  51. $text = strtr($text, array("\r" => '', "\n" => '<br />'));
  52. // Prevent conversion of all bbcode inside these bbcodes.
  53. // @todo Tie in with bbc permissions ?
  54. foreach (array('code', 'php', 'nobbc') as $code)
  55. {
  56. if (strpos($text, '['. $code) !== false)
  57. {
  58. $parts = preg_split('~(\[/' . $code . '\]|\[' . $code . '(?:=[^\]]+)?\])~i', $text, -1, PREG_SPLIT_DELIM_CAPTURE);
  59. // Only mess with stuff inside tags.
  60. for ($i = 0, $n = count($parts); $i < $n; $i++)
  61. {
  62. // Value of 2 means we're inside the tag.
  63. if ($i % 4 == 2)
  64. $parts[$i] = strtr($parts[$i], array('[' => '&#91;', ']' => '&#93;', "'" => "'"));
  65. }
  66. // Put our humpty dumpty message back together again.
  67. $text = implode('', $parts);
  68. }
  69. }
  70. // What tags do we allow?
  71. $allowed_tags = array('b', 'u', 'i', 's', 'hr', 'list', 'li', 'font', 'size', 'color', 'img', 'left', 'center', 'right', 'url', 'email', 'ftp', 'sub', 'sup');
  72. $text = parse_bbc($text, true, '', $allowed_tags);
  73. // Fix for having a line break then a thingy.
  74. $text = strtr($text, array('<br /><div' => '<div', "\n" => '', "\r" => ''));
  75. // Note that IE doesn't understand spans really - make them something "legacy"
  76. $working_html = array(
  77. '~<del>(.+?)</del>~i' => '<strike>$1</strike>',
  78. '~<span\sclass="bbc_u">(.+?)</span>~i' => '<u>$1</u>',
  79. '~<span\sstyle="color:\s*([#\d\w]+);" class="bbc_color">(.+?)</span>~i' => '<font color="$1">$2</font>',
  80. '~<span\sstyle="font-family:\s*([#\d\w\s]+);" class="bbc_font">(.+?)</span>~i' => '<font face="$1">$2</font>',
  81. '~<div\sstyle="text-align:\s*(left|right);">(.+?)</div>~i' => '<p align="$1">$2</p>',
  82. );
  83. $text = preg_replace(array_keys($working_html), array_values($working_html), $text);
  84. // Parse unique ID's and disable javascript into the smileys - using the double space.
  85. $i = 1;
  86. $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);
  87. return $text;
  88. }
  89. /**
  90. * The harder one - wysiwyg to BBC!
  91. *
  92. * @param string $text
  93. * @return string
  94. */
  95. function html_to_bbc($text)
  96. {
  97. global $modSettings, $smcFunc, $sourcedir, $scripturl, $context;
  98. // Replace newlines with spaces, as that's how browsers usually interpret them.
  99. $text = preg_replace("~\s*[\r\n]+\s*~", ' ', $text);
  100. // Though some of us love paragraphs, the parser will do better with breaks.
  101. $text = preg_replace('~</p>\s*?<p~i', '</p><br /><p', $text);
  102. $text = preg_replace('~</p>\s*(?!<)~i', '</p><br />', $text);
  103. // Safari/webkit wraps lines in Wysiwyg in <div>'s.
  104. if (isBrowser('webkit'))
  105. $text = preg_replace(array('~<div(?:\s(?:[^<>]*?))?' . '>~i', '</div>'), array('<br />', ''), $text);
  106. // If there's a trailing break get rid of it - Firefox tends to add one.
  107. $text = preg_replace('~<br\s?/?' . '>$~i', '', $text);
  108. // Remove any formatting within code tags.
  109. if (strpos($text, '[code') !== false)
  110. {
  111. $text = preg_replace('~<br\s?/?' . '>~i', '#smf_br_spec_grudge_cool!#', $text);
  112. $parts = preg_split('~(\[/code\]|\[code(?:=[^\]]+)?\])~i', $text, -1, PREG_SPLIT_DELIM_CAPTURE);
  113. // Only mess with stuff outside [code] tags.
  114. for ($i = 0, $n = count($parts); $i < $n; $i++)
  115. {
  116. // Value of 2 means we're inside the tag.
  117. if ($i % 4 == 2)
  118. $parts[$i] = strip_tags($parts[$i]);
  119. }
  120. $text = strtr(implode('', $parts), array('#smf_br_spec_grudge_cool!#' => '<br />'));
  121. }
  122. // Remove scripts, style and comment blocks.
  123. $text = preg_replace('~<script[^>]*[^/]?' . '>.*?</script>~i', '', $text);
  124. $text = preg_replace('~<style[^>]*[^/]?' . '>.*?</style>~i', '', $text);
  125. $text = preg_replace('~\\<\\!--.*?-->~i', '', $text);
  126. $text = preg_replace('~\\<\\!\\[CDATA\\[.*?\\]\\]\\>~i', '', $text);
  127. // Do the smileys ultra first!
  128. preg_match_all('~<img\s+[^<>]*?id="*smiley_\d+_([^<>]+?)[\s"/>]\s*[^<>]*?/*>(?:\s)?~i', $text, $matches);
  129. if (!empty($matches[0]))
  130. {
  131. // Easy if it's not custom.
  132. if (empty($modSettings['smiley_enable']))
  133. {
  134. $smileysfrom = array('>:D', ':D', '::)', '>:(', ':)', ';)', ';D', ':(', ':o', '8)', ':P', '???', ':-[', ':-X', ':-*', ':\'(', ':-\\', '^-^', 'O0', 'C:-)', '0:)');
  135. $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');
  136. foreach ($matches[1] as $k => $file)
  137. {
  138. $found = array_search($file, $smileysto);
  139. // Note the weirdness here is to stop double spaces between smileys.
  140. if ($found)
  141. $matches[1][$k] = '-[]-smf_smily_start#|#' . htmlspecialchars($smileysfrom[$found]) . '-[]-smf_smily_end#|#';
  142. else
  143. $matches[1][$k] = '';
  144. }
  145. }
  146. else
  147. {
  148. // Load all the smileys.
  149. $names = array();
  150. foreach ($matches[1] as $file)
  151. $names[] = $file;
  152. $names = array_unique($names);
  153. if (!empty($names))
  154. {
  155. $request = $smcFunc['db_query']('', '
  156. SELECT code, filename
  157. FROM {db_prefix}smileys
  158. WHERE filename IN ({array_string:smiley_filenames})',
  159. array(
  160. 'smiley_filenames' => $names,
  161. )
  162. );
  163. $mappings = array();
  164. while ($row = $smcFunc['db_fetch_assoc']($request))
  165. $mappings[$row['filename']] = htmlspecialchars($row['code']);
  166. $smcFunc['db_free_result']($request);
  167. foreach ($matches[1] as $k => $file)
  168. if (isset($mappings[$file]))
  169. $matches[1][$k] = '-[]-smf_smily_start#|#' . $mappings[$file] . '-[]-smf_smily_end#|#';
  170. }
  171. }
  172. // Replace the tags!
  173. $text = str_replace($matches[0], $matches[1], $text);
  174. // Now sort out spaces
  175. $text = str_replace(array('-[]-smf_smily_end#|#-[]-smf_smily_start#|#', '-[]-smf_smily_end#|#', '-[]-smf_smily_start#|#'), ' ', $text);
  176. }
  177. // Only try to buy more time if the client didn't quit.
  178. if (connection_aborted() && $context['server']['is_apache'])
  179. @apache_reset_timeout();
  180. $parts = preg_split('~(<[A-Za-z]+\s*[^<>]*?style="?[^<>"]+"?[^<>]*?(?:/?)>|</[A-Za-z]+>)~', $text, -1, PREG_SPLIT_DELIM_CAPTURE);
  181. $replacement = '';
  182. $stack = array();
  183. foreach ($parts as $part)
  184. {
  185. if (preg_match('~(<([A-Za-z]+)\s*[^<>]*?)style="?([^<>"]+)"?([^<>]*?(/?)>)~', $part, $matches) === 1)
  186. {
  187. // If it's being closed instantly, we can't deal with it...yet.
  188. if ($matches[5] === '/')
  189. continue;
  190. else
  191. {
  192. // Get an array of styles that apply to this element. (The strtr is there to combat HTML generated by Word.)
  193. $styles = explode(';', strtr($matches[3], array('&quot;' => '')));
  194. $curElement = $matches[2];
  195. $precedingStyle = $matches[1];
  196. $afterStyle = $matches[4];
  197. $curCloseTags = '';
  198. $extra_attr = '';
  199. foreach ($styles as $type_value_pair)
  200. {
  201. // Remove spaces and convert uppercase letters.
  202. $clean_type_value_pair = strtolower(strtr(trim($type_value_pair), '=', ':'));
  203. // Something like 'font-weight: bold' is expected here.
  204. if (strpos($clean_type_value_pair, ':') === false)
  205. continue;
  206. // Capture the elements of a single style item (e.g. 'font-weight' and 'bold').
  207. list ($style_type, $style_value) = explode(':', $type_value_pair);
  208. $style_value = trim($style_value);
  209. switch (trim($style_type))
  210. {
  211. case 'font-weight':
  212. if ($style_value === 'bold')
  213. {
  214. $curCloseTags .= '[/b]';
  215. $replacement .= '[b]';
  216. }
  217. break;
  218. case 'text-decoration':
  219. if ($style_value == 'underline')
  220. {
  221. $curCloseTags .= '[/u]';
  222. $replacement .= '[u]';
  223. }
  224. elseif ($style_value == 'line-through')
  225. {
  226. $curCloseTags .= '[/s]';
  227. $replacement .= '[s]';
  228. }
  229. break;
  230. case 'text-align':
  231. if ($style_value == 'left')
  232. {
  233. $curCloseTags .= '[/left]';
  234. $replacement .= '[left]';
  235. }
  236. elseif ($style_value == 'center')
  237. {
  238. $curCloseTags .= '[/center]';
  239. $replacement .= '[center]';
  240. }
  241. elseif ($style_value == 'right')
  242. {
  243. $curCloseTags .= '[/right]';
  244. $replacement .= '[right]';
  245. }
  246. break;
  247. case 'font-style':
  248. if ($style_value == 'italic')
  249. {
  250. $curCloseTags .= '[/i]';
  251. $replacement .= '[i]';
  252. }
  253. break;
  254. case 'color':
  255. $curCloseTags .= '[/color]';
  256. $replacement .= '[color=' . $style_value . ']';
  257. break;
  258. case 'font-size':
  259. // Sometimes people put decimals where decimals should not be.
  260. if (preg_match('~(\d)+\.\d+(p[xt])~i', $style_value, $dec_matches) === 1)
  261. $style_value = $dec_matches[1] . $dec_matches[2];
  262. $curCloseTags .= '[/size]';
  263. $replacement .= '[size=' . $style_value . ']';
  264. break;
  265. case 'font-family':
  266. // Only get the first freaking font if there's a list!
  267. if (strpos($style_value, ',') !== false)
  268. $style_value = substr($style_value, 0, strpos($style_value, ','));
  269. $curCloseTags .= '[/font]';
  270. $replacement .= '[font=' . strtr($style_value, array("'" => '')) . ']';
  271. break;
  272. // This is a hack for images with dimensions embedded.
  273. case 'width':
  274. case 'height':
  275. if (preg_match('~[1-9]\d*~i', $style_value, $dimension) === 1)
  276. $extra_attr .= ' ' . $style_type . '="' . $dimension[0] . '"';
  277. break;
  278. case 'list-style-type':
  279. 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)
  280. $extra_attr .= ' listtype="' . $listType[0] . '"';
  281. break;
  282. }
  283. }
  284. // Preserve some tags stripping the styling.
  285. if (in_array($matches[2], array('a', 'font')))
  286. {
  287. $replacement .= $precedingStyle . $afterStyle;
  288. $curCloseTags = '</' . $matches[2] . '>' . $curCloseTags;
  289. }
  290. // If there's something that still needs closing, push it to the stack.
  291. if (!empty($curCloseTags))
  292. array_push($stack, array(
  293. 'element' => strtolower($curElement),
  294. 'closeTags' => $curCloseTags
  295. )
  296. );
  297. elseif (!empty($extra_attr))
  298. $replacement .= $precedingStyle . $extra_attr . $afterStyle;
  299. }
  300. }
  301. elseif (preg_match('~</([A-Za-z]+)>~', $part, $matches) === 1)
  302. {
  303. // Is this the element that we've been waiting for to be closed?
  304. if (!empty($stack) && strtolower($matches[1]) === $stack[count($stack) - 1]['element'])
  305. {
  306. $byebyeTag = array_pop($stack);
  307. $replacement .= $byebyeTag['closeTags'];
  308. }
  309. // Must've been something else.
  310. else
  311. $replacement .= $part;
  312. }
  313. // In all other cases, just add the part to the replacement.
  314. else
  315. $replacement .= $part;
  316. }
  317. // Now put back the replacement in the text.
  318. $text = $replacement;
  319. // We are not finished yet, request more time.
  320. if (connection_aborted() && $context['server']['is_apache'])
  321. @apache_reset_timeout();
  322. // Let's pull out any legacy alignments.
  323. while (preg_match('~<([A-Za-z]+)\s+[^<>]*?(align="*(left|center|right)"*)[^<>]*?(/?)>~i', $text, $matches) === 1)
  324. {
  325. // Find the position in the text of this tag over again.
  326. $start_pos = strpos($text, $matches[0]);
  327. if ($start_pos === false)
  328. break;
  329. // End tag?
  330. if ($matches[4] != '/' && strpos($text, '</' . $matches[1] . '>', $start_pos) !== false)
  331. {
  332. $end_length = strlen('</' . $matches[1] . '>');
  333. $end_pos = strpos($text, '</' . $matches[1] . '>', $start_pos);
  334. // Remove the align from that tag so it's never checked again.
  335. $tag = substr($text, $start_pos, strlen($matches[0]));
  336. $content = substr($text, $start_pos + strlen($matches[0]), $end_pos - $start_pos - strlen($matches[0]));
  337. $tag = str_replace($matches[2], '', $tag);
  338. // Put the tags back into the body.
  339. $text = substr($text, 0, $start_pos) . $tag . '[' . $matches[3] . ']' . $content . '[/' . $matches[3] . ']' . substr($text, $end_pos);
  340. }
  341. else
  342. {
  343. // Just get rid of this evil tag.
  344. $text = substr($text, 0, $start_pos) . substr($text, $start_pos + strlen($matches[0]));
  345. }
  346. }
  347. // Let's do some special stuff for fonts - cause we all love fonts.
  348. while (preg_match('~<font\s+([^<>]*)>~i', $text, $matches) === 1)
  349. {
  350. // Find the position of this again.
  351. $start_pos = strpos($text, $matches[0]);
  352. $end_pos = false;
  353. if ($start_pos === false)
  354. break;
  355. // This must have an end tag - and we must find the right one.
  356. $lower_text = strtolower($text);
  357. $start_pos_test = $start_pos + 4;
  358. // How many starting tags must we find closing ones for first?
  359. $start_font_tag_stack = 0;
  360. while ($start_pos_test < strlen($text))
  361. {
  362. // Where is the next starting font?
  363. $next_start_pos = strpos($lower_text, '<font', $start_pos_test);
  364. $next_end_pos = strpos($lower_text, '</font>', $start_pos_test);
  365. // Did we past another starting tag before an end one?
  366. if ($next_start_pos !== false && $next_start_pos < $next_end_pos)
  367. {
  368. $start_font_tag_stack++;
  369. $start_pos_test = $next_start_pos + 4;
  370. }
  371. // Otherwise we have an end tag but not the right one?
  372. elseif ($start_font_tag_stack)
  373. {
  374. $start_font_tag_stack--;
  375. $start_pos_test = $next_end_pos + 4;
  376. }
  377. // Otherwise we're there!
  378. else
  379. {
  380. $end_pos = $next_end_pos;
  381. break;
  382. }
  383. }
  384. if ($end_pos === false)
  385. break;
  386. // Now work out what the attributes are.
  387. $attribs = fetchTagAttributes($matches[1]);
  388. $tags = array();
  389. foreach ($attribs as $s => $v)
  390. {
  391. if ($s == 'size')
  392. $tags[] = array('[size=' . (int) trim($v) . ']', '[/size]');
  393. elseif ($s == 'face')
  394. $tags[] = array('[font=' . trim(strtolower($v)) . ']', '[/font]');
  395. elseif ($s == 'color')
  396. $tags[] = array('[color=' . trim(strtolower($v)) . ']', '[/color]');
  397. }
  398. // As before add in our tags.
  399. $before = $after = '';
  400. foreach ($tags as $tag)
  401. {
  402. $before .= $tag[0];
  403. if (isset($tag[1]))
  404. $after = $tag[1] . $after;
  405. }
  406. // Remove the tag so it's never checked again.
  407. $content = substr($text, $start_pos + strlen($matches[0]), $end_pos - $start_pos - strlen($matches[0]));
  408. // Put the tags back into the body.
  409. $text = substr($text, 0, $start_pos) . $before . $content . $after . substr($text, $end_pos + 7);
  410. }
  411. // Almost there, just a little more time.
  412. if (connection_aborted() && $context['server']['is_apache'])
  413. @apache_reset_timeout();
  414. if (count($parts = preg_split('~<(/?)(li|ol|ul)([^>]*)>~i', $text, null, PREG_SPLIT_DELIM_CAPTURE)) > 1)
  415. {
  416. // A toggle that dermines whether we're directly under a <ol> or <ul>.
  417. $inList = false;
  418. // Keep track of the number of nested list levels.
  419. $listDepth = 0;
  420. // Map what we can expect from the HTML to what is supported by SMF.
  421. $listTypeMapping = array(
  422. '1' => 'decimal',
  423. 'A' => 'upper-alpha',
  424. 'a' => 'lower-alpha',
  425. 'I' => 'upper-roman',
  426. 'i' => 'lower-roman',
  427. 'disc' => 'disc',
  428. 'square' => 'square',
  429. 'circle' => 'circle',
  430. );
  431. // $i: text, $i + 1: '/', $i + 2: tag, $i + 3: tail.
  432. for ($i = 0, $numParts = count($parts) - 1; $i < $numParts; $i += 4)
  433. {
  434. $tag = strtolower($parts[$i + 2]);
  435. $isOpeningTag = $parts[$i + 1] === '';
  436. if ($isOpeningTag)
  437. {
  438. switch ($tag)
  439. {
  440. case 'ol':
  441. case 'ul':
  442. // We have a problem, we're already in a list.
  443. if ($inList)
  444. {
  445. // Inject a list opener, we'll deal with the ol/ul next loop.
  446. array_splice($parts, $i, 0, array(
  447. '',
  448. '',
  449. str_repeat("\t", $listDepth) . '[li]',
  450. '',
  451. ));
  452. $numParts = count($parts) - 1;
  453. // The inlist status changes a bit.
  454. $inList = false;
  455. }
  456. // Just starting a new list.
  457. else
  458. {
  459. $inList = true;
  460. if ($tag === 'ol')
  461. $listType = 'decimal';
  462. elseif (preg_match('~type="?(' . implode('|', array_keys($listTypeMapping)) . ')"?~', $parts[$i + 3], $match) === 1)
  463. $listType = $listTypeMapping[$match[1]];
  464. else
  465. $listType = null;
  466. $listDepth++;
  467. $parts[$i + 2] = '[list' . ($listType === null ? '' : ' type=' . $listType) . ']' . "\n";
  468. $parts[$i + 3] = '';
  469. }
  470. break;
  471. case 'li':
  472. // This is how it should be: a list item inside the list.
  473. if ($inList)
  474. {
  475. $parts[$i + 2] = str_repeat("\t", $listDepth) . '[li]';
  476. $parts[$i + 3] = '';
  477. // Within a list item, it's almost as if you're outside.
  478. $inList = false;
  479. }
  480. // The li is no direct child of a list.
  481. else
  482. {
  483. // We are apparently in a list item.
  484. if ($listDepth > 0)
  485. {
  486. $parts[$i + 2] = '[/li]' . "\n" . str_repeat("\t", $listDepth) . '[li]';
  487. $parts[$i + 3] = '';
  488. }
  489. // We're not even near a list.
  490. else
  491. {
  492. // Quickly create a list with an item.
  493. $listDepth++;
  494. $parts[$i + 2] = '[list]' . "\n\t" . '[li]';
  495. $parts[$i + 3] = '';
  496. }
  497. }
  498. break;
  499. }
  500. }
  501. // Handle all the closing tags.
  502. else
  503. {
  504. switch ($tag)
  505. {
  506. case 'ol':
  507. case 'ul':
  508. // As we expected it, closing the list while we're in it.
  509. if ($inList)
  510. {
  511. $inList = false;
  512. $listDepth--;
  513. $parts[$i + 1] = '';
  514. $parts[$i + 2] = str_repeat("\t", $listDepth) . '[/list]';
  515. $parts[$i + 3] = '';
  516. }
  517. else
  518. {
  519. // We're in a list item.
  520. if ($listDepth > 0)
  521. {
  522. // Inject closure for this list item first.
  523. // The content of $parts[$i] is left as is!
  524. array_splice($parts, $i + 1, 0, array(
  525. '', // $i + 1
  526. '[/li]' . "\n", // $i + 2
  527. '', // $i + 3
  528. '', // $i + 4
  529. ));
  530. $numParts = count($parts) - 1;
  531. // Now that we've closed the li, we're in list space.
  532. $inList = true;
  533. }
  534. // We're not even in a list, ignore
  535. else
  536. {
  537. $parts[$i + 1] = '';
  538. $parts[$i + 2] = '';
  539. $parts[$i + 3] = '';
  540. }
  541. }
  542. break;
  543. case 'li':
  544. if ($inList)
  545. {
  546. // There's no use for a </li> after <ol> or <ul>, ignore.
  547. $parts[$i + 1] = '';
  548. $parts[$i + 2] = '';
  549. $parts[$i + 3] = '';
  550. }
  551. else
  552. {
  553. // Remove the trailing breaks from the list item.
  554. $parts[$i] = preg_replace('~\s*<br\s*' . '/?' . '>\s*$~', '', $parts[$i]);
  555. $parts[$i + 1] = '';
  556. $parts[$i + 2] = '[/li]' . "\n";
  557. $parts[$i + 3] = '';
  558. // And we're back in the [list] space.
  559. $inList = true;
  560. }
  561. break;
  562. }
  563. }
  564. // If we're in the [list] space, no content is allowed.
  565. if ($inList && trim(preg_replace('~\s*<br\s*' . '/?' . '>\s*~', '', $parts[$i + 4])) !== '')
  566. {
  567. // Fix it by injecting an extra list item.
  568. array_splice($parts, $i + 4, 0, array(
  569. '', // No content.
  570. '', // Opening tag.
  571. 'li', // It's a <li>.
  572. '', // No tail.
  573. ));
  574. $numParts = count($parts) - 1;
  575. }
  576. }
  577. $text = implode('', $parts);
  578. if ($inList)
  579. {
  580. $listDepth--;
  581. $text .= str_repeat("\t", $listDepth) . '[/list]';
  582. }
  583. for ($i = $listDepth; $i > 0; $i--)
  584. $text .= '[/li]' . "\n" . str_repeat("\t", $i - 1) . '[/list]';
  585. }
  586. // I love my own image...
  587. while (preg_match('~<img\s+([^<>]*)/*>~i', $text, $matches) === 1)
  588. {
  589. // Find the position of the image.
  590. $start_pos = strpos($text, $matches[0]);
  591. if ($start_pos === false)
  592. break;
  593. $end_pos = $start_pos + strlen($matches[0]);
  594. $params = '';
  595. $had_params = array();
  596. $src = '';
  597. $attrs = fetchTagAttributes($matches[1]);
  598. foreach ($attrs as $attrib => $value)
  599. {
  600. if (in_array($attrib, array('width', 'height')))
  601. $params .= ' ' . $attrib . '=' . (int) $value;
  602. elseif ($attrib == 'alt' && trim($value) != '')
  603. $params .= ' alt=' . trim($value);
  604. elseif ($attrib == 'src')
  605. $src = trim($value);
  606. }
  607. $tag = '';
  608. if (!empty($src))
  609. {
  610. // Attempt to fix the path in case it's not present.
  611. if (preg_match('~^https?://~i', $src) === 0 && is_array($parsedURL = parse_url($scripturl)) && isset($parsedURL['host']))
  612. {
  613. $baseURL = (isset($parsedURL['scheme']) ? $parsedURL['scheme'] : 'http') . '://' . $parsedURL['host'] . (empty($parsedURL['port']) ? '' : ':' . $parsedURL['port']);
  614. if (substr($src, 0, 1) === '/')
  615. $src = $baseURL . $src;
  616. else
  617. $src = $baseURL . (empty($parsedURL['path']) ? '/' : preg_replace('~/(?:index\\.php)?$~', '', $parsedURL['path'])) . '/' . $src;
  618. }
  619. $tag = '[img' . $params . ']' . $src . '[/img]';
  620. }
  621. // Replace the tag
  622. $text = substr($text, 0, $start_pos) . $tag . substr($text, $end_pos);
  623. }
  624. // The final bits are the easy ones - tags which map to tags which map to tags - etc etc.
  625. $tags = array(
  626. '~<b(\s(.)*?)*?' . '>~i' => '[b]',
  627. '~</b>~i' => '[/b]',
  628. '~<i(\s(.)*?)*?' . '>~i' => '[i]',
  629. '~</i>~i' => '[/i]',
  630. '~<u(\s(.)*?)*?' . '>~i' => '[u]',
  631. '~</u>~i' => '[/u]',
  632. '~<strong(\s(.)*?)*?' . '>~i' => '[b]',
  633. '~</strong>~i' => '[/b]',
  634. '~<em(\s(.)*?)*?' . '>~i' => '[i]',
  635. '~</em>~i' => '[/i]',
  636. '~<s(\s(.)*?)*?' . '>~i' => "[s]",
  637. '~</s>~i' => "[/s]",
  638. '~<strike(\s(.)*?)*?' . '>~i' => '[s]',
  639. '~</strike>~i' => '[/s]',
  640. '~<del(\s(.)*?)*?' . '>~i' => '[s]',
  641. '~</del>~i' => '[/s]',
  642. '~<center(\s(.)*?)*?' . '>~i' => '[center]',
  643. '~</center>~i' => '[/center]',
  644. '~<pre(\s(.)*?)*?' . '>~i' => '[pre]',
  645. '~</pre>~i' => '[/pre]',
  646. '~<sub(\s(.)*?)*?' . '>~i' => '[sub]',
  647. '~</sub>~i' => '[/sub]',
  648. '~<sup(\s(.)*?)*?' . '>~i' => '[sup]',
  649. '~</sup>~i' => '[/sup]',
  650. '~<tt(\s(.)*?)*?' . '>~i' => '[tt]',
  651. '~</tt>~i' => '[/tt]',
  652. '~<table(\s(.)*?)*?' . '>~i' => '[table]',
  653. '~</table>~i' => '[/table]',
  654. '~<tr(\s(.)*?)*?' . '>~i' => '[tr]',
  655. '~</tr>~i' => '[/tr]',
  656. '~<(td|th)\s[^<>]*?colspan="?(\d{1,2})"?.*?' . '>~ie' => 'str_repeat(\'[td][/td]\', $2 - 1) . \'[td]\'',
  657. '~<(td|th)(\s(.)*?)*?' . '>~i' => '[td]',
  658. '~</(td|th)>~i' => '[/td]',
  659. '~<br(?:\s[^<>]*?)?' . '>~i' => "\n",
  660. '~<hr[^<>]*>(\n)?~i' => "[hr]\n$1",
  661. '~(\n)?\\[hr\\]~i' => "\n[hr]",
  662. '~^\n\\[hr\\]~i' => "[hr]",
  663. '~<blockquote(\s(.)*?)*?' . '>~i' => "&lt;blockquote&gt;",
  664. '~</blockquote>~i' => "&lt;/blockquote&gt;",
  665. '~<ins(\s(.)*?)*?' . '>~i' => "&lt;ins&gt;",
  666. '~</ins>~i' => "&lt;/ins&gt;",
  667. );
  668. $text = preg_replace(array_keys($tags), array_values($tags), $text);
  669. // Please give us just a little more time.
  670. if (connection_aborted() && $context['server']['is_apache'])
  671. @apache_reset_timeout();
  672. // What about URL's - the pain in the ass of the tag world.
  673. while (preg_match('~<a\s+([^<>]*)>([^<>]*)</a>~i', $text, $matches) === 1)
  674. {
  675. // Find the position of the URL.
  676. $start_pos = strpos($text, $matches[0]);
  677. if ($start_pos === false)
  678. break;
  679. $end_pos = $start_pos + strlen($matches[0]);
  680. $tag_type = 'url';
  681. $href = '';
  682. $attrs = fetchTagAttributes($matches[1]);
  683. foreach ($attrs as $attrib => $value)
  684. {
  685. if ($attrib == 'href')
  686. {
  687. $href = trim($value);
  688. // Are we dealing with an FTP link?
  689. if (preg_match('~^ftps?://~', $href) === 1)
  690. $tag_type = 'ftp';
  691. // Or is this a link to an email address?
  692. elseif (strpos($href, 'mailto:') === 0)
  693. {
  694. $tag_type = 'email';
  695. $href = substr($href, 7);
  696. }
  697. // No http(s), so attempt to fix this potential relative URL.
  698. elseif (preg_match('~^https?://~i', $href) === 0 && is_array($parsedURL = parse_url($scripturl)) && isset($parsedURL['host']))
  699. {
  700. $baseURL = (isset($parsedURL['scheme']) ? $parsedURL['scheme'] : 'http') . '://' . $parsedURL['host'] . (empty($parsedURL['port']) ? '' : ':' . $parsedURL['port']);
  701. if (substr($href, 0, 1) === '/')
  702. $href = $baseURL . $href;
  703. else
  704. $href = $baseURL . (empty($parsedURL['path']) ? '/' : preg_replace('~/(?:index\\.php)?$~', '', $parsedURL['path'])) . '/' . $href;
  705. }
  706. }
  707. // External URL?
  708. if ($attrib == 'target' && $tag_type == 'url')
  709. {
  710. if (trim($value) == '_blank')
  711. $tag_type == 'iurl';
  712. }
  713. }
  714. $tag = '';
  715. if ($href != '')
  716. {
  717. if ($matches[2] == $href)
  718. $tag = '[' . $tag_type . ']' . $href . '[/' . $tag_type . ']';
  719. else
  720. $tag = '[' . $tag_type . '=' . $href . ']' . $matches[2] . '[/' . $tag_type . ']';
  721. }
  722. // Replace the tag
  723. $text = substr($text, 0, $start_pos) . $tag . substr($text, $end_pos);
  724. }
  725. $text = strip_tags($text);
  726. // Some tags often end up as just dummy tags - remove those.
  727. $text = preg_replace('~\[[bisu]\]\s*\[/[bisu]\]~', '', $text);
  728. // Fix up entities.
  729. $text = preg_replace('~&#38;~i', '&#38;#38;', $text);
  730. $text = legalise_bbc($text);
  731. return $text;
  732. }
  733. /**
  734. * Returns an array of attributes associated with a tag.
  735. *
  736. * @param string $text
  737. * @return string
  738. */
  739. function fetchTagAttributes($text)
  740. {
  741. $attribs = array();
  742. $key = $value = '';
  743. $strpos = 0;
  744. $tag_state = 0; // 0 = key, 1 = attribute with no string, 2 = attribute with string
  745. for ($i = 0; $i < strlen($text); $i++)
  746. {
  747. // We're either moving from the key to the attribute or we're in a string and this is fine.
  748. if ($text[$i] == '=')
  749. {
  750. if ($tag_state == 0)
  751. $tag_state = 1;
  752. elseif ($tag_state == 2)
  753. $value .= '=';
  754. }
  755. // A space is either moving from an attribute back to a potential key or in a string is fine.
  756. elseif ($text[$i] == ' ')
  757. {
  758. if ($tag_state == 2)
  759. $value .= ' ';
  760. elseif ($tag_state == 1)
  761. {
  762. $attribs[$key] = $value;
  763. $key = $value = '';
  764. $tag_state = 0;
  765. }
  766. }
  767. // A quote?
  768. elseif ($text[$i] == '"')
  769. {
  770. // Must be either going into or out of a string.
  771. if ($tag_state == 1)
  772. $tag_state = 2;
  773. else
  774. $tag_state = 1;
  775. }
  776. // Otherwise it's fine.
  777. else
  778. {
  779. if ($tag_state == 0)
  780. $key .= $text[$i];
  781. else
  782. $value .= $text[$i];
  783. }
  784. }
  785. // Anything left?
  786. if ($key != '' && $value != '')
  787. $attribs[$key] = $value;
  788. return $attribs;
  789. }
  790. /**
  791. * Retrieves a list of message icons.
  792. * Based on the settings, the array will either contain a list of default
  793. * message icons or a list of custom message icons retrieved from the database.
  794. * The board_id is needed for the custom message icons (which can be set for
  795. * each board individually).
  796. *
  797. * @param int $board_id
  798. * @return array
  799. */
  800. function getMessageIcons($board_id)
  801. {
  802. global $modSettings, $context, $txt, $settings, $smcFunc;
  803. if (empty($modSettings['messageIcons_enable']))
  804. {
  805. loadLanguage('Post');
  806. $icons = array(
  807. array('value' => 'xx', 'name' => $txt['standard']),
  808. array('value' => 'thumbup', 'name' => $txt['thumbs_up']),
  809. array('value' => 'thumbdown', 'name' => $txt['thumbs_down']),
  810. array('value' => 'exclamation', 'name' => $txt['excamation_point']),
  811. array('value' => 'question', 'name' => $txt['question_mark']),
  812. array('value' => 'lamp', 'name' => $txt['lamp']),
  813. array('value' => 'smiley', 'name' => $txt['icon_smiley']),
  814. array('value' => 'angry', 'name' => $txt['icon_angry']),
  815. array('value' => 'cheesy', 'name' => $txt['icon_cheesy']),
  816. array('value' => 'grin', 'name' => $txt['icon_grin']),
  817. array('value' => 'sad', 'name' => $txt['icon_sad']),
  818. array('value' => 'wink', 'name' => $txt['icon_wink'])
  819. );
  820. foreach ($icons as $k => $dummy)
  821. {
  822. $icons[$k]['url'] = $settings['images_url'] . '/post/' . $dummy['value'] . '.gif';
  823. $icons[$k]['is_last'] = false;
  824. }
  825. }
  826. // Otherwise load the icons, and check we give the right image too...
  827. else
  828. {
  829. if (($temp = cache_get_data('posting_icons-' . $board_id, 480)) === null)
  830. {
  831. $request = $smcFunc['db_query']('select_message_icons', '
  832. SELECT title, filename
  833. FROM {db_prefix}message_icons
  834. WHERE id_board IN (0, {int:board_id})',
  835. array(
  836. 'board_id' => $board_id,
  837. )
  838. );
  839. $icon_data = array();
  840. while ($row = $smcFunc['db_fetch_assoc']($request))
  841. $icon_data[] = $row;
  842. $smcFunc['db_free_result']($request);
  843. cache_put_data('posting_icons-' . $board_id, $icon_data, 480);
  844. }
  845. else
  846. $icon_data = $temp;
  847. $icons = array();
  848. foreach ($icon_data as $icon)
  849. {
  850. $icons[$icon['filename']] = array(
  851. 'value' => $icon['filename'],
  852. 'name' => $icon['title'],
  853. 'url' => $settings[file_exists($settings['theme_dir'] . '/images/post/' . $icon['filename'] . '.gif') ? 'images_url' : 'default_images_url'] . '/post/' . $icon['filename'] . '.gif',
  854. 'is_last' => false,
  855. );
  856. }
  857. }
  858. return array_values($icons);
  859. }
  860. /**
  861. * Attempt to clean up illegal BBC caused by browsers like Opera which don't obey the rules
  862. * @param string $text
  863. * @return string
  864. */
  865. function legalise_bbc($text)
  866. {
  867. global $modSettings;
  868. // Don't care about the texts that are too short.
  869. if (strlen($text) < 3)
  870. return $text;
  871. // 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!
  872. // This will keep the order of tags that are open.
  873. $current_tags = array();
  874. // This will quickly let us see if the tag is active.
  875. $active_tags = array();
  876. // A list of tags that's disabled by the admin.
  877. $disabled = empty($modSettings['disabledBBC']) ? array() : array_flip(explode(',', strtolower($modSettings['disabledBBC'])));
  878. // Add flash if it's disabled as embedded tag.
  879. if (empty($modSettings['enableEmbeddedFlash']))
  880. $disabled['flash'] = true;
  881. // Get a list of all the tags that are not disabled.
  882. $all_tags = parse_bbc(false);
  883. $valid_tags = array();
  884. $self_closing_tags = array();
  885. foreach ($all_tags as $tag)
  886. {
  887. if (!isset($disabled[$tag['tag']]))
  888. $valid_tags[$tag['tag']] = !empty($tag['block_level']);
  889. if (isset($tag['type']) && $tag['type'] == 'closed')
  890. $self_closing_tags[] = $tag['tag'];
  891. }
  892. // Don't worry if we're in a code/nobbc.
  893. $in_code_nobbc = false;
  894. // 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!
  895. $align_tags = array('left', 'center', 'right', 'pre');
  896. // Remove those align tags that are not valid.
  897. $align_tags = array_intersect($align_tags, array_keys($valid_tags));
  898. // These keep track of where we are!
  899. if (!empty($align_tags) && count($matches = preg_split('~(\\[/?(?:' . implode('|', $align_tags) . ')\\])~', $text, -1, PREG_SPLIT_DELIM_CAPTURE)) > 1)
  900. {
  901. // The first one is never a tag.
  902. $isTag = false;
  903. // By default we're not inside a tag too.
  904. $insideTag = null;
  905. foreach ($matches as $i => $match)
  906. {
  907. // We're only interested in tags, not text.
  908. if ($isTag)
  909. {
  910. $isClosingTag = substr($match, 1, 1) === '/';
  911. $tagName = substr($match, $isClosingTag ? 2 : 1, -1);
  912. // We're closing the exact same tag that we opened.
  913. if ($isClosingTag && $insideTag === $tagName)
  914. $insideTag = null;
  915. // We're opening a tag and we're not yet inside one either
  916. elseif (!$isClosingTag && $insideTag === null)
  917. $insideTag = $tagName;
  918. // In all other cases, this tag must be invalid
  919. else
  920. unset($matches[$i]);
  921. }
  922. // The next one is gonna be the other one.
  923. $isTag = !$isTag;
  924. }
  925. // We're still inside a tag and had no chance for closure?
  926. if ($insideTag !== null)
  927. $matches[] = '[/' . $insideTag . ']';
  928. // And a complete text string again.
  929. $text = implode('', $matches);
  930. }
  931. // Quickly remove any tags which are back to back.
  932. $backToBackPattern = '~\\[(' . implode('|', array_diff(array_keys($valid_tags), array('td', 'anchor'))) . ')[^<>\\[\\]]*\\]\s*\\[/\\1\\]~';
  933. $lastlen = 0;
  934. while (strlen($text) !== $lastlen)
  935. $lastlen = strlen($text = preg_replace($backToBackPattern, '', $text));
  936. // Need to sort the tags my name length.
  937. uksort($valid_tags, 'sort_array_length');
  938. // These inline tags can compete with each other regarding style.
  939. $competing_tags = array(
  940. 'color',
  941. 'size',
  942. );
  943. // In case things changed above set these back to normal.
  944. $in_code_nobbc = false;
  945. $new_text_offset = 0;
  946. // These keep track of where we are!
  947. if (count($parts = preg_split(sprintf('~(\\[)(/?)(%1$s)((?:[\\s=][^\\]\\[]*)?\\])~', implode('|', array_keys($valid_tags))), $text, -1, PREG_SPLIT_DELIM_CAPTURE)) > 1)
  948. {
  949. // Start with just text.
  950. $isTag = false;
  951. // Start outside [nobbc] or [code] blocks.
  952. $inCode = false;
  953. $inNoBbc = false;
  954. // A buffer containing all opened inline elements.
  955. $inlineElements = array();
  956. // A buffer containing all opened block elements.
  957. $blockElements = array();
  958. // A buffer containing the opened inline elements that might compete.
  959. $competingElements = array();
  960. // $i: text, $i + 1: '[', $i + 2: '/', $i + 3: tag, $i + 4: tag tail.
  961. for ($i = 0, $n = count($parts) - 1; $i < $n; $i += 5)
  962. {
  963. $tag = $parts[$i + 3];
  964. $isOpeningTag = $parts[$i + 2] === '';
  965. $isClosingTag = $parts[$i + 2] === '/';
  966. $isBlockLevelTag = isset($valid_tags[$tag]) && $valid_tags[$tag] && !in_array($tag, $self_closing_tags);
  967. $isCompetingTag = in_array($tag, $competing_tags);
  968. // Check if this might be one of those cleaned out tags.
  969. if ($tag === '')
  970. continue;
  971. // Special case: inside [code] blocks any code is left untouched.
  972. elseif ($tag === 'code')
  973. {
  974. // We're inside a code block and closing it.
  975. if ($inCode && $isClosingTag)
  976. {
  977. $inCode = false;
  978. // Reopen tags that were closed before the code block.
  979. if (!empty($inlineElements))
  980. $parts[$i + 4] .= '[' . implode('][', array_keys($inlineElements)) . ']';
  981. }
  982. // We're outside a coding and nobbc block and opening it.
  983. elseif (!$inCode && !$inNoBbc && $isOpeningTag)
  984. {
  985. // If there are still inline elements left open, close them now.
  986. if (!empty($inlineElements))
  987. {
  988. $parts[$i] .= '[/' . implode('][/', array_reverse($inlineElements)) . ']';
  989. //$inlineElements = array();
  990. }
  991. $inCode = true;
  992. }
  993. // Nothing further to do.
  994. continue;
  995. }
  996. // Special case: inside [nobbc] blocks any BBC is left untouched.
  997. elseif ($tag === 'nobbc')
  998. {
  999. // We're inside a nobbc block and closing it.
  1000. if ($inNoBbc && $isClosingTag)
  1001. {
  1002. $inNoBbc = false;
  1003. // Some inline elements might've been closed that need reopening.
  1004. if (!empty($inlineElements))
  1005. $parts[$i + 4] .= '[' . implode('][', array_keys($inlineElements)) . ']';
  1006. }
  1007. // We're outside a nobbc and coding block and opening it.
  1008. elseif (!$inNoBbc && !$inCode && $isOpeningTag)
  1009. {
  1010. // Can't have inline elements still opened.
  1011. if (!empty($inlineElements))
  1012. {
  1013. $parts[$i] .= '[/' . implode('][/', array_reverse($inlineElements)) . ']';
  1014. //$inlineElements = array();
  1015. }
  1016. $inNoBbc = true;
  1017. }
  1018. continue;
  1019. }
  1020. // So, we're inside one of the special blocks: ignore any tag.
  1021. elseif ($inCode || $inNoBbc)
  1022. continue;
  1023. // We're dealing with an opening tag.
  1024. if ($isOpeningTag)
  1025. {
  1026. // Everyting inside the square brackets of the opening tag.
  1027. $elementContent = $parts[$i + 3] . substr($parts[$i + 4], 0, -1);
  1028. // A block level opening tag.
  1029. if ($isBlockLevelTag)
  1030. {
  1031. // Are there inline elements still open?
  1032. if (!empty($inlineElements))
  1033. {
  1034. // Close all the inline tags, a block tag is coming...
  1035. $parts[$i] .= '[/' . implode('][/', array_reverse($inlineElements)) . ']';
  1036. // Now open them again, we're inside the block tag now.
  1037. $parts[$i + 5] = '[' . implode('][', array_keys($inlineElements)) . ']' . $parts[$i + 5];
  1038. }
  1039. $blockElements[] = $tag;
  1040. }
  1041. // Inline opening tag.
  1042. elseif (!in_array($tag, $self_closing_tags))
  1043. {
  1044. // Can't have two opening elements with the same contents!
  1045. if (isset($inlineElements[$elementContent]))
  1046. {
  1047. // Get rid of this tag.
  1048. $parts[$i + 1] = $parts[$i + 2] = $parts[$i + 3] = $parts[$i + 4] = '';
  1049. // Now try to find the corresponding closing tag.
  1050. $curLevel = 1;
  1051. for ($j = $i + 5, $m = count($parts) - 1; $j < $m; $j += 5)
  1052. {
  1053. // Find the tags with the same tagname
  1054. if ($parts[$j + 3] === $tag)
  1055. {
  1056. // If it's an opening tag, increase the level.
  1057. if ($parts[$j + 2] === '')
  1058. $curLevel++;
  1059. // A closing tag, decrease the level.
  1060. else
  1061. {
  1062. $curLevel--;
  1063. // Gotcha! Clean out this closing tag gone rogue.
  1064. if ($curLevel === 0)
  1065. {
  1066. $parts[$j + 1] = $parts[$j + 2] = $parts[$j + 3] = $parts[$j + 4] = '';
  1067. break;
  1068. }
  1069. }
  1070. }
  1071. }
  1072. }
  1073. // Otherwise, add this one to the list.
  1074. else
  1075. {
  1076. if ($isCompetingTag)
  1077. {
  1078. if (!isset($competingElements[$tag]))
  1079. $competingElements[$tag] = array();
  1080. $competingElements[$tag][] = $parts[$i + 4];
  1081. if (count($competingElements[$tag]) > 1)
  1082. $parts[$i] .= '[/' . $tag . ']';
  1083. }
  1084. $inlineElements[$elementContent] = $tag;
  1085. }
  1086. }
  1087. }
  1088. // Closing tag.
  1089. else
  1090. {
  1091. // Closing the block tag.
  1092. if ($isBlockLevelTag)
  1093. {
  1094. // Close the elements that should've been closed by closing this tag.
  1095. if (!empty($blockElements))
  1096. {
  1097. $addClosingTags = array();
  1098. while ($element = array_pop($blockElements))
  1099. {
  1100. if ($element === $tag)
  1101. break;
  1102. // Still a block tag was open not equal to this tag.
  1103. $addClosingTags[] = $element['type'];
  1104. }
  1105. if (!empty($addClosingTags))
  1106. $parts[$i + 1] = '[/' . implode('][/', array_reverse($addClosingTags)) . ']' . $parts[$i + 1];
  1107. // Apparently the closing tag was not found on the stack.
  1108. if (!is_string($element) || $element !== $tag)
  1109. {
  1110. // Get rid of this particular closing tag, it was never opened.
  1111. $parts[$i + 1] = substr($parts[$i + 1], 0, -1);
  1112. $parts[$i + 2] = $parts[$i + 3] = $parts[$i + 4] = '';
  1113. continue;
  1114. }
  1115. }
  1116. else
  1117. {
  1118. // Get rid of this closing tag!
  1119. $parts[$i + 1] = $parts[$i + 2] = $parts[$i + 3] = $parts[$i + 4] = '';
  1120. continue;
  1121. }
  1122. // Inline elements are still left opened?
  1123. if (!empty($inlineElements))
  1124. {
  1125. // Close them first..
  1126. $parts[$i] .= '[/' . implode('][/', array_reverse($inlineElements)) . ']';
  1127. // Then reopen them.
  1128. $parts[$i + 5] = '[' . implode('][', array_keys($inlineElements)) . ']' . $parts[$i + 5];
  1129. }
  1130. }
  1131. // Inline tag.
  1132. else
  1133. {
  1134. // Are we expecting this tag to end?
  1135. if (in_array($tag, $inlineElements))
  1136. {
  1137. foreach (array_reverse($inlineElements, true) as $tagContentToBeClosed => $tagToBeClosed)
  1138. {
  1139. // Closing it one way or the other.
  1140. unset($inlineElements[$tagContentToBeClosed]);
  1141. // Was this the tag we were looking for?
  1142. if ($tagToBeClosed === $tag)
  1143. break;
  1144. // Nope, close it and look further!
  1145. else
  1146. $parts[$i] .= '[/' . $tagToBeClosed . ']';
  1147. }
  1148. if ($isCompetingTag && !empty($competingElements[$tag]))
  1149. {
  1150. array_pop($competingElements[$tag]);
  1151. if (count($competingElements[$tag]) > 0)
  1152. $parts[$i + 5] = '[' . $tag . $competingElements[$tag][count($competingElements[$tag]) - 1] . $parts[$i + 5];
  1153. }
  1154. }
  1155. // Unexpected closing tag, ex-ter-mi-nate.
  1156. else
  1157. $parts[$i + 1] = $parts[$i + 2] = $parts[$i + 3] = $parts[$i + 4] = '';
  1158. }
  1159. }
  1160. }
  1161. // Close the code tags.
  1162. if ($inCode)
  1163. $parts[$i] .= '[/code]';
  1164. // The same for nobbc tags.
  1165. elseif ($inNoBbc)
  1166. $parts[$i] .= '[/nobbc]';
  1167. // Still inline tags left unclosed? Close them now, better late than never.
  1168. elseif (!empty($inlineElements))
  1169. $parts[$i] .= '[/' . implode('][/', array_reverse($inlineElements)) . ']';
  1170. // Now close the block elements.
  1171. if (!empty($blockElements))
  1172. $parts[$i] .= '[/' . implode('][/', array_reverse($blockElements)) . ']';
  1173. $text = implode('', $parts);
  1174. }
  1175. // Final clean up of back to back tags.
  1176. $lastlen = 0;
  1177. while (strlen($text) !== $lastlen)
  1178. $lastlen = strlen($text = preg_replace($backToBackPattern, '', $text));
  1179. return $text;
  1180. }
  1181. /**
  1182. * A help function for legalise_bbc for sorting arrays based on length.
  1183. * @param string $a
  1184. * @param string $b
  1185. * @return int 1 or -1
  1186. */
  1187. function sort_array_length($a, $b)
  1188. {
  1189. return strlen($a) < strlen($b) ? 1 : -1;
  1190. }
  1191. /**
  1192. * Compatibility function - used in 1.1 for showing a post box.
  1193. *
  1194. * @param string $msg
  1195. * @return string
  1196. */
  1197. function theme_postbox($msg)
  1198. {
  1199. global $context;
  1200. return template_control_richedit($context['post_box_name']);
  1201. }
  1202. /**
  1203. * Creates a box that can be used for richedit stuff like BBC, Smileys etc.
  1204. * @param array $editorOptions
  1205. */
  1206. function create_control_richedit($editorOptions)
  1207. {
  1208. global $txt, $modSettings, $options, $smcFunc;
  1209. global $context, $settings, $user_info, $sourcedir, $scripturl;
  1210. // Load the Post language file... for the moment at least.
  1211. loadLanguage('Post');
  1212. // Every control must have a ID!
  1213. assert(isset($editorOptions['id']));
  1214. assert(isset($editorOptions['value']));
  1215. // Is this the first richedit - if so we need to ensure some template stuff is initialised.
  1216. if (empty($context['controls']['richedit']))
  1217. {
  1218. // Some general stuff.
  1219. $settings['smileys_url'] = $modSettings['smileys_url'] . '/' . $user_info['smiley_set'];
  1220. // This really has some WYSIWYG stuff.
  1221. loadTemplate('GenericControls', isBrowser('ie') ? 'editor_ie' : 'editor');
  1222. $context['html_headers'] .= '
  1223. <script type="text/javascript"><!-- // --><![CDATA[
  1224. var smf_smileys_url = \'' . $settings['smileys_url'] . '\';
  1225. var oEditorStrings= {
  1226. wont_work: \'' . addcslashes($txt['rich_edit_wont_work'], "'") . '\',
  1227. func_disabled: \'' . addcslashes($txt['rich_edit_function_disabled'], "'") . '\',
  1228. prompt_text_email: \'' . addcslashes($txt['prompt_text_email'], "'") . '\',
  1229. prompt_text_ftp: \'' . addcslashes($txt['prompt_text_ftp'], "'") . '\',
  1230. prompt_text_url: \'' . addcslashes($txt['prompt_text_url'], "'") . '\',
  1231. prompt_text_img: \'' . addcslashes($txt['prompt_text_img'], "'") . '\'
  1232. }
  1233. // ]]></script>
  1234. <script type="text/javascript" src="' . $settings['default_theme_url'] . '/scripts/editor.js?fin20"></script>';
  1235. $context['show_spellchecking'] = !empty($modSettings['enableSpellChecking']) && function_exists('pspell_new');
  1236. if ($context['show_spellchecking'])
  1237. {
  1238. $context['html_headers'] .= '
  1239. <script type="text/javascript" src="' . $settings['default_theme_url'] . '/scripts/spellcheck.js"></script>';
  1240. // Some hidden information is needed in order to make the spell checking work.
  1241. if (!isset($_REQUEST['xml']))
  1242. $context['insert_after_template'] .= '
  1243. <form name="spell_form" id="spell_form" method="post" accept-charset="' . $context['character_set'] . '" target="spellWindow" action="' . $scripturl . '?action=spellcheck">
  1244. <input type="hidden" name="spellstring" value="" />
  1245. </form>';
  1246. // Also make sure that spell check works with rich edit.
  1247. $context['html_headers'] .= '
  1248. <script type="text/javascript"><!-- // --><![CDATA[
  1249. function spellCheckDone()
  1250. {
  1251. for (i = 0; i < smf_editorArray.length; i++)
  1252. setTimeout("smf_editorArray[" + i + "].spellCheckEnd()", 150);
  1253. }
  1254. // ]]></script>';
  1255. }
  1256. }
  1257. // Start off the editor...
  1258. $context['controls']['richedit'][$editorOptions['id']] = array(
  1259. 'id' => $editorOptions['id'],
  1260. 'value' => $editorOptions['value'],
  1261. 'rich_value' => bbc_to_html($editorOptions['value']),
  1262. 'rich_active' => empty($modSettings['disable_wysiwyg']) && (!empty($options['wysiwyg_default']) || !empty($editorOptions['force_rich']) || !empty($_REQUEST[$editorOptions['id'] . '_mode'])),
  1263. 'disable_smiley_box' => !empty($editorOptions['disable_smiley_box']),
  1264. 'columns' => isset($editorOptions['columns']) ? $editorOptions['columns'] : 60,
  1265. 'rows' => isset($editorOptions['rows']) ? $editorOptions['rows'] : 12,
  1266. 'width' => isset($editorOptions['width']) ? $editorOptions['width'] : '70%',
  1267. 'height' => isset($editorOptions['height']) ? $editorOptions['height'] : '150px',
  1268. 'form' => isset($editorOptions['form']) ? $editorOptions['form'] : 'postmodify',
  1269. 'bbc_level' => !empty($editorOptions['bbc_level']) ? $editorOptions['bbc_level'] : 'full',
  1270. 'preview_type' => isset($editorOptions['preview_type']) ? (int) $editorOptions['preview_type'] : 1,
  1271. 'labels' => !empty($editorOptions['labels']) ? $editorOptions['labels'] : array(),
  1272. );
  1273. // Switch between default images and back... mostly in case you don't have an PersonalMessage template, but do have a Post template.
  1274. if (isset($settings['use_default_images']) && $settings['use_default_images'] == 'defaults' && isset($settings['default_template']))
  1275. {
  1276. $temp1 = $settings['theme_url'];
  1277. $settings['theme_url'] = $settings['default_theme_url'];
  1278. $temp2 = $settings['images_url'];
  1279. $settings['images_url'] = $settings['default_images_url'];
  1280. $temp3 = $settings['theme_dir'];
  1281. $settings['theme_dir'] = $settings['default_theme_dir'];
  1282. }
  1283. if (empty($context['bbc_tags']))
  1284. {
  1285. // 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!
  1286. $context['bbc_tags'] = array();
  1287. $context['bbc_tags'][] = array(
  1288. array(
  1289. 'image' => 'bold',
  1290. 'code' => 'b',
  1291. 'before' => '[b]',
  1292. 'after' => '[/b]',
  1293. 'description' => $txt['bold'],
  1294. ),
  1295. array(
  1296. 'image' => 'italicize',
  1297. 'code' => 'i',
  1298. 'before' => '[i]',
  1299. 'after' => '[/i]',
  1300. 'description' => $txt['italic'],
  1301. ),
  1302. array(
  1303. 'image' => 'underline',
  1304. 'code' => 'u',
  1305. 'before' => '[u]',
  1306. 'after' => '[/u]',
  1307. 'description' => $txt['underline']
  1308. ),
  1309. array(
  1310. 'image' => 'strike',
  1311. 'code' => 's',
  1312. 'before' => '[s]',
  1313. 'after' => '[/s]',
  1314. 'description' => $txt['strike']
  1315. ),
  1316. array(),
  1317. array(
  1318. 'image' => 'pre',
  1319. 'code' => 'pre',
  1320. 'before' => '[pre]',
  1321. 'after' => '[/pre]',
  1322. 'description' => $txt['preformatted']
  1323. ),
  1324. array(
  1325. 'image' => 'left',
  1326. 'code' => 'left',
  1327. 'before' => '[left]',
  1328. 'after' => '[/left]',
  1329. 'description' => $txt['left_align']
  1330. ),
  1331. array(
  1332. 'image' => 'center',
  1333. 'code' => 'center',
  1334. 'before' => '[center]',
  1335. 'after' => '[/center]',
  1336. 'description' => $txt['center']
  1337. ),
  1338. array(
  1339. 'image' => 'right',
  1340. 'code' => 'right',
  1341. 'before' => '[right]',
  1342. 'after' => '[/right]',
  1343. 'description' => $txt['right_align']
  1344. ),
  1345. );
  1346. $context['bbc_tags'][] = array(
  1347. array(
  1348. 'image' => 'flash',
  1349. 'code' => 'flash',
  1350. 'before' => '[flash=200,200]',
  1351. 'after' => '[/flash]',
  1352. 'description' => $txt['flash']
  1353. ),
  1354. array(
  1355. 'image' => 'img',
  1356. 'code' => 'img',
  1357. 'before' => '[img]',
  1358. 'after' => '[/img]',
  1359. 'description' => $txt['image']
  1360. ),
  1361. array(
  1362. 'image' => 'url',
  1363. 'code' => 'url',
  1364. 'before' => '[url]',
  1365. 'after' => '[/url]',
  1366. 'description' => $txt['hyperlink']
  1367. ),
  1368. array(
  1369. 'image' => 'email',
  1370. 'code' => 'email',
  1371. 'before' => '[email]',
  1372. 'after' => '[/email]',
  1373. 'description' => $txt['insert_email']
  1374. ),
  1375. array(
  1376. 'image' => 'ftp',
  1377. 'code' => 'ftp',
  1378. 'before' => '[ftp]',
  1379. 'after' => '[/ftp]',
  1380. 'description' => $txt['ftp']
  1381. ),
  1382. array(),
  1383. array(
  1384. 'image' => 'glow',
  1385. 'code' => 'glow',
  1386. 'before' => '[glow=red,2,300]',
  1387. 'after' => '[/glow]',
  1388. 'description' => $txt['glow']
  1389. ),
  1390. array(
  1391. 'image' => 'shadow',
  1392. 'code' => 'shadow',
  1393. 'before' => '[shadow=red,left]',
  1394. 'after' => '[/shadow]',
  1395. 'description' => $txt['shadow']
  1396. ),
  1397. array(
  1398. 'image' => 'move',
  1399. 'code' => 'move',
  1400. 'before' => '[move]',
  1401. 'after' => '[/move]',
  1402. 'description' => $txt['marquee']
  1403. ),
  1404. array(),
  1405. array(
  1406. 'image' => 'sup',
  1407. 'code' => 'sup',
  1408. 'before' => '[sup]',
  1409. 'after' => '[/sup]',
  1410. 'description' => $txt['superscript']
  1411. ),
  1412. array(
  1413. 'image' => 'sub',
  1414. 'code' => 'sub',
  1415. 'before' => '[sub]',
  1416. 'after' => '[/sub]',
  1417. 'description' => $txt['subscript']
  1418. ),
  1419. array(
  1420. 'image' => 'tele',
  1421. 'code' => 'tt',
  1422. 'before' => '[tt]',
  1423. 'after' => '[/tt]',
  1424. 'description' => $txt['teletype']
  1425. ),
  1426. array(),
  1427. array(
  1428. 'image' => 'table',
  1429. 'code' => 'table',
  1430. 'before' => '[table]\n[tr]\n[td]',
  1431. 'after' => '[/td]\n[/tr]\n[/table]',
  1432. 'description' => $txt['table']
  1433. ),
  1434. array(
  1435. 'image' => 'code',
  1436. 'code' => 'code',
  1437. 'before' => '[code]',
  1438. 'after' => '[/code]',
  1439. 'description' => $txt['bbc_code']
  1440. ),
  1441. array(
  1442. 'image' => 'quote',
  1443. 'code' => 'quote',
  1444. 'before' => '[quote]',
  1445. 'after' => '[/quote]',
  1446. 'description' => $txt['bbc_quote']
  1447. ),
  1448. array(),
  1449. array(
  1450. 'image' => 'list',
  1451. 'code' => 'list',
  1452. 'before' => '[list]\n[li]',
  1453. 'after' => '[/li]\n[li][/li]\n[/list]',
  1454. 'description' => $txt['list_unordered']
  1455. ),
  1456. array(
  1457. 'image' => 'orderlist',
  1458. 'code' => 'orderlist',
  1459. 'before' => '[list type=decimal]\n[li]',
  1460. 'after' => '[/li]\n[li][/li]\n[/list]',
  1461. 'description' => $txt['list_ordered']
  1462. ),
  1463. array(
  1464. 'image' => 'hr',
  1465. 'code' => 'hr',
  1466. 'before' => '[hr]',
  1467. 'description' => $txt['horizontal_rule']
  1468. ),
  1469. );
  1470. // Allow mods to modify BBC buttons.
  1471. call_integration_hook('integrate_bbc_buttons');
  1472. // Show the toggle?
  1473. if (empty($modSettings['disable_wysiwyg']))
  1474. {
  1475. $context['bbc_tags'][count($context['bbc_tags']) - 1][] = array();
  1476. $context['bbc_tags'][count($context['bbc_tags']) - 1][] = array(
  1477. 'image' => 'unformat',
  1478. 'code' => 'unformat',
  1479. 'before' => '',
  1480. 'description' => $txt['unformat_text'],
  1481. );
  1482. $context['bbc_tags'][count($context['bbc_tags']) - 1][] = array(
  1483. 'image' => 'toggle',
  1484. 'code' => 'toggle',
  1485. 'before' => '',
  1486. 'description' => $txt['toggle_view'],
  1487. );
  1488. }
  1489. foreach ($context['bbc_tags'] as $row => $tagRow)
  1490. $context['bbc_tags'][$row][count($tagRow) - 1]['isLast'] = true;
  1491. }
  1492. // Initialize smiley array... if not loaded before.
  1493. if (empty($context['smileys']) && empty($editorOptions['disable_smiley_box']))
  1494. {
  1495. $context['smileys'] = array(
  1496. 'postform' => array(),
  1497. 'popup' => array(),
  1498. );
  1499. // Load smileys - don't bother to run a query if we're not using the database's ones anyhow.
  1500. if (empty($modSettings['smiley_enable']) && $user_info['smiley_set'] != 'none')
  1501. $context['smileys']['postform'][] = array(
  1502. 'smileys' => array(
  1503. array(
  1504. 'code' => ':)',
  1505. 'filename' => 'smiley.gif',
  1506. 'description' => $txt['icon_smiley'],
  1507. ),
  1508. array(
  1509. 'code' => ';)',
  1510. 'filename' => 'wink.gif',
  1511. 'description' => $txt['icon_wink'],
  1512. ),
  1513. array(
  1514. 'code' => ':D',
  1515. 'filename' => 'cheesy.gif',
  1516. 'description' => $txt['icon_cheesy'],
  1517. ),
  1518. array(
  1519. 'code' => ';D',
  1520. 'filename' => 'grin.gif',
  1521. 'description' => $txt['icon_grin']
  1522. ),
  1523. array(
  1524. 'code' => '>:(',
  1525. 'filename' => 'angry.gif',
  1526. 'description' => $txt['icon_angry'],
  1527. ),
  1528. array(
  1529. 'code' => ':(',
  1530. 'filename' => 'sad.gif',
  1531. 'description' => $txt['icon_sad'],
  1532. ),
  1533. array(
  1534. 'code' => ':o',
  1535. 'filename' => 'shocked.gif',
  1536. 'description' => $txt['icon_shocked'],
  1537. ),
  1538. array(
  1539. 'code' => '8)',
  1540. 'filename' => 'cool.gif',
  1541. 'description' => $txt['icon_cool'],
  1542. ),
  1543. array(
  1544. 'code' => '???',
  1545. 'filename' => 'huh.gif',
  1546. 'description' => $txt['icon_huh'],
  1547. ),
  1548. array(
  1549. 'code' => '::)',
  1550. 'filename' => 'rolleyes.gif',
  1551. 'description' => $txt['icon_rolleyes'],
  1552. ),
  1553. array(
  1554. 'code' => ':P',
  1555. 'filename' => 'tongue.gif',
  1556. 'description' => $txt['icon_tongue'],
  1557. ),
  1558. array(
  1559. 'code' => ':-[',
  1560. 'filename' => 'embarrassed.gif',
  1561. 'description' => $txt['icon_embarrassed'],
  1562. ),
  1563. array(
  1564. 'code' => ':-X',
  1565. 'filename' => 'lipsrsealed.gif',
  1566. 'description' => $txt['icon_lips'],
  1567. ),
  1568. array(
  1569. 'code' => ':-\\',
  1570. 'filename' => 'undecided.gif',
  1571. 'description' => $txt['icon_undecided'],
  1572. ),
  1573. array(
  1574. 'code' => ':-*',
  1575. 'filename' => 'kiss.gif',
  1576. 'description' => $txt['icon_kiss'],
  1577. ),
  1578. array(
  1579. 'code' => ':\'(',
  1580. 'filename' => 'cry.gif',
  1581. 'description' => $txt['icon_cry'],
  1582. 'isLast' => true,
  1583. ),
  1584. ),
  1585. 'isLast' => true,
  1586. );
  1587. elseif ($user_info['smiley_set'] != 'none')
  1588. {
  1589. if (($temp = cache_get_data('posting_smileys', 480)) === null)
  1590. {
  1591. $request = $smcFunc['db_query']('', '
  1592. SELECT code, filename, description, smiley_row, hidden
  1593. FROM {db_prefix}smileys
  1594. WHERE hidden IN (0, 2)
  1595. ORDER BY smiley_row, smiley_order',
  1596. array(
  1597. )
  1598. );
  1599. while ($row = $smcFunc['db_fetch_assoc']($request))
  1600. {
  1601. $row['filename'] = htmlspecialchars($row['filename']);
  1602. $row['description'] = htmlspecialchars($row['description']);
  1603. $context['smileys'][empty($row['hidden']) ? 'postform' : 'popup'][$row['smiley_row']]['smileys'][] = $row;
  1604. }
  1605. $smcFunc['db_free_result']($request);
  1606. foreach ($context['smileys'] as $section => $smileyRows)
  1607. {
  1608. foreach ($smileyRows as $rowIndex => $smileys)
  1609. $context['smileys'][$section][$rowIndex]['smileys'][count($smileys['smileys']) - 1]['isLast'] = true;
  1610. if (!empty($smileyRows))
  1611. $context['smileys'][$section][count($smileyRows) - 1]['isLast'] = true;
  1612. }
  1613. cache_put_data('posting_smileys', $context['smileys'], 480);
  1614. }
  1615. else
  1616. $context['smileys'] = $temp;
  1617. }
  1618. }
  1619. // Set a flag so the sub template knows what to do...
  1620. $context['show_bbc'] = !empty($modSettings['enableBBC']) && !empty($settings['show_bbc']);
  1621. // Generate a list of buttons that shouldn't be shown - this should be the fastest way to do this.
  1622. $disabled_tags = array();
  1623. if (!empty($modSettings['disabledBBC']))
  1624. $disabled_tags = explode(',', $modSettings['disabledBBC']);
  1625. if (empty($modSettings['enableEmbeddedFlash']))
  1626. $disabled_tags[] = 'flash';
  1627. foreach ($disabled_tags as $tag)
  1628. {
  1629. if ($tag == 'list')
  1630. $context['disabled_tags']['orderlist'] = true;
  1631. $context['disabled_tags'][trim($tag)] = true;
  1632. }
  1633. // Switch the URLs back... now we're back to whatever the main sub template is. (like folder in PersonalMessage.)
  1634. if (isset($settings['use_default_images']) && $settings['use_default_images'] == 'defaults' && isset($settings['default_template']))
  1635. {
  1636. $settings['theme_url'] = $temp1;
  1637. $settings['images_url'] = $temp2;
  1638. $settings['theme_dir'] = $temp3;
  1639. }
  1640. }
  1641. /**
  1642. * Create a anti-bot verification control?
  1643. * @param array &$verificationOptions
  1644. * @param bool $do_test = false
  1645. */
  1646. function create_control_verification(&$verificationOptions, $do_test = false)
  1647. {
  1648. global $txt, $modSettings, $options, $smcFunc;
  1649. global $context, $settings, $user_info, $sourcedir, $scripturl;
  1650. // First verification means we need to set up some bits...
  1651. if (empty($context['controls']['verification']))
  1652. {
  1653. // The template
  1654. loadTemplate('GenericControls');
  1655. // Some javascript ma'am?
  1656. if (!empty($verificationOptions['override_visual']) || (!empty($modSettings['visual_verification_type']) && !isset($verificationOptions['override_visual'])))
  1657. $context['html_headers'] .= '
  1658. <script type="text/javascript" src="' . $settings['default_theme_url'] . '/scripts/captcha.js"></script>';
  1659. $context['use_graphic_library'] = in_array('gd', get_loaded_extensions());
  1660. // Skip I, J, L, O, Q, S and Z.
  1661. $context['standard_captcha_range'] = array_merge(range('A', 'H'), array('K', 'M', 'N', 'P', 'R'), range('T', 'Y'));
  1662. }
  1663. // Always have an ID.
  1664. assert(isset($verificationOptions['id']));
  1665. $isNew = !isset($context['controls']['verification'][$verificationOptions['id']]);
  1666. // Log this into our collection.
  1667. if ($isNew)
  1668. $context['controls']['verification'][$verificationOptions['id']] = array(
  1669. 'id' => $verificationOptions['id'],
  1670. 'show_visual' => !empty($verificationOptions['override_visual']) || (!empty($modSettings['visual_verification_type']) && !isset($verificationOptions['override_visual'])),
  1671. 'number_questions' => isset($verificationOptions['override_qs']) ? $verificationOptions['override_qs'] : (!empty($modSettings['qa_verification_number']) ? $modSettings['qa_verification_number'] : 0),
  1672. 'max_errors' => isset($verificationOptions['max_errors']) ? $verificationOptions['max_errors'] : 3,
  1673. 'image_href' => $scripturl . '?action=verificationcode;vid=' . $verificationOptions['id'] . ';rand=' . md5(mt_rand()),
  1674. 'text_value' => '',
  1675. 'questions' => array(),
  1676. );
  1677. $thisVerification = &$context['controls']['verification'][$verificationOptions['id']];
  1678. // Add javascript for the object.
  1679. if ($context['controls']['verification'][$verificationOptions['id']]['show_visual'] && !WIRELESS)
  1680. $context['insert_after_template'] .= '
  1681. <script type="text/javascript"><!-- // --><![CDATA[
  1682. var verification' . $verificationOptions['id'] . 'Handle = new smfCaptcha("' . $thisVerification['image_href'] . '", "' . $verificationOptions['id'] . '", ' . ($context['use_graphic_library'] ? 1 : 0) . ');
  1683. // ]]></script>';
  1684. // Is there actually going to be anything?
  1685. if (empty($thisVerification['show_visual']) && empty($thisVerification['number_questions']))
  1686. return false;
  1687. elseif (!$isNew && !$do_test)
  1688. return true;
  1689. // If we want questions do we have a cache of all the IDs?
  1690. if (!empty($thisVerification['number_questions']) && empty($modSettings['question_id_cache']))
  1691. {
  1692. if (($modSettings['question_id_cache'] = cache_get_data('verificationQuestionIds', 300)) === null)
  1693. {
  1694. $request = $smcFunc['db_query']('', '
  1695. SELECT id_comment
  1696. FROM {db_prefix}log_comments
  1697. WHERE comment_type = {string:ver_test}',
  1698. array(
  1699. 'ver_test' => 'ver_test',
  1700. )
  1701. );
  1702. $modSettings['question_id_cache'] = array();
  1703. while ($row = $smcFunc['db_fetch_assoc']($request))
  1704. $modSettings['question_id_cache'][] = $row['id_comment'];
  1705. $smcFunc['db_free_result']($request);
  1706. if (!empty($modSettings['cache_enable']))
  1707. cache_put_data('verificationQuestionIds', $modSettings['question_id_cache'], 300);
  1708. }
  1709. }
  1710. if (!isset($_SESSION[$verificationOptions['id'] . '_vv']))
  1711. $_SESSION[$verificationOptions['id'] . '_vv'] = array();
  1712. // Do we need to refresh the verification?
  1713. 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']))
  1714. $force_refresh = true;
  1715. else
  1716. $force_refresh = false;
  1717. // This can also force a fresh, although unlikely.
  1718. if (($thisVerification['show_visual'] && empty($_SESSION[$verificationOptions['id'] . '_vv']['code'])) || ($thisVerification['number_questions'] && empty($_SESSION[$verificationOptions['id'] . '_vv']['q'])))
  1719. $force_refresh = true;
  1720. $verification_errors = array();
  1721. // Start with any testing.
  1722. if ($do_test)
  1723. {
  1724. // This cannot happen!
  1725. if (!isset($_SESSION[$verificationOptions['id'] . '_vv']['count']))
  1726. fatal_lang_error('no_access', false);
  1727. // ... nor this!
  1728. if ($thisVerification['number_questions'] && (!isset($_SESSION[$verificationOptions['id'] . '_vv']['q']) || !isset($_REQUEST[$verificationOptions['id'] . '_vv']['q'])))
  1729. fatal_lang_error('no_access', false);
  1730. 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']))
  1731. $verification_errors[] = 'wrong_verification_code';
  1732. if ($thisVerification['number_questions'])
  1733. {
  1734. // Get the answers and see if they are all right!
  1735. $request = $smcFunc['db_query']('', '
  1736. SELECT id_comment, recipient_name AS answer
  1737. FROM {db_prefix}log_comments
  1738. WHERE comment_type = {string:ver_test}
  1739. AND id_comment IN ({array_int:comment_ids})',
  1740. array(
  1741. 'ver_test' => 'ver_test',
  1742. 'comment_ids' => $_SESSION[$verificationOptions['id'] . '_vv']['q'],
  1743. )
  1744. );
  1745. $incorrectQuestions = array();
  1746. while ($row = $smcFunc['db_fetch_assoc']($request))
  1747. {
  1748. 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']))
  1749. $incorrectQuestions[] = $row['id_comment'];
  1750. }
  1751. $smcFunc['db_free_result']($request);
  1752. if (!empty($incorrectQuestions))
  1753. $verification_errors[] = 'wrong_verification_answer';
  1754. }
  1755. }
  1756. // Any errors means we refresh potentially.
  1757. if (!empty($verification_errors))
  1758. {
  1759. if (empty($_SESSION[$verificationOptions['id'] . '_vv']['errors']))
  1760. $_SESSION[$verificationOptions['id'] . '_vv']['errors'] = 0;
  1761. // Too many errors?
  1762. elseif ($_SESSION[$verificationOptions['id'] . '_vv']['errors'] > $thisVerification['max_errors'])
  1763. $force_refresh = true;
  1764. // Keep a track of these.
  1765. $_SESSION[$verificationOptions['id'] . '_vv']['errors']++;
  1766. }
  1767. // Are we refreshing then?
  1768. if ($force_refresh)
  1769. {
  1770. // Assume nothing went before.
  1771. $_SESSION[$verificationOptions['id'] . '_vv']['count'] = 0;
  1772. $_SESSION[$verificationOptions['id'] . '_vv']['errors'] = 0;
  1773. $_SESSION[$verificationOptions['id'] . '_vv']['did_pass'] = false;
  1774. $_SESSION[$verificationOptions['id'] . '_vv']['q'] = array();
  1775. $_SESSION[$verificationOptions['id'] . '_vv']['code'] = '';
  1776. // Generating a new image.
  1777. if ($thisVerification['show_visual'])
  1778. {
  1779. // Are we overriding the range?
  1780. $character_range = !empty($verificationOptions['override_range']) ? $verificationOptions['override_range'] : $context['standard_captcha_range'];
  1781. for ($i = 0; $i < 6; $i++)
  1782. $_SESSION[$verificationOptions['id'] . '_vv']['code'] .= $character_range[array_rand($character_range)];
  1783. }
  1784. // Getting some new questions?
  1785. if ($thisVerification['number_questions'])
  1786. {
  1787. // Pick some random IDs
  1788. $questionIDs = array();
  1789. if ($thisVerification['number_questions'] == 1)
  1790. $questionIDs[] = $modSettings['question_id_cache'][array_rand($modSettings['question_id_cache'], $thisVerification['number_questions'])];
  1791. else
  1792. foreach (array_rand($modSettings['question_id_cache'], $thisVerification['number_questions']) as $index)
  1793. $questionIDs[] = $modSettings['question_id_cache'][$index];
  1794. }
  1795. }
  1796. else
  1797. {
  1798. // Same questions as before.
  1799. $questionIDs = !empty($_SESSION[$verificationOptions['id'] . '_vv']['q']) ? $_SESSION[$verificationOptions['id'] . '_vv']['q'] : array();
  1800. $thisVerification['text_value'] = !empty($_REQUEST[$verificationOptions['id'] . '_vv']['code']) ? $smcFunc['htmlspecialchars']($_REQUEST[$verificationOptions['id'] . '_vv']['code']) : '';
  1801. }
  1802. // Have we got some questions to load?
  1803. if (!empty($questionIDs))
  1804. {
  1805. $request = $smcFunc['db_query']('', '
  1806. SELECT id_comment, body AS question
  1807. FROM {db_prefix}log_comments
  1808. WHERE comment_type = {string:ver_test}
  1809. AND id_comment IN ({array_int:comment_ids})',
  1810. array(
  1811. 'ver_test' => 'ver_test',
  1812. 'comment_ids' => $questionIDs,
  1813. )
  1814. );
  1815. $_SESSION[$verificationOptions['id'] . '_vv']['q'] = array();
  1816. while ($row = $smcFunc['db_fetch_assoc']($request))
  1817. {
  1818. $thisVerification['questions'][] = array(
  1819. 'id' => $row['id_comment'],
  1820. 'q' => parse_bbc($row['question']),
  1821. 'is_error' => !empty($incorrectQuestions) && in_array($row['id_comment'], $incorrectQuestions),
  1822. // Remember a previous submission?
  1823. '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']]) : '',
  1824. );
  1825. $_SESSION[$verificationOptions['id'] . '_vv']['q'][] = $row['id_comment'];
  1826. }
  1827. $smcFunc['db_free_result']($request);
  1828. }
  1829. $_SESSION[$verificationOptions['id'] . '_vv']['count'] = empty($_SESSION[$verificationOptions['id'] . '_vv']['count']) ? 1 : $_SESSION[$verificationOptions['id'] . '_vv']['count'] + 1;
  1830. // Return errors if we have them.
  1831. if (!empty($verification_errors))
  1832. return $verification_errors;
  1833. // If we had a test that one, make a note.
  1834. elseif ($do_test)
  1835. $_SESSION[$verificationOptions['id'] . '_vv']['did_pass'] = true;
  1836. // Say that everything went well chaps.
  1837. return true;
  1838. }
  1839. /**
  1840. * This keeps track of all registered handling functions for auto suggest functionality and passes execution to them.
  1841. * @param bool $checkRegistered = null
  1842. */
  1843. function AutoSuggestHandler($checkRegistered = null)
  1844. {
  1845. global $context;
  1846. // These are all registered types.
  1847. $searchTypes = array(
  1848. 'member' => 'Member',
  1849. );
  1850. // If we're just checking the callback function is registered return true or false.
  1851. if ($checkRegistered !== null)
  1852. return isset($searchTypes[$checkRegistered]) && function_exists('AutoSuggest_Search_' . $checkRegistered);
  1853. checkSession('get');
  1854. loadTemplate('Xml');
  1855. // Any parameters?
  1856. $context['search_param'] = isset($_REQUEST['search_param']) ? unserialize(base64_decode($_REQUEST['search_param'])) : array();
  1857. if (isset($_REQUEST['suggest_type'], $_REQUEST['search']) && isset($searchTypes[$_REQUEST['suggest_type']]))
  1858. {
  1859. $function = 'AutoSuggest_Search_' . $searchTypes[$_REQUEST['suggest_type']];
  1860. $context['sub_template'] = 'generic_xml';
  1861. $context['xml_data'] = $function();
  1862. }
  1863. }
  1864. /**
  1865. * Search for a member - by real_name or member_name by default.
  1866. *
  1867. * @return string
  1868. */
  1869. function AutoSuggest_Search_Member()
  1870. {
  1871. global $user_info, $txt, $smcFunc, $context;
  1872. $_REQUEST['search'] = trim($smcFunc['strtolower']($_REQUEST['search'])) . '*';
  1873. $_REQUEST['search'] = strtr($_REQUEST['search'], array('%' => '\%', '_' => '\_', '*' => '%', '?' => '_', '&#038;' => '&amp;'));
  1874. // Find the member.
  1875. $request = $smcFunc['db_query']('', '
  1876. SELECT id_member, real_name
  1877. FROM {db_prefix}members
  1878. WHERE real_name LIKE {string:search}' . (!empty($context['search_param']['buddies']) ? '
  1879. AND id_member IN ({array_int:buddy_list})' : '') . '
  1880. AND is_activated IN (1, 11)
  1881. LIMIT ' . ($smcFunc['strlen']($_REQUEST['search']) <= 2 ? '100' : '800'),
  1882. array(
  1883. 'buddy_list' => $user_info['buddies'],
  1884. 'search' => $_REQUEST['search'],
  1885. )
  1886. );
  1887. $xml_data = array(
  1888. 'items' => array(
  1889. 'identifier' => 'item',
  1890. 'children' => array(),
  1891. ),
  1892. );
  1893. while ($row = $smcFunc['db_fetch_assoc']($request))
  1894. {
  1895. $row['real_name'] = strtr($row['real_name'], array('&amp;' => '&#038;', '&lt;' => '&#060;', '&gt;' => '&#062;', '&quot;' => '&#034;'));
  1896. $xml_data['items']['children'][] = array(
  1897. 'attributes' => array(
  1898. 'id' => $row['id_member'],
  1899. ),
  1900. 'value' => $row['real_name'],
  1901. );
  1902. }
  1903. $smcFunc['db_free_result']($request);
  1904. return $xml_data;
  1905. }
  1906. ?>