Subs.php 135 KB

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