Subs.php 149 KB

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