Subs-Editor.php 68 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249
  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', 'td')))
  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. $sizes_equivalence = array(1 => '8pt', '10pt', '12pt', '14pt', '18pt', '24pt', '36pt');
  390. foreach ($attribs as $s => $v)
  391. {
  392. if ($s == 'size')
  393. {
  394. // Cast before empty chech because casting a string results in a 0 and we don't have zeros in the array! ;)
  395. $v = (int) trim($v);
  396. $v = empty($v) ? 1 : $v;
  397. $tags[] = array('[size=' . $sizes_equivalence[$v] . ']', '[/size]');
  398. }
  399. elseif ($s == 'face')
  400. $tags[] = array('[font=' . trim(strtolower($v)) . ']', '[/font]');
  401. elseif ($s == 'color')
  402. $tags[] = array('[color=' . trim(strtolower($v)) . ']', '[/color]');
  403. }
  404. // As before add in our tags.
  405. $before = $after = '';
  406. foreach ($tags as $tag)
  407. {
  408. $before .= $tag[0];
  409. if (isset($tag[1]))
  410. $after = $tag[1] . $after;
  411. }
  412. // Remove the tag so it's never checked again.
  413. $content = substr($text, $start_pos + strlen($matches[0]), $end_pos - $start_pos - strlen($matches[0]));
  414. // Put the tags back into the body.
  415. $text = substr($text, 0, $start_pos) . $before . $content . $after . substr($text, $end_pos + 7);
  416. }
  417. // Almost there, just a little more time.
  418. if (connection_aborted() && $context['server']['is_apache'])
  419. @apache_reset_timeout();
  420. if (count($parts = preg_split('~<(/?)(li|ol|ul)([^>]*)>~i', $text, null, PREG_SPLIT_DELIM_CAPTURE)) > 1)
  421. {
  422. // A toggle that dermines whether we're directly under a <ol> or <ul>.
  423. $inList = false;
  424. // Keep track of the number of nested list levels.
  425. $listDepth = 0;
  426. // Map what we can expect from the HTML to what is supported by SMF.
  427. $listTypeMapping = array(
  428. '1' => 'decimal',
  429. 'A' => 'upper-alpha',
  430. 'a' => 'lower-alpha',
  431. 'I' => 'upper-roman',
  432. 'i' => 'lower-roman',
  433. 'disc' => 'disc',
  434. 'square' => 'square',
  435. 'circle' => 'circle',
  436. );
  437. // $i: text, $i + 1: '/', $i + 2: tag, $i + 3: tail.
  438. for ($i = 0, $numParts = count($parts) - 1; $i < $numParts; $i += 4)
  439. {
  440. $tag = strtolower($parts[$i + 2]);
  441. $isOpeningTag = $parts[$i + 1] === '';
  442. if ($isOpeningTag)
  443. {
  444. switch ($tag)
  445. {
  446. case 'ol':
  447. case 'ul':
  448. // We have a problem, we're already in a list.
  449. if ($inList)
  450. {
  451. // Inject a list opener, we'll deal with the ol/ul next loop.
  452. array_splice($parts, $i, 0, array(
  453. '',
  454. '',
  455. str_repeat("\t", $listDepth) . '[li]',
  456. '',
  457. ));
  458. $numParts = count($parts) - 1;
  459. // The inlist status changes a bit.
  460. $inList = false;
  461. }
  462. // Just starting a new list.
  463. else
  464. {
  465. $inList = true;
  466. if ($tag === 'ol')
  467. $listType = 'decimal';
  468. elseif (preg_match('~type="?(' . implode('|', array_keys($listTypeMapping)) . ')"?~', $parts[$i + 3], $match) === 1)
  469. $listType = $listTypeMapping[$match[1]];
  470. else
  471. $listType = null;
  472. $listDepth++;
  473. $parts[$i + 2] = '[list' . ($listType === null ? '' : ' type=' . $listType) . ']' . "\n";
  474. $parts[$i + 3] = '';
  475. }
  476. break;
  477. case 'li':
  478. // This is how it should be: a list item inside the list.
  479. if ($inList)
  480. {
  481. $parts[$i + 2] = str_repeat("\t", $listDepth) . '[li]';
  482. $parts[$i + 3] = '';
  483. // Within a list item, it's almost as if you're outside.
  484. $inList = false;
  485. }
  486. // The li is no direct child of a list.
  487. else
  488. {
  489. // We are apparently in a list item.
  490. if ($listDepth > 0)
  491. {
  492. $parts[$i + 2] = '[/li]' . "\n" . str_repeat("\t", $listDepth) . '[li]';
  493. $parts[$i + 3] = '';
  494. }
  495. // We're not even near a list.
  496. else
  497. {
  498. // Quickly create a list with an item.
  499. $listDepth++;
  500. $parts[$i + 2] = '[list]' . "\n\t" . '[li]';
  501. $parts[$i + 3] = '';
  502. }
  503. }
  504. break;
  505. }
  506. }
  507. // Handle all the closing tags.
  508. else
  509. {
  510. switch ($tag)
  511. {
  512. case 'ol':
  513. case 'ul':
  514. // As we expected it, closing the list while we're in it.
  515. if ($inList)
  516. {
  517. $inList = false;
  518. $listDepth--;
  519. $parts[$i + 1] = '';
  520. $parts[$i + 2] = str_repeat("\t", $listDepth) . '[/list]';
  521. $parts[$i + 3] = '';
  522. }
  523. else
  524. {
  525. // We're in a list item.
  526. if ($listDepth > 0)
  527. {
  528. // Inject closure for this list item first.
  529. // The content of $parts[$i] is left as is!
  530. array_splice($parts, $i + 1, 0, array(
  531. '', // $i + 1
  532. '[/li]' . "\n", // $i + 2
  533. '', // $i + 3
  534. '', // $i + 4
  535. ));
  536. $numParts = count($parts) - 1;
  537. // Now that we've closed the li, we're in list space.
  538. $inList = true;
  539. }
  540. // We're not even in a list, ignore
  541. else
  542. {
  543. $parts[$i + 1] = '';
  544. $parts[$i + 2] = '';
  545. $parts[$i + 3] = '';
  546. }
  547. }
  548. break;
  549. case 'li':
  550. if ($inList)
  551. {
  552. // There's no use for a </li> after <ol> or <ul>, ignore.
  553. $parts[$i + 1] = '';
  554. $parts[$i + 2] = '';
  555. $parts[$i + 3] = '';
  556. }
  557. else
  558. {
  559. // Remove the trailing breaks from the list item.
  560. $parts[$i] = preg_replace('~\s*<br\s*' . '/?' . '>\s*$~', '', $parts[$i]);
  561. $parts[$i + 1] = '';
  562. $parts[$i + 2] = '[/li]' . "\n";
  563. $parts[$i + 3] = '';
  564. // And we're back in the [list] space.
  565. $inList = true;
  566. }
  567. break;
  568. }
  569. }
  570. // If we're in the [list] space, no content is allowed.
  571. if ($inList && trim(preg_replace('~\s*<br\s*' . '/?' . '>\s*~', '', $parts[$i + 4])) !== '')
  572. {
  573. // Fix it by injecting an extra list item.
  574. array_splice($parts, $i + 4, 0, array(
  575. '', // No content.
  576. '', // Opening tag.
  577. 'li', // It's a <li>.
  578. '', // No tail.
  579. ));
  580. $numParts = count($parts) - 1;
  581. }
  582. }
  583. $text = implode('', $parts);
  584. if ($inList)
  585. {
  586. $listDepth--;
  587. $text .= str_repeat("\t", $listDepth) . '[/list]';
  588. }
  589. for ($i = $listDepth; $i > 0; $i--)
  590. $text .= '[/li]' . "\n" . str_repeat("\t", $i - 1) . '[/list]';
  591. }
  592. // I love my own image...
  593. while (preg_match('~<img\s+([^<>]*)/*>~i', $text, $matches) === 1)
  594. {
  595. // Find the position of the image.
  596. $start_pos = strpos($text, $matches[0]);
  597. if ($start_pos === false)
  598. break;
  599. $end_pos = $start_pos + strlen($matches[0]);
  600. $params = '';
  601. $had_params = array();
  602. $src = '';
  603. $attrs = fetchTagAttributes($matches[1]);
  604. foreach ($attrs as $attrib => $value)
  605. {
  606. if (in_array($attrib, array('width', 'height')))
  607. $params .= ' ' . $attrib . '=' . (int) $value;
  608. elseif ($attrib == 'alt' && trim($value) != '')
  609. $params .= ' alt=' . trim($value);
  610. elseif ($attrib == 'src')
  611. $src = trim($value);
  612. }
  613. $tag = '';
  614. if (!empty($src))
  615. {
  616. // Attempt to fix the path in case it's not present.
  617. if (preg_match('~^https?://~i', $src) === 0 && is_array($parsedURL = parse_url($scripturl)) && isset($parsedURL['host']))
  618. {
  619. $baseURL = (isset($parsedURL['scheme']) ? $parsedURL['scheme'] : 'http') . '://' . $parsedURL['host'] . (empty($parsedURL['port']) ? '' : ':' . $parsedURL['port']);
  620. if (substr($src, 0, 1) === '/')
  621. $src = $baseURL . $src;
  622. else
  623. $src = $baseURL . (empty($parsedURL['path']) ? '/' : preg_replace('~/(?:index\\.php)?$~', '', $parsedURL['path'])) . '/' . $src;
  624. }
  625. $tag = '[img' . $params . ']' . $src . '[/img]';
  626. }
  627. // Replace the tag
  628. $text = substr($text, 0, $start_pos) . $tag . substr($text, $end_pos);
  629. }
  630. // The final bits are the easy ones - tags which map to tags which map to tags - etc etc.
  631. $tags = array(
  632. '~<b(\s(.)*?)*?' . '>~i' => '[b]',
  633. '~</b>~i' => '[/b]',
  634. '~<i(\s(.)*?)*?' . '>~i' => '[i]',
  635. '~</i>~i' => '[/i]',
  636. '~<u(\s(.)*?)*?' . '>~i' => '[u]',
  637. '~</u>~i' => '[/u]',
  638. '~<strong(\s(.)*?)*?' . '>~i' => '[b]',
  639. '~</strong>~i' => '[/b]',
  640. '~<em(\s(.)*?)*?' . '>~i' => '[i]',
  641. '~</em>~i' => '[/i]',
  642. '~<s(\s(.)*?)*?' . '>~i' => "[s]",
  643. '~</s>~i' => "[/s]",
  644. '~<strike(\s(.)*?)*?' . '>~i' => '[s]',
  645. '~</strike>~i' => '[/s]',
  646. '~<del(\s(.)*?)*?' . '>~i' => '[s]',
  647. '~</del>~i' => '[/s]',
  648. '~<center(\s(.)*?)*?' . '>~i' => '[center]',
  649. '~</center>~i' => '[/center]',
  650. '~<pre(\s(.)*?)*?' . '>~i' => '[pre]',
  651. '~</pre>~i' => '[/pre]',
  652. '~<sub(\s(.)*?)*?' . '>~i' => '[sub]',
  653. '~</sub>~i' => '[/sub]',
  654. '~<sup(\s(.)*?)*?' . '>~i' => '[sup]',
  655. '~</sup>~i' => '[/sup]',
  656. '~<tt(\s(.)*?)*?' . '>~i' => '[tt]',
  657. '~</tt>~i' => '[/tt]',
  658. '~<table(\s(.)*?)*?' . '>~i' => '[table]',
  659. '~</table>~i' => '[/table]',
  660. '~<tr(\s(.)*?)*?' . '>~i' => '[tr]',
  661. '~</tr>~i' => '[/tr]',
  662. '~<(td|th)\s[^<>]*?colspan="?(\d{1,2})"?.*?' . '>~ie' => 'str_repeat(\'[td][/td]\', $2 - 1) . \'[td]\'',
  663. '~<(td|th)(\s(.)*?)*?' . '>~i' => '[td]',
  664. '~</(td|th)>~i' => '[/td]',
  665. '~<br(?:\s[^<>]*?)?' . '>~i' => "\n",
  666. '~<hr[^<>]*>(\n)?~i' => "[hr]\n$1",
  667. '~(\n)?\\[hr\\]~i' => "\n[hr]",
  668. '~^\n\\[hr\\]~i' => "[hr]",
  669. '~<blockquote(\s(.)*?)*?' . '>~i' => "&lt;blockquote&gt;",
  670. '~</blockquote>~i' => "&lt;/blockquote&gt;",
  671. '~<ins(\s(.)*?)*?' . '>~i' => "&lt;ins&gt;",
  672. '~</ins>~i' => "&lt;/ins&gt;",
  673. );
  674. $text = preg_replace(array_keys($tags), array_values($tags), $text);
  675. // Please give us just a little more time.
  676. if (connection_aborted() && $context['server']['is_apache'])
  677. @apache_reset_timeout();
  678. // What about URL's - the pain in the ass of the tag world.
  679. while (preg_match('~<a\s+([^<>]*)>([^<>]*)</a>~i', $text, $matches) === 1)
  680. {
  681. // Find the position of the URL.
  682. $start_pos = strpos($text, $matches[0]);
  683. if ($start_pos === false)
  684. break;
  685. $end_pos = $start_pos + strlen($matches[0]);
  686. $tag_type = 'url';
  687. $href = '';
  688. $attrs = fetchTagAttributes($matches[1]);
  689. foreach ($attrs as $attrib => $value)
  690. {
  691. if ($attrib == 'href')
  692. {
  693. $href = trim($value);
  694. // Are we dealing with an FTP link?
  695. if (preg_match('~^ftps?://~', $href) === 1)
  696. $tag_type = 'ftp';
  697. // Or is this a link to an email address?
  698. elseif (substr($href, 0, 7) == 'mailto:')
  699. {
  700. $tag_type = 'email';
  701. $href = substr($href, 7);
  702. }
  703. // No http(s), so attempt to fix this potential relative URL.
  704. elseif (preg_match('~^https?://~i', $href) === 0 && is_array($parsedURL = parse_url($scripturl)) && isset($parsedURL['host']))
  705. {
  706. $baseURL = (isset($parsedURL['scheme']) ? $parsedURL['scheme'] : 'http') . '://' . $parsedURL['host'] . (empty($parsedURL['port']) ? '' : ':' . $parsedURL['port']);
  707. if (substr($href, 0, 1) === '/')
  708. $href = $baseURL . $href;
  709. else
  710. $href = $baseURL . (empty($parsedURL['path']) ? '/' : preg_replace('~/(?:index\\.php)?$~', '', $parsedURL['path'])) . '/' . $href;
  711. }
  712. }
  713. // External URL?
  714. if ($attrib == 'target' && $tag_type == 'url')
  715. {
  716. if (trim($value) == '_blank')
  717. $tag_type == 'iurl';
  718. }
  719. }
  720. $tag = '';
  721. if ($href != '')
  722. {
  723. if ($matches[2] == $href)
  724. $tag = '[' . $tag_type . ']' . $href . '[/' . $tag_type . ']';
  725. else
  726. $tag = '[' . $tag_type . '=' . $href . ']' . $matches[2] . '[/' . $tag_type . ']';
  727. }
  728. // Replace the tag
  729. $text = substr($text, 0, $start_pos) . $tag . substr($text, $end_pos);
  730. }
  731. $text = strip_tags($text);
  732. // Some tags often end up as just dummy tags - remove those.
  733. $text = preg_replace('~\[[bisu]\]\s*\[/[bisu]\]~', '', $text);
  734. // Fix up entities.
  735. $text = preg_replace('~&#38;~i', '&#38;#38;', $text);
  736. $text = legalise_bbc($text);
  737. return $text;
  738. }
  739. /**
  740. * Returns an array of attributes associated with a tag.
  741. *
  742. * @param string $text
  743. * @return string
  744. */
  745. function fetchTagAttributes($text)
  746. {
  747. $attribs = array();
  748. $key = $value = '';
  749. $strpos = 0;
  750. $tag_state = 0; // 0 = key, 1 = attribute with no string, 2 = attribute with string
  751. for ($i = 0; $i < strlen($text); $i++)
  752. {
  753. // We're either moving from the key to the attribute or we're in a string and this is fine.
  754. if ($text[$i] == '=')
  755. {
  756. if ($tag_state == 0)
  757. $tag_state = 1;
  758. elseif ($tag_state == 2)
  759. $value .= '=';
  760. }
  761. // A space is either moving from an attribute back to a potential key or in a string is fine.
  762. elseif ($text[$i] == ' ')
  763. {
  764. if ($tag_state == 2)
  765. $value .= ' ';
  766. elseif ($tag_state == 1)
  767. {
  768. $attribs[$key] = $value;
  769. $key = $value = '';
  770. $tag_state = 0;
  771. }
  772. }
  773. // A quote?
  774. elseif ($text[$i] == '"')
  775. {
  776. // Must be either going into or out of a string.
  777. if ($tag_state == 1)
  778. $tag_state = 2;
  779. else
  780. $tag_state = 1;
  781. }
  782. // Otherwise it's fine.
  783. else
  784. {
  785. if ($tag_state == 0)
  786. $key .= $text[$i];
  787. else
  788. $value .= $text[$i];
  789. }
  790. }
  791. // Anything left?
  792. if ($key != '' && $value != '')
  793. $attribs[$key] = $value;
  794. return $attribs;
  795. }
  796. /**
  797. * Retrieves a list of message icons.
  798. * - Based on the settings, the array will either contain a list of default
  799. * message icons or a list of custom message icons retrieved from the database.
  800. * - The board_id is needed for the custom message icons (which can be set for
  801. * each board individually).
  802. *
  803. * @param int $board_id
  804. * @return array
  805. */
  806. function getMessageIcons($board_id)
  807. {
  808. global $modSettings, $context, $txt, $settings, $smcFunc;
  809. if (empty($modSettings['messageIcons_enable']))
  810. {
  811. loadLanguage('Post');
  812. $icons = array(
  813. array('value' => 'xx', 'name' => $txt['standard']),
  814. array('value' => 'thumbup', 'name' => $txt['thumbs_up']),
  815. array('value' => 'thumbdown', 'name' => $txt['thumbs_down']),
  816. array('value' => 'exclamation', 'name' => $txt['excamation_point']),
  817. array('value' => 'question', 'name' => $txt['question_mark']),
  818. array('value' => 'lamp', 'name' => $txt['lamp']),
  819. array('value' => 'smiley', 'name' => $txt['icon_smiley']),
  820. array('value' => 'angry', 'name' => $txt['icon_angry']),
  821. array('value' => 'cheesy', 'name' => $txt['icon_cheesy']),
  822. array('value' => 'grin', 'name' => $txt['icon_grin']),
  823. array('value' => 'sad', 'name' => $txt['icon_sad']),
  824. array('value' => 'wink', 'name' => $txt['icon_wink']),
  825. array('value' => 'poll', 'name' => $txt['icon_poll']),
  826. );
  827. foreach ($icons as $k => $dummy)
  828. {
  829. $icons[$k]['url'] = $settings['images_url'] . '/post/' . $dummy['value'] . '.png';
  830. $icons[$k]['is_last'] = false;
  831. }
  832. }
  833. // Otherwise load the icons, and check we give the right image too...
  834. else
  835. {
  836. if (($temp = cache_get_data('posting_icons-' . $board_id, 480)) == null)
  837. {
  838. $request = $smcFunc['db_query']('select_message_icons', '
  839. SELECT title, filename
  840. FROM {db_prefix}message_icons
  841. WHERE id_board IN (0, {int:board_id})',
  842. array(
  843. 'board_id' => $board_id,
  844. )
  845. );
  846. $icon_data = array();
  847. while ($row = $smcFunc['db_fetch_assoc']($request))
  848. $icon_data[] = $row;
  849. $smcFunc['db_free_result']($request);
  850. $icons = array();
  851. foreach ($icon_data as $icon)
  852. {
  853. $icons[$icon['filename']] = array(
  854. 'value' => $icon['filename'],
  855. 'name' => $icon['title'],
  856. 'url' => $settings[file_exists($settings['theme_dir'] . '/images/post/' . $icon['filename'] . '.png') ? 'images_url' : 'default_images_url'] . '/post/' . $icon['filename'] . '.png',
  857. 'is_last' => false,
  858. );
  859. }
  860. cache_put_data('posting_icons-' . $board_id, $icons, 480);
  861. }
  862. else
  863. $icons = $temp;
  864. }
  865. return array_values($icons);
  866. }
  867. /**
  868. * Attempt to clean up illegal BBC caused by browsers like Opera which don't obey the rules
  869. * @param string $text
  870. * @return string
  871. */
  872. function legalise_bbc($text)
  873. {
  874. global $modSettings;
  875. // Don't care about the texts that are too short.
  876. if (strlen($text) < 3)
  877. return $text;
  878. // 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!
  879. // This will keep the order of tags that are open.
  880. $current_tags = array();
  881. // This will quickly let us see if the tag is active.
  882. $active_tags = array();
  883. // A list of tags that's disabled by the admin.
  884. $disabled = empty($modSettings['disabledBBC']) ? array() : array_flip(explode(',', strtolower($modSettings['disabledBBC'])));
  885. // Add flash if it's disabled as embedded tag.
  886. if (empty($modSettings['enableEmbeddedFlash']))
  887. $disabled['flash'] = true;
  888. // Get a list of all the tags that are not disabled.
  889. $all_tags = parse_bbc(false);
  890. $valid_tags = array();
  891. $self_closing_tags = array();
  892. foreach ($all_tags as $tag)
  893. {
  894. if (!isset($disabled[$tag['tag']]))
  895. $valid_tags[$tag['tag']] = !empty($tag['block_level']);
  896. if (isset($tag['type']) && $tag['type'] == 'closed')
  897. $self_closing_tags[] = $tag['tag'];
  898. }
  899. // Don't worry if we're in a code/nobbc.
  900. $in_code_nobbc = false;
  901. // 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!
  902. $align_tags = array('left', 'center', 'right', 'pre');
  903. // Remove those align tags that are not valid.
  904. $align_tags = array_intersect($align_tags, array_keys($valid_tags));
  905. // These keep track of where we are!
  906. if (!empty($align_tags) && count($matches = preg_split('~(\\[/?(?:' . implode('|', $align_tags) . ')\\])~', $text, -1, PREG_SPLIT_DELIM_CAPTURE)) > 1)
  907. {
  908. // The first one is never a tag.
  909. $isTag = false;
  910. // By default we're not inside a tag too.
  911. $insideTag = null;
  912. foreach ($matches as $i => $match)
  913. {
  914. // We're only interested in tags, not text.
  915. if ($isTag)
  916. {
  917. $isClosingTag = substr($match, 1, 1) === '/';
  918. $tagName = substr($match, $isClosingTag ? 2 : 1, -1);
  919. // We're closing the exact same tag that we opened.
  920. if ($isClosingTag && $insideTag === $tagName)
  921. $insideTag = null;
  922. // We're opening a tag and we're not yet inside one either
  923. elseif (!$isClosingTag && $insideTag === null)
  924. $insideTag = $tagName;
  925. // In all other cases, this tag must be invalid
  926. else
  927. unset($matches[$i]);
  928. }
  929. // The next one is gonna be the other one.
  930. $isTag = !$isTag;
  931. }
  932. // We're still inside a tag and had no chance for closure?
  933. if ($insideTag !== null)
  934. $matches[] = '[/' . $insideTag . ']';
  935. // And a complete text string again.
  936. $text = implode('', $matches);
  937. }
  938. // Quickly remove any tags which are back to back.
  939. $backToBackPattern = '~\\[(' . implode('|', array_diff(array_keys($valid_tags), array('td', 'anchor'))) . ')[^<>\\[\\]]*\\]\s*\\[/\\1\\]~';
  940. $lastlen = 0;
  941. while (strlen($text) !== $lastlen)
  942. $lastlen = strlen($text = preg_replace($backToBackPattern, '', $text));
  943. // Need to sort the tags my name length.
  944. uksort($valid_tags, 'sort_array_length');
  945. // These inline tags can compete with each other regarding style.
  946. $competing_tags = array(
  947. 'color',
  948. 'size',
  949. );
  950. // In case things changed above set these back to normal.
  951. $in_code_nobbc = false;
  952. $new_text_offset = 0;
  953. // These keep track of where we are!
  954. if (count($parts = preg_split(sprintf('~(\\[)(/?)(%1$s)((?:[\\s=][^\\]\\[]*)?\\])~', implode('|', array_keys($valid_tags))), $text, -1, PREG_SPLIT_DELIM_CAPTURE)) > 1)
  955. {
  956. // Start with just text.
  957. $isTag = false;
  958. // Start outside [nobbc] or [code] blocks.
  959. $inCode = false;
  960. $inNoBbc = false;
  961. // A buffer containing all opened inline elements.
  962. $inlineElements = array();
  963. // A buffer containing all opened block elements.
  964. $blockElements = array();
  965. // A buffer containing the opened inline elements that might compete.
  966. $competingElements = array();
  967. // $i: text, $i + 1: '[', $i + 2: '/', $i + 3: tag, $i + 4: tag tail.
  968. for ($i = 0, $n = count($parts) - 1; $i < $n; $i += 5)
  969. {
  970. $tag = $parts[$i + 3];
  971. $isOpeningTag = $parts[$i + 2] === '';
  972. $isClosingTag = $parts[$i + 2] === '/';
  973. $isBlockLevelTag = isset($valid_tags[$tag]) && $valid_tags[$tag] && !in_array($tag, $self_closing_tags);
  974. $isCompetingTag = in_array($tag, $competing_tags);
  975. // Check if this might be one of those cleaned out tags.
  976. if ($tag === '')
  977. continue;
  978. // Special case: inside [code] blocks any code is left untouched.
  979. elseif ($tag === 'code')
  980. {
  981. // We're inside a code block and closing it.
  982. if ($inCode && $isClosingTag)
  983. {
  984. $inCode = false;
  985. // Reopen tags that were closed before the code block.
  986. if (!empty($inlineElements))
  987. $parts[$i + 4] .= '[' . implode('][', array_keys($inlineElements)) . ']';
  988. }
  989. // We're outside a coding and nobbc block and opening it.
  990. elseif (!$inCode && !$inNoBbc && $isOpeningTag)
  991. {
  992. // If there are still inline elements left open, close them now.
  993. if (!empty($inlineElements))
  994. {
  995. $parts[$i] .= '[/' . implode('][/', array_reverse($inlineElements)) . ']';
  996. //$inlineElements = array();
  997. }
  998. $inCode = true;
  999. }
  1000. // Nothing further to do.
  1001. continue;
  1002. }
  1003. // Special case: inside [nobbc] blocks any BBC is left untouched.
  1004. elseif ($tag === 'nobbc')
  1005. {
  1006. // We're inside a nobbc block and closing it.
  1007. if ($inNoBbc && $isClosingTag)
  1008. {
  1009. $inNoBbc = false;
  1010. // Some inline elements might've been closed that need reopening.
  1011. if (!empty($inlineElements))
  1012. $parts[$i + 4] .= '[' . implode('][', array_keys($inlineElements)) . ']';
  1013. }
  1014. // We're outside a nobbc and coding block and opening it.
  1015. elseif (!$inNoBbc && !$inCode && $isOpeningTag)
  1016. {
  1017. // Can't have inline elements still opened.
  1018. if (!empty($inlineElements))
  1019. {
  1020. $parts[$i] .= '[/' . implode('][/', array_reverse($inlineElements)) . ']';
  1021. //$inlineElements = array();
  1022. }
  1023. $inNoBbc = true;
  1024. }
  1025. continue;
  1026. }
  1027. // So, we're inside one of the special blocks: ignore any tag.
  1028. elseif ($inCode || $inNoBbc)
  1029. continue;
  1030. // We're dealing with an opening tag.
  1031. if ($isOpeningTag)
  1032. {
  1033. // Everyting inside the square brackets of the opening tag.
  1034. $elementContent = $parts[$i + 3] . substr($parts[$i + 4], 0, -1);
  1035. // A block level opening tag.
  1036. if ($isBlockLevelTag)
  1037. {
  1038. // Are there inline elements still open?
  1039. if (!empty($inlineElements))
  1040. {
  1041. // Close all the inline tags, a block tag is coming...
  1042. $parts[$i] .= '[/' . implode('][/', array_reverse($inlineElements)) . ']';
  1043. // Now open them again, we're inside the block tag now.
  1044. $parts[$i + 5] = '[' . implode('][', array_keys($inlineElements)) . ']' . $parts[$i + 5];
  1045. }
  1046. $blockElements[] = $tag;
  1047. }
  1048. // Inline opening tag.
  1049. elseif (!in_array($tag, $self_closing_tags))
  1050. {
  1051. // Can't have two opening elements with the same contents!
  1052. if (isset($inlineElements[$elementContent]))
  1053. {
  1054. // Get rid of this tag.
  1055. $parts[$i + 1] = $parts[$i + 2] = $parts[$i + 3] = $parts[$i + 4] = '';
  1056. // Now try to find the corresponding closing tag.
  1057. $curLevel = 1;
  1058. for ($j = $i + 5, $m = count($parts) - 1; $j < $m; $j += 5)
  1059. {
  1060. // Find the tags with the same tagname
  1061. if ($parts[$j + 3] === $tag)
  1062. {
  1063. // If it's an opening tag, increase the level.
  1064. if ($parts[$j + 2] === '')
  1065. $curLevel++;
  1066. // A closing tag, decrease the level.
  1067. else
  1068. {
  1069. $curLevel--;
  1070. // Gotcha! Clean out this closing tag gone rogue.
  1071. if ($curLevel === 0)
  1072. {
  1073. $parts[$j + 1] = $parts[$j + 2] = $parts[$j + 3] = $parts[$j + 4] = '';
  1074. break;
  1075. }
  1076. }
  1077. }
  1078. }
  1079. }
  1080. // Otherwise, add this one to the list.
  1081. else
  1082. {
  1083. if ($isCompetingTag)
  1084. {
  1085. if (!isset($competingElements[$tag]))
  1086. $competingElements[$tag] = array();
  1087. $competingElements[$tag][] = $parts[$i + 4];
  1088. if (count($competingElements[$tag]) > 1)
  1089. $parts[$i] .= '[/' . $tag . ']';
  1090. }
  1091. $inlineElements[$elementContent] = $tag;
  1092. }
  1093. }
  1094. }
  1095. // Closing tag.
  1096. else
  1097. {
  1098. // Closing the block tag.
  1099. if ($isBlockLevelTag)
  1100. {
  1101. // Close the elements that should've been closed by closing this tag.
  1102. if (!empty($blockElements))
  1103. {
  1104. $addClosingTags = array();
  1105. while ($element = array_pop($blockElements))
  1106. {
  1107. if ($element === $tag)
  1108. break;
  1109. // Still a block tag was open not equal to this tag.
  1110. $addClosingTags[] = $element['type'];
  1111. }
  1112. if (!empty($addClosingTags))
  1113. $parts[$i + 1] = '[/' . implode('][/', array_reverse($addClosingTags)) . ']' . $parts[$i + 1];
  1114. // Apparently the closing tag was not found on the stack.
  1115. if (!is_string($element) || $element !== $tag)
  1116. {
  1117. // Get rid of this particular closing tag, it was never opened.
  1118. $parts[$i + 1] = substr($parts[$i + 1], 0, -1);
  1119. $parts[$i + 2] = $parts[$i + 3] = $parts[$i + 4] = '';
  1120. continue;
  1121. }
  1122. }
  1123. else
  1124. {
  1125. // Get rid of this closing tag!
  1126. $parts[$i + 1] = $parts[$i + 2] = $parts[$i + 3] = $parts[$i + 4] = '';
  1127. continue;
  1128. }
  1129. // Inline elements are still left opened?
  1130. if (!empty($inlineElements))
  1131. {
  1132. // Close them first..
  1133. $parts[$i] .= '[/' . implode('][/', array_reverse($inlineElements)) . ']';
  1134. // Then reopen them.
  1135. $parts[$i + 5] = '[' . implode('][', array_keys($inlineElements)) . ']' . $parts[$i + 5];
  1136. }
  1137. }
  1138. // Inline tag.
  1139. else
  1140. {
  1141. // Are we expecting this tag to end?
  1142. if (in_array($tag, $inlineElements))
  1143. {
  1144. foreach (array_reverse($inlineElements, true) as $tagContentToBeClosed => $tagToBeClosed)
  1145. {
  1146. // Closing it one way or the other.
  1147. unset($inlineElements[$tagContentToBeClosed]);
  1148. // Was this the tag we were looking for?
  1149. if ($tagToBeClosed === $tag)
  1150. break;
  1151. // Nope, close it and look further!
  1152. else
  1153. $parts[$i] .= '[/' . $tagToBeClosed . ']';
  1154. }
  1155. if ($isCompetingTag && !empty($competingElements[$tag]))
  1156. {
  1157. array_pop($competingElements[$tag]);
  1158. if (count($competingElements[$tag]) > 0)
  1159. $parts[$i + 5] = '[' . $tag . $competingElements[$tag][count($competingElements[$tag]) - 1] . $parts[$i + 5];
  1160. }
  1161. }
  1162. // Unexpected closing tag, ex-ter-mi-nate.
  1163. else
  1164. $parts[$i + 1] = $parts[$i + 2] = $parts[$i + 3] = $parts[$i + 4] = '';
  1165. }
  1166. }
  1167. }
  1168. // Close the code tags.
  1169. if ($inCode)
  1170. $parts[$i] .= '[/code]';
  1171. // The same for nobbc tags.
  1172. elseif ($inNoBbc)
  1173. $parts[$i] .= '[/nobbc]';
  1174. // Still inline tags left unclosed? Close them now, better late than never.
  1175. elseif (!empty($inlineElements))
  1176. $parts[$i] .= '[/' . implode('][/', array_reverse($inlineElements)) . ']';
  1177. // Now close the block elements.
  1178. if (!empty($blockElements))
  1179. $parts[$i] .= '[/' . implode('][/', array_reverse($blockElements)) . ']';
  1180. $text = implode('', $parts);
  1181. }
  1182. // Final clean up of back to back tags.
  1183. $lastlen = 0;
  1184. while (strlen($text) !== $lastlen)
  1185. $lastlen = strlen($text = preg_replace($backToBackPattern, '', $text));
  1186. return $text;
  1187. }
  1188. /**
  1189. * A help function for legalise_bbc for sorting arrays based on length.
  1190. * @param string $a
  1191. * @param string $b
  1192. * @return int 1 or -1
  1193. */
  1194. function sort_array_length($a, $b)
  1195. {
  1196. return strlen($a) < strlen($b) ? 1 : -1;
  1197. }
  1198. /**
  1199. * Compatibility function - used in 1.1 for showing a post box.
  1200. *
  1201. * @param string $msg
  1202. * @return string
  1203. */
  1204. function theme_postbox($msg)
  1205. {
  1206. global $context;
  1207. return template_control_richedit($context['post_box_name']);
  1208. }
  1209. /**
  1210. * Creates a box that can be used for richedit stuff like BBC, Smileys etc.
  1211. * @param array $editorOptions
  1212. */
  1213. function create_control_richedit($editorOptions)
  1214. {
  1215. global $txt, $modSettings, $options, $smcFunc;
  1216. global $context, $settings, $user_info, $sourcedir, $scripturl;
  1217. // Load the Post language file... for the moment at least.
  1218. loadLanguage('Post');
  1219. // Every control must have a ID!
  1220. assert(isset($editorOptions['id']));
  1221. assert(isset($editorOptions['value']));
  1222. // Is this the first richedit - if so we need to ensure some template stuff is initialised.
  1223. if (empty($context['controls']['richedit']))
  1224. {
  1225. // Some general stuff.
  1226. $settings['smileys_url'] = $modSettings['smileys_url'] . '/' . $user_info['smiley_set'];
  1227. // This really has some WYSIWYG stuff.
  1228. loadTemplate('GenericControls', isBrowser('ie') ? 'editor_ie' : 'editor');
  1229. $context['html_headers'] .= '
  1230. <script type="text/javascript"><!-- // --><![CDATA[
  1231. var smf_smileys_url = \'' . $settings['smileys_url'] . '\';
  1232. var oEditorStrings= {
  1233. wont_work: \'' . addcslashes($txt['rich_edit_wont_work'], "'") . '\',
  1234. func_disabled: \'' . addcslashes($txt['rich_edit_function_disabled'], "'") . '\',
  1235. prompt_text_email: \'' . addcslashes($txt['prompt_text_email'], "'") . '\',
  1236. prompt_text_ftp: \'' . addcslashes($txt['prompt_text_ftp'], "'") . '\',
  1237. prompt_text_url: \'' . addcslashes($txt['prompt_text_url'], "'") . '\',
  1238. prompt_text_img: \'' . addcslashes($txt['prompt_text_img'], "'") . '\'
  1239. }
  1240. // ]]></script>
  1241. <script type="text/javascript" src="' . $settings['default_theme_url'] . '/scripts/editor.js?alp21"></script>';
  1242. $context['show_spellchecking'] = !empty($modSettings['enableSpellChecking']) && function_exists('pspell_new');
  1243. if ($context['show_spellchecking'])
  1244. {
  1245. $context['html_headers'] .= '
  1246. <script type="text/javascript" src="' . $settings['default_theme_url'] . '/scripts/spellcheck.js?alp21"></script>';
  1247. // Some hidden information is needed in order to make the spell checking work.
  1248. if (!isset($_REQUEST['xml']))
  1249. $context['insert_after_template'] .= '
  1250. <form name="spell_form" id="spell_form" method="post" accept-charset="' . $context['character_set'] . '" target="spellWindow" action="' . $scripturl . '?action=spellcheck">
  1251. <input type="hidden" name="spellstring" value="" />
  1252. </form>';
  1253. // Also make sure that spell check works with rich edit.
  1254. $context['html_headers'] .= '
  1255. <script type="text/javascript"><!-- // --><![CDATA[
  1256. function spellCheckDone()
  1257. {
  1258. for (i = 0; i < smf_editorArray.length; i++)
  1259. setTimeout("smf_editorArray[" + i + "].spellCheckEnd()", 150);
  1260. }
  1261. // ]]></script>';
  1262. }
  1263. }
  1264. // Start off the editor...
  1265. $context['controls']['richedit'][$editorOptions['id']] = array(
  1266. 'id' => $editorOptions['id'],
  1267. 'value' => $editorOptions['value'],
  1268. 'rich_value' => bbc_to_html($editorOptions['value']),
  1269. 'rich_active' => empty($modSettings['disable_wysiwyg']) && (!empty($options['wysiwyg_default']) || !empty($editorOptions['force_rich']) || !empty($_REQUEST[$editorOptions['id'] . '_mode'])),
  1270. 'disable_smiley_box' => !empty($editorOptions['disable_smiley_box']),
  1271. 'columns' => isset($editorOptions['columns']) ? $editorOptions['columns'] : 60,
  1272. 'rows' => isset($editorOptions['rows']) ? $editorOptions['rows'] : 12,
  1273. 'width' => isset($editorOptions['width']) ? $editorOptions['width'] : '70%',
  1274. 'height' => isset($editorOptions['height']) ? $editorOptions['height'] : '150px',
  1275. 'form' => isset($editorOptions['form']) ? $editorOptions['form'] : 'postmodify',
  1276. 'bbc_level' => !empty($editorOptions['bbc_level']) ? $editorOptions['bbc_level'] : 'full',
  1277. 'preview_type' => isset($editorOptions['preview_type']) ? (int) $editorOptions['preview_type'] : 1,
  1278. 'labels' => !empty($editorOptions['labels']) ? $editorOptions['labels'] : array(),
  1279. );
  1280. // Switch between default images and back... mostly in case you don't have an PersonalMessage template, but do have a Post template.
  1281. if (isset($settings['use_default_images']) && $settings['use_default_images'] == 'defaults' && isset($settings['default_template']))
  1282. {
  1283. $temp1 = $settings['theme_url'];
  1284. $settings['theme_url'] = $settings['default_theme_url'];
  1285. $temp2 = $settings['images_url'];
  1286. $settings['images_url'] = $settings['default_images_url'];
  1287. $temp3 = $settings['theme_dir'];
  1288. $settings['theme_dir'] = $settings['default_theme_dir'];
  1289. }
  1290. if (empty($context['bbc_tags']))
  1291. {
  1292. // 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!
  1293. $context['bbc_tags'] = array();
  1294. $context['bbc_tags'][] = array(
  1295. array(
  1296. 'image' => 'bold',
  1297. 'code' => 'b',
  1298. 'before' => '[b]',
  1299. 'after' => '[/b]',
  1300. 'description' => $txt['bold'],
  1301. ),
  1302. array(
  1303. 'image' => 'italicize',
  1304. 'code' => 'i',
  1305. 'before' => '[i]',
  1306. 'after' => '[/i]',
  1307. 'description' => $txt['italic'],
  1308. ),
  1309. array(
  1310. 'image' => 'underline',
  1311. 'code' => 'u',
  1312. 'before' => '[u]',
  1313. 'after' => '[/u]',
  1314. 'description' => $txt['underline']
  1315. ),
  1316. array(
  1317. 'image' => 'strike',
  1318. 'code' => 's',
  1319. 'before' => '[s]',
  1320. 'after' => '[/s]',
  1321. 'description' => $txt['strike']
  1322. ),
  1323. array(),
  1324. array(
  1325. 'image' => 'pre',
  1326. 'code' => 'pre',
  1327. 'before' => '[pre]',
  1328. 'after' => '[/pre]',
  1329. 'description' => $txt['preformatted']
  1330. ),
  1331. array(
  1332. 'image' => 'left',
  1333. 'code' => 'left',
  1334. 'before' => '[left]',
  1335. 'after' => '[/left]',
  1336. 'description' => $txt['left_align']
  1337. ),
  1338. array(
  1339. 'image' => 'center',
  1340. 'code' => 'center',
  1341. 'before' => '[center]',
  1342. 'after' => '[/center]',
  1343. 'description' => $txt['center']
  1344. ),
  1345. array(
  1346. 'image' => 'right',
  1347. 'code' => 'right',
  1348. 'before' => '[right]',
  1349. 'after' => '[/right]',
  1350. 'description' => $txt['right_align']
  1351. ),
  1352. );
  1353. $context['bbc_tags'][] = array(
  1354. array(
  1355. 'image' => 'flash',
  1356. 'code' => 'flash',
  1357. 'before' => '[flash=200,200]',
  1358. 'after' => '[/flash]',
  1359. 'description' => $txt['flash']
  1360. ),
  1361. array(
  1362. 'image' => 'img',
  1363. 'code' => 'img',
  1364. 'before' => '[img]',
  1365. 'after' => '[/img]',
  1366. 'description' => $txt['image']
  1367. ),
  1368. array(
  1369. 'image' => 'url',
  1370. 'code' => 'url',
  1371. 'before' => '[url]',
  1372. 'after' => '[/url]',
  1373. 'description' => $txt['hyperlink']
  1374. ),
  1375. array(
  1376. 'image' => 'email',
  1377. 'code' => 'email',
  1378. 'before' => '[email]',
  1379. 'after' => '[/email]',
  1380. 'description' => $txt['insert_email']
  1381. ),
  1382. array(
  1383. 'image' => 'ftp',
  1384. 'code' => 'ftp',
  1385. 'before' => '[ftp]',
  1386. 'after' => '[/ftp]',
  1387. 'description' => $txt['ftp']
  1388. ),
  1389. array(),
  1390. array(
  1391. 'image' => 'glow',
  1392. 'code' => 'glow',
  1393. 'before' => '[glow=red,2,300]',
  1394. 'after' => '[/glow]',
  1395. 'description' => $txt['glow']
  1396. ),
  1397. array(
  1398. 'image' => 'shadow',
  1399. 'code' => 'shadow',
  1400. 'before' => '[shadow=red,left]',
  1401. 'after' => '[/shadow]',
  1402. 'description' => $txt['shadow']
  1403. ),
  1404. array(
  1405. 'image' => 'move',
  1406. 'code' => 'move',
  1407. 'before' => '[move]',
  1408. 'after' => '[/move]',
  1409. 'description' => $txt['marquee']
  1410. ),
  1411. array(),
  1412. array(
  1413. 'image' => 'sup',
  1414. 'code' => 'sup',
  1415. 'before' => '[sup]',
  1416. 'after' => '[/sup]',
  1417. 'description' => $txt['superscript']
  1418. ),
  1419. array(
  1420. 'image' => 'sub',
  1421. 'code' => 'sub',
  1422. 'before' => '[sub]',
  1423. 'after' => '[/sub]',
  1424. 'description' => $txt['subscript']
  1425. ),
  1426. array(
  1427. 'image' => 'tele',
  1428. 'code' => 'tt',
  1429. 'before' => '[tt]',
  1430. 'after' => '[/tt]',
  1431. 'description' => $txt['teletype']
  1432. ),
  1433. array(),
  1434. array(
  1435. 'image' => 'table',
  1436. 'code' => 'table',
  1437. 'before' => '[table]\n[tr]\n[td]',
  1438. 'after' => '[/td]\n[/tr]\n[/table]',
  1439. 'description' => $txt['table']
  1440. ),
  1441. array(
  1442. 'image' => 'code',
  1443. 'code' => 'code',
  1444. 'before' => '[code]',
  1445. 'after' => '[/code]',
  1446. 'description' => $txt['bbc_code']
  1447. ),
  1448. array(
  1449. 'image' => 'quote',
  1450. 'code' => 'quote',
  1451. 'before' => '[quote]',
  1452. 'after' => '[/quote]',
  1453. 'description' => $txt['bbc_quote']
  1454. ),
  1455. array(),
  1456. array(
  1457. 'image' => 'list',
  1458. 'code' => 'list',
  1459. 'before' => '[list]\n[li]',
  1460. 'after' => '[/li]\n[li][/li]\n[/list]',
  1461. 'description' => $txt['list_unordered']
  1462. ),
  1463. array(
  1464. 'image' => 'orderlist',
  1465. 'code' => 'orderlist',
  1466. 'before' => '[list type=decimal]\n[li]',
  1467. 'after' => '[/li]\n[li][/li]\n[/list]',
  1468. 'description' => $txt['list_ordered']
  1469. ),
  1470. array(
  1471. 'image' => 'hr',
  1472. 'code' => 'hr',
  1473. 'before' => '[hr]',
  1474. 'description' => $txt['horizontal_rule']
  1475. ),
  1476. );
  1477. // Allow mods to modify BBC buttons.
  1478. call_integration_hook('integrate_bbc_buttons');
  1479. // Show the toggle?
  1480. if (empty($modSettings['disable_wysiwyg']))
  1481. {
  1482. $context['bbc_tags'][count($context['bbc_tags']) - 1][] = array();
  1483. $context['bbc_tags'][count($context['bbc_tags']) - 1][] = array(
  1484. 'image' => 'unformat',
  1485. 'code' => 'unformat',
  1486. 'before' => '',
  1487. 'description' => $txt['unformat_text'],
  1488. );
  1489. $context['bbc_tags'][count($context['bbc_tags']) - 1][] = array(
  1490. 'image' => 'toggle',
  1491. 'code' => 'toggle',
  1492. 'before' => '',
  1493. 'description' => $txt['toggle_view'],
  1494. );
  1495. }
  1496. foreach ($context['bbc_tags'] as $row => $tagRow)
  1497. $context['bbc_tags'][$row][count($tagRow) - 1]['isLast'] = true;
  1498. }
  1499. // Initialize smiley array... if not loaded before.
  1500. if (empty($context['smileys']) && empty($editorOptions['disable_smiley_box']))
  1501. {
  1502. $context['smileys'] = array(
  1503. 'postform' => array(),
  1504. 'popup' => array(),
  1505. );
  1506. // Load smileys - don't bother to run a query if we're not using the database's ones anyhow.
  1507. if (empty($modSettings['smiley_enable']) && $user_info['smiley_set'] != 'none')
  1508. $context['smileys']['postform'][] = array(
  1509. 'smileys' => array(
  1510. array(
  1511. 'code' => ':)',
  1512. 'filename' => 'smiley.gif',
  1513. 'description' => $txt['icon_smiley'],
  1514. ),
  1515. array(
  1516. 'code' => ';)',
  1517. 'filename' => 'wink.gif',
  1518. 'description' => $txt['icon_wink'],
  1519. ),
  1520. array(
  1521. 'code' => ':D',
  1522. 'filename' => 'cheesy.gif',
  1523. 'description' => $txt['icon_cheesy'],
  1524. ),
  1525. array(
  1526. 'code' => ';D',
  1527. 'filename' => 'grin.gif',
  1528. 'description' => $txt['icon_grin']
  1529. ),
  1530. array(
  1531. 'code' => '>:(',
  1532. 'filename' => 'angry.gif',
  1533. 'description' => $txt['icon_angry'],
  1534. ),
  1535. array(
  1536. 'code' => ':(',
  1537. 'filename' => 'sad.gif',
  1538. 'description' => $txt['icon_sad'],
  1539. ),
  1540. array(
  1541. 'code' => ':o',
  1542. 'filename' => 'shocked.gif',
  1543. 'description' => $txt['icon_shocked'],
  1544. ),
  1545. array(
  1546. 'code' => '8)',
  1547. 'filename' => 'cool.gif',
  1548. 'description' => $txt['icon_cool'],
  1549. ),
  1550. array(
  1551. 'code' => '???',
  1552. 'filename' => 'huh.gif',
  1553. 'description' => $txt['icon_huh'],
  1554. ),
  1555. array(
  1556. 'code' => '::)',
  1557. 'filename' => 'rolleyes.gif',
  1558. 'description' => $txt['icon_rolleyes'],
  1559. ),
  1560. array(
  1561. 'code' => ':P',
  1562. 'filename' => 'tongue.gif',
  1563. 'description' => $txt['icon_tongue'],
  1564. ),
  1565. array(
  1566. 'code' => ':-[',
  1567. 'filename' => 'embarrassed.gif',
  1568. 'description' => $txt['icon_embarrassed'],
  1569. ),
  1570. array(
  1571. 'code' => ':-X',
  1572. 'filename' => 'lipsrsealed.gif',
  1573. 'description' => $txt['icon_lips'],
  1574. ),
  1575. array(
  1576. 'code' => ':-\\',
  1577. 'filename' => 'undecided.gif',
  1578. 'description' => $txt['icon_undecided'],
  1579. ),
  1580. array(
  1581. 'code' => ':-*',
  1582. 'filename' => 'kiss.gif',
  1583. 'description' => $txt['icon_kiss'],
  1584. ),
  1585. array(
  1586. 'code' => ':\'(',
  1587. 'filename' => 'cry.gif',
  1588. 'description' => $txt['icon_cry'],
  1589. 'isLast' => true,
  1590. ),
  1591. ),
  1592. 'isLast' => true,
  1593. );
  1594. elseif ($user_info['smiley_set'] != 'none')
  1595. {
  1596. if (($temp = cache_get_data('posting_smileys', 480)) == null)
  1597. {
  1598. $request = $smcFunc['db_query']('', '
  1599. SELECT code, filename, description, smiley_row, hidden
  1600. FROM {db_prefix}smileys
  1601. WHERE hidden IN (0, 2)
  1602. ORDER BY smiley_row, smiley_order',
  1603. array(
  1604. )
  1605. );
  1606. while ($row = $smcFunc['db_fetch_assoc']($request))
  1607. {
  1608. $row['filename'] = htmlspecialchars($row['filename']);
  1609. $row['description'] = htmlspecialchars($row['description']);
  1610. $context['smileys'][empty($row['hidden']) ? 'postform' : 'popup'][$row['smiley_row']]['smileys'][] = $row;
  1611. }
  1612. $smcFunc['db_free_result']($request);
  1613. foreach ($context['smileys'] as $section => $smileyRows)
  1614. {
  1615. foreach ($smileyRows as $rowIndex => $smileys)
  1616. $context['smileys'][$section][$rowIndex]['smileys'][count($smileys['smileys']) - 1]['isLast'] = true;
  1617. if (!empty($smileyRows))
  1618. $context['smileys'][$section][count($smileyRows) - 1]['isLast'] = true;
  1619. }
  1620. cache_put_data('posting_smileys', $context['smileys'], 480);
  1621. }
  1622. else
  1623. $context['smileys'] = $temp;
  1624. }
  1625. }
  1626. // Set a flag so the sub template knows what to do...
  1627. $context['show_bbc'] = !empty($modSettings['enableBBC']) && !empty($settings['show_bbc']);
  1628. // Generate a list of buttons that shouldn't be shown - this should be the fastest way to do this.
  1629. $disabled_tags = array();
  1630. if (!empty($modSettings['disabledBBC']))
  1631. $disabled_tags = explode(',', $modSettings['disabledBBC']);
  1632. if (empty($modSettings['enableEmbeddedFlash']))
  1633. $disabled_tags[] = 'flash';
  1634. foreach ($disabled_tags as $tag)
  1635. {
  1636. if ($tag == 'list')
  1637. $context['disabled_tags']['orderlist'] = true;
  1638. $context['disabled_tags'][trim($tag)] = true;
  1639. }
  1640. // Switch the URLs back... now we're back to whatever the main sub template is. (like folder in PersonalMessage.)
  1641. if (isset($settings['use_default_images']) && $settings['use_default_images'] == 'defaults' && isset($settings['default_template']))
  1642. {
  1643. $settings['theme_url'] = $temp1;
  1644. $settings['images_url'] = $temp2;
  1645. $settings['theme_dir'] = $temp3;
  1646. }
  1647. }
  1648. /**
  1649. * Create a anti-bot verification control?
  1650. * @param array &$verificationOptions
  1651. * @param bool $do_test = false
  1652. */
  1653. function create_control_verification(&$verificationOptions, $do_test = false)
  1654. {
  1655. global $txt, $modSettings, $options, $smcFunc;
  1656. global $context, $settings, $user_info, $sourcedir, $scripturl;
  1657. // First verification means we need to set up some bits...
  1658. if (empty($context['controls']['verification']))
  1659. {
  1660. // The template
  1661. loadTemplate('GenericControls');
  1662. // Some javascript ma'am?
  1663. if (!empty($verificationOptions['override_visual']) || (!empty($modSettings['visual_verification_type']) && !isset($verificationOptions['override_visual'])))
  1664. $context['html_headers'] .= '
  1665. <script type="text/javascript" src="' . $settings['default_theme_url'] . '/scripts/captcha.js"></script>';
  1666. $context['use_graphic_library'] = in_array('gd', get_loaded_extensions());
  1667. // Skip I, J, L, O, Q, S and Z.
  1668. $context['standard_captcha_range'] = array_merge(range('A', 'H'), array('K', 'M', 'N', 'P', 'R'), range('T', 'Y'));
  1669. }
  1670. // Always have an ID.
  1671. assert(isset($verificationOptions['id']));
  1672. $isNew = !isset($context['controls']['verification'][$verificationOptions['id']]);
  1673. // Log this into our collection.
  1674. if ($isNew)
  1675. $context['controls']['verification'][$verificationOptions['id']] = array(
  1676. 'id' => $verificationOptions['id'],
  1677. 'show_visual' => !empty($verificationOptions['override_visual']) || (!empty($modSettings['visual_verification_type']) && !isset($verificationOptions['override_visual'])),
  1678. 'number_questions' => isset($verificationOptions['override_qs']) ? $verificationOptions['override_qs'] : (!empty($modSettings['qa_verification_number']) ? $modSettings['qa_verification_number'] : 0),
  1679. 'max_errors' => isset($verificationOptions['max_errors']) ? $verificationOptions['max_errors'] : 3,
  1680. 'image_href' => $scripturl . '?action=verificationcode;vid=' . $verificationOptions['id'] . ';rand=' . md5(mt_rand()),
  1681. 'text_value' => '',
  1682. 'questions' => array(),
  1683. );
  1684. $thisVerification = &$context['controls']['verification'][$verificationOptions['id']];
  1685. // Add javascript for the object.
  1686. if ($context['controls']['verification'][$verificationOptions['id']]['show_visual'] && !WIRELESS)
  1687. $context['insert_after_template'] .= '
  1688. <script type="text/javascript"><!-- // --><![CDATA[
  1689. var verification' . $verificationOptions['id'] . 'Handle = new smfCaptcha("' . $thisVerification['image_href'] . '", "' . $verificationOptions['id'] . '", ' . ($context['use_graphic_library'] ? 1 : 0) . ');
  1690. // ]]></script>';
  1691. // Is there actually going to be anything?
  1692. if (empty($thisVerification['show_visual']) && empty($thisVerification['number_questions']))
  1693. return false;
  1694. elseif (!$isNew && !$do_test)
  1695. return true;
  1696. // If we want questions do we have a cache of all the IDs?
  1697. if (!empty($thisVerification['number_questions']) && empty($modSettings['question_id_cache']))
  1698. {
  1699. if (($modSettings['question_id_cache'] = cache_get_data('verificationQuestionIds', 300)) == null)
  1700. {
  1701. $request = $smcFunc['db_query']('', '
  1702. SELECT id_comment
  1703. FROM {db_prefix}log_comments
  1704. WHERE comment_type = {string:ver_test}',
  1705. array(
  1706. 'ver_test' => 'ver_test',
  1707. )
  1708. );
  1709. $modSettings['question_id_cache'] = array();
  1710. while ($row = $smcFunc['db_fetch_assoc']($request))
  1711. $modSettings['question_id_cache'][] = $row['id_comment'];
  1712. $smcFunc['db_free_result']($request);
  1713. if (!empty($modSettings['cache_enable']))
  1714. cache_put_data('verificationQuestionIds', $modSettings['question_id_cache'], 300);
  1715. }
  1716. }
  1717. if (!isset($_SESSION[$verificationOptions['id'] . '_vv']))
  1718. $_SESSION[$verificationOptions['id'] . '_vv'] = array();
  1719. // Do we need to refresh the verification?
  1720. 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']))
  1721. $force_refresh = true;
  1722. else
  1723. $force_refresh = false;
  1724. // This can also force a fresh, although unlikely.
  1725. if (($thisVerification['show_visual'] && empty($_SESSION[$verificationOptions['id'] . '_vv']['code'])) || ($thisVerification['number_questions'] && empty($_SESSION[$verificationOptions['id'] . '_vv']['q'])))
  1726. $force_refresh = true;
  1727. $verification_errors = array();
  1728. // Start with any testing.
  1729. if ($do_test)
  1730. {
  1731. // This cannot happen!
  1732. if (!isset($_SESSION[$verificationOptions['id'] . '_vv']['count']))
  1733. fatal_lang_error('no_access', false);
  1734. // ... nor this!
  1735. if ($thisVerification['number_questions'] && (!isset($_SESSION[$verificationOptions['id'] . '_vv']['q']) || !isset($_REQUEST[$verificationOptions['id'] . '_vv']['q'])))
  1736. fatal_lang_error('no_access', false);
  1737. 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']))
  1738. $verification_errors[] = 'wrong_verification_code';
  1739. if ($thisVerification['number_questions'])
  1740. {
  1741. // Get the answers and see if they are all right!
  1742. $request = $smcFunc['db_query']('', '
  1743. SELECT id_comment, recipient_name AS answer
  1744. FROM {db_prefix}log_comments
  1745. WHERE comment_type = {string:ver_test}
  1746. AND id_comment IN ({array_int:comment_ids})',
  1747. array(
  1748. 'ver_test' => 'ver_test',
  1749. 'comment_ids' => $_SESSION[$verificationOptions['id'] . '_vv']['q'],
  1750. )
  1751. );
  1752. $incorrectQuestions = array();
  1753. while ($row = $smcFunc['db_fetch_assoc']($request))
  1754. {
  1755. if (!isset($_REQUEST[$verificationOptions['id'] . '_vv']['q'][$row['id_comment']]) || trim($_REQUEST[$verificationOptions['id'] . '_vv']['q'][$row['id_comment']]) == '' || trim($smcFunc['htmlspecialchars'](strtolower($_REQUEST[$verificationOptions['id'] . '_vv']['q'][$row['id_comment']]))) != strtolower($row['answer']))
  1756. $incorrectQuestions[] = $row['id_comment'];
  1757. }
  1758. $smcFunc['db_free_result']($request);
  1759. if (!empty($incorrectQuestions))
  1760. $verification_errors[] = 'wrong_verification_answer';
  1761. }
  1762. }
  1763. // Any errors means we refresh potentially.
  1764. if (!empty($verification_errors))
  1765. {
  1766. if (empty($_SESSION[$verificationOptions['id'] . '_vv']['errors']))
  1767. $_SESSION[$verificationOptions['id'] . '_vv']['errors'] = 0;
  1768. // Too many errors?
  1769. elseif ($_SESSION[$verificationOptions['id'] . '_vv']['errors'] > $thisVerification['max_errors'])
  1770. $force_refresh = true;
  1771. // Keep a track of these.
  1772. $_SESSION[$verificationOptions['id'] . '_vv']['errors']++;
  1773. }
  1774. // Are we refreshing then?
  1775. if ($force_refresh)
  1776. {
  1777. // Assume nothing went before.
  1778. $_SESSION[$verificationOptions['id'] . '_vv']['count'] = 0;
  1779. $_SESSION[$verificationOptions['id'] . '_vv']['errors'] = 0;
  1780. $_SESSION[$verificationOptions['id'] . '_vv']['did_pass'] = false;
  1781. $_SESSION[$verificationOptions['id'] . '_vv']['q'] = array();
  1782. $_SESSION[$verificationOptions['id'] . '_vv']['code'] = '';
  1783. // Generating a new image.
  1784. if ($thisVerification['show_visual'])
  1785. {
  1786. // Are we overriding the range?
  1787. $character_range = !empty($verificationOptions['override_range']) ? $verificationOptions['override_range'] : $context['standard_captcha_range'];
  1788. for ($i = 0; $i < 6; $i++)
  1789. $_SESSION[$verificationOptions['id'] . '_vv']['code'] .= $character_range[array_rand($character_range)];
  1790. }
  1791. // Getting some new questions?
  1792. if ($thisVerification['number_questions'])
  1793. {
  1794. // Pick some random IDs
  1795. $questionIDs = array();
  1796. if ($thisVerification['number_questions'] == 1)
  1797. $questionIDs[] = $modSettings['question_id_cache'][array_rand($modSettings['question_id_cache'], $thisVerification['number_questions'])];
  1798. else
  1799. foreach (array_rand($modSettings['question_id_cache'], $thisVerification['number_questions']) as $index)
  1800. $questionIDs[] = $modSettings['question_id_cache'][$index];
  1801. }
  1802. }
  1803. else
  1804. {
  1805. // Same questions as before.
  1806. $questionIDs = !empty($_SESSION[$verificationOptions['id'] . '_vv']['q']) ? $_SESSION[$verificationOptions['id'] . '_vv']['q'] : array();
  1807. $thisVerification['text_value'] = !empty($_REQUEST[$verificationOptions['id'] . '_vv']['code']) ? $smcFunc['htmlspecialchars']($_REQUEST[$verificationOptions['id'] . '_vv']['code']) : '';
  1808. }
  1809. // Have we got some questions to load?
  1810. if (!empty($questionIDs))
  1811. {
  1812. $request = $smcFunc['db_query']('', '
  1813. SELECT id_comment, body AS question
  1814. FROM {db_prefix}log_comments
  1815. WHERE comment_type = {string:ver_test}
  1816. AND id_comment IN ({array_int:comment_ids})',
  1817. array(
  1818. 'ver_test' => 'ver_test',
  1819. 'comment_ids' => $questionIDs,
  1820. )
  1821. );
  1822. $_SESSION[$verificationOptions['id'] . '_vv']['q'] = array();
  1823. while ($row = $smcFunc['db_fetch_assoc']($request))
  1824. {
  1825. $thisVerification['questions'][] = array(
  1826. 'id' => $row['id_comment'],
  1827. 'q' => parse_bbc($row['question']),
  1828. 'is_error' => !empty($incorrectQuestions) && in_array($row['id_comment'], $incorrectQuestions),
  1829. // Remember a previous submission?
  1830. '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']]) : '',
  1831. );
  1832. $_SESSION[$verificationOptions['id'] . '_vv']['q'][] = $row['id_comment'];
  1833. }
  1834. $smcFunc['db_free_result']($request);
  1835. }
  1836. $_SESSION[$verificationOptions['id'] . '_vv']['count'] = empty($_SESSION[$verificationOptions['id'] . '_vv']['count']) ? 1 : $_SESSION[$verificationOptions['id'] . '_vv']['count'] + 1;
  1837. // Return errors if we have them.
  1838. if (!empty($verification_errors))
  1839. return $verification_errors;
  1840. // If we had a test that one, make a note.
  1841. elseif ($do_test)
  1842. $_SESSION[$verificationOptions['id'] . '_vv']['did_pass'] = true;
  1843. // Say that everything went well chaps.
  1844. return true;
  1845. }
  1846. /**
  1847. * This keeps track of all registered handling functions for auto suggest functionality and passes execution to them.
  1848. * @param bool $checkRegistered = null
  1849. */
  1850. function AutoSuggestHandler($checkRegistered = null)
  1851. {
  1852. global $context;
  1853. // These are all registered types.
  1854. $searchTypes = array(
  1855. 'member' => 'Member',
  1856. 'versions' => 'SMFVersions',
  1857. );
  1858. // If we're just checking the callback function is registered return true or false.
  1859. if ($checkRegistered != null)
  1860. return isset($searchTypes[$checkRegistered]) && function_exists('AutoSuggest_Search_' . $checkRegistered);
  1861. checkSession('get');
  1862. loadTemplate('Xml');
  1863. // Any parameters?
  1864. $context['search_param'] = isset($_REQUEST['search_param']) ? unserialize(base64_decode($_REQUEST['search_param'])) : array();
  1865. if (isset($_REQUEST['suggest_type'], $_REQUEST['search']) && isset($searchTypes[$_REQUEST['suggest_type']]))
  1866. {
  1867. $function = 'AutoSuggest_Search_' . $searchTypes[$_REQUEST['suggest_type']];
  1868. $context['sub_template'] = 'generic_xml';
  1869. $context['xml_data'] = $function();
  1870. }
  1871. }
  1872. /**
  1873. * Search for a member - by real_name or member_name by default.
  1874. *
  1875. * @return string
  1876. */
  1877. function AutoSuggest_Search_Member()
  1878. {
  1879. global $user_info, $txt, $smcFunc, $context;
  1880. $_REQUEST['search'] = trim($smcFunc['strtolower']($_REQUEST['search'])) . '*';
  1881. $_REQUEST['search'] = strtr($_REQUEST['search'], array('%' => '\%', '_' => '\_', '*' => '%', '?' => '_', '&#038;' => '&amp;'));
  1882. // Find the member.
  1883. $request = $smcFunc['db_query']('', '
  1884. SELECT id_member, real_name
  1885. FROM {db_prefix}members
  1886. WHERE real_name LIKE {string:search}' . (!empty($context['search_param']['buddies']) ? '
  1887. AND id_member IN ({array_int:buddy_list})' : '') . '
  1888. AND is_activated IN (1, 11)
  1889. LIMIT ' . ($smcFunc['strlen']($_REQUEST['search']) <= 2 ? '100' : '800'),
  1890. array(
  1891. 'buddy_list' => $user_info['buddies'],
  1892. 'search' => $_REQUEST['search'],
  1893. )
  1894. );
  1895. $xml_data = array(
  1896. 'items' => array(
  1897. 'identifier' => 'item',
  1898. 'children' => array(),
  1899. ),
  1900. );
  1901. while ($row = $smcFunc['db_fetch_assoc']($request))
  1902. {
  1903. $row['real_name'] = strtr($row['real_name'], array('&amp;' => '&#038;', '&lt;' => '&#060;', '&gt;' => '&#062;', '&quot;' => '&#034;'));
  1904. $xml_data['items']['children'][] = array(
  1905. 'attributes' => array(
  1906. 'id' => $row['id_member'],
  1907. ),
  1908. 'value' => $row['real_name'],
  1909. );
  1910. }
  1911. $smcFunc['db_free_result']($request);
  1912. return $xml_data;
  1913. }
  1914. function AutoSuggest_Search_SMFVersions()
  1915. {
  1916. $xml_data = array(
  1917. 'items' => array(
  1918. 'identifier' => 'item',
  1919. 'children' => array(),
  1920. ),
  1921. );
  1922. $versions = array(
  1923. 'SMF 1.1',
  1924. 'SMF 1.1.1',
  1925. 'SMF 1.1.2',
  1926. 'SMF 1.1.3',
  1927. 'SMF 1.1.4',
  1928. 'SMF 1.1.5',
  1929. 'SMF 1.1.6',
  1930. 'SMF 1.1.7',
  1931. 'SMF 1.1.8',
  1932. 'SMF 1.1.9',
  1933. 'SMF 1.1.10',
  1934. 'SMF 1.1.11',
  1935. 'SMF 1.1.12',
  1936. 'SMF 1.1.13',
  1937. 'SMF 1.1.14',
  1938. 'SMF 1.1.15',
  1939. 'SMF 1.1.16',
  1940. 'SMF 2.0 beta 1',
  1941. 'SMF 2.0 beta 1.2',
  1942. 'SMF 2.0 beta 2',
  1943. 'SMF 2.0 beta 3',
  1944. 'SMF 2.0 RC 1',
  1945. 'SMF 2.0 RC 1.2',
  1946. 'SMF 2.0 RC 2',
  1947. 'SMF 2.0 RC 3',
  1948. 'SMF 2.0',
  1949. 'SMF 2.0.1',
  1950. 'SMF 2.0.2',
  1951. );
  1952. foreach ($versions as $id => $version)
  1953. if (strpos($version, strtoupper($_REQUEST['search'])) !== false)
  1954. $xml_data['items']['children'][] = array(
  1955. 'attributes' => array(
  1956. 'id' => $id,
  1957. ),
  1958. 'value' => $version,
  1959. );
  1960. return $xml_data;
  1961. }
  1962. ?>