2
0

Subs.php 150 KB

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