Subs.php 133 KB

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