Subs.php 150 KB

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