Subs-Editor.php 67 KB

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