Subs.php 151 KB

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