PageRenderTime 66ms CodeModel.GetById 8ms RepoModel.GetById 0ms app.codeStats 1ms

/php/Sources/Load.php

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