Subs-Editor.php 75 KB

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