Subs.php 132 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731
  1. <?php
  2. /**
  3. * Simple Machines Forum (SMF)
  4. *
  5. * @package SMF
  6. * @author Simple Machines http://www.simplemachines.org
  7. * @copyright 2011 Simple Machines
  8. * @license http://www.simplemachines.org/about/smf/license.php BSD
  9. *
  10. * @version 2.0
  11. */
  12. if (!defined('SMF'))
  13. die('Hacking attempt...');
  14. /* This file has all the main functions in it that relate to, well,
  15. everything. It provides all of the following functions:
  16. void updateStats(string statistic, string condition = '1')
  17. - statistic can be 'member', 'message', 'topic', or 'postgroups'.
  18. - parameter1 and parameter2 are optional, and are used to update only
  19. those stats that need updating.
  20. - the 'member' statistic updates the latest member, the total member
  21. count, and the number of unapproved members.
  22. - 'member' also only counts approved members when approval is on, but
  23. is much more efficient with it off.
  24. - updating 'message' changes the total number of messages, and the
  25. highest message id by id_msg - which can be parameters 1 and 2,
  26. respectively.
  27. - 'topic' updates the total number of topics, or if parameter1 is true
  28. simply increments them.
  29. - the 'postgroups' case updates those members who match condition's
  30. post-based membergroups in the database (restricted by parameter1).
  31. void updateMemberData(int id_member, array data)
  32. - updates the columns in the members table.
  33. - id_member is either an int or an array of ints to be updated.
  34. - data is an associative array of the columns to be updated and their
  35. respective values.
  36. - any string values updated should be quoted and slashed.
  37. - the value of any column can be '+' or '-', which mean 'increment'
  38. and decrement, respectively.
  39. - if the member's post number is updated, updates their post groups.
  40. - this function should be used whenever member data needs to be
  41. updated in place of an UPDATE query.
  42. void updateSettings(array changeArray, use_update = false)
  43. - updates both the settings table and $modSettings array.
  44. - all of changeArray's indexes and values are assumed to have escaped
  45. apostrophes (')!
  46. - if a variable is already set to what you want to change it to, that
  47. variable will be skipped over; it would be unnecessary to reset.
  48. - if use_update is true, UPDATEs will be used instead of REPLACE.
  49. - when use_update is true, the value can be true or false to increment
  50. or decrement it, respectively.
  51. string constructPageIndex(string base_url, int &start, int max_value,
  52. int num_per_page, bool compact_start = false)
  53. - builds the page list, e.g. 1 ... 6 7 [8] 9 10 ... 15.
  54. - compact_start caused it to use "url.page" instead of
  55. "url;start=page".
  56. - handles any wireless settings (adding special things to URLs.)
  57. - very importantly, cleans up the start value passed, and forces it to
  58. be a multiple of num_per_page.
  59. - also checks that start is not more than max_value.
  60. - base_url should be the URL without any start parameter on it.
  61. - uses the compactTopicPagesEnable and compactTopicPagesContiguous
  62. settings to decide how to display the menu.
  63. - an example is available near the function definition.
  64. string comma_format(float number)
  65. - formats a number to display in the style of the admins' choosing.
  66. - uses the format of number_format to decide how to format the number.
  67. - for example, it might display "1 234,50".
  68. - caches the formatting data from the setting for optimization.
  69. string timeformat(int time, bool show_today = true, string offset_type = false)
  70. - returns a pretty formated version of time based on the user's format
  71. in $user_info['time_format'].
  72. - applies all necessary time offsets to the timestamp, unless offset_type
  73. is set.
  74. - if todayMod is set and show_today was not not specified or true, an
  75. alternate format string is used to show the date with something to
  76. show it is "today" or "yesterday".
  77. - performs localization (more than just strftime would do alone.)
  78. string un_htmlspecialchars(string text)
  79. - removes the base entities (&lt;, &quot;, etc.) from text.
  80. - should be used instead of html_entity_decode for PHP version
  81. compatibility reasons.
  82. - additionally converts &nbsp; and &#039;.
  83. - returns the string without entities.
  84. string shorten_subject(string regular_subject, int length)
  85. - shortens a subject so that it is either shorter than length, or that
  86. length plus an ellipsis.
  87. - respects internationalization characters and entities as one character.
  88. - avoids trailing entities.
  89. - returns the shortened string.
  90. int forum_time(bool use_user_offset = true)
  91. - returns the current time with offsets.
  92. - always applies the offset in the time_offset setting.
  93. - if use_user_offset is true, applies the user's offset as well.
  94. - returns seconds since the unix epoch.
  95. array permute(array input)
  96. - calculates all the possible permutations (orders) of array.
  97. - should not be called on huge arrays (bigger than like 10 elements.)
  98. - returns an array containing each permutation.
  99. string parse_bbc(string message, bool smileys = true, string cache_id = '', array parse_tags = null)
  100. - this very hefty function parses bbc in message.
  101. - only parses bbc tags which are not disabled in disabledBBC.
  102. - also handles basic HTML, if enablePostHTML is on.
  103. - caches the from/to replace regular expressions so as not to reload
  104. them every time a string is parsed.
  105. - only parses smileys if smileys is true.
  106. - does nothing if the enableBBC setting is off.
  107. - applies the fixLongWords magic if the setting is set to on.
  108. - uses the cache_id as a unique identifier to facilitate any caching
  109. it may do.
  110. - returns the modified message.
  111. void parsesmileys(string &message)
  112. - the smiley parsing function which makes pretty faces appear :).
  113. - if custom smiley sets are turned off by smiley_enable, the default
  114. set of smileys will be used.
  115. - these are specifically not parsed in code tags [url=mailto:[email protected]]
  116. - caches the smileys from the database or array in memory.
  117. - doesn't return anything, but rather modifies message directly.
  118. string highlight_php_code(string code)
  119. - Uses PHP's highlight_string() to highlight PHP syntax
  120. - does special handling to keep the tabs in the code available.
  121. - used to parse PHP code from inside [code] and [php] tags.
  122. - returns the code with highlighted HTML.
  123. void redirectexit(string setLocation = '', bool use_refresh = false)
  124. // !!!
  125. void obExit(bool do_header = true, bool do_footer = do_header)
  126. // !!!
  127. array url_image_size(string url)
  128. - uses getimagesize() to determine the size of a file.
  129. - attempts to connect to the server first so it won't time out.
  130. - returns false on failure, otherwise the output of getimagesize().
  131. void determineTopicClass(array &topic_context)
  132. // !!!
  133. void setupThemeContext(bool force_reload = false)
  134. // !!!
  135. void template_rawdata()
  136. // !!!
  137. void template_header()
  138. // !!!
  139. void theme_copyright(bool get_it = false)
  140. // !!!
  141. void template_footer()
  142. // !!!
  143. void getAttachmentFilename(string filename, int id_attach, bool new = true)
  144. // !!!
  145. array ip2range(string $fullip)
  146. - converts a given IP string to an array.
  147. - internal function used to convert a user-readable format to
  148. a format suitable for the database.
  149. - returns 'unknown' if the ip in the input was '255.255.255.255'.
  150. string host_from_ip(string ip_address)
  151. // !!!
  152. string create_button(string filename, string alt, string label, bool custom = '')
  153. // !!!
  154. void clean_cache(type = '')
  155. - clean the cache directory ($cachedir, if any and in use)
  156. - it may only remove the files of a certain type
  157. (if the $type parameter is given)
  158. array call_integration_hook(string hook, array parameters = array())
  159. - calls all functions of the given hook.
  160. - supports static class method calls.
  161. - returns the results of the functions as an array.
  162. void add_integration_function(string hook, string function, bool permanent = true)
  163. - adds the given function to the given hook.
  164. - does nothing if the functions is already added.
  165. - if permanent parameter is true, updates the value in settings table.
  166. void remove_integration_function(string hook, string function)
  167. - removes the given function from the given hook.
  168. - does nothing if the functions is not available.
  169. */
  170. // Update some basic statistics...
  171. function updateStats($type, $parameter1 = null, $parameter2 = null)
  172. {
  173. global $sourcedir, $modSettings, $smcFunc;
  174. switch ($type)
  175. {
  176. case 'member':
  177. $changes = array(
  178. 'memberlist_updated' => time(),
  179. );
  180. // #1 latest member ID, #2 the real name for a new registration.
  181. if (is_numeric($parameter1))
  182. {
  183. $changes['latestMember'] = $parameter1;
  184. $changes['latestRealName'] = $parameter2;
  185. updateSettings(array('totalMembers' => true), true);
  186. }
  187. // We need to calculate the totals.
  188. else
  189. {
  190. // Update the latest activated member (highest id_member) and count.
  191. $result = $smcFunc['db_query']('', '
  192. SELECT COUNT(*), MAX(id_member)
  193. FROM {db_prefix}members
  194. WHERE is_activated = {int:is_activated}',
  195. array(
  196. 'is_activated' => 1,
  197. )
  198. );
  199. list ($changes['totalMembers'], $changes['latestMember']) = $smcFunc['db_fetch_row']($result);
  200. $smcFunc['db_free_result']($result);
  201. // Get the latest activated member's display name.
  202. $result = $smcFunc['db_query']('', '
  203. SELECT real_name
  204. FROM {db_prefix}members
  205. WHERE id_member = {int:id_member}
  206. LIMIT 1',
  207. array(
  208. 'id_member' => (int) $changes['latestMember'],
  209. )
  210. );
  211. list ($changes['latestRealName']) = $smcFunc['db_fetch_row']($result);
  212. $smcFunc['db_free_result']($result);
  213. // Are we using registration approval?
  214. if ((!empty($modSettings['registration_method']) && $modSettings['registration_method'] == 2) || !empty($modSettings['approveAccountDeletion']))
  215. {
  216. // Update the amount of members awaiting approval - ignoring COPPA accounts, as you can't approve them until you get permission.
  217. $result = $smcFunc['db_query']('', '
  218. SELECT COUNT(*)
  219. FROM {db_prefix}members
  220. WHERE is_activated IN ({array_int:activation_status})',
  221. array(
  222. 'activation_status' => array(3, 4),
  223. )
  224. );
  225. list ($changes['unapprovedMembers']) = $smcFunc['db_fetch_row']($result);
  226. $smcFunc['db_free_result']($result);
  227. }
  228. }
  229. updateSettings($changes);
  230. break;
  231. case 'message':
  232. if ($parameter1 === true && $parameter2 !== null)
  233. updateSettings(array('totalMessages' => true, 'maxMsgID' => $parameter2), true);
  234. else
  235. {
  236. // SUM and MAX on a smaller table is better for InnoDB tables.
  237. $result = $smcFunc['db_query']('', '
  238. SELECT SUM(num_posts + unapproved_posts) AS total_messages, MAX(id_last_msg) AS max_msg_id
  239. FROM {db_prefix}boards
  240. WHERE redirect = {string:blank_redirect}' . (!empty($modSettings['recycle_enable']) && $modSettings['recycle_board'] > 0 ? '
  241. AND id_board != {int:recycle_board}' : ''),
  242. array(
  243. 'recycle_board' => isset($modSettings['recycle_board']) ? $modSettings['recycle_board'] : 0,
  244. 'blank_redirect' => '',
  245. )
  246. );
  247. $row = $smcFunc['db_fetch_assoc']($result);
  248. $smcFunc['db_free_result']($result);
  249. updateSettings(array(
  250. 'totalMessages' => $row['total_messages'] === null ? 0 : $row['total_messages'],
  251. 'maxMsgID' => $row['max_msg_id'] === null ? 0 : $row['max_msg_id']
  252. ));
  253. }
  254. break;
  255. case 'subject':
  256. // Remove the previous subject (if any).
  257. $smcFunc['db_query']('', '
  258. DELETE FROM {db_prefix}log_search_subjects
  259. WHERE id_topic = {int:id_topic}',
  260. array(
  261. 'id_topic' => (int) $parameter1,
  262. )
  263. );
  264. // Insert the new subject.
  265. if ($parameter2 !== null)
  266. {
  267. $parameter1 = (int) $parameter1;
  268. $parameter2 = text2words($parameter2);
  269. $inserts = array();
  270. foreach ($parameter2 as $word)
  271. $inserts[] = array($word, $parameter1);
  272. if (!empty($inserts))
  273. $smcFunc['db_insert']('ignore',
  274. '{db_prefix}log_search_subjects',
  275. array('word' => 'string', 'id_topic' => 'int'),
  276. $inserts,
  277. array('word', 'id_topic')
  278. );
  279. }
  280. break;
  281. case 'topic':
  282. if ($parameter1 === true)
  283. updateSettings(array('totalTopics' => true), true);
  284. else
  285. {
  286. // Get the number of topics - a SUM is better for InnoDB tables.
  287. // We also ignore the recycle bin here because there will probably be a bunch of one-post topics there.
  288. $result = $smcFunc['db_query']('', '
  289. SELECT SUM(num_topics + unapproved_topics) AS total_topics
  290. FROM {db_prefix}boards' . (!empty($modSettings['recycle_enable']) && $modSettings['recycle_board'] > 0 ? '
  291. WHERE id_board != {int:recycle_board}' : ''),
  292. array(
  293. 'recycle_board' => !empty($modSettings['recycle_board']) ? $modSettings['recycle_board'] : 0,
  294. )
  295. );
  296. $row = $smcFunc['db_fetch_assoc']($result);
  297. $smcFunc['db_free_result']($result);
  298. updateSettings(array('totalTopics' => $row['total_topics'] === null ? 0 : $row['total_topics']));
  299. }
  300. break;
  301. case 'postgroups':
  302. // Parameter two is the updated columns: we should check to see if we base groups off any of these.
  303. if ($parameter2 !== null && !in_array('posts', $parameter2))
  304. return;
  305. if (($postgroups = cache_get_data('updateStats:postgroups', 360)) == null)
  306. {
  307. // Fetch the postgroups!
  308. $request = $smcFunc['db_query']('', '
  309. SELECT id_group, min_posts
  310. FROM {db_prefix}membergroups
  311. WHERE min_posts != {int:min_posts}',
  312. array(
  313. 'min_posts' => -1,
  314. )
  315. );
  316. $postgroups = array();
  317. while ($row = $smcFunc['db_fetch_assoc']($request))
  318. $postgroups[$row['id_group']] = $row['min_posts'];
  319. $smcFunc['db_free_result']($request);
  320. // Sort them this way because if it's done with MySQL it causes a filesort :(.
  321. arsort($postgroups);
  322. cache_put_data('updateStats:postgroups', $postgroups, 360);
  323. }
  324. // Oh great, they've screwed their post groups.
  325. if (empty($postgroups))
  326. return;
  327. // Set all membergroups from most posts to least posts.
  328. $conditions = '';
  329. foreach ($postgroups as $id => $min_posts)
  330. {
  331. $conditions .= '
  332. WHEN posts >= ' . $min_posts . (!empty($lastMin) ? ' AND posts <= ' . $lastMin : '') . ' THEN ' . $id;
  333. $lastMin = $min_posts;
  334. }
  335. // A big fat CASE WHEN... END is faster than a zillion UPDATE's ;).
  336. $smcFunc['db_query']('', '
  337. UPDATE {db_prefix}members
  338. SET id_post_group = CASE ' . $conditions . '
  339. ELSE 0
  340. END' . ($parameter1 != null ? '
  341. WHERE ' . (is_array($parameter1) ? 'id_member IN ({array_int:members})' : 'id_member = {int:members}') : ''),
  342. array(
  343. 'members' => $parameter1,
  344. )
  345. );
  346. break;
  347. default:
  348. trigger_error('updateStats(): Invalid statistic type \'' . $type . '\'', E_USER_NOTICE);
  349. }
  350. }
  351. // Assumes the data has been htmlspecialchar'd.
  352. function updateMemberData($members, $data)
  353. {
  354. global $modSettings, $user_info, $smcFunc;
  355. $parameters = array();
  356. if (is_array($members))
  357. {
  358. $condition = 'id_member IN ({array_int:members})';
  359. $parameters['members'] = $members;
  360. }
  361. elseif ($members === null)
  362. $condition = '1=1';
  363. else
  364. {
  365. $condition = 'id_member = {int:member}';
  366. $parameters['member'] = $members;
  367. }
  368. if (!empty($modSettings['integrate_change_member_data']))
  369. {
  370. // Only a few member variables are really interesting for integration.
  371. $integration_vars = array(
  372. 'member_name',
  373. 'real_name',
  374. 'email_address',
  375. 'id_group',
  376. 'gender',
  377. 'birthdate',
  378. 'website_title',
  379. 'website_url',
  380. 'location',
  381. 'hide_email',
  382. 'time_format',
  383. 'time_offset',
  384. 'avatar',
  385. 'lngfile',
  386. );
  387. $vars_to_integrate = array_intersect($integration_vars, array_keys($data));
  388. // Only proceed if there are any variables left to call the integration function.
  389. if (count($vars_to_integrate) != 0)
  390. {
  391. // Fetch a list of member_names if necessary
  392. if ((!is_array($members) && $members === $user_info['id']) || (is_array($members) && count($members) == 1 && in_array($user_info['id'], $members)))
  393. $member_names = array($user_info['username']);
  394. else
  395. {
  396. $member_names = array();
  397. $request = $smcFunc['db_query']('', '
  398. SELECT member_name
  399. FROM {db_prefix}members
  400. WHERE ' . $condition,
  401. $parameters
  402. );
  403. while ($row = $smcFunc['db_fetch_assoc']($request))
  404. $member_names[] = $row['member_name'];
  405. $smcFunc['db_free_result']($request);
  406. }
  407. if (!empty($member_names))
  408. foreach ($vars_to_integrate as $var)
  409. call_integration_hook('integrate_change_member_data', array($member_names, $var, $data[$var]));
  410. }
  411. }
  412. // Everything is assumed to be a string unless it's in the below.
  413. $knownInts = array(
  414. 'date_registered', 'posts', 'id_group', 'last_login', 'instant_messages', 'unread_messages',
  415. 'new_pm', 'pm_prefs', 'gender', 'hide_email', 'show_online', 'pm_email_notify', 'pm_receive_from', 'karma_good', 'karma_bad',
  416. 'notify_announcements', 'notify_send_body', 'notify_regularity', 'notify_types',
  417. 'id_theme', 'is_activated', 'id_msg_last_visit', 'id_post_group', 'total_time_logged_in', 'warning',
  418. );
  419. $knownFloats = array(
  420. 'time_offset',
  421. );
  422. $setString = '';
  423. foreach ($data as $var => $val)
  424. {
  425. $type = 'string';
  426. if (in_array($var, $knownInts))
  427. $type = 'int';
  428. elseif (in_array($var, $knownFloats))
  429. $type = 'float';
  430. elseif ($var == 'birthdate')
  431. $type = 'date';
  432. // Doing an increment?
  433. if ($type == 'int' && ($val === '+' || $val === '-'))
  434. {
  435. $val = $var . ' ' . $val . ' 1';
  436. $type = 'raw';
  437. }
  438. // Ensure posts, instant_messages, and unread_messages don't overflow or underflow.
  439. if (in_array($var, array('posts', 'instant_messages', 'unread_messages')))
  440. {
  441. if (preg_match('~^' . $var . ' (\+ |- |\+ -)([\d]+)~', $val, $match))
  442. {
  443. if ($match[1] != '+ ')
  444. $val = 'CASE WHEN ' . $var . ' <= ' . abs($match[2]) . ' THEN 0 ELSE ' . $val . ' END';
  445. $type = 'raw';
  446. }
  447. }
  448. $setString .= ' ' . $var . ' = {' . $type . ':p_' . $var . '},';
  449. $parameters['p_' . $var] = $val;
  450. }
  451. $smcFunc['db_query']('', '
  452. UPDATE {db_prefix}members
  453. SET' . substr($setString, 0, -1) . '
  454. WHERE ' . $condition,
  455. $parameters
  456. );
  457. updateStats('postgroups', $members, array_keys($data));
  458. // Clear any caching?
  459. if (!empty($modSettings['cache_enable']) && $modSettings['cache_enable'] >= 2 && !empty($members))
  460. {
  461. if (!is_array($members))
  462. $members = array($members);
  463. foreach ($members as $member)
  464. {
  465. if ($modSettings['cache_enable'] >= 3)
  466. {
  467. cache_put_data('member_data-profile-' . $member, null, 120);
  468. cache_put_data('member_data-normal-' . $member, null, 120);
  469. cache_put_data('member_data-minimal-' . $member, null, 120);
  470. }
  471. cache_put_data('user_settings-' . $member, null, 60);
  472. }
  473. }
  474. }
  475. // Updates the settings table as well as $modSettings... only does one at a time if $update is true.
  476. function updateSettings($changeArray, $update = false, $debug = false)
  477. {
  478. global $modSettings, $smcFunc;
  479. if (empty($changeArray) || !is_array($changeArray))
  480. return;
  481. // In some cases, this may be better and faster, but for large sets we don't want so many UPDATEs.
  482. if ($update)
  483. {
  484. foreach ($changeArray as $variable => $value)
  485. {
  486. $smcFunc['db_query']('', '
  487. UPDATE {db_prefix}settings
  488. SET value = {' . ($value === false || $value === true ? 'raw' : 'string') . ':value}
  489. WHERE variable = {string:variable}',
  490. array(
  491. 'value' => $value === true ? 'value + 1' : ($value === false ? 'value - 1' : $value),
  492. 'variable' => $variable,
  493. )
  494. );
  495. $modSettings[$variable] = $value === true ? $modSettings[$variable] + 1 : ($value === false ? $modSettings[$variable] - 1 : $value);
  496. }
  497. // Clean out the cache and make sure the cobwebs are gone too.
  498. cache_put_data('modSettings', null, 90);
  499. return;
  500. }
  501. $replaceArray = array();
  502. foreach ($changeArray as $variable => $value)
  503. {
  504. // Don't bother if it's already like that ;).
  505. if (isset($modSettings[$variable]) && $modSettings[$variable] == $value)
  506. continue;
  507. // If the variable isn't set, but would only be set to nothing'ness, then don't bother setting it.
  508. elseif (!isset($modSettings[$variable]) && empty($value))
  509. continue;
  510. $replaceArray[] = array($variable, $value);
  511. $modSettings[$variable] = $value;
  512. }
  513. if (empty($replaceArray))
  514. return;
  515. $smcFunc['db_insert']('replace',
  516. '{db_prefix}settings',
  517. array('variable' => 'string-255', 'value' => 'string-65534'),
  518. $replaceArray,
  519. array('variable')
  520. );
  521. // Kill the cache - it needs redoing now, but we won't bother ourselves with that here.
  522. cache_put_data('modSettings', null, 90);
  523. }
  524. // Constructs a page list.
  525. // $pageindex = constructPageIndex($scripturl . '?board=' . $board, $_REQUEST['start'], $num_messages, $maxindex, true);
  526. function constructPageIndex($base_url, &$start, $max_value, $num_per_page, $flexible_start = false)
  527. {
  528. global $modSettings;
  529. // Save whether $start was less than 0 or not.
  530. $start = (int) $start;
  531. $start_invalid = $start < 0;
  532. // Make sure $start is a proper variable - not less than 0.
  533. if ($start_invalid)
  534. $start = 0;
  535. // Not greater than the upper bound.
  536. elseif ($start >= $max_value)
  537. $start = max(0, (int) $max_value - (((int) $max_value % (int) $num_per_page) == 0 ? $num_per_page : ((int) $max_value % (int) $num_per_page)));
  538. // And it has to be a multiple of $num_per_page!
  539. else
  540. $start = max(0, (int) $start - ((int) $start % (int) $num_per_page));
  541. // Wireless will need the protocol on the URL somewhere.
  542. if (WIRELESS)
  543. $base_url .= ';' . WIRELESS_PROTOCOL;
  544. $base_link = '<a class="navPages" href="' . ($flexible_start ? $base_url : strtr($base_url, array('%' => '%%')) . ';start=%1$d') . '">%2$s</a> ';
  545. // Compact pages is off or on?
  546. if (empty($modSettings['compactTopicPagesEnable']))
  547. {
  548. // Show the left arrow.
  549. $pageindex = $start == 0 ? ' ' : sprintf($base_link, $start - $num_per_page, '&#171;');
  550. // Show all the pages.
  551. $display_page = 1;
  552. for ($counter = 0; $counter < $max_value; $counter += $num_per_page)
  553. $pageindex .= $start == $counter && !$start_invalid ? '<strong>' . $display_page++ . '</strong> ' : sprintf($base_link, $counter, $display_page++);
  554. // Show the right arrow.
  555. $display_page = ($start + $num_per_page) > $max_value ? $max_value : ($start + $num_per_page);
  556. if ($start != $counter - $max_value && !$start_invalid)
  557. $pageindex .= $display_page > $counter - $num_per_page ? ' ' : sprintf($base_link, $display_page, '&#187;');
  558. }
  559. else
  560. {
  561. // If they didn't enter an odd value, pretend they did.
  562. $PageContiguous = (int) ($modSettings['compactTopicPagesContiguous'] - ($modSettings['compactTopicPagesContiguous'] % 2)) / 2;
  563. // Show the first page. (>1< ... 6 7 [8] 9 10 ... 15)
  564. if ($start > $num_per_page * $PageContiguous)
  565. $pageindex = sprintf($base_link, 0, '1');
  566. else
  567. $pageindex = '';
  568. // Show the ... after the first page. (1 >...< 6 7 [8] 9 10 ... 15)
  569. if ($start > $num_per_page * ($PageContiguous + 1))
  570. $pageindex .= '<span style="font-weight: bold;" onclick="' . htmlspecialchars('expandPages(this, ' . JavaScriptEscape(($flexible_start ? $base_url : strtr($base_url, array('%' => '%%')) . ';start=%1$d')) . ', ' . $num_per_page . ', ' . ($start - $num_per_page * $PageContiguous) . ', ' . $num_per_page . ');') . '" onmouseover="this.style.cursor = \'pointer\';"> ... </span>';
  571. // Show the pages before the current one. (1 ... >6 7< [8] 9 10 ... 15)
  572. for ($nCont = $PageContiguous; $nCont >= 1; $nCont--)
  573. if ($start >= $num_per_page * $nCont)
  574. {
  575. $tmpStart = $start - $num_per_page * $nCont;
  576. $pageindex.= sprintf($base_link, $tmpStart, $tmpStart / $num_per_page + 1);
  577. }
  578. // Show the current page. (1 ... 6 7 >[8]< 9 10 ... 15)
  579. if (!$start_invalid)
  580. $pageindex .= '[<strong>' . ($start / $num_per_page + 1) . '</strong>] ';
  581. else
  582. $pageindex .= sprintf($base_link, $start, $start / $num_per_page + 1);
  583. // Show the pages after the current one... (1 ... 6 7 [8] >9 10< ... 15)
  584. $tmpMaxPages = (int) (($max_value - 1) / $num_per_page) * $num_per_page;
  585. for ($nCont = 1; $nCont <= $PageContiguous; $nCont++)
  586. if ($start + $num_per_page * $nCont <= $tmpMaxPages)
  587. {
  588. $tmpStart = $start + $num_per_page * $nCont;
  589. $pageindex .= sprintf($base_link, $tmpStart, $tmpStart / $num_per_page + 1);
  590. }
  591. // Show the '...' part near the end. (1 ... 6 7 [8] 9 10 >...< 15)
  592. if ($start + $num_per_page * ($PageContiguous + 1) < $tmpMaxPages)
  593. $pageindex .= '<span style="font-weight: bold;" onclick="expandPages(this, \'' . ($flexible_start ? strtr($base_url, array('\'' => '\\\'')) : strtr($base_url, array('%' => '%%', '\'' => '\\\'')) . ';start=%1$d') . '\', ' . ($start + $num_per_page * ($PageContiguous + 1)) . ', ' . $tmpMaxPages . ', ' . $num_per_page . ');" onmouseover="this.style.cursor=\'pointer\';"> ... </span>';
  594. // Show the last number in the list. (1 ... 6 7 [8] 9 10 ... >15<)
  595. if ($start + $num_per_page * $PageContiguous < $tmpMaxPages)
  596. $pageindex .= sprintf($base_link, $tmpMaxPages, $tmpMaxPages / $num_per_page + 1);
  597. }
  598. return $pageindex;
  599. }
  600. // Formats a number to display in the style of the admin's choosing.
  601. function comma_format($number, $override_decimal_count = false)
  602. {
  603. global $txt;
  604. static $thousands_separator = null, $decimal_separator = null, $decimal_count = null;
  605. // @todo Should, perhaps, this just be handled in the language files, and not a mod setting?
  606. // (French uses 1 234,00 for example... what about a multilingual forum?)
  607. // Cache these values...
  608. if ($decimal_separator === null)
  609. {
  610. // Not set for whatever reason?
  611. if (empty($txt['number_format']) || preg_match('~^1([^\d]*)?234([^\d]*)(0*?)$~', $txt['number_format'], $matches) != 1)
  612. return $number;
  613. // Cache these each load...
  614. $thousands_separator = $matches[1];
  615. $decimal_separator = $matches[2];
  616. $decimal_count = strlen($matches[3]);
  617. }
  618. // Format the string with our friend, number_format.
  619. return number_format($number, is_float($number) ? ($override_decimal_count === false ? $decimal_count : $override_decimal_count) : 0, $decimal_separator, $thousands_separator);
  620. }
  621. // Format a time to make it look purdy.
  622. function timeformat($log_time, $show_today = true, $offset_type = false)
  623. {
  624. global $context, $user_info, $txt, $modSettings, $smcFunc;
  625. static $non_twelve_hour;
  626. // Offset the time.
  627. if (!$offset_type)
  628. $time = $log_time + ($user_info['time_offset'] + $modSettings['time_offset']) * 3600;
  629. // Just the forum offset?
  630. elseif ($offset_type == 'forum')
  631. $time = $log_time + $modSettings['time_offset'] * 3600;
  632. else
  633. $time = $log_time;
  634. // We can't have a negative date (on Windows, at least.)
  635. if ($log_time < 0)
  636. $log_time = 0;
  637. // Today and Yesterday?
  638. if ($modSettings['todayMod'] >= 1 && $show_today === true)
  639. {
  640. // Get the current time.
  641. $nowtime = forum_time();
  642. $then = @getdate($time);
  643. $now = @getdate($nowtime);
  644. // Try to make something of a time format string...
  645. $s = strpos($user_info['time_format'], '%S') === false ? '' : ':%S';
  646. if (strpos($user_info['time_format'], '%H') === false && strpos($user_info['time_format'], '%T') === false)
  647. {
  648. $h = strpos($user_info['time_format'], '%l') === false ? '%I' : '%l';
  649. $today_fmt = $h . ':%M' . $s . ' %p';
  650. }
  651. else
  652. $today_fmt = '%H:%M' . $s;
  653. // Same day of the year, same year.... Today!
  654. if ($then['yday'] == $now['yday'] && $then['year'] == $now['year'])
  655. return $txt['today'] . timeformat($log_time, $today_fmt, $offset_type);
  656. // Day-of-year is one less and same year, or it's the first of the year and that's the last of the year...
  657. if ($modSettings['todayMod'] == '2' && (($then['yday'] == $now['yday'] - 1 && $then['year'] == $now['year']) || ($now['yday'] == 0 && $then['year'] == $now['year'] - 1) && $then['mon'] == 12 && $then['mday'] == 31))
  658. return $txt['yesterday'] . timeformat($log_time, $today_fmt, $offset_type);
  659. }
  660. $str = !is_bool($show_today) ? $show_today : $user_info['time_format'];
  661. if (setlocale(LC_TIME, $txt['lang_locale']))
  662. {
  663. if (!isset($non_twelve_hour))
  664. $non_twelve_hour = trim(strftime('%p')) === '';
  665. if ($non_twelve_hour && strpos($str, '%p') !== false)
  666. $str = str_replace('%p', (strftime('%H', $time) < 12 ? $txt['time_am'] : $txt['time_pm']), $str);
  667. foreach (array('%a', '%A', '%b', '%B') as $token)
  668. if (strpos($str, $token) !== false)
  669. $str = str_replace($token, !empty($txt['lang_capitalize_dates']) ? $smcFunc['ucwords'](strftime($token, $time)) : strftime($token, $time), $str);
  670. }
  671. else
  672. {
  673. // Do-it-yourself time localization. Fun.
  674. foreach (array('%a' => 'days_short', '%A' => 'days', '%b' => 'months_short', '%B' => 'months') as $token => $text_label)
  675. if (strpos($str, $token) !== false)
  676. $str = str_replace($token, $txt[$text_label][(int) strftime($token === '%a' || $token === '%A' ? '%w' : '%m', $time)], $str);
  677. if (strpos($str, '%p') !== false)
  678. $str = str_replace('%p', (strftime('%H', $time) < 12 ? $txt['time_am'] : $txt['time_pm']), $str);
  679. }
  680. // Windows doesn't support %e; on some versions, strftime fails altogether if used, so let's prevent that.
  681. if ($context['server']['is_windows'] && strpos($str, '%e') !== false)
  682. $str = str_replace('%e', ltrim(strftime('%d', $time), '0'), $str);
  683. // Format any other characters..
  684. return strftime($str, $time);
  685. }
  686. // Removes special entities from strings. Compatibility...
  687. function un_htmlspecialchars($string)
  688. {
  689. static $translation;
  690. if (!isset($translation))
  691. $translation = array_flip(get_html_translation_table(HTML_SPECIALCHARS, ENT_QUOTES)) + array('&#039;' => '\'', '&nbsp;' => ' ');
  692. return strtr($string, $translation);
  693. }
  694. // Shorten a subject + internationalization concerns.
  695. function shorten_subject($subject, $len)
  696. {
  697. global $smcFunc;
  698. // It was already short enough!
  699. if ($smcFunc['strlen']($subject) <= $len)
  700. return $subject;
  701. // Shorten it by the length it was too long, and strip off junk from the end.
  702. return $smcFunc['substr']($subject, 0, $len) . '...';
  703. }
  704. // The current time with offset.
  705. function forum_time($use_user_offset = true, $timestamp = null)
  706. {
  707. global $user_info, $modSettings;
  708. if ($timestamp === null)
  709. $timestamp = time();
  710. elseif ($timestamp == 0)
  711. return 0;
  712. return $timestamp + ($modSettings['time_offset'] + ($use_user_offset ? $user_info['time_offset'] : 0)) * 3600;
  713. }
  714. // This gets all possible permutations of an array.
  715. function permute($array)
  716. {
  717. $orders = array($array);
  718. $n = count($array);
  719. $p = range(0, $n);
  720. for ($i = 1; $i < $n; null)
  721. {
  722. $p[$i]--;
  723. $j = $i % 2 != 0 ? $p[$i] : 0;
  724. $temp = $array[$i];
  725. $array[$i] = $array[$j];
  726. $array[$j] = $temp;
  727. for ($i = 1; $p[$i] == 0; $i++)
  728. $p[$i] = 1;
  729. $orders[] = $array;
  730. }
  731. return $orders;
  732. }
  733. // Parse bulletin board code in a string, as well as smileys optionally.
  734. function parse_bbc($message, $smileys = true, $cache_id = '', $parse_tags = array())
  735. {
  736. global $txt, $scripturl, $context, $modSettings, $user_info, $smcFunc;
  737. static $bbc_codes = array(), $itemcodes = array(), $no_autolink_tags = array();
  738. static $disabled;
  739. // Don't waste cycles
  740. if ($message === '')
  741. return '';
  742. // Never show smileys for wireless clients. More bytes, can't see it anyway :P.
  743. if (WIRELESS)
  744. $smileys = false;
  745. elseif ($smileys !== null && ($smileys == '1' || $smileys == '0'))
  746. $smileys = (bool) $smileys;
  747. if (empty($modSettings['enableBBC']) && $message !== false)
  748. {
  749. if ($smileys === true)
  750. parsesmileys($message);
  751. return $message;
  752. }
  753. // Just in case it wasn't determined yet whether UTF-8 is enabled.
  754. if (!isset($context['utf8']))
  755. $context['utf8'] = (empty($modSettings['global_character_set']) ? $txt['lang_character_set'] : $modSettings['global_character_set']) === 'UTF-8';
  756. // If we are not doing every tag then we don't cache this run.
  757. if (!empty($parse_tags) && !empty($bbc_codes))
  758. {
  759. $temp_bbc = $bbc_codes;
  760. $bbc_codes = array();
  761. }
  762. // Sift out the bbc for a performance improvement.
  763. if (empty($bbc_codes) || $message === false || !empty($parse_tags))
  764. {
  765. if (!empty($modSettings['disabledBBC']))
  766. {
  767. $temp = explode(',', strtolower($modSettings['disabledBBC']));
  768. foreach ($temp as $tag)
  769. $disabled[trim($tag)] = true;
  770. }
  771. if (empty($modSettings['enableEmbeddedFlash']))
  772. $disabled['flash'] = true;
  773. /* The following bbc are formatted as an array, with keys as follows:
  774. tag: the tag's name - should be lowercase!
  775. type: one of...
  776. - (missing): [tag]parsed content[/tag]
  777. - unparsed_equals: [tag=xyz]parsed content[/tag]
  778. - parsed_equals: [tag=parsed data]parsed content[/tag]
  779. - unparsed_content: [tag]unparsed content[/tag]
  780. - closed: [tag], [tag/], [tag /]
  781. - unparsed_commas: [tag=1,2,3]parsed content[/tag]
  782. - unparsed_commas_content: [tag=1,2,3]unparsed content[/tag]
  783. - unparsed_equals_content: [tag=...]unparsed content[/tag]
  784. parameters: an optional array of parameters, for the form
  785. [tag abc=123]content[/tag]. The array is an associative array
  786. where the keys are the parameter names, and the values are an
  787. array which may contain the following:
  788. - match: a regular expression to validate and match the value.
  789. - quoted: true if the value should be quoted.
  790. - validate: callback to evaluate on the data, which is $data.
  791. - value: a string in which to replace $1 with the data.
  792. either it or validate may be used, not both.
  793. - optional: true if the parameter is optional.
  794. test: a regular expression to test immediately after the tag's
  795. '=', ' ' or ']'. Typically, should have a \] at the end.
  796. Optional.
  797. content: only available for unparsed_content, closed,
  798. unparsed_commas_content, and unparsed_equals_content.
  799. $1 is replaced with the content of the tag. Parameters
  800. are replaced in the form {param}. For unparsed_commas_content,
  801. $2, $3, ..., $n are replaced.
  802. before: only when content is not used, to go before any
  803. content. For unparsed_equals, $1 is replaced with the value.
  804. For unparsed_commas, $1, $2, ..., $n are replaced.
  805. after: similar to before in every way, except that it is used
  806. when the tag is closed.
  807. disabled_content: used in place of content when the tag is
  808. disabled. For closed, default is '', otherwise it is '$1' if
  809. block_level is false, '<div>$1</div>' elsewise.
  810. disabled_before: used in place of before when disabled. Defaults
  811. to '<div>' if block_level, '' if not.
  812. disabled_after: used in place of after when disabled. Defaults
  813. to '</div>' if block_level, '' if not.
  814. block_level: set to true the tag is a "block level" tag, similar
  815. to HTML. Block level tags cannot be nested inside tags that are
  816. not block level, and will not be implicitly closed as easily.
  817. One break following a block level tag may also be removed.
  818. trim: if set, and 'inside' whitespace after the begin tag will be
  819. removed. If set to 'outside', whitespace after the end tag will
  820. meet the same fate.
  821. validate: except when type is missing or 'closed', a callback to
  822. validate the data as $data. Depending on the tag's type, $data
  823. may be a string or an array of strings (corresponding to the
  824. replacement.)
  825. quoted: when type is 'unparsed_equals' or 'parsed_equals' only,
  826. may be not set, 'optional', or 'required' corresponding to if
  827. the content may be quoted. This allows the parser to read
  828. [tag="abc]def[esdf]"] properly.
  829. require_parents: an array of tag names, or not set. If set, the
  830. enclosing tag *must* be one of the listed tags, or parsing won't
  831. occur.
  832. require_children: similar to require_parents, if set children
  833. won't be parsed if they are not in the list.
  834. disallow_children: similar to, but very different from,
  835. require_children, if it is set the listed tags will not be
  836. parsed inside the tag.
  837. parsed_tags_allowed: an array restricting what BBC can be in the
  838. parsed_equals parameter, if desired.
  839. */
  840. $codes = array(
  841. array(
  842. 'tag' => 'abbr',
  843. 'type' => 'unparsed_equals',
  844. 'before' => '<abbr title="$1">',
  845. 'after' => '</abbr>',
  846. 'quoted' => 'optional',
  847. 'disabled_after' => ' ($1)',
  848. ),
  849. array(
  850. 'tag' => 'acronym',
  851. 'type' => 'unparsed_equals',
  852. 'before' => '<acronym title="$1">',
  853. 'after' => '</acronym>',
  854. 'quoted' => 'optional',
  855. 'disabled_after' => ' ($1)',
  856. ),
  857. array(
  858. 'tag' => 'anchor',
  859. 'type' => 'unparsed_equals',
  860. 'test' => '[#]?([A-Za-z][A-Za-z0-9_\-]*)\]',
  861. 'before' => '<span id="post_$1">',
  862. 'after' => '</span>',
  863. ),
  864. array(
  865. 'tag' => 'b',
  866. 'before' => '<strong>',
  867. 'after' => '</strong>',
  868. ),
  869. array(
  870. 'tag' => 'bdo',
  871. 'type' => 'unparsed_equals',
  872. 'before' => '<bdo dir="$1">',
  873. 'after' => '</bdo>',
  874. 'test' => '(rtl|ltr)\]',
  875. 'block_level' => true,
  876. ),
  877. array(
  878. 'tag' => 'black',
  879. 'before' => '<span style="color: black;" class="bbc_color">',
  880. 'after' => '</span>',
  881. ),
  882. array(
  883. 'tag' => 'blue',
  884. 'before' => '<span style="color: blue;" class="bbc_color">',
  885. 'after' => '</span>',
  886. ),
  887. array(
  888. 'tag' => 'br',
  889. 'type' => 'closed',
  890. 'content' => '<br />',
  891. ),
  892. array(
  893. 'tag' => 'center',
  894. 'before' => '<div align="center">',
  895. 'after' => '</div>',
  896. 'block_level' => true,
  897. ),
  898. array(
  899. 'tag' => 'code',
  900. 'type' => 'unparsed_content',
  901. 'content' => '<div class="codeheader">' . $txt['code'] . ': <a href="javascript:void(0);" onclick="return smfSelectText(this);" class="codeoperation">' . $txt['code_select'] . '</a></div>' . ($context['browser']['is_gecko'] || $context['browser']['is_opera'] ? '<pre style="margin: 0; padding: 0;">' : '') . '<code class="bbc_code">$1</code>' . ($context['browser']['is_gecko'] || $context['browser']['is_opera'] ? '</pre>' : ''),
  902. // @todo Maybe this can be simplified?
  903. 'validate' => isset($disabled['code']) ? null : create_function('&$tag, &$data, $disabled', '
  904. global $context;
  905. if (!isset($disabled[\'code\']))
  906. {
  907. $php_parts = preg_split(\'~(&lt;\?php|\?&gt;)~\', $data, -1, PREG_SPLIT_DELIM_CAPTURE);
  908. for ($php_i = 0, $php_n = count($php_parts); $php_i < $php_n; $php_i++)
  909. {
  910. // Do PHP code coloring?
  911. if ($php_parts[$php_i] != \'&lt;?php\')
  912. continue;
  913. $php_string = \'\';
  914. while ($php_i + 1 < count($php_parts) && $php_parts[$php_i] != \'?&gt;\')
  915. {
  916. $php_string .= $php_parts[$php_i];
  917. $php_parts[$php_i++] = \'\';
  918. }
  919. $php_parts[$php_i] = highlight_php_code($php_string . $php_parts[$php_i]);
  920. }
  921. // Fix the PHP code stuff...
  922. $data = str_replace("<pre style=\"display: inline;\">\t</pre>", "\t", implode(\'\', $php_parts));
  923. // Older browsers are annoying, aren\'t they?
  924. if ($context[\'browser\'][\'is_ie4\'] || $context[\'browser\'][\'is_ie5\'] || $context[\'browser\'][\'is_ie5.5\'])
  925. $data = str_replace("\t", "<pre style=\"display: inline;\">\t</pre>", $data);
  926. else
  927. $data = str_replace("\t", "<span style=\"white-space: pre;\">\t</span>", $data);
  928. // Recent Opera bug requiring temporary fix. &nsbp; is needed before </code> to avoid broken selection.
  929. if ($context[\'browser\'][\'is_opera\'])
  930. $data .= \'&nbsp;\';
  931. }'),
  932. 'block_level' => true,
  933. ),
  934. array(
  935. 'tag' => 'code',
  936. 'type' => 'unparsed_equals_content',
  937. 'content' => '<div class="codeheader">' . $txt['code'] . ': ($2) <a href="#" onclick="return smfSelectText(this);" class="codeoperation">' . $txt['code_select'] . '</a></div>' . ($context['browser']['is_gecko'] || $context['browser']['is_opera'] ? '<pre style="margin: 0; padding: 0;">' : '') . '<code class="bbc_code">$1</code>' . ($context['browser']['is_gecko'] || $context['browser']['is_opera'] ? '</pre>' : ''),
  938. // @todo Maybe this can be simplified?
  939. 'validate' => isset($disabled['code']) ? null : create_function('&$tag, &$data, $disabled', '
  940. global $context;
  941. if (!isset($disabled[\'code\']))
  942. {
  943. $php_parts = preg_split(\'~(&lt;\?php|\?&gt;)~\', $data[0], -1, PREG_SPLIT_DELIM_CAPTURE);
  944. for ($php_i = 0, $php_n = count($php_parts); $php_i < $php_n; $php_i++)
  945. {
  946. // Do PHP code coloring?
  947. if ($php_parts[$php_i] != \'&lt;?php\')
  948. continue;
  949. $php_string = \'\';
  950. while ($php_i + 1 < count($php_parts) && $php_parts[$php_i] != \'?&gt;\')
  951. {
  952. $php_string .= $php_parts[$php_i];
  953. $php_parts[$php_i++] = \'\';
  954. }
  955. $php_parts[$php_i] = highlight_php_code($php_string . $php_parts[$php_i]);
  956. }
  957. // Fix the PHP code stuff...
  958. $data[0] = str_replace("<pre style=\"display: inline;\">\t</pre>", "\t", implode(\'\', $php_parts));
  959. // Older browsers are annoying, aren\'t they?
  960. if ($context[\'browser\'][\'is_ie4\'] || $context[\'browser\'][\'is_ie5\'] || $context[\'browser\'][\'is_ie5.5\'])
  961. $data[0] = str_replace("\t", "<pre style=\"display: inline;\">\t</pre>", $data[0]);
  962. else
  963. $data[0] = str_replace("\t", "<span style=\"white-space: pre;\">\t</span>", $data[0]);
  964. // Recent Opera bug requiring temporary fix. &nsbp; is needed before </code> to avoid broken selection.
  965. if ($context[\'browser\'][\'is_opera\'])
  966. $data[0] .= \'&nbsp;\';
  967. }'),
  968. 'block_level' => true,
  969. ),
  970. array(
  971. 'tag' => 'color',
  972. 'type' => 'unparsed_equals',
  973. 'test' => '(#[\da-fA-F]{3}|#[\da-fA-F]{6}|[A-Za-z]{1,20}|rgb\(\d{1,3}, ?\d{1,3}, ?\d{1,3}\))\]',
  974. 'before' => '<span style="color: $1;" class="bbc_color">',
  975. 'after' => '</span>',
  976. ),
  977. array(
  978. 'tag' => 'email',
  979. 'type' => 'unparsed_content',
  980. 'content' => '<a href="mailto:$1" class="bbc_email">$1</a>',
  981. // @todo Should this respect guest_hideContacts?
  982. 'validate' => create_function('&$tag, &$data, $disabled', '$data = strtr($data, array(\'<br />\' => \'\'));'),
  983. ),
  984. array(
  985. 'tag' => 'email',
  986. 'type' => 'unparsed_equals',
  987. 'before' => '<a href="mailto:$1" class="bbc_email">',
  988. 'after' => '</a>',
  989. // @todo Should this respect guest_hideContacts?
  990. 'disallow_children' => array('email', 'ftp', 'url', 'iurl'),
  991. 'disabled_after' => ' ($1)',
  992. ),
  993. array(
  994. 'tag' => 'flash',
  995. 'type' => 'unparsed_commas_content',
  996. 'test' => '\d+,\d+\]',
  997. 'content' => ($context['browser']['is_ie'] && !$context['browser']['is_mac_ie'] ? '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="$2" height="$3"><param name="movie" value="$1" /><param name="play" value="true" /><param name="loop" value="true" /><param name="quality" value="high" /><param name="AllowScriptAccess" value="never" /><embed src="$1" width="$2" height="$3" play="true" loop="true" quality="high" AllowScriptAccess="never" /><noembed><a href="$1" target="_blank" class="new_win">$1</a></noembed></object>' : '<embed type="application/x-shockwave-flash" src="$1" width="$2" height="$3" play="true" loop="true" quality="high" AllowScriptAccess="never" /><noembed><a href="$1" target="_blank" class="new_win">$1</a></noembed>'),
  998. 'validate' => create_function('&$tag, &$data, $disabled', '
  999. if (isset($disabled[\'url\']))
  1000. $tag[\'content\'] = \'$1\';
  1001. elseif (strpos($data[0], \'http://\') !== 0 && strpos($data[0], \'https://\') !== 0)
  1002. $data[0] = \'http://\' . $data[0];
  1003. '),
  1004. 'disabled_content' => '<a href="$1" target="_blank" class="new_win">$1</a>',
  1005. ),
  1006. array(
  1007. 'tag' => 'font',
  1008. 'type' => 'unparsed_equals',
  1009. 'test' => '[A-Za-z0-9_,\-\s]+?\]',
  1010. 'before' => '<span style="font-family: $1;" class="bbc_font">',
  1011. 'after' => '</span>',
  1012. ),
  1013. array(
  1014. 'tag' => 'ftp',
  1015. 'type' => 'unparsed_content',
  1016. 'content' => '<a href="$1" class="bbc_ftp new_win" target="_blank">$1</a>',
  1017. 'validate' => create_function('&$tag, &$data, $disabled', '
  1018. $data = strtr($data, array(\'<br />\' => \'\'));
  1019. if (strpos($data, \'ftp://\') !== 0 && strpos($data, \'ftps://\') !== 0)
  1020. $data = \'ftp://\' . $data;
  1021. '),
  1022. ),
  1023. array(
  1024. 'tag' => 'ftp',
  1025. 'type' => 'unparsed_equals',
  1026. 'before' => '<a href="$1" class="bbc_ftp new_win" target="_blank">',
  1027. 'after' => '</a>',
  1028. 'validate' => create_function('&$tag, &$data, $disabled', '
  1029. if (strpos($data, \'ftp://\') !== 0 && strpos($data, \'ftps://\') !== 0)
  1030. $data = \'ftp://\' . $data;
  1031. '),
  1032. 'disallow_children' => array('email', 'ftp', 'url', 'iurl'),
  1033. 'disabled_after' => ' ($1)',
  1034. ),
  1035. array(
  1036. 'tag' => 'glow',
  1037. 'type' => 'unparsed_commas',
  1038. 'test' => '[#0-9a-zA-Z\-]{3,12},([012]\d{1,2}|\d{1,2})(,[^]]+)?\]',
  1039. 'before' => $context['browser']['is_ie'] ? '<table border="0" cellpadding="0" cellspacing="0" style="display: inline; vertical-align: middle; font: inherit;"><tr><td style="filter: Glow(color=$1, strength=$2); font: inherit;">' : '<span style="text-shadow: $1 1px 1px 1px">',
  1040. 'after' => $context['browser']['is_ie'] ? '</td></tr></table> ' : '</span>',
  1041. ),
  1042. array(
  1043. 'tag' => 'green',
  1044. 'before' => '<span style="color: green;" class="bbc_color">',
  1045. 'after' => '</span>',
  1046. ),
  1047. array(
  1048. 'tag' => 'html',
  1049. 'type' => 'unparsed_content',
  1050. 'content' => '$1',
  1051. 'block_level' => true,
  1052. 'disabled_content' => '$1',
  1053. ),
  1054. array(
  1055. 'tag' => 'hr',
  1056. 'type' => 'closed',
  1057. 'content' => '<hr />',
  1058. 'block_level' => true,
  1059. ),
  1060. array(
  1061. 'tag' => 'i',
  1062. 'before' => '<em>',
  1063. 'after' => '</em>',
  1064. ),
  1065. array(
  1066. 'tag' => 'img',
  1067. 'type' => 'unparsed_content',
  1068. 'parameters' => array(
  1069. 'alt' => array('optional' => true),
  1070. 'width' => array('optional' => true, 'value' => ' width="$1"', 'match' => '(\d+)'),
  1071. 'height' => array('optional' => true, 'value' => ' height="$1"', 'match' => '(\d+)'),
  1072. ),
  1073. 'content' => '<img src="$1" alt="{alt}"{width}{height} class="bbc_img resized" />',
  1074. 'validate' => create_function('&$tag, &$data, $disabled', '
  1075. $data = strtr($data, array(\'<br />\' => \'\'));
  1076. if (strpos($data, \'http://\') !== 0 && strpos($data, \'https://\') !== 0)
  1077. $data = \'http://\' . $data;
  1078. '),
  1079. 'disabled_content' => '($1)',
  1080. ),
  1081. array(
  1082. 'tag' => 'img',
  1083. 'type' => 'unparsed_content',
  1084. 'content' => '<img src="$1" alt="" class="bbc_img" />',
  1085. 'validate' => create_function('&$tag, &$data, $disabled', '
  1086. $data = strtr($data, array(\'<br />\' => \'\'));
  1087. if (strpos($data, \'http://\') !== 0 && strpos($data, \'https://\') !== 0)
  1088. $data = \'http://\' . $data;
  1089. '),
  1090. 'disabled_content' => '($1)',
  1091. ),
  1092. array(
  1093. 'tag' => 'iurl',
  1094. 'type' => 'unparsed_content',
  1095. 'content' => '<a href="$1" class="bbc_link">$1</a>',
  1096. 'validate' => create_function('&$tag, &$data, $disabled', '
  1097. $data = strtr($data, array(\'<br />\' => \'\'));
  1098. if (strpos($data, \'http://\') !== 0 && strpos($data, \'https://\') !== 0)
  1099. $data = \'http://\' . $data;
  1100. '),
  1101. ),
  1102. array(
  1103. 'tag' => 'iurl',
  1104. 'type' => 'unparsed_equals',
  1105. 'before' => '<a href="$1" class="bbc_link">',
  1106. 'after' => '</a>',
  1107. 'validate' => create_function('&$tag, &$data, $disabled', '
  1108. if (substr($data, 0, 1) == \'#\')
  1109. $data = \'#post_\' . substr($data, 1);
  1110. elseif (strpos($data, \'http://\') !== 0 && strpos($data, \'https://\') !== 0)
  1111. $data = \'http://\' . $data;
  1112. '),
  1113. 'disallow_children' => array('email', 'ftp', 'url', 'iurl'),
  1114. 'disabled_after' => ' ($1)',
  1115. ),
  1116. array(
  1117. 'tag' => 'left',
  1118. 'before' => '<div style="text-align: left;">',
  1119. 'after' => '</div>',
  1120. 'block_level' => true,
  1121. ),
  1122. array(
  1123. 'tag' => 'li',
  1124. 'before' => '<li>',
  1125. 'after' => '</li>',
  1126. 'trim' => 'outside',
  1127. 'require_parents' => array('list'),
  1128. 'block_level' => true,
  1129. 'disabled_before' => '',
  1130. 'disabled_after' => '<br />',
  1131. ),
  1132. array(
  1133. 'tag' => 'list',
  1134. 'before' => '<ul class="bbc_list">',
  1135. 'after' => '</ul>',
  1136. 'trim' => 'inside',
  1137. 'require_children' => array('li', 'list'),
  1138. 'block_level' => true,
  1139. ),
  1140. array(
  1141. 'tag' => 'list',
  1142. 'parameters' => array(
  1143. 'type' => array('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)'),
  1144. ),
  1145. 'before' => '<ul class="bbc_list" style="list-style-type: {type};">',
  1146. 'after' => '</ul>',
  1147. 'trim' => 'inside',
  1148. 'require_children' => array('li'),
  1149. 'block_level' => true,
  1150. ),
  1151. array(
  1152. 'tag' => 'ltr',
  1153. 'before' => '<div dir="ltr">',
  1154. 'after' => '</div>',
  1155. 'block_level' => true,
  1156. ),
  1157. array(
  1158. 'tag' => 'me',
  1159. 'type' => 'unparsed_equals',
  1160. 'before' => '<div class="meaction">* $1 ',
  1161. 'after' => '</div>',
  1162. 'quoted' => 'optional',
  1163. 'block_level' => true,
  1164. 'disabled_before' => '/me ',
  1165. 'disabled_after' => '<br />',
  1166. ),
  1167. array(
  1168. 'tag' => 'move',
  1169. 'before' => '<marquee>',
  1170. 'after' => '</marquee>',
  1171. 'block_level' => true,
  1172. 'disallow_children' => array('move'),
  1173. ),
  1174. array(
  1175. 'tag' => 'nobbc',
  1176. 'type' => 'unparsed_content',
  1177. 'content' => '$1',
  1178. ),
  1179. array(
  1180. 'tag' => 'php',
  1181. 'type' => 'unparsed_content',
  1182. 'content' => '<span class="phpcode">$1</span>',
  1183. 'validate' => isset($disabled['php']) ? null : create_function('&$tag, &$data, $disabled', '
  1184. if (!isset($disabled[\'php\']))
  1185. {
  1186. $add_begin = substr(trim($data), 0, 5) != \'&lt;?\';
  1187. $data = highlight_php_code($add_begin ? \'&lt;?php \' . $data . \'?&gt;\' : $data);
  1188. if ($add_begin)
  1189. $data = preg_replace(array(\'~^(.+?)&lt;\?.{0,40}?php(?:&nbsp;|\s)~\', \'~\?&gt;((?:</(font|span)>)*)$~\'), \'$1\', $data, 2);
  1190. }'),
  1191. 'block_level' => false,
  1192. 'disabled_content' => '$1',
  1193. ),
  1194. array(
  1195. 'tag' => 'pre',
  1196. 'before' => '<pre>',
  1197. 'after' => '</pre>',
  1198. ),
  1199. array(
  1200. 'tag' => 'quote',
  1201. 'before' => '<div class="quoteheader"><div class="topslice_quote">' . $txt['quote'] . '</div></div><blockquote>',
  1202. 'after' => '</blockquote><div class="quotefooter"><div class="botslice_quote"></div></div>',
  1203. 'block_level' => true,
  1204. ),
  1205. array(
  1206. 'tag' => 'quote',
  1207. 'parameters' => array(
  1208. 'author' => array('match' => '(.{1,192}?)', 'quoted' => true),
  1209. ),
  1210. 'before' => '<div class="quoteheader"><div class="topslice_quote">' . $txt['quote_from'] . ': {author}</div></div><blockquote>',
  1211. 'after' => '</blockquote><div class="quotefooter"><div class="botslice_quote"></div></div>',
  1212. 'block_level' => true,
  1213. ),
  1214. array(
  1215. 'tag' => 'quote',
  1216. 'type' => 'parsed_equals',
  1217. 'before' => '<div class="quoteheader"><div class="topslice_quote">' . $txt['quote_from'] . ': $1</div></div><blockquote>',
  1218. 'after' => '</blockquote><div class="quotefooter"><div class="botslice_quote"></div></div>',
  1219. 'quoted' => 'optional',
  1220. // Don't allow everything to be embedded with the author name.
  1221. 'parsed_tags_allowed' => array('url', 'iurl', 'ftp'),
  1222. 'block_level' => true,
  1223. ),
  1224. array(
  1225. 'tag' => 'quote',
  1226. 'parameters' => array(
  1227. 'author' => array('match' => '([^<>]{1,192}?)'),
  1228. 'link' => array('match' => '(?:board=\d+;)?((?:topic|threadid)=[\dmsg#\./]{1,40}(?:;start=[\dmsg#\./]{1,40})?|action=profile;u=\d+)'),
  1229. 'date' => array('match' => '(\d+)', 'validate' => 'timeformat'),
  1230. ),
  1231. 'before' => '<div class="quoteheader"><div class="topslice_quote"><a href="' . $scripturl . '?{link}">' . $txt['quote_from'] . ': {author} ' . $txt['search_on'] . ' {date}</a></div></div><blockquote>',
  1232. 'after' => '</blockquote><div class="quotefooter"><div class="botslice_quote"></div></div>',
  1233. 'block_level' => true,
  1234. ),
  1235. array(
  1236. 'tag' => 'quote',
  1237. 'parameters' => array(
  1238. 'author' => array('match' => '(.{1,192}?)'),
  1239. ),
  1240. 'before' => '<div class="quoteheader"><div class="topslice_quote">' . $txt['quote_from'] . ': {author}</div></div><blockquote>',
  1241. 'after' => '</blockquote><div class="quotefooter"><div class="botslice_quote"></div></div>',
  1242. 'block_level' => true,
  1243. ),
  1244. array(
  1245. 'tag' => 'red',
  1246. 'before' => '<span style="color: red;" class="bbc_color">',
  1247. 'after' => '</span>',
  1248. ),
  1249. array(
  1250. 'tag' => 'right',
  1251. 'before' => '<div style="text-align: right;">',
  1252. 'after' => '</div>',
  1253. 'block_level' => true,
  1254. ),
  1255. array(
  1256. 'tag' => 'rtl',
  1257. 'before' => '<div dir="rtl">',
  1258. 'after' => '</div>',
  1259. 'block_level' => true,
  1260. ),
  1261. array(
  1262. 'tag' => 's',
  1263. 'before' => '<del>',
  1264. 'after' => '</del>',
  1265. ),
  1266. array(
  1267. 'tag' => 'shadow',
  1268. 'type' => 'unparsed_commas',
  1269. 'test' => '[#0-9a-zA-Z\-]{3,12},(left|right|top|bottom|[0123]\d{0,2})\]',
  1270. 'before' => $context['browser']['is_ie'] ? '<span style="display: inline-block; filter: Shadow(color=$1, direction=$2); height: 1.2em;">' : '<span style="text-shadow: $1 $2">',
  1271. 'after' => '</span>',
  1272. 'validate' => $context['browser']['is_ie'] ? create_function('&$tag, &$data, $disabled', '
  1273. if ($data[1] == \'left\')
  1274. $data[1] = 270;
  1275. elseif ($data[1] == \'right\')
  1276. $data[1] = 90;
  1277. elseif ($data[1] == \'top\')
  1278. $data[1] = 0;
  1279. elseif ($data[1] == \'bottom\')
  1280. $data[1] = 180;
  1281. else
  1282. $data[1] = (int) $data[1];') : create_function('&$tag, &$data, $disabled', '
  1283. if ($data[1] == \'top\' || (is_numeric($data[1]) && $data[1] < 50))
  1284. $data[1] = \'0 -2px 1px\';
  1285. elseif ($data[1] == \'right\' || (is_numeric($data[1]) && $data[1] < 100))
  1286. $data[1] = \'2px 0 1px\';
  1287. elseif ($data[1] == \'bottom\' || (is_numeric($data[1]) && $data[1] < 190))
  1288. $data[1] = \'0 2px 1px\';
  1289. elseif ($data[1] == \'left\' || (is_numeric($data[1]) && $data[1] < 280))
  1290. $data[1] = \'-2px 0 1px\';
  1291. else
  1292. $data[1] = \'1px 1px 1px\';'),
  1293. ),
  1294. array(
  1295. 'tag' => 'size',
  1296. 'type' => 'unparsed_equals',
  1297. 'test' => '([1-9][\d]?p[xt]|small(?:er)?|large[r]?|x[x]?-(?:small|large)|medium|(0\.[1-9]|[1-9](\.[\d][\d]?)?)?em)\]',
  1298. 'before' => '<span style="font-size: $1;" class="bbc_size">',
  1299. 'after' => '</span>',
  1300. ),
  1301. array(
  1302. 'tag' => 'size',
  1303. 'type' => 'unparsed_equals',
  1304. 'test' => '[1-7]\]',
  1305. 'before' => '<span style="font-size: $1;" class="bbc_size">',
  1306. 'after' => '</span>',
  1307. 'validate' => create_function('&$tag, &$data, $disabled', '
  1308. $sizes = array(1 => 0.7, 2 => 1.0, 3 => 1.35, 4 => 1.45, 5 => 2.0, 6 => 2.65, 7 => 3.95);
  1309. $data = $sizes[$data] . \'em\';'
  1310. ),
  1311. ),
  1312. array(
  1313. 'tag' => 'sub',
  1314. 'before' => '<sub>',
  1315. 'after' => '</sub>',
  1316. ),
  1317. array(
  1318. 'tag' => 'sup',
  1319. 'before' => '<sup>',
  1320. 'after' => '</sup>',
  1321. ),
  1322. array(
  1323. 'tag' => 'table',
  1324. 'before' => '<table class="bbc_table">',
  1325. 'after' => '</table>',
  1326. 'trim' => 'inside',
  1327. 'require_children' => array('tr'),
  1328. 'block_level' => true,
  1329. ),
  1330. array(
  1331. 'tag' => 'td',
  1332. 'before' => '<td>',
  1333. 'after' => '</td>',
  1334. 'require_parents' => array('tr'),
  1335. 'trim' => 'outside',
  1336. 'block_level' => true,
  1337. 'disabled_before' => '',
  1338. 'disabled_after' => '',
  1339. ),
  1340. array(
  1341. 'tag' => 'time',
  1342. 'type' => 'unparsed_content',
  1343. 'content' => '$1',
  1344. 'validate' => create_function('&$tag, &$data, $disabled', '
  1345. if (is_numeric($data))
  1346. $data = timeformat($data);
  1347. else
  1348. $tag[\'content\'] = \'[time]$1[/time]\';'),
  1349. ),
  1350. array(
  1351. 'tag' => 'tr',
  1352. 'before' => '<tr>',
  1353. 'after' => '</tr>',
  1354. 'require_parents' => array('table'),
  1355. 'require_children' => array('td'),
  1356. 'trim' => 'both',
  1357. 'block_level' => true,
  1358. 'disabled_before' => '',
  1359. 'disabled_after' => '',
  1360. ),
  1361. array(
  1362. 'tag' => 'tt',
  1363. 'before' => '<tt class="bbc_tt">',
  1364. 'after' => '</tt>',
  1365. ),
  1366. array(
  1367. 'tag' => 'u',
  1368. 'before' => '<span class="bbc_u">',
  1369. 'after' => '</span>',
  1370. ),
  1371. array(
  1372. 'tag' => 'url',
  1373. 'type' => 'unparsed_content',
  1374. 'content' => '<a href="$1" class="bbc_link" target="_blank">$1</a>',
  1375. 'validate' => create_function('&$tag, &$data, $disabled', '
  1376. $data = strtr($data, array(\'<br />\' => \'\'));
  1377. if (strpos($data, \'http://\') !== 0 && strpos($data, \'https://\') !== 0)
  1378. $data = \'http://\' . $data;
  1379. '),
  1380. ),
  1381. array(
  1382. 'tag' => 'url',
  1383. 'type' => 'unparsed_equals',
  1384. 'before' => '<a href="$1" class="bbc_link" target="_blank">',
  1385. 'after' => '</a>',
  1386. 'validate' => create_function('&$tag, &$data, $disabled', '
  1387. if (strpos($data, \'http://\') !== 0 && strpos($data, \'https://\') !== 0)
  1388. $data = \'http://\' . $data;
  1389. '),
  1390. 'disallow_children' => array('email', 'ftp', 'url', 'iurl'),
  1391. 'disabled_after' => ' ($1)',
  1392. ),
  1393. array(
  1394. 'tag' => 'white',
  1395. 'before' => '<span style="color: white;" class="bbc_color">',
  1396. 'after' => '</span>',
  1397. ),
  1398. );
  1399. // Let mods add new BBC without hassle.
  1400. call_integration_hook('integrate_bbc_codes', array(&$codes));
  1401. // This is mainly for the bbc manager, so it's easy to add tags above. Custom BBC should be added above this line.
  1402. if ($message === false)
  1403. {
  1404. if (isset($temp_bbc))
  1405. $bbc_codes = $temp_bbc;
  1406. return $codes;
  1407. }
  1408. // So the parser won't skip them.
  1409. $itemcodes = array(
  1410. '*' => 'disc',
  1411. '@' => 'disc',
  1412. '+' => 'square',
  1413. 'x' => 'square',
  1414. '#' => 'square',
  1415. 'o' => 'circle',
  1416. 'O' => 'circle',
  1417. '0' => 'circle',
  1418. );
  1419. if (!isset($disabled['li']) && !isset($disabled['list']))
  1420. {
  1421. foreach ($itemcodes as $c => $dummy)
  1422. $bbc_codes[$c] = array();
  1423. }
  1424. // Inside these tags autolink is not recommendable.
  1425. $no_autolink_tags = array(
  1426. 'url',
  1427. 'iurl',
  1428. 'ftp',
  1429. 'email',
  1430. );
  1431. // Shhhh!
  1432. if (!isset($disabled['color']))
  1433. {
  1434. $codes[] = array(
  1435. 'tag' => 'chrissy',
  1436. 'before' => '<span style="color: #cc0099;">',
  1437. 'after' => ' :-*</span>',
  1438. );
  1439. $codes[] = array(
  1440. 'tag' => 'kissy',
  1441. 'before' => '<span style="color: #cc0099;">',
  1442. 'after' => ' :-*</span>',
  1443. );
  1444. }
  1445. foreach ($codes as $code)
  1446. {
  1447. // If we are not doing every tag only do ones we are interested in.
  1448. if (empty($parse_tags) || in_array($code['tag'], $parse_tags))
  1449. $bbc_codes[substr($code['tag'], 0, 1)][] = $code;
  1450. }
  1451. $codes = null;
  1452. }
  1453. // Shall we take the time to cache this?
  1454. if ($cache_id != '' && !empty($modSettings['cache_enable']) && (($modSettings['cache_enable'] >= 2 && strlen($message) > 1000) || strlen($message) > 2400) && empty($parse_tags))
  1455. {
  1456. // It's likely this will change if the message is modified.
  1457. $cache_key = 'parse:' . $cache_id . '-' . md5(md5($message) . '-' . $smileys . (empty($disabled) ? '' : implode(',', array_keys($disabled))) . serialize($context['browser']) . $txt['lang_locale'] . $user_info['time_offset'] . $user_info['time_format']);
  1458. if (($temp = cache_get_data($cache_key, 240)) != null)
  1459. return $temp;
  1460. $cache_t = microtime();
  1461. }
  1462. if ($smileys === 'print')
  1463. {
  1464. // [glow], [shadow], and [move] can't really be printed.
  1465. $disabled['glow'] = true;
  1466. $disabled['shadow'] = true;
  1467. $disabled['move'] = true;
  1468. // Colors can't well be displayed... supposed to be black and white.
  1469. $disabled['color'] = true;
  1470. $disabled['black'] = true;
  1471. $disabled['blue'] = true;
  1472. $disabled['white'] = true;
  1473. $disabled['red'] = true;
  1474. $disabled['green'] = true;
  1475. $disabled['me'] = true;
  1476. // Color coding doesn't make sense.
  1477. $disabled['php'] = true;
  1478. // Links are useless on paper... just show the link.
  1479. $disabled['ftp'] = true;
  1480. $disabled['url'] = true;
  1481. $disabled['iurl'] = true;
  1482. $disabled['email'] = true;
  1483. $disabled['flash'] = true;
  1484. // @todo Change maybe?
  1485. if (!isset($_GET['images']))
  1486. $disabled['img'] = true;
  1487. // @todo Interface/setting to add more?
  1488. }
  1489. $open_tags = array();
  1490. $message = strtr($message, array("\n" => '<br />'));
  1491. // The non-breaking-space looks a bit different each time.
  1492. $non_breaking_space = $context['utf8'] ? ($context['server']['complex_preg_chars'] ? '\x{A0}' : "\xC2\xA0") : '\xA0';
  1493. // This saves time by doing our break long words checks here.
  1494. if (!empty($modSettings['fixLongWords']) && $modSettings['fixLongWords'] > 5)
  1495. {
  1496. if ($context['browser']['is_gecko'] || $context['browser']['is_konqueror'])
  1497. $breaker = '<span style="margin: 0 -0.5ex 0 0;"> </span>';
  1498. // Opera...
  1499. elseif ($context['browser']['is_opera'])
  1500. $breaker = '<span style="margin: 0 -0.65ex 0 -1px;"> </span>';
  1501. // Internet Explorer...
  1502. else
  1503. $breaker = '<span style="width: 0; margin: 0 -0.6ex 0 -1px;"> </span>';
  1504. // PCRE will not be happy if we don't give it a short.
  1505. $modSettings['fixLongWords'] = (int) min(65535, $modSettings['fixLongWords']);
  1506. }
  1507. $pos = -1;
  1508. while ($pos !== false)
  1509. {
  1510. $last_pos = isset($last_pos) ? max($pos, $last_pos) : $pos;
  1511. $pos = strpos($message, '[', $pos + 1);
  1512. // Failsafe.
  1513. if ($pos === false || $last_pos > $pos)
  1514. $pos = strlen($message) + 1;
  1515. // Can't have a one letter smiley, URL, or email! (sorry.)
  1516. if ($last_pos < $pos - 1)
  1517. {
  1518. // Make sure the $last_pos is not negative.
  1519. $last_pos = max($last_pos, 0);
  1520. // Pick a block of data to do some raw fixing on.
  1521. $data = substr($message, $last_pos, $pos - $last_pos);
  1522. // Take care of some HTML!
  1523. if (!empty($modSettings['enablePostHTML']) && strpos($data, '&lt;') !== false)
  1524. {
  1525. $data = preg_replace('~&lt;a\s+href=((?:&quot;)?)((?:https?://|ftps?://|mailto:)\S+?)\\1&gt;~i', '[url=$2]', $data);
  1526. $data = preg_replace('~&lt;/a&gt;~i', '[/url]', $data);
  1527. // <br /> should be empty.
  1528. $empty_tags = array('br', 'hr');
  1529. foreach ($empty_tags as $tag)
  1530. $data = str_replace(array('&lt;' . $tag . '&gt;', '&lt;' . $tag . '/&gt;', '&lt;' . $tag . ' /&gt;'), '[' . $tag . ' /]', $data);
  1531. // b, u, i, s, pre... basic tags.
  1532. $closable_tags = array('b', 'u', 'i', 's', 'em', 'ins', 'del', 'pre', 'blockquote');
  1533. foreach ($closable_tags as $tag)
  1534. {
  1535. $diff = substr_count($data, '&lt;' . $tag . '&gt;') - substr_count($data, '&lt;/' . $tag . '&gt;');
  1536. $data = strtr($data, array('&lt;' . $tag . '&gt;' => '<' . $tag . '>', '&lt;/' . $tag . '&gt;' => '</' . $tag . '>'));
  1537. if ($diff > 0)
  1538. $data = substr($data, 0, -1) . str_repeat('</' . $tag . '>', $diff) . substr($data, -1);
  1539. }
  1540. // Do <img ... /> - with security... action= -> action-.
  1541. preg_match_all('~&lt;img\s+src=((?:&quot;)?)((?:https?://|ftps?://)\S+?)\\1(?:\s+alt=(&quot;.*?&quot;|\S*?))?(?:\s?/)?&gt;~i', $data, $matches, PREG_PATTERN_ORDER);
  1542. if (!empty($matches[0]))
  1543. {
  1544. $replaces = array();
  1545. foreach ($matches[2] as $match => $imgtag)
  1546. {
  1547. $alt = empty($matches[3][$match]) ? '' : ' alt=' . preg_replace('~^&quot;|&quot;$~', '', $matches[3][$match]);
  1548. // Remove action= from the URL - no funny business, now.
  1549. if (preg_match('~action(=|%3d)(?!dlattach)~i', $imgtag) != 0)
  1550. $imgtag = preg_replace('~action(?:=|%3d)(?!dlattach)~i', 'action-', $imgtag);
  1551. // Check if the image is larger than allowed.
  1552. if (!empty($modSettings['max_image_width']) && !empty($modSettings['max_image_height']))
  1553. {
  1554. list ($width, $height) = url_image_size($imgtag);
  1555. if (!empty($modSettings['max_image_width']) && $width > $modSettings['max_image_width'])
  1556. {
  1557. $height = (int) (($modSettings['max_image_width'] * $height) / $width);
  1558. $width = $modSettings['max_image_width'];
  1559. }
  1560. if (!empty($modSettings['max_image_height']) && $height > $modSettings['max_image_height'])
  1561. {
  1562. $width = (int) (($modSettings['max_image_height'] * $width) / $height);
  1563. $height = $modSettings['max_image_height'];
  1564. }
  1565. // Set the new image tag.
  1566. $replaces[$matches[0][$match]] = '[img width=' . $width . ' height=' . $height . $alt . ']' . $imgtag . '[/img]';
  1567. }
  1568. else
  1569. $replaces[$matches[0][$match]] = '[img' . $alt . ']' . $imgtag . '[/img]';
  1570. }
  1571. $data = strtr($data, $replaces);
  1572. }
  1573. }
  1574. if (!empty($modSettings['autoLinkUrls']))
  1575. {
  1576. // Are we inside tags that should be auto linked?
  1577. $no_autolink_area = false;
  1578. if (!empty($open_tags))
  1579. {
  1580. foreach ($open_tags as $open_tag)
  1581. if (in_array($open_tag['tag'], $no_autolink_tags))
  1582. $no_autolink_area = true;
  1583. }
  1584. // Don't go backwards.
  1585. // @todo Don't think is the real solution....
  1586. $lastAutoPos = isset($lastAutoPos) ? $lastAutoPos : 0;
  1587. if ($pos < $lastAutoPos)
  1588. $no_autolink_area = true;
  1589. $lastAutoPos = $pos;
  1590. if (!$no_autolink_area)
  1591. {
  1592. // Parse any URLs.... have to get rid of the @ problems some things cause... stupid email addresses.
  1593. if (!isset($disabled['url']) && (strpos($data, '://') !== false || strpos($data, 'www.') !== false) && strpos($data, '[url') === false)
  1594. {
  1595. // Switch out quotes really quick because they can cause problems.
  1596. $data = strtr($data, array('&#039;' => '\'', '&nbsp;' => $context['utf8'] ? "\xC2\xA0" : "\xA0", '&quot;' => '>">', '"' => '<"<', '&lt;' => '<lt<'));
  1597. // Only do this if the preg survives.
  1598. if (is_string($result = preg_replace(array(
  1599. '~(?<=[\s>\.(;\'"]|^)((?:http|https)://[\w\-_%@:|]+(?:\.[\w\-_%]+)*(?::\d+)?(?:/[\w\-_\~%\.@!,\?&;=#(){}+:\'\\\\]*)*[/\w\-_\~%@\?;=#}\\\\])~i',
  1600. '~(?<=[\s>\.(;\'"]|^)((?:ftp|ftps)://[\w\-_%@:|]+(?:\.[\w\-_%]+)*(?::\d+)?(?:/[\w\-_\~%\.@,\?&;=#(){}+:\'\\\\]*)*[/\w\-_\~%@\?;=#}\\\\])~i',
  1601. '~(?<=[\s>(\'<]|^)(www(?:\.[\w\-_]+)+(?::\d+)?(?:/[\w\-_\~%\.@!,\?&;=#(){}+:\'\\\\]*)*[/\w\-_\~%@\?;=#}\\\\])~i'
  1602. ), array(
  1603. '[url]$1[/url]',
  1604. '[ftp]$1[/ftp]',
  1605. '[url=http://$1]$1[/url]'
  1606. ), $data)))
  1607. $data = $result;
  1608. $data = strtr($data, array('\'' => '&#039;', $context['utf8'] ? "\xC2\xA0" : "\xA0" => '&nbsp;', '>">' => '&quot;', '<"<' => '"', '<lt<' => '&lt;'));
  1609. }
  1610. // Next, emails...
  1611. if (!isset($disabled['email']) && strpos($data, '@') !== false && strpos($data, '[email') === false)
  1612. {
  1613. $data = preg_replace('~(?<=[\?\s' . $non_breaking_space . '\[\]()*\\\;>]|^)([\w\-\.]{1,80}@[\w\-]+\.[\w\-\.]+[\w\-])(?=[?,\s' . $non_breaking_space . '\[\]()*\\\]|$|<br />|&nbsp;|&gt;|&lt;|&quot;|&#039;|\.(?:\.|;|&nbsp;|\s|$|<br />))~' . ($context['utf8'] ? 'u' : ''), '[email]$1[/email]', $data);
  1614. $data = preg_replace('~(?<=<br />)([\w\-\.]{1,80}@[\w\-]+\.[\w\-\.]+[\w\-])(?=[?\.,;\s' . $non_breaking_space . '\[\]()*\\\]|$|<br />|&nbsp;|&gt;|&lt;|&quot;|&#039;)~' . ($context['utf8'] ? 'u' : ''), '[email]$1[/email]', $data);
  1615. }
  1616. }
  1617. }
  1618. $data = strtr($data, array("\t" => '&nbsp;&nbsp;&nbsp;'));
  1619. if (!empty($modSettings['fixLongWords']) && $modSettings['fixLongWords'] > 5)
  1620. {
  1621. // The idea is, find words xx long, and then replace them with xx + space + more.
  1622. if ($smcFunc['strlen']($data) > $modSettings['fixLongWords'])
  1623. {
  1624. // This is done in a roundabout way because $breaker has "long words" :P.
  1625. $data = strtr($data, array($breaker => '< >', '&nbsp;' => $context['utf8'] ? "\xC2\xA0" : "\xA0"));
  1626. $data = preg_replace(
  1627. '~(?<=[>;:!? ' . $non_breaking_space . '\]()]|^)([\w' . ($context['utf8'] ? '\pL' : '') . '\.]{' . $modSettings['fixLongWords'] . ',})~e' . ($context['utf8'] ? 'u' : ''),
  1628. 'preg_replace(\'/(.{' . ($modSettings['fixLongWords'] - 1) . '})/' . ($context['utf8'] ? 'u' : '') . '\', \'\\$1< >\', \'$1\')',
  1629. $data);
  1630. $data = strtr($data, array('< >' => $breaker, $context['utf8'] ? "\xC2\xA0" : "\xA0" => '&nbsp;'));
  1631. }
  1632. }
  1633. // If it wasn't changed, no copying or other boring stuff has to happen!
  1634. if ($data != substr($message, $last_pos, $pos - $last_pos))
  1635. {
  1636. $message = substr($message, 0, $last_pos) . $data . substr($message, $pos);
  1637. // Since we changed it, look again in case we added or removed a tag. But we don't want to skip any.
  1638. $old_pos = strlen($data) + $last_pos;
  1639. $pos = strpos($message, '[', $last_pos);
  1640. $pos = $pos === false ? $old_pos : min($pos, $old_pos);
  1641. }
  1642. }
  1643. // Are we there yet? Are we there yet?
  1644. if ($pos >= strlen($message) - 1)
  1645. break;
  1646. $tags = strtolower(substr($message, $pos + 1, 1));
  1647. if ($tags == '/' && !empty($open_tags))
  1648. {
  1649. $pos2 = strpos($message, ']', $pos + 1);
  1650. if ($pos2 == $pos + 2)
  1651. continue;
  1652. $look_for = strtolower(substr($message, $pos + 2, $pos2 - $pos - 2));
  1653. $to_close = array();
  1654. $block_level = null;
  1655. do
  1656. {
  1657. $tag = array_pop($open_tags);
  1658. if (!$tag)
  1659. break;
  1660. if (!empty($tag['block_level']))
  1661. {
  1662. // Only find out if we need to.
  1663. if ($block_level === false)
  1664. {
  1665. array_push($open_tags, $tag);
  1666. break;
  1667. }
  1668. // The idea is, if we are LOOKING for a block level tag, we can close them on the way.
  1669. if (strlen($look_for) > 0 && isset($bbc_codes[$look_for[0]]))
  1670. {
  1671. foreach ($bbc_codes[$look_for[0]] as $temp)
  1672. if ($temp['tag'] == $look_for)
  1673. {
  1674. $block_level = !empty($temp['block_level']);
  1675. break;
  1676. }
  1677. }
  1678. if ($block_level !== true)
  1679. {
  1680. $block_level = false;
  1681. array_push($open_tags, $tag);
  1682. break;
  1683. }
  1684. }
  1685. $to_close[] = $tag;
  1686. }
  1687. while ($tag['tag'] != $look_for);
  1688. // Did we just eat through everything and not find it?
  1689. if ((empty($open_tags) && (empty($tag) || $tag['tag'] != $look_for)))
  1690. {
  1691. $open_tags = $to_close;
  1692. continue;
  1693. }
  1694. elseif (!empty($to_close) && $tag['tag'] != $look_for)
  1695. {
  1696. if ($block_level === null && isset($look_for[0], $bbc_codes[$look_for[0]]))
  1697. {
  1698. foreach ($bbc_codes[$look_for[0]] as $temp)
  1699. if ($temp['tag'] == $look_for)
  1700. {
  1701. $block_level = !empty($temp['block_level']);
  1702. break;
  1703. }
  1704. }
  1705. // We're not looking for a block level tag (or maybe even a tag that exists...)
  1706. if (!$block_level)
  1707. {
  1708. foreach ($to_close as $tag)
  1709. array_push($open_tags, $tag);
  1710. continue;
  1711. }
  1712. }
  1713. foreach ($to_close as $tag)
  1714. {
  1715. $message = substr($message, 0, $pos) . "\n" . $tag['after'] . "\n" . substr($message, $pos2 + 1);
  1716. $pos += strlen($tag['after']) + 2;
  1717. $pos2 = $pos - 1;
  1718. // See the comment at the end of the big loop - just eating whitespace ;).
  1719. if (!empty($tag['block_level']) && substr($message, $pos, 6) == '<br />')
  1720. $message = substr($message, 0, $pos) . substr($message, $pos + 6);
  1721. if (!empty($tag['trim']) && $tag['trim'] != 'inside' && preg_match('~(<br />|&nbsp;|\s)*~', substr($message, $pos), $matches) != 0)
  1722. $message = substr($message, 0, $pos) . substr($message, $pos + strlen($matches[0]));
  1723. }
  1724. if (!empty($to_close))
  1725. {
  1726. $to_close = array();
  1727. $pos--;
  1728. }
  1729. continue;
  1730. }
  1731. // No tags for this character, so just keep going (fastest possible course.)
  1732. if (!isset($bbc_codes[$tags]))
  1733. continue;
  1734. $inside = empty($open_tags) ? null : $open_tags[count($open_tags) - 1];
  1735. $tag = null;
  1736. foreach ($bbc_codes[$tags] as $possible)
  1737. {
  1738. // Not a match?
  1739. if (strtolower(substr($message, $pos + 1, strlen($possible['tag']))) != $possible['tag'])
  1740. continue;
  1741. $next_c = substr($message, $pos + 1 + strlen($possible['tag']), 1);
  1742. // A test validation?
  1743. if (isset($possible['test']) && preg_match('~^' . $possible['test'] . '~', substr($message, $pos + 1 + strlen($possible['tag']) + 1)) == 0)
  1744. continue;
  1745. // Do we want parameters?
  1746. elseif (!empty($possible['parameters']))
  1747. {
  1748. if ($next_c != ' ')
  1749. continue;
  1750. }
  1751. elseif (isset($possible['type']))
  1752. {
  1753. // Do we need an equal sign?
  1754. if (in_array($possible['type'], array('unparsed_equals', 'unparsed_commas', 'unparsed_commas_content', 'unparsed_equals_content', 'parsed_equals')) && $next_c != '=')
  1755. continue;
  1756. // Maybe we just want a /...
  1757. if ($possible['type'] == 'closed' && $next_c != ']' && substr($message, $pos + 1 + strlen($possible['tag']), 2) != '/]' && substr($message, $pos + 1 + strlen($possible['tag']), 3) != ' /]')
  1758. continue;
  1759. // An immediate ]?
  1760. if ($possible['type'] == 'unparsed_content' && $next_c != ']')
  1761. continue;
  1762. }
  1763. // No type means 'parsed_content', which demands an immediate ] without parameters!
  1764. elseif ($next_c != ']')
  1765. continue;
  1766. // Check allowed tree?
  1767. if (isset($possible['require_parents']) && ($inside === null || !in_array($inside['tag'], $possible['require_parents'])))
  1768. continue;
  1769. elseif (isset($inside['require_children']) && !in_array($possible['tag'], $inside['require_children']))
  1770. continue;
  1771. // If this is in the list of disallowed child tags, don't parse it.
  1772. elseif (isset($inside['disallow_children']) && in_array($possible['tag'], $inside['disallow_children']))
  1773. continue;
  1774. $pos1 = $pos + 1 + strlen($possible['tag']) + 1;
  1775. // Quotes can have alternate styling, we do this php-side due to all the permutations of quotes.
  1776. if ($possible['tag'] == 'quote')
  1777. {
  1778. // Start with standard
  1779. $quote_alt = false;
  1780. foreach ($open_tags as $open_quote)
  1781. {
  1782. // Every parent quote this quote has flips the styling
  1783. if ($open_quote['tag'] == 'quote')
  1784. $quote_alt = !$quote_alt;
  1785. }
  1786. // Add a class to the quote to style alternating blockquotes
  1787. $possible['before'] = strtr($possible['before'], array('<blockquote>' => '<blockquote class="bbc_' . ($quote_alt ? 'alternate' : 'standard') . '_quote">'));
  1788. }
  1789. // This is long, but it makes things much easier and cleaner.
  1790. if (!empty($possible['parameters']))
  1791. {
  1792. $preg = array();
  1793. foreach ($possible['parameters'] as $p => $info)
  1794. $preg[] = '(\s+' . $p . '=' . (empty($info['quoted']) ? '' : '&quot;') . (isset($info['match']) ? $info['match'] : '(.+?)') . (empty($info['quoted']) ? '' : '&quot;') . ')' . (empty($info['optional']) ? '' : '?');
  1795. // Okay, this may look ugly and it is, but it's not going to happen much and it is the best way of allowing any order of parameters but still parsing them right.
  1796. $match = false;
  1797. $orders = permute($preg);
  1798. foreach ($orders as $p)
  1799. if (preg_match('~^' . implode('', $p) . '\]~i', substr($message, $pos1 - 1), $matches) != 0)
  1800. {
  1801. $match = true;
  1802. break;
  1803. }
  1804. // Didn't match our parameter list, try the next possible.
  1805. if (!$match)
  1806. continue;
  1807. $params = array();
  1808. for ($i = 1, $n = count($matches); $i < $n; $i += 2)
  1809. {
  1810. $key = strtok(ltrim($matches[$i]), '=');
  1811. if (isset($possible['parameters'][$key]['value']))
  1812. $params['{' . $key . '}'] = strtr($possible['parameters'][$key]['value'], array('$1' => $matches[$i + 1]));
  1813. elseif (isset($possible['parameters'][$key]['validate']))
  1814. $params['{' . $key . '}'] = $possible['parameters'][$key]['validate']($matches[$i + 1]);
  1815. else
  1816. $params['{' . $key . '}'] = $matches[$i + 1];
  1817. // Just to make sure: replace any $ or { so they can't interpolate wrongly.
  1818. $params['{' . $key . '}'] = strtr($params['{' . $key . '}'], array('$' => '&#036;', '{' => '&#123;'));
  1819. }
  1820. foreach ($possible['parameters'] as $p => $info)
  1821. {
  1822. if (!isset($params['{' . $p . '}']))
  1823. $params['{' . $p . '}'] = '';
  1824. }
  1825. $tag = $possible;
  1826. // Put the parameters into the string.
  1827. if (isset($tag['before']))
  1828. $tag['before'] = strtr($tag['before'], $params);
  1829. if (isset($tag['after']))
  1830. $tag['after'] = strtr($tag['after'], $params);
  1831. if (isset($tag['content']))
  1832. $tag['content'] = strtr($tag['content'], $params);
  1833. $pos1 += strlen($matches[0]) - 1;
  1834. }
  1835. else
  1836. $tag = $possible;
  1837. break;
  1838. }
  1839. // Item codes are complicated buggers... they are implicit [li]s and can make [list]s!
  1840. if ($smileys !== false && $tag === null && isset($itemcodes[substr($message, $pos + 1, 1)]) && substr($message, $pos + 2, 1) == ']' && !isset($disabled['list']) && !isset($disabled['li']))
  1841. {
  1842. if (substr($message, $pos + 1, 1) == '0' && !in_array(substr($message, $pos - 1, 1), array(';', ' ', "\t", '>')))
  1843. continue;
  1844. $tag = $itemcodes[substr($message, $pos + 1, 1)];
  1845. // First let's set up the tree: it needs to be in a list, or after an li.
  1846. if ($inside === null || ($inside['tag'] != 'list' && $inside['tag'] != 'li'))
  1847. {
  1848. $open_tags[] = array(
  1849. 'tag' => 'list',
  1850. 'after' => '</ul>',
  1851. 'block_level' => true,
  1852. 'require_children' => array('li'),
  1853. 'disallow_children' => isset($inside['disallow_children']) ? $inside['disallow_children'] : null,
  1854. );
  1855. $code = '<ul class="bbc_list">';
  1856. }
  1857. // We're in a list item already: another itemcode? Close it first.
  1858. elseif ($inside['tag'] == 'li')
  1859. {
  1860. array_pop($open_tags);
  1861. $code = '</li>';
  1862. }
  1863. else
  1864. $code = '';
  1865. // Now we open a new tag.
  1866. $open_tags[] = array(
  1867. 'tag' => 'li',
  1868. 'after' => '</li>',
  1869. 'trim' => 'outside',
  1870. 'block_level' => true,
  1871. 'disallow_children' => isset($inside['disallow_children']) ? $inside['disallow_children'] : null,
  1872. );
  1873. // First, open the tag...
  1874. $code .= '<li' . ($tag == '' ? '' : ' type="' . $tag . '"') . '>';
  1875. $message = substr($message, 0, $pos) . "\n" . $code . "\n" . substr($message, $pos + 3);
  1876. $pos += strlen($code) - 1 + 2;
  1877. // Next, find the next break (if any.) If there's more itemcode after it, keep it going - otherwise close!
  1878. $pos2 = strpos($message, '<br />', $pos);
  1879. $pos3 = strpos($message, '[/', $pos);
  1880. if ($pos2 !== false && ($pos2 <= $pos3 || $pos3 === false))
  1881. {
  1882. preg_match('~^(<br />|&nbsp;|\s|\[)+~', substr($message, $pos2 + 6), $matches);
  1883. $message = substr($message, 0, $pos2) . "\n" . (!empty($matches[0]) && substr($matches[0], -1) == '[' ? '[/li]' : '[/li][/list]') . "\n" . substr($message, $pos2);
  1884. $open_tags[count($open_tags) - 2]['after'] = '</ul>';
  1885. }
  1886. // Tell the [list] that it needs to close specially.
  1887. else
  1888. {
  1889. // Move the li over, because we're not sure what we'll hit.
  1890. $open_tags[count($open_tags) - 1]['after'] = '';
  1891. $open_tags[count($open_tags) - 2]['after'] = '</li></ul>';
  1892. }
  1893. continue;
  1894. }
  1895. // Implicitly close lists and tables if something other than what's required is in them. This is needed for itemcode.
  1896. if ($tag === null && $inside !== null && !empty($inside['require_children']))
  1897. {
  1898. array_pop($open_tags);
  1899. $message = substr($message, 0, $pos) . "\n" . $inside['after'] . "\n" . substr($message, $pos);
  1900. $pos += strlen($inside['after']) - 1 + 2;
  1901. }
  1902. // No tag? Keep looking, then. Silly people using brackets without actual tags.
  1903. if ($tag === null)
  1904. continue;
  1905. // Propagate the list to the child (so wrapping the disallowed tag won't work either.)
  1906. if (isset($inside['disallow_children']))
  1907. $tag['disallow_children'] = isset($tag['disallow_children']) ? array_unique(array_merge($tag['disallow_children'], $inside['disallow_children'])) : $inside['disallow_children'];
  1908. // Is this tag disabled?
  1909. if (isset($disabled[$tag['tag']]))
  1910. {
  1911. if (!isset($tag['disabled_before']) && !isset($tag['disabled_after']) && !isset($tag['disabled_content']))
  1912. {
  1913. $tag['before'] = !empty($tag['block_level']) ? '<div>' : '';
  1914. $tag['after'] = !empty($tag['block_level']) ? '</div>' : '';
  1915. $tag['content'] = isset($tag['type']) && $tag['type'] == 'closed' ? '' : (!empty($tag['block_level']) ? '<div>$1</div>' : '$1');
  1916. }
  1917. elseif (isset($tag['disabled_before']) || isset($tag['disabled_after']))
  1918. {
  1919. $tag['before'] = isset($tag['disabled_before']) ? $tag['disabled_before'] : (!empty($tag['block_level']) ? '<div>' : '');
  1920. $tag['after'] = isset($tag['disabled_after']) ? $tag['disabled_after'] : (!empty($tag['block_level']) ? '</div>' : '');
  1921. }
  1922. else
  1923. $tag['content'] = $tag['disabled_content'];
  1924. }
  1925. // The only special case is 'html', which doesn't need to close things.
  1926. if (!empty($tag['block_level']) && $tag['tag'] != 'html' && empty($inside['block_level']))
  1927. {
  1928. $n = count($open_tags) - 1;
  1929. while (empty($open_tags[$n]['block_level']) && $n >= 0)
  1930. $n--;
  1931. // Close all the non block level tags so this tag isn't surrounded by them.
  1932. for ($i = count($open_tags) - 1; $i > $n; $i--)
  1933. {
  1934. $message = substr($message, 0, $pos) . "\n" . $open_tags[$i]['after'] . "\n" . substr($message, $pos);
  1935. $pos += strlen($open_tags[$i]['after']) + 2;
  1936. $pos1 += strlen($open_tags[$i]['after']) + 2;
  1937. // Trim or eat trailing stuff... see comment at the end of the big loop.
  1938. if (!empty($open_tags[$i]['block_level']) && substr($message, $pos, 6) == '<br />')
  1939. $message = substr($message, 0, $pos) . substr($message, $pos + 6);
  1940. if (!empty($open_tags[$i]['trim']) && $tag['trim'] != 'inside' && preg_match('~(<br />|&nbsp;|\s)*~', substr($message, $pos), $matches) != 0)
  1941. $message = substr($message, 0, $pos) . substr($message, $pos + strlen($matches[0]));
  1942. array_pop($open_tags);
  1943. }
  1944. }
  1945. // No type means 'parsed_content'.
  1946. if (!isset($tag['type']))
  1947. {
  1948. // @todo Check for end tag first, so people can say "I like that [i] tag"?
  1949. $open_tags[] = $tag;
  1950. $message = substr($message, 0, $pos) . "\n" . $tag['before'] . "\n" . substr($message, $pos1);
  1951. $pos += strlen($tag['before']) - 1 + 2;
  1952. }
  1953. // Don't parse the content, just skip it.
  1954. elseif ($tag['type'] == 'unparsed_content')
  1955. {
  1956. $pos2 = stripos($message, '[/' . substr($message, $pos + 1, strlen($tag['tag'])) . ']', $pos1);
  1957. if ($pos2 === false)
  1958. continue;
  1959. $data = substr($message, $pos1, $pos2 - $pos1);
  1960. if (!empty($tag['block_level']) && substr($data, 0, 6) == '<br />')
  1961. $data = substr($data, 6);
  1962. if (isset($tag['validate']))
  1963. $tag['validate']($tag, $data, $disabled);
  1964. $code = strtr($tag['content'], array('$1' => $data));
  1965. $message = substr($message, 0, $pos) . "\n" . $code . "\n" . substr($message, $pos2 + 3 + strlen($tag['tag']));
  1966. $pos += strlen($code) - 1 + 2;
  1967. $last_pos = $pos + 1;
  1968. }
  1969. // Don't parse the content, just skip it.
  1970. elseif ($tag['type'] == 'unparsed_equals_content')
  1971. {
  1972. // The value may be quoted for some tags - check.
  1973. if (isset($tag['quoted']))
  1974. {
  1975. $quoted = substr($message, $pos1, 6) == '&quot;';
  1976. if ($tag['quoted'] != 'optional' && !$quoted)
  1977. continue;
  1978. if ($quoted)
  1979. $pos1 += 6;
  1980. }
  1981. else
  1982. $quoted = false;
  1983. $pos2 = strpos($message, $quoted == false ? ']' : '&quot;]', $pos1);
  1984. if ($pos2 === false)
  1985. continue;
  1986. $pos3 = stripos($message, '[/' . substr($message, $pos + 1, strlen($tag['tag'])) . ']', $pos2);
  1987. if ($pos3 === false)
  1988. continue;
  1989. $data = array(
  1990. substr($message, $pos2 + ($quoted == false ? 1 : 7), $pos3 - ($pos2 + ($quoted == false ? 1 : 7))),
  1991. substr($message, $pos1, $pos2 - $pos1)
  1992. );
  1993. if (!empty($tag['block_level']) && substr($data[0], 0, 6) == '<br />')
  1994. $data[0] = substr($data[0], 6);
  1995. // Validation for my parking, please!
  1996. if (isset($tag['validate']))
  1997. $tag['validate']($tag, $data, $disabled);
  1998. $code = strtr($tag['content'], array('$1' => $data[0], '$2' => $data[1]));
  1999. $message = substr($message, 0, $pos) . "\n" . $code . "\n" . substr($message, $pos3 + 3 + strlen($tag['tag']));
  2000. $pos += strlen($code) - 1 + 2;
  2001. }
  2002. // A closed tag, with no content or value.
  2003. elseif ($tag['type'] == 'closed')
  2004. {
  2005. $pos2 = strpos($message, ']', $pos);
  2006. $message = substr($message, 0, $pos) . "\n" . $tag['content'] . "\n" . substr($message, $pos2 + 1);
  2007. $pos += strlen($tag['content']) - 1 + 2;
  2008. }
  2009. // This one is sorta ugly... :/. Unfortunately, it's needed for flash.
  2010. elseif ($tag['type'] == 'unparsed_commas_content')
  2011. {
  2012. $pos2 = strpos($message, ']', $pos1);
  2013. if ($pos2 === false)
  2014. continue;
  2015. $pos3 = stripos($message, '[/' . substr($message, $pos + 1, strlen($tag['tag'])) . ']', $pos2);
  2016. if ($pos3 === false)
  2017. continue;
  2018. // We want $1 to be the content, and the rest to be csv.
  2019. $data = explode(',', ',' . substr($message, $pos1, $pos2 - $pos1));
  2020. $data[0] = substr($message, $pos2 + 1, $pos3 - $pos2 - 1);
  2021. if (isset($tag['validate']))
  2022. $tag['validate']($tag, $data, $disabled);
  2023. $code = $tag['content'];
  2024. foreach ($data as $k => $d)
  2025. $code = strtr($code, array('$' . ($k + 1) => trim($d)));
  2026. $message = substr($message, 0, $pos) . "\n" . $code . "\n" . substr($message, $pos3 + 3 + strlen($tag['tag']));
  2027. $pos += strlen($code) - 1 + 2;
  2028. }
  2029. // This has parsed content, and a csv value which is unparsed.
  2030. elseif ($tag['type'] == 'unparsed_commas')
  2031. {
  2032. $pos2 = strpos($message, ']', $pos1);
  2033. if ($pos2 === false)
  2034. continue;
  2035. $data = explode(',', substr($message, $pos1, $pos2 - $pos1));
  2036. if (isset($tag['validate']))
  2037. $tag['validate']($tag, $data, $disabled);
  2038. // Fix after, for disabled code mainly.
  2039. foreach ($data as $k => $d)
  2040. $tag['after'] = strtr($tag['after'], array('$' . ($k + 1) => trim($d)));
  2041. $open_tags[] = $tag;
  2042. // Replace them out, $1, $2, $3, $4, etc.
  2043. $code = $tag['before'];
  2044. foreach ($data as $k => $d)
  2045. $code = strtr($code, array('$' . ($k + 1) => trim($d)));
  2046. $message = substr($message, 0, $pos) . "\n" . $code . "\n" . substr($message, $pos2 + 1);
  2047. $pos += strlen($code) - 1 + 2;
  2048. }
  2049. // A tag set to a value, parsed or not.
  2050. elseif ($tag['type'] == 'unparsed_equals' || $tag['type'] == 'parsed_equals')
  2051. {
  2052. // The value may be quoted for some tags - check.
  2053. if (isset($tag['quoted']))
  2054. {
  2055. $quoted = substr($message, $pos1, 6) == '&quot;';
  2056. if ($tag['quoted'] != 'optional' && !$quoted)
  2057. continue;
  2058. if ($quoted)
  2059. $pos1 += 6;
  2060. }
  2061. else
  2062. $quoted = false;
  2063. $pos2 = strpos($message, $quoted == false ? ']' : '&quot;]', $pos1);
  2064. if ($pos2 === false)
  2065. continue;
  2066. $data = substr($message, $pos1, $pos2 - $pos1);
  2067. // Validation for my parking, please!
  2068. if (isset($tag['validate']))
  2069. $tag['validate']($tag, $data, $disabled);
  2070. // For parsed content, we must recurse to avoid security problems.
  2071. if ($tag['type'] != 'unparsed_equals')
  2072. $data = parse_bbc($data, !empty($tag['parsed_tags_allowed']) ? false : true, '', !empty($tag['parsed_tags_allowed']) ? $tag['parsed_tags_allowed'] : array());
  2073. $tag['after'] = strtr($tag['after'], array('$1' => $data));
  2074. $open_tags[] = $tag;
  2075. $code = strtr($tag['before'], array('$1' => $data));
  2076. $message = substr($message, 0, $pos) . "\n" . $code . "\n" . substr($message, $pos2 + ($quoted == false ? 1 : 7));
  2077. $pos += strlen($code) - 1 + 2;
  2078. }
  2079. // If this is block level, eat any breaks after it.
  2080. if (!empty($tag['block_level']) && substr($message, $pos + 1, 6) == '<br />')
  2081. $message = substr($message, 0, $pos + 1) . substr($message, $pos + 7);
  2082. // Are we trimming outside this tag?
  2083. if (!empty($tag['trim']) && $tag['trim'] != 'outside' && preg_match('~(<br />|&nbsp;|\s)*~', substr($message, $pos + 1), $matches) != 0)
  2084. $message = substr($message, 0, $pos + 1) . substr($message, $pos + 1 + strlen($matches[0]));
  2085. }
  2086. // Close any remaining tags.
  2087. while ($tag = array_pop($open_tags))
  2088. $message .= "\n" . $tag['after'] . "\n";
  2089. // Parse the smileys within the parts where it can be done safely.
  2090. if ($smileys === true)
  2091. {
  2092. $message_parts = explode("\n", $message);
  2093. for ($i = 0, $n = count($message_parts); $i < $n; $i += 2)
  2094. parsesmileys($message_parts[$i]);
  2095. $message = implode('', $message_parts);
  2096. }
  2097. // No smileys, just get rid of the markers.
  2098. else
  2099. $message = strtr($message, array("\n" => ''));
  2100. if (substr($message, 0, 1) == ' ')
  2101. $message = '&nbsp;' . substr($message, 1);
  2102. // Cleanup whitespace.
  2103. $message = strtr($message, array(' ' => ' &nbsp;', "\r" => '', "\n" => '<br />', '<br /> ' => '<br />&nbsp;', '&#13;' => "\n"));
  2104. // Cache the output if it took some time...
  2105. if (isset($cache_key, $cache_t) && array_sum(explode(' ', microtime())) - array_sum(explode(' ', $cache_t)) > 0.05)
  2106. cache_put_data($cache_key, $message, 240);
  2107. // If this was a force parse revert if needed.
  2108. if (!empty($parse_tags))
  2109. {
  2110. if (empty($temp_bbc))
  2111. $bbc_codes = array();
  2112. else
  2113. {
  2114. $bbc_codes = $temp_bbc;
  2115. unset($temp_bbc);
  2116. }
  2117. }
  2118. return $message;
  2119. }
  2120. // Parse smileys in the passed message.
  2121. function parsesmileys(&$message)
  2122. {
  2123. global $modSettings, $txt, $user_info, $context, $smcFunc;
  2124. static $smileyPregSearch = array(), $smileyPregReplacements = array();
  2125. // No smiley set at all?!
  2126. if ($user_info['smiley_set'] === 'none' || trim($message) === '')
  2127. return;
  2128. // If the smiley array hasn't been set, do it now.
  2129. if (empty($smileyPregSearch))
  2130. {
  2131. // Use the default smileys if it is disabled. (better for "portability" of smileys.)
  2132. if (empty($modSettings['smiley_enable']))
  2133. {
  2134. $smileysfrom = array('>:D', ':D', '::)', '>:(', ':))', ':)', ';)', ';D', ':(', ':o', '8)', ':P', '???', ':-[', ':-X', ':-*', ':\'(', ':-\\', '^-^', 'O0', 'C:-)', '0:)');
  2135. $smileysto = array('evil.gif', 'cheesy.gif', 'rolleyes.gif', 'angry.gif', 'laugh.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');
  2136. $smileysdescs = array('', $txt['icon_cheesy'], $txt['icon_rolleyes'], $txt['icon_angry'], '', $txt['icon_smiley'], $txt['icon_wink'], $txt['icon_grin'], $txt['icon_sad'], $txt['icon_shocked'], $txt['icon_cool'], $txt['icon_tongue'], $txt['icon_huh'], $txt['icon_embarrassed'], $txt['icon_lips'], $txt['icon_kiss'], $txt['icon_cry'], $txt['icon_undecided'], '', '', '', '');
  2137. }
  2138. else
  2139. {
  2140. // Load the smileys in reverse order by length so they don't get parsed wrong.
  2141. if (($temp = cache_get_data('parsing_smileys', 480)) == null)
  2142. {
  2143. $result = $smcFunc['db_query']('', '
  2144. SELECT code, filename, description
  2145. FROM {db_prefix}smileys',
  2146. array(
  2147. )
  2148. );
  2149. $smileysfrom = array();
  2150. $smileysto = array();
  2151. $smileysdescs = array();
  2152. while ($row = $smcFunc['db_fetch_assoc']($result))
  2153. {
  2154. $smileysfrom[] = $row['code'];
  2155. $smileysto[] = $row['filename'];
  2156. $smileysdescs[] = $row['description'];
  2157. }
  2158. $smcFunc['db_free_result']($result);
  2159. cache_put_data('parsing_smileys', array($smileysfrom, $smileysto, $smileysdescs), 480);
  2160. }
  2161. else
  2162. list ($smileysfrom, $smileysto, $smileysdescs) = $temp;
  2163. }
  2164. // The non-breaking-space is a complex thing...
  2165. $non_breaking_space = $context['utf8'] ? ($context['server']['complex_preg_chars'] ? '\x{A0}' : "\xC2\xA0") : '\xA0';
  2166. // This smiley regex makes sure it doesn't parse smileys within code tags (so [url=mailto:[email protected]] doesn't parse the :D smiley)
  2167. $smileyPregReplacements = array();
  2168. $searchParts = array();
  2169. for ($i = 0, $n = count($smileysfrom); $i < $n; $i++)
  2170. {
  2171. $smileyCode = '<img src="' . htmlspecialchars($modSettings['smileys_url'] . '/' . $user_info['smiley_set'] . '/' . $smileysto[$i]) . '" alt="' . strtr(htmlspecialchars($smileysfrom[$i], ENT_QUOTES), array(':' => '&#58;', '(' => '&#40;', ')' => '&#41;', '$' => '&#36;', '[' => '&#091;')). '" title="' . strtr(htmlspecialchars($smileysdescs[$i]), array(':' => '&#58;', '(' => '&#40;', ')' => '&#41;', '$' => '&#36;', '[' => '&#091;')) . '" class="smiley" />';
  2172. $smileyPregReplacements[$smileysfrom[$i]] = $smileyCode;
  2173. $searchParts[] = preg_quote($smileysfrom[$i], '~');
  2174. if ($smileysfrom[$i] != ($specialChars = htmlspecialchars($smileysfrom[$i], ENT_QUOTES)))
  2175. {
  2176. $smileyPregReplacements[$specialChars] = $smileyCode;
  2177. $searchParts[] = preg_quote($specialChars, '~');
  2178. }
  2179. }
  2180. $smileyPregSearch = '~(?<=[>:\?\.\s' . $non_breaking_space . '[\]()*\\\;]|^)(' . implode('|', $searchParts) . ')(?=[^[:alpha:]0-9]|$)~e' . ($context['utf8'] ? 'u' : '');
  2181. }
  2182. // Replace away!
  2183. $message = preg_replace($smileyPregSearch, '$smileyPregReplacements[\'$1\']', $message);
  2184. }
  2185. // Highlight any code...
  2186. function highlight_php_code($code)
  2187. {
  2188. global $context;
  2189. // Remove special characters.
  2190. $code = un_htmlspecialchars(strtr($code, array('<br />' => "\n", "\t" => 'SMF_TAB();', '&#91;' => '[')));
  2191. $oldlevel = error_reporting(0);
  2192. // It's easier in 4.2.x+.
  2193. if (@version_compare(PHP_VERSION, '4.2.0') == -1)
  2194. {
  2195. ob_start();
  2196. @highlight_string($code);
  2197. $buffer = str_replace(array("\n", "\r"), '', ob_get_contents());
  2198. ob_end_clean();
  2199. }
  2200. else
  2201. $buffer = str_replace(array("\n", "\r"), '', @highlight_string($code, true));
  2202. error_reporting($oldlevel);
  2203. // Yes, I know this is kludging it, but this is the best way to preserve tabs from PHP :P.
  2204. $buffer = preg_replace('~SMF_TAB(?:</(?:font|span)><(?:font color|span style)="[^"]*?">)?\\(\\);~', '<pre style="display: inline;">' . "\t" . '</pre>', $buffer);
  2205. return strtr($buffer, array('\'' => '&#039;', '<code>' => '', '</code>' => ''));
  2206. }
  2207. /**
  2208. * Make sure the browser doesn't come back and repost the form data.
  2209. * Should be used whenever anything is posted.
  2210. */
  2211. function redirectexit($setLocation = '', $refresh = false)
  2212. {
  2213. global $scripturl, $context, $modSettings, $db_show_debug, $db_cache;
  2214. // In case we have mail to send, better do that - as obExit doesn't always quite make it...
  2215. if (!empty($context['flush_mail']))
  2216. // @todo this relies on 'flush_mail' being only set in AddMailQueue itself... :\
  2217. AddMailQueue(true);
  2218. $add = preg_match('~^(ftp|http)[s]?://~', $setLocation) == 0 && substr($setLocation, 0, 6) != 'about:';
  2219. if (WIRELESS)
  2220. {
  2221. // Add the scripturl on if needed.
  2222. if ($add)
  2223. $setLocation = $scripturl . '?' . $setLocation;
  2224. $char = strpos($setLocation, '?') === false ? '?' : ';';
  2225. if (strpos($setLocation, '#') !== false)
  2226. $setLocation = strtr($setLocation, array('#' => $char . WIRELESS_PROTOCOL . '#'));
  2227. else
  2228. $setLocation .= $char . WIRELESS_PROTOCOL;
  2229. }
  2230. elseif ($add)
  2231. $setLocation = $scripturl . ($setLocation != '' ? '?' . $setLocation : '');
  2232. // Put the session ID in.
  2233. if (defined('SID') && SID != '')
  2234. $setLocation = preg_replace('/^' . preg_quote($scripturl, '/') . '(?!\?' . preg_quote(SID, '/') . ')\\??/', $scripturl . '?' . SID . ';', $setLocation);
  2235. // Keep that debug in their for template debugging!
  2236. elseif (isset($_GET['debug']))
  2237. $setLocation = preg_replace('/^' . preg_quote($scripturl, '/') . '\\??/', $scripturl . '?debug;', $setLocation);
  2238. if (!empty($modSettings['queryless_urls']) && (empty($context['server']['is_cgi']) || @ini_get('cgi.fix_pathinfo') == 1 || @get_cfg_var('cgi.fix_pathinfo') == 1) && (!empty($context['server']['is_apache']) || !empty($context['server']['is_lighttpd']) || !empty($context['server']['is_litespeed'])))
  2239. {
  2240. if (defined('SID') && SID != '')
  2241. $setLocation = preg_replace('/^' . preg_quote($scripturl, '/') . '\?(?:' . SID . '(?:;|&|&amp;))((?:board|topic)=[^#]+?)(#[^"]*?)?$/e', "\$scripturl . '/' . strtr('\$1', '&;=', '//,') . '.html\$2?' . SID", $setLocation);
  2242. else
  2243. $setLocation = preg_replace('/^' . preg_quote($scripturl, '/') . '\?((?:board|topic)=[^#"]+?)(#[^"]*?)?$/e', "\$scripturl . '/' . strtr('\$1', '&;=', '//,') . '.html\$2'", $setLocation);
  2244. }
  2245. // Maybe integrations want to change where we are heading?
  2246. call_integration_hook('integrate_redirect', array(&$setLocation, &$refresh));
  2247. // We send a Refresh header only in special cases because Location looks better. (and is quicker...)
  2248. if ($refresh && !WIRELESS)
  2249. header('Refresh: 0; URL=' . strtr($setLocation, array(' ' => '%20')));
  2250. else
  2251. header('Location: ' . str_replace(' ', '%20', $setLocation));
  2252. // Debugging.
  2253. if (isset($db_show_debug) && $db_show_debug === true)
  2254. $_SESSION['debug_redirect'] = $db_cache;
  2255. obExit(false);
  2256. }
  2257. // Ends execution. Takes care of template loading and remembering the previous URL.
  2258. function obExit($header = null, $do_footer = null, $from_index = false, $from_fatal_error = false)
  2259. {
  2260. global $context, $settings, $modSettings, $txt, $smcFunc;
  2261. static $header_done = false, $footer_done = false, $level = 0, $has_fatal_error = false;
  2262. // Attempt to prevent a recursive loop.
  2263. ++$level;
  2264. if ($level > 1 && !$from_fatal_error && !$has_fatal_error)
  2265. exit;
  2266. if ($from_fatal_error)
  2267. $has_fatal_error = true;
  2268. // Clear out the stat cache.
  2269. trackStats();
  2270. // If we have mail to send, send it.
  2271. if (!empty($context['flush_mail']))
  2272. // @todo this relies on 'flush_mail' being only set in AddMailQueue itself... :\
  2273. AddMailQueue(true);
  2274. $do_header = $header === null ? !$header_done : $header;
  2275. if ($do_footer === null)
  2276. $do_footer = $do_header;
  2277. // Has the template/header been done yet?
  2278. if ($do_header)
  2279. {
  2280. // Was the page title set last minute? Also update the HTML safe one.
  2281. if (!empty($context['page_title']) && empty($context['page_title_html_safe']))
  2282. $context['page_title_html_safe'] = $smcFunc['htmlspecialchars'](un_htmlspecialchars($context['page_title']));
  2283. // Start up the session URL fixer.
  2284. ob_start('ob_sessrewrite');
  2285. if (!empty($settings['output_buffers']) && is_string($settings['output_buffers']))
  2286. $buffers = explode(',', $settings['output_buffers']);
  2287. elseif (!empty($settings['output_buffers']))
  2288. $buffers = $settings['output_buffers'];
  2289. else
  2290. $buffers = array();
  2291. if (isset($modSettings['integrate_buffer']))
  2292. $buffers = array_merge(explode(',', $modSettings['integrate_buffer']), $buffers);
  2293. if (!empty($buffers))
  2294. foreach ($buffers as $function)
  2295. {
  2296. $function = trim($function);
  2297. $call = strpos($function, '::') !== false ? explode('::', $function) : $function;
  2298. // Is it valid?
  2299. if (is_callable($call))
  2300. ob_start($call);
  2301. }
  2302. // Display the screen in the logical order.
  2303. template_header();
  2304. $header_done = true;
  2305. }
  2306. if ($do_footer)
  2307. {
  2308. if (WIRELESS && !isset($context['sub_template']))
  2309. fatal_lang_error('wireless_error_notyet', false);
  2310. // Just show the footer, then.
  2311. loadSubTemplate(isset($context['sub_template']) ? $context['sub_template'] : 'main');
  2312. // Anything special to put out?
  2313. if (!empty($context['insert_after_template']) && !isset($_REQUEST['xml']))
  2314. echo $context['insert_after_template'];
  2315. // Just so we don't get caught in an endless loop of errors from the footer...
  2316. if (!$footer_done)
  2317. {
  2318. $footer_done = true;
  2319. template_footer();
  2320. // (since this is just debugging... it's okay that it's after </html>.)
  2321. if (!isset($_REQUEST['xml']))
  2322. displayDebug();
  2323. }
  2324. }
  2325. // Remember this URL in case someone doesn't like sending HTTP_REFERER.
  2326. if (strpos($_SERVER['REQUEST_URL'], 'action=dlattach') === false && strpos($_SERVER['REQUEST_URL'], 'action=viewsmfile') === false)
  2327. $_SESSION['old_url'] = $_SERVER['REQUEST_URL'];
  2328. // For session check verification.... don't switch browsers...
  2329. $_SESSION['USER_AGENT'] = $_SERVER['HTTP_USER_AGENT'];
  2330. if (!empty($settings['strict_doctype']))
  2331. {
  2332. // The theme author wants to use the STRICT doctype (only God knows why).
  2333. $temp = ob_get_contents();
  2334. if (function_exists('ob_clean'))
  2335. ob_clean();
  2336. else
  2337. {
  2338. ob_end_clean();
  2339. ob_start('ob_sessrewrite');
  2340. }
  2341. echo strtr($temp, array(
  2342. 'var smf_iso_case_folding' => 'var target_blank = \'_blank\'; var smf_iso_case_folding',
  2343. 'target="_blank"' => 'onclick="this.target=target_blank"'));
  2344. }
  2345. // Hand off the output to the portal, etc. we're integrated with.
  2346. call_integration_hook('integrate_exit', array($do_footer && !WIRELESS));
  2347. // Don't exit if we're coming from index.php; that will pass through normally.
  2348. if (!$from_index || WIRELESS)
  2349. exit;
  2350. }
  2351. function determineTopicClass(&$topic_context)
  2352. {
  2353. // Set topic class depending on locked status and number of replies.
  2354. if ($topic_context['is_very_hot'])
  2355. $topic_context['class'] = 'veryhot';
  2356. elseif ($topic_context['is_hot'])
  2357. $topic_context['class'] = 'hot';
  2358. else
  2359. $topic_context['class'] = 'normal';
  2360. $topic_context['class'] .= $topic_context['is_poll'] ? '_poll' : '_post';
  2361. if ($topic_context['is_locked'])
  2362. $topic_context['class'] .= '_locked';
  2363. if ($topic_context['is_sticky'])
  2364. $topic_context['class'] .= '_sticky';
  2365. // This is so old themes will still work.
  2366. $topic_context['extended_class'] = &$topic_context['class'];
  2367. }
  2368. // Sets up the basic theme context stuff.
  2369. function setupThemeContext($forceload = false)
  2370. {
  2371. global $modSettings, $user_info, $scripturl, $context, $settings, $options, $txt, $maintenance;
  2372. global $user_settings, $smcFunc;
  2373. static $loaded = false;
  2374. // Under SSI this function can be called more then once. That can cause some problems.
  2375. // So only run the function once unless we are forced to run it again.
  2376. if ($loaded && !$forceload)
  2377. return;
  2378. $loaded = true;
  2379. $context['in_maintenance'] = !empty($maintenance);
  2380. $context['current_time'] = timeformat(time(), false);
  2381. $context['current_action'] = isset($_GET['action']) ? $_GET['action'] : '';
  2382. $context['show_quick_login'] = !empty($modSettings['enableVBStyleLogin']) && $user_info['is_guest'];
  2383. // Get some news...
  2384. $context['news_lines'] = explode("\n", str_replace("\r", '', trim(addslashes($modSettings['news']))));
  2385. $context['fader_news_lines'] = array();
  2386. for ($i = 0, $n = count($context['news_lines']); $i < $n; $i++)
  2387. {
  2388. if (trim($context['news_lines'][$i]) == '')
  2389. continue;
  2390. // Clean it up for presentation ;).
  2391. $context['news_lines'][$i] = parse_bbc(stripslashes(trim($context['news_lines'][$i])), true, 'news' . $i);
  2392. // Gotta be special for the javascript.
  2393. $context['fader_news_lines'][$i] = strtr(addslashes($context['news_lines'][$i]), array('/' => '\/', '<a href=' => '<a hre" + "f='));
  2394. }
  2395. $context['random_news_line'] = $context['news_lines'][mt_rand(0, count($context['news_lines']) - 1)];
  2396. if (!$user_info['is_guest'])
  2397. {
  2398. $context['user']['messages'] = &$user_info['messages'];
  2399. $context['user']['unread_messages'] = &$user_info['unread_messages'];
  2400. // Personal message popup...
  2401. if ($user_info['unread_messages'] > (isset($_SESSION['unread_messages']) ? $_SESSION['unread_messages'] : 0))
  2402. $context['user']['popup_messages'] = true;
  2403. else
  2404. $context['user']['popup_messages'] = false;
  2405. $_SESSION['unread_messages'] = $user_info['unread_messages'];
  2406. if (allowedTo('moderate_forum'))
  2407. $context['unapproved_members'] = (!empty($modSettings['registration_method']) && $modSettings['registration_method'] == 2) || !empty($modSettings['approveAccountDeletion']) ? $modSettings['unapprovedMembers'] : 0;
  2408. $context['show_open_reports'] = empty($user_settings['mod_prefs']) || $user_settings['mod_prefs'][0] == 1;
  2409. $context['user']['avatar'] = array();
  2410. // Figure out the avatar... uploaded?
  2411. if ($user_info['avatar']['url'] == '' && !empty($user_info['avatar']['id_attach']))
  2412. $context['user']['avatar']['href'] = $user_info['avatar']['custom_dir'] ? $modSettings['custom_avatar_url'] . '/' . $user_info['avatar']['filename'] : $scripturl . '?action=dlattach;attach=' . $user_info['avatar']['id_attach'] . ';type=avatar';
  2413. // Full URL?
  2414. elseif (substr($user_info['avatar']['url'], 0, 7) == 'http://')
  2415. {
  2416. $context['user']['avatar']['href'] = $user_info['avatar']['url'];
  2417. if ($modSettings['avatar_action_too_large'] == 'option_html_resize' || $modSettings['avatar_action_too_large'] == 'option_js_resize')
  2418. {
  2419. if (!empty($modSettings['avatar_max_width_external']))
  2420. $context['user']['avatar']['width'] = $modSettings['avatar_max_width_external'];
  2421. if (!empty($modSettings['avatar_max_height_external']))
  2422. $context['user']['avatar']['height'] = $modSettings['avatar_max_height_external'];
  2423. }
  2424. }
  2425. // Otherwise we assume it's server stored?
  2426. elseif ($user_info['avatar']['url'] != '')
  2427. $context['user']['avatar']['href'] = $modSettings['avatar_url'] . '/' . htmlspecialchars($user_info['avatar']['url']);
  2428. if (!empty($context['user']['avatar']))
  2429. $context['user']['avatar']['image'] = '<img src="' . $context['user']['avatar']['href'] . '"' . (isset($context['user']['avatar']['width']) ? ' width="' . $context['user']['avatar']['width'] . '"' : '') . (isset($context['user']['avatar']['height']) ? ' height="' . $context['user']['avatar']['height'] . '"' : '') . ' alt="" class="avatar" />';
  2430. // Figure out how long they've been logged in.
  2431. $context['user']['total_time_logged_in'] = array(
  2432. 'days' => floor($user_info['total_time_logged_in'] / 86400),
  2433. 'hours' => floor(($user_info['total_time_logged_in'] % 86400) / 3600),
  2434. 'minutes' => floor(($user_info['total_time_logged_in'] % 3600) / 60)
  2435. );
  2436. }
  2437. else
  2438. {
  2439. $context['user']['messages'] = 0;
  2440. $context['user']['unread_messages'] = 0;
  2441. $context['user']['avatar'] = array();
  2442. $context['user']['total_time_logged_in'] = array('days' => 0, 'hours' => 0, 'minutes' => 0);
  2443. $context['user']['popup_messages'] = false;
  2444. if (!empty($modSettings['registration_method']) && $modSettings['registration_method'] == 1)
  2445. $txt['welcome_guest'] .= $txt['welcome_guest_activate'];
  2446. // If we've upgraded recently, go easy on the passwords.
  2447. if (!empty($modSettings['disableHashTime']) && ($modSettings['disableHashTime'] == 1 || time() < $modSettings['disableHashTime']))
  2448. $context['disable_login_hashing'] = true;
  2449. elseif ($context['browser']['is_ie5'] || $context['browser']['is_ie5.5'])
  2450. $context['disable_login_hashing'] = true;
  2451. }
  2452. // Setup the main menu items.
  2453. setupMenuContext();
  2454. if (empty($settings['theme_version']))
  2455. $context['show_vBlogin'] = $context['show_quick_login'];
  2456. // This is here because old index templates might still use it.
  2457. $context['show_news'] = !empty($settings['enable_news']);
  2458. // This is done to allow theme authors to customize it as they want.
  2459. $context['show_pm_popup'] = $context['user']['popup_messages'] && !empty($options['popup_messages']) && (!isset($_REQUEST['action']) || $_REQUEST['action'] != 'pm');
  2460. // Resize avatars the fancy, but non-GD requiring way.
  2461. if ($modSettings['avatar_action_too_large'] == 'option_js_resize' && (!empty($modSettings['avatar_max_width_external']) || !empty($modSettings['avatar_max_height_external'])))
  2462. {
  2463. $context['html_headers'] .= '
  2464. <script type="text/javascript"><!-- // --><![CDATA[
  2465. var smf_avatarMaxWidth = ' . (int) $modSettings['avatar_max_width_external'] . ';
  2466. var smf_avatarMaxHeight = ' . (int) $modSettings['avatar_max_height_external'] . ';';
  2467. if (!$context['browser']['is_ie'] && !$context['browser']['is_mac_ie'])
  2468. $context['html_headers'] .= '
  2469. window.addEventListener("load", smf_avatarResize, false);';
  2470. else
  2471. $context['html_headers'] .= '
  2472. var window_oldAvatarOnload = window.onload;
  2473. window.onload = smf_avatarResize;';
  2474. // @todo Move this over to script.js?
  2475. $context['html_headers'] .= '
  2476. // ]]></script>';
  2477. }
  2478. // This looks weird, but it's because BoardIndex.php references the variable.
  2479. $context['common_stats']['latest_member'] = array(
  2480. 'id' => $modSettings['latestMember'],
  2481. 'name' => $modSettings['latestRealName'],
  2482. 'href' => $scripturl . '?action=profile;u=' . $modSettings['latestMember'],
  2483. 'link' => '<a href="' . $scripturl . '?action=profile;u=' . $modSettings['latestMember'] . '">' . $modSettings['latestRealName'] . '</a>',
  2484. );
  2485. $context['common_stats'] = array(
  2486. 'total_posts' => comma_format($modSettings['totalMessages']),
  2487. 'total_topics' => comma_format($modSettings['totalTopics']),
  2488. 'total_members' => comma_format($modSettings['totalMembers']),
  2489. 'latest_member' => $context['common_stats']['latest_member'],
  2490. );
  2491. if (empty($settings['theme_version']))
  2492. $context['html_headers'] .= '
  2493. <script type="text/javascript"><!-- // --><![CDATA[
  2494. var smf_scripturl = "' . $scripturl . '";
  2495. // ]]></script>';
  2496. if (!isset($context['page_title']))
  2497. $context['page_title'] = '';
  2498. // Set some specific vars.
  2499. $context['page_title_html_safe'] = $smcFunc['htmlspecialchars'](un_htmlspecialchars($context['page_title']));
  2500. $context['meta_keywords'] = !empty($modSettings['meta_keywords']) ? $smcFunc['htmlspecialchars']($modSettings['meta_keywords']) : '';
  2501. }
  2502. // This is the only template included in the sources...
  2503. function template_rawdata()
  2504. {
  2505. global $context;
  2506. echo $context['raw_data'];
  2507. }
  2508. function template_header()
  2509. {
  2510. global $txt, $modSettings, $context, $settings, $user_info, $boarddir, $cachedir;
  2511. setupThemeContext();
  2512. // Print stuff to prevent caching of pages (except on attachment errors, etc.)
  2513. if (empty($context['no_last_modified']))
  2514. {
  2515. header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
  2516. header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
  2517. // Are we debugging the template/html content?
  2518. if (!isset($_REQUEST['xml']) && isset($_GET['debug']) && !$context['browser']['is_ie'] && !WIRELESS)
  2519. header('Content-Type: application/xhtml+xml');
  2520. elseif (!isset($_REQUEST['xml']) && !WIRELESS)
  2521. header('Content-Type: text/html; charset=' . (empty($context['character_set']) ? 'ISO-8859-1' : $context['character_set']));
  2522. }
  2523. header('Content-Type: text/' . (isset($_REQUEST['xml']) ? 'xml' : 'html') . '; charset=' . (empty($context['character_set']) ? 'ISO-8859-1' : $context['character_set']));
  2524. $checked_securityFiles = false;
  2525. $showed_banned = false;
  2526. foreach ($context['template_layers'] as $layer)
  2527. {
  2528. loadSubTemplate($layer . '_above', true);
  2529. // May seem contrived, but this is done in case the body and main layer aren't there...
  2530. if (in_array($layer, array('body', 'main')) && allowedTo('admin_forum') && !$user_info['is_guest'] && !$checked_securityFiles)
  2531. {
  2532. $checked_securityFiles = true;
  2533. $securityFiles = array('install.php', 'webinstall.php', 'upgrade.php', 'convert.php', 'repair_paths.php', 'repair_settings.php', 'Settings.php~', 'Settings_bak.php~');
  2534. foreach ($securityFiles as $i => $securityFile)
  2535. {
  2536. if (!file_exists($boarddir . '/' . $securityFile))
  2537. unset($securityFiles[$i]);
  2538. }
  2539. if (!empty($securityFiles) || (!empty($modSettings['cache_enable']) && !is_writable($cachedir)))
  2540. {
  2541. echo '
  2542. <div class="errorbox">
  2543. <p class="alert">!!</p>
  2544. <h3>', empty($securityFiles) ? $txt['cache_writable_head'] : $txt['security_risk'], '</h3>
  2545. <p>';
  2546. foreach ($securityFiles as $securityFile)
  2547. {
  2548. echo '
  2549. ', $txt['not_removed'], '<strong>', $securityFile, '</strong>!<br />';
  2550. if ($securityFile == 'Settings.php~' || $securityFile == 'Settings_bak.php~')
  2551. echo '
  2552. ', sprintf($txt['not_removed_extra'], $securityFile, substr($securityFile, 0, -1)), '<br />';
  2553. }
  2554. if (!empty($modSettings['cache_enable']) && !is_writable($cachedir))
  2555. echo '
  2556. <strong>', $txt['cache_writable'], '</strong><br />';
  2557. echo '
  2558. </p>
  2559. </div>';
  2560. }
  2561. }
  2562. // If the user is banned from posting inform them of it.
  2563. elseif (in_array($layer, array('main', 'body')) && isset($_SESSION['ban']['cannot_post']) && !$showed_banned)
  2564. {
  2565. $showed_banned = true;
  2566. echo '
  2567. <div class="windowbg alert" style="margin: 2ex; padding: 2ex; border: 2px dashed red;">
  2568. ', sprintf($txt['you_are_post_banned'], $user_info['is_guest'] ? $txt['guest_title'] : $user_info['name']);
  2569. if (!empty($_SESSION['ban']['cannot_post']['reason']))
  2570. echo '
  2571. <div style="padding-left: 4ex; padding-top: 1ex;">', $_SESSION['ban']['cannot_post']['reason'], '</div>';
  2572. if (!empty($_SESSION['ban']['expire_time']))
  2573. echo '
  2574. <div>', sprintf($txt['your_ban_expires'], timeformat($_SESSION['ban']['expire_time'], false)), '</div>';
  2575. else
  2576. echo '
  2577. <div>', $txt['your_ban_expires_never'], '</div>';
  2578. echo '
  2579. </div>';
  2580. }
  2581. }
  2582. if (isset($settings['use_default_images']) && $settings['use_default_images'] == 'defaults' && isset($settings['default_template']))
  2583. {
  2584. $settings['theme_url'] = $settings['default_theme_url'];
  2585. $settings['images_url'] = $settings['default_images_url'];
  2586. $settings['theme_dir'] = $settings['default_theme_dir'];
  2587. }
  2588. }
  2589. // Show the copyright...
  2590. function theme_copyright($get_it = false)
  2591. {
  2592. global $forum_copyright, $context, $boardurl, $forum_version, $txt, $modSettings;
  2593. // Don't display copyright for things like SSI.
  2594. if (!isset($forum_version))
  2595. return;
  2596. // Put in the version...
  2597. $forum_copyright = sprintf($forum_copyright, $forum_version);
  2598. echo '
  2599. <span class="smalltext" style="display: inline; visibility: visible; font-family: Verdana, Arial, sans-serif;">' . $forum_copyright . '
  2600. </span>';
  2601. }
  2602. function template_footer()
  2603. {
  2604. global $context, $settings, $modSettings, $time_start, $db_count;
  2605. // Show the load time? (only makes sense for the footer.)
  2606. $context['show_load_time'] = !empty($modSettings['timeLoadPageEnable']);
  2607. $context['load_time'] = round(array_sum(explode(' ', microtime())) - array_sum(explode(' ', $time_start)), 3);
  2608. $context['load_queries'] = $db_count;
  2609. if (isset($settings['use_default_images']) && $settings['use_default_images'] == 'defaults' && isset($settings['default_template']))
  2610. {
  2611. $settings['theme_url'] = $settings['actual_theme_url'];
  2612. $settings['images_url'] = $settings['actual_images_url'];
  2613. $settings['theme_dir'] = $settings['actual_theme_dir'];
  2614. }
  2615. foreach (array_reverse($context['template_layers']) as $layer)
  2616. loadSubTemplate($layer . '_below', true);
  2617. }
  2618. // Get an attachment's encrypted filename. If $new is true, won't check for file existence.
  2619. function getAttachmentFilename($filename, $attachment_id, $dir = null, $new = false, $file_hash = '')
  2620. {
  2621. global $modSettings, $smcFunc;
  2622. // Just make up a nice hash...
  2623. if ($new)
  2624. return sha1(md5($filename . time()) . mt_rand());
  2625. // Grab the file hash if it wasn't added.
  2626. if ($file_hash === '')
  2627. {
  2628. $request = $smcFunc['db_query']('', '
  2629. SELECT file_hash
  2630. FROM {db_prefix}attachments
  2631. WHERE id_attach = {int:id_attach}',
  2632. array(
  2633. 'id_attach' => $attachment_id,
  2634. ));
  2635. if ($smcFunc['db_num_rows']($request) === 0)
  2636. return false;
  2637. list ($file_hash) = $smcFunc['db_fetch_row']($request);
  2638. $smcFunc['db_free_result']($request);
  2639. }
  2640. // In case of files from the old system, do a legacy call.
  2641. if (empty($file_hash))
  2642. return getLegacyAttachmentFilename($filename, $attachment_id, $dir, $new);
  2643. // Are we using multiple directories?
  2644. if (!empty($modSettings['currentAttachmentUploadDir']))
  2645. {
  2646. if (!is_array($modSettings['attachmentUploadDir']))
  2647. $modSettings['attachmentUploadDir'] = unserialize($modSettings['attachmentUploadDir']);
  2648. $path = $modSettings['attachmentUploadDir'][$dir];
  2649. }
  2650. else
  2651. $path = $modSettings['attachmentUploadDir'];
  2652. return $path . '/' . $attachment_id . '_' . $file_hash;
  2653. }
  2654. // Older attachments may still use this function.
  2655. function getLegacyAttachmentFilename($filename, $attachment_id, $dir = null, $new = false)
  2656. {
  2657. global $modSettings, $db_character_set;
  2658. $clean_name = $filename;
  2659. // Remove international characters (windows-1252)
  2660. // These lines should never be needed again. Still, behave.
  2661. if (empty($db_character_set) || $db_character_set != 'utf8')
  2662. {
  2663. $clean_name = strtr($filename,
  2664. "\x8a\x8e\x9a\x9e\x9f\xc0\xc1\xc2\xc3\xc4\xc5\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf\xd1\xd2\xd3\xd4\xd5\xd6\xd8\xd9\xda\xdb\xdc\xdd\xe0\xe1\xe2\xe3\xe4\xe5\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef\xf1\xf2\xf3\xf4\xf5\xf6\xf8\xf9\xfa\xfb\xfc\xfd\xff",
  2665. 'SZszYAAAAAACEEEEIIIINOOOOOOUUUUYaaaaaaceeeeiiiinoooooouuuuyy');
  2666. $clean_name = strtr($clean_name, array("\xde" => 'TH', "\xfe" =>
  2667. 'th', "\xd0" => 'DH', "\xf0" => 'dh', "\xdf" => 'ss', "\x8c" => 'OE',
  2668. "\x9c" => 'oe', "\c6" => 'AE', "\xe6" => 'ae', "\xb5" => 'u'));
  2669. }
  2670. // Sorry, no spaces, dots, or anything else but letters allowed.
  2671. $clean_name = preg_replace(array('/\s/', '/[^\w_\.\-]/'), array('_', ''), $clean_name);
  2672. $enc_name = $attachment_id . '_' . strtr($clean_name, '.', '_') . md5($clean_name);
  2673. $clean_name = preg_replace('~\.[\.]+~', '.', $clean_name);
  2674. if ($attachment_id == false || ($new && empty($modSettings['attachmentEncryptFilenames'])))
  2675. return $clean_name;
  2676. elseif ($new)
  2677. return $enc_name;
  2678. // Are we using multiple directories?
  2679. if (!empty($modSettings['currentAttachmentUploadDir']))
  2680. {
  2681. if (!is_array($modSettings['attachmentUploadDir']))
  2682. $modSettings['attachmentUploadDir'] = unserialize($modSettings['attachmentUploadDir']);
  2683. $path = $modSettings['attachmentUploadDir'][$dir];
  2684. }
  2685. else
  2686. $path = $modSettings['attachmentUploadDir'];
  2687. if (file_exists($path . '/' . $enc_name))
  2688. $filename = $path . '/' . $enc_name;
  2689. else
  2690. $filename = $path . '/' . $clean_name;
  2691. return $filename;
  2692. }
  2693. // Convert a single IP to a ranged IP.
  2694. function ip2range($fullip)
  2695. {
  2696. // Pretend that 'unknown' is 255.255.255.255. (since that can't be an IP anyway.)
  2697. if ($fullip == 'unknown')
  2698. $fullip = '255.255.255.255';
  2699. $ip_parts = explode('.', $fullip);
  2700. $ip_array = array();
  2701. if (count($ip_parts) != 4)
  2702. return array();
  2703. for ($i = 0; $i < 4; $i++)
  2704. {
  2705. if ($ip_parts[$i] == '*')
  2706. $ip_array[$i] = array('low' => '0', 'high' => '255');
  2707. elseif (preg_match('/^(\d{1,3})\-(\d{1,3})$/', $ip_parts[$i], $range) == 1)
  2708. $ip_array[$i] = array('low' => $range[1], 'high' => $range[2]);
  2709. elseif (is_numeric($ip_parts[$i]))
  2710. $ip_array[$i] = array('low' => $ip_parts[$i], 'high' => $ip_parts[$i]);
  2711. }
  2712. return $ip_array;
  2713. }
  2714. // Lookup an IP; try shell_exec first because we can do a timeout on it.
  2715. function host_from_ip($ip)
  2716. {
  2717. global $modSettings;
  2718. if (($host = cache_get_data('hostlookup-' . $ip, 600)) !== null)
  2719. return $host;
  2720. $t = microtime();
  2721. // If we can't access nslookup/host, PHP 4.1.x might just crash.
  2722. if (@version_compare(PHP_VERSION, '4.2.0') == -1)
  2723. $host = false;
  2724. // Try the Linux host command, perhaps?
  2725. if (!isset($host) && (strpos(strtolower(PHP_OS), 'win') === false || strpos(strtolower(PHP_OS), 'darwin') !== false) && mt_rand(0, 1) == 1)
  2726. {
  2727. if (!isset($modSettings['host_to_dis']))
  2728. $test = @shell_exec('host -W 1 ' . @escapeshellarg($ip));
  2729. else
  2730. $test = @shell_exec('host ' . @escapeshellarg($ip));
  2731. // Did host say it didn't find anything?
  2732. if (strpos($test, 'not found') !== false)
  2733. $host = '';
  2734. // Invalid server option?
  2735. elseif ((strpos($test, 'invalid option') || strpos($test, 'Invalid query name 1')) && !isset($modSettings['host_to_dis']))
  2736. updateSettings(array('host_to_dis' => 1));
  2737. // Maybe it found something, after all?
  2738. elseif (preg_match('~\s([^\s]+?)\.\s~', $test, $match) == 1)
  2739. $host = $match[1];
  2740. }
  2741. // This is nslookup; usually only Windows, but possibly some Unix?
  2742. if (!isset($host) && strpos(strtolower(PHP_OS), 'win') !== false && strpos(strtolower(PHP_OS), 'darwin') === false && mt_rand(0, 1) == 1)
  2743. {
  2744. $test = @shell_exec('nslookup -timeout=1 ' . @escapeshellarg($ip));
  2745. if (strpos($test, 'Non-existent domain') !== false)
  2746. $host = '';
  2747. elseif (preg_match('~Name:\s+([^\s]+)~', $test, $match) == 1)
  2748. $host = $match[1];
  2749. }
  2750. // This is the last try :/.
  2751. if (!isset($host) || $host === false)
  2752. $host = @gethostbyaddr($ip);
  2753. // It took a long time, so let's cache it!
  2754. if (array_sum(explode(' ', microtime())) - array_sum(explode(' ', $t)) > 0.5)
  2755. cache_put_data('hostlookup-' . $ip, $host, 600);
  2756. return $host;
  2757. }
  2758. // Chops a string into words and prepares them to be inserted into (or searched from) the database.
  2759. function text2words($text, $max_chars = 20, $encrypt = false)
  2760. {
  2761. global $smcFunc, $context;
  2762. // Step 1: Remove entities/things we don't consider words:
  2763. $words = preg_replace('~(?:[\x0B\0' . ($context['utf8'] ? ($context['server']['complex_preg_chars'] ? '\x{A0}' : "\xC2\xA0") : '\xA0') . '\t\r\s\n(){}\\[\\]<>!@$%^*.,:+=`\~\?/\\\\]+|&(?:amp|lt|gt|quot);)+~' . ($context['utf8'] ? 'u' : ''), ' ', strtr($text, array('<br />' => ' ')));
  2764. // Step 2: Entities we left to letters, where applicable, lowercase.
  2765. $words = un_htmlspecialchars($smcFunc['strtolower']($words));
  2766. // Step 3: Ready to split apart and index!
  2767. $words = explode(' ', $words);
  2768. if ($encrypt)
  2769. {
  2770. $possible_chars = array_flip(array_merge(range(46, 57), range(65, 90), range(97, 122)));
  2771. $returned_ints = array();
  2772. foreach ($words as $word)
  2773. {
  2774. if (($word = trim($word, '-_\'')) !== '')
  2775. {
  2776. $encrypted = substr(crypt($word, 'uk'), 2, $max_chars);
  2777. $total = 0;
  2778. for ($i = 0; $i < $max_chars; $i++)
  2779. $total += $possible_chars[ord($encrypted{$i})] * pow(63, $i);
  2780. $returned_ints[] = $max_chars == 4 ? min($total, 16777215) : $total;
  2781. }
  2782. }
  2783. return array_unique($returned_ints);
  2784. }
  2785. else
  2786. {
  2787. // Trim characters before and after and add slashes for database insertion.
  2788. $returned_words = array();
  2789. foreach ($words as $word)
  2790. if (($word = trim($word, '-_\'')) !== '')
  2791. $returned_words[] = $max_chars === null ? $word : substr($word, 0, $max_chars);
  2792. // Filter out all words that occur more than once.
  2793. return array_unique($returned_words);
  2794. }
  2795. }
  2796. // Creates an image/text button
  2797. function create_button($name, $alt, $label = '', $custom = '', $force_use = false)
  2798. {
  2799. global $settings, $txt, $context;
  2800. // Does the current loaded theme have this and we are not forcing the usage of this function?
  2801. if (function_exists('template_create_button') && !$force_use)
  2802. return template_create_button($name, $alt, $label = '', $custom = '');
  2803. if (!$settings['use_image_buttons'])
  2804. return $txt[$alt];
  2805. elseif (!empty($settings['use_buttons']))
  2806. return '<img src="' . $settings['images_url'] . '/buttons/' . $name . '" alt="' . $txt[$alt] . '" ' . $custom . ' />' . ($label != '' ? '<strong>' . $txt[$label] . '</strong>' : '');
  2807. else
  2808. return '<img src="' . $settings['lang_images_url'] . '/' . $name . '" alt="' . $txt[$alt] . '" ' . $custom . ' />';
  2809. }
  2810. // Empty out the cache folder.
  2811. function clean_cache($type = '')
  2812. {
  2813. global $cachedir, $sourcedir;
  2814. // No directory = no game.
  2815. if (!is_dir($cachedir))
  2816. return;
  2817. // Remove the files in SMF's own disk cache, if any
  2818. $dh = opendir($cachedir);
  2819. while ($file = readdir($dh))
  2820. {
  2821. if ($file != '.' && $file != '..' && $file != 'index.php' && $file != '.htaccess' && (!$type || substr($file, 0, strlen($type)) == $type))
  2822. @unlink($cachedir . '/' . $file);
  2823. }
  2824. closedir($dh);
  2825. // Invalidate cache, to be sure!
  2826. // ... as long as Load.php can be modified, anyway.
  2827. @touch($sourcedir . '/' . 'Load.php');
  2828. clearstatcache();
  2829. }
  2830. // Load classes that are both (E_STRICT) PHP 4 and PHP 5 compatible.
  2831. function loadClassFile($filename)
  2832. {
  2833. global $sourcedir;
  2834. static $files_included = array();
  2835. if (!file_exists($sourcedir . '/' . $filename))
  2836. fatal_lang_error('error_bad_file', 'general', array($sourcedir . '/' . $filename));
  2837. // Using a version below PHP 5.0? Do a compatibility conversion.
  2838. if (@version_compare(PHP_VERSION, '5.0.0') != 1)
  2839. {
  2840. // Check if it was included before.
  2841. if (in_array($filename, $files_included))
  2842. return;
  2843. // Make sure we don't include it again.
  2844. $files_included[] = $filename;
  2845. // Do some replacements to make it PHP 4 compatible.
  2846. eval('?' . '>' . preg_replace(array(
  2847. '~class\s+([\w-_]+)([^}]+)function\s+__construct\s*\(~',
  2848. '~([\s\t]+)public\s+\$~',
  2849. '~([\s\t]+)private\s+\$~',
  2850. '~([\s\t]+)protected\s+\$~',
  2851. '~([\s\t]+)public\s+function\s+~',
  2852. '~([\s\t]+)private\s+function\s+~',
  2853. '~([\s\t]+)protected\s+function\s+~',
  2854. ), array(
  2855. 'class $1$2function $1(',
  2856. '$1var $',
  2857. '$1var $',
  2858. '$1var $',
  2859. '$1function ',
  2860. '$1function ',
  2861. '$1function ',
  2862. ), rtrim(file_get_contents($sourcedir . '/' . $filename))));
  2863. }
  2864. else
  2865. require_once($sourcedir . '/' . $filename);
  2866. }
  2867. function setupMenuContext()
  2868. {
  2869. global $context, $modSettings, $user_info, $txt, $scripturl;
  2870. // Set up the menu privileges.
  2871. $context['allow_search'] = allowedTo('search_posts');
  2872. $context['allow_admin'] = allowedTo(array('admin_forum', 'manage_boards', 'manage_permissions', 'moderate_forum', 'manage_membergroups', 'manage_bans', 'send_mail', 'edit_news', 'manage_attachments', 'manage_smileys'));
  2873. $context['allow_edit_profile'] = !$user_info['is_guest'] && allowedTo(array('profile_view_own', 'profile_view_any', 'profile_identity_own', 'profile_identity_any', 'profile_extra_own', 'profile_extra_any', 'profile_remove_own', 'profile_remove_any', 'moderate_forum', 'manage_membergroups', 'profile_title_own', 'profile_title_any'));
  2874. $context['allow_memberlist'] = allowedTo('view_mlist');
  2875. $context['allow_calendar'] = allowedTo('calendar_view') && !empty($modSettings['cal_enabled']);
  2876. $context['allow_moderation_center'] = $context['user']['can_mod'];
  2877. $context['allow_pm'] = allowedTo('pm_read');
  2878. $cacheTime = $modSettings['lastActive'] * 60;
  2879. // All the buttons we can possible want and then some, try pulling the final list of buttons from cache first.
  2880. if (($menu_buttons = cache_get_data('menu_buttons-' . implode('_', $user_info['groups']) . '-' . $user_info['language'], $cacheTime)) === null || time() - $cacheTime <= $modSettings['settings_updated'])
  2881. {
  2882. $buttons = array(
  2883. 'home' => array(
  2884. 'title' => $txt['home'],
  2885. 'href' => $scripturl,
  2886. 'show' => true,
  2887. 'sub_buttons' => array(
  2888. ),
  2889. 'is_last' => $context['right_to_left'],
  2890. ),
  2891. 'help' => array(
  2892. 'title' => $txt['help'],
  2893. 'href' => $scripturl . '?action=help',
  2894. 'show' => true,
  2895. 'sub_buttons' => array(
  2896. ),
  2897. ),
  2898. 'search' => array(
  2899. 'title' => $txt['search'],
  2900. 'href' => $scripturl . '?action=search',
  2901. 'show' => $context['allow_search'],
  2902. 'sub_buttons' => array(
  2903. ),
  2904. ),
  2905. 'admin' => array(
  2906. 'title' => $txt['admin'],
  2907. 'href' => $scripturl . '?action=admin',
  2908. 'show' => $context['allow_admin'],
  2909. 'sub_buttons' => array(
  2910. 'featuresettings' => array(
  2911. 'title' => $txt['modSettings_title'],
  2912. 'href' => $scripturl . '?action=admin;area=featuresettings',
  2913. 'show' => allowedTo('admin_forum'),
  2914. ),
  2915. 'packages' => array(
  2916. 'title' => $txt['package'],
  2917. 'href' => $scripturl . '?action=admin;area=packages',
  2918. 'show' => allowedTo('admin_forum'),
  2919. ),
  2920. 'errorlog' => array(
  2921. 'title' => $txt['errlog'],
  2922. 'href' => $scripturl . '?action=admin;area=logs;sa=errorlog;desc',
  2923. 'show' => allowedTo('admin_forum') && !empty($modSettings['enableErrorLogging']),
  2924. ),
  2925. 'permissions' => array(
  2926. 'title' => $txt['edit_permissions'],
  2927. 'href' => $scripturl . '?action=admin;area=permissions',
  2928. 'show' => allowedTo('manage_permissions'),
  2929. 'is_last' => true,
  2930. ),
  2931. ),
  2932. ),
  2933. 'moderate' => array(
  2934. 'title' => $txt['moderate'],
  2935. 'href' => $scripturl . '?action=moderate',
  2936. 'show' => $context['allow_moderation_center'],
  2937. 'sub_buttons' => array(
  2938. 'modlog' => array(
  2939. 'title' => $txt['modlog_view'],
  2940. 'href' => $scripturl . '?action=moderate;area=modlog',
  2941. 'show' => !empty($modSettings['modlog_enabled']) && !empty($user_info['mod_cache']) && $user_info['mod_cache']['bq'] != '0=1',
  2942. ),
  2943. 'poststopics' => array(
  2944. 'title' => $txt['mc_unapproved_poststopics'],
  2945. 'href' => $scripturl . '?action=moderate;area=postmod;sa=posts',
  2946. 'show' => $modSettings['postmod_active'] && !empty($user_info['mod_cache']['ap']),
  2947. ),
  2948. 'attachments' => array(
  2949. 'title' => $txt['mc_unapproved_attachments'],
  2950. 'href' => $scripturl . '?action=moderate;area=attachmod;sa=attachments',
  2951. 'show' => $modSettings['postmod_active'] && !empty($user_info['mod_cache']['ap']),
  2952. ),
  2953. 'reports' => array(
  2954. 'title' => $txt['mc_reported_posts'],
  2955. 'href' => $scripturl . '?action=moderate;area=reports',
  2956. 'show' => !empty($user_info['mod_cache']) && $user_info['mod_cache']['bq'] != '0=1',
  2957. 'is_last' => true,
  2958. ),
  2959. ),
  2960. ),
  2961. 'profile' => array(
  2962. 'title' => $txt['profile'],
  2963. 'href' => $scripturl . '?action=profile',
  2964. 'show' => $context['allow_edit_profile'],
  2965. 'sub_buttons' => array(
  2966. 'summary' => array(
  2967. 'title' => $txt['summary'],
  2968. 'href' => $scripturl . '?action=profile',
  2969. 'show' => true,
  2970. ),
  2971. 'account' => array(
  2972. 'title' => $txt['account'],
  2973. 'href' => $scripturl . '?action=profile;area=account',
  2974. 'show' => allowedTo(array('profile_identity_any', 'profile_identity_own', 'manage_membergroups')),
  2975. ),
  2976. 'profile' => array(
  2977. 'title' => $txt['forumprofile'],
  2978. 'href' => $scripturl . '?action=profile;area=forumprofile',
  2979. 'show' => allowedTo(array('profile_extra_any', 'profile_extra_own')),
  2980. 'is_last' => true,
  2981. ),
  2982. ),
  2983. ),
  2984. 'pm' => array(
  2985. 'title' => $txt['pm_short'],
  2986. 'href' => $scripturl . '?action=pm',
  2987. 'show' => $context['allow_pm'],
  2988. 'sub_buttons' => array(
  2989. 'pm_read' => array(
  2990. 'title' => $txt['pm_menu_read'],
  2991. 'href' => $scripturl . '?action=pm',
  2992. 'show' => allowedTo('pm_read'),
  2993. ),
  2994. 'pm_send' => array(
  2995. 'title' => $txt['pm_menu_send'],
  2996. 'href' => $scripturl . '?action=pm;sa=send',
  2997. 'show' => allowedTo('pm_send'),
  2998. 'is_last' => true,
  2999. ),
  3000. ),
  3001. ),
  3002. 'calendar' => array(
  3003. 'title' => $txt['calendar'],
  3004. 'href' => $scripturl . '?action=calendar',
  3005. 'show' => $context['allow_calendar'],
  3006. 'sub_buttons' => array(
  3007. 'view' => array(
  3008. 'title' => $txt['calendar_menu'],
  3009. 'href' => $scripturl . '?action=calendar',
  3010. 'show' => allowedTo('calendar_post'),
  3011. ),
  3012. 'post' => array(
  3013. 'title' => $txt['calendar_post_event'],
  3014. 'href' => $scripturl . '?action=calendar;sa=post',
  3015. 'show' => allowedTo('calendar_post'),
  3016. 'is_last' => true,
  3017. ),
  3018. ),
  3019. ),
  3020. 'mlist' => array(
  3021. 'title' => $txt['members_title'],
  3022. 'href' => $scripturl . '?action=mlist',
  3023. 'show' => $context['allow_memberlist'],
  3024. 'sub_buttons' => array(
  3025. 'mlist_view' => array(
  3026. 'title' => $txt['mlist_menu_view'],
  3027. 'href' => $scripturl . '?action=mlist',
  3028. 'show' => true,
  3029. ),
  3030. 'mlist_search' => array(
  3031. 'title' => $txt['mlist_search'],
  3032. 'href' => $scripturl . '?action=mlist;sa=search',
  3033. 'show' => true,
  3034. 'is_last' => true,
  3035. ),
  3036. ),
  3037. ),
  3038. 'login' => array(
  3039. 'title' => $txt['login'],
  3040. 'href' => $scripturl . '?action=login',
  3041. 'show' => $user_info['is_guest'],
  3042. 'sub_buttons' => array(
  3043. ),
  3044. ),
  3045. 'register' => array(
  3046. 'title' => $txt['register'],
  3047. 'href' => $scripturl . '?action=register',
  3048. 'show' => $user_info['is_guest'],
  3049. 'sub_buttons' => array(
  3050. ),
  3051. 'is_last' => !$context['right_to_left'],
  3052. ),
  3053. 'logout' => array(
  3054. 'title' => $txt['logout'],
  3055. 'href' => $scripturl . '?action=logout;%1$s=%2$s',
  3056. 'show' => !$user_info['is_guest'],
  3057. 'sub_buttons' => array(
  3058. ),
  3059. 'is_last' => !$context['right_to_left'],
  3060. ),
  3061. );
  3062. // Allow editing menu buttons easily.
  3063. call_integration_hook('integrate_menu_buttons', array(&$buttons));
  3064. // Now we put the buttons in the context so the theme can use them.
  3065. $menu_buttons = array();
  3066. foreach ($buttons as $act => $button)
  3067. if (!empty($button['show']))
  3068. {
  3069. $button['active_button'] = false;
  3070. // Make sure the last button truely is the last button.
  3071. if (!empty($button['is_last']))
  3072. {
  3073. if (isset($last_button))
  3074. unset($menu_buttons[$last_button]['is_last']);
  3075. $last_button = $act;
  3076. }
  3077. // Go through the sub buttons if there are any.
  3078. if (!empty($button['sub_buttons']))
  3079. foreach ($button['sub_buttons'] as $key => $subbutton)
  3080. {
  3081. if (empty($subbutton['show']))
  3082. unset($button['sub_buttons'][$key]);
  3083. // 2nd level sub buttons next...
  3084. if (!empty($subbutton['sub_buttons']))
  3085. {
  3086. foreach ($subbutton['sub_buttons'] as $key2 => $sub_button2)
  3087. {
  3088. if (empty($sub_button2['show']))
  3089. unset($button['sub_buttons'][$key]['sub_buttons'][$key2]);
  3090. }
  3091. }
  3092. }
  3093. $menu_buttons[$act] = $button;
  3094. }
  3095. if (!empty($modSettings['cache_enable']) && $modSettings['cache_enable'] >= 2)
  3096. cache_put_data('menu_buttons-' . implode('_', $user_info['groups']) . '-' . $user_info['language'], $menu_buttons, $cacheTime);
  3097. }
  3098. $context['menu_buttons'] = $menu_buttons;
  3099. // Logging out requires the session id in the url.
  3100. if (isset($context['menu_buttons']['logout']))
  3101. $context['menu_buttons']['logout']['href'] = sprintf($context['menu_buttons']['logout']['href'], $context['session_var'], $context['session_id']);
  3102. // Figure out which action we are doing so we can set the active tab.
  3103. // Default to home.
  3104. $current_action = 'home';
  3105. if (isset($context['menu_buttons'][$context['current_action']]))
  3106. $current_action = $context['current_action'];
  3107. elseif ($context['current_action'] == 'search2')
  3108. $current_action = 'search';
  3109. elseif ($context['current_action'] == 'theme')
  3110. $current_action = isset($_REQUEST['sa']) && $_REQUEST['sa'] == 'pick' ? 'profile' : 'admin';
  3111. elseif ($context['current_action'] == 'register2')
  3112. $current_action = 'register';
  3113. elseif ($context['current_action'] == 'login2' || ($user_info['is_guest'] && $context['current_action'] == 'reminder'))
  3114. $current_action = 'login';
  3115. elseif ($context['current_action'] == 'groups' && $context['allow_moderation_center'])
  3116. $current_action = 'moderate';
  3117. $context['menu_buttons'][$current_action]['active_button'] = true;
  3118. if (!$user_info['is_guest'] && $context['user']['unread_messages'] > 0 && isset($context['menu_buttons']['pm']))
  3119. {
  3120. $context['menu_buttons']['pm']['alttitle'] = $context['menu_buttons']['pm']['title'] . ' [' . $context['user']['unread_messages'] . ']';
  3121. $context['menu_buttons']['pm']['title'] .= ' [<strong>' . $context['user']['unread_messages'] . '</strong>]';
  3122. }
  3123. }
  3124. // Generate a random seed and ensure it's stored in settings.
  3125. function smf_seed_generator()
  3126. {
  3127. global $modSettings;
  3128. // Never existed?
  3129. if (empty($modSettings['rand_seed']))
  3130. {
  3131. $modSettings['rand_seed'] = microtime() * 1000000;
  3132. updateSettings(array('rand_seed' => $modSettings['rand_seed']));
  3133. }
  3134. if (@version_compare(PHP_VERSION, '4.2.0') == -1)
  3135. {
  3136. $seed = ($modSettings['rand_seed'] + ((double) microtime() * 1000003)) & 0x7fffffff;
  3137. mt_srand($seed);
  3138. }
  3139. // Change the seed.
  3140. updateSettings(array('rand_seed' => mt_rand()));
  3141. }
  3142. // Process functions of an integration hook.
  3143. function call_integration_hook($hook, $parameters = array())
  3144. {
  3145. global $modSettings;
  3146. $results = array();
  3147. if (empty($modSettings[$hook]))
  3148. return $results;
  3149. $functions = explode(',', $modSettings[$hook]);
  3150. // Loop through each function.
  3151. foreach ($functions as $function)
  3152. {
  3153. $function = trim($function);
  3154. $call = strpos($function, '::') !== false ? explode('::', $function) : $function;
  3155. // Is it valid?
  3156. if (is_callable($call))
  3157. $results[$function] = call_user_func_array($call, $parameters);
  3158. }
  3159. return $results;
  3160. }
  3161. // Add a function for integration hook.
  3162. function add_integration_function($hook, $function, $permanent = true)
  3163. {
  3164. global $smcFunc, $modSettings;
  3165. // Is it going to be permanent?
  3166. if ($permanent)
  3167. {
  3168. $request = $smcFunc['db_query']('', '
  3169. SELECT value
  3170. FROM {db_prefix}settings
  3171. WHERE variable = {string:variable}',
  3172. array(
  3173. 'variable' => $hook,
  3174. )
  3175. );
  3176. list($current_functions) = $smcFunc['db_fetch_row']($request);
  3177. $smcFunc['db_free_result']($request);
  3178. if (!empty($current_functions))
  3179. {
  3180. $current_functions = explode(',', $current_functions);
  3181. if (in_array($function, $current_functions))
  3182. return;
  3183. $permanent_functions = array_merge($current_functions, array($function));
  3184. }
  3185. else
  3186. $permanent_functions = array($function);
  3187. updateSettings(array($hook => implode(',', $permanent_functions)));
  3188. }
  3189. // Make current function list usable.
  3190. $functions = empty($modSettings[$hook]) ? array() : explode(',', $modSettings[$hook]);
  3191. // Do nothing, if it's already there.
  3192. if (in_array($function, $functions))
  3193. return;
  3194. $functions[] = $function;
  3195. $modSettings[$hook] = implode(',', $functions);
  3196. }
  3197. // Remove an integration hook function.
  3198. function remove_integration_function($hook, $function)
  3199. {
  3200. global $smcFunc, $modSettings;
  3201. // Get the permanent functions.
  3202. $request = $smcFunc['db_query']('', '
  3203. SELECT value
  3204. FROM {db_prefix}settings
  3205. WHERE variable = {string:variable}',
  3206. array(
  3207. 'variable' => $hook,
  3208. )
  3209. );
  3210. list($current_functions) = $smcFunc['db_fetch_row']($request);
  3211. $smcFunc['db_free_result']($request);
  3212. if (!empty($current_functions))
  3213. {
  3214. $current_functions = explode(',', $current_functions);
  3215. if (in_array($function, $current_functions))
  3216. updateSettings(array($hook => implode(',', array_diff($current_functions, array($function)))));
  3217. }
  3218. // Turn the function list into something usable.
  3219. $functions = empty($modSettings[$hook]) ? array() : explode(',', $modSettings[$hook]);
  3220. // You can only remove it if it's available.
  3221. if (!in_array($function, $functions))
  3222. return;
  3223. $functions = array_diff($functions, array($function));
  3224. $modSettings[$hook] = implode(',', $functions);
  3225. }
  3226. ?>