Subs.php 136 KB

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