Subs.php 134 KB

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