Subs.php 142 KB

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