PageRenderTime 59ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 1ms

/sources/Load.php

https://github.com/Arantor/Elkarte
PHP | 2675 lines | 1871 code | 319 blank | 485 comment | 567 complexity | aa50a9f16e94833f2dd6f37f29c15a9e MD5 | raw file
Possible License(s): BSD-3-Clause, LGPL-3.0

Large files files are truncated, but you can click here to view the full file

  1. <?php
  2. /**
  3. * @name ElkArte Forum
  4. * @copyright ElkArte Forum contributors
  5. * @license BSD http://opensource.org/licenses/BSD-3-Clause
  6. *
  7. * This software is a derived product, based on:
  8. *
  9. * Simple Machines Forum (SMF)
  10. * copyright: 2011 Simple Machines (http://www.simplemachines.org)
  11. * license: BSD, See included LICENSE.TXT for terms and conditions.
  12. *
  13. * @version 1.0 Alpha
  14. *
  15. * This file has the hefty job of loading information for the forum.
  16. *
  17. */
  18. if (!defined('ELKARTE'))
  19. die('No access...');
  20. /**
  21. * Load the $modSettings array.
  22. *
  23. * @global array $modSettings is a giant array of all of the forum-wide settings and statistics.
  24. */
  25. function reloadSettings()
  26. {
  27. global $modSettings, $smcFunc, $txt, $db_character_set, $context;
  28. // Most database systems have not set UTF-8 as their default input charset.
  29. if (!empty($db_character_set))
  30. $smcFunc['db_query']('set_character_set', '
  31. SET NAMES ' . $db_character_set,
  32. array(
  33. )
  34. );
  35. // Try to load it from the cache first; it'll never get cached if the setting is off.
  36. if (($modSettings = cache_get_data('modSettings', 90)) == null)
  37. {
  38. $request = $smcFunc['db_query']('', '
  39. SELECT variable, value
  40. FROM {db_prefix}settings',
  41. array(
  42. )
  43. );
  44. $modSettings = array();
  45. if (!$request)
  46. display_db_error();
  47. while ($row = $smcFunc['db_fetch_row']($request))
  48. $modSettings[$row[0]] = $row[1];
  49. $smcFunc['db_free_result']($request);
  50. // Do a few things to protect against missing settings or settings with invalid values...
  51. if (empty($modSettings['defaultMaxTopics']) || $modSettings['defaultMaxTopics'] <= 0 || $modSettings['defaultMaxTopics'] > 999)
  52. $modSettings['defaultMaxTopics'] = 20;
  53. if (empty($modSettings['defaultMaxMessages']) || $modSettings['defaultMaxMessages'] <= 0 || $modSettings['defaultMaxMessages'] > 999)
  54. $modSettings['defaultMaxMessages'] = 15;
  55. if (empty($modSettings['defaultMaxMembers']) || $modSettings['defaultMaxMembers'] <= 0 || $modSettings['defaultMaxMembers'] > 999)
  56. $modSettings['defaultMaxMembers'] = 30;
  57. if (!empty($modSettings['cache_enable']))
  58. cache_put_data('modSettings', $modSettings, 90);
  59. }
  60. // Set a list of common functions.
  61. $ent_list = empty($modSettings['disableEntityCheck']) ? '&(#\d{1,7}|quot|amp|lt|gt|nbsp);' : '&(#021|quot|amp|lt|gt|nbsp);';
  62. $ent_check = empty($modSettings['disableEntityCheck']) ? array('preg_replace_callback(\'~(&#(\d{1,7}|x[0-9a-fA-F]{1,6});)~\', \'entity_fix__callback\', ', ')') : array('', '');
  63. // Preg_replace space characters
  64. $space_chars = '\x{A0}\x{AD}\x{2000}-\x{200F}\x{201F}\x{202F}\x{3000}\x{FEFF}';
  65. // global array of anonymous helper functions, used mosly to properly handle multi byte strings
  66. $smcFunc += array(
  67. 'entity_fix' => create_function('$string', '
  68. $num = $string[0] === \'x\' ? hexdec(substr($string, 1)) : (int) $string;
  69. return $num < 0x20 || $num > 0x10FFFF || ($num >= 0xD800 && $num <= 0xDFFF) || $num === 0x202E || $num === 0x202D ? \'\' : \'&#\' . $num . \';\';'),
  70. 'htmlspecialchars' => create_function('$string, $quote_style = ENT_COMPAT, $charset = \'UTF-8\'', '
  71. global $smcFunc;
  72. return ' . strtr($ent_check[0], array('&' => '&amp;')) . 'htmlspecialchars($string, $quote_style, \'UTF-8\')' . $ent_check[1] . ';'),
  73. 'htmltrim' => create_function('$string', '
  74. global $smcFunc;
  75. return preg_replace(\'~^(?:[ \t\n\r\x0B\x00' . $space_chars . ']|&nbsp;)+|(?:[ \t\n\r\x0B\x00' . $space_chars . ']|&nbsp;)+$~u\', \'\', ' . implode('$string', $ent_check) . ');'),
  76. 'strlen' => create_function('$string', '
  77. global $smcFunc;
  78. return strlen(preg_replace(\'~' . $ent_list . '|.~u' . '\', \'_\', ' . implode('$string', $ent_check) . '));'),
  79. 'strpos' => create_function('$haystack, $needle, $offset = 0', '
  80. global $smcFunc;
  81. $haystack_arr = preg_split(\'~(&#' . (empty($modSettings['disableEntityCheck']) ? '\d{1,7}' : '021') . ';|&quot;|&amp;|&lt;|&gt;|&nbsp;|.)~u\', ' . implode('$haystack', $ent_check) . ', -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
  82. $haystack_size = count($haystack_arr);
  83. if (strlen($needle) === 1)
  84. {
  85. $result = array_search($needle, array_slice($haystack_arr, $offset));
  86. return is_int($result) ? $result + $offset : false;
  87. }
  88. else
  89. {
  90. $needle_arr = preg_split(\'~(&#' . (empty($modSettings['disableEntityCheck']) ? '\d{1,7}' : '021') . ';|&quot;|&amp;|&lt;|&gt;|&nbsp;|.)~u\', ' . implode('$needle', $ent_check) . ', -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
  91. $needle_size = count($needle_arr);
  92. $result = array_search($needle_arr[0], array_slice($haystack_arr, $offset));
  93. while ((int) $result === $result)
  94. {
  95. $offset += $result;
  96. if (array_slice($haystack_arr, $offset, $needle_size) === $needle_arr)
  97. return $offset;
  98. $result = array_search($needle_arr[0], array_slice($haystack_arr, ++$offset));
  99. }
  100. return false;
  101. }'),
  102. 'substr' => create_function('$string, $start, $length = null', '
  103. global $smcFunc;
  104. $ent_arr = preg_split(\'~(&#' . (empty($modSettings['disableEntityCheck']) ? '\d{1,7}' : '021') . ';|&quot;|&amp;|&lt;|&gt;|&nbsp;|.)~u\', ' . implode('$string', $ent_check) . ', -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
  105. return $length === null ? implode(\'\', array_slice($ent_arr, $start)) : implode(\'\', array_slice($ent_arr, $start, $length));'),
  106. 'strtolower' => function_exists('mb_strtolower') ? create_function('$string', '
  107. return mb_strtolower($string, \'UTF-8\');') : create_function('$string', '
  108. require_once(SUBSDIR . \'/Charset.subs.php\');
  109. return utf8_strtolower($string);'),
  110. 'strtoupper' => function_exists('mb_strtoupper') ? create_function('$string', '
  111. return mb_strtoupper($string, \'UTF-8\');') : create_function('$string', '
  112. require_once(SUBSDIR . \'/Charset.subs.php\');
  113. return utf8_strtoupper($string);'),
  114. 'truncate' => create_function('$string, $length', (empty($modSettings['disableEntityCheck']) ? '
  115. global $smcFunc;
  116. $string = ' . implode('$string', $ent_check) . ';' : '') . '
  117. preg_match(\'~^(' . $ent_list . '|.){\' . $smcFunc[\'strlen\'](substr($string, 0, $length)) . \'}~u\', $string, $matches);
  118. $string = $matches[0];
  119. while (strlen($string) > $length)
  120. $string = preg_replace(\'~(?:' . $ent_list . '|.)$~u\', \'\', $string);
  121. return $string;'),
  122. 'ucfirst' => create_function('$string', '
  123. global $smcFunc;
  124. return $smcFunc[\'strtoupper\']($smcFunc[\'substr\']($string, 0, 1)) . $smcFunc[\'substr\']($string, 1);'),
  125. 'ucwords' => create_function('$string', '
  126. global $smcFunc;
  127. $words = preg_split(\'~([\s\r\n\t]+)~\', $string, -1, PREG_SPLIT_DELIM_CAPTURE);
  128. for ($i = 0, $n = count($words); $i < $n; $i += 2)
  129. $words[$i] = $smcFunc[\'ucfirst\']($words[$i]);
  130. return implode(\'\', $words);'),
  131. );
  132. // Setting the timezone is a requirement for some functions in PHP >= 5.1.
  133. if (isset($modSettings['default_timezone']) && function_exists('date_default_timezone_set'))
  134. date_default_timezone_set($modSettings['default_timezone']);
  135. // Check the load averages?
  136. if (!empty($modSettings['loadavg_enable']))
  137. {
  138. if (($modSettings['load_average'] = cache_get_data('loadavg', 90)) == null)
  139. {
  140. $modSettings['load_average'] = @file_get_contents('/proc/loadavg');
  141. if (!empty($modSettings['load_average']) && preg_match('~^([^ ]+?) ([^ ]+?) ([^ ]+)~', $modSettings['load_average'], $matches) != 0)
  142. $modSettings['load_average'] = (float) $matches[1];
  143. elseif (($modSettings['load_average'] = @`uptime`) != null && preg_match('~load average[s]?: (\d+\.\d+), (\d+\.\d+), (\d+\.\d+)~i', $modSettings['load_average'], $matches) != 0)
  144. $modSettings['load_average'] = (float) $matches[1];
  145. else
  146. unset($modSettings['load_average']);
  147. if (!empty($modSettings['load_average']))
  148. cache_put_data('loadavg', $modSettings['load_average'], 90);
  149. }
  150. if (!empty($modSettings['load_average']))
  151. call_integration_hook('integrate_load_average', array($modSettings['load_average']));
  152. if (!empty($modSettings['loadavg_forum']) && !empty($modSettings['load_average']) && $modSettings['load_average'] >= $modSettings['loadavg_forum'])
  153. display_loadavg_error();
  154. }
  155. // Is post moderation alive and well?
  156. $modSettings['postmod_active'] = isset($modSettings['admin_features']) ? in_array('pm', explode(',', $modSettings['admin_features'])) : true;
  157. // Here to justify the name of this function. :P
  158. // It should be added to the install and upgrade scripts.
  159. // But since the convertors need to be updated also. This is easier.
  160. if (empty($modSettings['currentAttachmentUploadDir']))
  161. {
  162. updateSettings(array(
  163. 'attachmentUploadDir' => serialize(array(1 => $modSettings['attachmentUploadDir'])),
  164. 'currentAttachmentUploadDir' => 1,
  165. ));
  166. }
  167. // Integration is cool.
  168. if (defined('ELKARTE_INTEGRATION_SETTINGS'))
  169. {
  170. $integration_settings = unserialize(ELKARTE_INTEGRATION_SETTINGS);
  171. foreach ($integration_settings as $hook => $function)
  172. add_integration_function($hook, $function, false);
  173. }
  174. // Any files to pre include?
  175. if (!empty($modSettings['integrate_pre_include']))
  176. {
  177. $pre_includes = explode(',', $modSettings['integrate_pre_include']);
  178. foreach ($pre_includes as $include)
  179. {
  180. $include = strtr(trim($include), array('BOARDDIR' => BOARDDIR, 'SOURCEDIR' => SOURCEDIR, 'SUBSDIR' => SUBSDIR));
  181. if (file_exists($include))
  182. require_once($include);
  183. }
  184. }
  185. // Call pre load integration functions.
  186. call_integration_hook('integrate_pre_load');
  187. }
  188. /**
  189. * Load all the important user information.
  190. * What it does:
  191. * - sets up the $user_info array
  192. * - assigns $user_info['query_wanna_see_board'] for what boards the user can see.
  193. * - first checks for cookie or integration validation.
  194. * - uses the current session if no integration function or cookie is found.
  195. * - checks password length, if member is activated and the login span isn't over.
  196. * - if validation fails for the user, $id_member is set to 0.
  197. * - updates the last visit time when needed.
  198. */
  199. function loadUserSettings()
  200. {
  201. global $modSettings, $user_settings, $smcFunc, $settings;
  202. global $cookiename, $user_info, $language, $context;
  203. // Check first the integration, then the cookie, and last the session.
  204. if (count($integration_ids = call_integration_hook('integrate_verify_user')) > 0)
  205. {
  206. $id_member = 0;
  207. foreach ($integration_ids as $integration_id)
  208. {
  209. $integration_id = (int) $integration_id;
  210. if ($integration_id > 0)
  211. {
  212. $id_member = $integration_id;
  213. $already_verified = true;
  214. break;
  215. }
  216. }
  217. }
  218. else
  219. $id_member = 0;
  220. if (empty($id_member) && isset($_COOKIE[$cookiename]))
  221. {
  222. // Fix a security hole in PHP 4.3.9 and below...
  223. 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)
  224. {
  225. list ($id_member, $password) = @unserialize($_COOKIE[$cookiename]);
  226. $id_member = !empty($id_member) && strlen($password) > 0 ? (int) $id_member : 0;
  227. }
  228. else
  229. $id_member = 0;
  230. }
  231. elseif (empty($id_member) && isset($_SESSION['login_' . $cookiename]) && ($_SESSION['USER_AGENT'] == $_SERVER['HTTP_USER_AGENT'] || !empty($modSettings['disableCheckUA'])))
  232. {
  233. // @todo Perhaps we can do some more checking on this, such as on the first octet of the IP?
  234. list ($id_member, $password, $login_span) = @unserialize($_SESSION['login_' . $cookiename]);
  235. $id_member = !empty($id_member) && strlen($password) == 40 && $login_span > time() ? (int) $id_member : 0;
  236. }
  237. // Only load this stuff if the user isn't a guest.
  238. if ($id_member != 0)
  239. {
  240. // Is the member data cached?
  241. if (empty($modSettings['cache_enable']) || $modSettings['cache_enable'] < 2 || ($user_settings = cache_get_data('user_settings-' . $id_member, 60)) == null)
  242. {
  243. $request = $smcFunc['db_query']('', '
  244. SELECT mem.*, IFNULL(a.id_attach, 0) AS id_attach, a.filename, a.attachment_type
  245. FROM {db_prefix}members AS mem
  246. LEFT JOIN {db_prefix}attachments AS a ON (a.id_member = {int:id_member})
  247. WHERE mem.id_member = {int:id_member}
  248. LIMIT 1',
  249. array(
  250. 'id_member' => $id_member,
  251. )
  252. );
  253. $user_settings = $smcFunc['db_fetch_assoc']($request);
  254. $smcFunc['db_free_result']($request);
  255. if(!empty($modSettings['avatar_default']) && empty($user_settings['avatar']) && empty($user_settings['filename']))
  256. $user_settings['avatar'] = $settings['images_url'] . '/default_avatar.png';
  257. if (!empty($modSettings['cache_enable']) && $modSettings['cache_enable'] >= 2)
  258. cache_put_data('user_settings-' . $id_member, $user_settings, 60);
  259. }
  260. // Did we find 'im? If not, junk it.
  261. if (!empty($user_settings))
  262. {
  263. // As much as the password should be right, we can assume the integration set things up.
  264. if (!empty($already_verified) && $already_verified === true)
  265. $check = true;
  266. // SHA-1 passwords should be 40 characters long.
  267. elseif (strlen($password) == 40)
  268. $check = sha1($user_settings['passwd'] . $user_settings['password_salt']) == $password;
  269. else
  270. $check = false;
  271. // Wrong password or not activated - either way, you're going nowhere.
  272. $id_member = $check && ($user_settings['is_activated'] == 1 || $user_settings['is_activated'] == 11) ? $user_settings['id_member'] : 0;
  273. }
  274. else
  275. $id_member = 0;
  276. // If we no longer have the member maybe they're being all hackey, stop brute force!
  277. if (!$id_member)
  278. 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);
  279. }
  280. // Found 'im, let's set up the variables.
  281. if ($id_member != 0)
  282. {
  283. // Let's not update the last visit time in these cases...
  284. // 1. SSI doesn't count as visiting the forum.
  285. // 2. RSS feeds and XMLHTTP requests don't count either.
  286. // 3. If it was set within this session, no need to set it again.
  287. // 4. New session, yet updated < five hours ago? Maybe cache can help.
  288. if (ELKARTE != '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))
  289. {
  290. // @todo can this be cached?
  291. // Do a quick query to make sure this isn't a mistake.
  292. $result = $smcFunc['db_query']('', '
  293. SELECT poster_time
  294. FROM {db_prefix}messages
  295. WHERE id_msg = {int:id_msg}
  296. LIMIT 1',
  297. array(
  298. 'id_msg' => $user_settings['id_msg_last_visit'],
  299. )
  300. );
  301. list ($visitTime) = $smcFunc['db_fetch_row']($result);
  302. $smcFunc['db_free_result']($result);
  303. $_SESSION['id_msg_last_visit'] = $user_settings['id_msg_last_visit'];
  304. // If it was *at least* five hours ago...
  305. if ($visitTime < time() - 5 * 3600)
  306. {
  307. 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']));
  308. $user_settings['last_login'] = time();
  309. if (!empty($modSettings['cache_enable']) && $modSettings['cache_enable'] >= 2)
  310. cache_put_data('user_settings-' . $id_member, $user_settings, 60);
  311. if (!empty($modSettings['cache_enable']))
  312. cache_put_data('user_last_visit-' . $id_member, $_SESSION['id_msg_last_visit'], 5 * 3600);
  313. }
  314. }
  315. elseif (empty($_SESSION['id_msg_last_visit']))
  316. $_SESSION['id_msg_last_visit'] = $user_settings['id_msg_last_visit'];
  317. $username = $user_settings['member_name'];
  318. if (empty($user_settings['additional_groups']))
  319. $user_info = array(
  320. 'groups' => array($user_settings['id_group'], $user_settings['id_post_group'])
  321. );
  322. else
  323. $user_info = array(
  324. 'groups' => array_merge(
  325. array($user_settings['id_group'], $user_settings['id_post_group']),
  326. explode(',', $user_settings['additional_groups'])
  327. )
  328. );
  329. // Because history has proven that it is possible for groups to go bad - clean up in case.
  330. foreach ($user_info['groups'] as $k => $v)
  331. $user_info['groups'][$k] = (int) $v;
  332. // This is a logged in user, so definitely not a spider.
  333. $user_info['possibly_robot'] = false;
  334. }
  335. // If the user is a guest, initialize all the critical user settings.
  336. else
  337. {
  338. // This is what a guest's variables should be.
  339. $username = '';
  340. $user_info = array('groups' => array(-1));
  341. $user_settings = array();
  342. if (isset($_COOKIE[$cookiename]))
  343. $_COOKIE[$cookiename] = '';
  344. // Create a login token if it doesn't exist yet.
  345. if (!isset($_SESSION['token']['post-login']))
  346. createToken('login');
  347. else
  348. list ($context['login_token_var'],,, $context['login_token']) = $_SESSION['token']['post-login'];
  349. // Do we perhaps think this is a search robot? Check every five minutes just in case...
  350. if ((!empty($modSettings['spider_mode']) || !empty($modSettings['spider_group'])) && (!isset($_SESSION['robot_check']) || $_SESSION['robot_check'] < time() - 300))
  351. {
  352. require_once(SUBSDIR . '/SearchEngines.subs.php');
  353. $user_info['possibly_robot'] = spiderCheck();
  354. }
  355. elseif (!empty($modSettings['spider_mode']))
  356. $user_info['possibly_robot'] = isset($_SESSION['id_robot']) ? $_SESSION['id_robot'] : 0;
  357. // If we haven't turned on proper spider hunts then have a guess!
  358. else
  359. {
  360. $ci_user_agent = strtolower($_SERVER['HTTP_USER_AGENT']);
  361. $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 || strpos($ci_user_agent, 'msnbot') !== false;
  362. }
  363. }
  364. // Set up the $user_info array.
  365. $user_info += array(
  366. 'id' => $id_member,
  367. 'username' => $username,
  368. 'name' => isset($user_settings['real_name']) ? $user_settings['real_name'] : '',
  369. 'email' => isset($user_settings['email_address']) ? $user_settings['email_address'] : '',
  370. 'passwd' => isset($user_settings['passwd']) ? $user_settings['passwd'] : '',
  371. 'language' => empty($user_settings['lngfile']) || empty($modSettings['userLanguage']) ? $language : $user_settings['lngfile'],
  372. 'is_guest' => $id_member == 0,
  373. 'is_admin' => in_array(1, $user_info['groups']),
  374. 'theme' => empty($user_settings['id_theme']) ? 0 : $user_settings['id_theme'],
  375. 'last_login' => empty($user_settings['last_login']) ? 0 : $user_settings['last_login'],
  376. 'ip' => $_SERVER['REMOTE_ADDR'],
  377. 'ip2' => $_SERVER['BAN_CHECK_IP'],
  378. 'posts' => empty($user_settings['posts']) ? 0 : $user_settings['posts'],
  379. 'time_format' => empty($user_settings['time_format']) ? $modSettings['time_format'] : $user_settings['time_format'],
  380. 'time_offset' => empty($user_settings['time_offset']) ? 0 : $user_settings['time_offset'],
  381. 'avatar' => array(
  382. 'url' => isset($user_settings['avatar']) ? $user_settings['avatar'] : '',
  383. 'filename' => empty($user_settings['filename']) ? '' : $user_settings['filename'],
  384. 'custom_dir' => !empty($user_settings['attachment_type']) && $user_settings['attachment_type'] == 1,
  385. 'id_attach' => isset($user_settings['id_attach']) ? $user_settings['id_attach'] : 0
  386. ),
  387. 'smiley_set' => isset($user_settings['smiley_set']) ? $user_settings['smiley_set'] : '',
  388. 'messages' => empty($user_settings['instant_messages']) ? 0 : $user_settings['instant_messages'],
  389. 'unread_messages' => empty($user_settings['unread_messages']) ? 0 : $user_settings['unread_messages'],
  390. 'total_time_logged_in' => empty($user_settings['total_time_logged_in']) ? 0 : $user_settings['total_time_logged_in'],
  391. 'buddies' => !empty($modSettings['enable_buddylist']) && !empty($user_settings['buddy_list']) ? explode(',', $user_settings['buddy_list']) : array(),
  392. 'ignoreboards' => !empty($user_settings['ignore_boards']) && !empty($modSettings['allow_ignore_boards']) ? explode(',', $user_settings['ignore_boards']) : array(),
  393. 'ignoreusers' => !empty($user_settings['pm_ignore_list']) ? explode(',', $user_settings['pm_ignore_list']) : array(),
  394. 'warning' => isset($user_settings['warning']) ? $user_settings['warning'] : 0,
  395. 'permissions' => array(),
  396. );
  397. $user_info['groups'] = array_unique($user_info['groups']);
  398. // 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.
  399. if (!empty($user_info['ignoreboards']) && empty($user_info['ignoreboards'][$tmp = count($user_info['ignoreboards']) - 1]))
  400. unset($user_info['ignoreboards'][$tmp]);
  401. // Do we have any languages to validate this?
  402. if (!empty($modSettings['userLanguage']) && (!empty($_GET['language']) || !empty($_SESSION['language'])))
  403. $languages = getLanguages();
  404. // Allow the user to change their language if its valid.
  405. if (!empty($modSettings['userLanguage']) && !empty($_GET['language']) && isset($languages[strtr($_GET['language'], './\\:', '____')]))
  406. {
  407. $user_info['language'] = strtr($_GET['language'], './\\:', '____');
  408. $_SESSION['language'] = $user_info['language'];
  409. }
  410. elseif (!empty($modSettings['userLanguage']) && !empty($_SESSION['language']) && isset($languages[strtr($_SESSION['language'], './\\:', '____')]))
  411. $user_info['language'] = strtr($_SESSION['language'], './\\:', '____');
  412. // Just build this here, it makes it easier to change/use - administrators can see all boards.
  413. if ($user_info['is_admin'])
  414. $user_info['query_see_board'] = '1=1';
  415. // Otherwise just the groups in $user_info['groups'].
  416. else
  417. $user_info['query_see_board'] = '((FIND_IN_SET(' . implode(', b.member_groups) != 0 OR FIND_IN_SET(', $user_info['groups']) . ', b.member_groups) != 0)' . (!empty($modSettings['deny_boards_access']) ? ' AND (FIND_IN_SET(' . implode(', b.deny_member_groups) = 0 AND FIND_IN_SET(', $user_info['groups']) . ', b.deny_member_groups) = 0)' : '') . (isset($user_info['mod_cache']) ? ' OR ' . $user_info['mod_cache']['mq'] : '') . ')';
  418. // Build the list of boards they WANT to see.
  419. // This will take the place of query_see_boards in certain spots, so it better include the boards they can see also
  420. // If they aren't ignoring any boards then they want to see all the boards they can see
  421. if (empty($user_info['ignoreboards']))
  422. $user_info['query_wanna_see_board'] = $user_info['query_see_board'];
  423. // Ok I guess they don't want to see all the boards
  424. else
  425. $user_info['query_wanna_see_board'] = '(' . $user_info['query_see_board'] . ' AND b.id_board NOT IN (' . implode(',', $user_info['ignoreboards']) . '))';
  426. call_integration_hook('integrate_user_info');
  427. }
  428. /**
  429. * Check for moderators and see if they have access to the board.
  430. * What it does:
  431. * - sets up the $board_info array for current board information.
  432. * - if cache is enabled, the $board_info array is stored in cache.
  433. * - redirects to appropriate post if only message id is requested.
  434. * - is only used when inside a topic or board.
  435. * - determines the local moderators for the board.
  436. * - adds group id 3 if the user is a local moderator for the board they are in.
  437. * - prevents access if user is not in proper group nor a local moderator of the board.
  438. */
  439. function loadBoard()
  440. {
  441. global $txt, $scripturl, $context, $modSettings;
  442. global $board_info, $board, $topic, $user_info, $smcFunc;
  443. // Assume they are not a moderator.
  444. $user_info['is_mod'] = false;
  445. $context['user']['is_mod'] = &$user_info['is_mod'];
  446. // Start the linktree off empty..
  447. $context['linktree'] = array();
  448. // Have they by chance specified a message id but nothing else?
  449. if (empty($_REQUEST['action']) && empty($topic) && empty($board) && !empty($_REQUEST['msg']))
  450. {
  451. // Make sure the message id is really an int.
  452. $_REQUEST['msg'] = (int) $_REQUEST['msg'];
  453. // Looking through the message table can be slow, so try using the cache first.
  454. if (($topic = cache_get_data('msg_topic-' . $_REQUEST['msg'], 120)) === NULL)
  455. {
  456. $request = $smcFunc['db_query']('', '
  457. SELECT id_topic
  458. FROM {db_prefix}messages
  459. WHERE id_msg = {int:id_msg}
  460. LIMIT 1',
  461. array(
  462. 'id_msg' => $_REQUEST['msg'],
  463. )
  464. );
  465. // So did it find anything?
  466. if ($smcFunc['db_num_rows']($request))
  467. {
  468. list ($topic) = $smcFunc['db_fetch_row']($request);
  469. $smcFunc['db_free_result']($request);
  470. // Save save save.
  471. cache_put_data('msg_topic-' . $_REQUEST['msg'], $topic, 120);
  472. }
  473. }
  474. // Remember redirection is the key to avoiding fallout from your bosses.
  475. if (!empty($topic))
  476. redirectexit('topic=' . $topic . '.msg' . $_REQUEST['msg'] . '#msg' . $_REQUEST['msg']);
  477. else
  478. {
  479. loadPermissions();
  480. loadTheme();
  481. fatal_lang_error('topic_gone', false);
  482. }
  483. }
  484. // Load this board only if it is specified.
  485. if (empty($board) && empty($topic))
  486. {
  487. $board_info = array('moderators' => array());
  488. return;
  489. }
  490. if (!empty($modSettings['cache_enable']) && (empty($topic) || $modSettings['cache_enable'] >= 3))
  491. {
  492. // @todo SLOW?
  493. if (!empty($topic))
  494. $temp = cache_get_data('topic_board-' . $topic, 120);
  495. else
  496. $temp = cache_get_data('board-' . $board, 120);
  497. if (!empty($temp))
  498. {
  499. $board_info = $temp;
  500. $board = $board_info['id'];
  501. }
  502. }
  503. if (empty($temp))
  504. {
  505. $request = $smcFunc['db_query']('', '
  506. SELECT
  507. c.id_cat, b.name AS bname, b.description, b.num_topics, b.member_groups, b.deny_member_groups,
  508. b.id_parent, c.name AS cname, IFNULL(mem.id_member, 0) AS id_moderator,
  509. mem.real_name' . (!empty($topic) ? ', b.id_board' : '') . ', b.child_level,
  510. b.id_theme, b.override_theme, b.count_posts, b.id_profile, b.redirect,
  511. b.unapproved_topics, b.unapproved_posts' . (!empty($topic) ? ', t.approved, t.id_member_started' : '') . '
  512. FROM {db_prefix}boards AS b' . (!empty($topic) ? '
  513. INNER JOIN {db_prefix}topics AS t ON (t.id_topic = {int:current_topic})' : '') . '
  514. LEFT JOIN {db_prefix}categories AS c ON (c.id_cat = b.id_cat)
  515. LEFT JOIN {db_prefix}moderators AS mods ON (mods.id_board = {raw:board_link})
  516. LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = mods.id_member)
  517. WHERE b.id_board = {raw:board_link}',
  518. array(
  519. 'current_topic' => $topic,
  520. 'board_link' => empty($topic) ? $smcFunc['db_quote']('{int:current_board}', array('current_board' => $board)) : 't.id_board',
  521. )
  522. );
  523. // If there aren't any, skip.
  524. if ($smcFunc['db_num_rows']($request) > 0)
  525. {
  526. $row = $smcFunc['db_fetch_assoc']($request);
  527. // Set the current board.
  528. if (!empty($row['id_board']))
  529. $board = $row['id_board'];
  530. // Basic operating information. (globals... :/)
  531. $board_info = array(
  532. 'id' => $board,
  533. 'moderators' => array(),
  534. 'cat' => array(
  535. 'id' => $row['id_cat'],
  536. 'name' => $row['cname']
  537. ),
  538. 'name' => $row['bname'],
  539. 'description' => $row['description'],
  540. 'num_topics' => $row['num_topics'],
  541. 'unapproved_topics' => $row['unapproved_topics'],
  542. 'unapproved_posts' => $row['unapproved_posts'],
  543. 'unapproved_user_topics' => 0,
  544. 'parent_boards' => getBoardParents($row['id_parent']),
  545. 'parent' => $row['id_parent'],
  546. 'child_level' => $row['child_level'],
  547. 'theme' => $row['id_theme'],
  548. 'override_theme' => !empty($row['override_theme']),
  549. 'profile' => $row['id_profile'],
  550. 'redirect' => $row['redirect'],
  551. 'posts_count' => empty($row['count_posts']),
  552. 'cur_topic_approved' => empty($topic) || $row['approved'],
  553. 'cur_topic_starter' => empty($topic) ? 0 : $row['id_member_started'],
  554. );
  555. // Load the membergroups allowed, and check permissions.
  556. $board_info['groups'] = $row['member_groups'] == '' ? array() : explode(',', $row['member_groups']);
  557. $board_info['deny_groups'] = $row['deny_member_groups'] == '' ? array() : explode(',', $row['deny_member_groups']);
  558. do
  559. {
  560. if (!empty($row['id_moderator']))
  561. $board_info['moderators'][$row['id_moderator']] = array(
  562. 'id' => $row['id_moderator'],
  563. 'name' => $row['real_name'],
  564. 'href' => $scripturl . '?action=profile;u=' . $row['id_moderator'],
  565. 'link' => '<a href="' . $scripturl . '?action=profile;u=' . $row['id_moderator'] . '">' . $row['real_name'] . '</a>'
  566. );
  567. }
  568. while ($row = $smcFunc['db_fetch_assoc']($request));
  569. // If the board only contains unapproved posts and the user isn't an approver then they can't see any topics.
  570. // If that is the case do an additional check to see if they have any topics waiting to be approved.
  571. if ($board_info['num_topics'] == 0 && $modSettings['postmod_active'] && !allowedTo('approve_posts'))
  572. {
  573. // Free the previous result
  574. $smcFunc['db_free_result']($request);
  575. // @todo why is this using id_topic?
  576. // @todo Can this get cached?
  577. $request = $smcFunc['db_query']('', '
  578. SELECT COUNT(id_topic)
  579. FROM {db_prefix}topics
  580. WHERE id_member_started={int:id_member}
  581. AND approved = {int:unapproved}
  582. AND id_board = {int:board}',
  583. array(
  584. 'id_member' => $user_info['id'],
  585. 'unapproved' => 0,
  586. 'board' => $board,
  587. )
  588. );
  589. list ($board_info['unapproved_user_topics']) = $smcFunc['db_fetch_row']($request);
  590. }
  591. if (!empty($modSettings['cache_enable']) && (empty($topic) || $modSettings['cache_enable'] >= 3))
  592. {
  593. // @todo SLOW?
  594. if (!empty($topic))
  595. cache_put_data('topic_board-' . $topic, $board_info, 120);
  596. cache_put_data('board-' . $board, $board_info, 120);
  597. }
  598. }
  599. else
  600. {
  601. // Otherwise the topic is invalid, there are no moderators, etc.
  602. $board_info = array(
  603. 'moderators' => array(),
  604. 'error' => 'exist'
  605. );
  606. $topic = null;
  607. $board = 0;
  608. }
  609. $smcFunc['db_free_result']($request);
  610. }
  611. if (!empty($topic))
  612. $_GET['board'] = (int) $board;
  613. if (!empty($board))
  614. {
  615. // Now check if the user is a moderator.
  616. $user_info['is_mod'] = isset($board_info['moderators'][$user_info['id']]);
  617. if (count(array_intersect($user_info['groups'], $board_info['groups'])) == 0 && !$user_info['is_admin'])
  618. $board_info['error'] = 'access';
  619. if (!empty($modSettings['deny_boards_access']) && count(array_intersect($user_info['groups'], $board_info['deny_groups'])) != 0 && !$user_info['is_admin'])
  620. $board_info['error'] = 'access';
  621. // Build up the linktree.
  622. $context['linktree'] = array_merge(
  623. $context['linktree'],
  624. array(array(
  625. 'url' => $scripturl . '#c' . $board_info['cat']['id'],
  626. 'name' => $board_info['cat']['name']
  627. )),
  628. array_reverse($board_info['parent_boards']),
  629. array(array(
  630. 'url' => $scripturl . '?board=' . $board . '.0',
  631. 'name' => $board_info['name']
  632. ))
  633. );
  634. }
  635. // Set the template contextual information.
  636. $context['user']['is_mod'] = &$user_info['is_mod'];
  637. $context['current_topic'] = $topic;
  638. $context['current_board'] = $board;
  639. // Hacker... you can't see this topic, I'll tell you that. (but moderators can!)
  640. if (!empty($board_info['error']) && (!empty($modSettings['deny_boards_access']) || $board_info['error'] != 'access' || !$user_info['is_mod']))
  641. {
  642. // The permissions and theme need loading, just to make sure everything goes smoothly.
  643. loadPermissions();
  644. loadTheme();
  645. $_GET['board'] = '';
  646. $_GET['topic'] = '';
  647. // The linktree should not give the game away mate!
  648. $context['linktree'] = array(
  649. array(
  650. 'url' => $scripturl,
  651. 'name' => $context['forum_name_html_safe']
  652. )
  653. );
  654. // If it's a prefetching agent or we're requesting an attachment.
  655. if ((isset($_SERVER['HTTP_X_MOZ']) && $_SERVER['HTTP_X_MOZ'] == 'prefetch') || (!empty($_REQUEST['action']) && $_REQUEST['action'] === 'dlattach'))
  656. {
  657. ob_end_clean();
  658. header('HTTP/1.1 403 Forbidden');
  659. die;
  660. }
  661. elseif ($user_info['is_guest'])
  662. {
  663. loadLanguage('Errors');
  664. is_not_guest($txt['topic_gone']);
  665. }
  666. else
  667. fatal_lang_error('topic_gone', false);
  668. }
  669. if ($user_info['is_mod'])
  670. $user_info['groups'][] = 3;
  671. }
  672. /**
  673. * Load this user's permissions.
  674. *
  675. */
  676. function loadPermissions()
  677. {
  678. global $user_info, $board, $board_info, $modSettings, $smcFunc;
  679. if ($user_info['is_admin'])
  680. {
  681. banPermissions();
  682. return;
  683. }
  684. if (!empty($modSettings['cache_enable']))
  685. {
  686. $cache_groups = $user_info['groups'];
  687. asort($cache_groups);
  688. $cache_groups = implode(',', $cache_groups);
  689. // If it's a spider then cache it different.
  690. if ($user_info['possibly_robot'])
  691. $cache_groups .= '-spider';
  692. if ($modSettings['cache_enable'] >= 2 && !empty($board) && ($temp = cache_get_data('permissions:' . $cache_groups . ':' . $board, 240)) != null && time() - 240 > $modSettings['settings_updated'])
  693. {
  694. list ($user_info['permissions']) = $temp;
  695. banPermissions();
  696. return;
  697. }
  698. elseif (($temp = cache_get_data('permissions:' . $cache_groups, 240)) != null && time() - 240 > $modSettings['settings_updated'])
  699. list ($user_info['permissions'], $removals) = $temp;
  700. }
  701. // If it is detected as a robot, and we are restricting permissions as a special group - then implement this.
  702. $spider_restrict = $user_info['possibly_robot'] && !empty($modSettings['spider_group']) ? ' OR (id_group = {int:spider_group} AND add_deny = 0)' : '';
  703. if (empty($user_info['permissions']))
  704. {
  705. // Get the general permissions.
  706. $request = $smcFunc['db_query']('', '
  707. SELECT permission, add_deny
  708. FROM {db_prefix}permissions
  709. WHERE id_group IN ({array_int:member_groups})
  710. ' . $spider_restrict,
  711. array(
  712. 'member_groups' => $user_info['groups'],
  713. 'spider_group' => !empty($modSettings['spider_group']) ? $modSettings['spider_group'] : 0,
  714. )
  715. );
  716. $removals = array();
  717. while ($row = $smcFunc['db_fetch_assoc']($request))
  718. {
  719. if (empty($row['add_deny']))
  720. $removals[] = $row['permission'];
  721. else
  722. $user_info['permissions'][] = $row['permission'];
  723. }
  724. $smcFunc['db_free_result']($request);
  725. if (isset($cache_groups))
  726. cache_put_data('permissions:' . $cache_groups, array($user_info['permissions'], $removals), 240);
  727. }
  728. // Get the board permissions.
  729. if (!empty($board))
  730. {
  731. // Make sure the board (if any) has been loaded by loadBoard().
  732. if (!isset($board_info['profile']))
  733. fatal_lang_error('no_board');
  734. $request = $smcFunc['db_query']('', '
  735. SELECT permission, add_deny
  736. FROM {db_prefix}board_permissions
  737. WHERE (id_group IN ({array_int:member_groups})
  738. ' . $spider_restrict . ')
  739. AND id_profile = {int:id_profile}',
  740. array(
  741. 'member_groups' => $user_info['groups'],
  742. 'id_profile' => $board_info['profile'],
  743. 'spider_group' => !empty($modSettings['spider_group']) ? $modSettings['spider_group'] : 0,
  744. )
  745. );
  746. while ($row = $smcFunc['db_fetch_assoc']($request))
  747. {
  748. if (empty($row['add_deny']))
  749. $removals[] = $row['permission'];
  750. else
  751. $user_info['permissions'][] = $row['permission'];
  752. }
  753. $smcFunc['db_free_result']($request);
  754. }
  755. // Remove all the permissions they shouldn't have ;).
  756. if (!empty($modSettings['permission_enable_deny']))
  757. $user_info['permissions'] = array_diff($user_info['permissions'], $removals);
  758. if (isset($cache_groups) && !empty($board) && $modSettings['cache_enable'] >= 2)
  759. cache_put_data('permissions:' . $cache_groups . ':' . $board, array($user_info['permissions'], null), 240);
  760. // Banned? Watch, don't touch..
  761. banPermissions();
  762. // Load the mod cache so we can know what additional boards they should see, but no sense in doing it for guests
  763. if (!$user_info['is_guest'])
  764. {
  765. if (!isset($_SESSION['mc']) || $_SESSION['mc']['time'] <= $modSettings['settings_updated'])
  766. {
  767. require_once(SUBSDIR . '/Auth.subs.php');
  768. rebuildModCache();
  769. }
  770. else
  771. $user_info['mod_cache'] = $_SESSION['mc'];
  772. }
  773. }
  774. /**
  775. * Loads an array of users' data by ID or member_name.
  776. *
  777. * @param mixed $users An array of users by id or name
  778. * @param bool $is_name = false $users is by name or by id
  779. * @param string $set = 'normal' What kind of data to load (normal, profile, minimal)
  780. * @return array|bool The ids of the members loaded or false
  781. */
  782. function loadMemberData($users, $is_name = false, $set = 'normal')
  783. {
  784. global $user_profile, $modSettings, $board_info, $smcFunc, $context;
  785. // Can't just look for no users :P.
  786. if (empty($users))
  787. return false;
  788. // Pass the set value
  789. $context['loadMemberContext_set'] = $set;
  790. // Make sure it's an array.
  791. $users = !is_array($users) ? array($users) : array_unique($users);
  792. $loaded_ids = array();
  793. if (!$is_name && !empty($modSettings['cache_enable']) && $modSettings['cache_enable'] >= 3)
  794. {
  795. $users = array_values($users);
  796. for ($i = 0, $n = count($users); $i < $n; $i++)
  797. {
  798. $data = cache_get_data('member_data-' . $set . '-' . $users[$i], 240);
  799. if ($data == null)
  800. continue;
  801. $loaded_ids[] = $data['id_member'];
  802. $user_profile[$data['id_member']] = $data;
  803. unset($users[$i]);
  804. }
  805. }
  806. // Used by default
  807. $select_columns = '
  808. IFNULL(lo.log_time, 0) AS is_online, IFNULL(a.id_attach, 0) AS id_attach, a.filename, a.attachment_type,
  809. mem.signature, mem.personal_text, mem.location, mem.gender, mem.avatar, mem.id_member, mem.member_name,
  810. mem.real_name, mem.email_address, mem.hide_email, mem.date_registered, mem.website_title, mem.website_url,
  811. mem.birthdate, mem.member_ip, mem.member_ip2, mem.posts, mem.last_login,
  812. mem.karma_good, mem.id_post_group, mem.karma_bad, mem.lngfile, mem.id_group, mem.time_offset, mem.show_online,
  813. mg.online_color AS member_group_color, IFNULL(mg.group_name, {string:blank_string}) AS member_group,
  814. pg.online_color AS post_group_color, IFNULL(pg.group_name, {string:blank_string}) AS post_group,
  815. mem.is_activated, mem.warning' . (!empty($modSettings['titlesEnable']) ? ', mem.usertitle, ' : '') . '
  816. CASE WHEN mem.id_group = 0 OR mg.icons = {string:blank_string} THEN pg.icons ELSE mg.icons END AS icons';
  817. $select_tables = '
  818. LEFT JOIN {db_prefix}log_online AS lo ON (lo.id_member = mem.id_member)
  819. LEFT JOIN {db_prefix}attachments AS a ON (a.id_member = mem.id_member)
  820. LEFT JOIN {db_prefix}membergroups AS pg ON (pg.id_group = mem.id_post_group)
  821. LEFT JOIN {db_prefix}membergroups AS mg ON (mg.id_group = mem.id_group)';
  822. // We add or replace according to the set
  823. switch ($set)
  824. {
  825. case 'normal':
  826. $select_columns .= ', mem.buddy_list';
  827. break;
  828. case 'profile':
  829. $select_columns .= ', mem.openid_uri, mem.id_theme, mem.pm_ignore_list, mem.pm_email_notify, mem.pm_receive_from,
  830. mem.time_format, mem.secret_question, mem.additional_groups, mem.smiley_set,
  831. mem.total_time_logged_in, mem.notify_announcements, mem.notify_regularity, mem.notify_send_body,
  832. mem.notify_types, lo.url, mem.ignore_boards, mem.password_salt, mem.pm_prefs, mem.buddy_list';
  833. break;
  834. case 'minimal':
  835. $select_columns = '
  836. mem.id_member, mem.member_name, mem.real_name, mem.email_address, mem.hide_email, mem.date_registered,
  837. mem.posts, mem.last_login, mem.member_ip, mem.member_ip2, mem.lngfile, mem.id_group';
  838. $select_tables = '';
  839. break;
  840. default:
  841. trigger_error('loadMemberData(): Invalid member data set \'' . $set . '\'', E_USER_WARNING);
  842. }
  843. // Allow mods to easily add to the selected member data
  844. call_integration_hook('integrate_load_member_data', array($select_columns, $select_tables, $set));
  845. if (!empty($users))
  846. {
  847. // Load the member's data.
  848. $request = $smcFunc['db_query']('', '
  849. SELECT' . $select_columns . '
  850. FROM {db_prefix}members AS mem' . $select_tables . '
  851. WHERE mem.' . ($is_name ? 'member_name' : 'id_member') . (count($users) == 1 ? ' = {' . ($is_name ? 'string' : 'int') . ':users}' : ' IN ({' . ($is_name ? 'array_string' : 'array_int') . ':users})'),
  852. array(
  853. 'blank_string' => '',
  854. 'users' => count($users) == 1 ? current($users) : $users,
  855. )
  856. );
  857. $new_loaded_ids = array();
  858. while ($row = $smcFunc['db_fetch_assoc']($request))
  859. {
  860. $new_loaded_ids[] = $row['id_member'];
  861. $loaded_ids[] = $row['id_member'];
  862. $row['options'] = array();
  863. $user_profile[$row['id_member']] = $row;
  864. }
  865. $smcFunc['db_free_result']($request);
  866. }
  867. if (!empty($new_loaded_ids) && $set !== 'minimal')
  868. {
  869. $request = $smcFunc['db_query']('', '
  870. SELECT *
  871. FROM {db_prefix}themes
  872. WHERE id_member' . (count($new_loaded_ids) == 1 ? ' = {int:loaded_ids}' : ' IN ({array_int:loaded_ids})'),
  873. array(
  874. 'loaded_ids' => count($new_loaded_ids) == 1 ? $new_loaded_ids[0] : $new_loaded_ids,
  875. )
  876. );
  877. while ($row = $smcFunc['db_fetch_assoc']($request))
  878. $user_profile[$row['id_member']]['options'][$row['variable']] = $row['value'];
  879. $smcFunc['db_free_result']($request);
  880. }
  881. if (!empty($new_loaded_ids) && !empty($modSettings['cache_enable']) && $modSettings['cache_enable'] >= 3)
  882. {
  883. for ($i = 0, $n = count($new_loaded_ids); $i < $n; $i++)
  884. cache_put_data('member_data-' . $set . '-' . $new_loaded_ids[$i], $user_profile[$new_loaded_ids[$i]], 240);
  885. }
  886. // Are we loading any moderators? If so, fix their group data...
  887. if (!empty($loaded_ids) && !empty($board_info['moderators']) && $set === 'normal' && count($temp_mods = array_intersect($loaded_ids, array_keys($board_info['moderators']))) !== 0)
  888. {
  889. if (($row = cache_get_data('moderator_group_info', 480)) == null)
  890. {
  891. require_once(SUBSDIR . '/Membergroups.subs.php');
  892. $row = membergroupsById(3, 1, true);
  893. cache_put_data('moderator_group_info', $row, 480);
  894. }
  895. foreach ($temp_mods as $id)
  896. {
  897. // By popular demand, don't show admins or global moderators as moderators.
  898. if ($user_profile[$id]['id_group'] != 1 && $user_profile[$id]['id_group'] != 2)
  899. $user_profile[$id]['member_group'] = $row['group_name'];
  900. // If the Moderator group has no color or icons, but their group does... don't overwrite.
  901. if (!empty($row['icons']))
  902. $user_profile[$id]['icons'] = $row['icons'];
  903. if (!empty($row['online_color']))
  904. $user_profile[$id]['member_group_color'] = $row['online_color'];
  905. }
  906. }
  907. return empty($loaded_ids) ? false : $loaded_ids;
  908. }
  909. /**
  910. * Loads the user's basic values... meant for template/theme usage.
  911. *
  912. * @param int $user
  913. * @param bool $display_custom_fields = false
  914. * @return boolean
  915. */
  916. function loadMemberContext($user, $display_custom_fields = false)
  917. {
  918. global $memberContext, $user_profile, $txt, $scripturl, $user_info;
  919. global $context, $modSettings, $board_info, $settings;
  920. global $smcFunc;
  921. static $dataLoaded = array();
  922. // If this person's data is already loaded, skip it.
  923. if (isset($dataLoaded[$user]))
  924. return true;
  925. // We can't load guests or members not loaded by loadMemberData()!
  926. if ($user == 0)
  927. return false;
  928. if (!isset($user_profile[$user]))
  929. {
  930. trigger_error('loadMemberContext(): member id ' . $user . ' not previously loaded by loadMemberData()', E_USER_WARNING);
  931. return false;
  932. }
  933. // Well, it's loaded now anyhow.
  934. $dataLoaded[$user] = true;
  935. $profile = $user_profile[$user];
  936. // Censor everything.
  937. censorText($profile['signature']);
  938. censorText($profile['personal_text']);
  939. censorText($profile['location']);
  940. // Set things up to be used before hand.
  941. $gendertxt = $profile['gender'] == 2 ? $txt['female'] : ($profile['gender'] == 1 ? $txt['male'] : '');
  942. $profile['signature'] = str_replace(array("\n", "\r"), array('<br />', ''), $profile['signature']);
  943. $profile['signature'] = parse_bbc($profile['signature'], true, 'sig' . $profile['id_member']);
  944. $profile['is_online'] = (!empty($profile['show_online']) || allowedTo('moderate_forum')) && $profile['is_online'] > 0;
  945. $profile['icons'] = empty($profile['icons']) ? array('', '') : explode('#', $profile['icons']);
  946. // Setup the buddy status here (One whole in_array call saved :P)
  947. $profile['buddy'] = in_array($profile['id_member'], $user_info['buddies']);
  948. $buddy_list = !empty($profile['buddy_list']) ? explode(',', $profile['buddy_list']) : array();
  949. // If we're always html resizing, assume it's too large.
  950. if ($modSettings['avatar_action_too_large'] == 'option_html_resize' || $modSettings['avatar_action_too_large'] == 'option_js_resize')
  951. {
  952. $avatar_width = !empty($modSettings['avatar_max_width_external']) ? ' width="' . $modSettings['avatar_max_width_external'] . '"' : '';
  953. $avatar_height = !empty($modSettings['avatar_max_height_external']) ? ' height="' . $modSettings['avatar_max_height_external'] . '"' : '';
  954. }
  955. else
  956. {
  957. $avatar_width = '';
  958. $avatar_height = '';
  959. }
  960. // These minimal values are always loaded
  961. $memberContext[$user] = array(
  962. 'username' => $profile['member_name'],
  963. 'name' => $profile['real_name'],
  964. 'id' => $profile['id_member'],
  965. 'href' => $scripturl . '?action=profile;u=' . $profile['id_member'],
  966. 'link' => '<a href="' . $scripturl . '?action=profile;u=' . $profile['id_member'] . '" title="' . $txt['profile_of'] . ' ' . $profile['real_name'] . '">' . $profile['real_name'] . '</a>',
  967. 'email' => $profile['email_address'],
  968. 'show_email' => showEmailAddress(!empty($profile['hide_email']), $profile['id_member']),
  969. 'registered' => empty($profile['date_registered']) ? $txt['not_applicable'] : timeformat($profile['date_registered']),
  970. 'registered_timestamp' => empty($profile['date_registered']) ? 0 : forum_time(true, $profile['date_registered']),
  971. );
  972. // If the set isn't minimal then load the monstrous array.
  973. if ($context['loadMemberContext_set'] !== 'minimal')
  974. $memberContext[$user] += array(
  975. 'username_color' => '<span '. (!empty($profile['member_group_color']) ? 'style="color:'. $profile['member_group_color'] .';"' : '') .'>'. $profile['member_name'] .'</span>',
  976. 'name_color' => '<span '. (!empty($profile['member_group_color']) ? 'style="color:'. $profile['member_group_color'] .';"' : '') .'>'. $profile['real_name'] .'</span>',
  977. 'link_color' => '<a href="' . $scripturl . '?action=profile;u=' . $profile['id_member'] . '" title="' . $txt['profile_of'] . ' ' . $profile['real_name'] . '" '. (!empty($profile['member_group_color']) ? 'style="color:'. $profile['member_group_color'] .';"' : '') .'>' . $profile['real_name'] . '</a>',
  978. 'is_buddy' => $profile['buddy'],
  979. 'is_reverse_buddy' => in_array($user_info['id'], $buddy_list),
  980. 'buddies' => $buddy_list,
  981. 'title' => !empty($modSettings['titlesEnable']) ? $profile['usertitle'] : '',
  982. 'blurb' => $profile['personal_text'],
  983. 'gender' => array(
  984. 'name' => $gendertxt,
  985. 'image' => !empty($profile['gender']) ? '<img class="gender" src="' . $settings['images_url'] . '/' . ($profile['gender'] == 1 ? 'Male' : 'Female') . '.png" alt="' . $gendertxt . '" />' : ''
  986. ),
  987. 'website' => array(
  988. 'title' => $profile['website_title'],
  989. 'url' => $profile['website_url'],
  990. ),
  991. 'birth_date' => empty($profile['birthdate']) || $profile['birthdate'] === '0001-01-01' ? '0000-00-00' : (substr($profile['birthdate'], 0, 4) === '0004' ? '0000' . substr($profile['birthdate'], 4) : $profile['birthdate']),
  992. 'signature' => $profile['signature'],
  993. 'location' => $profile['location'],
  994. 'real_posts' => $profile['posts'],
  995. 'posts' => comma_format($profile['posts']),
  996. 'avatar' => determineAvatar($profile, $avatar_width, $avatar_height),
  997. 'last_login' => empty($profile['last_login']) ? $txt['never'] : timeformat($profile['last_login']),
  998. 'last_login_timestamp' => empty($profile['last_login']) ? 0 : forum_time(0, $profile['last_login']),
  999. 'karma' => array(
  1000. 'good' => $profile['karma_good'],
  1001. 'bad' => $profile['karma_bad'],
  1002. 'allow' => !$user_info['is_guest'] && !empty($modSettings['karmaMode']) && $user_info['id'] != $user && allowedTo('karma_edit') &&
  1003. ($user_info['posts'] >= $modSettings['karmaMinPosts'] || $user_info['is_admin']),
  1004. ),
  1005. 'ip' => htmlspecialchars($profile['member_ip']),
  1006. 'ip2' => htmlspecialchars($profile['member_ip2']),
  1007. 'online' => array(
  1008. 'is_online' => $profile['is_online'],
  1009. 'text' => $smcFunc['htmlspecialchars']($txt[$profile['is_online'] ? 'online' : 'offline']),
  1010. 'member_online_text' => sprintf($txt[$profile['is_online'] ? 'member_is_online' : 'member_is_offline'], $smcFunc['htmlspecialchars']($profile['real_name'])),
  1011. 'href' => $scripturl . '?action=pm;sa=send;u=' . $profile['id_member'],
  1012. 'link' => '<a href="' . $scripturl . '?action=pm;sa=send;u=' . $profile['id_member'] . '">' . $txt[$profile['is_online'] ? 'online' : 'offline'] . '</a>',
  1013. 'image_href' => $settings['images_url'] . '/' . ($profile['buddy'] ? 'buddy_' : '') . ($profile['is_online'] ? 'useron' : 'useroff') . '.png',
  1014. 'label' => $txt[$profile['is_online'] ? 'online' : 'offline']
  1015. ),
  1016. 'language' => $smcFunc['ucwords'](strtr($profile['lngfile'], array('_' => ' '))),
  1017. 'is_activated' => isset($profile['is_activated']) ? $profile['is_activated'] : 1,
  1018. 'is_banned' => isset($profile['is_activated']) ? $profile['is_activated'] >= 10 : 0,
  1019. 'options' => $profile['options'],
  1020. 'is_guest' => false,
  1021. 'group' => $profile['member_group'],
  1022. 'group_color' => $profile['member_group_color'],
  1023. 'group_id' => $profile['id_group'],
  1024. 'post_group' => $profile['post_group'],
  1025. 'post_group_color' => $profile['post_group_color'],
  1026. 'group_icons' => str_repeat('<img src="' . str_replace('$language', $context['user']['language'], isset($profile['icons'][1]) ? $settings['images_url'] . '/' . $profile['icons'][1] : '') . '" alt="*" />', empty($profile['icons'][0]) || empty($profile['icons'][1]) ? 0 : $profile['icons'][0]),
  1027. 'warning' => $profile['warning'],
  1028. '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' : (''))),
  1029. 'local_time' => timeformat(time() + ($profile['time_offset'] - $user_info['time_offset']) * 3600, false),
  1030. );
  1031. // Are we also loading the members custom fields into context?
  1032. if ($display_custom_fields && !empty($modSettings['displayFields']))
  1033. {
  1034. $memberContext[$user]['custom_fields'] = array();
  1035. if (!isset($context['display_fields']))
  1036. $context['display_fields'] = unserialize($modSettings['displayFields']);
  1037. foreach ($context['display_fields'] as $custom)
  1038. {
  1039. if (!isset($custom['title']) || trim($custom['title']) == '' || empty($profile['options'][$custom['colname']]))
  1040. continue;
  1041. $value = $profile['options'][$custom['colname']];
  1042. // …

Large files files are truncated, but you can click here to view the full file