Subs-Editor.php 67 KB

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