Subs-Editor.php 68 KB

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