Load.php 110 KB

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