Subs-Editor.php 67 KB

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