Subs.php 136 KB

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