Load.php 116 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863
  1. <?php
  2. /**
  3. * This file has the hefty job of loading information for the forum.
  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. * Load the $modSettings array.
  18. *
  19. * @todo okay question of the day: why a function for loading settings is called reloadSettings()
  20. *
  21. * @global array $modSettings is a giant array of all of the forum-wide settings and statistics.
  22. */
  23. function reloadSettings()
  24. {
  25. global $modSettings, $boarddir, $smcFunc, $txt, $db_character_set, $context, $sourcedir;
  26. // Most database systems have not set UTF-8 as their default input charset.
  27. if (!empty($db_character_set))
  28. $smcFunc['db_query']('set_character_set', '
  29. SET NAMES ' . $db_character_set,
  30. array(
  31. )
  32. );
  33. // Try to load it from the cache first; it'll never get cached if the setting is off.
  34. if (($modSettings = cache_get_data('modSettings', 90)) == null)
  35. {
  36. $request = $smcFunc['db_query']('', '
  37. SELECT variable, value
  38. FROM {db_prefix}settings',
  39. array(
  40. )
  41. );
  42. $modSettings = array();
  43. if (!$request)
  44. display_db_error();
  45. while ($row = $smcFunc['db_fetch_row']($request))
  46. $modSettings[$row[0]] = $row[1];
  47. $smcFunc['db_free_result']($request);
  48. // Do a few things to protect against missing settings or settings with invalid values...
  49. if (empty($modSettings['defaultMaxTopics']) || $modSettings['defaultMaxTopics'] <= 0 || $modSettings['defaultMaxTopics'] > 999)
  50. $modSettings['defaultMaxTopics'] = 20;
  51. if (empty($modSettings['defaultMaxMessages']) || $modSettings['defaultMaxMessages'] <= 0 || $modSettings['defaultMaxMessages'] > 999)
  52. $modSettings['defaultMaxMessages'] = 15;
  53. if (empty($modSettings['defaultMaxMembers']) || $modSettings['defaultMaxMembers'] <= 0 || $modSettings['defaultMaxMembers'] > 999)
  54. $modSettings['defaultMaxMembers'] = 30;
  55. if (!empty($modSettings['cache_enable']))
  56. cache_put_data('modSettings', $modSettings, 90);
  57. }
  58. // UTF-8 in regular expressions is unsupported on PHP(win) versions < 4.2.3.
  59. $utf8 = (empty($modSettings['global_character_set']) ? $txt['lang_character_set'] : $modSettings['global_character_set']) === 'UTF-8';
  60. // Set a list of common functions.
  61. $ent_list = empty($modSettings['disableEntityCheck']) ? '&(#\d{1,7}|quot|amp|lt|gt|nbsp);' : '&(#021|quot|amp|lt|gt|nbsp);';
  62. $ent_check = empty($modSettings['disableEntityCheck']) ? array('preg_replace(\'~(&#(\d{1,7}|x[0-9a-fA-F]{1,6});)~e\', \'$smcFunc[\\\'entity_fix\\\'](\\\'\\2\\\')\', ', ')') : array('', '');
  63. // Preg_replace can handle complex characters only for higher PHP versions.
  64. $space_chars = $utf8 ? '\x{A0}\x{AD}\x{2000}-\x{200F}\x{201F}\x{202F}\x{3000}\x{FEFF}' : '\x00-\x08\x0B\x0C\x0E-\x19\xA0';
  65. // global array of anonymous helper functions, used mosly to properly handle multi byte strings
  66. $smcFunc += array(
  67. 'entity_fix' => create_function('$string', '
  68. $num = $string[0] === \'x\' ? hexdec(substr($string, 1)) : (int) $string;
  69. return $num < 0x20 || $num > 0x10FFFF || ($num >= 0xD800 && $num <= 0xDFFF) || $num == 0x202E ? \'\' : \'&#\' . $num . \';\';'),
  70. 'htmlspecialchars' => create_function('$string, $quote_style = ENT_COMPAT, $charset = \'ISO-8859-1\'', '
  71. global $smcFunc;
  72. return ' . strtr($ent_check[0], array('&' => '&amp;')) . 'htmlspecialchars($string, $quote_style, ' . ($utf8 ? '\'UTF-8\'' : '$charset') . ')' . $ent_check[1] . ';'),
  73. 'htmltrim' => create_function('$string', '
  74. global $smcFunc;
  75. return preg_replace(\'~^(?:[ \t\n\r\x0B\x00' . $space_chars . ']|&nbsp;)+|(?:[ \t\n\r\x0B\x00' . $space_chars . ']|&nbsp;)+$~' . ($utf8 ? 'u' : '') . '\', \'\', ' . implode('$string', $ent_check) . ');'),
  76. 'strlen' => create_function('$string', '
  77. global $smcFunc;
  78. return strlen(preg_replace(\'~' . $ent_list . ($utf8 ? '|.~u' : '~') . '\', \'_\', ' . implode('$string', $ent_check) . '));'),
  79. 'strpos' => create_function('$haystack, $needle, $offset = 0', '
  80. global $smcFunc;
  81. $haystack_arr = preg_split(\'~(&#' . (empty($modSettings['disableEntityCheck']) ? '\d{1,7}' : '021') . ';|&quot;|&amp;|&lt;|&gt;|&nbsp;|.)~' . ($utf8 ? 'u' : '') . '\', ' . implode('$haystack', $ent_check) . ', -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
  82. $haystack_size = count($haystack_arr);
  83. if (strlen($needle) === 1)
  84. {
  85. $result = array_search($needle, array_slice($haystack_arr, $offset));
  86. return is_int($result) ? $result + $offset : false;
  87. }
  88. else
  89. {
  90. $needle_arr = preg_split(\'~(&#' . (empty($modSettings['disableEntityCheck']) ? '\d{1,7}' : '021') . ';|&quot;|&amp;|&lt;|&gt;|&nbsp;|.)~' . ($utf8 ? 'u' : '') . '\', ' . implode('$needle', $ent_check) . ', -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
  91. $needle_size = count($needle_arr);
  92. $result = array_search($needle_arr[0], array_slice($haystack_arr, $offset));
  93. while ((int) $result === $result)
  94. {
  95. $offset += $result;
  96. if (array_slice($haystack_arr, $offset, $needle_size) === $needle_arr)
  97. return $offset;
  98. $result = array_search($needle_arr[0], array_slice($haystack_arr, ++$offset));
  99. }
  100. return false;
  101. }'),
  102. 'substr' => create_function('$string, $start, $length = null', '
  103. global $smcFunc;
  104. $ent_arr = preg_split(\'~(&#' . (empty($modSettings['disableEntityCheck']) ? '\d{1,7}' : '021') . ';|&quot;|&amp;|&lt;|&gt;|&nbsp;|.)~' . ($utf8 ? 'u' : '') . '\', ' . implode('$string', $ent_check) . ', -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
  105. return $length === null ? implode(\'\', array_slice($ent_arr, $start)) : implode(\'\', array_slice($ent_arr, $start, $length));'),
  106. 'strtolower' => $utf8 ? (function_exists('mb_strtolower') ? create_function('$string', '
  107. return mb_strtolower($string, \'UTF-8\');') : create_function('$string', '
  108. global $sourcedir;
  109. require_once($sourcedir . \'/Subs-Charset.php\');
  110. return utf8_strtolower($string);')) : 'strtolower',
  111. 'strtoupper' => $utf8 ? (function_exists('mb_strtoupper') ? create_function('$string', '
  112. return mb_strtoupper($string, \'UTF-8\');') : create_function('$string', '
  113. global $sourcedir;
  114. require_once($sourcedir . \'/Subs-Charset.php\');
  115. return utf8_strtoupper($string);')) : 'strtoupper',
  116. 'truncate' => create_function('$string, $length', (empty($modSettings['disableEntityCheck']) ? '
  117. global $smcFunc;
  118. $string = ' . implode('$string', $ent_check) . ';' : '') . '
  119. preg_match(\'~^(' . $ent_list . '|.){\' . $smcFunc[\'strlen\'](substr($string, 0, $length)) . \'}~'. ($utf8 ? 'u' : '') . '\', $string, $matches);
  120. $string = $matches[0];
  121. while (strlen($string) > $length)
  122. $string = preg_replace(\'~(?:' . $ent_list . '|.)$~'. ($utf8 ? 'u' : '') . '\', \'\', $string);
  123. return $string;'),
  124. 'ucfirst' => $utf8 ? create_function('$string', '
  125. global $smcFunc;
  126. return $smcFunc[\'strtoupper\']($smcFunc[\'substr\']($string, 0, 1)) . $smcFunc[\'substr\']($string, 1);') : 'ucfirst',
  127. 'ucwords' => $utf8 ? create_function('$string', '
  128. global $smcFunc;
  129. $words = preg_split(\'~([\s\r\n\t]+)~\', $string, -1, PREG_SPLIT_DELIM_CAPTURE);
  130. for ($i = 0, $n = count($words); $i < $n; $i += 2)
  131. $words[$i] = $smcFunc[\'ucfirst\']($words[$i]);
  132. return implode(\'\', $words);') : 'ucwords',
  133. );
  134. // Setting the timezone is a requirement for some functions in PHP >= 5.1.
  135. if (isset($modSettings['default_timezone']) && function_exists('date_default_timezone_set'))
  136. date_default_timezone_set($modSettings['default_timezone']);
  137. // Check the load averages?
  138. if (!empty($modSettings['loadavg_enable']))
  139. {
  140. if (($modSettings['load_average'] = cache_get_data('loadavg', 90)) == null)
  141. {
  142. $modSettings['load_average'] = @file_get_contents('/proc/loadavg');
  143. if (!empty($modSettings['load_average']) && preg_match('~^([^ ]+?) ([^ ]+?) ([^ ]+)~', $modSettings['load_average'], $matches) != 0)
  144. $modSettings['load_average'] = (float) $matches[1];
  145. elseif (($modSettings['load_average'] = @`uptime`) != null && preg_match('~load average[s]?: (\d+\.\d+), (\d+\.\d+), (\d+\.\d+)~i', $modSettings['load_average'], $matches) != 0)
  146. $modSettings['load_average'] = (float) $matches[1];
  147. else
  148. unset($modSettings['load_average']);
  149. if (!empty($modSettings['load_average']))
  150. cache_put_data('loadavg', $modSettings['load_average'], 90);
  151. }
  152. if (!empty($modSettings['load_average']))
  153. call_integration_hook('integrate_load_average', array($modSettings['load_average']));
  154. if (!empty($modSettings['loadavg_forum']) && !empty($modSettings['load_average']) && $modSettings['load_average'] >= $modSettings['loadavg_forum'])
  155. display_loadavg_error();
  156. }
  157. // Is post moderation alive and well?
  158. $modSettings['postmod_active'] = isset($modSettings['admin_features']) ? in_array('pm', explode(',', $modSettings['admin_features'])) : true;
  159. // Integration is cool.
  160. if (defined('SMF_INTEGRATION_SETTINGS'))
  161. {
  162. $integration_settings = unserialize(SMF_INTEGRATION_SETTINGS);
  163. foreach ($integration_settings as $hook => $function)
  164. add_integration_function($hook, $function, false);
  165. }
  166. // Any files to pre include?
  167. if (!empty($modSettings['integrate_pre_include']))
  168. {
  169. $pre_includes = explode(',', $modSettings['integrate_pre_include']);
  170. foreach ($pre_includes as $include)
  171. {
  172. $include = strtr(trim($include), array('$boarddir' => $boarddir, '$sourcedir' => $sourcedir));
  173. if (file_exists($include))
  174. require_once($include);
  175. }
  176. }
  177. // Call pre load integration functions.
  178. call_integration_hook('integrate_pre_load');
  179. }
  180. /**
  181. * Load all the important user information.
  182. * What it does:
  183. * - sets up the $user_info array
  184. * - assigns $user_info['query_wanna_see_board'] for what boards the user can see.
  185. * - first checks for cookie or integration validation.
  186. * - uses the current session if no integration function or cookie is found.
  187. * - checks password length, if member is activated and the login span isn't over.
  188. * - if validation fails for the user, $id_member is set to 0.
  189. * - updates the last visit time when needed.
  190. */
  191. function loadUserSettings()
  192. {
  193. global $modSettings, $user_settings, $sourcedir, $smcFunc;
  194. global $cookiename, $user_info, $language, $context;
  195. // Check first the integration, then the cookie, and last the session.
  196. if (count($integration_ids = call_integration_hook('integrate_verify_user')) > 0)
  197. {
  198. $id_member = 0;
  199. foreach ($integration_ids as $integration_id)
  200. {
  201. $integration_id = (int) $integration_id;
  202. if ($integration_id > 0)
  203. {
  204. $id_member = $integration_id;
  205. $already_verified = true;
  206. break;
  207. }
  208. }
  209. }
  210. else
  211. $id_member = 0;
  212. if (empty($id_member) && isset($_COOKIE[$cookiename]))
  213. {
  214. // Fix a security hole in PHP 4.3.9 and below...
  215. if (preg_match('~^a:[34]:\{i:0;(i:\d{1,6}|s:[1-8]:"\d{1,8}");i:1;s:(0|40):"([a-fA-F0-9]{40})?";i:2;[id]:\d{1,14};(i:3;i:\d;)?\}$~i', $_COOKIE[$cookiename]) == 1)
  216. {
  217. list ($id_member, $password) = @unserialize($_COOKIE[$cookiename]);
  218. $id_member = !empty($id_member) && strlen($password) > 0 ? (int) $id_member : 0;
  219. }
  220. else
  221. $id_member = 0;
  222. }
  223. elseif (empty($id_member) && isset($_SESSION['login_' . $cookiename]) && ($_SESSION['USER_AGENT'] == $_SERVER['HTTP_USER_AGENT'] || !empty($modSettings['disableCheckUA'])))
  224. {
  225. // @todo Perhaps we can do some more checking on this, such as on the first octet of the IP?
  226. list ($id_member, $password, $login_span) = @unserialize($_SESSION['login_' . $cookiename]);
  227. $id_member = !empty($id_member) && strlen($password) == 40 && $login_span > time() ? (int) $id_member : 0;
  228. }
  229. // Only load this stuff if the user isn't a guest.
  230. if ($id_member != 0)
  231. {
  232. // Is the member data cached?
  233. if (empty($modSettings['cache_enable']) || $modSettings['cache_enable'] < 2 || ($user_settings = cache_get_data('user_settings-' . $id_member, 60)) == null)
  234. {
  235. $request = $smcFunc['db_query']('', '
  236. SELECT mem.*, IFNULL(a.id_attach, 0) AS id_attach, a.filename, a.attachment_type
  237. FROM {db_prefix}members AS mem
  238. LEFT JOIN {db_prefix}attachments AS a ON (a.id_member = {int:id_member})
  239. WHERE mem.id_member = {int:id_member}
  240. LIMIT 1',
  241. array(
  242. 'id_member' => $id_member,
  243. )
  244. );
  245. $user_settings = $smcFunc['db_fetch_assoc']($request);
  246. $smcFunc['db_free_result']($request);
  247. if (!empty($modSettings['cache_enable']) && $modSettings['cache_enable'] >= 2)
  248. cache_put_data('user_settings-' . $id_member, $user_settings, 60);
  249. }
  250. // Did we find 'im? If not, junk it.
  251. if (!empty($user_settings))
  252. {
  253. // As much as the password should be right, we can assume the integration set things up.
  254. if (!empty($already_verified) && $already_verified === true)
  255. $check = true;
  256. // SHA-1 passwords should be 40 characters long.
  257. elseif (strlen($password) == 40)
  258. $check = sha1($user_settings['passwd'] . $user_settings['password_salt']) == $password;
  259. else
  260. $check = false;
  261. // Wrong password or not activated - either way, you're going nowhere.
  262. $id_member = $check && ($user_settings['is_activated'] == 1 || $user_settings['is_activated'] == 11) ? $user_settings['id_member'] : 0;
  263. }
  264. else
  265. $id_member = 0;
  266. // If we no longer have the member maybe they're being all hackey, stop brute force!
  267. if (!$id_member)
  268. {
  269. require_once($sourcedir . '/LogInOut.php');
  270. validatePasswordFlood(!empty($user_settings['id_member']) ? $user_settings['id_member'] : $id_member, !empty($user_settings['passwd_flood']) ? $user_settings['passwd_flood'] : false, $id_member != 0);
  271. }
  272. }
  273. // Found 'im, let's set up the variables.
  274. if ($id_member != 0)
  275. {
  276. // Let's not update the last visit time in these cases...
  277. // 1. SSI doesn't count as visiting the forum.
  278. // 2. RSS feeds and XMLHTTP requests don't count either.
  279. // 3. If it was set within this session, no need to set it again.
  280. // 4. New session, yet updated < five hours ago? Maybe cache can help.
  281. if (SMF != 'SSI' && !isset($_REQUEST['xml']) && (!isset($_REQUEST['action']) || $_REQUEST['action'] != '.xml') && empty($_SESSION['id_msg_last_visit']) && (empty($modSettings['cache_enable']) || ($_SESSION['id_msg_last_visit'] = cache_get_data('user_last_visit-' . $id_member, 5 * 3600)) === null))
  282. {
  283. // @todo can this be cached?
  284. // Do a quick query to make sure this isn't a mistake.
  285. $result = $smcFunc['db_query']('', '
  286. SELECT poster_time
  287. FROM {db_prefix}messages
  288. WHERE id_msg = {int:id_msg}
  289. LIMIT 1',
  290. array(
  291. 'id_msg' => $user_settings['id_msg_last_visit'],
  292. )
  293. );
  294. list ($visitTime) = $smcFunc['db_fetch_row']($result);
  295. $smcFunc['db_free_result']($result);
  296. $_SESSION['id_msg_last_visit'] = $user_settings['id_msg_last_visit'];
  297. // If it was *at least* five hours ago...
  298. if ($visitTime < time() - 5 * 3600)
  299. {
  300. updateMemberData($id_member, array('id_msg_last_visit' => (int) $modSettings['maxMsgID'], 'last_login' => time(), 'member_ip' => $_SERVER['REMOTE_ADDR'], 'member_ip2' => $_SERVER['BAN_CHECK_IP']));
  301. $user_settings['last_login'] = time();
  302. if (!empty($modSettings['cache_enable']) && $modSettings['cache_enable'] >= 2)
  303. cache_put_data('user_settings-' . $id_member, $user_settings, 60);
  304. if (!empty($modSettings['cache_enable']))
  305. cache_put_data('user_last_visit-' . $id_member, $_SESSION['id_msg_last_visit'], 5 * 3600);
  306. }
  307. }
  308. elseif (empty($_SESSION['id_msg_last_visit']))
  309. $_SESSION['id_msg_last_visit'] = $user_settings['id_msg_last_visit'];
  310. $username = $user_settings['member_name'];
  311. if (empty($user_settings['additional_groups']))
  312. $user_info = array(
  313. 'groups' => array($user_settings['id_group'], $user_settings['id_post_group'])
  314. );
  315. else
  316. $user_info = array(
  317. 'groups' => array_merge(
  318. array($user_settings['id_group'], $user_settings['id_post_group']),
  319. explode(',', $user_settings['additional_groups'])
  320. )
  321. );
  322. // Because history has proven that it is possible for groups to go bad - clean up in case.
  323. foreach ($user_info['groups'] as $k => $v)
  324. $user_info['groups'][$k] = (int) $v;
  325. // This is a logged in user, so definitely not a spider.
  326. $user_info['possibly_robot'] = false;
  327. }
  328. // If the user is a guest, initialize all the critical user settings.
  329. else
  330. {
  331. // This is what a guest's variables should be.
  332. $username = '';
  333. $user_info = array('groups' => array(-1));
  334. $user_settings = array();
  335. if (isset($_COOKIE[$cookiename]))
  336. $_COOKIE[$cookiename] = '';
  337. // Create a login token if it doesn't exist yet.
  338. if (!isset($_SESSION['token']['post-login']))
  339. createToken('login');
  340. else
  341. list ($context['login_token_var'],,, $context['login_token']) = $_SESSION['token']['post-login'];
  342. // Do we perhaps think this is a search robot? Check every five minutes just in case...
  343. if ((!empty($modSettings['spider_mode']) || !empty($modSettings['spider_group'])) && (!isset($_SESSION['robot_check']) || $_SESSION['robot_check'] < time() - 300))
  344. {
  345. require_once($sourcedir . '/ManageSearchEngines.php');
  346. $user_info['possibly_robot'] = SpiderCheck();
  347. }
  348. elseif (!empty($modSettings['spider_mode']))
  349. $user_info['possibly_robot'] = isset($_SESSION['id_robot']) ? $_SESSION['id_robot'] : 0;
  350. // If we haven't turned on proper spider hunts then have a guess!
  351. else
  352. {
  353. $ci_user_agent = strtolower($_SERVER['HTTP_USER_AGENT']);
  354. $user_info['possibly_robot'] = (strpos($_SERVER['HTTP_USER_AGENT'], 'Mozilla') === false && strpos($_SERVER['HTTP_USER_AGENT'], 'Opera') === false) || strpos($ci_user_agent, 'googlebot') !== false || strpos($ci_user_agent, 'slurp') !== false || strpos($ci_user_agent, 'crawl') !== false;
  355. }
  356. }
  357. // Set up the $user_info array.
  358. $user_info += array(
  359. 'id' => $id_member,
  360. 'username' => $username,
  361. 'name' => isset($user_settings['real_name']) ? $user_settings['real_name'] : '',
  362. 'email' => isset($user_settings['email_address']) ? $user_settings['email_address'] : '',
  363. 'passwd' => isset($user_settings['passwd']) ? $user_settings['passwd'] : '',
  364. 'language' => empty($user_settings['lngfile']) || empty($modSettings['userLanguage']) ? $language : $user_settings['lngfile'],
  365. 'is_guest' => $id_member == 0,
  366. 'is_admin' => in_array(1, $user_info['groups']),
  367. 'theme' => empty($user_settings['id_theme']) ? 0 : $user_settings['id_theme'],
  368. 'last_login' => empty($user_settings['last_login']) ? 0 : $user_settings['last_login'],
  369. 'ip' => $_SERVER['REMOTE_ADDR'],
  370. 'ip2' => $_SERVER['BAN_CHECK_IP'],
  371. 'posts' => empty($user_settings['posts']) ? 0 : $user_settings['posts'],
  372. 'time_format' => empty($user_settings['time_format']) ? $modSettings['time_format'] : $user_settings['time_format'],
  373. 'time_offset' => empty($user_settings['time_offset']) ? 0 : $user_settings['time_offset'],
  374. 'avatar' => array(
  375. 'url' => isset($user_settings['avatar']) ? $user_settings['avatar'] : '',
  376. 'filename' => empty($user_settings['filename']) ? '' : $user_settings['filename'],
  377. 'custom_dir' => !empty($user_settings['attachment_type']) && $user_settings['attachment_type'] == 1,
  378. 'id_attach' => isset($user_settings['id_attach']) ? $user_settings['id_attach'] : 0
  379. ),
  380. 'smiley_set' => isset($user_settings['smiley_set']) ? $user_settings['smiley_set'] : '',
  381. 'messages' => empty($user_settings['instant_messages']) ? 0 : $user_settings['instant_messages'],
  382. 'unread_messages' => empty($user_settings['unread_messages']) ? 0 : $user_settings['unread_messages'],
  383. 'total_time_logged_in' => empty($user_settings['total_time_logged_in']) ? 0 : $user_settings['total_time_logged_in'],
  384. 'buddies' => !empty($modSettings['enable_buddylist']) && !empty($user_settings['buddy_list']) ? explode(',', $user_settings['buddy_list']) : array(),
  385. 'ignoreboards' => !empty($user_settings['ignore_boards']) && !empty($modSettings['allow_ignore_boards']) ? explode(',', $user_settings['ignore_boards']) : array(),
  386. 'ignoreusers' => !empty($user_settings['pm_ignore_list']) ? explode(',', $user_settings['pm_ignore_list']) : array(),
  387. 'warning' => isset($user_settings['warning']) ? $user_settings['warning'] : 0,
  388. 'permissions' => array(),
  389. );
  390. $user_info['groups'] = array_unique($user_info['groups']);
  391. // Make sure that the last item in the ignore boards array is valid. If the list was too long it could have an ending comma that could cause problems.
  392. if (!empty($user_info['ignoreboards']) && empty($user_info['ignoreboards'][$tmp = count($user_info['ignoreboards']) - 1]))
  393. unset($user_info['ignoreboards'][$tmp]);
  394. // Do we have any languages to validate this?
  395. if (!empty($modSettings['userLanguage']) && (!empty($_GET['language']) || !empty($_SESSION['language'])))
  396. $languages = getLanguages();
  397. // Allow the user to change their language if its valid.
  398. if (!empty($modSettings['userLanguage']) && !empty($_GET['language']) && isset($languages[strtr($_GET['language'], './\\:', '____')]))
  399. {
  400. $user_info['language'] = strtr($_GET['language'], './\\:', '____');
  401. $_SESSION['language'] = $user_info['language'];
  402. }
  403. elseif (!empty($modSettings['userLanguage']) && !empty($_SESSION['language']) && isset($languages[strtr($_SESSION['language'], './\\:', '____')]))
  404. $user_info['language'] = strtr($_SESSION['language'], './\\:', '____');
  405. // Just build this here, it makes it easier to change/use - administrators can see all boards.
  406. if ($user_info['is_admin'])
  407. $user_info['query_see_board'] = '1=1';
  408. // Otherwise just the groups in $user_info['groups'].
  409. else
  410. $user_info['query_see_board'] = '(FIND_IN_SET(' . implode(', b.member_groups) != 0 OR FIND_IN_SET(', $user_info['groups']) . ', b.member_groups) != 0' . (isset($user_info['mod_cache']) ? ' OR ' . $user_info['mod_cache']['mq'] : '') . ')';
  411. // Build the list of boards they WANT to see.
  412. // This will take the place of query_see_boards in certain spots, so it better include the boards they can see also
  413. // If they aren't ignoring any boards then they want to see all the boards they can see
  414. if (empty($user_info['ignoreboards']))
  415. $user_info['query_wanna_see_board'] = $user_info['query_see_board'];
  416. // Ok I guess they don't want to see all the boards
  417. else
  418. $user_info['query_wanna_see_board'] = '(' . $user_info['query_see_board'] . ' AND b.id_board NOT IN (' . implode(',', $user_info['ignoreboards']) . '))';
  419. call_integration_hook('integrate_user_info');
  420. }
  421. /**
  422. * Check for moderators and see if they have access to the board.
  423. * What it does:
  424. * - sets up the $board_info array for current board information.
  425. * - if cache is enabled, the $board_info array is stored in cache.
  426. * - redirects to appropriate post if only message id is requested.
  427. * - is only used when inside a topic or board.
  428. * - determines the local moderators for the board.
  429. * - adds group id 3 if the user is a local moderator for the board they are in.
  430. * - prevents access if user is not in proper group nor a local moderator of the board.
  431. */
  432. function loadBoard()
  433. {
  434. global $txt, $scripturl, $context, $modSettings;
  435. global $board_info, $board, $topic, $user_info, $smcFunc;
  436. // Assume they are not a moderator.
  437. $user_info['is_mod'] = false;
  438. $context['user']['is_mod'] = &$user_info['is_mod'];
  439. // Start the linktree off empty..
  440. $context['linktree'] = array();
  441. // Have they by chance specified a message id but nothing else?
  442. if (empty($_REQUEST['action']) && empty($topic) && empty($board) && !empty($_REQUEST['msg']))
  443. {
  444. // Make sure the message id is really an int.
  445. $_REQUEST['msg'] = (int) $_REQUEST['msg'];
  446. // Looking through the message table can be slow, so try using the cache first.
  447. if (($topic = cache_get_data('msg_topic-' . $_REQUEST['msg'], 120)) === NULL)
  448. {
  449. $request = $smcFunc['db_query']('', '
  450. SELECT id_topic
  451. FROM {db_prefix}messages
  452. WHERE id_msg = {int:id_msg}
  453. LIMIT 1',
  454. array(
  455. 'id_msg' => $_REQUEST['msg'],
  456. )
  457. );
  458. // So did it find anything?
  459. if ($smcFunc['db_num_rows']($request))
  460. {
  461. list ($topic) = $smcFunc['db_fetch_row']($request);
  462. $smcFunc['db_free_result']($request);
  463. // Save save save.
  464. cache_put_data('msg_topic-' . $_REQUEST['msg'], $topic, 120);
  465. }
  466. }
  467. // Remember redirection is the key to avoiding fallout from your bosses.
  468. if (!empty($topic))
  469. redirectexit('topic=' . $topic . '.msg' . $_REQUEST['msg'] . '#msg' . $_REQUEST['msg']);
  470. else
  471. {
  472. loadPermissions();
  473. loadTheme();
  474. fatal_lang_error('topic_gone', false);
  475. }
  476. }
  477. // Load this board only if it is specified.
  478. if (empty($board) && empty($topic))
  479. {
  480. $board_info = array('moderators' => array());
  481. return;
  482. }
  483. if (!empty($modSettings['cache_enable']) && (empty($topic) || $modSettings['cache_enable'] >= 3))
  484. {
  485. // @todo SLOW?
  486. if (!empty($topic))
  487. $temp = cache_get_data('topic_board-' . $topic, 120);
  488. else
  489. $temp = cache_get_data('board-' . $board, 120);
  490. if (!empty($temp))
  491. {
  492. $board_info = $temp;
  493. $board = $board_info['id'];
  494. }
  495. }
  496. if (empty($temp))
  497. {
  498. $request = $smcFunc['db_query']('', '
  499. SELECT
  500. c.id_cat, b.name AS bname, b.description, b.num_topics, b.member_groups,
  501. b.id_parent, c.name AS cname, IFNULL(mem.id_member, 0) AS id_moderator,
  502. mem.real_name' . (!empty($topic) ? ', b.id_board' : '') . ', b.child_level,
  503. b.id_theme, b.override_theme, b.count_posts, b.id_profile, b.redirect,
  504. b.unapproved_topics, b.unapproved_posts' . (!empty($topic) ? ', t.approved, t.id_member_started' : '') . '
  505. FROM {db_prefix}boards AS b' . (!empty($topic) ? '
  506. INNER JOIN {db_prefix}topics AS t ON (t.id_topic = {int:current_topic})' : '') . '
  507. LEFT JOIN {db_prefix}categories AS c ON (c.id_cat = b.id_cat)
  508. LEFT JOIN {db_prefix}moderators AS mods ON (mods.id_board = {raw:board_link})
  509. LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = mods.id_member)
  510. WHERE b.id_board = {raw:board_link}',
  511. array(
  512. 'current_topic' => $topic,
  513. 'board_link' => empty($topic) ? $smcFunc['db_quote']('{int:current_board}', array('current_board' => $board)) : 't.id_board',
  514. )
  515. );
  516. // If there aren't any, skip.
  517. if ($smcFunc['db_num_rows']($request) > 0)
  518. {
  519. $row = $smcFunc['db_fetch_assoc']($request);
  520. // Set the current board.
  521. if (!empty($row['id_board']))
  522. $board = $row['id_board'];
  523. // Basic operating information. (globals... :/)
  524. $board_info = array(
  525. 'id' => $board,
  526. 'moderators' => array(),
  527. 'cat' => array(
  528. 'id' => $row['id_cat'],
  529. 'name' => $row['cname']
  530. ),
  531. 'name' => $row['bname'],
  532. 'description' => $row['description'],
  533. 'num_topics' => $row['num_topics'],
  534. 'unapproved_topics' => $row['unapproved_topics'],
  535. 'unapproved_posts' => $row['unapproved_posts'],
  536. 'unapproved_user_topics' => 0,
  537. 'parent_boards' => getBoardParents($row['id_parent']),
  538. 'parent' => $row['id_parent'],
  539. 'child_level' => $row['child_level'],
  540. 'theme' => $row['id_theme'],
  541. 'override_theme' => !empty($row['override_theme']),
  542. 'profile' => $row['id_profile'],
  543. 'redirect' => $row['redirect'],
  544. 'posts_count' => empty($row['count_posts']),
  545. 'cur_topic_approved' => empty($topic) || $row['approved'],
  546. 'cur_topic_starter' => empty($topic) ? 0 : $row['id_member_started'],
  547. );
  548. // Load the membergroups allowed, and check permissions.
  549. $board_info['groups'] = $row['member_groups'] == '' ? array() : explode(',', $row['member_groups']);
  550. do
  551. {
  552. if (!empty($row['id_moderator']))
  553. $board_info['moderators'][$row['id_moderator']] = array(
  554. 'id' => $row['id_moderator'],
  555. 'name' => $row['real_name'],
  556. 'href' => $scripturl . '?action=profile;u=' . $row['id_moderator'],
  557. 'link' => '<a href="' . $scripturl . '?action=profile;u=' . $row['id_moderator'] . '">' . $row['real_name'] . '</a>'
  558. );
  559. }
  560. while ($row = $smcFunc['db_fetch_assoc']($request));
  561. // If the board only contains unapproved posts and the user isn't an approver then they can't see any topics.
  562. // If that is the case do an additional check to see if they have any topics waiting to be approved.
  563. if ($board_info['num_topics'] == 0 && $modSettings['postmod_active'] && !allowedTo('approve_posts'))
  564. {
  565. // Free the previous result
  566. $smcFunc['db_free_result']($request);
  567. // @todo why is this using id_topic?
  568. // @todo Can this get cached?
  569. $request = $smcFunc['db_query']('', '
  570. SELECT COUNT(id_topic)
  571. FROM {db_prefix}topics
  572. WHERE id_member_started={int:id_member}
  573. AND approved = {int:unapproved}
  574. AND id_board = {int:board}',
  575. array(
  576. 'id_member' => $user_info['id'],
  577. 'unapproved' => 0,
  578. 'board' => $board,
  579. )
  580. );
  581. list ($board_info['unapproved_user_topics']) = $smcFunc['db_fetch_row']($request);
  582. }
  583. if (!empty($modSettings['cache_enable']) && (empty($topic) || $modSettings['cache_enable'] >= 3))
  584. {
  585. // @todo SLOW?
  586. if (!empty($topic))
  587. cache_put_data('topic_board-' . $topic, $board_info, 120);
  588. cache_put_data('board-' . $board, $board_info, 120);
  589. }
  590. }
  591. else
  592. {
  593. // Otherwise the topic is invalid, there are no moderators, etc.
  594. $board_info = array(
  595. 'moderators' => array(),
  596. 'error' => 'exist'
  597. );
  598. $topic = null;
  599. $board = 0;
  600. }
  601. $smcFunc['db_free_result']($request);
  602. }
  603. if (!empty($topic))
  604. $_GET['board'] = (int) $board;
  605. if (!empty($board))
  606. {
  607. // Now check if the user is a moderator.
  608. $user_info['is_mod'] = isset($board_info['moderators'][$user_info['id']]);
  609. if (count(array_intersect($user_info['groups'], $board_info['groups'])) == 0 && !$user_info['is_admin'])
  610. $board_info['error'] = 'access';
  611. // Build up the linktree.
  612. $context['linktree'] = array_merge(
  613. $context['linktree'],
  614. array(array(
  615. 'url' => $scripturl . '#c' . $board_info['cat']['id'],
  616. 'name' => $board_info['cat']['name']
  617. )),
  618. array_reverse($board_info['parent_boards']),
  619. array(array(
  620. 'url' => $scripturl . '?board=' . $board . '.0',
  621. 'name' => $board_info['name']
  622. ))
  623. );
  624. }
  625. // Set the template contextual information.
  626. $context['user']['is_mod'] = &$user_info['is_mod'];
  627. $context['current_topic'] = $topic;
  628. $context['current_board'] = $board;
  629. // Hacker... you can't see this topic, I'll tell you that. (but moderators can!)
  630. if (!empty($board_info['error']) && ($board_info['error'] != 'access' || !$user_info['is_mod']))
  631. {
  632. // The permissions and theme need loading, just to make sure everything goes smoothly.
  633. loadPermissions();
  634. loadTheme();
  635. $_GET['board'] = '';
  636. $_GET['topic'] = '';
  637. // The linktree should not give the game away mate!
  638. $context['linktree'] = array(
  639. array(
  640. 'url' => $scripturl,
  641. 'name' => $context['forum_name_html_safe']
  642. )
  643. );
  644. // If it's a prefetching agent or we're requesting an attachment.
  645. if ((isset($_SERVER['HTTP_X_MOZ']) && $_SERVER['HTTP_X_MOZ'] == 'prefetch') || (!empty($_REQUEST['action']) && $_REQUEST['action'] === 'dlattach'))
  646. {
  647. ob_end_clean();
  648. header('HTTP/1.1 403 Forbidden');
  649. die;
  650. }
  651. elseif ($user_info['is_guest'])
  652. {
  653. loadLanguage('Errors');
  654. is_not_guest($txt['topic_gone']);
  655. }
  656. else
  657. fatal_lang_error('topic_gone', false);
  658. }
  659. if ($user_info['is_mod'])
  660. $user_info['groups'][] = 3;
  661. }
  662. /**
  663. * Load this user's permissions.
  664. *
  665. */
  666. function loadPermissions()
  667. {
  668. global $user_info, $board, $board_info, $modSettings, $smcFunc, $sourcedir;
  669. if ($user_info['is_admin'])
  670. {
  671. banPermissions();
  672. return;
  673. }
  674. if (!empty($modSettings['cache_enable']))
  675. {
  676. $cache_groups = $user_info['groups'];
  677. asort($cache_groups);
  678. $cache_groups = implode(',', $cache_groups);
  679. // If it's a spider then cache it different.
  680. if ($user_info['possibly_robot'])
  681. $cache_groups .= '-spider';
  682. if ($modSettings['cache_enable'] >= 2 && !empty($board) && ($temp = cache_get_data('permissions:' . $cache_groups . ':' . $board, 240)) != null && time() - 240 > $modSettings['settings_updated'])
  683. {
  684. list ($user_info['permissions']) = $temp;
  685. banPermissions();
  686. return;
  687. }
  688. elseif (($temp = cache_get_data('permissions:' . $cache_groups, 240)) != null && time() - 240 > $modSettings['settings_updated'])
  689. list ($user_info['permissions'], $removals) = $temp;
  690. }
  691. // If it is detected as a robot, and we are restricting permissions as a special group - then implement this.
  692. $spider_restrict = $user_info['possibly_robot'] && !empty($modSettings['spider_group']) ? ' OR (id_group = {int:spider_group} AND add_deny = 0)' : '';
  693. if (empty($user_info['permissions']))
  694. {
  695. // Get the general permissions.
  696. $request = $smcFunc['db_query']('', '
  697. SELECT permission, add_deny
  698. FROM {db_prefix}permissions
  699. WHERE id_group IN ({array_int:member_groups})
  700. ' . $spider_restrict,
  701. array(
  702. 'member_groups' => $user_info['groups'],
  703. 'spider_group' => !empty($modSettings['spider_group']) ? $modSettings['spider_group'] : 0,
  704. )
  705. );
  706. $removals = array();
  707. while ($row = $smcFunc['db_fetch_assoc']($request))
  708. {
  709. if (empty($row['add_deny']))
  710. $removals[] = $row['permission'];
  711. else
  712. $user_info['permissions'][] = $row['permission'];
  713. }
  714. $smcFunc['db_free_result']($request);
  715. if (isset($cache_groups))
  716. cache_put_data('permissions:' . $cache_groups, array($user_info['permissions'], $removals), 240);
  717. }
  718. // Get the board permissions.
  719. if (!empty($board))
  720. {
  721. // Make sure the board (if any) has been loaded by loadBoard().
  722. if (!isset($board_info['profile']))
  723. fatal_lang_error('no_board');
  724. $request = $smcFunc['db_query']('', '
  725. SELECT permission, add_deny
  726. FROM {db_prefix}board_permissions
  727. WHERE (id_group IN ({array_int:member_groups})
  728. ' . $spider_restrict . ')
  729. AND id_profile = {int:id_profile}',
  730. array(
  731. 'member_groups' => $user_info['groups'],
  732. 'id_profile' => $board_info['profile'],
  733. 'spider_group' => !empty($modSettings['spider_group']) ? $modSettings['spider_group'] : 0,
  734. )
  735. );
  736. while ($row = $smcFunc['db_fetch_assoc']($request))
  737. {
  738. if (empty($row['add_deny']))
  739. $removals[] = $row['permission'];
  740. else
  741. $user_info['permissions'][] = $row['permission'];
  742. }
  743. $smcFunc['db_free_result']($request);
  744. }
  745. // Remove all the permissions they shouldn't have ;).
  746. if (!empty($modSettings['permission_enable_deny']))
  747. $user_info['permissions'] = array_diff($user_info['permissions'], $removals);
  748. if (isset($cache_groups) && !empty($board) && $modSettings['cache_enable'] >= 2)
  749. cache_put_data('permissions:' . $cache_groups . ':' . $board, array($user_info['permissions'], null), 240);
  750. // Banned? Watch, don't touch..
  751. banPermissions();
  752. // Load the mod cache so we can know what additional boards they should see, but no sense in doing it for guests
  753. if (!$user_info['is_guest'])
  754. {
  755. if (!isset($_SESSION['mc']) || $_SESSION['mc']['time'] <= $modSettings['settings_updated'])
  756. {
  757. require_once($sourcedir . '/Subs-Auth.php');
  758. rebuildModCache();
  759. }
  760. else
  761. $user_info['mod_cache'] = $_SESSION['mc'];
  762. }
  763. }
  764. /**
  765. * Loads an array of users' data by ID or member_name.
  766. *
  767. * @param mixed $users An array of users by id or name
  768. * @param bool $is_name = false $users is by name or by id
  769. * @param string $set = 'normal' What kind of data to load (normal, profile, minimal)
  770. * @return array|bool The ids of the members loaded or false
  771. */
  772. function loadMemberData($users, $is_name = false, $set = 'normal')
  773. {
  774. global $user_profile, $modSettings, $board_info, $smcFunc;
  775. // Can't just look for no users :P.
  776. if (empty($users))
  777. return false;
  778. // Make sure it's an array.
  779. $users = !is_array($users) ? array($users) : array_unique($users);
  780. $loaded_ids = array();
  781. if (!$is_name && !empty($modSettings['cache_enable']) && $modSettings['cache_enable'] >= 3)
  782. {
  783. $users = array_values($users);
  784. for ($i = 0, $n = count($users); $i < $n; $i++)
  785. {
  786. $data = cache_get_data('member_data-' . $set . '-' . $users[$i], 240);
  787. if ($data == null)
  788. continue;
  789. $loaded_ids[] = $data['id_member'];
  790. $user_profile[$data['id_member']] = $data;
  791. unset($users[$i]);
  792. }
  793. }
  794. if ($set == 'normal')
  795. {
  796. $select_columns = '
  797. IFNULL(lo.log_time, 0) AS is_online, IFNULL(a.id_attach, 0) AS id_attach, a.filename, a.attachment_type,
  798. mem.signature, mem.personal_text, mem.location, mem.gender, mem.avatar, mem.id_member, mem.member_name,
  799. mem.real_name, mem.email_address, mem.hide_email, mem.date_registered, mem.website_title, mem.website_url,
  800. mem.birthdate, mem.member_ip, mem.member_ip2, mem.icq, mem.aim, mem.yim, mem.msn, mem.posts, mem.last_login,
  801. mem.karma_good, mem.id_post_group, mem.karma_bad, mem.lngfile, mem.id_group, mem.time_offset, mem.show_online,
  802. mem.buddy_list, mg.online_color AS member_group_color, IFNULL(mg.group_name, {string:blank_string}) AS member_group,
  803. pg.online_color AS post_group_color, IFNULL(pg.group_name, {string:blank_string}) AS post_group, mem.is_activated, mem.warning,
  804. CASE WHEN mem.id_group = 0 OR mg.stars = {string:blank_string} THEN pg.stars ELSE mg.stars END AS stars' . (!empty($modSettings['titlesEnable']) ? ',
  805. mem.usertitle' : '');
  806. $select_tables = '
  807. LEFT JOIN {db_prefix}log_online AS lo ON (lo.id_member = mem.id_member)
  808. LEFT JOIN {db_prefix}attachments AS a ON (a.id_member = mem.id_member)
  809. LEFT JOIN {db_prefix}membergroups AS pg ON (pg.id_group = mem.id_post_group)
  810. LEFT JOIN {db_prefix}membergroups AS mg ON (mg.id_group = mem.id_group)';
  811. }
  812. elseif ($set == 'profile')
  813. {
  814. $select_columns = '
  815. IFNULL(lo.log_time, 0) AS is_online, IFNULL(a.id_attach, 0) AS id_attach, a.filename, a.attachment_type,
  816. mem.signature, mem.personal_text, mem.location, mem.gender, mem.avatar, mem.id_member, mem.member_name,
  817. mem.real_name, mem.email_address, mem.hide_email, mem.date_registered, mem.website_title, mem.website_url,
  818. mem.openid_uri, mem.birthdate, mem.icq, mem.aim, mem.yim, mem.msn, mem.posts, mem.last_login, mem.karma_good,
  819. mem.karma_bad, mem.member_ip, mem.member_ip2, mem.lngfile, mem.id_group, mem.id_theme, mem.buddy_list,
  820. mem.pm_ignore_list, mem.pm_email_notify, mem.pm_receive_from, mem.time_offset' . (!empty($modSettings['titlesEnable']) ? ', mem.usertitle' : '') . ',
  821. mem.time_format, mem.secret_question, mem.is_activated, mem.additional_groups, mem.smiley_set, mem.show_online,
  822. mem.total_time_logged_in, mem.id_post_group, mem.notify_announcements, mem.notify_regularity, mem.notify_send_body,
  823. mem.notify_types, lo.url, mg.online_color AS member_group_color, IFNULL(mg.group_name, {string:blank_string}) AS member_group,
  824. pg.online_color AS post_group_color, IFNULL(pg.group_name, {string:blank_string}) AS post_group, mem.ignore_boards, mem.warning,
  825. CASE WHEN mem.id_group = 0 OR mg.stars = {string:blank_string} THEN pg.stars ELSE mg.stars END AS stars, mem.password_salt, mem.pm_prefs';
  826. $select_tables = '
  827. LEFT JOIN {db_prefix}log_online AS lo ON (lo.id_member = mem.id_member)
  828. LEFT JOIN {db_prefix}attachments AS a ON (a.id_member = mem.id_member)
  829. LEFT JOIN {db_prefix}membergroups AS pg ON (pg.id_group = mem.id_post_group)
  830. LEFT JOIN {db_prefix}membergroups AS mg ON (mg.id_group = mem.id_group)';
  831. }
  832. elseif ($set == 'minimal')
  833. {
  834. $select_columns = '
  835. mem.id_member, mem.member_name, mem.real_name, mem.email_address, mem.hide_email, mem.date_registered,
  836. mem.posts, mem.last_login, mem.member_ip, mem.member_ip2, mem.lngfile, mem.id_group';
  837. $select_tables = '';
  838. }
  839. else
  840. trigger_error('loadMemberData(): Invalid member data set \'' . $set . '\'', E_USER_WARNING);
  841. if (!empty($users))
  842. {
  843. // Load the member's data.
  844. $request = $smcFunc['db_query']('', '
  845. SELECT' . $select_columns . '
  846. FROM {db_prefix}members AS mem' . $select_tables . '
  847. WHERE mem.' . ($is_name ? 'member_name' : 'id_member') . (count($users) == 1 ? ' = {' . ($is_name ? 'string' : 'int') . ':users}' : ' IN ({' . ($is_name ? 'array_string' : 'array_int') . ':users})'),
  848. array(
  849. 'blank_string' => '',
  850. 'users' => count($users) == 1 ? current($users) : $users,
  851. )
  852. );
  853. $new_loaded_ids = array();
  854. while ($row = $smcFunc['db_fetch_assoc']($request))
  855. {
  856. $new_loaded_ids[] = $row['id_member'];
  857. $loaded_ids[] = $row['id_member'];
  858. $row['options'] = array();
  859. $user_profile[$row['id_member']] = $row;
  860. }
  861. $smcFunc['db_free_result']($request);
  862. }
  863. if (!empty($new_loaded_ids) && $set !== 'minimal')
  864. {
  865. $request = $smcFunc['db_query']('', '
  866. SELECT *
  867. FROM {db_prefix}themes
  868. WHERE id_member' . (count($new_loaded_ids) == 1 ? ' = {int:loaded_ids}' : ' IN ({array_int:loaded_ids})'),
  869. array(
  870. 'loaded_ids' => count($new_loaded_ids) == 1 ? $new_loaded_ids[0] : $new_loaded_ids,
  871. )
  872. );
  873. while ($row = $smcFunc['db_fetch_assoc']($request))
  874. $user_profile[$row['id_member']]['options'][$row['variable']] = $row['value'];
  875. $smcFunc['db_free_result']($request);
  876. }
  877. if (!empty($new_loaded_ids) && !empty($modSettings['cache_enable']) && $modSettings['cache_enable'] >= 3)
  878. {
  879. for ($i = 0, $n = count($new_loaded_ids); $i < $n; $i++)
  880. cache_put_data('member_data-' . $set . '-' . $new_loaded_ids[$i], $user_profile[$new_loaded_ids[$i]], 240);
  881. }
  882. // Are we loading any moderators? If so, fix their group data...
  883. if (!empty($loaded_ids) && !empty($board_info['moderators']) && $set === 'normal' && count($temp_mods = array_intersect($loaded_ids, array_keys($board_info['moderators']))) !== 0)
  884. {
  885. if (($row = cache_get_data('moderator_group_info', 480)) == null)
  886. {
  887. $request = $smcFunc['db_query']('', '
  888. SELECT group_name AS member_group, online_color AS member_group_color, stars
  889. FROM {db_prefix}membergroups
  890. WHERE id_group = {int:moderator_group}
  891. LIMIT 1',
  892. array(
  893. 'moderator_group' => 3,
  894. )
  895. );
  896. $row = $smcFunc['db_fetch_assoc']($request);
  897. $smcFunc['db_free_result']($request);
  898. cache_put_data('moderator_group_info', $row, 480);
  899. }
  900. foreach ($temp_mods as $id)
  901. {
  902. // By popular demand, don't show admins or global moderators as moderators.
  903. if ($user_profile[$id]['id_group'] != 1 && $user_profile[$id]['id_group'] != 2)
  904. $user_profile[$id]['member_group'] = $row['member_group'];
  905. // If the Moderator group has no color or stars, but their group does... don't overwrite.
  906. if (!empty($row['stars']))
  907. $user_profile[$id]['stars'] = $row['stars'];
  908. if (!empty($row['member_group_color']))
  909. $user_profile[$id]['member_group_color'] = $row['member_group_color'];
  910. }
  911. }
  912. return empty($loaded_ids) ? false : $loaded_ids;
  913. }
  914. /**
  915. * Loads the user's basic values... meant for template/theme usage.
  916. *
  917. * @param int $user
  918. * @param bool $display_custom_fields = false
  919. * @return bool
  920. */
  921. function loadMemberContext($user, $display_custom_fields = false)
  922. {
  923. global $memberContext, $user_profile, $txt, $scripturl, $user_info;
  924. global $context, $modSettings, $board_info, $settings;
  925. global $smcFunc;
  926. static $dataLoaded = array();
  927. // If this person's data is already loaded, skip it.
  928. if (isset($dataLoaded[$user]))
  929. return true;
  930. // We can't load guests or members not loaded by loadMemberData()!
  931. if ($user == 0)
  932. return false;
  933. if (!isset($user_profile[$user]))
  934. {
  935. trigger_error('loadMemberContext(): member id ' . $user . ' not previously loaded by loadMemberData()', E_USER_WARNING);
  936. return false;
  937. }
  938. // Well, it's loaded now anyhow.
  939. $dataLoaded[$user] = true;
  940. $profile = $user_profile[$user];
  941. // Censor everything.
  942. censorText($profile['signature']);
  943. censorText($profile['personal_text']);
  944. censorText($profile['location']);
  945. // Set things up to be used before hand.
  946. $gendertxt = $profile['gender'] == 2 ? $txt['female'] : ($profile['gender'] == 1 ? $txt['male'] : '');
  947. $profile['signature'] = str_replace(array("\n", "\r"), array('<br />', ''), $profile['signature']);
  948. $profile['signature'] = parse_bbc($profile['signature'], true, 'sig' . $profile['id_member']);
  949. $profile['is_online'] = (!empty($profile['show_online']) || allowedTo('moderate_forum')) && $profile['is_online'] > 0;
  950. $profile['stars'] = empty($profile['stars']) ? array('', '') : explode('#', $profile['stars']);
  951. // Setup the buddy status here (One whole in_array call saved :P)
  952. $profile['buddy'] = in_array($profile['id_member'], $user_info['buddies']);
  953. $buddy_list = !empty($profile['buddy_list']) ? explode(',', $profile['buddy_list']) : array();
  954. // If we're always html resizing, assume it's too large.
  955. if ($modSettings['avatar_action_too_large'] == 'option_html_resize' || $modSettings['avatar_action_too_large'] == 'option_js_resize')
  956. {
  957. $avatar_width = !empty($modSettings['avatar_max_width_external']) ? ' width="' . $modSettings['avatar_max_width_external'] . '"' : '';
  958. $avatar_height = !empty($modSettings['avatar_max_height_external']) ? ' height="' . $modSettings['avatar_max_height_external'] . '"' : '';
  959. }
  960. else
  961. {
  962. $avatar_width = '';
  963. $avatar_height = '';
  964. }
  965. // What a monstrous array...
  966. $memberContext[$user] = array(
  967. 'username' => $profile['member_name'],
  968. 'name' => $profile['real_name'],
  969. 'id' => $profile['id_member'],
  970. 'is_buddy' => $profile['buddy'],
  971. 'is_reverse_buddy' => in_array($user_info['id'], $buddy_list),
  972. 'buddies' => $buddy_list,
  973. 'title' => !empty($modSettings['titlesEnable']) ? $profile['usertitle'] : '',
  974. 'href' => $scripturl . '?action=profile;u=' . $profile['id_member'],
  975. 'link' => '<a href="' . $scripturl . '?action=profile;u=' . $profile['id_member'] . '" title="' . $txt['profile_of'] . ' ' . $profile['real_name'] . '">' . $profile['real_name'] . '</a>',
  976. 'email' => $profile['email_address'],
  977. 'show_email' => showEmailAddress(!empty($profile['hide_email']), $profile['id_member']),
  978. 'registered' => empty($profile['date_registered']) ? $txt['not_applicable'] : timeformat($profile['date_registered']),
  979. 'registered_timestamp' => empty($profile['date_registered']) ? 0 : forum_time(true, $profile['date_registered']),
  980. 'blurb' => $profile['personal_text'],
  981. 'gender' => array(
  982. 'name' => $gendertxt,
  983. 'image' => !empty($profile['gender']) ? '<img class="gender" src="' . $settings['images_url'] . '/' . ($profile['gender'] == 1 ? 'Male' : 'Female') . '.png" alt="' . $gendertxt . '" />' : ''
  984. ),
  985. 'website' => array(
  986. 'title' => $profile['website_title'],
  987. 'url' => $profile['website_url'],
  988. ),
  989. 'birth_date' => empty($profile['birthdate']) || $profile['birthdate'] === '0001-01-01' ? '0000-00-00' : (substr($profile['birthdate'], 0, 4) === '0004' ? '0000' . substr($profile['birthdate'], 4) : $profile['birthdate']),
  990. 'signature' => $profile['signature'],
  991. 'location' => $profile['location'],
  992. 'icq' => $profile['icq'] != '' && (empty($modSettings['guest_hideContacts']) || !$user_info['is_guest']) ? array(
  993. 'name' => $profile['icq'],
  994. 'href' => 'http://www.icq.com/whitepages/about_me.php?uin=' . $profile['icq'],
  995. 'link' => '<a class="icq new_win" href="http://www.icq.com/whitepages/about_me.php?uin=' . $profile['icq'] . '" target="_blank" title="' . $txt['icq_title'] . ' - ' . $profile['icq'] . '"><img src="http://status.icq.com/online.png?img=5&amp;icq=' . $profile['icq'] . '" alt="' . $txt['icq_title'] . ' - ' . $profile['icq'] . '" width="18" height="18" /></a>',
  996. 'link_text' => '<a class="icq extern" href="http://www.icq.com/whitepages/about_me.php?uin=' . $profile['icq'] . '" title="' . $txt['icq_title'] . ' - ' . $profile['icq'] . '">' . $profile['icq'] . '</a>',
  997. ) : array('name' => '', 'add' => '', 'href' => '', 'link' => '', 'link_text' => ''),
  998. 'aim' => $profile['aim'] != '' && (empty($modSettings['guest_hideContacts']) || !$user_info['is_guest']) ? array(
  999. 'name' => $profile['aim'],
  1000. 'href' => 'aim:goim?screenname=' . urlencode(strtr($profile['aim'], array(' ' => '%20'))) . '&amp;message=' . $txt['aim_default_message'],
  1001. 'link' => '<a class="aim" href="aim:goim?screenname=' . urlencode(strtr($profile['aim'], array(' ' => '%20'))) . '&amp;message=' . $txt['aim_default_message'] . '" title="' . $txt['aim_title'] . ' - ' . $profile['aim'] . '"><img src="' . $settings['images_url'] . '/aim.png" alt="' . $txt['aim_title'] . ' - ' . $profile['aim'] . '" /></a>',
  1002. 'link_text' => '<a class="aim" href="aim:goim?screenname=' . urlencode(strtr($profile['aim'], array(' ' => '%20'))) . '&amp;message=' . $txt['aim_default_message'] . '" title="' . $txt['aim_title'] . ' - ' . $profile['aim'] . '">' . $profile['aim'] . '</a>'
  1003. ) : array('name' => '', 'href' => '', 'link' => '', 'link_text' => ''),
  1004. 'yim' => $profile['yim'] != '' && (empty($modSettings['guest_hideContacts']) || !$user_info['is_guest']) ? array(
  1005. 'name' => $profile['yim'],
  1006. 'href' => 'http://edit.yahoo.com/config/send_webmesg?.target=' . urlencode($profile['yim']),
  1007. 'link' => '<a class="yim" href="http://edit.yahoo.com/config/send_webmesg?.target=' . urlencode($profile['yim']) . '" title="' . $txt['yim_title'] . ' - ' . $profile['yim'] . '"><img src="http://opi.yahoo.com/online?u=' . urlencode($profile['yim']) . '&amp;m=g&amp;t=0" alt="' . $txt['yim_title'] . ' - ' . $profile['yim'] . '" /></a>',
  1008. 'link_text' => '<a class="yim" href="http://edit.yahoo.com/config/send_webmesg?.target=' . urlencode($profile['yim']) . '" title="' . $txt['yim_title'] . ' - ' . $profile['yim'] . '">' . $profile['yim'] . '</a>'
  1009. ) : array('name' => '', 'href' => '', 'link' => '', 'link_text' => ''),
  1010. 'msn' => $profile['msn'] !='' && (empty($modSettings['guest_hideContacts']) || !$user_info['is_guest']) ? array(
  1011. 'name' => $profile['msn'],
  1012. 'href' => 'http://members.msn.com/' . $profile['msn'],
  1013. 'link' => '<a class="msn new_win" href="http://members.msn.com/' . $profile['msn'] . '" title="' . $txt['msn_title'] . ' - ' . $profile['msn'] . '"><img src="' . $settings['images_url'] . '/msntalk.png" alt="' . $txt['msn_title'] . ' - ' . $profile['msn'] . '" /></a>',
  1014. 'link_text' => '<a class="msn new_win" href="http://members.msn.com/' . $profile['msn'] . '" title="' . $txt['msn_title'] . ' - ' . $profile['msn'] . '">' . $profile['msn'] . '</a>'
  1015. ) : array('name' => '', 'href' => '', 'link' => '', 'link_text' => ''),
  1016. 'real_posts' => $profile['posts'],
  1017. 'posts' => $profile['posts'] > 500000 ? $txt['geek'] : comma_format($profile['posts']),
  1018. 'avatar' => array(
  1019. 'name' => $profile['avatar'],
  1020. 'image' => $profile['avatar'] == '' ? ($profile['id_attach'] > 0 ? '<img class="avatar" src="' . (empty($profile['attachment_type']) ? $scripturl . '?action=dlattach;attach=' . $profile['id_attach'] . ';type=avatar' : $modSettings['custom_avatar_url'] . '/' . $profile['filename']) . '" alt="" />' : '') : (stristr($profile['avatar'], 'http://') ? '<img class="avatar" src="' . $profile['avatar'] . '"' . $avatar_width . $avatar_height . ' alt="" />' : '<img class="avatar" src="' . $modSettings['avatar_url'] . '/' . htmlspecialchars($profile['avatar']) . '" alt="" />'),
  1021. 'href' => $profile['avatar'] == '' ? ($profile['id_attach'] > 0 ? (empty($profile['attachment_type']) ? $scripturl . '?action=dlattach;attach=' . $profile['id_attach'] . ';type=avatar' : $modSettings['custom_avatar_url'] . '/' . $profile['filename']) : '') : (stristr($profile['avatar'], 'http://') ? $profile['avatar'] : $modSettings['avatar_url'] . '/' . $profile['avatar']),
  1022. 'url' => $profile['avatar'] == '' ? '' : (stristr($profile['avatar'], 'http://') ? $profile['avatar'] : $modSettings['avatar_url'] . '/' . $profile['avatar'])
  1023. ),
  1024. 'last_login' => empty($profile['last_login']) ? $txt['never'] : timeformat($profile['last_login']),
  1025. 'last_login_timestamp' => empty($profile['last_login']) ? 0 : forum_time(0, $profile['last_login']),
  1026. 'karma' => array(
  1027. 'good' => $profile['karma_good'],
  1028. 'bad' => $profile['karma_bad'],
  1029. 'allow' => !$user_info['is_guest'] && !empty($modSettings['karmaMode']) && $user_info['id'] != $user && allowedTo('karma_edit') &&
  1030. ($user_info['posts'] >= $modSettings['karmaMinPosts'] || $user_info['is_admin']),
  1031. ),
  1032. 'ip' => htmlspecialchars($profile['member_ip']),
  1033. 'ip2' => htmlspecialchars($profile['member_ip2']),
  1034. 'online' => array(
  1035. 'is_online' => $profile['is_online'],
  1036. 'text' => $txt[$profile['is_online'] ? 'online' : 'offline'],
  1037. 'href' => $scripturl . '?action=pm;sa=send;u=' . $profile['id_member'],
  1038. 'link' => '<a href="' . $scripturl . '?action=pm;sa=send;u=' . $profile['id_member'] . '">' . $txt[$profile['is_online'] ? 'online' : 'offline'] . '</a>',
  1039. 'image_href' => $settings['images_url'] . '/' . ($profile['buddy'] ? 'buddy_' : '') . ($profile['is_online'] ? 'useron' : 'useroff') . '.png',
  1040. 'label' => $txt[$profile['is_online'] ? 'online' : 'offline']
  1041. ),
  1042. 'language' => $smcFunc['ucwords'](strtr($profile['lngfile'], array('_' => ' ', '-utf8' => ''))),
  1043. 'is_activated' => isset($profile['is_activated']) ? $profile['is_activated'] : 1,
  1044. 'is_banned' => isset($profile['is_activated']) ? $profile['is_activated'] >= 10 : 0,
  1045. 'options' => $profile['options'],
  1046. 'is_guest' => false,
  1047. 'group' => $profile['member_group'],
  1048. 'group_color' => $profile['member_group_color'],
  1049. 'group_id' => $profile['id_group'],
  1050. 'post_group' => $profile['post_group'],
  1051. 'post_group_color' => $profile['post_group_color'],
  1052. 'group_stars' => str_repeat('<img src="' . str_replace('$language', $context['user']['language'], isset($profile['stars'][1]) ? $settings['images_url'] . '/' . $profile['stars'][1] : '') . '" alt="*" />', empty($profile['stars'][0]) || empty($profile['stars'][1]) ? 0 : $profile['stars'][0]),
  1053. 'warning' => $profile['warning'],
  1054. 'warning_status' => !empty($modSettings['warning_mute']) && $modSettings['warning_mute'] <= $profile['warning'] ? 'mute' : (!empty($modSettings['warning_moderate']) && $modSettings['warning_moderate'] <= $profile['warning'] ? 'moderate' : (!empty($modSettings['warning_watch']) && $modSettings['warning_watch'] <= $profile['warning'] ? 'watch' : (''))),
  1055. 'local_time' => timeformat(time() + ($profile['time_offset'] - $user_info['time_offset']) * 3600, false),
  1056. );
  1057. // First do a quick run through to make sure there is something to be shown.
  1058. $memberContext[$user]['has_messenger'] = false;
  1059. foreach (array('icq', 'msn', 'aim', 'yim') as $messenger)
  1060. {
  1061. if (!isset($context['disabled_fields'][$messenger]) && !empty($memberContext[$user][$messenger]['link']))
  1062. {
  1063. $memberContext[$user]['has_messenger'] = true;
  1064. break;
  1065. }
  1066. }
  1067. // Are we also loading the members custom fields into context?
  1068. if ($display_custom_fields && !empty($modSettings['displayFields']))
  1069. {
  1070. $memberContext[$user]['custom_fields'] = array();
  1071. if (!isset($context['display_fields']))
  1072. $context['display_fields'] = unserialize($modSettings['displayFields']);
  1073. foreach ($context['display_fields'] as $custom)
  1074. {
  1075. if (!isset($custom['title']) || trim($custom['title']) == '' || empty($profile['options'][$custom['colname']]))
  1076. continue;
  1077. $value = $profile['options'][$custom['colname']];
  1078. // BBC?
  1079. if ($custom['bbc'])
  1080. $value = parse_bbc($value);
  1081. // ... or checkbox?
  1082. elseif (isset($custom['type']) && $custom['type'] == 'check')
  1083. $value = $value ? $txt['yes'] : $txt['no'];
  1084. // Enclosing the user input within some other text?
  1085. if (!empty($custom['enclose']))
  1086. $value = strtr($custom['enclose'], array(
  1087. '{SCRIPTURL}' => $scripturl,
  1088. '{IMAGES_URL}' => $settings['images_url'],
  1089. '{DEFAULT_IMAGES_URL}' => $settings['default_images_url'],
  1090. '{INPUT}' => $value,
  1091. ));
  1092. $memberContext[$user]['custom_fields'][] = array(
  1093. 'title' => $custom['title'],
  1094. 'colname' => $custom['colname'],
  1095. 'value' => $value,
  1096. 'placement' => !empty($custom['placement']) ? $custom['placement'] : 0,
  1097. );
  1098. }
  1099. }
  1100. call_integration_hook('integrate_member_context', array(&$user, $display_custom_fields));
  1101. return true;
  1102. }
  1103. /**
  1104. * Loads information about what browser the user is viewing with and places it in $context
  1105. *
  1106. */
  1107. function detectBrowser()
  1108. {
  1109. global $context, $user_info;
  1110. // The following determines the user agent (browser) as best it can.
  1111. $context['browser'] = array(
  1112. 'is_opera' => strpos($_SERVER['HTTP_USER_AGENT'], 'Opera') !== false,
  1113. 'is_webkit' => strpos($_SERVER['HTTP_USER_AGENT'], 'AppleWebKit') !== false,
  1114. 'is_firefox' => preg_match('~(?:Firefox|Ice[wW]easel|IceCat|Shiretoko|Minefield)/~', $_SERVER['HTTP_USER_AGENT']) === 1,
  1115. 'is_web_tv' => strpos($_SERVER['HTTP_USER_AGENT'], 'WebTV') !== false,
  1116. 'is_konqueror' => strpos($_SERVER['HTTP_USER_AGENT'], 'Konqueror') !== false,
  1117. );
  1118. // <Insert corny Geico gecko comment here>.
  1119. $context['browser']['is_gecko'] = strpos($_SERVER['HTTP_USER_AGENT'], 'Gecko') !== false && !$context['browser']['is_webkit'] && !$context['browser']['is_konqueror'];
  1120. // I'm IE, Yes I'm the real IE; All you other IEs are just imitating.
  1121. $context['browser']['is_ie'] = !$context['browser']['is_opera'] && !$context['browser']['is_gecko'] && !$context['browser']['is_web_tv'] && preg_match('~MSIE \d+~', $_SERVER['HTTP_USER_AGENT']) === 1;
  1122. // Detect Safari/Chrome/iP[ao]d/iPhone from webkit.
  1123. if ($context['browser']['is_webkit'])
  1124. {
  1125. $context['browser'] += array(
  1126. 'is_chrome' => $context['browser']['is_webkit'] && strpos($_SERVER['HTTP_USER_AGENT'], 'Chrome') !== false,
  1127. 'is_iphone' => strpos($_SERVER['HTTP_USER_AGENT'], 'iPhone') !== false || strpos($_SERVER['HTTP_USER_AGENT'], 'iPod') !== false,
  1128. 'is_blackberry' => strpos($_SERVER['HTTP_USER_AGENT'], 'BlackBerry') !== false || strpos($_SERVER['HTTP_USER_AGENT'], 'PlayBook') !== false,
  1129. 'is_android' => strpos($_SERVER['HTTP_USER_AGENT'], 'Android') !== false,
  1130. );
  1131. $context['browser']['is_safari'] = !$context['browser']['is_chrome'] && strpos($_SERVER['HTTP_USER_AGENT'], 'Safari') !== false;
  1132. $context['browser']['is_ipad'] = $context['browser']['is_iphone'] && strpos($_SERVER['HTTP_USER_AGENT'], 'iPad') !== false;
  1133. }
  1134. // More Opera checks if we are opera.
  1135. if ($context['browser']['is_opera'])
  1136. $context['browser'] += array(
  1137. 'is_opera6' => strpos($_SERVER['HTTP_USER_AGENT'], 'Opera 6') !== false,
  1138. 'is_opera7' => strpos($_SERVER['HTTP_USER_AGENT'], 'Opera 7') !== false || strpos($_SERVER['HTTP_USER_AGENT'], 'Opera/7') !== false,
  1139. 'is_opera8' => strpos($_SERVER['HTTP_USER_AGENT'], 'Opera 8') !== false || strpos($_SERVER['HTTP_USER_AGENT'], 'Opera/8') !== false,
  1140. 'is_opera9' => preg_match('~Opera[ /]9(?!\\.[89])~', $_SERVER['HTTP_USER_AGENT']) === 1,
  1141. 'is_opera10' => preg_match('~Opera[ /]10\\.~', $_SERVER['HTTP_USER_AGENT']) === 1 || (preg_match('~Opera[ /]9\\.[89]~', $_SERVER['HTTP_USER_AGENT']) === 1 && preg_match('~Version/1[0-9]\\.~', $_SERVER['HTTP_USER_AGENT']) === 1),
  1142. 'is_opera_mobi' => strpos($_SERVER['HTTP_USER_AGENT'], 'Opera Mobi') !== false,
  1143. );
  1144. // Additional firefox checks.
  1145. if ($context['browser']['is_firefox'])
  1146. $context['browser'] += array(
  1147. 'is_firefox1' => preg_match('~(?:Firefox|Ice[wW]easel|IceCat)/1\\.~', $_SERVER['HTTP_USER_AGENT']) === 1,
  1148. 'is_firefox2' => preg_match('~(?:Firefox|Ice[wW]easel|IceCat)/2\\.~', $_SERVER['HTTP_USER_AGENT']) === 1,
  1149. 'is_firefox3' => preg_match('~(?:Firefox|Ice[wW]easel|IceCat|Shiretoko|Minefield)/3\\.~', $_SERVER['HTTP_USER_AGENT']) === 1,
  1150. );
  1151. // Additional IE checks.
  1152. if ($context['browser']['is_ie'])
  1153. {
  1154. $context['browser'] += array(
  1155. 'is_ie9' => strpos($_SERVER['HTTP_USER_AGENT'], 'Trident/5.0') !== false,
  1156. 'is_ie8' => strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE 8') !== false,
  1157. 'is_ie_mobi' => strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE 7') !== false && strpos($_SERVER['HTTP_USER_AGENT'], 'IEMobile/7') !== false,
  1158. 'is_ie5.5' => strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE 5.5') !== false,
  1159. 'is_ie5' => strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE 5.0') !== false,
  1160. 'is_ie4' => strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE 4') !== false && !$context['browser']['is_web_tv'],
  1161. 'is_mac_ie' => strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE 5.') !== false && strpos($_SERVER['HTTP_USER_AGENT'], 'Mac') !== false,
  1162. );
  1163. // Detect IE7 and not IE8/IE9 in combat mode.
  1164. $context['browser']['is_ie7'] = strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE 7') !== false && !($context['browser']['is_ie8'] || $context['browser']['is_ie9']);
  1165. // Before IE8 we need to fix IE... lots!
  1166. $context['browser']['ie_standards_fix'] = ($context['browser']['is_ie8'] || $context['browser']['is_ie9']) ? false : true;
  1167. $context['browser']['is_ie6'] = strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE 6') !== false && !$context['browser']['is_ie8'] && !$context['browser']['is_ie7'];
  1168. }
  1169. $context['browser']['needs_size_fix'] = false;
  1170. if ($context['browser']['is_ie'] || $context['browser']['is_opera'])
  1171. $context['browser']['needs_size_fix'] = (!empty($context['browser']['is_ie5']) || !empty($context['browser']['is_ie5.5']) || !empty($context['browser']['is_ie4']) || !empty($context['browser']['is_opera6'])) && strpos($_SERVER['HTTP_USER_AGENT'], 'Mac') === false;
  1172. // Be you robot or human?
  1173. if ($user_info['possibly_robot'])
  1174. {
  1175. // This isn't meant to be reliable, it's just meant to catch most bots to prevent PHPSESSID from showing up.
  1176. $context['browser']['possibly_robot'] = !empty($user_info['possibly_robot']);
  1177. // Robots shouldn't be logging in or registering. So, they aren't a bot. Better to be wrong than sorry (or people won't be able to log in!), anyway.
  1178. if ((isset($_REQUEST['action']) && in_array($_REQUEST['action'], array('login', 'login2', 'register'))) || !$user_info['is_guest'])
  1179. $context['browser']['possibly_robot'] = false;
  1180. }
  1181. else
  1182. $context['browser']['possibly_robot'] = false;
  1183. // Fill out the rest as needed to support mods that don't use isBrowser
  1184. $context['browser'] += array(
  1185. 'is_opera6' => false,
  1186. 'is_opera7' => false,
  1187. 'is_opera8' => false,
  1188. 'is_opera9' => false,
  1189. 'is_opera10' => false,
  1190. 'is_ie4' => false,
  1191. 'is_mac_ie' => false,
  1192. 'is_firefox1' => false,
  1193. 'is_firefox2' => false,
  1194. 'is_firefox3' => false,
  1195. 'is_iphone' => false,
  1196. 'is_android' => false,
  1197. 'is_chrome' => false,
  1198. 'is_safari' => false,
  1199. 'is_ie8' => false,
  1200. 'is_ie7' => false,
  1201. 'is_ie6' => false,
  1202. 'is_ie5.5' => false,
  1203. 'is_ie5' => false,
  1204. 'ie_standards_fix' => false,
  1205. );
  1206. }
  1207. /**
  1208. * Are we using this browser?
  1209. *
  1210. * Wrapper function for detectBrowser
  1211. * @param $browser: browser we are checking for.
  1212. */
  1213. function isBrowser($browser)
  1214. {
  1215. global $context;
  1216. // @todo REMOVE THIS BEFORE BETA 1 RELEASE.
  1217. if (in_array($browser, array('ie7', 'ie6', 'ie5.5', 'ie5', 'ie5', 'ie4', 'mac_ie', 'firefox1')))
  1218. {
  1219. $line = $file = null;
  1220. foreach (debug_backtrace() as $step)
  1221. {
  1222. // Found it?
  1223. if (strpos($step['function'], 'query') === false && !in_array(substr($step['function'], 0, 7), array('smf_db_', 'preg_re', 'db_erro', 'call_us')) && strpos($step['function'], '__') !== 0)
  1224. {
  1225. $function = '<br />Function: ' . $step['function'];
  1226. break;
  1227. }
  1228. if (isset($step['line']))
  1229. {
  1230. $file = $step['file'];
  1231. $line = $step['line'];
  1232. }
  1233. }
  1234. log_error('Old browser support' . $function, 'debug', $file, $line);
  1235. }
  1236. // Don't know any browser!
  1237. if (empty($context['browser']))
  1238. detectBrowser();
  1239. return !empty($context['browser'][$browser]) || !empty($context['browser']['is_' . $browser]) ? true : false;
  1240. }
  1241. /**
  1242. * Load a theme, by ID.
  1243. *
  1244. * @param int $id_theme = 0
  1245. * @param bool $initialize = true
  1246. */
  1247. function loadTheme($id_theme = 0, $initialize = true)
  1248. {
  1249. global $user_info, $user_settings, $board_info, $sc, $boarddir;
  1250. global $txt, $boardurl, $scripturl, $mbname, $modSettings, $language;
  1251. global $context, $settings, $options, $sourcedir, $ssi_theme, $smcFunc;
  1252. // The theme was specified by parameter.
  1253. if (!empty($id_theme))
  1254. $id_theme = (int) $id_theme;
  1255. // The theme was specified by REQUEST.
  1256. elseif (!empty($_REQUEST['theme']) && (!empty($modSettings['theme_allow']) || allowedTo('admin_forum')))
  1257. {
  1258. $id_theme = (int) $_REQUEST['theme'];
  1259. $_SESSION['id_theme'] = $id_theme;
  1260. }
  1261. // The theme was specified by REQUEST... previously.
  1262. elseif (!empty($_SESSION['id_theme']) && (!empty($modSettings['theme_allow']) || allowedTo('admin_forum')))
  1263. $id_theme = (int) $_SESSION['id_theme'];
  1264. // The theme is just the user's choice. (might use ?board=1;theme=0 to force board theme.)
  1265. elseif (!empty($user_info['theme']) && !isset($_REQUEST['theme']) && (!empty($modSettings['theme_allow']) || allowedTo('admin_forum')))
  1266. $id_theme = $user_info['theme'];
  1267. // The theme was specified by the board.
  1268. elseif (!empty($board_info['theme']))
  1269. $id_theme = $board_info['theme'];
  1270. // The theme is the forum's default.
  1271. else
  1272. $id_theme = $modSettings['theme_guests'];
  1273. // Verify the id_theme... no foul play.
  1274. // Always allow the board specific theme, if they are overriding.
  1275. if (!empty($board_info['theme']) && $board_info['override_theme'])
  1276. $id_theme = $board_info['theme'];
  1277. // If they have specified a particular theme to use with SSI allow it to be used.
  1278. elseif (!empty($ssi_theme) && $id_theme == $ssi_theme)
  1279. $id_theme = (int) $id_theme;
  1280. elseif (!empty($modSettings['knownThemes']) && !allowedTo('admin_forum'))
  1281. {
  1282. $themes = explode(',', $modSettings['knownThemes']);
  1283. if (!in_array($id_theme, $themes))
  1284. $id_theme = $modSettings['theme_guests'];
  1285. else
  1286. $id_theme = (int) $id_theme;
  1287. }
  1288. else
  1289. $id_theme = (int) $id_theme;
  1290. $member = empty($user_info['id']) ? -1 : $user_info['id'];
  1291. if (!empty($modSettings['cache_enable']) && $modSettings['cache_enable'] >= 2 && ($temp = cache_get_data('theme_settings-' . $id_theme . ':' . $member, 60)) != null && time() - 60 > $modSettings['settings_updated'])
  1292. {
  1293. $themeData = $temp;
  1294. $flag = true;
  1295. }
  1296. elseif (($temp = cache_get_data('theme_settings-' . $id_theme, 90)) != null && time() - 60 > $modSettings['settings_updated'])
  1297. $themeData = $temp + array($member => array());
  1298. else
  1299. $themeData = array(-1 => array(), 0 => array(), $member => array());
  1300. if (empty($flag))
  1301. {
  1302. // Load variables from the current or default theme, global or this user's.
  1303. $result = $smcFunc['db_query']('', '
  1304. SELECT variable, value, id_member, id_theme
  1305. FROM {db_prefix}themes
  1306. WHERE id_member' . (empty($themeData[0]) ? ' IN (-1, 0, {int:id_member})' : ' = {int:id_member}') . '
  1307. AND id_theme' . ($id_theme == 1 ? ' = {int:id_theme}' : ' IN ({int:id_theme}, 1)'),
  1308. array(
  1309. 'id_theme' => $id_theme,
  1310. 'id_member' => $member,
  1311. )
  1312. );
  1313. // Pick between $settings and $options depending on whose data it is.
  1314. while ($row = $smcFunc['db_fetch_assoc']($result))
  1315. {
  1316. // There are just things we shouldn't be able to change as members.
  1317. if ($row['id_member'] != 0 && in_array($row['variable'], array('actual_theme_url', 'actual_images_url', 'base_theme_dir', 'base_theme_url', 'default_images_url', 'default_theme_dir', 'default_theme_url', 'default_template', 'images_url', 'number_recent_posts', 'smiley_sets_default', 'theme_dir', 'theme_id', 'theme_layers', 'theme_templates', 'theme_url')))
  1318. continue;
  1319. // If this is the theme_dir of the default theme, store it.
  1320. if (in_array($row['variable'], array('theme_dir', 'theme_url', 'images_url')) && $row['id_theme'] == '1' && empty($row['id_member']))
  1321. $themeData[0]['default_' . $row['variable']] = $row['value'];
  1322. // If this isn't set yet, is a theme option, or is not the default theme..
  1323. if (!isset($themeData[$row['id_member']][$row['variable']]) || $row['id_theme'] != '1')
  1324. $themeData[$row['id_member']][$row['variable']] = substr($row['variable'], 0, 5) == 'show_' ? $row['value'] == '1' : $row['value'];
  1325. }
  1326. $smcFunc['db_free_result']($result);
  1327. if (!empty($themeData[-1]))
  1328. foreach ($themeData[-1] as $k => $v)
  1329. {
  1330. if (!isset($themeData[$member][$k]))
  1331. $themeData[$member][$k] = $v;
  1332. }
  1333. if (!empty($modSettings['cache_enable']) && $modSettings['cache_enable'] >= 2)
  1334. cache_put_data('theme_settings-' . $id_theme . ':' . $member, $themeData, 60);
  1335. // Only if we didn't already load that part of the cache...
  1336. elseif (!isset($temp))
  1337. cache_put_data('theme_settings-' . $id_theme, array(-1 => $themeData[-1], 0 => $themeData[0]), 90);
  1338. }
  1339. $settings = $themeData[0];
  1340. $options = $themeData[$member];
  1341. $settings['theme_id'] = $id_theme;
  1342. $settings['actual_theme_url'] = $settings['theme_url'];
  1343. $settings['actual_images_url'] = $settings['images_url'];
  1344. $settings['actual_theme_dir'] = $settings['theme_dir'];
  1345. $settings['template_dirs'] = array();
  1346. // This theme first.
  1347. $settings['template_dirs'][] = $settings['theme_dir'];
  1348. // Based on theme (if there is one).
  1349. if (!empty($settings['base_theme_dir']))
  1350. $settings['template_dirs'][] = $settings['base_theme_dir'];
  1351. // Lastly the default theme.
  1352. if ($settings['theme_dir'] != $settings['default_theme_dir'])
  1353. $settings['template_dirs'][] = $settings['default_theme_dir'];
  1354. if (!$initialize)
  1355. return;
  1356. // Check to see if they're accessing it from the wrong place.
  1357. if (isset($_SERVER['HTTP_HOST']) || isset($_SERVER['SERVER_NAME']))
  1358. {
  1359. $detected_url = isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) == 'on' ? 'https://' : 'http://';
  1360. $detected_url .= empty($_SERVER['HTTP_HOST']) ? $_SERVER['SERVER_NAME'] . (empty($_SERVER['SERVER_PORT']) || $_SERVER['SERVER_PORT'] == '80' ? '' : ':' . $_SERVER['SERVER_PORT']) : $_SERVER['HTTP_HOST'];
  1361. $temp = preg_replace('~/' . basename($scripturl) . '(/.+)?$~', '', strtr(dirname($_SERVER['PHP_SELF']), '\\', '/'));
  1362. if ($temp != '/')
  1363. $detected_url .= $temp;
  1364. }
  1365. if (isset($detected_url) && $detected_url != $boardurl)
  1366. {
  1367. // Try #1 - check if it's in a list of alias addresses.
  1368. if (!empty($modSettings['forum_alias_urls']))
  1369. {
  1370. $aliases = explode(',', $modSettings['forum_alias_urls']);
  1371. foreach ($aliases as $alias)
  1372. {
  1373. // Rip off all the boring parts, spaces, etc.
  1374. if ($detected_url == trim($alias) || strtr($detected_url, array('http://' => '', 'https://' => '')) == trim($alias))
  1375. $do_fix = true;
  1376. }
  1377. }
  1378. // Hmm... check #2 - is it just different by a www? Send them to the correct place!!
  1379. if (empty($do_fix) && strtr($detected_url, array('://' => '://www.')) == $boardurl && (empty($_GET) || count($_GET) == 1) && SMF != 'SSI')
  1380. {
  1381. // Okay, this seems weird, but we don't want an endless loop - this will make $_GET not empty ;).
  1382. if (empty($_GET))
  1383. redirectexit('wwwRedirect');
  1384. else
  1385. {
  1386. list ($k, $v) = each($_GET);
  1387. if ($k != 'wwwRedirect')
  1388. redirectexit('wwwRedirect;' . $k . '=' . $v);
  1389. }
  1390. }
  1391. // #3 is just a check for SSL...
  1392. if (strtr($detected_url, array('https://' => 'http://')) == $boardurl)
  1393. $do_fix = true;
  1394. // Okay, #4 - perhaps it's an IP address? We're gonna want to use that one, then. (assuming it's the IP or something...)
  1395. if (!empty($do_fix) || preg_match('~^http[s]?://(?:[\d\.:]+|\[[\d:]+\](?::\d+)?)(?:$|/)~', $detected_url) == 1)
  1396. {
  1397. // Caching is good ;).
  1398. $oldurl = $boardurl;
  1399. // Fix $boardurl and $scripturl.
  1400. $boardurl = $detected_url;
  1401. $scripturl = strtr($scripturl, array($oldurl => $boardurl));
  1402. $_SERVER['REQUEST_URL'] = strtr($_SERVER['REQUEST_URL'], array($oldurl => $boardurl));
  1403. // Fix the theme urls...
  1404. $settings['theme_url'] = strtr($settings['theme_url'], array($oldurl => $boardurl));
  1405. $settings['default_theme_url'] = strtr($settings['default_theme_url'], array($oldurl => $boardurl));
  1406. $settings['actual_theme_url'] = strtr($settings['actual_theme_url'], array($oldurl => $boardurl));
  1407. $settings['images_url'] = strtr($settings['images_url'], array($oldurl => $boardurl));
  1408. $settings['default_images_url'] = strtr($settings['default_images_url'], array($oldurl => $boardurl));
  1409. $settings['actual_images_url'] = strtr($settings['actual_images_url'], array($oldurl => $boardurl));
  1410. // And just a few mod settings :).
  1411. $modSettings['smileys_url'] = strtr($modSettings['smileys_url'], array($oldurl => $boardurl));
  1412. $modSettings['avatar_url'] = strtr($modSettings['avatar_url'], array($oldurl => $boardurl));
  1413. // Clean up after loadBoard().
  1414. if (isset($board_info['moderators']))
  1415. {
  1416. foreach ($board_info['moderators'] as $k => $dummy)
  1417. {
  1418. $board_info['moderators'][$k]['href'] = strtr($dummy['href'], array($oldurl => $boardurl));
  1419. $board_info['moderators'][$k]['link'] = strtr($dummy['link'], array('"' . $oldurl => '"' . $boardurl));
  1420. }
  1421. }
  1422. foreach ($context['linktree'] as $k => $dummy)
  1423. $context['linktree'][$k]['url'] = strtr($dummy['url'], array($oldurl => $boardurl));
  1424. }
  1425. }
  1426. // Set up the contextual user array.
  1427. $context['user'] = array(
  1428. 'id' => $user_info['id'],
  1429. 'is_logged' => !$user_info['is_guest'],
  1430. 'is_guest' => &$user_info['is_guest'],
  1431. 'is_admin' => &$user_info['is_admin'],
  1432. 'is_mod' => &$user_info['is_mod'],
  1433. // A user can mod if they have permission to see the mod center, or they are a board/group/approval moderator.
  1434. 'can_mod' => allowedTo('access_mod_center') || (!$user_info['is_guest'] && ($user_info['mod_cache']['gq'] != '0=1' || $user_info['mod_cache']['bq'] != '0=1' || ($modSettings['postmod_active'] && !empty($user_info['mod_cache']['ap'])))),
  1435. 'username' => $user_info['username'],
  1436. 'language' => $user_info['language'],
  1437. 'email' => $user_info['email'],
  1438. 'ignoreusers' => $user_info['ignoreusers'],
  1439. );
  1440. if (!$context['user']['is_guest'])
  1441. $context['user']['name'] = $user_info['name'];
  1442. elseif ($context['user']['is_guest'] && !empty($txt['guest_title']))
  1443. $context['user']['name'] = $txt['guest_title'];
  1444. // Determine the current smiley set.
  1445. $user_info['smiley_set'] = (!in_array($user_info['smiley_set'], explode(',', $modSettings['smiley_sets_known'])) && $user_info['smiley_set'] != 'none') || empty($modSettings['smiley_sets_enable']) ? (!empty($settings['smiley_sets_default']) ? $settings['smiley_sets_default'] : $modSettings['smiley_sets_default']) : $user_info['smiley_set'];
  1446. $context['user']['smiley_set'] = $user_info['smiley_set'];
  1447. // Some basic information...
  1448. if (!isset($context['html_headers']))
  1449. $context['html_headers'] = '';
  1450. $context['menu_separator'] = !empty($settings['use_image_buttons']) ? ' ' : ' | ';
  1451. $context['session_var'] = $_SESSION['session_var'];
  1452. $context['session_id'] = $_SESSION['session_value'];
  1453. $context['forum_name'] = $mbname;
  1454. $context['forum_name_html_safe'] = $smcFunc['htmlspecialchars']($context['forum_name']);
  1455. $context['header_logo_url_html_safe'] = empty($settings['header_logo_url']) ? '' : $smcFunc['htmlspecialchars']($settings['header_logo_url']);
  1456. $context['current_action'] = isset($_REQUEST['action']) ? $_REQUEST['action'] : null;
  1457. $context['current_subaction'] = isset($_REQUEST['sa']) ? $_REQUEST['sa'] : null;
  1458. $context['can_register'] = empty($modSettings['registration_method']) || $modSettings['registration_method'] != 3;
  1459. if (isset($modSettings['load_average']))
  1460. $context['load_average'] = $modSettings['load_average'];
  1461. // Set some permission related settings.
  1462. $context['show_login_bar'] = $user_info['is_guest'] && !empty($modSettings['enableVBStyleLogin']);
  1463. // This determines the server... not used in many places, except for login fixing.
  1464. $context['server'] = array(
  1465. 'is_iis' => isset($_SERVER['SERVER_SOFTWARE']) && strpos($_SERVER['SERVER_SOFTWARE'], 'Microsoft-IIS') !== false,
  1466. 'is_apache' => isset($_SERVER['SERVER_SOFTWARE']) && strpos($_SERVER['SERVER_SOFTWARE'], 'Apache') !== false,
  1467. 'is_litespeed' => isset($_SERVER['SERVER_SOFTWARE']) && strpos($_SERVER['SERVER_SOFTWARE'], 'LiteSpeed') !== false,
  1468. 'is_lighttpd' => isset($_SERVER['SERVER_SOFTWARE']) && strpos($_SERVER['SERVER_SOFTWARE'], 'lighttpd') !== false,
  1469. 'is_nginx' => isset($_SERVER['SERVER_SOFTWARE']) && strpos($_SERVER['SERVER_SOFTWARE'], 'nginx') !== false,
  1470. 'is_cgi' => isset($_SERVER['SERVER_SOFTWARE']) && strpos(php_sapi_name(), 'cgi') !== false,
  1471. 'is_windows' => strpos(PHP_OS, 'WIN') === 0,
  1472. 'iso_case_folding' => ord(strtolower(chr(138))) === 154,
  1473. );
  1474. // A bug in some versions of IIS under CGI (older ones) makes cookie setting not work with Location: headers.
  1475. $context['server']['needs_login_fix'] = $context['server']['is_cgi'] && $context['server']['is_iis'];
  1476. // Detect the browser. This is separated out because it's also used in attachment downloads
  1477. detectBrowser();
  1478. // Set the top level linktree up.
  1479. array_unshift($context['linktree'], array(
  1480. 'url' => $scripturl,
  1481. 'name' => $context['forum_name_html_safe']
  1482. ));
  1483. // This allows sticking some HTML on the page output - useful for controls.
  1484. $context['insert_after_template'] = '';
  1485. if (!isset($txt))
  1486. $txt = array();
  1487. $simpleActions = array(
  1488. 'findmember',
  1489. 'helpadmin',
  1490. 'printpage',
  1491. 'quotefast',
  1492. 'spellcheck',
  1493. );
  1494. $context['javascript_files'] = array();
  1495. $context['css_files'] = array();
  1496. // Wireless mode? Load up the wireless stuff.
  1497. if (WIRELESS)
  1498. {
  1499. $context['template_layers'] = array(WIRELESS_PROTOCOL);
  1500. loadTemplate('Wireless');
  1501. loadLanguage('Wireless+index+Modifications');
  1502. }
  1503. // Output is fully XML, so no need for the index template.
  1504. elseif (isset($_REQUEST['xml']))
  1505. {
  1506. loadLanguage('index+Modifications');
  1507. loadTemplate('Xml');
  1508. $context['template_layers'] = array();
  1509. }
  1510. // These actions don't require the index template at all.
  1511. elseif (!empty($_REQUEST['action']) && in_array($_REQUEST['action'], $simpleActions))
  1512. {
  1513. loadLanguage('index+Modifications');
  1514. $context['template_layers'] = array();
  1515. }
  1516. else
  1517. {
  1518. // Custom templates to load, or just default?
  1519. if (isset($settings['theme_templates']))
  1520. $templates = explode(',', $settings['theme_templates']);
  1521. else
  1522. $templates = array('index');
  1523. // Load each template...
  1524. foreach ($templates as $template)
  1525. loadTemplate($template);
  1526. // ...and attempt to load their associated language files.
  1527. $required_files = implode('+', array_merge($templates, array('Modifications')));
  1528. loadLanguage($required_files, '', false);
  1529. // Custom template layers?
  1530. if (isset($settings['theme_layers']))
  1531. $context['template_layers'] = explode(',', $settings['theme_layers']);
  1532. else
  1533. $context['template_layers'] = array('html', 'body');
  1534. }
  1535. // Initialize the theme.
  1536. loadSubTemplate('init', 'ignore');
  1537. // Load the compatibility stylesheet if the theme hasn't been updated for 2.0 RC2 (yet).
  1538. if (isset($settings['theme_version']) && (version_compare($settings['theme_version'], '2.0 RC2', '<') || strpos($settings['theme_version'], '2.0 Beta') !== false))
  1539. loadTemplate(false, 'compat');
  1540. // Guests may still need a name.
  1541. if ($context['user']['is_guest'] && empty($context['user']['name']))
  1542. $context['user']['name'] = $txt['guest_title'];
  1543. // Any theme-related strings that need to be loaded?
  1544. if (!empty($settings['require_theme_strings']))
  1545. loadLanguage('ThemeStrings', '', false);
  1546. // We allow theme variants, because we're cool.
  1547. $context['theme_variant'] = '';
  1548. $context['theme_variant_url'] = '';
  1549. if (!empty($settings['theme_variants']))
  1550. {
  1551. // Overriding - for previews and that ilk.
  1552. if (!empty($_REQUEST['variant']))
  1553. $_SESSION['id_variant'] = $_REQUEST['variant'];
  1554. // User selection?
  1555. if (empty($settings['disable_user_variant']) || allowedTo('admin_forum'))
  1556. $context['theme_variant'] = !empty($_SESSION['id_variant']) ? $_SESSION['id_variant'] : (!empty($options['theme_variant']) ? $options['theme_variant'] : '');
  1557. // If not a user variant, select the default.
  1558. if ($context['theme_variant'] == '' || !in_array($context['theme_variant'], $settings['theme_variants']))
  1559. $context['theme_variant'] = !empty($settings['default_variant']) && in_array($settings['default_variant'], $settings['theme_variants']) ? $settings['default_variant'] : $settings['theme_variants'][0];
  1560. // Do this to keep things easier in the templates.
  1561. $context['theme_variant'] = '_' . $context['theme_variant'];
  1562. $context['theme_variant_url'] = $context['theme_variant'] . '/';
  1563. }
  1564. // Let's be compatible with old themes!
  1565. if (!function_exists('template_html_above') && in_array('html', $context['template_layers']))
  1566. $context['template_layers'] = array('main');
  1567. // Allow overriding the board wide time/number formats.
  1568. if (empty($user_settings['time_format']) && !empty($txt['time_format']))
  1569. $user_info['time_format'] = $txt['time_format'];
  1570. $txt['number_format'] = empty($txt['number_format']) ? empty($modSettings['number_format']) ? '' : $modSettings['number_format'] : $txt['number_format'];
  1571. if (isset($settings['use_default_images']) && $settings['use_default_images'] == 'always')
  1572. {
  1573. $settings['theme_url'] = $settings['default_theme_url'];
  1574. $settings['images_url'] = $settings['default_images_url'];
  1575. $settings['theme_dir'] = $settings['default_theme_dir'];
  1576. }
  1577. // Make a special URL for the language.
  1578. $settings['lang_images_url'] = $settings['images_url'] . '/' . (!empty($txt['image_lang']) ? $txt['image_lang'] : $user_info['language']);
  1579. // Set the character set from the template.
  1580. $context['character_set'] = empty($modSettings['global_character_set']) ? $txt['lang_character_set'] : $modSettings['global_character_set'];
  1581. $context['utf8'] = $context['character_set'] === 'UTF-8';
  1582. $context['right_to_left'] = !empty($txt['lang_rtl']);
  1583. $context['tabindex'] = 1;
  1584. // Fix font size with HTML 4.01, etc.
  1585. if (isset($settings['doctype']))
  1586. $context['browser']['needs_size_fix'] |= $settings['doctype'] == 'html' && isBrowser('ie6');
  1587. // Compatibility.
  1588. if (!isset($settings['theme_version']))
  1589. $modSettings['memberCount'] = $modSettings['totalMembers'];
  1590. // This allows us to change the way things look for the admin.
  1591. $context['admin_features'] = isset($modSettings['admin_features']) ? explode(',', $modSettings['admin_features']) : array('cd,cp,k,w,rg,ml,pm');
  1592. // If we think we have mail to send, let's offer up some possibilities... robots get pain (Now with scheduled task support!)
  1593. if ((!empty($modSettings['mail_next_send']) && $modSettings['mail_next_send'] < time() && empty($modSettings['mail_queue_use_cron'])) || empty($modSettings['next_task_time']) || $modSettings['next_task_time'] < time())
  1594. {
  1595. if (isBrowser('possibly_robot'))
  1596. {
  1597. // @todo Maybe move this somewhere better?!
  1598. require_once($sourcedir . '/ScheduledTasks.php');
  1599. // What to do, what to do?!
  1600. if (empty($modSettings['next_task_time']) || $modSettings['next_task_time'] < time())
  1601. AutoTask();
  1602. else
  1603. ReduceMailQueue();
  1604. }
  1605. else
  1606. {
  1607. $type = empty($modSettings['next_task_time']) || $modSettings['next_task_time'] < time() ? 'task' : 'mailq';
  1608. $ts = $type == 'mailq' ? $modSettings['mail_next_send'] : $modSettings['next_task_time'];
  1609. $context['html_headers'] .= '
  1610. <script type="text/javascript">
  1611. function smfAutoTask()
  1612. {
  1613. var tempImage = new Image();
  1614. tempImage.src = smf_scripturl + "?scheduled=' . $type . ';ts=' . $ts . '";
  1615. }
  1616. window.setTimeout("smfAutoTask();", 1);
  1617. </script>';
  1618. }
  1619. }
  1620. // Any files to include at this point?
  1621. if (!empty($modSettings['integrate_theme_include']))
  1622. {
  1623. $theme_includes = explode(',', $modSettings['integrate_theme_include']);
  1624. foreach ($theme_includes as $include)
  1625. {
  1626. $include = strtr(trim($include), array('$boarddir' => $boarddir, '$sourcedir' => $sourcedir, '$themedir' => $settings['theme_dir']));
  1627. if (file_exists($include))
  1628. require_once($include);
  1629. }
  1630. }
  1631. // Call load theme integration functions.
  1632. call_integration_hook('integrate_load_theme');
  1633. // We are ready to go.
  1634. $context['theme_loaded'] = true;
  1635. }
  1636. /**
  1637. * Load a template - if the theme doesn't include it, use the default.
  1638. * What this function does:
  1639. * - loads a template file with the name template_name from the current, default, or base theme.
  1640. * - detects a wrong default theme directory and tries to work around it.
  1641. *
  1642. * @uses the template_include() function to include the file.
  1643. * @param string $template_name
  1644. * @param array $style_sheets = array()
  1645. * @param bool $fatal = true if fatal is true, dies with an error message if the template cannot be found
  1646. * @return bool
  1647. */
  1648. function loadTemplate($template_name, $style_sheets = array(), $fatal = true)
  1649. {
  1650. global $context, $settings, $txt, $scripturl, $boarddir, $db_show_debug;
  1651. // Do any style sheets first, cause we're easy with those.
  1652. if (!empty($style_sheets))
  1653. {
  1654. if (!is_array($style_sheets))
  1655. $style_sheets = array($style_sheets);
  1656. foreach ($style_sheets as $sheet)
  1657. {
  1658. // Prevent the style sheet from being included twice.
  1659. if (strpos($context['html_headers'], 'id="' . $sheet . '_css"') !== false)
  1660. continue;
  1661. $sheet_path = file_exists($settings['theme_dir']. '/css/' . $sheet . '.css') ? 'theme_url' : (file_exists($settings['default_theme_dir']. '/css/' . $sheet . '.css') ? 'default_theme_url' : '');
  1662. if ($sheet_path)
  1663. {
  1664. $context['html_headers'] .= "\n\t" . '<link rel="stylesheet" type="text/css" id="' . $sheet . '_css" href="' . $settings[$sheet_path] . '/css/' . $sheet . '.css" />';
  1665. if ($db_show_debug === true)
  1666. $context['debug']['sheets'][] = $sheet . ' (' . basename($settings[$sheet_path]) . ')';
  1667. }
  1668. }
  1669. }
  1670. // No template to load?
  1671. if ($template_name === false)
  1672. return true;
  1673. $loaded = false;
  1674. foreach ($settings['template_dirs'] as $template_dir)
  1675. {
  1676. if (file_exists($template_dir . '/' . $template_name . '.template.php'))
  1677. {
  1678. $loaded = true;
  1679. template_include($template_dir . '/' . $template_name . '.template.php', true);
  1680. break;
  1681. }
  1682. }
  1683. if ($loaded)
  1684. {
  1685. // For compatibility reasons, if this is the index template without new functions, include compatible stuff.
  1686. if (substr($template_name, 0, 5) == 'index' && !function_exists('template_button_strip'))
  1687. loadTemplate('Compat');
  1688. if ($db_show_debug === true)
  1689. $context['debug']['templates'][] = $template_name . ' (' . basename($template_dir) . ')';
  1690. // If they have specified an initialization function for this template, go ahead and call it now.
  1691. if (function_exists('template_' . $template_name . '_init'))
  1692. call_user_func('template_' . $template_name . '_init');
  1693. }
  1694. // Hmmm... doesn't exist?! I don't suppose the directory is wrong, is it?
  1695. elseif (!file_exists($settings['default_theme_dir']) && file_exists($boarddir . '/Themes/default'))
  1696. {
  1697. $settings['default_theme_dir'] = $boarddir . '/Themes/default';
  1698. $settings['template_dirs'][] = $settings['default_theme_dir'];
  1699. if (!empty($context['user']['is_admin']) && !isset($_GET['th']))
  1700. {
  1701. loadLanguage('Errors');
  1702. echo '
  1703. <div class="alert errorbox">
  1704. <a href="', $scripturl . '?action=admin;area=theme;sa=settings;th=1;' . $context['session_var'] . '=' . $context['session_id'], '" class="alert">', $txt['theme_dir_wrong'], '</a>
  1705. </div>';
  1706. }
  1707. loadTemplate($template_name);
  1708. }
  1709. // Cause an error otherwise.
  1710. elseif ($template_name != 'Errors' && $template_name != 'index' && $fatal)
  1711. fatal_lang_error('theme_template_error', 'template', array((string) $template_name));
  1712. elseif ($fatal)
  1713. die(log_error(sprintf(isset($txt['theme_template_error']) ? $txt['theme_template_error'] : 'Unable to load Themes/default/%s.template.php!', (string) $template_name), 'template'));
  1714. else
  1715. return false;
  1716. }
  1717. /**
  1718. * Load a sub-template.
  1719. * What it does:
  1720. * - loads the sub template specified by sub_template_name, which must be in an already-loaded template.
  1721. * - if ?debug is in the query string, shows administrators a marker after every sub template
  1722. * for debugging purposes.
  1723. *
  1724. * @todo get rid of reading $_REQUEST directly
  1725. *
  1726. * @param string $sub_template_name
  1727. * @param bool $fatal = false, $fatal = true is for templates that shouldn't get a 'pretty' error screen.
  1728. */
  1729. function loadSubTemplate($sub_template_name, $fatal = false)
  1730. {
  1731. global $context, $settings, $options, $txt, $db_show_debug;
  1732. if ($db_show_debug === true)
  1733. $context['debug']['sub_templates'][] = $sub_template_name;
  1734. // Figure out what the template function is named.
  1735. $theme_function = 'template_' . $sub_template_name;
  1736. if (function_exists($theme_function))
  1737. $theme_function();
  1738. elseif ($fatal === false)
  1739. fatal_lang_error('theme_template_error', 'template', array((string) $sub_template_name));
  1740. elseif ($fatal !== 'ignore')
  1741. die(log_error(sprintf(isset($txt['theme_template_error']) ? $txt['theme_template_error'] : 'Unable to load the %s sub template!', (string) $sub_template_name), 'template'));
  1742. // Are we showing debugging for templates? Just make sure not to do it before the doctype...
  1743. if (allowedTo('admin_forum') && isset($_REQUEST['debug']) && !in_array($sub_template_name, array('init', 'main_below')) && ob_get_length() > 0 && !isset($_REQUEST['xml']))
  1744. {
  1745. echo '
  1746. <div style="font-size: 8pt; border: 1px dashed red; background: orange; text-align: center; font-weight: bold;">---- ', $sub_template_name, ' ends ----</div>';
  1747. }
  1748. }
  1749. /**
  1750. * Add a CSS file for output later
  1751. *
  1752. * @param string $filename
  1753. * @param array $options
  1754. */
  1755. function loadCSSFile($filename, $options = array())
  1756. {
  1757. global $settings, $context;
  1758. if (strpos($filename, 'http://') === false || !empty($options['local']))
  1759. $filename = $settings['theme_url'] . '/' . $filename;
  1760. $context['css_files'][$filename] = $options;
  1761. }
  1762. /**
  1763. * Add a Javascript file for output later
  1764. *
  1765. * @param string $filename
  1766. * @param array $options, possible parameters:
  1767. * - local (true/false): define if the file is local
  1768. * - default_theme (true/false): force use of default theme url
  1769. * - defer (true/false): define if the file should be load in head or before the closing <html> tag
  1770. */
  1771. function loadJavascriptFile($filename, $options = array())
  1772. {
  1773. global $settings, $context;
  1774. $theme = !empty($options['default_theme']) ? 'default_theme_url' : 'theme_url';
  1775. if (strpos($filename, 'http') === false || !empty($options['local']))
  1776. $filename = $settings[$theme] . '/' . $filename;
  1777. $context['javascript_files'][$filename] = $options;
  1778. }
  1779. /**
  1780. * Load a language file. Tries the current and default themes as well as the user and global languages.
  1781. *
  1782. * @param string $template_name
  1783. * @param string $lang
  1784. * @param bool $fatal = true
  1785. * @param bool $force_reload = false
  1786. * @return string The language actually loaded.
  1787. */
  1788. function loadLanguage($template_name, $lang = '', $fatal = true, $force_reload = false)
  1789. {
  1790. global $user_info, $language, $settings, $context, $modSettings;
  1791. global $cachedir, $db_show_debug, $sourcedir, $txt;
  1792. static $already_loaded = array();
  1793. // Default to the user's language.
  1794. if ($lang == '')
  1795. $lang = isset($user_info['language']) ? $user_info['language'] : $language;
  1796. // Do we want the English version of language file as fallback?
  1797. if (empty($modSettings['disable_language_fallback']) && $lang != 'english')
  1798. loadLanguage($template_name, 'english', false);
  1799. if (!$force_reload && isset($already_loaded[$template_name]) && $already_loaded[$template_name] == $lang)
  1800. return $lang;
  1801. // Make sure we have $settings - if not we're in trouble and need to find it!
  1802. if (empty($settings['default_theme_dir']))
  1803. {
  1804. require_once($sourcedir . '/ScheduledTasks.php');
  1805. loadEssentialThemeData();
  1806. }
  1807. // What theme are we in?
  1808. $theme_name = basename($settings['theme_url']);
  1809. if (empty($theme_name))
  1810. $theme_name = 'unknown';
  1811. // For each file open it up and write it out!
  1812. foreach (explode('+', $template_name) as $template)
  1813. {
  1814. // Obviously, the current theme is most important to check.
  1815. $attempts = array(
  1816. array($settings['theme_dir'], $template, $lang, $settings['theme_url']),
  1817. array($settings['theme_dir'], $template, $language, $settings['theme_url']),
  1818. );
  1819. // Do we have a base theme to worry about?
  1820. if (isset($settings['base_theme_dir']))
  1821. {
  1822. $attempts[] = array($settings['base_theme_dir'], $template, $lang, $settings['base_theme_url']);
  1823. $attempts[] = array($settings['base_theme_dir'], $template, $language, $settings['base_theme_url']);
  1824. }
  1825. // Fall back on the default theme if necessary.
  1826. $attempts[] = array($settings['default_theme_dir'], $template, $lang, $settings['default_theme_url']);
  1827. $attempts[] = array($settings['default_theme_dir'], $template, $language, $settings['default_theme_url']);
  1828. // Fall back on the English language if none of the preferred languages can be found.
  1829. if (!in_array('english', array($lang, $language)))
  1830. {
  1831. $attempts[] = array($settings['theme_dir'], $template, 'english', $settings['theme_url']);
  1832. $attempts[] = array($settings['default_theme_dir'], $template, 'english', $settings['default_theme_url']);
  1833. }
  1834. // Try to find the language file.
  1835. $found = false;
  1836. foreach ($attempts as $k => $file)
  1837. {
  1838. if (file_exists($file[0] . '/languages/' . $file[1] . '.' . $file[2] . '.php'))
  1839. {
  1840. // Include it!
  1841. template_include($file[0] . '/languages/' . $file[1] . '.' . $file[2] . '.php');
  1842. // Note that we found it.
  1843. $found = true;
  1844. break;
  1845. }
  1846. }
  1847. // That couldn't be found! Log the error, but *try* to continue normally.
  1848. if (!$found && $fatal)
  1849. {
  1850. log_error(sprintf($txt['theme_language_error'], $template_name . '.' . $lang, 'template'));
  1851. break;
  1852. }
  1853. // For the sake of backward compatibility
  1854. if (!empty($txt['emails']))
  1855. {
  1856. foreach ($txt['emails'] as $key => $value)
  1857. {
  1858. $txt[$key . '_subject'] = $value['subject'];
  1859. $txt[$key . '_body'] = $value['body'];
  1860. }
  1861. $txt['emails'] = array();
  1862. }
  1863. if (!empty($birthdayEmails))
  1864. {
  1865. foreach ($birthdayEmails as $key => $value)
  1866. {
  1867. $txtBirthdayEmails[$key . '_subject'] = $value['subject'];
  1868. $txtBirthdayEmails[$key . '_body'] = $value['body'];
  1869. $txtBirthdayEmails[$key . '_author'] = $value['author'];
  1870. }
  1871. $birthdayEmails = array();
  1872. }
  1873. }
  1874. // Keep track of what we're up to soldier.
  1875. if ($db_show_debug === true)
  1876. $context['debug']['language_files'][] = $template_name . '.' . $lang . ' (' . $theme_name . ')';
  1877. // Remember what we have loaded, and in which language.
  1878. $already_loaded[$template_name] = $lang;
  1879. // Return the language actually loaded.
  1880. return $lang;
  1881. }
  1882. /**
  1883. * Get all parent boards (requires first parent as parameter)
  1884. * It finds all the parents of id_parent, and that board itself.
  1885. * Additionally, it detects the moderators of said boards.
  1886. *
  1887. * @param int $id_parent
  1888. * @return an array of information about the boards found.
  1889. */
  1890. function getBoardParents($id_parent)
  1891. {
  1892. global $scripturl, $smcFunc;
  1893. // First check if we have this cached already.
  1894. if (($boards = cache_get_data('board_parents-' . $id_parent, 480)) === null)
  1895. {
  1896. $boards = array();
  1897. $original_parent = $id_parent;
  1898. // Loop while the parent is non-zero.
  1899. while ($id_parent != 0)
  1900. {
  1901. $result = $smcFunc['db_query']('', '
  1902. SELECT
  1903. b.id_parent, b.name, {int:board_parent} AS id_board, IFNULL(mem.id_member, 0) AS id_moderator,
  1904. mem.real_name, b.child_level
  1905. FROM {db_prefix}boards AS b
  1906. LEFT JOIN {db_prefix}moderators AS mods ON (mods.id_board = b.id_board)
  1907. LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = mods.id_member)
  1908. WHERE b.id_board = {int:board_parent}',
  1909. array(
  1910. 'board_parent' => $id_parent,
  1911. )
  1912. );
  1913. // In the EXTREMELY unlikely event this happens, give an error message.
  1914. if ($smcFunc['db_num_rows']($result) == 0)
  1915. fatal_lang_error('parent_not_found', 'critical');
  1916. while ($row = $smcFunc['db_fetch_assoc']($result))
  1917. {
  1918. if (!isset($boards[$row['id_board']]))
  1919. {
  1920. $id_parent = $row['id_parent'];
  1921. $boards[$row['id_board']] = array(
  1922. 'url' => $scripturl . '?board=' . $row['id_board'] . '.0',
  1923. 'name' => $row['name'],
  1924. 'level' => $row['child_level'],
  1925. 'moderators' => array()
  1926. );
  1927. }
  1928. // If a moderator exists for this board, add that moderator for all children too.
  1929. if (!empty($row['id_moderator']))
  1930. foreach ($boards as $id => $dummy)
  1931. {
  1932. $boards[$id]['moderators'][$row['id_moderator']] = array(
  1933. 'id' => $row['id_moderator'],
  1934. 'name' => $row['real_name'],
  1935. 'href' => $scripturl . '?action=profile;u=' . $row['id_moderator'],
  1936. 'link' => '<a href="' . $scripturl . '?action=profile;u=' . $row['id_moderator'] . '">' . $row['real_name'] . '</a>'
  1937. );
  1938. }
  1939. }
  1940. $smcFunc['db_free_result']($result);
  1941. }
  1942. cache_put_data('board_parents-' . $original_parent, $boards, 480);
  1943. }
  1944. return $boards;
  1945. }
  1946. /**
  1947. * Attempt to reload our known languages.
  1948. * It will try to choose only utf8 or non-utf8 languages.
  1949. *
  1950. * @param bool $use_cache = true
  1951. * @param bool $favor_utf8 = true
  1952. * @return array
  1953. */
  1954. function getLanguages($use_cache = true, $favor_utf8 = true)
  1955. {
  1956. global $context, $smcFunc, $settings, $modSettings;
  1957. // Either we don't use the cache, or its expired.
  1958. if (!$use_cache || ($context['languages'] = cache_get_data('known_languages' . ($favor_utf8 ? '' : '_all'), !empty($modSettings['cache_enable']) && $modSettings['cache_enable'] < 1 ? 86400 : 3600)) == null)
  1959. {
  1960. // If we don't have our theme information yet, lets get it.
  1961. if (empty($settings['default_theme_dir']))
  1962. loadTheme(0, false);
  1963. // Default language directories to try.
  1964. $language_directories = array(
  1965. $settings['default_theme_dir'] . '/languages',
  1966. $settings['actual_theme_dir'] . '/languages',
  1967. );
  1968. // We possibly have a base theme directory.
  1969. if (!empty($settings['base_theme_dir']))
  1970. $language_directories[] = $settings['base_theme_dir'] . '/languages';
  1971. // Remove any duplicates.
  1972. $language_directories = array_unique($language_directories);
  1973. foreach ($language_directories as $language_dir)
  1974. {
  1975. // Can't look in here... doesn't exist!
  1976. if (!file_exists($language_dir))
  1977. continue;
  1978. $dir = dir($language_dir);
  1979. while ($entry = $dir->read())
  1980. {
  1981. // Look for the index language file....
  1982. if (!preg_match('~^index\.(.+)\.php$~', $entry, $matches))
  1983. continue;
  1984. $context['languages'][$matches[1]] = array(
  1985. 'name' => $smcFunc['ucwords'](strtr($matches[1], array('_' => ' '))),
  1986. 'selected' => false,
  1987. 'filename' => $matches[1],
  1988. 'location' => $language_dir . '/index.' . $matches[1] . '.php',
  1989. );
  1990. }
  1991. $dir->close();
  1992. }
  1993. // Favoring UTF8? Then prevent us from selecting non-UTF8 versions.
  1994. if ($favor_utf8)
  1995. {
  1996. foreach ($context['languages'] as $lang)
  1997. if (substr($lang['filename'], strlen($lang['filename']) - 5, 5) != '-utf8' && isset($context['languages'][$lang['filename'] . '-utf8']))
  1998. unset($context['languages'][$lang['filename']]);
  1999. }
  2000. // Lets cash in on this deal.
  2001. if (!empty($modSettings['cache_enable']))
  2002. cache_put_data('known_languages' . ($favor_utf8 ? '' : '_all'), $context['languages'], !empty($modSettings['cache_enable']) && $modSettings['cache_enable'] < 1 ? 86400 : 3600);
  2003. }
  2004. return $context['languages'];
  2005. }
  2006. /**
  2007. * Replace all vulgar words with respective proper words. (substring or whole words..)
  2008. * What this function does:
  2009. * - it censors the passed string.
  2010. * - if the theme setting allow_no_censored is on, and the theme option
  2011. * show_no_censored is enabled, does not censor, unless force is also set.
  2012. * - it caches the list of censored words to reduce parsing.
  2013. *
  2014. * @param string &$text
  2015. * @param bool $force = false
  2016. * @return string The censored text
  2017. */
  2018. function censorText(&$text, $force = false)
  2019. {
  2020. global $modSettings, $options, $settings, $txt;
  2021. static $censor_vulgar = null, $censor_proper;
  2022. if ((!empty($options['show_no_censored']) && $settings['allow_no_censored'] && !$force) || empty($modSettings['censor_vulgar']) || trim($text) === '')
  2023. return $text;
  2024. // If they haven't yet been loaded, load them.
  2025. if ($censor_vulgar == null)
  2026. {
  2027. $censor_vulgar = explode("\n", $modSettings['censor_vulgar']);
  2028. $censor_proper = explode("\n", $modSettings['censor_proper']);
  2029. // Quote them for use in regular expressions.
  2030. if (!empty($modSettings['censorWholeWord']))
  2031. {
  2032. for ($i = 0, $n = count($censor_vulgar); $i < $n; $i++)
  2033. {
  2034. $censor_vulgar[$i] = str_replace(array('\\\\\\*', '\\*', '&', '\''), array('[*]', '[^\s]*?', '&amp;', '&#039;'), preg_quote($censor_vulgar[$i], '/'));
  2035. $censor_vulgar[$i] = '/(?<=^|\W)' . $censor_vulgar[$i] . '(?=$|\W)/' . (empty($modSettings['censorIgnoreCase']) ? '' : 'i') . ((empty($modSettings['global_character_set']) ? $txt['lang_character_set'] : $modSettings['global_character_set']) === 'UTF-8' ? 'u' : '');
  2036. // @todo I'm thinking the old way is some kind of bug and this is actually fixing it.
  2037. //if (strpos($censor_vulgar[$i], '\'') !== false)
  2038. //$censor_vulgar[$i] = str_replace('\'', '&#039;', $censor_vulgar[$i]);
  2039. }
  2040. }
  2041. }
  2042. // Censoring isn't so very complicated :P.
  2043. if (empty($modSettings['censorWholeWord']))
  2044. $text = empty($modSettings['censorIgnoreCase']) ? str_ireplace($censor_vulgar, $censor_proper, $text) : str_replace($censor_vulgar, $censor_proper, $text);
  2045. else
  2046. $text = preg_replace($censor_vulgar, $censor_proper, $text);
  2047. return $text;
  2048. }
  2049. /**
  2050. * Load the template/language file using eval or require? (with eval we can show an error message!)
  2051. * - loads the template or language file specified by filename.
  2052. * - uses eval unless disableTemplateEval is enabled.
  2053. * - outputs a parse error if the file did not exist or contained errors.
  2054. * - attempts to detect the error and line, and show detailed information.
  2055. *
  2056. * @param string $filename
  2057. * @param bool $once = false, if true only includes the file once (like include_once)
  2058. */
  2059. function template_include($filename, $once = false)
  2060. {
  2061. global $context, $settings, $options, $txt, $scripturl, $modSettings;
  2062. global $user_info, $boardurl, $boarddir, $sourcedir;
  2063. global $maintenance, $mtitle, $mmessage;
  2064. static $templates = array();
  2065. // We want to be able to figure out any errors...
  2066. @ini_set('track_errors', '1');
  2067. // Don't include the file more than once, if $once is true.
  2068. if ($once && in_array($filename, $templates))
  2069. return;
  2070. // Add this file to the include list, whether $once is true or not.
  2071. else
  2072. $templates[] = $filename;
  2073. // Are we going to use eval?
  2074. if (empty($modSettings['disableTemplateEval']))
  2075. {
  2076. $file_found = file_exists($filename) && eval('?' . '>' . rtrim(file_get_contents($filename))) !== false;
  2077. $settings['current_include_filename'] = $filename;
  2078. }
  2079. else
  2080. {
  2081. $file_found = file_exists($filename);
  2082. if ($once && $file_found)
  2083. require_once($filename);
  2084. elseif ($file_found)
  2085. require($filename);
  2086. }
  2087. if ($file_found !== true)
  2088. {
  2089. ob_end_clean();
  2090. if (!empty($modSettings['enableCompressedOutput']))
  2091. @ob_start('ob_gzhandler');
  2092. else
  2093. ob_start();
  2094. if (isset($_GET['debug']) && !WIRELESS)
  2095. header('Content-Type: application/xhtml+xml; charset=' . (empty($context['character_set']) ? 'ISO-8859-1' : $context['character_set']));
  2096. // Don't cache error pages!!
  2097. header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
  2098. header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
  2099. header('Cache-Control: no-cache');
  2100. if (!isset($txt['template_parse_error']))
  2101. {
  2102. $txt['template_parse_error'] = 'Template Parse Error!';
  2103. $txt['template_parse_error_message'] = 'It seems something has gone sour on the forum with the template system. This problem should only be temporary, so please come back later and try again. If you continue to see this message, please contact the administrator.<br /><br />You can also try <a href="javascript:location.reload();">refreshing this page</a>.';
  2104. $txt['template_parse_error_details'] = 'There was a problem loading the <tt><strong>%1$s</strong></tt> template or language file. Please check the syntax and try again - remember, single quotes (<tt>\'</tt>) often have to be escaped with a slash (<tt>\\</tt>). To see more specific error information from PHP, try <a href="' . $boardurl . '%1$s" class="extern">accessing the file directly</a>.<br /><br />You may want to try to <a href="javascript:location.reload();">refresh this page</a> or <a href="' . $scripturl . '?theme=1">use the default theme</a>.';
  2105. }
  2106. // First, let's get the doctype and language information out of the way.
  2107. echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  2108. <html xmlns="http://www.w3.org/1999/xhtml"', !empty($context['right_to_left']) ? ' dir="rtl"' : '', '>
  2109. <head>';
  2110. if (isset($context['character_set']))
  2111. echo '
  2112. <meta http-equiv="Content-Type" content="text/html; charset=', $context['character_set'], '" />';
  2113. if (!empty($maintenance) && !allowedTo('admin_forum'))
  2114. echo '
  2115. <title>', $mtitle, '</title>
  2116. </head>
  2117. <body>
  2118. <h3>', $mtitle, '</h3>
  2119. ', $mmessage, '
  2120. </body>
  2121. </html>';
  2122. elseif (!allowedTo('admin_forum'))
  2123. echo '
  2124. <title>', $txt['template_parse_error'], '</title>
  2125. </head>
  2126. <body>
  2127. <h3>', $txt['template_parse_error'], '</h3>
  2128. ', $txt['template_parse_error_message'], '
  2129. </body>
  2130. </html>';
  2131. else
  2132. {
  2133. require_once($sourcedir . '/Subs-Package.php');
  2134. $error = fetch_web_data($boardurl . strtr($filename, array($boarddir => '', strtr($boarddir, '\\', '/') => '')));
  2135. if (empty($error) && ini_get('track_errors'))
  2136. $error = $php_errormsg;
  2137. $error = strtr($error, array('<b>' => '<strong>', '</b>' => '</strong>'));
  2138. echo '
  2139. <title>', $txt['template_parse_error'], '</title>
  2140. </head>
  2141. <body>
  2142. <h3>', $txt['template_parse_error'], '</h3>
  2143. ', sprintf($txt['template_parse_error_details'], strtr($filename, array($boarddir => '', strtr($boarddir, '\\', '/') => '')));
  2144. if (!empty($error))
  2145. echo '
  2146. <hr />
  2147. <div style="margin: 0 20px;"><tt>', strtr(strtr($error, array('<strong>' . $boarddir => '<strong>...', '<strong>' . strtr($boarddir, '\\', '/') => '<strong>...')), '\\', '/'), '</tt></div>';
  2148. // I know, I know... this is VERY COMPLICATED. Still, it's good.
  2149. if (preg_match('~ <strong>(\d+)</strong><br( /)?' . '>$~i', $error, $match) != 0)
  2150. {
  2151. $data = file($filename);
  2152. $data2 = highlight_php_code(implode('', $data));
  2153. $data2 = preg_split('~\<br( /)?\>~', $data2);
  2154. // Fix the PHP code stuff...
  2155. if (isBrowser('ie4') || isBrowser('ie5') || isBrowser('ie5.5'))
  2156. $data2 = str_replace("\t", '<pre style="display: inline;">' . "\t" . '</pre>', $data2);
  2157. elseif (!isBrowser('gecko'))
  2158. $data2 = str_replace("\t", '<span style="white-space: pre;">' . "\t" . '</span>', $data2);
  2159. else
  2160. $data2 = str_replace('<pre style="display: inline;">' . "\t" . '</pre>', "\t", $data2);
  2161. // Now we get to work around a bug in PHP where it doesn't escape <br />s!
  2162. $j = -1;
  2163. foreach ($data as $line)
  2164. {
  2165. $j++;
  2166. if (substr_count($line, '<br />') == 0)
  2167. continue;
  2168. $n = substr_count($line, '<br />');
  2169. for ($i = 0; $i < $n; $i++)
  2170. {
  2171. $data2[$j] .= '&lt;br /&gt;' . $data2[$j + $i + 1];
  2172. unset($data2[$j + $i + 1]);
  2173. }
  2174. $j += $n;
  2175. }
  2176. $data2 = array_values($data2);
  2177. array_unshift($data2, '');
  2178. echo '
  2179. <div style="margin: 2ex 20px; width: 96%; overflow: auto;"><pre style="margin: 0;">';
  2180. // Figure out what the color coding was before...
  2181. $line = max($match[1] - 9, 1);
  2182. $last_line = '';
  2183. for ($line2 = $line - 1; $line2 > 1; $line2--)
  2184. if (strpos($data2[$line2], '<') !== false)
  2185. {
  2186. if (preg_match('~(<[^/>]+>)[^<]*$~', $data2[$line2], $color_match) != 0)
  2187. $last_line = $color_match[1];
  2188. break;
  2189. }
  2190. // Show the relevant lines...
  2191. for ($n = min($match[1] + 4, count($data2) + 1); $line <= $n; $line++)
  2192. {
  2193. if ($line == $match[1])
  2194. echo '</pre><div style="background-color: #ffb0b5;"><pre style="margin: 0;">';
  2195. echo '<span style="color: black;">', sprintf('%' . strlen($n) . 's', $line), ':</span> ';
  2196. if (isset($data2[$line]) && $data2[$line] != '')
  2197. echo substr($data2[$line], 0, 2) == '</' ? preg_replace('~^</[^>]+>~', '', $data2[$line]) : $last_line . $data2[$line];
  2198. if (isset($data2[$line]) && preg_match('~(<[^/>]+>)[^<]*$~', $data2[$line], $color_match) != 0)
  2199. {
  2200. $last_line = $color_match[1];
  2201. echo '</', substr($last_line, 1, 4), '>';
  2202. }
  2203. elseif ($last_line != '' && strpos($data2[$line], '<') !== false)
  2204. $last_line = '';
  2205. elseif ($last_line != '' && $data2[$line] != '')
  2206. echo '</', substr($last_line, 1, 4), '>';
  2207. if ($line == $match[1])
  2208. echo '</pre></div><pre style="margin: 0;">';
  2209. else
  2210. echo "\n";
  2211. }
  2212. echo '</pre></div>';
  2213. }
  2214. echo '
  2215. </body>
  2216. </html>';
  2217. }
  2218. die;
  2219. }
  2220. }
  2221. /**
  2222. * Initialize a database connection.
  2223. */
  2224. function loadDatabase()
  2225. {
  2226. global $db_persist, $db_connection, $db_server, $db_user, $db_passwd;
  2227. global $db_type, $db_name, $ssi_db_user, $ssi_db_passwd, $sourcedir, $db_prefix;
  2228. // Figure out what type of database we are using.
  2229. if (empty($db_type) || !file_exists($sourcedir . '/Subs-Db-' . $db_type . '.php'))
  2230. $db_type = 'mysql';
  2231. // Load the file for the database.
  2232. require_once($sourcedir . '/Subs-Db-' . $db_type . '.php');
  2233. // If we are in SSI try them first, but don't worry if it doesn't work, we have the normal username and password we can use.
  2234. if (SMF == 'SSI' && !empty($ssi_db_user) && !empty($ssi_db_passwd))
  2235. $db_connection = smf_db_initiate($db_server, $db_name, $ssi_db_user, $ssi_db_passwd, $db_prefix, array('persist' => $db_persist, 'non_fatal' => true, 'dont_select_db' => true));
  2236. // Either we aren't in SSI mode, or it failed.
  2237. if (empty($db_connection))
  2238. $db_connection = smf_db_initiate($db_server, $db_name, $db_user, $db_passwd, $db_prefix, array('persist' => $db_persist, 'dont_select_db' => SMF == 'SSI'));
  2239. // Safe guard here, if there isn't a valid connection lets put a stop to it.
  2240. if (!$db_connection)
  2241. display_db_error();
  2242. // If in SSI mode fix up the prefix.
  2243. if (SMF == 'SSI')
  2244. db_fix_prefix($db_prefix, $db_name);
  2245. }
  2246. /**
  2247. * Try to retrieve a cache entry. On failure, call the appropriate function.
  2248. *
  2249. * @param string $key
  2250. * @param string $file
  2251. * @param string $function
  2252. * @param array $params
  2253. * @param int $level = 1
  2254. * @return string
  2255. */
  2256. function cache_quick_get($key, $file, $function, $params, $level = 1)
  2257. {
  2258. global $modSettings, $sourcedir;
  2259. // @todo Why are we doing this if caching is disabled?
  2260. if (function_exists('call_integration_hook'))
  2261. call_integration_hook('pre_cache_quick_get', array(&$key, &$file, &$function, &$params, &$level));
  2262. /* Refresh the cache if either:
  2263. 1. Caching is disabled.
  2264. 2. The cache level isn't high enough.
  2265. 3. The item has not been cached or the cached item expired.
  2266. 4. The cached item has a custom expiration condition evaluating to true.
  2267. 5. The expire time set in the cache item has passed (needed for Zend).
  2268. */
  2269. if (empty($modSettings['cache_enable']) || $modSettings['cache_enable'] < $level || !is_array($cache_block = cache_get_data($key, 3600)) || (!empty($cache_block['refresh_eval']) && eval($cache_block['refresh_eval'])) || (!empty($cache_block['expires']) && $cache_block['expires'] < time()))
  2270. {
  2271. require_once($sourcedir . '/' . $file);
  2272. $cache_block = call_user_func_array($function, $params);
  2273. if (!empty($modSettings['cache_enable']) && $modSettings['cache_enable'] >= $level)
  2274. cache_put_data($key, $cache_block, $cache_block['expires'] - time());
  2275. }
  2276. // Some cached data may need a freshening up after retrieval.
  2277. if (!empty($cache_block['post_retri_eval']))
  2278. eval($cache_block['post_retri_eval']);
  2279. if (function_exists('call_integration_hook'))
  2280. call_integration_hook('post_cache_quick_get', array(&$cache_block));
  2281. return $cache_block['data'];
  2282. }
  2283. /**
  2284. * Puts value in the cache under key for ttl seconds.
  2285. * It may "miss" so shouldn't be depended on, and may go to any of many various caching servers.
  2286. * It supports:
  2287. *
  2288. * Turck MMCache: http://turck-mmcache.sourceforge.net/index_old.html#api
  2289. * Xcache: http://xcache.lighttpd.net/wiki/XcacheApi
  2290. * memcache: http://www.php.net/memcache
  2291. * APC: http://www.php.net/apc
  2292. * eAccelerator: http://bart.eaccelerator.net/doc/phpdoc/
  2293. * Zend: http://files.zend.com/help/Zend-Platform/output_cache_functions.htm
  2294. * Zend: http://files.zend.com/help/Zend-Platform/zend_cache_functions.htm
  2295. *
  2296. * @param string $key
  2297. * @param mixed $value
  2298. * @param int $ttl = 120
  2299. */
  2300. function cache_put_data($key, $value, $ttl = 120)
  2301. {
  2302. global $boardurl, $sourcedir, $modSettings, $memcached;
  2303. global $cache_hits, $cache_count, $db_show_debug, $cachedir;
  2304. global $cache_accelerator, $cache_enable;
  2305. if (empty($cache_enable))
  2306. return;
  2307. $cache_count = isset($cache_count) ? $cache_count + 1 : 1;
  2308. if (isset($db_show_debug) && $db_show_debug === true)
  2309. {
  2310. $cache_hits[$cache_count] = array('k' => $key, 'd' => 'put', 's' => $value === null ? 0 : strlen(serialize($value)));
  2311. $st = microtime();
  2312. }
  2313. $key = md5($boardurl . filemtime($sourcedir . '/Load.php')) . '-SMF-' . strtr($key, ':', '-');
  2314. $value = $value === null ? null : serialize($value);
  2315. switch ($cache_accelerator)
  2316. {
  2317. case 'memcached':
  2318. // The simple yet efficient memcached.
  2319. if (function_exists('memcached_set') || function_exists('memcache_set') && isset($modSettings['cache_memcached']) && trim($modSettings['cache_memcached']) != '')
  2320. {
  2321. // Not connected yet?
  2322. if (empty($memcached))
  2323. get_memcached_server();
  2324. if (!$memcached)
  2325. return;
  2326. memcache_set($memcached, $key, $value, 0, $ttl);
  2327. }
  2328. break;
  2329. case 'eaccelerator':
  2330. // eAccelerator...
  2331. if (function_exists('eaccelerator_put'))
  2332. {
  2333. if (mt_rand(0, 10) == 1)
  2334. eaccelerator_gc();
  2335. if ($value === null)
  2336. @eaccelerator_rm($key);
  2337. else
  2338. eaccelerator_put($key, $value, $ttl);
  2339. }
  2340. break;
  2341. case 'mmcache':
  2342. // Turck MMCache?
  2343. if (function_exists('mmcache_put'))
  2344. {
  2345. if (mt_rand(0, 10) == 1)
  2346. mmcache_gc();
  2347. if ($value === null)
  2348. @mmcache_rm($key);
  2349. else
  2350. {
  2351. mmcache_lock($key);
  2352. mmcache_put($key, $value, $ttl);
  2353. mmcache_unlock($key);
  2354. }
  2355. }
  2356. break;
  2357. case 'apc':
  2358. // Alternative PHP Cache, ahoy!
  2359. if (function_exists('apc_store'))
  2360. {
  2361. // An extended key is needed to counteract a bug in APC.
  2362. if ($value === null)
  2363. apc_delete($key . 'smf');
  2364. else
  2365. apc_store($key . 'smf', $value, $ttl);
  2366. }
  2367. break;
  2368. case 'zend':
  2369. // Zend Platform/ZPS/etc.
  2370. if (function_exists('zend_shm_cache_store'))
  2371. zend_shm_cache_store('SMF::' . $key, $value, $ttl);
  2372. elseif (function_exists('output_cache_put'))
  2373. output_cache_put($key, $value);
  2374. break;
  2375. case 'xcache':
  2376. if (function_exists('xcache_set') && ini_get('xcache.var_size') > 0)
  2377. {
  2378. if ($value === null)
  2379. xcache_unset($key);
  2380. else
  2381. xcache_set($key, $value, $ttl);
  2382. }
  2383. break;
  2384. default:
  2385. // Otherwise custom cache?
  2386. if ($value === null)
  2387. @unlink($cachedir . '/data_' . $key . '.php');
  2388. else
  2389. {
  2390. $cache_data = '<' . '?' . 'php if (!defined(\'SMF\')) die; if (' . (time() + $ttl) . ' < time()) $expired = true; else{$expired = false; $value = \'' . addcslashes($value, '\\\'') . '\';}' . '?' . '>';
  2391. // Write out the cache file, check that the cache write was successful; all the data must be written
  2392. // If it fails due to low diskspace, or other, remove the cache file
  2393. if (file_put_contents($cachedir . '/data_' . $key . '.php', $cache_data, LOCK_EX) !== strlen($cache_data))
  2394. @unlink($cachedir . '/data_' . $key . '.php');
  2395. }
  2396. break;
  2397. }
  2398. if (function_exists('call_integration_hook'))
  2399. call_integration_hook('cache_put_data', array(&$key, &$value, &$ttl));
  2400. if (isset($db_show_debug) && $db_show_debug === true)
  2401. $cache_hits[$cache_count]['t'] = array_sum(explode(' ', microtime())) - array_sum(explode(' ', $st));
  2402. }
  2403. /**
  2404. * Gets the value from the cache specified by key, so long as it is not older than ttl seconds.
  2405. * It may often "miss", so shouldn't be depended on.
  2406. * It supports the same as cache_put_data().
  2407. *
  2408. * @param string $key
  2409. * @param int $ttl = 120
  2410. * @return string
  2411. */
  2412. function cache_get_data($key, $ttl = 120)
  2413. {
  2414. global $boardurl, $sourcedir, $modSettings, $memcached;
  2415. global $cache_hits, $cache_count, $db_show_debug, $cachedir;
  2416. global $cache_accelerator, $cache_enable;
  2417. if (empty($cache_enable))
  2418. return;
  2419. $cache_count = isset($cache_count) ? $cache_count + 1 : 1;
  2420. if (isset($db_show_debug) && $db_show_debug === true)
  2421. {
  2422. $cache_hits[$cache_count] = array('k' => $key, 'd' => 'get');
  2423. $st = microtime();
  2424. }
  2425. $key = md5($boardurl . filemtime($sourcedir . '/Load.php')) . '-SMF-' . strtr($key, ':', '-');
  2426. switch ($cache_accelerator)
  2427. {
  2428. case 'memcache':
  2429. // Okay, let's go for it memcached!
  2430. if ((function_exists('memcache_get') || function_exists('memcached_get')) && isset($modSettings['cache_memcached']) && trim($modSettings['cache_memcached']) != '')
  2431. {
  2432. // Not connected yet?
  2433. if (empty($memcached))
  2434. get_memcached_server();
  2435. if (!$memcached)
  2436. return null;
  2437. $value = (function_exists('memcache_get')) ? memcache_get($cache['connection'], $key) : memcached_get($cache['connection'], $key);
  2438. }
  2439. break;
  2440. case 'eaccelerator':
  2441. // Again, eAccelerator.
  2442. if (function_exists('eaccelerator_get'))
  2443. $value = eaccelerator_get($key);
  2444. break;
  2445. case 'mmcache':
  2446. // The older, but ever-stable, Turck MMCache...
  2447. if (function_exists('mmcache_get'))
  2448. $value = mmcache_get($key);
  2449. break;
  2450. case 'apc':
  2451. // This is the free APC from PECL.
  2452. if (function_exists('apc_fetch'))
  2453. $value = apc_fetch($key . 'smf');
  2454. break;
  2455. case 'zend':
  2456. // Zend's pricey stuff.
  2457. if (function_exists('zend_shm_cache_fetch'))
  2458. $value = zend_shm_cache_fetch('SMF::' . $key, $ttl);
  2459. elseif (function_exists('output_cache_get'))
  2460. $value = output_cache_get($key, $ttl);
  2461. break;
  2462. case 'xcache':
  2463. if (function_exists('xcache_get') && ini_get('xcache.var_size') > 0)
  2464. $value = xcache_get($key);
  2465. break;
  2466. default:
  2467. // Otherwise it's SMF data!
  2468. if (file_exists($cachedir . '/data_' . $key . '.php') && filesize($cachedir . '/data_' . $key . '.php') > 10)
  2469. {
  2470. require($cachedir . '/data_' . $key . '.php');
  2471. if (!empty($expired) && isset($value))
  2472. {
  2473. @unlink($cachedir . '/data_' . $key . '.php');
  2474. unset($value);
  2475. }
  2476. }
  2477. break;
  2478. }
  2479. if (isset($db_show_debug) && $db_show_debug === true)
  2480. {
  2481. $cache_hits[$cache_count]['t'] = array_sum(explode(' ', microtime())) - array_sum(explode(' ', $st));
  2482. $cache_hits[$cache_count]['s'] = isset($value) ? strlen($value) : 0;
  2483. }
  2484. if (function_exists('call_integration_hook'))
  2485. call_integration_hook('cache_get_data', array(&$key, &$ttl, &$value));
  2486. return empty($value) ? null : @unserialize($value);
  2487. }
  2488. /**
  2489. * Get memcache servers.
  2490. * This function is used by cache_get_data() and cache_put_data().
  2491. * It attempts to connect to a random server in the cache_memcached setting.
  2492. * It recursively calls itself up to $level times.
  2493. *
  2494. * @param int $level = 3
  2495. */
  2496. function get_memcached_server($level = 3)
  2497. {
  2498. global $modSettings, $memcached, $db_persist, $cache_memcached;
  2499. $servers = explode(',', $cache_memcached);
  2500. $server = explode(':', trim($servers[array_rand($servers)]));
  2501. $cache = (function_exists('memcache_get')) ? 'memcache' : ((function_exists('memcached_get') ? 'memcached' : ''));
  2502. // Don't try more times than we have servers!
  2503. $level = min(count($servers), $level);
  2504. // Don't wait too long: yes, we want the server, but we might be able to run the query faster!
  2505. if (empty($db_persist))
  2506. {
  2507. if ($cache === 'memcached')
  2508. $memcached = memcached_connect($server[0], empty($server[1]) ? 11211 : $server[1]);
  2509. if ($cache === 'memcache')
  2510. $memcached = memcache_connect($server[0], empty($server[1]) ? 11211 : $server[1]);
  2511. }
  2512. else
  2513. {
  2514. if ($cache === 'memcached')
  2515. $memcached = memcached_pconnect($server[0], empty($server[1]) ? 11211 : $server[1]);
  2516. if ($cache === 'memcache')
  2517. $memcached = memcache_pconnect($server[0], empty($server[1]) ? 11211 : $server[1]);
  2518. }
  2519. if (!$memcached && $level > 0)
  2520. get_memcached_server($level - 1);
  2521. }
  2522. ?>