PageRenderTime 72ms CodeModel.GetById 20ms 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
  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. // BBC?
  1043. if ($custom['bbc'])
  1044. $value = parse_bbc($value);
  1045. // ... or checkbox?
  1046. elseif (isset($custom['type']) && $custom['type'] == 'check')
  1047. $value = $value ? $txt['yes'] : $txt['no'];
  1048. // Enclosing the user input within some other text?
  1049. if (!empty($custom['enclose']))
  1050. $value = strtr($custom['enclose'], array(
  1051. '{SCRIPTURL}' => $scripturl,
  1052. '{IMAGES_URL}' => $settings['images_url'],
  1053. '{DEFAULT_IMAGES_URL}' => $settings['default_images_url'],
  1054. '{INPUT}' => $value,
  1055. ));
  1056. $memberContext[$user]['custom_fields'][] = array(
  1057. 'title' => $custom['title'],
  1058. 'colname' => $custom['colname'],
  1059. 'value' => $value,
  1060. 'placement' => !empty($custom['placement']) ? $custom['placement'] : 0,
  1061. );
  1062. }
  1063. }
  1064. call_integration_hook('integrate_member_context', array($user, $display_custom_fields));
  1065. return true;
  1066. }
  1067. /**
  1068. * Loads information about what browser the user is viewing with and places it in $context
  1069. * - uses the class from BrowserDetect.class.php
  1070. *
  1071. */
  1072. function detectBrowser()
  1073. {
  1074. // Load the current user's browser of choice
  1075. $detector = new Browser_Detector;
  1076. $detector->detectBrowser();
  1077. }
  1078. /**
  1079. * Are we using this browser?
  1080. *
  1081. * Wrapper function for detectBrowser
  1082. * @param $browser: browser we are checking for.
  1083. */
  1084. function isBrowser($browser)
  1085. {
  1086. global $context;
  1087. // Don't know any browser!
  1088. if (empty($context['browser']))
  1089. detectBrowser();
  1090. return !empty($context['browser'][$browser]) || !empty($context['browser']['is_' . $browser]) ? true : false;
  1091. }
  1092. /**
  1093. * Load a theme, by ID.
  1094. *
  1095. * @param int $id_theme = 0
  1096. * @param bool $initialize = true
  1097. */
  1098. function loadTheme($id_theme = 0, $initialize = true)
  1099. {
  1100. global $user_info, $user_settings, $board_info, $sc;
  1101. global $txt, $boardurl, $scripturl, $mbname, $modSettings, $language;
  1102. global $context, $settings, $options, $ssi_theme, $smcFunc;
  1103. // The theme was specified by parameter.
  1104. if (!empty($id_theme))
  1105. $id_theme = (int) $id_theme;
  1106. // The theme was specified by REQUEST.
  1107. elseif (!empty($_REQUEST['theme']) && (!empty($modSettings['theme_allow']) || allowedTo('admin_forum')))
  1108. {
  1109. $id_theme = (int) $_REQUEST['theme'];
  1110. $_SESSION['id_theme'] = $id_theme;
  1111. }
  1112. // The theme was specified by REQUEST... previously.
  1113. elseif (!empty($_SESSION['id_theme']) && (!empty($modSettings['theme_allow']) || allowedTo('admin_forum')))
  1114. $id_theme = (int) $_SESSION['id_theme'];
  1115. // The theme is just the user's choice. (might use ?board=1;theme=0 to force board theme.)
  1116. elseif (!empty($user_info['theme']) && !isset($_REQUEST['theme']) && (!empty($modSettings['theme_allow']) || allowedTo('admin_forum')))
  1117. $id_theme = $user_info['theme'];
  1118. // The theme was specified by the board.
  1119. elseif (!empty($board_info['theme']))
  1120. $id_theme = $board_info['theme'];
  1121. // The theme is the forum's default.
  1122. else
  1123. $id_theme = $modSettings['theme_guests'];
  1124. // Verify the id_theme... no foul play.
  1125. // Always allow the board specific theme, if they are overriding.
  1126. if (!empty($board_info['theme']) && $board_info['override_theme'])
  1127. $id_theme = $board_info['theme'];
  1128. // If they have specified a particular theme to use with SSI allow it to be used.
  1129. elseif (!empty($ssi_theme) && $id_theme == $ssi_theme)
  1130. $id_theme = (int) $id_theme;
  1131. elseif (!empty($modSettings['knownThemes']) && !allowedTo('admin_forum'))
  1132. {
  1133. $themes = explode(',', $modSettings['knownThemes']);
  1134. if (!in_array($id_theme, $themes))
  1135. $id_theme = $modSettings['theme_guests'];
  1136. else
  1137. $id_theme = (int) $id_theme;
  1138. }
  1139. else
  1140. $id_theme = (int) $id_theme;
  1141. $member = empty($user_info['id']) ? -1 : $user_info['id'];
  1142. 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'])
  1143. {
  1144. $themeData = $temp;
  1145. $flag = true;
  1146. }
  1147. elseif (($temp = cache_get_data('theme_settings-' . $id_theme, 90)) != null && time() - 60 > $modSettings['settings_updated'])
  1148. $themeData = $temp + array($member => array());
  1149. else
  1150. $themeData = array(-1 => array(), 0 => array(), $member => array());
  1151. if (empty($flag))
  1152. {
  1153. // Load variables from the current or default theme, global or this user's.
  1154. $result = $smcFunc['db_query']('', '
  1155. SELECT variable, value, id_member, id_theme
  1156. FROM {db_prefix}themes
  1157. WHERE id_member' . (empty($themeData[0]) ? ' IN (-1, 0, {int:id_member})' : ' = {int:id_member}') . '
  1158. AND id_theme' . ($id_theme == 1 ? ' = {int:id_theme}' : ' IN ({int:id_theme}, 1)'),
  1159. array(
  1160. 'id_theme' => $id_theme,
  1161. 'id_member' => $member,
  1162. )
  1163. );
  1164. // Pick between $settings and $options depending on whose data it is.
  1165. while ($row = $smcFunc['db_fetch_assoc']($result))
  1166. {
  1167. // There are just things we shouldn't be able to change as members.
  1168. 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')))
  1169. continue;
  1170. // If this is the theme_dir of the default theme, store it.
  1171. if (in_array($row['variable'], array('theme_dir', 'theme_url', 'images_url')) && $row['id_theme'] == '1' && empty($row['id_member']))
  1172. $themeData[0]['default_' . $row['variable']] = $row['value'];
  1173. // If this isn't set yet, is a theme option, or is not the default theme..
  1174. if (!isset($themeData[$row['id_member']][$row['variable']]) || $row['id_theme'] != '1')
  1175. $themeData[$row['id_member']][$row['variable']] = substr($row['variable'], 0, 5) == 'show_' ? $row['value'] == '1' : $row['value'];
  1176. }
  1177. $smcFunc['db_free_result']($result);
  1178. if (!empty($themeData[-1]))
  1179. {
  1180. foreach ($themeData[-1] as $k => $v)
  1181. {
  1182. if (!isset($themeData[$member][$k]))
  1183. $themeData[$member][$k] = $v;
  1184. }
  1185. }
  1186. if (!empty($modSettings['cache_enable']) && $modSettings['cache_enable'] >= 2)
  1187. cache_put_data('theme_settings-' . $id_theme . ':' . $member, $themeData, 60);
  1188. // Only if we didn't already load that part of the cache...
  1189. elseif (!isset($temp))
  1190. cache_put_data('theme_settings-' . $id_theme, array(-1 => $themeData[-1], 0 => $themeData[0]), 90);
  1191. }
  1192. $settings = $themeData[0];
  1193. $options = $themeData[$member];
  1194. $settings['theme_id'] = $id_theme;
  1195. $settings['actual_theme_url'] = $settings['theme_url'];
  1196. $settings['actual_images_url'] = $settings['images_url'];
  1197. $settings['actual_theme_dir'] = $settings['theme_dir'];
  1198. $settings['template_dirs'] = array();
  1199. // This theme first.
  1200. $settings['template_dirs'][] = $settings['theme_dir'];
  1201. // Based on theme (if there is one).
  1202. if (!empty($settings['base_theme_dir']))
  1203. $settings['template_dirs'][] = $settings['base_theme_dir'];
  1204. // Lastly the default theme.
  1205. if ($settings['theme_dir'] != $settings['default_theme_dir'])
  1206. $settings['template_dirs'][] = $settings['default_theme_dir'];
  1207. if (!$initialize)
  1208. return;
  1209. // Check to see if they're accessing it from the wrong place.
  1210. if (isset($_SERVER['HTTP_HOST']) || isset($_SERVER['SERVER_NAME']))
  1211. {
  1212. $detected_url = isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) == 'on' ? 'https://' : 'http://';
  1213. $detected_url .= empty($_SERVER['HTTP_HOST']) ? $_SERVER['SERVER_NAME'] . (empty($_SERVER['SERVER_PORT']) || $_SERVER['SERVER_PORT'] == '80' ? '' : ':' . $_SERVER['SERVER_PORT']) : $_SERVER['HTTP_HOST'];
  1214. $temp = preg_replace('~/' . basename($scripturl) . '(/.+)?$~', '', strtr(dirname($_SERVER['PHP_SELF']), '\\', '/'));
  1215. if ($temp != '/')
  1216. $detected_url .= $temp;
  1217. }
  1218. if (isset($detected_url) && $detected_url != $boardurl)
  1219. {
  1220. // Try #1 - check if it's in a list of alias addresses.
  1221. if (!empty($modSettings['forum_alias_urls']))
  1222. {
  1223. $aliases = explode(',', $modSettings['forum_alias_urls']);
  1224. foreach ($aliases as $alias)
  1225. {
  1226. // Rip off all the boring parts, spaces, etc.
  1227. if ($detected_url == trim($alias) || strtr($detected_url, array('http://' => '', 'https://' => '')) == trim($alias))
  1228. $do_fix = true;
  1229. }
  1230. }
  1231. // Hmm... check #2 - is it just different by a www? Send them to the correct place!!
  1232. if (empty($do_fix) && strtr($detected_url, array('://' => '://www.')) == $boardurl && (empty($_GET) || count($_GET) == 1) && ELKARTE != 'SSI')
  1233. {
  1234. // Okay, this seems weird, but we don't want an endless loop - this will make $_GET not empty ;).
  1235. if (empty($_GET))
  1236. redirectexit('wwwRedirect');
  1237. else
  1238. {
  1239. list ($k, $v) = each($_GET);
  1240. if ($k != 'wwwRedirect')
  1241. redirectexit('wwwRedirect;' . $k . '=' . $v);
  1242. }
  1243. }
  1244. // #3 is just a check for SSL...
  1245. if (strtr($detected_url, array('https://' => 'http://')) == $boardurl)
  1246. $do_fix = true;
  1247. // Okay, #4 - perhaps it's an IP address? We're gonna want to use that one, then. (assuming it's the IP or something...)
  1248. if (!empty($do_fix) || preg_match('~^http[s]?://(?:[\d\.:]+|\[[\d:]+\](?::\d+)?)(?:$|/)~', $detected_url) == 1)
  1249. {
  1250. // Caching is good ;).
  1251. $oldurl = $boardurl;
  1252. // Fix $boardurl and $scripturl.
  1253. $boardurl = $detected_url;
  1254. $scripturl = strtr($scripturl, array($oldurl => $boardurl));
  1255. $_SERVER['REQUEST_URL'] = strtr($_SERVER['REQUEST_URL'], array($oldurl => $boardurl));
  1256. // Fix the theme urls...
  1257. $settings['theme_url'] = strtr($settings['theme_url'], array($oldurl => $boardurl));
  1258. $settings['default_theme_url'] = strtr($settings['default_theme_url'], array($oldurl => $boardurl));
  1259. $settings['actual_theme_url'] = strtr($settings['actual_theme_url'], array($oldurl => $boardurl));
  1260. $settings['images_url'] = strtr($settings['images_url'], array($oldurl => $boardurl));
  1261. $settings['default_images_url'] = strtr($settings['default_images_url'], array($oldurl => $boardurl));
  1262. $settings['actual_images_url'] = strtr($settings['actual_images_url'], array($oldurl => $boardurl));
  1263. // And just a few mod settings :).
  1264. $modSettings['smileys_url'] = strtr($modSettings['smileys_url'], array($oldurl => $boardurl));
  1265. $modSettings['avatar_url'] = strtr($modSettings['avatar_url'], array($oldurl => $boardurl));
  1266. // Clean up after loadBoard().
  1267. if (isset($board_info['moderators']))
  1268. {
  1269. foreach ($board_info['moderators'] as $k => $dummy)
  1270. {
  1271. $board_info['moderators'][$k]['href'] = strtr($dummy['href'], array($oldurl => $boardurl));
  1272. $board_info['moderators'][$k]['link'] = strtr($dummy['link'], array('"' . $oldurl => '"' . $boardurl));
  1273. }
  1274. }
  1275. foreach ($context['linktree'] as $k => $dummy)
  1276. $context['linktree'][$k]['url'] = strtr($dummy['url'], array($oldurl => $boardurl));
  1277. }
  1278. }
  1279. // Set up the contextual user array.
  1280. $context['user'] = array(
  1281. 'id' => $user_info['id'],
  1282. 'is_logged' => !$user_info['is_guest'],
  1283. 'is_guest' => &$user_info['is_guest'],
  1284. 'is_admin' => &$user_info['is_admin'],
  1285. 'is_mod' => &$user_info['is_mod'],
  1286. // A user can mod if they have permission to see the mod center, or they are a board/group/approval moderator.
  1287. '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'])))),
  1288. 'username' => $user_info['username'],
  1289. 'language' => $user_info['language'],
  1290. 'email' => $user_info['email'],
  1291. 'ignoreusers' => $user_info['ignoreusers'],
  1292. );
  1293. if (!$context['user']['is_guest'])
  1294. $context['user']['name'] = $user_info['name'];
  1295. elseif ($context['user']['is_guest'] && !empty($txt['guest_title']))
  1296. $context['user']['name'] = $txt['guest_title'];
  1297. // Determine the current smiley set.
  1298. $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'];
  1299. $context['user']['smiley_set'] = $user_info['smiley_set'];
  1300. // Some basic information...
  1301. if (!isset($context['html_headers']))
  1302. $context['html_headers'] = '';
  1303. if (!isset($context['javascript_files']))
  1304. $context['javascript_files'] = array();
  1305. if (!isset($context['css_files']))
  1306. $context['css_files'] = array();
  1307. if (!isset($context['javascript_inline']))
  1308. $context['javascript_inline'] = array('standard' => array(), 'defer' => array());
  1309. if (!isset($context['javascript_vars']))
  1310. $context['javascript_vars'] = array();
  1311. $context['menu_separator'] = !empty($settings['use_image_buttons']) ? ' ' : ' | ';
  1312. $context['session_var'] = $_SESSION['session_var'];
  1313. $context['session_id'] = $_SESSION['session_value'];
  1314. $context['forum_name'] = $mbname;
  1315. $context['forum_name_html_safe'] = $smcFunc['htmlspecialchars']($context['forum_name']);
  1316. $context['header_logo_url_html_safe'] = empty($settings['header_logo_url']) ? '' : $smcFunc['htmlspecialchars']($settings['header_logo_url']);
  1317. $context['current_action'] = isset($_REQUEST['action']) ? $_REQUEST['action'] : null;
  1318. $context['current_subaction'] = isset($_REQUEST['sa']) ? $_REQUEST['sa'] : null;
  1319. $context['can_register'] = empty($modSettings['registration_method']) || $modSettings['registration_method'] != 3;
  1320. if (isset($modSettings['load_average']))
  1321. $context['load_average'] = $modSettings['load_average'];
  1322. // Set some permission related settings.
  1323. $context['show_login_bar'] = $user_info['is_guest'] && !empty($modSettings['enableVBStyleLogin']);
  1324. // This determines the server... not used in many places, except for login fixing.
  1325. $context['server'] = array(
  1326. 'is_iis' => isset($_SERVER['SERVER_SOFTWARE']) && strpos($_SERVER['SERVER_SOFTWARE'], 'Microsoft-IIS') !== false,
  1327. 'is_apache' => isset($_SERVER['SERVER_SOFTWARE']) && strpos($_SERVER['SERVER_SOFTWARE'], 'Apache') !== false,
  1328. 'is_litespeed' => isset($_SERVER['SERVER_SOFTWARE']) && strpos($_SERVER['SERVER_SOFTWARE'], 'LiteSpeed') !== false,
  1329. 'is_lighttpd' => isset($_SERVER['SERVER_SOFTWARE']) && strpos($_SERVER['SERVER_SOFTWARE'], 'lighttpd') !== false,
  1330. 'is_nginx' => isset($_SERVER['SERVER_SOFTWARE']) && strpos($_SERVER['SERVER_SOFTWARE'], 'nginx') !== false,
  1331. 'is_cgi' => isset($_SERVER['SERVER_SOFTWARE']) && strpos(php_sapi_name(), 'cgi') !== false,
  1332. 'is_windows' => strpos(PHP_OS, 'WIN') === 0,
  1333. 'iso_case_folding' => ord(strtolower(chr(138))) === 154,
  1334. );
  1335. // A bug in some versions of IIS under CGI (older ones) makes cookie setting not work with Location: headers.
  1336. $context['server']['needs_login_fix'] = $context['server']['is_cgi'] && $context['server']['is_iis'];
  1337. // Detect the browser. This is separated out because it's also used in attachment downloads
  1338. detectBrowser();
  1339. // Set the top level linktree up.
  1340. array_unshift($context['linktree'], array(
  1341. 'url' => $scripturl,
  1342. 'name' => $context['forum_name_html_safe']
  1343. ));
  1344. // This allows sticking some HTML on the page output - useful for controls.
  1345. $context['insert_after_template'] = '';
  1346. if (!isset($txt))
  1347. $txt = array();
  1348. $simpleActions = array(
  1349. 'findmember',
  1350. 'quickhelp',
  1351. 'printpage',
  1352. 'quotefast',
  1353. 'spellcheck',
  1354. );
  1355. // Output is fully XML, so no need for the index template.
  1356. if (isset($_REQUEST['xml']))
  1357. {
  1358. loadLanguage('index+Modifications');
  1359. loadTemplate('Xml');
  1360. $context['template_layers'] = array();
  1361. }
  1362. // These actions don't require the index template at all.
  1363. elseif (!empty($_REQUEST['action']) && in_array($_REQUEST['action'], $simpleActions))
  1364. {
  1365. loadLanguage('index+Modifications');
  1366. $context['template_layers'] = array();
  1367. }
  1368. else
  1369. {
  1370. // Custom templates to load, or just default?
  1371. if (isset($settings['theme_templates']))
  1372. $templates = explode(',', $settings['theme_templates']);
  1373. else
  1374. $templates = array('index');
  1375. // Load each template...
  1376. foreach ($templates as $template)
  1377. loadTemplate($template);
  1378. // ...and attempt to load their associated language files.
  1379. $required_files = implode('+', array_merge($templates, array('Modifications')));
  1380. loadLanguage($required_files, '', false);
  1381. // Custom template layers?
  1382. if (isset($settings['theme_layers']))
  1383. $context['template_layers'] = explode(',', $settings['theme_layers']);
  1384. else
  1385. $context['template_layers'] = array('html', 'body');
  1386. }
  1387. // Initialize the theme.
  1388. loadSubTemplate('init', 'ignore');
  1389. // Guests may still need a name.
  1390. if ($context['user']['is_guest'] && empty($context['user']['name']))
  1391. $context['user']['name'] = $txt['guest_title'];
  1392. // Any theme-related strings that need to be loaded?
  1393. if (!empty($settings['require_theme_strings']))
  1394. loadLanguage('ThemeStrings', '', false);
  1395. // We allow theme variants, because we're cool.
  1396. $context['theme_variant'] = '';
  1397. $context['theme_variant_url'] = '';
  1398. if (!empty($settings['theme_variants']))
  1399. {
  1400. // Overriding - for previews and that ilk.
  1401. if (!empty($_REQUEST['variant']))
  1402. $_SESSION['id_variant'] = $_REQUEST['variant'];
  1403. // User selection?
  1404. if (empty($settings['disable_user_variant']) || allowedTo('admin_forum'))
  1405. $context['theme_variant'] = !empty($_SESSION['id_variant']) ? $_SESSION['id_variant'] : (!empty($options['theme_variant']) ? $options['theme_variant'] : '');
  1406. // If not a user variant, select the default.
  1407. if ($context['theme_variant'] == '' || !in_array($context['theme_variant'], $settings['theme_variants']))
  1408. $context['theme_variant'] = !empty($settings['default_variant']) && in_array($settings['default_variant'], $settings['theme_variants']) ? $settings['default_variant'] : $settings['theme_variants'][0];
  1409. // Do this to keep things easier in the templates.
  1410. $context['theme_variant'] = '_' . $context['theme_variant'];
  1411. $context['theme_variant_url'] = $context['theme_variant'] . '/';
  1412. }
  1413. // Let's be compatible with old themes!
  1414. if (!function_exists('template_html_above') && in_array('html', $context['template_layers']))
  1415. $context['template_layers'] = array('main');
  1416. // Allow overriding the board wide time/number formats.
  1417. if (empty($user_settings['time_format']) && !empty($txt['time_format']))
  1418. $user_info['time_format'] = $txt['time_format'];
  1419. if (isset($settings['use_default_images']) && $settings['use_default_images'] == 'always')
  1420. {
  1421. $settings['theme_url'] = $settings['default_theme_url'];
  1422. $settings['images_url'] = $settings['default_images_url'];
  1423. $settings['theme_dir'] = $settings['default_theme_dir'];
  1424. }
  1425. // Make a special URL for the language.
  1426. $settings['lang_images_url'] = $settings['images_url'] . '/' . (!empty($txt['image_lang']) ? $txt['image_lang'] : $user_info['language']);
  1427. // Set the character set from the template.
  1428. $context['character_set'] = 'UTF-8';
  1429. $context['right_to_left'] = !empty($txt['lang_rtl']);
  1430. $context['tabindex'] = 1;
  1431. // Compatibility.
  1432. if (!isset($settings['theme_version']))
  1433. $modSettings['memberCount'] = $modSettings['totalMembers'];
  1434. // This allows us to change the way things look for the admin.
  1435. $context['admin_features'] = isset($modSettings['admin_features']) ? explode(',', $modSettings['admin_features']) : array('cd,cp,k,w,rg,ml,pm');
  1436. // Default JS variables for use in every theme
  1437. $context['javascript_vars'] = array(
  1438. 'smf_theme_url' => '"' . $settings['theme_url'] . '"',
  1439. 'smf_default_theme_url' => '"' . $settings['default_theme_url'] . '"',
  1440. 'smf_images_url' => '"' . $settings['images_url'] . '"',
  1441. 'smf_scripturl' => '"' . $scripturl . '"',
  1442. 'smf_default_theme_url' => '"' . $settings['default_theme_url'] . '"',
  1443. 'smf_iso_case_folding' => $context['server']['iso_case_folding'] ? 'true' : 'false',
  1444. 'smf_charset' => '"UTF-8"',
  1445. 'smf_session_id' => '"' . $context['session_id'] . '"',
  1446. 'smf_session_var' => '"' . $context['session_var'] . '"',
  1447. 'smf_member_id' => $context['user']['id'],
  1448. 'ajax_notification_text' => JavaScriptEscape($txt['ajax_in_progress']),
  1449. 'ajax_notification_cancel_text' => JavaScriptEscape($txt['modify_cancel']),
  1450. 'help_popup_heading_text' => JavaScriptEscape($txt['help_popup']),
  1451. 'use_click_menu' => (!empty($options['use_click_menu']) ? 'true' : 'false'),
  1452. );
  1453. // Queue our Javascript
  1454. loadJavascriptFile(array('elk_jquery_plugins.js', 'script.js', 'theme.js'));
  1455. // If we think we have mail to send, let's offer up some possibilities... robots get pain (Now with scheduled task support!)
  1456. 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())
  1457. {
  1458. if (isBrowser('possibly_robot'))
  1459. {
  1460. // @todo Maybe move this somewhere better?!
  1461. require_once(SOURCEDIR . '/ScheduledTasks.php');
  1462. // What to do, what to do?!
  1463. if (empty($modSettings['next_task_time']) || $modSettings['next_task_time'] < time())
  1464. AutoTask();
  1465. else
  1466. ReduceMailQueue();
  1467. }
  1468. else
  1469. {
  1470. $type = empty($modSettings['next_task_time']) || $modSettings['next_task_time'] < time() ? 'task' : 'mailq';
  1471. $ts = $type == 'mailq' ? $modSettings['mail_next_send'] : $modSettings['next_task_time'];
  1472. addInlineJavascript('
  1473. function smfAutoTask()
  1474. {
  1475. var tempImage = new Image();
  1476. tempImage.src = smf_scripturl + "?scheduled=' . $type . ';ts=' . $ts . '";
  1477. }
  1478. window.setTimeout("smfAutoTask();", 1);');
  1479. }
  1480. }
  1481. // Any files to include at this point?
  1482. if (!empty($modSettings['integrate_theme_include']))
  1483. {
  1484. $theme_includes = explode(',', $modSettings['integrate_theme_include']);
  1485. foreach ($theme_includes as $include)
  1486. {
  1487. $include = strtr(trim($include), array('BOARDDIR' => BOARDDIR, 'SOURCEDIR' => SOURCEDIR, '$themedir' => $settings['theme_dir']));
  1488. if (file_exists($include))
  1489. require_once($include);
  1490. }
  1491. }
  1492. // Call load theme integration functions.
  1493. call_integration_hook('integrate_load_theme');
  1494. // We are ready to go.
  1495. $context['theme_loaded'] = true;
  1496. }
  1497. /**
  1498. * This loads the bare minimum data.
  1499. * Needed by scheduled tasks, and any other code that needs language files
  1500. * before the forum (the theme) is loaded.
  1501. */
  1502. function loadEssentialThemeData()
  1503. {
  1504. global $settings, $modSettings, $smcFunc, $mbname, $context;
  1505. // Get all the default theme variables.
  1506. $result = $smcFunc['db_query']('', '
  1507. SELECT id_theme, variable, value
  1508. FROM {db_prefix}themes
  1509. WHERE id_member = {int:no_member}
  1510. AND id_theme IN (1, {int:theme_guests})',
  1511. array(
  1512. 'no_member' => 0,
  1513. 'theme_guests' => $modSettings['theme_guests'],
  1514. )
  1515. );
  1516. while ($row = $smcFunc['db_fetch_assoc']($result))
  1517. {
  1518. $settings[$row['variable']] = $row['value'];
  1519. // Is this the default theme?
  1520. if (in_array($row['variable'], array('theme_dir', 'theme_url', 'images_url')) && $row['id_theme'] == '1')
  1521. $settings['default_' . $row['variable']] = $row['value'];
  1522. }
  1523. $smcFunc['db_free_result']($result);
  1524. // Check we have some directories setup.
  1525. if (empty($settings['template_dirs']))
  1526. {
  1527. $settings['template_dirs'] = array($settings['theme_dir']);
  1528. // Based on theme (if there is one).
  1529. if (!empty($settings['base_theme_dir']))
  1530. $settings['template_dirs'][] = $settings['base_theme_dir'];
  1531. // Lastly the default theme.
  1532. if ($settings['theme_dir'] != $settings['default_theme_dir'])
  1533. $settings['template_dirs'][] = $settings['default_theme_dir'];
  1534. }
  1535. // Assume we want this.
  1536. $context['forum_name'] = $mbname;
  1537. // Check loadLanguage actually exists!
  1538. if (!function_exists('loadLanguage'))
  1539. require_once(SOURCEDIR . '/Subs.php');
  1540. loadLanguage('index+Modifications');
  1541. }
  1542. /**
  1543. * Load a template - if the theme doesn't include it, use the default.
  1544. * What this function does:
  1545. * - loads a template file with the name template_name from the current, default, or base theme.
  1546. * - detects a wrong default theme directory and tries to work around it.
  1547. *
  1548. * @uses the template_include() function to include the file.
  1549. * @param string $template_name
  1550. * @param array $style_sheets = array()
  1551. * @param bool $fatal = true if fatal is true, dies with an error message if the template cannot be found
  1552. * @return boolean
  1553. */
  1554. function loadTemplate($template_name, $style_sheets = array(), $fatal = true)
  1555. {
  1556. global $context, $settings, $txt, $scripturl, $db_show_debug;
  1557. static $default_loaded;
  1558. if (!is_array($style_sheets))
  1559. $style_sheets = array($style_sheets);
  1560. // The most efficient way of writing multi themes is to use a master index.css plus variant.css files.
  1561. if (!empty($context['theme_variant']))
  1562. $default_sheets = array('index.css', $context['theme_variant'] . '.css');
  1563. else
  1564. $default_sheets = array('index.css');
  1565. // Any specific template style sheets to load?
  1566. if (!empty($style_sheets))
  1567. loadCSSFile(
  1568. array(implode('.css,', $style_sheets) . '.css')
  1569. );
  1570. elseif (empty($default_loaded))
  1571. {
  1572. loadCSSFile($default_sheets);
  1573. $default_loaded = true;
  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 (substr($template_name, 0, 5) == 'index' && !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=list;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. *
  1657. * @param string $filename
  1658. * @param array $params
  1659. * Keys are the following:
  1660. * - ['local'] (true/false): define if the file is local
  1661. * - ['fallback'] (true/false): if false will attempt to load the file from the default theme if not found in the current theme
  1662. * - ['stale'] (true/false/string): if true or null, use cache stale, false do not, or used a supplied string
  1663. *
  1664. * @param string $id
  1665. */
  1666. function loadCSSFile($filenames, $params = array(), $id = '')
  1667. {
  1668. global $settings, $context;
  1669. if (empty($filenames))
  1670. return;
  1671. if (!is_array($filenames))
  1672. $filenames = array($filenames);
  1673. // static values for all these settings
  1674. $params['stale'] = (!isset($params['stale']) || $params['stale'] === true) ? '?alph21' : (is_string($params['stale']) ? ($params['stale'] = $params['stale'][0] === '?' ? $params['stale'] : '?' . $params['stale']) : '');
  1675. $params['fallback'] = (!empty($params['fallback']) && ($params['fallback'] === false)) ? false : true;
  1676. // Whoa ... we've done this before yes?
  1677. $cache_name = 'load_css_' . md5($settings['theme_dir'] . implode('_', $filenames));
  1678. if (($temp = cache_get_data($cache_name, 600)) !== null)
  1679. {
  1680. if (empty($context['css_files']))
  1681. $context['css_files'] = array();
  1682. $context['css_files'] += $temp;
  1683. }
  1684. else
  1685. {
  1686. // All the files in this group use the parameters as defined above
  1687. foreach ($filenames as $filename)
  1688. {
  1689. // account for shorthand like admin.css?xyz11 filenames
  1690. $has_cache_staler = strpos($filename, '.css?');
  1691. $params['basename'] = $has_cache_staler ? substr($filename, 0, $has_cache_staler + 4) : $filename;
  1692. $this_id = empty($id) ? strtr(basename($filename), '?', '_') : $id;
  1693. // Is this a local file?
  1694. if (substr($filename, 0, 4) !== 'http' || !empty($params['local']))
  1695. {
  1696. $params['local'] = true;
  1697. $params['dir'] = $settings['theme_dir'] . '/css/';
  1698. $params['url'] = $settings['theme_url'];
  1699. // Fallback if needed?
  1700. if ($params['fallback'] && ($settings['theme_dir'] !== $settings['default_theme_dir']) && !file_exists($settings['theme_dir'] . '/css/' . $filename))
  1701. {
  1702. // Fallback if we are not already in the default theme
  1703. if (file_exists($settings['default_theme_dir'] . '/css/' . $filename))
  1704. {
  1705. $filename = $settings['default_theme_url'] . '/css/' . $filename . ($has_cache_staler ? '' : $params['stale']);
  1706. $params['dir'] = $settings['default_theme_dir'] . '/css/';
  1707. $params['url'] = $settings['default_theme_url'];
  1708. }
  1709. else
  1710. $filename = false;
  1711. }
  1712. else
  1713. $filename = $settings['theme_url'] . '/css/' . $filename . ($has_cache_staler ? '' : $params['stale']);
  1714. }
  1715. // Add it to the array for use in the template
  1716. if (!empty($filename))
  1717. $context['css_files'][$this_id] = array('filename' => $filename, 'options' => $params);
  1718. }
  1719. // Save this build
  1720. cache_put_data($cache_name, $context['css_files'], 600);
  1721. }
  1722. }
  1723. /**
  1724. * Add a Javascript file for output later
  1725. *
  1726. * Can be passed an array of filenames, all which will have the same parameters applied, if you
  1727. * need specific parameters on a per file basis, call it multiple times
  1728. *
  1729. * @param array $filenames
  1730. * @param array $params
  1731. * Keys are the following:
  1732. * - ['local'] (true/false): define if the file is local
  1733. * - ['defer'] (true/false): define if the file should load in <head> or before the closing <html> tag
  1734. * - ['fallback'] (true/false): if true will attempt to load the file from the default theme if not found in the current
  1735. * - ['async'] (true/false): if the script should be loaded asynchronously (HTML5)
  1736. * - ['stale'] (true/false/string): if true or null, use cache stale, false do not, or used a supplied string
  1737. *
  1738. * @param string $id
  1739. */
  1740. function loadJavascriptFile($filenames, $params = array(), $id = '')
  1741. {
  1742. global $settings, $context;
  1743. if (empty($filenames))
  1744. return;
  1745. if (!is_array($filenames))
  1746. $filenames = array($filenames);
  1747. // static values for all these files
  1748. $params['stale'] = (!isset($params['stale']) || $params['stale'] === true) ? '?alph21' : (is_string($params['stale']) ? ($params['stale'] = $params['stale'][0] === '?' ? $params['stale'] : '?' . $params['stale']) : '');
  1749. $params['fallback'] = (!empty($params['fallback']) && ($params['fallback'] === false)) ? false : true;
  1750. // dejvu?
  1751. $cache_name = 'load_js_' . md5($settings['theme_dir'] . implode('_', $filenames));
  1752. if (($temp = cache_get_data($cache_name, 600)) !== null)
  1753. {
  1754. if (empty($context['javascript_files']))
  1755. $context['javascript_files'] = array();
  1756. $context['javascript_files'] += $temp;
  1757. }
  1758. else
  1759. {
  1760. // All the files in this group use the above parameters
  1761. foreach ($filenames as $filename)
  1762. {
  1763. // account for shorthand like admin.js?xyz11 filenames
  1764. $has_cache_staler = strpos($filename, '.js?');
  1765. $params['basename'] = $has_cache_staler ? substr($filename, 0, $has_cache_staler + 3) : $filename;
  1766. $this_id = empty($id) ? strtr(basename($filename), '?', '_') : $id;
  1767. // Is this a local file?
  1768. if (substr($filename, 0, 4) !== 'http' || !empty($params['local']))
  1769. {
  1770. $params['local'] = true;
  1771. $params['dir'] = $settings['theme_dir'] . '/scripts/';
  1772. // Fallback if we are not already in the default theme
  1773. if ($params['fallback'] && ($settings['theme_dir'] !== $settings['default_theme_dir']) && !file_exists($settings['theme_dir'] . '/scripts/' . $filename))
  1774. {
  1775. // can't find it in this theme, how about the default?
  1776. if (file_exists($settings['default_theme_dir'] . '/scripts/' . $filename))
  1777. {
  1778. $filename = $settings['default_theme_url'] . '/scripts/' . $filename . ($has_cache_staler ? '' : $params['stale']);
  1779. $params['dir'] = $settings['default_theme_dir'] . '/scripts/';
  1780. }
  1781. else
  1782. $filename = false;
  1783. }
  1784. else
  1785. $filename = $settings['theme_url'] . '/scripts/' . $filename . ($has_cache_staler ? '' : $params['stale']);
  1786. }
  1787. // Add it to the array for use in the template
  1788. if (!empty($filename)) {
  1789. $context['javascript_files'][$this_id] = array('filename' => $filename, 'options' => $params);
  1790. }
  1791. }
  1792. // Save it so we don't have to build this so often
  1793. cache_put_data($cache_name, $context['javascript_files'], 600);
  1794. }
  1795. }
  1796. /**
  1797. * Add a Javascript variable for output later (for feeding text strings and similar to JS)
  1798. * Cleaner and easier (for modders) than to use the function below.
  1799. *
  1800. * @param string $key
  1801. * @param string $value
  1802. * @param bool $escape = false, whether or not to escape the value
  1803. */
  1804. function addJavascriptVar($key, $value, $escape = false)
  1805. {
  1806. global $context;
  1807. if (!empty($key) && !empty($value))
  1808. $context['javascript_vars'][$key] = !empty($escape) ? JavaScriptEscape($value) : $value;
  1809. }
  1810. /**
  1811. * Add a block of inline Javascript code to be executed later
  1812. *
  1813. * - only use this if you have to, generally external JS files are better, but for very small scripts
  1814. * or for scripts that require help from PHP/whatever, this can be useful.
  1815. * - all code added with this function is added to the same <script> tag so do make sure your JS is clean!
  1816. *
  1817. * @param string $javascript
  1818. * @param bool $defer = false, define if the script should load in <head> or before the closing <html> tag
  1819. */
  1820. function addInlineJavascript($javascript, $defer = false)
  1821. {
  1822. global $context;
  1823. if (!empty($javascript))
  1824. $context['javascript_inline'][(!empty($defer) ? 'defer' : 'standard')][] = $javascript;
  1825. }
  1826. /**
  1827. * Load a language file. Tries the current and default themes as well as the user and global languages.
  1828. *
  1829. * @param string $template_name
  1830. * @param string $lang
  1831. * @param bool $fatal = true
  1832. * @param bool $force_reload = false
  1833. * @return string The language actually loaded.
  1834. */
  1835. function loadLanguage($template_name, $lang = '', $fatal = true, $force_reload = false)
  1836. {
  1837. global $user_info, $language, $settings, $context, $modSettings;
  1838. global $db_show_debug, $txt;
  1839. static $already_loaded = array();
  1840. // Default to the user's language.
  1841. if ($lang == '')
  1842. $lang = isset($user_info['language']) ? $user_info['language'] : $language;
  1843. // Do we want the English version of language file as fallback?
  1844. if (empty($modSettings['disable_language_fallback']) && $lang != 'english')
  1845. loadLanguage($template_name, 'english', false);
  1846. if (!$force_reload && isset($already_loaded[$template_name]) && $already_loaded[$template_name] == $lang)
  1847. return $lang;
  1848. // Make sure we have $settings - if not we're in trouble and need to find it!
  1849. if (empty($settings['default_theme_dir']))
  1850. loadEssentialThemeData();
  1851. // What theme are we in?
  1852. $theme_name = basename($settings['theme_url']);
  1853. if (empty($theme_name))
  1854. $theme_name = 'unknown';
  1855. // For each file open it up and write it out!
  1856. foreach (explode('+', $template_name) as $template)
  1857. {
  1858. // Obviously, the current theme is most important to check.
  1859. $attempts = array(
  1860. array($settings['theme_dir'], $template, $lang, $settings['theme_url']),
  1861. array($settings['theme_dir'], $template, $language, $settings['theme_url']),
  1862. );
  1863. // Do we have a base theme to worry about?
  1864. if (isset($settings['base_theme_dir']))
  1865. {
  1866. $attempts[] = array($settings['base_theme_dir'], $template, $lang, $settings['base_theme_url']);
  1867. $attempts[] = array($settings['base_theme_dir'], $template, $language, $settings['base_theme_url']);
  1868. }
  1869. // Fall back on the default theme if necessary.
  1870. $attempts[] = array($settings['default_theme_dir'], $template, $lang, $settings['default_theme_url']);
  1871. $attempts[] = array($settings['default_theme_dir'], $template, $language, $settings['default_theme_url']);
  1872. // Fall back on the English language if none of the preferred languages can be found.
  1873. if (!in_array('english', array($lang, $language)))
  1874. {
  1875. $attempts[] = array($settings['theme_dir'], $template, 'english', $settings['theme_url']);
  1876. $attempts[] = array($settings['default_theme_dir'], $template, 'english', $settings['default_theme_url']);
  1877. }
  1878. // Try to find the language file.
  1879. $found = false;
  1880. foreach ($attempts as $k => $file)
  1881. {
  1882. if (file_exists($file[0] . '/languages/' . $file[1] . '.' . $file[2] . '.php'))
  1883. {
  1884. // Include it!
  1885. template_include($file[0] . '/languages/' . $file[1] . '.' . $file[2] . '.php');
  1886. // Note that we found it.
  1887. $found = true;
  1888. break;
  1889. }
  1890. }
  1891. // That couldn't be found! Log the error, but *try* to continue normally.
  1892. if (!$found && $fatal)
  1893. {
  1894. log_error(sprintf($txt['theme_language_error'], $template_name . '.' . $lang, 'template'));
  1895. break;
  1896. }
  1897. // For the sake of backward compatibility
  1898. if (!empty($txt['emails']))
  1899. {
  1900. foreach ($txt['emails'] as $key => $value)
  1901. {
  1902. $txt[$key . '_subject'] = $value['subject'];
  1903. $txt[$key . '_body'] = $value['body'];
  1904. }
  1905. $txt['emails'] = array();
  1906. }
  1907. if (!empty($birthdayEmails))
  1908. {
  1909. foreach ($birthdayEmails as $key => $value)
  1910. {
  1911. $txtBirthdayEmails[$key . '_subject'] = $value['subject'];
  1912. $txtBirthdayEmails[$key . '_body'] = $value['body'];
  1913. $txtBirthdayEmails[$key . '_author'] = $value['author'];
  1914. }
  1915. $birthdayEmails = array();
  1916. }
  1917. }
  1918. // Keep track of what we're up to soldier.
  1919. if ($db_show_debug === true)
  1920. $context['debug']['language_files'][] = $template_name . '.' . $lang . ' (' . $theme_name . ')';
  1921. // Remember what we have loaded, and in which language.
  1922. $already_loaded[$template_name] = $lang;
  1923. // Return the language actually loaded.
  1924. return $lang;
  1925. }
  1926. /**
  1927. * Get all parent boards (requires first parent as parameter)
  1928. * It finds all the parents of id_parent, and that board itself.
  1929. * Additionally, it detects the moderators of said boards.
  1930. *
  1931. * @param int $id_parent
  1932. * @return an array of information about the boards found.
  1933. */
  1934. function getBoardParents($id_parent)
  1935. {
  1936. global $scripturl, $smcFunc;
  1937. // First check if we have this cached already.
  1938. if (($boards = cache_get_data('board_parents-' . $id_parent, 480)) === null)
  1939. {
  1940. $boards = array();
  1941. $original_parent = $id_parent;
  1942. // Loop while the parent is non-zero.
  1943. while ($id_parent != 0)
  1944. {
  1945. $result = $smcFunc['db_query']('', '
  1946. SELECT
  1947. b.id_parent, b.name, {int:board_parent} AS id_board, IFNULL(mem.id_member, 0) AS id_moderator,
  1948. mem.real_name, b.child_level
  1949. FROM {db_prefix}boards AS b
  1950. LEFT JOIN {db_prefix}moderators AS mods ON (mods.id_board = b.id_board)
  1951. LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = mods.id_member)
  1952. WHERE b.id_board = {int:board_parent}',
  1953. array(
  1954. 'board_parent' => $id_parent,
  1955. )
  1956. );
  1957. // In the EXTREMELY unlikely event this happens, give an error message.
  1958. if ($smcFunc['db_num_rows']($result) == 0)
  1959. fatal_lang_error('parent_not_found', 'critical');
  1960. while ($row = $smcFunc['db_fetch_assoc']($result))
  1961. {
  1962. if (!isset($boards[$row['id_board']]))
  1963. {
  1964. $id_parent = $row['id_parent'];
  1965. $boards[$row['id_board']] = array(
  1966. 'url' => $scripturl . '?board=' . $row['id_board'] . '.0',
  1967. 'name' => $row['name'],
  1968. 'level' => $row['child_level'],
  1969. 'moderators' => array()
  1970. );
  1971. }
  1972. // If a moderator exists for this board, add that moderator for all children too.
  1973. if (!empty($row['id_moderator']))
  1974. foreach ($boards as $id => $dummy)
  1975. {
  1976. $boards[$id]['moderators'][$row['id_moderator']] = array(
  1977. 'id' => $row['id_moderator'],
  1978. 'name' => $row['real_name'],
  1979. 'href' => $scripturl . '?action=profile;u=' . $row['id_moderator'],
  1980. 'link' => '<a href="' . $scripturl . '?action=profile;u=' . $row['id_moderator'] . '">' . $row['real_name'] . '</a>'
  1981. );
  1982. }
  1983. }
  1984. $smcFunc['db_free_result']($result);
  1985. }
  1986. cache_put_data('board_parents-' . $original_parent, $boards, 480);
  1987. }
  1988. return $boards;
  1989. }
  1990. /**
  1991. * Attempt to reload our known languages.
  1992. *
  1993. * @param bool $use_cache = true
  1994. * @param bool $favor_utf8 = true
  1995. * @return array
  1996. */
  1997. function getLanguages($use_cache = true)
  1998. {
  1999. global $context, $smcFunc, $settings, $modSettings;
  2000. // Either we don't use the cache, or its expired.
  2001. if (!$use_cache || ($context['languages'] = cache_get_data('known_languages', !empty($modSettings['cache_enable']) && $modSettings['cache_enable'] < 1 ? 86400 : 3600)) == null)
  2002. {
  2003. // If we don't have our theme information yet, lets get it.
  2004. if (empty($settings['default_theme_dir']))
  2005. loadTheme(0, false);
  2006. // Default language directories to try.
  2007. $language_directories = array(
  2008. $settings['default_theme_dir'] . '/languages',
  2009. $settings['actual_theme_dir'] . '/languages',
  2010. );
  2011. // We possibly have a base theme directory.
  2012. if (!empty($settings['base_theme_dir']))
  2013. $language_directories[] = $settings['base_theme_dir'] . '/languages';
  2014. // Remove any duplicates.
  2015. $language_directories = array_unique($language_directories);
  2016. foreach ($language_directories as $language_dir)
  2017. {
  2018. // Can't look in here... doesn't exist!
  2019. if (!file_exists($language_dir))
  2020. continue;
  2021. $dir = dir($language_dir);
  2022. while ($entry = $dir->read())
  2023. {
  2024. // Look for the index language file....
  2025. if (!preg_match('~^index\.(.+)\.php$~', $entry, $matches))
  2026. continue;
  2027. $context['languages'][$matches[1]] = array(
  2028. 'name' => $smcFunc['ucwords'](strtr($matches[1], array('_' => ' '))),
  2029. 'selected' => false,
  2030. 'filename' => $matches[1],
  2031. 'location' => $language_dir . '/index.' . $matches[1] . '.php',
  2032. );
  2033. }
  2034. $dir->close();
  2035. }
  2036. // Lets cash in on this deal.
  2037. if (!empty($modSettings['cache_enable']))
  2038. cache_put_data('known_languages', $context['languages'], !empty($modSettings['cache_enable']) && $modSettings['cache_enable'] < 1 ? 86400 : 3600);
  2039. }
  2040. return $context['languages'];
  2041. }
  2042. /**
  2043. * Replace all vulgar words with respective proper words. (substring or whole words..)
  2044. * What this function does:
  2045. * - it censors the passed string.
  2046. * - if the theme setting allow_no_censored is on, and the theme option
  2047. * show_no_censored is enabled, does not censor, unless force is also set.
  2048. * - it caches the list of censored words to reduce parsing.
  2049. *
  2050. * @param string &$text
  2051. * @param bool $force = false
  2052. * @return string The censored text
  2053. */
  2054. function censorText(&$text, $force = false)
  2055. {
  2056. global $modSettings, $options, $settings, $txt;
  2057. static $censor_vulgar = null, $censor_proper;
  2058. if ((!empty($options['show_no_censored']) && $settings['allow_no_censored'] && !$force) || empty($modSettings['censor_vulgar']) || trim($text) === '')
  2059. return $text;
  2060. // If they haven't yet been loaded, load them.
  2061. if ($censor_vulgar == null)
  2062. {
  2063. $censor_vulgar = explode("\n", $modSettings['censor_vulgar']);
  2064. $censor_proper = explode("\n", $modSettings['censor_proper']);
  2065. // Quote them for use in regular expressions.
  2066. if (!empty($modSettings['censorWholeWord']))
  2067. {
  2068. for ($i = 0, $n = count($censor_vulgar); $i < $n; $i++)
  2069. {
  2070. $censor_vulgar[$i] = str_replace(array('\\\\\\*', '\\*', '&', '\''), array('[*]', '[^\s]*?', '&amp;', '&#039;'), preg_quote($censor_vulgar[$i], '/'));
  2071. $censor_vulgar[$i] = '/(?<=^|\W)' . $censor_vulgar[$i] . '(?=$|\W)/u' . (empty($modSettings['censorIgnoreCase']) ? '' : 'i');
  2072. // @todo I'm thinking the old way is some kind of bug and this is actually fixing it.
  2073. //if (strpos($censor_vulgar[$i], '\'') !== false)
  2074. //$censor_vulgar[$i] = str_replace('\'', '&#039;', $censor_vulgar[$i]);
  2075. }
  2076. }
  2077. }
  2078. // Censoring isn't so very complicated :P.
  2079. if (empty($modSettings['censorWholeWord']))
  2080. $text = empty($modSettings['censorIgnoreCase']) ? str_ireplace($censor_vulgar, $censor_proper, $text) : str_replace($censor_vulgar, $censor_proper, $text);
  2081. else
  2082. $text = preg_replace($censor_vulgar, $censor_proper, $text);
  2083. return $text;
  2084. }
  2085. /**
  2086. * Load the template/language file using eval or require? (with eval we can show an error message!)
  2087. * - loads the template or language file specified by filename.
  2088. * - uses eval unless disableTemplateEval is enabled.
  2089. * - outputs a parse error if the file did not exist or contained errors.
  2090. * - attempts to detect the error and line, and show detailed information.
  2091. *
  2092. * @param string $filename
  2093. * @param bool $once = false, if true only includes the file once (like include_once)
  2094. */
  2095. function template_include($filename, $once = false)
  2096. {
  2097. global $context, $settings, $options, $txt, $scripturl, $modSettings;
  2098. global $user_info, $boardurl;
  2099. global $maintenance, $mtitle, $mmessage;
  2100. static $templates = array();
  2101. // We want to be able to figure out any errors...
  2102. @ini_set('track_errors', '1');
  2103. // Don't include the file more than once, if $once is true.
  2104. if ($once && in_array($filename, $templates))
  2105. return;
  2106. // Add this file to the include list, whether $once is true or not.
  2107. else
  2108. $templates[] = $filename;
  2109. // Are we going to use eval?
  2110. if (empty($modSettings['disableTemplateEval']))
  2111. {
  2112. $file_found = file_exists($filename) && eval('?' . '>' . rtrim(file_get_contents($filename))) !== false;
  2113. $settings['current_include_filename'] = $filename;
  2114. }
  2115. else
  2116. {
  2117. $file_found = file_exists($filename);
  2118. if ($once && $file_found)
  2119. require_once($filename);
  2120. elseif ($file_found)
  2121. require($filename);
  2122. }
  2123. if ($file_found !== true)
  2124. {
  2125. ob_end_clean();
  2126. if (!empty($modSettings['enableCompressedOutput']))
  2127. @ob_start('ob_gzhandler');
  2128. else
  2129. ob_start();
  2130. if (isset($_GET['debug']))
  2131. header('Content-Type: application/xhtml+xml; charset=UTF-8');
  2132. // Don't cache error pages!!
  2133. header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
  2134. header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
  2135. header('Cache-Control: no-cache');
  2136. if (!isset($txt['template_parse_error']))
  2137. {
  2138. $txt['template_parse_error'] = 'Template Parse Error!';
  2139. $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>.';
  2140. $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>.';
  2141. }
  2142. // First, let's get the doctype and language information out of the way.
  2143. echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  2144. <html xmlns="http://www.w3.org/1999/xhtml"', !empty($context['right_to_left']) ? ' dir="rtl"' : '', '>
  2145. <head>
  2146. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />';
  2147. if (!empty($maintenance) && !allowedTo('admin_forum'))
  2148. echo '
  2149. <title>', $mtitle, '</title>
  2150. </head>
  2151. <body>
  2152. <h3>', $mtitle, '</h3>
  2153. ', $mmessage, '
  2154. </body>
  2155. </html>';
  2156. elseif (!allowedTo('admin_forum'))
  2157. echo '
  2158. <title>', $txt['template_parse_error'], '</title>
  2159. </head>
  2160. <body>
  2161. <h3>', $txt['template_parse_error'], '</h3>
  2162. ', $txt['template_parse_error_message'], '
  2163. </body>
  2164. </html>';
  2165. else
  2166. {
  2167. require_once(SUBSDIR . '/Package.subs.php');
  2168. $error = fetch_web_data($boardurl . strtr($filename, array(BOARDDIR => '', strtr(BOARDDIR, '\\', '/') => '')));
  2169. if (empty($error) && ini_get('track_errors'))
  2170. $error = $php_errormsg;
  2171. $error = strtr($error, array('<b>' => '<strong>', '</b>' => '</strong>'));
  2172. echo '
  2173. <title>', $txt['template_parse_error'], '</title>
  2174. </head>
  2175. <body>
  2176. <h3>', $txt['template_parse_error'], '</h3>
  2177. ', sprintf($txt['template_parse_error_details'], strtr($filename, array(BOARDDIR => '', strtr(BOARDDIR, '\\', '/') => '')));
  2178. if (!empty($error))
  2179. echo '
  2180. <hr />
  2181. <div style="margin: 0 20px;"><tt>', strtr(strtr($error, array('<strong>' . BOARDDIR => '<strong>...', '<strong>' . strtr(BOARDDIR, '\\', '/') => '<strong>...')), '\\', '/'), '</tt></div>';
  2182. // I know, I know... this is VERY COMPLICATED. Still, it's good.
  2183. if (preg_match('~ <strong>(\d+)</strong><br( /)?' . '>$~i', $error, $match) != 0)
  2184. {
  2185. $data = file($filename);
  2186. $data2 = highlight_php_code(implode('', $data));
  2187. $data2 = preg_split('~\<br( /)?\>~', $data2);
  2188. // Fix the PHP code stuff...
  2189. if (!isBrowser('gecko'))
  2190. $data2 = str_replace("\t", '<span style="white-space: pre;">' . "\t" . '</span>', $data2);
  2191. else
  2192. $data2 = str_replace('<pre style="display: inline;">' . "\t" . '</pre>', "\t", $data2);
  2193. // Now we get to work around a bug in PHP where it doesn't escape <br />s!
  2194. $j = -1;
  2195. foreach ($data as $line)
  2196. {
  2197. $j++;
  2198. if (substr_count($line, '<br />') == 0)
  2199. continue;
  2200. $n = substr_count($line, '<br />');
  2201. for ($i = 0; $i < $n; $i++)
  2202. {
  2203. $data2[$j] .= '&lt;br /&gt;' . $data2[$j + $i + 1];
  2204. unset($data2[$j + $i + 1]);
  2205. }
  2206. $j += $n;
  2207. }
  2208. $data2 = array_values($data2);
  2209. array_unshift($data2, '');
  2210. echo '
  2211. <div style="margin: 2ex 20px; width: 96%; overflow: auto;"><pre style="margin: 0;">';
  2212. // Figure out what the color coding was before...
  2213. $line = max($match[1] - 9, 1);
  2214. $last_line = '';
  2215. for ($line2 = $line - 1; $line2 > 1; $line2--)
  2216. if (strpos($data2[$line2], '<') !== false)
  2217. {
  2218. if (preg_match('~(<[^/>]+>)[^<]*$~', $data2[$line2], $color_match) != 0)
  2219. $last_line = $color_match[1];
  2220. break;
  2221. }
  2222. // Show the relevant lines...
  2223. for ($n = min($match[1] + 4, count($data2) + 1); $line <= $n; $line++)
  2224. {
  2225. if ($line == $match[1])
  2226. echo '</pre><div style="background-color: #ffb0b5;"><pre style="margin: 0;">';
  2227. echo '<span style="color: black;">', sprintf('%' . strlen($n) . 's', $line), ':</span> ';
  2228. if (isset($data2[$line]) && $data2[$line] != '')
  2229. echo substr($data2[$line], 0, 2) == '</' ? preg_replace('~^</[^>]+>~', '', $data2[$line]) : $last_line . $data2[$line];
  2230. if (isset($data2[$line]) && preg_match('~(<[^/>]+>)[^<]*$~', $data2[$line], $color_match) != 0)
  2231. {
  2232. $last_line = $color_match[1];
  2233. echo '</', substr($last_line, 1, 4), '>';
  2234. }
  2235. elseif ($last_line != '' && strpos($data2[$line], '<') !== false)
  2236. $last_line = '';
  2237. elseif ($last_line != '' && $data2[$line] != '')
  2238. echo '</', substr($last_line, 1, 4), '>';
  2239. if ($line == $match[1])
  2240. echo '</pre></div><pre style="margin: 0;">';
  2241. else
  2242. echo "\n";
  2243. }
  2244. echo '</pre></div>';
  2245. }
  2246. echo '
  2247. </body>
  2248. </html>';
  2249. }
  2250. die;
  2251. }
  2252. }
  2253. /**
  2254. * Initialize a database connection.
  2255. */
  2256. function loadDatabase()
  2257. {
  2258. global $db_persist, $db_connection, $db_server, $db_user, $db_passwd;
  2259. global $db_type, $db_name, $ssi_db_user, $ssi_db_passwd, $db_prefix;
  2260. // Figure out what type of database we are using.
  2261. if (empty($db_type) || !file_exists(SOURCEDIR . '/database/Db-' . $db_type . '.subs.php'))
  2262. $db_type = 'mysql';
  2263. // Load the file for the database.
  2264. require_once(SOURCEDIR . '/database/Db-' . $db_type . '.subs.php');
  2265. // 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.
  2266. if (ELKARTE == 'SSI' && !empty($ssi_db_user) && !empty($ssi_db_passwd))
  2267. $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));
  2268. // Either we aren't in SSI mode, or it failed.
  2269. if (empty($db_connection))
  2270. $db_connection = smf_db_initiate($db_server, $db_name, $db_user, $db_passwd, $db_prefix, array('persist' => $db_persist, 'dont_select_db' => ELKARTE == 'SSI'));
  2271. // Safe guard here, if there isn't a valid connection lets put a stop to it.
  2272. if (!$db_connection)
  2273. display_db_error();
  2274. // If in SSI mode fix up the prefix.
  2275. if (ELKARTE == 'SSI')
  2276. db_fix_prefix($db_prefix, $db_name);
  2277. }
  2278. /**
  2279. * Determine the user's avatar type and return the information as an array
  2280. *
  2281. * @param array $profile
  2282. * @param type $max_avatar_width
  2283. * @param type $max_avatar_height
  2284. * @return array $avatar
  2285. */
  2286. function determineAvatar($profile, $max_avatar_width, $max_avatar_height)
  2287. {
  2288. global $modSettings, $scripturl, $settings;
  2289. // uploaded avatar?
  2290. if ($profile['id_attach'] > 0 && empty($profile['avatar']))
  2291. {
  2292. // where are those pesky avatars?
  2293. $avatar_url = empty($profile['attachment_type']) ? $scripturl . '?action=dlattach;attach=' . $profile['id_attach'] . ';type=avatar' : $modSettings['custom_avatar_url'] . '/' . $profile['filename'];
  2294. $avatar = array(
  2295. 'name' => $profile['avatar'],
  2296. 'image' => '<img class="avatar" src="' . $avatar_url . '" alt="" />',
  2297. 'href' => $avatar_url,
  2298. 'url' => '',
  2299. );
  2300. }
  2301. // remote avatar?
  2302. elseif (stristr($profile['avatar'], 'http://'))
  2303. {
  2304. $avatar = array(
  2305. 'name' => $profile['avatar'],
  2306. 'image' => '<img class="avatar" src="' . $profile['avatar'] . '" ' . $max_avatar_width . $max_avatar_height . ' alt="" border="0" />',
  2307. 'href' => $profile['avatar'],
  2308. 'url' => $profile['avatar'],
  2309. );
  2310. }
  2311. // Gravatar instead?
  2312. elseif (!empty($profile['avatar']) && $profile['avatar'] === 'gravatar')
  2313. {
  2314. // Gravatars URL.
  2315. $gravatar_url = 'http://www.gravatar.com/avatar/' . md5(strtolower($profile['email_address'])) . 'd=' . $modSettings['avatar_max_height_external'] . (!empty($modSettings['gravatar_rating']) ? ('&r=' . $modSettings['gravatar_rating']) : '');
  2316. $avatar = array(
  2317. 'name' => $profile['avatar'],
  2318. 'image' => '<img src="' . $gravatar_url . '" alt="" class="avatar" border="0" />',
  2319. 'href' => $gravatar_url,
  2320. 'url' => $gravatar_url,
  2321. );
  2322. }
  2323. // an avatar from the gallery?
  2324. elseif (!empty($profile['avatar']) && !stristr($profile['avatar'], 'http://'))
  2325. {
  2326. $avatar = array(
  2327. 'name' => $profile['avatar'],
  2328. 'image' => '<img class="avatar" src="' . $modSettings['avatar_url'] . '/' . $profile['avatar'] . '" alt="" />',
  2329. 'href' => $modSettings['avatar_url'] . '/' . $profile['avatar'],
  2330. 'url' => $modSettings['avatar_url'] . '/' . $profile['avatar'],
  2331. );
  2332. }
  2333. // no custon avatar found yet, maybe a default avatar?
  2334. elseif (($modSettings['avatar_default']) && empty($profile['avatar']) && empty($profile['filename']))
  2335. {
  2336. $avatar = array(
  2337. 'name' => '',
  2338. 'image' => '<img src="' . $settings['images_url'] . '/default_avatar.png' . '" alt="" class="avatar" border="0" />',
  2339. 'href' => $settings['images_url'] . '/default_avatar.png',
  2340. 'url' => 'http://',
  2341. );
  2342. }
  2343. //finally ...
  2344. else
  2345. $avatar = array(
  2346. 'name' => '',
  2347. 'image' => '',
  2348. 'href' => '',
  2349. 'url' => ''
  2350. );
  2351. return $avatar;
  2352. }